index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/JobLockFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.io.Closeable; import java.util.concurrent.TimeoutException; import org.apache.gobblin.runtime.api.JobSpec; /** * A factory for locks keyed on {@link JobSpec} . Typical usecase is to prevent the same job being * executed concurrently. */ public interface JobLockFactory<T extends JobLock> extends Closeable { /** Creates a lock for the specified job. Lock is not acquired. */ T getJobLock(JobSpec jobSpec) throws TimeoutException; }
1,400
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLockFactoryManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.io.IOException; import org.slf4j.Logger; import com.google.common.base.Optional; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.runtime.instance.hadoop.HadoopConfigLoader; /** * Manages instances of {@link FileBasedJobLockFactory}. */ @Alias(value="file") public class FileBasedJobLockFactoryManager extends AbstractJobLockFactoryManager<FileBasedJobLock, FileBasedJobLockFactory> { public static final String CONFIG_PREFIX = "job.lock.file"; @Override protected Config getFactoryConfig(Config sysConfig) { return sysConfig.hasPath(CONFIG_PREFIX) ? sysConfig.getConfig(CONFIG_PREFIX) : ConfigFactory.empty(); } @Override protected FileBasedJobLockFactory createFactoryInstance(final Optional<Logger> log, final Config sysConfig, final Config factoryConfig) { HadoopConfigLoader hadoopConfLoader = new HadoopConfigLoader(sysConfig); try { return FileBasedJobLockFactory.create(factoryConfig, hadoopConfLoader.getConf(), log); } catch (IOException e) { throw new RuntimeException("Unable to create job lock factory: " +e, e); } } }
1,401
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/ListenableJobLock.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; public interface ListenableJobLock extends JobLock { /** * Sets the job lock event listener. * * @param jobLockEventListener the listener for lock events */ void setEventListener(JobLockEventListener jobLockEventListener); }
1,402
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/AbstractJobLockFactoryManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import com.google.common.base.Optional; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.typesafe.config.Config; /** * A default base implementation for {@link JobLockFactoryManager} implementations. It maintains a * cache from a factory configuration to factory instance. */ public abstract class AbstractJobLockFactoryManager<T extends JobLock, F extends JobLockFactory<T>> implements JobLockFactoryManager<T, F> { private final Cache<Config, F> _factoryCache; protected AbstractJobLockFactoryManager(Cache<Config, F> factoryCache) { _factoryCache = factoryCache; } public AbstractJobLockFactoryManager() { this(CacheBuilder.newBuilder().<Config, F>build()); } /** Extracts the factory-specific configuration from the system configuration. The extracted * object should uniquely identify the factory instance. */ protected abstract Config getFactoryConfig(Config sysConfig); /** Creates a new factory instance using the specified factory and system configs. */ protected abstract F createFactoryInstance(final Optional<Logger> log, final Config sysConfig, final Config factoryConfig); /** {@inheritDoc} */ @Override public F getJobLockFactory(final Config sysConfig, final Optional<Logger> log) { final Config factoryConfig = getFactoryConfig(sysConfig); try { return _factoryCache.get(factoryConfig, new Callable<F>() { @Override public F call() throws Exception { return createFactoryInstance(log, sysConfig, factoryConfig); } }) ; } catch (ExecutionException e) { throw new RuntimeException("Unable to create a job lock factory: " + e, e); } } }
1,403
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/JobLockEventListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; /** * The listener for lock events. * * @author joelbaranick */ public class JobLockEventListener { /** * Invoked when the lock is lost */ public void onLost() { } }
1,404
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/LegacyJobLockFactoryManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import org.apache.commons.lang3.reflect.ConstructorUtils; import com.google.common.base.Preconditions; import org.apache.gobblin.configuration.ConfigurationKeys; /** * The factory used to create instances of {@link JobLock}. * * @author joelbaranick */ public class LegacyJobLockFactoryManager { /** * Gets an instance of {@link JobLock}. * * @param properties the properties used to determine which instance of {@link JobLock} to create and the * relevant settings * @param jobLockEventListener the {@link JobLock} event listener * @return an instance of {@link JobLock} * @throws JobLockException throw when the {@link JobLock} fails to initialize */ public static JobLock getJobLock(Properties properties, JobLockEventListener jobLockEventListener) throws JobLockException { Preconditions.checkNotNull(properties); Preconditions.checkNotNull(jobLockEventListener); JobLock jobLock; if (properties.containsKey(ConfigurationKeys.JOB_LOCK_TYPE)) { try { Class<?> jobLockClass = Class.forName( properties.getProperty(ConfigurationKeys.JOB_LOCK_TYPE, FileBasedJobLock.class.getName())); jobLock = (JobLock) ConstructorUtils.invokeConstructor(jobLockClass, properties); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new JobLockException(e); } } else { jobLock = new FileBasedJobLock(properties); } if (jobLock instanceof ListenableJobLock) { ((ListenableJobLock)jobLock).setEventListener(jobLockEventListener); } return jobLock; } }
1,405
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLock.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.io.IOException; import java.util.Properties; import org.apache.hadoop.fs.Path; import com.google.common.annotations.VisibleForTesting; import org.apache.gobblin.configuration.ConfigurationKeys; /** * An implementation of {@link JobLock} that relies on new file creation on a file system. * * <p> * Acquiring a lock is done by creating a new empty file on the file system and * releasing a lock is done by deleting the empty file associated with the lock. * </p> * * @author Yinan Li */ public class FileBasedJobLock implements JobLock { /** Legacy */ public static final String JOB_LOCK_DIR = "job.lock.dir"; public static final String LOCK_FILE_EXTENSION = ".lock"; private final FileBasedJobLockFactory parent; private final Path lockFile; public FileBasedJobLock(Properties properties) throws JobLockException { this(properties.getProperty(ConfigurationKeys.JOB_NAME_KEY), FileBasedJobLockFactory.createForProperties(properties)); } FileBasedJobLock(String jobName, FileBasedJobLockFactory parent) { this.parent = parent; this.lockFile = parent.getLockFile(jobName); } /** * Acquire the lock. * * @throws JobLockException thrown if the {@link JobLock} fails to be acquired */ @Override public void lock() throws JobLockException { this.parent.lock(this.lockFile); } /** * Release the lock. * * @throws JobLockException thrown if the {@link JobLock} fails to be released */ @Override public void unlock() throws JobLockException { this.parent.unlock(this.lockFile); } /** * Try locking the lock. * * @return <em>true</em> if the lock is successfully locked, * <em>false</em> if otherwise. * @throws JobLockException thrown if the {@link JobLock} fails to be acquired */ @Override public boolean tryLock() throws JobLockException { return this.parent.tryLock(this.lockFile); } /** * Check if the lock is locked. * * @return if the lock is locked * @throws JobLockException thrown if checking the status of the {@link JobLock} fails */ @Override public boolean isLocked() throws JobLockException { return this.parent.isLocked(this.lockFile); } /** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. * * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { } @VisibleForTesting Path getLockFile() { return lockFile; } }
1,406
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/DistributedHiveLockFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.locks; import java.io.IOException; import java.util.Properties; import org.apache.gobblin.hive.HiveLockFactory; import org.apache.gobblin.hive.HiveLockImpl; /** * A lock factory that extends {@link HiveLockFactory} provide a get method for a distributed lock for a specific object */ public class DistributedHiveLockFactory extends HiveLockFactory { public DistributedHiveLockFactory(Properties properties) { super(properties); } public HiveLockImpl get(String name) { return new HiveLockImpl<ZookeeperBasedJobLock>(new ZookeeperBasedJobLock(properties, name)) { @Override public void lock() throws IOException { try { this.lock.lock(); } catch (JobLockException e) { throw new IOException(e); } } @Override public void unlock() throws IOException { try { this.lock.unlock(); } catch (JobLockException e) { throw new IOException(e); } } }; } }
1,407
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/AsynchronousFork.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.fork; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.gobblin.runtime.BoundedBlockingRecordQueue; import org.apache.gobblin.runtime.ExecutionModel; import org.apache.gobblin.runtime.Task; import org.apache.gobblin.runtime.TaskContext; import org.apache.gobblin.runtime.TaskExecutor; import org.apache.gobblin.runtime.TaskState; import lombok.extern.slf4j.Slf4j; import com.google.common.base.Optional; import com.google.common.base.Throwables; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.converter.DataConversionException; /** * A class representing a forked branch of operations of a {@link Task} flow. The {@link Fork}s of a * {@link Task} are executed in a thread pool managed by the {@link TaskExecutor}, which is different * from the thread pool used to execute {@link Task}s. * * <p> * Each {@link Fork} consists of the following steps: * <ul> * <li>Getting the next record off the record queue.</li> * <li>Converting the record and doing row-level quality checking if applicable.</li> * <li>Writing the record out if it passes the quality checking.</li> * <li>Cleaning up and exiting once all the records have been processed.</li> * </ul> * </p> * * @author Yinan Li */ @Slf4j @SuppressWarnings("unchecked") public class AsynchronousFork extends Fork { private final BoundedBlockingRecordQueue<Object> recordQueue; public AsynchronousFork(TaskContext taskContext, Object schema, int branches, int index, ExecutionModel executionModel) throws Exception { super(taskContext, schema, branches, index, executionModel); TaskState taskState = taskContext.getTaskState(); this.recordQueue = BoundedBlockingRecordQueue.newBuilder() .hasCapacity(taskState.getPropAsInt( ConfigurationKeys.FORK_RECORD_QUEUE_CAPACITY_KEY, ConfigurationKeys.DEFAULT_FORK_RECORD_QUEUE_CAPACITY)) .useTimeout(taskState.getPropAsLong( ConfigurationKeys.FORK_RECORD_QUEUE_TIMEOUT_KEY, ConfigurationKeys.DEFAULT_FORK_RECORD_QUEUE_TIMEOUT)) .useTimeoutTimeUnit(TimeUnit.valueOf(taskState.getProp( ConfigurationKeys.FORK_RECORD_QUEUE_TIMEOUT_UNIT_KEY, ConfigurationKeys.DEFAULT_FORK_RECORD_QUEUE_TIMEOUT_UNIT))) .collectStats() .build(); } @Override public Optional<BoundedBlockingRecordQueue<Object>.QueueStats> queueStats() { return this.recordQueue.stats(); } @Override protected void processRecords() throws IOException, DataConversionException { while (processRecord()) { } } @Override protected boolean putRecordImpl(Object record) throws InterruptedException { return this.recordQueue.put(record); } boolean processRecord() throws IOException, DataConversionException { try { Object record = this.recordQueue.get(); if (record == null || record == Fork.SHUTDOWN_RECORD) { // The parent task has already done pulling records so no new record means this fork is done if (this.isParentTaskDone()) { return false; } } else { this.processRecord(record); } } catch (InterruptedException ie) { log.warn("Interrupted while trying to get a record off the queue", ie); Throwables.propagate(ie); } return true; } }
1,408
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.fork; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.io.Closer; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import org.apache.gobblin.Constructs; import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes; import org.apache.gobblin.broker.iface.SharedResourcesBroker; import org.apache.gobblin.commit.SpeculativeAttemptAwareConstruct; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.converter.Converter; import org.apache.gobblin.converter.DataConversionException; import org.apache.gobblin.instrumented.Instrumented; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.publisher.TaskPublisher; import org.apache.gobblin.qualitychecker.row.RowLevelPolicyCheckResults; import org.apache.gobblin.qualitychecker.row.RowLevelPolicyChecker; import org.apache.gobblin.qualitychecker.task.TaskLevelPolicyCheckResults; import org.apache.gobblin.records.RecordStreamConsumer; import org.apache.gobblin.records.RecordStreamProcessor; import org.apache.gobblin.records.RecordStreamWithMetadata; import org.apache.gobblin.runtime.BoundedBlockingRecordQueue; import org.apache.gobblin.runtime.ExecutionModel; import org.apache.gobblin.runtime.ForkThrowableHolder; import org.apache.gobblin.runtime.MultiConverter; import org.apache.gobblin.runtime.Task; import org.apache.gobblin.runtime.TaskContext; import org.apache.gobblin.runtime.TaskExecutor; import org.apache.gobblin.runtime.TaskState; import org.apache.gobblin.runtime.util.ExceptionCleanupUtils; import org.apache.gobblin.runtime.util.ForkMetrics; import org.apache.gobblin.state.ConstructState; import org.apache.gobblin.stream.ControlMessage; import org.apache.gobblin.stream.RecordEnvelope; import org.apache.gobblin.util.FinalState; import org.apache.gobblin.util.ForkOperatorUtils; import org.apache.gobblin.writer.DataWriter; import org.apache.gobblin.writer.DataWriterBuilder; import org.apache.gobblin.writer.DataWriterWrapperBuilder; import org.apache.gobblin.writer.Destination; import org.apache.gobblin.writer.PartitionedDataWriter; import org.apache.gobblin.writer.WatermarkAwareWriter; /** * A class representing a forked branch of operations of a {@link Task} flow. The {@link Fork}s of a * {@link Task} are executed in a thread pool managed by the {@link TaskExecutor}, which is different * from the thread pool used to execute {@link Task}s. * * <p> * Each {@link Fork} consists of the following steps: * <ul> * <li>Getting the next record off the record queue.</li> * <li>Converting the record and doing row-level quality checking if applicable.</li> * <li>Writing the record out if it passes the quality checking.</li> * <li>Cleaning up and exiting once all the records have been processed.</li> * </ul> * </p> * * @author Yinan Li */ @SuppressWarnings("unchecked") public class Fork<S, D> implements Closeable, FinalState, RecordStreamConsumer<S, D>, Runnable { // Possible state of a fork enum ForkState { PENDING, RUNNING, SUCCEEDED, FAILED, COMMITTED } private final Logger logger; private final TaskContext taskContext; private final TaskState taskState; // A TaskState instance specific to this Fork private final TaskState forkTaskState; private final String taskId; private final Optional<String> taskAttemptId; private final int branches; private final int index; private final ExecutionModel executionModel; private final Converter converter; private final Optional<Object> convertedSchema; private final RowLevelPolicyChecker rowLevelPolicyChecker; private final RowLevelPolicyCheckResults rowLevelPolicyCheckingResult; private final Closer closer = Closer.create(); // The writer will be lazily created when the first data record arrives private Optional<DataWriter<Object>> writer = Optional.absent(); // This is used by the parent task to signal that it has done pulling records and this fork // should not expect any new incoming data records. This is written by the parent task and // read by this fork. Since this flag will be updated by only a single thread and updates to // a boolean are atomic, volatile is sufficient here. private volatile boolean parentTaskDone = false; // Writes to and reads of references are always atomic according to the Java language specs. // An AtomicReference is still used here for the compareAntSet operation. private final AtomicReference<ForkState> forkState; protected static final Object SHUTDOWN_RECORD = new Object(); private SharedResourcesBroker<GobblinScopeTypes> broker; public Fork(TaskContext taskContext, Object schema, int branches, int index, ExecutionModel executionModel) throws Exception { this.logger = LoggerFactory.getLogger(Fork.class.getName() + "-" + index); this.taskContext = taskContext; this.taskState = this.taskContext.getTaskState(); this.broker = this.taskState.getTaskBrokerNullable(); // Make a copy if there are more than one branches this.forkTaskState = branches > 1 ? new TaskState(this.taskState) : this.taskState; this.taskId = this.taskState.getTaskId(); this.taskAttemptId = this.taskState.getTaskAttemptId(); this.branches = branches; this.index = index; this.executionModel = executionModel; this.converter = this.closer.register(new MultiConverter(this.taskContext.getConverters(this.index, this.forkTaskState))); this.convertedSchema = Optional.fromNullable(this.converter.convertSchema(schema, this.taskState)); this.rowLevelPolicyChecker = this.closer.register(this.taskContext.getRowLevelPolicyChecker(this.index)); this.rowLevelPolicyCheckingResult = new RowLevelPolicyCheckResults(); // Build writer eagerly if configured, or if streaming is enabled boolean useEagerWriterInitialization = this.taskState .getPropAsBoolean(ConfigurationKeys.WRITER_EAGER_INITIALIZATION_KEY, ConfigurationKeys.DEFAULT_WRITER_EAGER_INITIALIZATION) || isStreamingMode(); if (useEagerWriterInitialization) { buildWriterIfNotPresent(); } this.forkState = new AtomicReference<>(ForkState.PENDING); /** * Create a {@link GobblinMetrics} for this {@link Fork} instance so that all new {@link MetricContext}s returned by * {@link Instrumented#setMetricContextName(State, String)} will be children of the forkMetrics. */ if (GobblinMetrics.isEnabled(this.taskState)) { ForkMetrics forkMetrics = ForkMetrics.get(this.taskState, index); this.closer.register(forkMetrics.getMetricContext()); Instrumented.setMetricContextName(this.taskState, forkMetrics.getMetricContext().getName()); } } private boolean isStreamingMode() { return this.executionModel.equals(ExecutionModel.STREAMING); } @SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED", justification = "We actually don't care about the return value of subscribe.") public void consumeRecordStream(RecordStreamWithMetadata<D, S> stream) throws RecordStreamProcessor.StreamProcessingException { if (this.converter instanceof MultiConverter) { // if multiconverter, unpack it for (Converter cverter : ((MultiConverter) this.converter).getConverters()) { stream = cverter.processStream(stream, this.taskState); } } else { stream = this.converter.processStream(stream, this.taskState); } stream = this.rowLevelPolicyChecker.processStream(stream, this.taskState); stream = stream.mapStream(s -> s.map(r -> { onEachRecord(); return r; })); stream = stream.mapStream(s -> s.doOnSubscribe(subscription -> onStart())); stream = stream.mapStream(s -> s.doOnComplete(() -> verifyAndSetForkState(ForkState.RUNNING, ForkState.SUCCEEDED))); stream = stream.mapStream(s -> s.doOnCancel(() -> { // Errors don't propagate up from below the fork, but cancel the stream, so use the failed state to indicate that // the fork failed to complete, which will then fail the task. verifyAndSetForkState(ForkState.RUNNING, ForkState.FAILED); })); stream = stream.mapStream(s -> s.doOnError(exc -> { verifyAndSetForkState(ForkState.RUNNING, ForkState.FAILED); this.logger.error(String.format("Fork %d of task %s failed to process data records", this.index, this.taskId), exc); })); stream = stream.mapStream(s -> s.doFinally(this::cleanup)); stream.getRecordStream().subscribe(r -> { if (r instanceof RecordEnvelope) { this.writer.get().writeEnvelope((RecordEnvelope) r); } else if (r instanceof ControlMessage) { // Nack with error and reraise the error if the control message handling raises an error. // This is to avoid missing an ack/nack in the error path. try { this.writer.get().getMessageHandler().handleMessage((ControlMessage) r); } catch (Throwable error) { r.nack(error); throw error; } r.ack(); } }, e -> { // Handle writer close in error case since onComplete will not call when exception happens if (this.writer.isPresent()) { this.writer.get().close(); } logger.error("Failed to process record.", e); verifyAndSetForkState(ForkState.RUNNING, ForkState.FAILED); }, () -> { if (this.writer.isPresent()) { this.writer.get().close(); } }); } private void onStart() throws IOException { compareAndSetForkState(ForkState.PENDING, ForkState.RUNNING); } private void onEachRecord() throws IOException { buildWriterIfNotPresent(); } @Override public void run() { compareAndSetForkState(ForkState.PENDING, ForkState.RUNNING); try { processRecords(); // Close the writer now if configured. One case where this is set is to release memory from ORC writers that can // have large buffers. Making this an opt-in option to avoid breaking anything that relies on keeping the writer // open until commit. if (this.writer.isPresent() && taskContext.getTaskState().getPropAsBoolean( ConfigurationKeys.FORK_CLOSE_WRITER_ON_COMPLETION, ConfigurationKeys.DEFAULT_FORK_CLOSE_WRITER_ON_COMPLETION)) { this.writer.get().close(); } compareAndSetForkState(ForkState.RUNNING, ForkState.SUCCEEDED); } catch (Throwable t) { Throwable cleanedUpException = ExceptionCleanupUtils.removeEmptyWrappers(t); // Set throwable to holder first because AsynchronousFork::putRecord can pull the throwable when it detects ForkState.FAILED status. ForkThrowableHolder holder = Task.getForkThrowableHolder(this.broker); holder.setThrowable(this.getIndex(), cleanedUpException); this.forkState.set(ForkState.FAILED); this.logger.error(String.format("Fork %d of task %s failed.", this.index, this.taskId), cleanedUpException); } finally { this.cleanup(); } } /** * {@inheritDoc}. * * @return a {@link org.apache.gobblin.configuration.State} object storing merged final states of constructs * used in this {@link Fork} */ @Override public State getFinalState() { ConstructState state = new ConstructState(); if (this.converter != null) { state.addConstructState(Constructs.CONVERTER, new ConstructState(this.converter.getFinalState())); } if (this.rowLevelPolicyChecker != null) { state.addConstructState(Constructs.ROW_QUALITY_CHECKER, new ConstructState(this.rowLevelPolicyChecker.getFinalState())); } if (this.writer.isPresent() && this.writer.get() instanceof FinalState) { state.addConstructState(Constructs.WRITER, new ConstructState(((FinalState) this.writer.get()).getFinalState())); } return state; } /** * Put a new record into the record queue for this {@link Fork} to process. * * <p> * This method is used by the {@link Task} that creates this {@link Fork}. * </p> * * @param record the new record * @return whether the record has been successfully put into the queue * @throws InterruptedException */ public boolean putRecord(Object record) throws InterruptedException { if (this.forkState.compareAndSet(ForkState.FAILED, ForkState.FAILED)) { ForkThrowableHolder holder = Task.getForkThrowableHolder(this.broker); Optional<Throwable> forkThrowable = holder.getThrowable(this.index); if (forkThrowable.isPresent()) { throw new IllegalStateException( String.format("Fork %d of task %s has failed and is no longer running", this.index, this.taskId), forkThrowable.get()); } else { throw new IllegalStateException( String.format("Fork %d of task %s has failed and is no longer running", this.index, this.taskId)); } } return this.putRecordImpl(record); } /** * Tell this {@link Fork} that the parent task is already done pulling records and * it should not expect more incoming data records. * * <p> * This method is used by the {@link Task} that creates this {@link Fork}. * </p> */ public void markParentTaskDone() { this.parentTaskDone = true; try { this.putRecord(SHUTDOWN_RECORD); } catch (InterruptedException e) { this.logger.info("Interrupted while writing a shutdown record into the fork queue. Ignoring"); } } /** * Check if the parent task is done. * @return {@code true} if the parent task is done; otherwise {@code false}. */ public boolean isParentTaskDone() { return parentTaskDone; } /** * Update record-level metrics. */ public void updateRecordMetrics() { if (this.writer.isPresent()) { this.taskState.updateRecordMetrics(this.writer.get().recordsWritten(), this.index); } } /** * Update byte-level metrics. */ public void updateByteMetrics() throws IOException { if (this.writer.isPresent()) { this.taskState.updateByteMetrics(this.writer.get().bytesWritten(), this.index); } } /** * Commit data of this {@link Fork}. * */ public boolean commit() { try { if (checkDataQuality(this.convertedSchema)) { // Commit data if all quality checkers pass. Again, not to catch the exception // it may throw so the exception gets propagated to the caller of this method. this.logger.info(String.format("Committing data for fork %d of task %s", this.index, this.taskId)); commitData(); verifyAndSetForkState(ForkState.SUCCEEDED, ForkState.COMMITTED); this.logger.info(String.format("Fork %d of task %s successfully committed data", this.index, this.taskId)); return true; } this.logger.error(String.format("Fork %d of task %s failed to pass quality checking", this.index, this.taskId)); verifyAndSetForkState(ForkState.SUCCEEDED, ForkState.FAILED); return false; } catch (Throwable t) { this.logger.error(String.format("Fork %d of task %s failed to commit data", this.index, this.taskId), t); this.forkState.set(ForkState.FAILED); Throwables.propagate(t); return false; } } /** * Get the ID of the task that creates this {@link Fork}. * * @return the ID of the task that creates this {@link Fork} */ public String getTaskId() { return this.taskId; } /** * Get the branch index of this {@link Fork}. * * @return branch index of this {@link Fork} */ public int getIndex() { return this.index; } /** * Get a {@link BoundedBlockingRecordQueue.QueueStats} object representing the record queue * statistics of this {@link Fork}. * * @return a {@link BoundedBlockingRecordQueue.QueueStats} object representing the record queue * statistics of this {@link Fork} wrapped in an {@link com.google.common.base.Optional}, * which means it may be absent if collecting of queue statistics is not enabled. */ public Optional<BoundedBlockingRecordQueue<Object>.QueueStats> queueStats() { return Optional.absent(); }; /** * Return if this {@link Fork} has succeeded processing all records. * * @return if this {@link Fork} has succeeded processing all records */ public boolean isSucceeded() { return this.forkState.compareAndSet(ForkState.SUCCEEDED, ForkState.SUCCEEDED); } public boolean isDone() { return this.forkState.get() == ForkState.SUCCEEDED || this.forkState.get() == ForkState.FAILED || this.forkState.get() == ForkState.COMMITTED; } @Override public String toString() { return "Fork: TaskId = \"" + this.taskId + "\" Index: \"" + this.index + "\" State: \"" + this.forkState + "\""; } @Override public void close() throws IOException { // Tell this fork that the parent task is done. This is a second chance call if the parent // task failed and didn't do so through the normal way of calling markParentTaskDone(). this.parentTaskDone = true; // Record the fork state into the task state that will be persisted into the state store this.taskState.setProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.FORK_STATE_KEY, this.branches, this.index), this.forkState.get().name()); try { this.closer.close(); } finally { if (this.writer.isPresent()) { this.writer.get().cleanup(); } } } /** * Get the number of records written by this {@link Fork}. * * @return the number of records written by this {@link Fork} */ public long getRecordsWritten() { return this.writer.isPresent() ? this.writer.get().recordsWritten() : 0L; } /** * Get the number of bytes written by this {@link Fork}. * * @return the number of bytes written by this {@link Fork} */ public long getBytesWritten() { try { return this.writer.isPresent() ? this.writer.get().bytesWritten() : 0L; } catch (Throwable t) { // Return 0 if the writer does not implement bytesWritten(); return 0L; } } protected void processRecords() throws IOException, DataConversionException { throw new UnsupportedOperationException(); } protected void processRecord(Object record) throws IOException, DataConversionException { if (this.forkState.compareAndSet(ForkState.FAILED, ForkState.FAILED)) { throw new IllegalStateException( String.format("Fork %d of task %s has failed and is no longer running", this.index, this.taskId)); } if (record == null || record == SHUTDOWN_RECORD) { /** * null record indicates a timeout on record acquisition, SHUTDOWN_RECORD is sent during shutdown. * Will loop unless the parent task has indicated that it is already done pulling records. */ if (this.parentTaskDone) { return; } } else { if (isStreamingMode()) { // Unpack the record from its container RecordEnvelope recordEnvelope = (RecordEnvelope) record; // Convert the record, check its data quality, and finally write it out if quality checking passes. for (Object convertedRecord : this.converter.convertRecord(this.convertedSchema, recordEnvelope.getRecord(), this.taskState)) { if (this.rowLevelPolicyChecker.executePolicies(convertedRecord, this.rowLevelPolicyCheckingResult)) { // for each additional record we pass down, increment the acks needed ((WatermarkAwareWriter) this.writer.get()).writeEnvelope( recordEnvelope.withRecord(convertedRecord)); } } } else { buildWriterIfNotPresent(); // Convert the record, check its data quality, and finally write it out if quality checking passes. for (Object convertedRecord : this.converter.convertRecord(this.convertedSchema, record, this.taskState)) { if (this.rowLevelPolicyChecker.executePolicies(convertedRecord, this.rowLevelPolicyCheckingResult)) { this.writer.get().writeEnvelope(new RecordEnvelope<>(convertedRecord)); } } } } } protected boolean putRecordImpl(Object record) throws InterruptedException { throw new UnsupportedOperationException(); }; protected void cleanup() { } /** * Build a {@link org.apache.gobblin.writer.DataWriter} for writing fetched data records. */ private DataWriter<Object> buildWriter() throws IOException { String writerId = this.taskId; // Add the task starting time if configured. // This is used to reduce file name collisions which can happen due to the execution of a workunit across multiple // task instances. // File names are generated from the writerId which is based on the taskId. Different instances of // the task have the same taskId, so file name collisions can occur. // Adding the task start time to the taskId gives a writerId that should be different across task instances. if (this.taskState.getPropAsBoolean(ConfigurationKeys.WRITER_ADD_TASK_TIMESTAMP, false)) { String taskStartTime = this.taskState.getProp(ConfigurationKeys.TASK_START_TIME_MILLIS_KEY); Preconditions.checkArgument(taskStartTime != null, ConfigurationKeys.TASK_START_TIME_MILLIS_KEY + " has not been set"); writerId = this.taskId + "_" + taskStartTime; } DataWriterBuilder<Object, Object> builder = this.taskContext.getDataWriterBuilder(this.branches, this.index) .writeTo(Destination.of(this.taskContext.getDestinationType(this.branches, this.index), this.taskState)) .writeInFormat(this.taskContext.getWriterOutputFormat(this.branches, this.index)).withWriterId(writerId) .withSchema(this.convertedSchema.orNull()).withBranches(this.branches).forBranch(this.index); if (this.taskAttemptId.isPresent()) { builder.withAttemptId(this.taskAttemptId.get()); } DataWriter<Object> writer = new PartitionedDataWriter<>(builder, this.taskContext.getTaskState()); logger.info("Wrapping writer " + writer); return new DataWriterWrapperBuilder<>(writer, this.taskState).build(); } private void buildWriterIfNotPresent() throws IOException { if (!this.writer.isPresent()) { this.writer = Optional.of(this.closer.register(buildWriter())); } } /** * Check data quality. * * @return whether data publishing is successful and data should be committed */ private boolean checkDataQuality(Optional<Object> schema) throws Exception { if (this.branches > 1) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED)); this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED)); } String writerRecordsWrittenKey = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_RECORDS_WRITTEN, this.branches, this.index); if (this.writer.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, this.writer.get().recordsWritten()); this.taskState.setProp(writerRecordsWrittenKey, this.writer.get().recordsWritten()); } else { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, 0L); this.taskState.setProp(writerRecordsWrittenKey, 0L); } if (schema.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACT_SCHEMA, schema.get().toString()); } try { // Do task-level quality checking TaskLevelPolicyCheckResults taskResults = this.taskContext.getTaskLevelPolicyChecker(this.forkTaskState, this.branches > 1 ? this.index : -1) .executePolicies(); TaskPublisher publisher = this.taskContext.getTaskPublisher(this.forkTaskState, taskResults); switch (publisher.canPublish()) { case SUCCESS: return true; case CLEANUP_FAIL: this.logger.error("Cleanup failed for task " + this.taskId); break; case POLICY_TESTS_FAIL: this.logger.error("Not all quality checking passed for task " + this.taskId); break; case COMPONENTS_NOT_FINISHED: this.logger.error("Not all components completed for task " + this.taskId); break; default: break; } return false; } catch (Throwable t) { this.logger.error("Failed to check task-level data quality", t); return false; } } /** * Commit task data. */ private void commitData() throws IOException { if (this.writer.isPresent()) { // Not to catch the exception this may throw so it gets propagated this.writer.get().commit(); } try { if (GobblinMetrics.isEnabled(this.taskState.getWorkunit())) { // Update record-level and byte-level metrics after the writer commits updateRecordMetrics(); updateByteMetrics(); } } catch (IOException ioe) { // Trap the exception as failing to update metrics should not cause the task to fail this.logger.error("Failed to update byte-level metrics of task " + this.taskId); } } /** * Compare and set the state of this {@link Fork} to a new state if and only if the current state * is equal to the expected state. */ private boolean compareAndSetForkState(ForkState expectedState, ForkState newState) { return this.forkState.compareAndSet(expectedState, newState); } /** * Compare and set the state of this {@link Fork} to a new state if and only if the current state * is equal to the expected state. Throw an exception if the state did not match. */ private void verifyAndSetForkState(ForkState expectedState, ForkState newState) { if (!compareAndSetForkState(expectedState, newState)) { throw new IllegalStateException(String .format("Expected fork state %s; actual fork state %s", expectedState.name(), this.forkState.get().name())); } } public boolean isSpeculativeExecutionSafe() { if (!this.writer.isPresent()) { return true; } if (!(this.writer.get() instanceof SpeculativeAttemptAwareConstruct)) { this.logger.info("Writer is not speculative safe: " + this.writer.get().getClass().toString()); return false; } return ((SpeculativeAttemptAwareConstruct) this.writer.get()).isSpeculativeAttemptSafe(); } public DataWriter getWriter() throws IOException { Preconditions.checkState(this.writer.isPresent(), "Asked to get a writer, but writer is null"); return this.writer.get(); } }
1,409
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/SynchronousFork.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.fork; import com.google.common.base.Optional; import com.google.common.base.Throwables; import org.apache.gobblin.converter.DataConversionException; import org.apache.gobblin.runtime.BoundedBlockingRecordQueue; import org.apache.gobblin.runtime.ExecutionModel; import org.apache.gobblin.runtime.TaskContext; import org.apache.gobblin.util.concurrent.AutoResetEvent; import java.io.IOException; @SuppressWarnings("unchecked") public class SynchronousFork extends Fork { private AutoResetEvent autoResetEvent; private volatile Throwable throwable; public SynchronousFork(TaskContext taskContext, Object schema, int branches, int index, ExecutionModel executionModel) throws Exception { super(taskContext, schema, branches, index, executionModel); this.autoResetEvent = new AutoResetEvent(); } @Override protected void processRecords() throws IOException, DataConversionException { try { this.autoResetEvent.waitOne(); if (this.throwable != null) { Throwables.propagateIfPossible(this.throwable, IOException.class, DataConversionException.class); throw new RuntimeException(throwable); } } catch (InterruptedException ie) { Throwables.propagate(ie); } } @Override protected boolean putRecordImpl(Object record) throws InterruptedException { try { this.processRecord(record); } catch (Throwable t) { this.throwable = t; this.autoResetEvent.set(); } return true; } @Override public void markParentTaskDone() { super.markParentTaskDone(); this.autoResetEvent.set(); } @Override public Optional<BoundedBlockingRecordQueue<Object>.QueueStats> queueStats() { return Optional.absent(); } }
1,410
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/crypto/DecryptCli.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.crypto; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.IOUtils; import com.google.common.collect.ImmutableMap; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.crypto.EncryptionConfigParser; import org.apache.gobblin.crypto.EncryptionFactory; import org.apache.gobblin.runtime.cli.CliApplication; @Alias(value = "decrypt", description = "Decryption utilities") public class DecryptCli implements CliApplication { private static final Option KEYSTORE_LOCATION = Option.builder("k").longOpt("ks_location").hasArg().required().desc("Keystore location").build(); private static final Option INPUT_LOCATION = Option.builder("i").longOpt("in").hasArg().required().desc("File to be decrypted").build(); private static final Option OUTPUT_LOCATION = Option.builder("o").longOpt("out").hasArg().required().desc("Output file (stdin if not specified)").build(); @Override public void run(String[] args) { try { Options options = new Options(); options.addOption(KEYSTORE_LOCATION); options.addOption(INPUT_LOCATION); options.addOption(OUTPUT_LOCATION); CommandLine cli; try { CommandLineParser parser = new DefaultParser(); cli = parser.parse(options, Arrays.copyOfRange(args, 1, args.length)); } catch (ParseException pe) { System.out.println("Command line parse exception: " + pe.getMessage()); printUsage(options); return; } Map<String, Object> encryptionProperties = ImmutableMap.<String, Object>of( EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY, "aes_rotating", EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY, cli.getOptionValue(KEYSTORE_LOCATION.getOpt()), EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY, getPasswordFromConsole() ); InputStream fIs = new BufferedInputStream(new FileInputStream(new File(cli.getOptionValue(INPUT_LOCATION.getOpt())))); InputStream cipherStream = EncryptionFactory.buildStreamCryptoProvider(encryptionProperties).decodeInputStream(fIs); OutputStream out = new BufferedOutputStream(new FileOutputStream(cli.getOptionValue(OUTPUT_LOCATION.getOpt()))); long bytes = IOUtils.copyLarge(cipherStream, out); out.flush(); out.close(); System.out.println("Copied " + String.valueOf(bytes) + " bytes."); } catch (IOException e) { throw new RuntimeException(e); } } private void printUsage(Options options) { HelpFormatter formatter = new HelpFormatter(); String usage = "decryption utilities "; formatter.printHelp(usage, options); } private static String getPasswordFromConsole() { System.out.print("Please enter the keystore password: "); return new String(System.console().readPassword()); } }
1,411
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/app/ServiceBasedAppLauncher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.app; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.reflect.ConstructorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.ServiceManager; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.rest.JobExecutionInfoServer; import org.apache.gobblin.runtime.api.AdminWebServerFactory; import org.apache.gobblin.runtime.services.JMXReportingService; import org.apache.gobblin.runtime.services.MetricsReportingService; import org.apache.gobblin.util.ApplicationLauncherUtils; import org.apache.gobblin.util.ClassAliasResolver; /** * An implementation of {@link ApplicationLauncher} that defines an application as a set of {@link Service}s that should * be started and stopped. The class will run a set of core services, some of which are optional, some of which are * mandatory. These {@link Service}s are as follows: * * <ul> * <li>{@link MetricsReportingService} is optional and controlled by {@link ConfigurationKeys#METRICS_ENABLED_KEY}</li> * <li>{@link JobExecutionInfoServer} is optional and controlled by {@link ConfigurationKeys#JOB_EXECINFO_SERVER_ENABLED_KEY}</li> * <li>AdminWebServer is optional and controlled by {@link ConfigurationKeys#ADMIN_SERVER_ENABLED_KEY}</li> * <li>{@link JMXReportingService} is mandatory</li> * </ul> * * <p> * Additional {@link Service}s can be added via the {@link #addService(Service)} method. A {@link Service} cannot be * added after the application has started. Additional {@link Service}s can also be specified via the configuration * key {@link #APP_ADDITIONAL_SERVICES}. * </p> * * <p> * An {@link ServiceBasedAppLauncher} cannot be restarted. * </p> */ @Alpha public class ServiceBasedAppLauncher implements ApplicationLauncher { /** * The name of the application. Not applicable for YARN jobs, which uses a separate key for the application name. */ public static final String APP_NAME = "app.name"; /** * The number of seconds to wait for the application to stop, the default value is {@link #DEFAULT_APP_STOP_TIME_SECONDS} */ public static final String APP_STOP_TIME_SECONDS = "app.stop.time.seconds"; private static final String DEFAULT_APP_STOP_TIME_SECONDS = Long.toString(60); /** * A comma separated list of fully qualified classes that implement the {@link Service} interface. These * {@link Service}s will be run in addition to the core services. */ public static final String APP_ADDITIONAL_SERVICES = "app.additional.services"; private static final Logger LOG = LoggerFactory.getLogger(ServiceBasedAppLauncher.class); private final int stopTime; private final String appId; private final List<Service> services; private volatile boolean hasStarted = false; private volatile boolean hasStopped = false; private ServiceManager serviceManager; public ServiceBasedAppLauncher(Properties properties, String appName) throws Exception { this.stopTime = Integer.parseInt(properties.getProperty(APP_STOP_TIME_SECONDS, DEFAULT_APP_STOP_TIME_SECONDS)); this.appId = ApplicationLauncherUtils.newAppId(appName); this.services = new ArrayList<>(); // Add core Services needed for any application addJobExecutionServerAndAdminUI(properties); addMetricsService(properties); addJMXReportingService(); // Add any additional Services specified via configuration keys addServicesFromProperties(properties); // Add a shutdown hook that interrupts the main thread addInterruptedShutdownHook(); } /** * Starts the {@link ApplicationLauncher} by starting all associated services. This method also adds a shutdown hook * that invokes {@link #stop()} and the {@link #close()} methods. So {@link #stop()} and {@link #close()} need not be * called explicitly; they can be triggered during the JVM shutdown. */ @Override public synchronized void start() { if (this.hasStarted) { LOG.warn("ApplicationLauncher has already started"); return; } this.hasStarted = true; this.serviceManager = new ServiceManager(this.services); // A listener that shutdowns the application if any service fails. this.serviceManager.addListener(new ServiceManager.Listener() { @Override public void failure(Service service) { super.failure(service); LOG.error(String.format("Service %s has failed.", service.getClass().getSimpleName()), service.failureCause()); try { service.stopAsync(); ServiceBasedAppLauncher.this.stop(); } catch (ApplicationException ae) { LOG.error("Could not shutdown services gracefully. This may cause the application to hang."); } } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { ServiceBasedAppLauncher.this.stop(); } catch (ApplicationException e) { LOG.error("Failed to shutdown application", e); } finally { try { ServiceBasedAppLauncher.this.close(); } catch (IOException e) { LOG.error("Failed to close application", e); } } } }); LOG.info("Starting the Gobblin application and all its associated Services"); // Start the application this.serviceManager.startAsync().awaitHealthy(); } /** * Stops the {@link ApplicationLauncher} by stopping all associated services. */ @Override public synchronized void stop() throws ApplicationException { if (!this.hasStarted) { LOG.warn("ApplicationLauncher was never started"); return; } if (this.hasStopped) { LOG.warn("ApplicationLauncher has already stopped"); return; } this.hasStopped = true; LOG.info("Shutting down the application"); try { this.serviceManager.stopAsync().awaitStopped(this.stopTime, TimeUnit.SECONDS); } catch (TimeoutException te) { LOG.error("Timeout in stopping the service manager", te); } } @Override public void close() throws IOException { // Do nothing } /** * Add a {@link Service} to be run by this {@link ApplicationLauncher}. * * <p> * This method is public because there are certain classes launchers (such as Azkaban) that require the * {@link ApplicationLauncher} to extend a pre-defined class. Since Java classes cannot extend multiple classes, * composition needs to be used. In which case this method needs to be public. * </p> */ public void addService(Service service) { if (this.hasStarted) { throw new IllegalArgumentException("Cannot add a service while the application is running!"); } this.services.add(service); } private void addJobExecutionServerAndAdminUI(Properties properties) { boolean jobExecInfoServerEnabled = Boolean .valueOf(properties.getProperty(ConfigurationKeys.JOB_EXECINFO_SERVER_ENABLED_KEY, Boolean.FALSE.toString())); boolean adminUiServerEnabled = Boolean.valueOf(properties.getProperty(ConfigurationKeys.ADMIN_SERVER_ENABLED_KEY, Boolean.FALSE.toString())); if (jobExecInfoServerEnabled) { LOG.info("Will launch the job execution info server"); JobExecutionInfoServer executionInfoServer = new JobExecutionInfoServer(properties); addService(executionInfoServer); if (adminUiServerEnabled) { LOG.info("Will launch the admin UI server"); addService(createAdminServer(properties, executionInfoServer.getAdvertisedServerUri())); } } else if (adminUiServerEnabled) { LOG.warn("Not launching the admin UI because the job execution info server is not enabled"); } } public static Service createAdminServer(Properties properties, URI executionInfoServerURI) { String factoryClassName = properties.getProperty(ConfigurationKeys.ADMIN_SERVER_FACTORY_CLASS_KEY, ConfigurationKeys.DEFAULT_ADMIN_SERVER_FACTORY_CLASS); ClassAliasResolver<AdminWebServerFactory> classResolver = new ClassAliasResolver<>(AdminWebServerFactory.class); try { AdminWebServerFactory factoryInstance = classResolver.resolveClass(factoryClassName).newInstance(); return factoryInstance.createInstance(properties, executionInfoServerURI); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Unable to instantiate the AdminWebServer factory. " + "Have you included the module in the gobblin distribution? :" + e, e); } } private void addMetricsService(Properties properties) { if (GobblinMetrics.isEnabled(properties)) { addService(new MetricsReportingService(properties, this.appId)); } } private void addJMXReportingService() { addService(new JMXReportingService()); } private void addServicesFromProperties(Properties properties) throws IllegalAccessException, InstantiationException, ClassNotFoundException, InvocationTargetException { if (properties.containsKey(APP_ADDITIONAL_SERVICES)) { for (String serviceClassName : new State(properties).getPropAsSet(APP_ADDITIONAL_SERVICES)) { Class<?> serviceClass = Class.forName(serviceClassName); if (Service.class.isAssignableFrom(serviceClass)) { Service service; Constructor<?> constructor = ConstructorUtils.getMatchingAccessibleConstructor(serviceClass, Properties.class); if (constructor != null) { service = (Service) constructor.newInstance(properties); } else { service = (Service) serviceClass.newInstance(); } addService(service); } else { throw new IllegalArgumentException(String.format("Class %s specified by %s does not implement %s", serviceClassName, APP_ADDITIONAL_SERVICES, Service.class.getSimpleName())); } } } } private void addInterruptedShutdownHook() { final Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mainThread.interrupt(); } }); } }
1,412
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/app/ApplicationLauncher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.app; import java.io.Closeable; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.runtime.JobLauncher; /** * Launches a Gobblin application. An application may launch one or multiple jobs via a {@link JobLauncher}. An * {@link ApplicationLauncher} is only responsible for starting and stopping one application. Typically, only one * application per JVM will be launched. * * <p> * An application can be started via the {@link #start()} method and then stopped via the {@link #stop()} method. * </p> */ @Alpha public interface ApplicationLauncher extends Closeable { /** * Start a Gobblin application. * * @throws ApplicationException if there is any problem starting the application */ public void start() throws ApplicationException; /** * Stop the Gobblin application. * * @throws ApplicationException if there is any problem starting the application */ public void stop() throws ApplicationException; }
1,413
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/app/ApplicationException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.app; import org.apache.gobblin.annotation.Alpha; /** * An {@link Exception} thrown by an {@link ApplicationLauncher}. */ @Alpha public class ApplicationException extends Exception { private static final long serialVersionUID = -7131035635096992762L; public ApplicationException(String message, Throwable cause) { super(message, cause); } }
1,414
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_spec/JobResolutionCallbacks.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_spec; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobTemplate; /** * Callbacks executed during job resolution by {@link JobSpecResolver}. */ @Alpha public interface JobResolutionCallbacks { /** * Called before a job is resolved, providing the original job spec and template to be used. */ void beforeResolution(JobSpecResolver jobSpecResolver, JobSpec jobSpec, JobTemplate jobTemplate) throws JobTemplate.TemplateException; /** * Called after a job is resolved, providing the final resolved spec. */ void afterResolution(JobSpecResolver jobSpecResolver, ResolvedJobSpec resolvedJobSpec); }
1,415
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_spec/JobSpecResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_spec; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.gobblin.runtime.api.GobblinInstanceDriver; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.job_catalog.InMemoryJobCatalog; import org.apache.gobblin.runtime.job_catalog.PackagedTemplatesJobCatalogDecorator; import org.apache.gobblin.util.ClassAliasResolver; import org.apache.gobblin.util.ConfigUtils; import com.google.common.base.Splitter; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigFactory; import lombok.AllArgsConstructor; /** * Resolved {@link JobSpec}s into {@link ResolvedJobSpec}s, this means: * - Applying the template to obtain the final job config. * - Calling resolution callbacks. */ @AllArgsConstructor public class JobSpecResolver { public static final String JOB_RESOLUTION_ACTIONS_KEY = "org.apache.gobblin.jobResolution.actions"; private final JobCatalogWithTemplates jobCatalog; private final List<JobResolutionCallbacks> jobResolutionCallbacks; private final Config sysConfig; /** * Obtain a mock {@link JobSpecResolver} with an empty configuration. It does not run any callbacks. * @return */ public static JobSpecResolver mock() { try { return new Builder().sysConfig(ConfigFactory.empty()).build(); } catch (IOException ioe) { throw new RuntimeException("Unexpected error. This is an error in code.", ioe); } } /** * @return a Builder for {@link JobSpecResolver}. */ public static Builder builder(GobblinInstanceDriver driver) throws IOException { return new Builder().sysConfig(driver.getSysConfig().getConfig()).jobCatalog(driver.getJobCatalog()); } /** * @return a Builder for {@link JobSpecResolver}. */ public static Builder builder(Config sysConfig) throws IOException { return new Builder().sysConfig(sysConfig); } /** * Used for building {@link JobSpecResolver}. */ public static class Builder { private JobCatalogWithTemplates jobCatalog = new PackagedTemplatesJobCatalogDecorator(new InMemoryJobCatalog()); private List<JobResolutionCallbacks> jobResolutionCallbacks = new ArrayList<>(); private Config sysConfig; private Builder sysConfig(Config sysConfig) throws IOException { this.sysConfig = sysConfig; for (String action : Splitter.on(",").trimResults().omitEmptyStrings() .split(ConfigUtils.getString(sysConfig, JOB_RESOLUTION_ACTIONS_KEY, ""))) { try { ClassAliasResolver<JobResolutionCallbacks> resolver = new ClassAliasResolver<>(JobResolutionCallbacks.class); JobResolutionCallbacks actionInstance = resolver.resolveClass(action).newInstance(); this.jobResolutionCallbacks.add(actionInstance); } catch (ReflectiveOperationException roe) { throw new IOException(roe); } } return this; } /** * Set the job catalog where templates may be found. */ public Builder jobCatalog(JobCatalog jobCatalog) { this.jobCatalog = new PackagedTemplatesJobCatalogDecorator(jobCatalog); return this; } /** * Add a {@link JobResolutionCallbacks} to the resolution process. */ public Builder jobResolutionAction(JobResolutionCallbacks action) { this.jobResolutionCallbacks.add(action); return this; } /** * @return a {@link JobSpecResolver} */ public JobSpecResolver build() { return new JobSpecResolver(this.jobCatalog, this.jobResolutionCallbacks, this.sysConfig); } } /** * Resolve an input {@link JobSpec} applying any templates. * * @throws SpecNotFoundException If no template exists with the specified URI. * @throws JobTemplate.TemplateException If the template throws an exception during resolution. * @throws ConfigException If the job config cannot be resolved. */ public ResolvedJobSpec resolveJobSpec(JobSpec jobSpec) throws SpecNotFoundException, JobTemplate.TemplateException, ConfigException { if (jobSpec instanceof ResolvedJobSpec) { return (ResolvedJobSpec) jobSpec; } JobTemplate jobTemplate = null; if (jobSpec.getJobTemplate().isPresent()) { jobTemplate = jobSpec.getJobTemplate().get(); } else if (jobSpec.getTemplateURI().isPresent()) { jobTemplate = jobCatalog.getTemplate(jobSpec.getTemplateURI().get()); } for (JobResolutionCallbacks action : this.jobResolutionCallbacks) { action.beforeResolution(this, jobSpec, jobTemplate); } Config resolvedConfig; if (jobTemplate == null) { resolvedConfig = jobSpec.getConfig().resolve(); } else { resolvedConfig = jobTemplate.getResolvedConfig(jobSpec.getConfig()).resolve(); } ResolvedJobSpec resolvedJobSpec = new ResolvedJobSpec(jobSpec, resolvedConfig); for (JobResolutionCallbacks action : this.jobResolutionCallbacks) { action.afterResolution(this, resolvedJobSpec); } return resolvedJobSpec; } }
1,416
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_spec/SecureTemplateEnforcer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_spec; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SecureJobTemplate; /** * A {@link JobResolutionCallbacks} that blocks resolution of any job that does not use a secure template. */ public class SecureTemplateEnforcer implements JobResolutionCallbacks { @Override public void beforeResolution(JobSpecResolver jobSpecResolver, JobSpec jobSpec, JobTemplate jobTemplate) throws JobTemplate.TemplateException { if (!(jobTemplate instanceof SecureJobTemplate) || !((SecureJobTemplate) jobTemplate).isSecure()) { throw new JobTemplate.TemplateException(String.format("Unallowed template resolution. %s is not a secure template.", jobTemplate == null ? "null" : jobTemplate.getUri())); } } @Override public void afterResolution(JobSpecResolver jobSpecResolver, ResolvedJobSpec resolvedJobSpec) { // NOOP } }
1,417
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_spec/ResolvedJobSpec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_spec; import java.net.URI; import com.google.common.base.Optional; import com.typesafe.config.Config; import lombok.Getter; import org.apache.gobblin.runtime.api.GobblinInstanceDriver; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.job_catalog.InMemoryJobCatalog; import org.apache.gobblin.runtime.job_catalog.PackagedTemplatesJobCatalogDecorator; import org.apache.gobblin.util.ConfigUtils; /** * A job spec whose template has been applied to its configuration. */ public class ResolvedJobSpec extends JobSpec { @Getter private final JobSpec originalJobSpec; /** * @deprecated Use {@link JobSpecResolver} */ @Deprecated public ResolvedJobSpec(JobSpec other) throws SpecNotFoundException, JobTemplate.TemplateException { this(other, new InMemoryJobCatalog()); } /** * @deprecated Use {@link JobSpecResolver} */ @Deprecated public ResolvedJobSpec(JobSpec other, GobblinInstanceDriver driver) throws SpecNotFoundException, JobTemplate.TemplateException { this(other, driver.getJobCatalog()); } /** * Resolve the job spec using classpath templates as well as any templates available in the input {@link JobCatalog}. * @deprecated Use {@link JobSpecResolver} */ @Deprecated public ResolvedJobSpec(JobSpec other, JobCatalog catalog) throws SpecNotFoundException, JobTemplate.TemplateException { super(other.getUri(), other.getVersion(), other.getDescription(), resolveConfig(other, catalog), ConfigUtils.configToProperties(resolveConfig(other, catalog)), other.getTemplateURI(), other.getJobTemplate(), other.getMetadata()); this.originalJobSpec = other; } ResolvedJobSpec(JobSpec other, Config resolvedConfig) { super(other.getUri(), other.getVersion(), other.getDescription(), resolvedConfig, ConfigUtils.configToProperties(resolvedConfig), other.getTemplateURI(), other.getJobTemplate(), other.getMetadata()); this.originalJobSpec = other; } private static Config resolveConfig(JobSpec jobSpec, JobCatalog catalog) throws SpecNotFoundException, JobTemplate.TemplateException { Optional<URI> templateURIOpt = jobSpec.getTemplateURI(); if (templateURIOpt.isPresent()) { JobCatalogWithTemplates catalogWithTemplates = new PackagedTemplatesJobCatalogDecorator(catalog); JobTemplate template = catalogWithTemplates.getTemplate(templateURIOpt.get()); return template.getResolvedConfig(jobSpec.getConfig()).resolve(); } else { return jobSpec.getConfig().resolve(); } } @Override public boolean equals(Object other) { return other instanceof ResolvedJobSpec && super.equals(other) && this.originalJobSpec.equals(((ResolvedJobSpec) other).originalJobSpec); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + originalJobSpec.hashCode(); return result; } }
1,418
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/ForkMetrics.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.util.List; import java.util.concurrent.Callable; import com.google.common.collect.ImmutableList; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.runtime.TaskState; import org.apache.gobblin.runtime.fork.Fork; /** * An extension to {@link GobblinMetrics} specifically for {@link Fork}. */ public class ForkMetrics extends GobblinMetrics { private static final String FORK_METRICS_BRANCH_NAME_KEY = "forkBranchName"; protected ForkMetrics(TaskState taskState, int index) { super(name(taskState, index), TaskMetrics.get(taskState).getMetricContext(), getForkMetricsTags(taskState, index)); } public static ForkMetrics get(final TaskState taskState, int index) { return (ForkMetrics) GOBBLIN_METRICS_REGISTRY.getOrCreate(name(taskState, index), new Callable<GobblinMetrics>() { @Override public GobblinMetrics call() throws Exception { return new ForkMetrics(taskState, index); } }); } /** * Creates a unique {@link String} representing this branch. */ private static String getForkMetricsId(State state, int index) { return state.getProp(ConfigurationKeys.FORK_BRANCH_NAME_KEY + "." + index, ConfigurationKeys.DEFAULT_FORK_BRANCH_NAME + index); } /** * Creates a {@link List} of {@link Tag}s for a {@link Fork} instance. The {@link Tag}s are purely based on the * index and the branch name. */ private static List<Tag<?>> getForkMetricsTags(State state, int index) { return ImmutableList.<Tag<?>>of(new Tag<>(FORK_METRICS_BRANCH_NAME_KEY, getForkMetricsId(state, index))); } /** * Creates a {@link String} that is a concatenation of the {@link TaskMetrics#getName()} and * {@link #getForkMetricsId(State, int)}. */ protected static String name(TaskState taskState, int index) { return METRICS_ID_PREFIX + taskState.getJobId() + "." + taskState.getTaskId() + "." + getForkMetricsId(taskState, index); } }
1,419
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/InjectionNames.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; /** * These names are used for dependency injection, when we need to inject different instances of the same type, * or inject constants. * */ public final class InjectionNames { public static final String SERVICE_NAME = "serviceName"; public static final String FORCE_LEADER = "forceLeader"; public static final String FLOW_CATALOG_LOCAL_COMMIT = "flowCatalogLocalCommit"; // TODO: Rename `warm_standby_enabled` config to `message_forwarding_enabled` since it's a misnomer. public static final String WARM_STANDBY_ENABLED = "statelessRestAPIEnabled"; public static final String MULTI_ACTIVE_SCHEDULER_ENABLED = "multiActiveSchedulerEnabled"; }
1,420
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/JobStateToJsonConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.List; import java.util.Properties; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.apache.commons.lang.StringUtils; import org.apache.gobblin.metastore.DatasetStateStore; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.JobConfigurationUtils; import org.apache.hadoop.conf.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.Closer; import com.google.gson.stream.JsonWriter; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metastore.StateStore; import org.apache.gobblin.runtime.JobState; /** * A utility class for converting a {@link org.apache.gobblin.runtime.JobState} object to a json-formatted document. * * @author Yinan Li */ @Slf4j public class JobStateToJsonConverter { private static final Logger LOGGER = LoggerFactory.getLogger(JobStateToJsonConverter.class); private static final String JOB_STATE_STORE_TABLE_SUFFIX = ".jst"; private final StateStore<? extends JobState> jobStateStore; private final boolean keepConfig; public JobStateToJsonConverter(StateStore stateStore, boolean keepConfig) { this.keepConfig = keepConfig; this.jobStateStore = stateStore; } // Constructor for backwards compatibility public JobStateToJsonConverter(Properties props, String storeUrl, boolean keepConfig) throws IOException { Configuration conf = new Configuration(); JobConfigurationUtils.putPropertiesIntoConfiguration(props, conf); if (StringUtils.isNotBlank(storeUrl)) { props.setProperty(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, storeUrl); } this.jobStateStore = (StateStore) DatasetStateStore.buildDatasetStateStore(ConfigUtils.propertiesToConfig(props)); this.keepConfig = keepConfig; } /** * Convert a single {@link JobState} of the given job instance. * * @param jobName job name * @param jobId job ID * @param writer {@link java.io.Writer} to write the json document * @throws IOException */ public void convert(String jobName, String jobId, Writer writer) throws IOException { List<? extends JobState> jobStates = this.jobStateStore.getAll(jobName, jobId + JOB_STATE_STORE_TABLE_SUFFIX); if (jobStates.isEmpty()) { LOGGER.warn(String.format("No job state found for job with name %s and id %s", jobName, jobId)); return; } try (JsonWriter jsonWriter = new JsonWriter(writer)) { jsonWriter.setIndent("\t"); // There should be only a single job state writeJobState(jsonWriter, jobStates.get(0)); } } /** * Convert the most recent {@link JobState} of the given job. * * @param jobName job name * @param writer {@link java.io.Writer} to write the json document */ public void convert(String jobName, Writer writer) throws IOException { convert(jobName, "current", writer); } /** * Convert all past {@link JobState}s of the given job. * * @param jobName job name * @param writer {@link java.io.Writer} to write the json document * @throws IOException */ public void convertAll(String jobName, Writer writer) throws IOException { List<? extends JobState> jobStates = this.jobStateStore.getAll(jobName); if (jobStates.isEmpty()) { LOGGER.warn(String.format("No job state found for job with name %s", jobName)); return; } try (JsonWriter jsonWriter = new JsonWriter(writer)) { jsonWriter.setIndent("\t"); writeJobStates(jsonWriter, jobStates); } } /** * Write a single {@link JobState} to json document. * * @param jsonWriter {@link com.google.gson.stream.JsonWriter} * @param jobState {@link JobState} to write to json document * @throws IOException */ private void writeJobState(JsonWriter jsonWriter, JobState jobState) throws IOException { jobState.toJson(jsonWriter, this.keepConfig); } /** * Write a list of {@link JobState}s to json document. * * @param jsonWriter {@link com.google.gson.stream.JsonWriter} * @param jobStates list of {@link JobState}s to write to json document * @throws IOException */ private void writeJobStates(JsonWriter jsonWriter, List<? extends JobState> jobStates) throws IOException { jsonWriter.beginArray(); for (JobState jobState : jobStates) { writeJobState(jsonWriter, jobState); } jsonWriter.endArray(); } public void outputToJson(CommandLine cmd) throws IOException { StringWriter stringWriter = new StringWriter(); if (cmd.hasOption('i')) { this.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter); } else { if (cmd.hasOption('a')) { this.convertAll(cmd.getOptionValue('n'), stringWriter); } else { this.convert(cmd.getOptionValue('n'), stringWriter); } } if (cmd.hasOption('t')) { Closer closer = Closer.create(); try { FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t'))); OutputStreamWriter outputStreamWriter = closer.register(new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING)); BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter)); bufferedWriter.write(stringWriter.toString()); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } else { System.out.println(stringWriter.toString()); } } }
1,421
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/JobMetrics.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.util.List; import java.util.concurrent.Callable; import com.google.common.base.Optional; import com.google.common.collect.Lists; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.metrics.event.JobEvent; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.TaskState; import org.apache.gobblin.util.ClustersNames; /** * An extension to {@link GobblinMetrics} specifically for job runs. * * @author Yinan Li */ @Slf4j public class JobMetrics extends GobblinMetrics { public static final CreatorTag DEFAULT_CREATOR_TAG = new CreatorTag( "driver"); protected final String jobName; @Getter protected final CreatorTag creatorTag; protected JobMetrics(JobState job, CreatorTag tag) { this(job, null, tag); } protected JobMetrics(JobState job, MetricContext parentContext, CreatorTag creatorTag) { super(name(job), parentContext, tagsForJob(job)); this.jobName = job.getJobName(); this.creatorTag = creatorTag; } public static class CreatorTag extends Tag<String> { public CreatorTag(String value) { super("creator", value); } } /** * Get a new {@link GobblinMetrics} instance for a given job. * @deprecated use {@link JobMetrics#get(String, String, CreatorTag)} instead. * * @param jobName job name * @param jobId job ID * @return a new {@link GobblinMetrics} instance for the given job */ @Deprecated public static JobMetrics get(String jobName, String jobId) { return get(new JobState(jobName, jobId), DEFAULT_CREATOR_TAG); } /** * Get a new {@link GobblinMetrics} instance for a given job. * * @param creatorTag the unique id which can tell who initiates this get operation * @param jobName job name * @param jobId job ID * @param creatorTag who creates this job metrics * @return a new {@link GobblinMetrics} instance for the given job */ public static JobMetrics get(String jobName, String jobId, CreatorTag creatorTag) { return get(new JobState(jobName, jobId), creatorTag); } /** * Get a new {@link GobblinMetrics} instance for a given job. * * @param creatorTag the unique id which can tell who initiates this get operation * @param jobId job ID * @return a new {@link GobblinMetrics} instance for the given job */ public static JobMetrics get(String jobId, CreatorTag creatorTag) { return get(null, jobId, creatorTag); } /** * Get a new {@link GobblinMetrics} instance for a given job. * * @param creatorTag the unique id which can tell who initiates this get operation * @param jobState the given {@link JobState} instance * @param parentContext is the parent {@link MetricContext} * @return a {@link JobMetrics} instance */ public static JobMetrics get(final JobState jobState, final MetricContext parentContext, CreatorTag creatorTag) { return (JobMetrics) GOBBLIN_METRICS_REGISTRY.getOrCreate(name(jobState), new Callable<GobblinMetrics>() { @Override public GobblinMetrics call() throws Exception { return new JobMetrics(jobState, parentContext, creatorTag); } }); } /** * Get a {@link JobMetrics} instance for the job with the given {@link JobState} instance. * @deprecated use {@link JobMetrics#get(JobState, CreatorTag)} instead. * * @param jobState the given {@link JobState} instance * @return a {@link JobMetrics} instance */ @Deprecated public static JobMetrics get(final JobState jobState) { return (JobMetrics) GOBBLIN_METRICS_REGISTRY.getOrCreate(name(jobState), new Callable<GobblinMetrics>() { @Override public GobblinMetrics call() throws Exception { return new JobMetrics(jobState, DEFAULT_CREATOR_TAG); } }); } /** * Get a {@link JobMetrics} instance for the job with the given {@link JobState} instance and a creator tag. * * @param creatorTag the unique id which can tell who initiates this get operation * @param jobState the given {@link JobState} instance * @return a {@link JobMetrics} instance */ public static JobMetrics get(final JobState jobState, CreatorTag creatorTag) { return (JobMetrics) GOBBLIN_METRICS_REGISTRY.getOrCreate(name(jobState), new Callable<GobblinMetrics>() { @Override public GobblinMetrics call() throws Exception { return new JobMetrics(jobState, creatorTag); } }); } /** * Remove the {@link JobMetrics} instance for the job with the given {@link JobState} instance. * * <p> * Removing a {@link JobMetrics} instance for a job will also remove the {@link TaskMetrics}s * of every tasks of the job. This is only used by job driver where there is no {@link ForkMetrics}. * </p> * @param jobState the given {@link JobState} instance */ public static void remove(JobState jobState) { remove(name(jobState)); for (TaskState taskState : jobState.getTaskStates()) { TaskMetrics.remove(taskState); } } /** * Attempt to remove the {@link JobMetrics} instance for the job with the given jobId. * It also checks the creator tag of this {@link JobMetrics}. If the given tag doesn't * match the creator tag, this {@link JobMetrics} won't be removed. */ public static void attemptRemove(String jobId, Tag matchTag) { Optional<GobblinMetrics> gobblinMetricsOptional = GOBBLIN_METRICS_REGISTRY.get( GobblinMetrics.METRICS_ID_PREFIX + jobId); JobMetrics jobMetrics = gobblinMetricsOptional.isPresent()? (JobMetrics) (gobblinMetricsOptional.get()): null; // only remove if the tag matches if (jobMetrics != null && jobMetrics.getCreatorTag().equals(matchTag)) { log.info("Removing job metrics because creator matches : " + matchTag.getValue()); GOBBLIN_METRICS_REGISTRY.remove(GobblinMetrics.METRICS_ID_PREFIX + jobId); } } private static String name(JobState jobState) { return METRICS_ID_PREFIX + jobState.getJobId(); } private static List<Tag<?>> tagsForJob(JobState jobState) { List<Tag<?>> tags = Lists.newArrayList(); tags.add(new Tag<>(JobEvent.METADATA_JOB_NAME, jobState.getJobName() == null ? "" : jobState.getJobName())); tags.add(new Tag<>(JobEvent.METADATA_JOB_ID, jobState.getJobId())); tags.addAll(getCustomTagsFromState(jobState)); return tags; } /** * @deprecated use {@link ClustersNames#getInstance()#getClusterName()} */ @Deprecated public static String getClusterIdentifierTag() { return ClustersNames.getInstance().getClusterName(); } }
1,422
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/RuntimeConstructs.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import org.apache.gobblin.runtime.fork.Fork; /** * @deprecated due to non essential usage within this repository. */ @Deprecated public enum RuntimeConstructs { FORK("Fork", Fork.class); private final String name; private final Class<?> klazz; RuntimeConstructs(String name, Class<?> klazz) { this.name = name; this.klazz = klazz; } @Override public String toString() { return this.name; } public Class<?> constructClass() { return this.klazz; } }
1,423
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/TaskMetrics.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.util.List; import java.util.concurrent.Callable; import com.google.common.collect.Lists; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.metrics.event.TaskEvent; import org.apache.gobblin.runtime.Task; import org.apache.gobblin.runtime.TaskState; /** * An extension to {@link GobblinMetrics} specifically for tasks. * * @author Yinan Li */ public class TaskMetrics extends GobblinMetrics { protected final String jobId; protected TaskMetrics(TaskState taskState) { super(name(taskState), parentContextForTask(taskState), tagsForTask(taskState)); this.jobId = taskState.getJobId(); } /** * Get a {@link TaskMetrics} instance for the task with the given {@link TaskState} instance. * * @param taskState the given {@link TaskState} instance * @return a {@link TaskMetrics} instance */ public static TaskMetrics get(final TaskState taskState) { return (TaskMetrics) GOBBLIN_METRICS_REGISTRY.getOrCreate(name(taskState), new Callable<GobblinMetrics>() { @Override public GobblinMetrics call() throws Exception { return new TaskMetrics(taskState); } }); } /** * Remove the {@link TaskMetrics} instance for the task with the given {@link TaskMetrics} instance. * Please note this method is invoked by job driver so it won't delete any underlying {@link ForkMetrics} * because the {@link org.apache.gobblin.runtime.fork.Fork} can be created on different nodes. * * @param taskState the given {@link TaskState} instance */ public static void remove(TaskState taskState) { remove(name(taskState)); } /** * Remove the {@link TaskMetrics} instance for the task with the given {@link TaskMetrics} instance. * Please note that this will also delete the underlying {@link ForkMetrics} related to this specific task. * * @param task the given task instance */ public static void remove(Task task) { task.getForks().forEach(forkOpt -> { remove(ForkMetrics.name(task.getTaskState(), forkOpt.get().getIndex())); }); remove(name(task)); } public static String name(TaskState taskState) { return METRICS_ID_PREFIX + taskState.getJobId() + "." + taskState.getTaskId(); } private static String name(Task task) { return name(task.getTaskState()); } protected static List<Tag<?>> tagsForTask(TaskState taskState) { List<Tag<?>> tags = Lists.newArrayList(); tags.add(new Tag<>(TaskEvent.METADATA_TASK_ID, taskState.getTaskId())); tags.add(new Tag<>(TaskEvent.METADATA_TASK_ATTEMPT_ID, taskState.getTaskAttemptId().or(""))); tags.add(new Tag<>(ConfigurationKeys.DATASET_URN_KEY, taskState.getProp(ConfigurationKeys.DATASET_URN_KEY, ConfigurationKeys.DEFAULT_DATASET_URN))); tags.addAll(getCustomTagsFromState(taskState)); return tags; } private static MetricContext parentContextForTask(TaskState taskState) { return JobMetrics.get( taskState.getProp(ConfigurationKeys.JOB_NAME_KEY), taskState.getJobId(), new JobMetrics.CreatorTag(taskState.getTaskId())) .getMetricContext(); } public static String taskInstanceRemoved(String metricName) { final String METRIC_SEPARATOR = "_"; String[] taskIdTokens = metricName.split(METRIC_SEPARATOR); StringBuilder sb = new StringBuilder(taskIdTokens[0]); // chopping taskId and jobId from metric name for (int i = 1; i < taskIdTokens.length - 2; i++) { sb.append(METRIC_SEPARATOR).append(taskIdTokens[i]); } return sb.toString(); } }
1,424
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/GsonUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import com.fatboyindustrial.gsonjavatime.Converters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public final class GsonUtils { /** * GSON serializer that can convert Java 8 date and time types to ISO standard representation. */ public static final Gson GSON_WITH_DATE_HANDLING = createGsonSerializerWithDateHandling(); private GsonUtils() { } private static Gson createGsonSerializerWithDateHandling() { GsonBuilder gsonBuilder = new GsonBuilder(); // Adding Java 8 date and time converters Converters.registerAll(gsonBuilder); return gsonBuilder.create(); } }
1,425
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/StateStores.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.util.Map; import org.apache.hadoop.fs.Path; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValue; import com.typesafe.config.ConfigValueFactory; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metastore.StateStore; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.TaskState; import org.apache.gobblin.source.workunit.MultiWorkUnit; import org.apache.gobblin.source.workunit.WorkUnit; import org.apache.gobblin.util.ClassAliasResolver; import org.apache.gobblin.util.ConfigUtils; import lombok.Getter; /** * state stores used for storing work units and task states */ public class StateStores { @Getter private final StateStore<TaskState> taskStateStore; @Getter private final StateStore<WorkUnit> wuStateStore; @Getter private final StateStore<MultiWorkUnit> mwuStateStore; // state store for job.state files. This should not be confused with the jst state store @Getter private final StateStore<JobState> jobStateStore; /** * Creates the state stores under storeBase * {@link WorkUnit}s will be stored under storeBase/_workunits/subdir/filename.(m)wu * {@link TaskState}s will be stored under storeBase/_taskstates/subdir/filename.tst * {@link JobState}s will be stored under StoreBase/_jobStates/subdir/filename.job.state * Some state stores such as the MysqlStateStore do not preserve the path prefix of storeRoot. * In those cases only the last three components of the path determine the key for the data. * @param config config properties * @param taskStoreBase the base directory that holds the store root for the task state store */ public StateStores(Config config, Path taskStoreBase, String taskStoreTable, Path workUnitStoreBase, String workUnitStoreTable, Path jobStateStoreBase, String jobStateStoreTable) { String stateStoreType = ConfigUtils.getString(config, ConfigurationKeys.INTERMEDIATE_STATE_STORE_TYPE_KEY, ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_TYPE_KEY, ConfigurationKeys.DEFAULT_STATE_STORE_TYPE)); ClassAliasResolver<StateStore.Factory> resolver = new ClassAliasResolver<>(StateStore.Factory.class); StateStore.Factory stateStoreFactory; try { stateStoreFactory = resolver.resolveClass(stateStoreType).newInstance(); } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); } catch (InstantiationException ie) { throw new RuntimeException(ie); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } // Override properties to configure the WorkUnit and MultiWorkUnit StateStores with the appropriate root/db location Path inputWorkUnitDir = new Path(workUnitStoreBase, workUnitStoreTable); Config wuStateStoreConfig = getStateStoreConfig(config, inputWorkUnitDir.toString(), workUnitStoreTable); // Override properties to place the TaskState StateStore at the appropriate location Path taskStateOutputDir = new Path(taskStoreBase, taskStoreTable); Config taskStateStoreConfig = getStateStoreConfig(config, taskStateOutputDir.toString(), taskStoreTable); taskStateStore = stateStoreFactory.createStateStore(taskStateStoreConfig, TaskState.class); wuStateStore = stateStoreFactory.createStateStore(wuStateStoreConfig, WorkUnit.class); mwuStateStore = stateStoreFactory.createStateStore(wuStateStoreConfig, MultiWorkUnit.class); // create a state store to store job.state content if configured if (ConfigUtils.getBoolean(config, ConfigurationKeys.JOB_STATE_IN_STATE_STORE, ConfigurationKeys.DEFAULT_JOB_STATE_IN_STATE_STORE)) { // Override properties to place the JobState StateStore at the appropriate location Path jobStateOutputDir = new Path(jobStateStoreBase, jobStateStoreTable); Config jobStateStoreConfig = getStateStoreConfig(config, jobStateOutputDir.toString(), jobStateStoreTable); jobStateStore = stateStoreFactory.createStateStore(jobStateStoreConfig, JobState.class); } else { jobStateStore = null; } } /** * @return true if a state store is present for storing job.state content */ public boolean haveJobStateStore() { return this.jobStateStore != null; } private static Config getStateStoreConfig(Config config, String rootDir, String dbTableKey) { Config fallbackConfig = ConfigFactory.empty() .withFallback(config) .withValue(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, ConfigValueFactory.fromAnyRef(rootDir)) .withValue(ConfigurationKeys.STATE_STORE_DB_TABLE_KEY, ConfigValueFactory.fromAnyRef(dbTableKey)); Config scopedConfig = ConfigFactory.empty(); for (Map.Entry<String, ConfigValue> entry : config.withOnlyPath(ConfigurationKeys.INTERMEDIATE_STATE_STORE_PREFIX).entrySet()) { scopedConfig.withValue(entry.getKey().substring(ConfigurationKeys.INTERMEDIATE_STATE_STORE_PREFIX.length()), entry.getValue()); } return scopedConfig.withFallback(fallbackConfig); } }
1,426
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/MetricGroup.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; /** * Enumeration of metric groups used internally. */ public enum MetricGroup { JOB, TASK }
1,427
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/ExceptionCleanupUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; public final class ExceptionCleanupUtils { private ExceptionCleanupUtils() { } /** * Removes exceptions that were wrapping another exception without providing a message of their own. * * When a checked exception is defined on the interface, and one of the implementations want to propagate a * different type of exception, that implementation can wrap the original exception. For example, Gobblin * codebase frequently wraps exception into new IOException(cause). As a result, users see large stack traces * where real error is hidden below several wrappers. This method will remove the wrappers to provide users with * better error messages. * */ public static Throwable removeEmptyWrappers(Throwable exception) { if (exception == null) { return null; } if (exception.getCause() != null && exception.getCause().toString().equals(exception.getMessage())) { return removeEmptyWrappers(exception.getCause()); } return exception; } }
1,428
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/MultiWorkUnitUnpackingIterator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; import java.util.Iterator; import org.apache.gobblin.source.workunit.MultiWorkUnit; import org.apache.gobblin.source.workunit.WorkUnit; import lombok.RequiredArgsConstructor; /** * An {@link Iterator} that unpacks {@link MultiWorkUnit}s. */ @RequiredArgsConstructor public class MultiWorkUnitUnpackingIterator implements Iterator<WorkUnit> { private final Iterator<WorkUnit> workUnits; /** The iterator for {@link #nextWu} if it's a {@link MultiWorkUnit} */ private Iterator<WorkUnit> currentIterator; /** The work unit to be checked in {@link #next()} */ private WorkUnit nextWu; /** A flag indicating if a new seek operation will be needed */ private boolean needSeek = true; @Override public boolean hasNext() { seekNext(); return nextWu != null; } @Override public WorkUnit next() { // In case, the caller forgets to call hasNext() seekNext(); WorkUnit wu = nextWu; if (nextWu instanceof MultiWorkUnit) { wu = this.currentIterator.next(); } needSeek = true; return wu; } /** Seek to the next available work unit, skipping all empty work units */ private void seekNext() { if (!needSeek) { return; } // First, iterate all if (this.currentIterator != null && this.currentIterator.hasNext()) { needSeek = false; return; } // Then, find the next available work unit nextWu = null; this.currentIterator = null; while (nextWu == null && workUnits.hasNext()) { nextWu = workUnits.next(); if (nextWu instanceof MultiWorkUnit) { this.currentIterator = ((MultiWorkUnit) nextWu).getWorkUnits().iterator(); if (!this.currentIterator.hasNext()) { nextWu = null; } } } needSeek = false; } @Override public void remove() { throw new UnsupportedOperationException(); } }
1,429
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/ClustersNames.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.util; /** * Allows conversion of URLs identifying a Hadoop cluster (e.g. resource manager url or * a job tracker URL) to a human-readable name. * * <p>The class will automatically load a resource named {@link #URL_TO_NAME_MAP_RESOURCE_NAME} to * get a default mapping. It expects this resource to be in the Java Properties file format. The * name of the property is the cluster URL and the value is the human-readable name. * * <p><b>IMPORTANT:</b> Don't forget to escape colons ":" in the file as those may be interpreted * as name/value separators. */ public class ClustersNames extends org.apache.gobblin.util.ClustersNames { private static ClustersNames THE_INSTANCE; public static ClustersNames getInstance() { synchronized (ClustersNames.class) { if (null == THE_INSTANCE) { THE_INSTANCE = new ClustersNames(); } return THE_INSTANCE; } } }
1,430
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins/PluginStaticKeys.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.plugins; /** * Static keys for {@link org.apache.gobblin.runtime.api.GobblinInstancePlugin}s. */ public class PluginStaticKeys { public static final String HADOOP_LOGIN_FROM_KEYTAB_ALIAS = "hadoopLoginFromKeytab"; public static final String INSTANCE_CONFIG_PREFIX = "gobblin.instance"; // Kerberos auth'n public static final String HADOOP_CONFIG_PREFIX = INSTANCE_CONFIG_PREFIX + ".hadoop"; public static final String LOGIN_USER_KEY = "loginUser"; public static final String LOGIN_USER_FULL_KEY = HADOOP_CONFIG_PREFIX + "." + LOGIN_USER_KEY; public static final String LOGIN_USER_KEYTAB_FILE_KEY = "loginUserKeytabFile"; public static final String LOGIN_USER_KEYTAB_FILE_FULL_KEY = HADOOP_CONFIG_PREFIX + "." + LOGIN_USER_KEYTAB_FILE_KEY; }
1,431
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins/GobblinInstancePluginUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.plugins; import java.util.Collection; import java.util.List; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.typesafe.config.Config; import org.apache.gobblin.runtime.api.GobblinInstancePluginFactory; import org.apache.gobblin.util.ClassAliasResolver; /** * Utilities to instantiate {@link GobblinInstancePluginFactory}s. */ public class GobblinInstancePluginUtils { private static final ClassAliasResolver<GobblinInstancePluginFactory> RESOLVER = new ClassAliasResolver<>(GobblinInstancePluginFactory.class); public static final String PLUGINS_KEY = PluginStaticKeys.INSTANCE_CONFIG_PREFIX + "pluginAliases"; /** * Parse a collection of {@link GobblinInstancePluginFactory} from the system configuration by reading the key * {@link #PLUGINS_KEY}. */ public static Collection<GobblinInstancePluginFactory> instantiatePluginsFromSysConfig(Config config) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String pluginsStr = config.getString(PLUGINS_KEY); List<GobblinInstancePluginFactory> plugins = Lists.newArrayList(); for (String pluginName : Splitter.on(",").split(pluginsStr)) { plugins.add(instantiatePluginByAlias(pluginName)); } return plugins; } /** * Instantiate a {@link GobblinInstancePluginFactory} by alias. */ public static GobblinInstancePluginFactory instantiatePluginByAlias(String alias) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return RESOLVER.resolveClass(alias).newInstance(); } }
1,432
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins/metrics/GobblinMetricsPlugin.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.plugins.metrics; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.runtime.api.GobblinInstanceDriver; import org.apache.gobblin.runtime.api.GobblinInstancePlugin; import org.apache.gobblin.runtime.api.GobblinInstancePluginFactory; import org.apache.gobblin.runtime.instance.plugin.BaseIdlePluginImpl; /** * A {@link GobblinInstancePlugin} for enabling metrics. */ public class GobblinMetricsPlugin extends BaseIdlePluginImpl { @Alias("metrics") public static class Factory implements GobblinInstancePluginFactory { @Override public GobblinInstancePlugin createPlugin(GobblinInstanceDriver instance) { return new GobblinMetricsPlugin(instance); } } private final GobblinMetrics metrics; public GobblinMetricsPlugin(GobblinInstanceDriver instance) { super(instance); this.metrics = GobblinMetrics.get(getInstance().getInstanceName()); } @Override protected void startUp() throws Exception { this.metrics.startMetricReporting(getInstance().getSysConfig().getConfigAsProperties()); } @Override protected void shutDown() throws Exception { this.metrics.stopMetricsReporting(); super.shutDown(); } }
1,433
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/plugins/email/EmailNotificationPlugin.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.plugins.email; import java.net.URI; import org.apache.commons.mail.EmailException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.GobblinInstanceDriver; import org.apache.gobblin.runtime.api.GobblinInstancePlugin; import org.apache.gobblin.runtime.api.GobblinInstancePluginFactory; import org.apache.gobblin.runtime.api.JobExecutionDriver; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobLifecycleListener; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.instance.StandardGobblinInstanceDriver; import org.apache.gobblin.runtime.instance.plugin.BaseIdlePluginImpl; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.EmailUtils; /** * A plugin that attaches an email notification listener to a {@link GobblinInstanceDriver}. The listener sends emails * on job completion */ public class EmailNotificationPlugin extends BaseIdlePluginImpl { private static final Logger LOGGER = LoggerFactory.getLogger(EmailNotificationPlugin.class); /** * An instance level setting to disable email notifications to all job launched by an instance */ public static final String EMAIL_NOTIFICATIONS_DISABLED_KEY = StandardGobblinInstanceDriver.INSTANCE_CFG_PREFIX + ".emailNotifications.disabled"; public static final boolean EMAIL_NOTIFICATIONS_DISABLED_DEFAULT = false; public EmailNotificationPlugin(GobblinInstanceDriver instance) { super(instance); } @Override protected void startUp() throws Exception { instance.registerJobLifecycleListener(new EmailNotificationListerner()); LOGGER.info("Started Email Notification Plugin"); } public static class Factory implements GobblinInstancePluginFactory { @Override public GobblinInstancePlugin createPlugin(GobblinInstanceDriver instance) { return new EmailNotificationPlugin(instance); } } /** * Sends emails when job completes with FAILED, COMMITED or CANCELLED state. * Emails sent when job fails with FAILED status can be turned off by setting {@link ConfigurationKeys#ALERT_EMAIL_ENABLED_KEY} to false * Emails sent when job completes with COMMITTED/CANCELLED status can be turned off by * setting {@link ConfigurationKeys#NOTIFICATION_EMAIL_ENABLED_KEY} to false */ private static class EmailNotificationListerner implements JobLifecycleListener { @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (newStatus.isDone() && !previousStatus.isDone()) { boolean alertEmailEnabled = ConfigUtils.getBoolean(state.getJobSpec().getConfig(), ConfigurationKeys.ALERT_EMAIL_ENABLED_KEY, false); boolean notificationEmailEnabled = ConfigUtils.getBoolean(state.getJobSpec().getConfig(), ConfigurationKeys.NOTIFICATION_EMAIL_ENABLED_KEY, false); // Send failure emails if (alertEmailEnabled && newStatus.isFailure()) { try { LOGGER.info("Sending job failure email for job: {}", state.getJobSpec().toShortString()); EmailUtils.sendJobFailureAlertEmail(state.getJobSpec().toShortString(), getEmailBody(state, previousStatus, newStatus), 1, ConfigUtils.configToState(state.getJobSpec().getConfig())); } catch (EmailException ee) { LOGGER.error("Failed to send job failure alert email for job " + state.getJobSpec().toShortString(), ee); } return; } // Send job completion emails if (notificationEmailEnabled && (newStatus.isCancelled() || newStatus.isSuccess())) { try { LOGGER.info("Sending job completion email for job: {}", state.getJobSpec().toShortString()); EmailUtils.sendJobCompletionEmail(state.getJobSpec().toShortString(), getEmailBody(state, previousStatus, newStatus), newStatus.toString(), ConfigUtils.configToState(state.getJobSpec().getConfig())); } catch (EmailException ee) { LOGGER.error("Failed to send job completion notification email for job " + state.getJobSpec().toShortString(), ee); } } } } private static String getEmailBody(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { return new StringBuilder().append("JobId: ") .append(state.getJobSpec().getConfig().getString(ConfigurationKeys.JOB_ID_KEY)) .append("RunningState: ").append(newStatus.toString()).append("\n") .append("JobExecutionState: ").append(state.getJobSpec().toLongString()).append("\n") .append("ExecutionMetadata: ").append(state.getExecutionMetadata()).toString(); } @Override public void onAddJob(JobSpec addedJob) { } @Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { } @Override public void onUpdateJob(JobSpec updatedJob) { } @Override public void onJobScheduled(JobSpecSchedule jobSchedule) { } @Override public void onJobUnscheduled(JobSpecSchedule jobSchedule) { } @Override public void onJobTriggered(JobSpec jobSpec) { } @Override public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { } @Override public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { } @Override public void onJobLaunch(JobExecutionDriver jobDriver) { } } }
1,434
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/template/PullFileToConfigConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.template; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.google.api.client.util.Charsets; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigResolveOptions; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.job_catalog.PackagedTemplatesJobCatalogDecorator; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.PathUtils; import org.apache.gobblin.util.PullFileLoader; import lombok.Data; /** * A simple script to convert old style pull files into *.conf files using templates. * * This script will load *.pull files and a template, and will attempt to create a *.conf file using that template * that resolves to the same job configuration as the pull file resolves. To do this, it compares all of the config * key-value pairs in the pull file against those in the template, and writes out only those key-value pairs that * are different from the template. It then writes the *.conf file to the output directory. * * The template can include a key {@link #DO_NOT_OVERRIDE_KEY} with an array of strings representing keys in the template * that should not appear in the output *.conf even if they resolve to different values. * * Note the template must be a resource-style template and it must be in the classpath. * * Usage: * PullFileToConfigConverter <pullFilesRootPath> <pullFilesToConvertGlob> resource:///<templatePath> <sysConfigPath> <outputDir> * */ @Data public class PullFileToConfigConverter { public static final String DO_NOT_OVERRIDE_KEY = "pullFileToConfigConverter.doNotOverride"; private static final Set<String> FILTER_KEYS = ImmutableSet.of("job.config.path", "jobconf.dir", "jobconf.fullyQualifiedPath"); private final Path pullFileRootPath; private final Path fileGlobToConvert; private final Path templateURI; private final File sysConfigPath; private final Path outputPath; public static void main(String[] args) throws Exception { if (args.length != 5) { System.out.println("Usage: PullFileToConfigConverter <pullFilesRootPath> <pullFilesToConvertGlob> resource:///<templatePath> <sysConfigPath> <outputDir>"); System.exit(1); } new PullFileToConfigConverter(new Path(args[0]), new Path(args[1]), new Path(args[2]), new File(args[3]), new Path(args[4])) .convert(); } public void convert() throws IOException { Config baseConfig = ConfigFactory.parseString(DO_NOT_OVERRIDE_KEY + ": []"); FileSystem pullFileFs = pullFileRootPath.getFileSystem(new Configuration()); FileSystem outputFs = this.outputPath.getFileSystem(new Configuration()); Config sysConfig = ConfigFactory.parseFile(this.sysConfigPath); PullFileLoader pullFileLoader = new PullFileLoader(this.pullFileRootPath, pullFileFs, PullFileLoader.DEFAULT_JAVA_PROPS_PULL_FILE_EXTENSIONS, PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); PackagedTemplatesJobCatalogDecorator catalog = new PackagedTemplatesJobCatalogDecorator(); ConfigResolveOptions configResolveOptions = ConfigResolveOptions.defaults(); configResolveOptions = configResolveOptions.setAllowUnresolved(true); ResourceBasedJobTemplate template; Config templateConfig; try { template = (ResourceBasedJobTemplate) catalog.getTemplate(templateURI.toUri()); templateConfig = sysConfig.withFallback(template.getRawTemplateConfig()).withFallback(baseConfig).resolve(configResolveOptions); } catch (SpecNotFoundException|JobTemplate.TemplateException exc) { throw new IOException(exc); } Set<String> doNotOverride = templateConfig.hasPath(DO_NOT_OVERRIDE_KEY) ? Sets.newHashSet(templateConfig.getStringList(DO_NOT_OVERRIDE_KEY)) : Sets.<String>newHashSet(); ConfigRenderOptions configRenderOptions = ConfigRenderOptions.defaults(); configRenderOptions = configRenderOptions.setComments(false); configRenderOptions = configRenderOptions.setOriginComments(false); configRenderOptions = configRenderOptions.setFormatted(true); configRenderOptions = configRenderOptions.setJson(false); for (FileStatus pullFile : pullFileFs.globStatus(this.fileGlobToConvert)) { Config pullFileConfig = pullFileLoader.loadPullFile(pullFile.getPath(), ConfigFactory.empty(), true).resolve(); Map<String, String> outputConfigMap = Maps.newHashMap(); outputConfigMap.put(ConfigurationKeys.JOB_TEMPLATE_PATH, this.templateURI.toString()); boolean somethingChanged; do { somethingChanged = false; Config currentOutputConfig = ConfigFactory.parseMap(outputConfigMap); Config currentResolvedConfig = currentOutputConfig.withFallback(templateConfig).resolve(configResolveOptions); for (Map.Entry<Object, Object> entry : ConfigUtils.configToProperties(pullFileConfig).entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); try { if ((!currentResolvedConfig.hasPath(key)) || (!currentResolvedConfig.getString(key).equals(value) && !doNotOverride.contains(key))) { if (!FILTER_KEYS.contains(key)) { somethingChanged = true; outputConfigMap.put(key, value); } } } catch (ConfigException.NotResolved nre) { // path is unresolved in config, will try again next iteration } } } while (somethingChanged); try { Config outputConfig = ConfigFactory.parseMap(outputConfigMap); Config currentResolvedConfig = outputConfig.withFallback(templateConfig).resolve(); String rendered = outputConfig.root().render(configRenderOptions); Path newPath = PathUtils.removeExtension(pullFile.getPath(), PullFileLoader.DEFAULT_JAVA_PROPS_PULL_FILE_EXTENSIONS.toArray(new String[]{})); newPath = PathUtils.addExtension(newPath, "conf"); newPath = new Path(this.outputPath, newPath.getName()); FSDataOutputStream os = outputFs.create(newPath); os.write(rendered.getBytes(Charsets.UTF_8)); os.close(); } catch (ConfigException.NotResolved nre) { throw new IOException("Not all configuration keys were resolved in pull file " + pullFile.getPath(), nre); } } } }
1,435
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/template/ResourceBasedJobTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.template; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.job_catalog.PackagedTemplatesJobCatalogDecorator; import lombok.extern.slf4j.Slf4j; /** * A {@link org.apache.gobblin.runtime.api.JobTemplate} that reads the template information from a resources file. * * This class is final because otherwise we could not guarantee the {@link InputStream} to be closed if the super * constructor throws an exception. */ @Slf4j public final class ResourceBasedJobTemplate extends HOCONInputStreamJobTemplate { public static final String SCHEME = "resource"; public static ResourceBasedJobTemplate forURI(URI uri, JobCatalogWithTemplates catalog) throws SpecNotFoundException, TemplateException, IOException { try (InputStream is = getInputStreamForURI(uri)) { return new ResourceBasedJobTemplate(is, uri, catalog); } } public static ResourceBasedJobTemplate forResourcePath(String path) throws SpecNotFoundException, TemplateException, IOException, URISyntaxException { return forResourcePath(path, new PackagedTemplatesJobCatalogDecorator()); } public static ResourceBasedJobTemplate forResourcePath(String path, JobCatalogWithTemplates catalog) throws SpecNotFoundException, TemplateException, IOException, URISyntaxException { return forURI(new URI(path), catalog); } /** * Initializes the template by retrieving the specified template file and obtain some special attributes. */ private ResourceBasedJobTemplate(InputStream is, URI uri, JobCatalogWithTemplates catalog) throws SpecNotFoundException, TemplateException, IOException { super(is, uri, catalog); } private static InputStream getInputStreamForURI(URI uri) throws IOException { Preconditions.checkArgument(uri.getScheme() == null || uri.getScheme().equals(SCHEME), "Unexpected template scheme: " + uri); Preconditions.checkArgument(!Strings.isNullOrEmpty(uri.getPath()), "Template path is null: " + uri); log.info("Loading the resource based job configuration template " + uri); String path = uri.getPath(); if (path.startsWith("/")) { path = path.substring(1); } InputStream is = ResourceBasedJobTemplate.class.getClassLoader().getResourceAsStream(path); if (is == null) { throw new IOException(String.format("Could not find resource at path %s required to load template %s.", path, uri)); } return is; } }
1,436
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/template/InheritingJobTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.template; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.typesafe.config.Config; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; /** * A {@link JobTemplate} that supports inheriting other {@link JobTemplate}s. */ public abstract class InheritingJobTemplate implements JobTemplate { private final List<URI> superTemplateUris; private final JobCatalogWithTemplates catalog; private List<JobTemplate> superTemplates; private boolean resolved; public InheritingJobTemplate(List<URI> superTemplateUris, JobCatalogWithTemplates catalog) { this.superTemplateUris = superTemplateUris; this.catalog = catalog; this.resolved = false; } public InheritingJobTemplate(List<JobTemplate> superTemplates, boolean skipResolve) { this.superTemplateUris = Lists.newArrayList(); this.catalog = null; this.superTemplates = superTemplates; this.resolved = skipResolve; } public InheritingJobTemplate(List<JobTemplate> superTemplates) { this(superTemplates, true); } /** * Resolves a list of {@link URI}s to actual {@link JobTemplate}s. This pattern is necessary to detect loops in * inheritance and prevent them from causing a stack overflow. */ private synchronized void ensureTemplatesResolved() throws SpecNotFoundException, TemplateException{ if (this.resolved) { return; } Map<URI, JobTemplate> loadedTemplates = Maps.newHashMap(); loadedTemplates.put(getUri(), this); resolveTemplates(loadedTemplates); } /** * Resolve all superTemplates being field variables within the class. * There are two types of resolution being involved in this method: * 1) When all templates are being represented as {@link #superTemplateUris}, the actual template will be loaded from * catalog first and enter resolution process. The physical {@link #superTemplates} are being materialized after that. * 2) org.apache.gobblin.runtime.template.InheritingJobTemplate#InheritingJobTemplate(java.util.List, boolean) provides * interface to directly provide physical {@link #superTemplates}. This case is determined by non-null containers of * {@link #superTemplates}. * */ private void resolveTemplates(Map<URI, JobTemplate> loadedTemplates) throws SpecNotFoundException, TemplateException { if (this.resolved) { return; } if (this.superTemplateUris.size() > 0) { this.superTemplates = Lists.newArrayList(); for (URI uri : this.superTemplateUris) { if (!loadedTemplates.containsKey(uri)) { JobTemplate newTemplate = this.catalog.getTemplate(uri); resolveTemplateRecursionHelper(newTemplate, uri, loadedTemplates); } this.superTemplates.add(loadedTemplates.get(uri)); } } else if (superTemplates != null ) { for (JobTemplate newTemplate : this.superTemplates) { if (!loadedTemplates.containsKey(newTemplate.getUri())) { resolveTemplateRecursionHelper(newTemplate, newTemplate.getUri(), loadedTemplates); } } } this.resolved = true; } /** * The canonicalURI needs to be there when the template needs to loaded from catalog, as the format are adjusted * while constructing the template. * Essentially, jobCatalog.load(templateUris.get(0)).getUri().equal(templateUris.get(0)) return false. */ private void resolveTemplateRecursionHelper(JobTemplate newTemplate, URI canonicalURI, Map<URI, JobTemplate> loadedTemplates) throws SpecNotFoundException, TemplateException { loadedTemplates.put(canonicalURI, newTemplate); if (newTemplate instanceof InheritingJobTemplate) { ((InheritingJobTemplate) newTemplate).resolveTemplates(loadedTemplates); } } public Collection<JobTemplate> getSuperTemplates() throws SpecNotFoundException, TemplateException { ensureTemplatesResolved(); if (superTemplates != null ) { return ImmutableList.copyOf(this.superTemplates); } else { return ImmutableList.of(); } } @Override public Config getRawTemplateConfig() throws SpecNotFoundException, TemplateException { ensureTemplatesResolved(); return getRawTemplateConfigHelper(Sets.<JobTemplate>newHashSet()); } private Config getRawTemplateConfigHelper(Set<JobTemplate> alreadyInheritedTemplates) throws SpecNotFoundException, TemplateException { Config rawTemplate = getLocalRawTemplate(); if (this.superTemplates != null) { for (JobTemplate template : Lists.reverse(this.superTemplates)) { if (!alreadyInheritedTemplates.contains(template)) { alreadyInheritedTemplates.add(template); Config thisFallback = template instanceof InheritingJobTemplate ? ((InheritingJobTemplate) template).getRawTemplateConfigHelper(alreadyInheritedTemplates) : template.getRawTemplateConfig(); rawTemplate = rawTemplate.withFallback(thisFallback); } } } return rawTemplate; } protected abstract Config getLocalRawTemplate(); @Override public Collection<String> getRequiredConfigList() throws SpecNotFoundException, TemplateException { ensureTemplatesResolved(); Set<String> allRequired = getRequiredConfigListHelper(Sets.<JobTemplate>newHashSet()); final Config rawConfig = getRawTemplateConfig(); Set<String> filteredRequired = Sets.filter(allRequired, new Predicate<String>() { @Override public boolean apply(String input) { return !rawConfig.hasPath(input); } }); return filteredRequired; } private Set<String> getRequiredConfigListHelper(Set<JobTemplate> alreadyLoadedTemplates) throws SpecNotFoundException, TemplateException { Set<String> requiredConfigs = Sets.newHashSet(getLocallyRequiredConfigList()); if (this.superTemplates != null) { for (JobTemplate template : this.superTemplates) { if (!alreadyLoadedTemplates.contains(template)) { alreadyLoadedTemplates.add(template); requiredConfigs.addAll(template instanceof InheritingJobTemplate ? ((InheritingJobTemplate) template).getRequiredConfigListHelper(alreadyLoadedTemplates) : template.getRequiredConfigList()); } } } return requiredConfigs; } protected abstract Collection<String> getLocallyRequiredConfigList(); @Override public Config getResolvedConfig(Config userConfig) throws SpecNotFoundException, TemplateException { ensureTemplatesResolved(); return getResolvedConfigHelper(userConfig, Sets.<JobTemplate>newHashSet()); } private Config getResolvedConfigHelper(Config userConfig, Set<JobTemplate> alreadyLoadedTemplates) throws SpecNotFoundException, TemplateException { Config config = getLocallyResolvedConfig(userConfig); if (superTemplates != null ) { for (JobTemplate template : Lists.reverse(this.superTemplates)) { if (!alreadyLoadedTemplates.contains(template)) { alreadyLoadedTemplates.add(template); Config fallback = template instanceof InheritingJobTemplate ? ((InheritingJobTemplate) template) .getResolvedConfigHelper(config, alreadyLoadedTemplates) : template.getResolvedConfig(config); config = config.withFallback(fallback); } } } return config; } protected abstract Config getLocallyResolvedConfig(Config userConfig) throws TemplateException; }
1,437
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/template/StaticJobTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.template; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.typesafe.config.Config; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SecureJobTemplate; import org.apache.gobblin.util.ConfigUtils; /** * A {@link JobTemplate} using a static {@link Config} as the raw configuration for the template. */ @Slf4j public class StaticJobTemplate extends InheritingJobTemplate implements SecureJobTemplate { public static final String SUPER_TEMPLATE_KEY = "gobblin.template.inherit"; public static final String IS_SECURE_KEY = "gobblin.template.isSecure"; public static final String SECURE_OVERRIDABLE_PROPERTIES_KEYS = "gobblin.template.secure.overridableProperties"; private Config rawConfig; private Set<String> requiredAttributes; @Getter private final URI uri; @Getter private final String version; @Getter private final String description; @Getter private Collection<String> dependencies; public StaticJobTemplate(URI uri, String version, String description, Config config, JobCatalogWithTemplates catalog) throws TemplateException { this(uri, version, description, config, getSuperTemplateUris(config), catalog); } /** An constructor that materialize multiple templates into a single static template * The constructor provided multiple in-memory templates as the input instead of templateURIs * */ public StaticJobTemplate(URI uri, String version, String description, Config config, List<JobTemplate> templates) { super(templates, false); this.uri = uri; this.version = version; this.rawConfig = config; this.description = description; } protected StaticJobTemplate(URI uri, String version, String description, Config config, List<URI> superTemplateUris, JobCatalogWithTemplates catalog) { super(superTemplateUris, catalog); this.uri = uri; this.version = version; this.description = description; this.rawConfig = config; this.requiredAttributes = config.hasPath(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST) ? new HashSet<>( Arrays.asList(config.getString(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST).split(","))) : Sets.<String>newHashSet(); this.dependencies = config.hasPath(ConfigurationKeys.JOB_DEPENDENCIES) ? Arrays .asList(config.getString(ConfigurationKeys.JOB_DEPENDENCIES).split(",")) : new ArrayList<>(); } private static List<URI> getSuperTemplateUris(Config config) throws TemplateException { if (config.hasPath(SUPER_TEMPLATE_KEY)) { List<URI> uris = Lists.newArrayList(); for (String uriString : ConfigUtils.getStringList(config, SUPER_TEMPLATE_KEY)) { try { uris.add(new URI(uriString)); } catch (URISyntaxException use) { throw new TemplateException("Super template uri is malformed: " + uriString, use); } } return uris; } else { return Lists.newArrayList(); } } @Override protected Config getLocalRawTemplate() { return this.rawConfig; } @Override protected Collection<String> getLocallyRequiredConfigList() { return this.requiredAttributes; } @Override protected Config getLocallyResolvedConfig(Config userConfig) { Config filteredUserConfig = SecureJobTemplate.filterUserConfig(this, userConfig, log); return filteredUserConfig.withFallback(this.rawConfig); } @Override public boolean isSecure() { return ConfigUtils.getBoolean(this.rawConfig, IS_SECURE_KEY, false); } @Override public Collection<String> overridableProperties() { return isSecure() ? ConfigUtils.getStringList(this.rawConfig, SECURE_OVERRIDABLE_PROPERTIES_KEYS) : Collections.emptyList(); } }
1,438
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/template/HOCONInputStreamJobTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.template; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import com.google.common.base.Charsets; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.SpecNotFoundException; /** * A {@link org.apache.gobblin.runtime.api.JobTemplate} that loads a HOCON file as a {@link StaticJobTemplate}. */ @Slf4j public class HOCONInputStreamJobTemplate extends StaticJobTemplate { public static final String VERSION_KEY = "gobblin.template.version"; public static final String DEFAULT_VERSION = "1"; /** * Load a template from an {@link InputStream}. Caller is responsible for closing {@link InputStream}. */ public HOCONInputStreamJobTemplate(InputStream inputStream, URI uri, JobCatalogWithTemplates catalog) throws SpecNotFoundException, TemplateException { this(ConfigFactory.parseReader(new InputStreamReader(inputStream, Charsets.UTF_8)), uri, catalog); } public HOCONInputStreamJobTemplate(Config config, URI uri, JobCatalogWithTemplates catalog) throws SpecNotFoundException, TemplateException { super(uri, config.hasPath(VERSION_KEY) ? config.getString(VERSION_KEY) : DEFAULT_VERSION, config.hasPath(ConfigurationKeys.JOB_DESCRIPTION_KEY) ? config.getString(ConfigurationKeys.JOB_DESCRIPTION_KEY) : "", config, catalog); } }
1,439
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/GenericGsonSpecSerDe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import com.google.common.base.Charsets; import com.google.gson.Gson; import com.google.gson.JsonDeserializer; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializer; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecSerDe; import org.apache.gobblin.runtime.api.SpecSerDeException; /** * Abstract {@link SpecSerDe} providing scaffolding to serialize a specific {@link Spec} derived class as JSON using {@link Gson}. * Extending classes MUST supply a per-instance serializer and a deserializer and SHOULD be concrete (non-generic), to permit * naming/reference from properties-based configuration. */ public abstract class GenericGsonSpecSerDe<T extends Spec> implements SpecSerDe { private final GsonSerDe<T> gsonSerDe; private final Class<T> specClass; protected GenericGsonSpecSerDe(Class<T> specClass, JsonSerializer<T> serializer, JsonDeserializer<T> deserializer) { this.specClass = specClass; this.gsonSerDe = new GsonSerDe<T>(specClass, serializer, deserializer); } @Override public byte[] serialize(Spec spec) throws SpecSerDeException { if (!specClass.isInstance(spec)) { throw new SpecSerDeException("Failed to serialize spec " + spec.getUri() + ", only " + specClass.getName() + " is supported"); } try { return this.gsonSerDe.serialize(specClass.cast(spec)).getBytes(Charsets.UTF_8); } catch (JsonParseException e) { throw new SpecSerDeException(spec, e); } } @Override public Spec deserialize(byte[] spec) throws SpecSerDeException { try { return this.gsonSerDe.deserialize(new String(spec, Charsets.UTF_8)); } catch (JsonParseException e) { throw new SpecSerDeException(e); } } }
1,440
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/FlowSpecSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import java.lang.reflect.Type; import java.net.URI; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.typesafe.config.ConfigRenderOptions; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.Spec; public class FlowSpecSerializer implements JsonSerializer<FlowSpec> { public static final String FLOW_SPEC_URI_KEY= "uri"; public static final String FLOW_SPEC_VERSION_KEY = "version"; public static final String FLOW_SPEC_DESCRIPTION_KEY = "description"; public static final String FLOW_SPEC_CONFIG_KEY = "config"; public static final String FLOW_SPEC_CONFIG_AS_PROPERTIES_KEY = "configAsProperties"; public static final String FLOW_SPEC_TEMPLATE_URIS_KEY = "templateURIs"; public static final String FLOW_SPEC_CHILD_SPECS_KEY = "childSpecs"; @Override public JsonElement serialize(FlowSpec src, Type typeOfSrc, JsonSerializationContext context) { JsonObject flowSpecJson = new JsonObject(); flowSpecJson.add(FLOW_SPEC_URI_KEY, context.serialize(src.getUri())); flowSpecJson.add(FLOW_SPEC_VERSION_KEY, context.serialize(src.getVersion())); flowSpecJson.add(FLOW_SPEC_DESCRIPTION_KEY, context.serialize(src.getDescription())); flowSpecJson.add(FLOW_SPEC_CONFIG_KEY, context.serialize(src.getConfig().root().render(ConfigRenderOptions.concise()))); flowSpecJson.add(FLOW_SPEC_CONFIG_AS_PROPERTIES_KEY, context.serialize(src.getConfigAsProperties())); JsonArray templateURIs = new JsonArray(); if (src.getTemplateURIs().isPresent()) { for (URI templateURI : src.getTemplateURIs().get()) { templateURIs.add(context.serialize(templateURI)); } } flowSpecJson.add(FLOW_SPEC_TEMPLATE_URIS_KEY, templateURIs); JsonArray childSpecs = new JsonArray(); if (src.getChildSpecs().isPresent()) { for (Spec spec : src.getChildSpecs().get()) { childSpecs.add(context.serialize(spec)); } } flowSpecJson.add(FLOW_SPEC_CHILD_SPECS_KEY, childSpecs); return flowSpecJson; } }
1,441
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/JobSpecSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import org.apache.gobblin.runtime.api.JobSpec; public class JobSpecSerializer implements JsonSerializer<JobSpec> { public static final String JOB_SPEC_URI_KEY = "uri"; public static final String JOB_SPEC_VERSION_KEY = "version"; public static final String JOB_SPEC_DESCRIPTION_KEY = "description"; public static final String JOB_SPEC_TEMPLATE_URI_KEY = "templateURI"; public static final String JOB_SPEC_CONFIG_AS_PROPERTIES_KEY = "configAsProperties"; @Override public JsonElement serialize(JobSpec src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jobSpecJson = new JsonObject(); jobSpecJson.add(JOB_SPEC_URI_KEY, context.serialize(src.getUri())); jobSpecJson.add(JOB_SPEC_VERSION_KEY, context.serialize(src.getVersion())); jobSpecJson.add(JOB_SPEC_DESCRIPTION_KEY, context.serialize(src.getDescription())); jobSpecJson.add(JOB_SPEC_TEMPLATE_URI_KEY, src.getTemplateURI().isPresent() ? context.serialize(src.getTemplateURI().get()) : null); jobSpecJson.add(JOB_SPEC_CONFIG_AS_PROPERTIES_KEY, context.serialize(src.getConfigAsProperties())); // NOTE: do not serialize `JobSpec.jobTemplate`, since `transient` return jobSpecJson; } }
1,442
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/GsonJobSpecSerDe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import com.google.gson.Gson; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.SpecSerDe; /** * {@link SpecSerDe} for {@link JobSpec}s that serializes as JSON using {@link Gson}. */ public class GsonJobSpecSerDe extends GenericGsonSpecSerDe<JobSpec> { public GsonJobSpecSerDe() { super(JobSpec.class, new JobSpecSerializer(), new JobSpecDeserializer()); } }
1,443
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/GsonFlowSpecSerDe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import com.google.gson.Gson; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.SpecSerDe; /** * {@link SpecSerDe} for {@link FlowSpec}s that serializes as JSON using {@link Gson}. */ public class GsonFlowSpecSerDe extends GenericGsonSpecSerDe<FlowSpec> { public GsonFlowSpecSerDe() { super(FlowSpec.class, new FlowSpecSerializer(), new FlowSpecDeserializer()); } }
1,444
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/GsonSerDe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonSerializer; /** * SerDe library used in GaaS for {@link org.apache.gobblin.runtime.api.SpecStore} and * {@link org.apache.gobblin.service.modules.orchestration.DagStateStore}. * * The solution is built on top of {@link Gson} library. * @param <T> The type of object to be serialized. */ public class GsonSerDe<T> { private final Gson gson; private final JsonSerializer<T> serializer; private final JsonDeserializer<T> deserializer; private final Type type; public GsonSerDe(Type type, JsonSerializer<T> serializer, JsonDeserializer<T> deserializer) { this.serializer = serializer; this.deserializer = deserializer; this.type = type; this.gson = new GsonBuilder().registerTypeAdapter(type, serializer) .registerTypeAdapter(type, deserializer) .create(); } public String serialize(T object) { return gson.toJson(object, type); } public T deserialize(String serializedObject) { return gson.fromJson(serializedObject, type); } }
1,445
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/FlowSpecDeserializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.Spec; public class FlowSpecDeserializer implements JsonDeserializer<FlowSpec> { @Override public FlowSpec deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { JsonObject jsonObject = json.getAsJsonObject(); String uri = jsonObject.get(FlowSpecSerializer.FLOW_SPEC_URI_KEY).getAsString(); String version = jsonObject.get(FlowSpecSerializer.FLOW_SPEC_VERSION_KEY).getAsString(); String description = jsonObject.get(FlowSpecSerializer.FLOW_SPEC_DESCRIPTION_KEY).getAsString(); Config config = ConfigFactory.parseString(jsonObject.get(FlowSpecSerializer.FLOW_SPEC_CONFIG_KEY).getAsString()); Properties properties; try { properties = context.deserialize(jsonObject.get(FlowSpecSerializer.FLOW_SPEC_CONFIG_AS_PROPERTIES_KEY), Properties.class); } catch (JsonParseException e) { // for backward compatibility properties = new Properties(); try { properties.load(new StringReader(jsonObject.get(FlowSpecSerializer.FLOW_SPEC_CONFIG_AS_PROPERTIES_KEY).getAsString())); } catch (IOException ioe) { throw new JsonParseException(e); } } Set<URI> templateURIs = new HashSet<>(); try { for (JsonElement template : jsonObject.get(FlowSpecSerializer.FLOW_SPEC_TEMPLATE_URIS_KEY).getAsJsonArray()) { templateURIs.add(new URI(template.getAsString())); } } catch (URISyntaxException e) { throw new JsonParseException(e); } List<Spec> childSpecs = new ArrayList<>(); for (JsonElement spec : jsonObject.get(FlowSpecSerializer.FLOW_SPEC_CHILD_SPECS_KEY).getAsJsonArray()) { childSpecs.add(context.deserialize(spec, FlowSpec.class)); } FlowSpec.Builder builder = FlowSpec.builder(uri).withVersion(version).withDescription(description).withConfig(config) .withConfigAsProperties(properties); if (!templateURIs.isEmpty()) { builder = builder.withTemplates(templateURIs); } if (!childSpecs.isEmpty()) { builder = builder.withChildSpecs(childSpecs); } return builder.build(); } }
1,446
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/JavaSpecSerDe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import org.apache.commons.lang3.SerializationException; import org.apache.commons.lang3.SerializationUtils; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecSerDe; import org.apache.gobblin.runtime.api.SpecSerDeException; /** * {@link SpecSerDe} that does Java serialization using {@link SerializationUtils} */ public class JavaSpecSerDe implements SpecSerDe { @Override public byte[] serialize(Spec spec) throws SpecSerDeException { try { return SerializationUtils.serialize(spec); } catch (SerializationException e) { throw new SpecSerDeException(spec, e); } } @Override public Spec deserialize(byte[] spec) throws SpecSerDeException { try { return SerializationUtils.deserialize(spec); } catch (SerializationException e) { throw new SpecSerDeException(e); } } }
1,447
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_serde/JobSpecDeserializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_serde; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; import java.util.Properties; import org.apache.gobblin.runtime.api.JobSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JobSpecDeserializer implements JsonDeserializer<JobSpec> { private static final Logger LOGGER = LoggerFactory.getLogger(JobSpecDeserializer.class); @Override public JobSpec deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { JsonObject jsonObject = json.getAsJsonObject(); String uri = jsonObject.get(JobSpecSerializer.JOB_SPEC_URI_KEY).getAsString(); String version = jsonObject.get(JobSpecSerializer.JOB_SPEC_VERSION_KEY).getAsString(); String description = jsonObject.get(JobSpecSerializer.JOB_SPEC_DESCRIPTION_KEY).getAsString(); Optional<URI> templateURI = Optional.ofNullable(jsonObject.get(JobSpecSerializer.JOB_SPEC_TEMPLATE_URI_KEY)).flatMap(jsonElem -> { try { return Optional.of(new URI(jsonElem.getAsString())); } catch (URISyntaxException | RuntimeException e) { LOGGER.warn(String.format("error deserializing '%s' as a URI: %s", jsonElem.toString(), e.getMessage())); return Optional.empty(); } }); Properties properties; try { properties = context.deserialize(jsonObject.get(JobSpecSerializer.JOB_SPEC_CONFIG_AS_PROPERTIES_KEY), Properties.class); } catch (JsonParseException e) { // for backward compatibility... (is this needed for `JobSpec`, or only for (inspiration) `FlowSpec`???) properties = new Properties(); try { properties.load(new StringReader(jsonObject.get(JobSpecSerializer.JOB_SPEC_CONFIG_AS_PROPERTIES_KEY).getAsString())); } catch (IOException ioe) { throw new JsonParseException(e); } } JobSpec.Builder builder = JobSpec.builder(uri).withVersion(version).withDescription(description).withConfigAsProperties(properties); if (templateURI.isPresent()) { builder = builder.withTemplate(templateURI.get()); } return builder.build(); } }
1,448
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/scheduler/DefaultJobSpecSchedulerListenerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.scheduler; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.api.JobSpecSchedulerListener; /** * Default no-op implementation for {@link JobSpecSchedulerListener}. It may optionally log * the callbacks. */ public class DefaultJobSpecSchedulerListenerImpl implements JobSpecSchedulerListener { protected final Optional<Logger> _log; /** * Constructor * @param log if no log is specified, the logging will be done. Logging level is INFO. */ public DefaultJobSpecSchedulerListenerImpl(Optional<Logger> log) { _log = log; } public DefaultJobSpecSchedulerListenerImpl(Logger log) { this(Optional.of(log)); } /** Constructor with no logging */ public DefaultJobSpecSchedulerListenerImpl() { this(Optional.<Logger>absent()); } /** {@inheritDoc} */ @Override public void onJobScheduled(JobSpecSchedule jobSchedule) { if (_log.isPresent()) { _log.get().info("Job scheduled: " + jobSchedule); } } /** {@inheritDoc} */ @Override public void onJobUnscheduled(JobSpecSchedule jobSchedule) { if (_log.isPresent()) { _log.get().info("Job unscheduled: " + jobSchedule); } } /** {@inheritDoc} */ @Override public void onJobTriggered(JobSpec jobSpec) { if (_log.isPresent()) { _log.get().info("Job triggered: " + jobSpec); } } }
1,449
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/scheduler/AbstractJobSpecScheduler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.scheduler; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.AbstractIdleService; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.api.JobSpecScheduler; import org.apache.gobblin.runtime.api.JobSpecSchedulerListener; /** * A base implementation of {@link JobSpecScheduler} that keeps track of {@link JobSpecSchedule}s * and listeners. Subclasses are expected to implement mainly * {@link #doScheduleJob(JobSpec, Runnable)} and {@link #doUnschedule(JobSpecSchedule)} which * implement the actual scheduling. */ public abstract class AbstractJobSpecScheduler extends AbstractIdleService implements JobSpecScheduler { protected final Map<URI, JobSpecSchedule> _schedules = new HashMap<>(); private final Logger _log; private final JobSpecSchedulerListeners _callbacksDispatcher; public AbstractJobSpecScheduler(Optional<Logger> log) { _log = log.or(LoggerFactory.getLogger(getClass())); _callbacksDispatcher = new JobSpecSchedulerListeners(_log); } /** {@inheritDoc} */ @Override public void registerJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _callbacksDispatcher.registerJobSpecSchedulerListener(listener); } /** {@inheritDoc} */ @Override public void registerWeakJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _callbacksDispatcher.registerWeakJobSpecSchedulerListener(listener); } /** {@inheritDoc} */ @Override public void unregisterJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _callbacksDispatcher.unregisterJobSpecSchedulerListener(listener); } /** {@inheritDoc} */ @Override public List<JobSpecSchedulerListener> getJobSpecSchedulerListeners() { return _callbacksDispatcher.getJobSpecSchedulerListeners(); } /** {@inheritDoc} */ @Override public JobSpecSchedule scheduleJob(JobSpec jobSpec, Runnable jobRunnable) { _log.info("Scheduling JobSpec " + jobSpec); final URI jobSpecURI = jobSpec.getUri(); JobSpecSchedule newSchedule = null; Runnable runnableWithTriggerCallback = new TriggerRunnable(jobSpec, jobRunnable); synchronized (this) { JobSpecSchedule existingSchedule = _schedules.get(jobSpecURI); if (null != existingSchedule) { if (existingSchedule.getJobSpec().equals(jobSpec)) { _log.warn("Ignoring already scheduled job: " + jobSpec); return existingSchedule; } // a new job spec -- unschedule first so that we schedule the new version unscheduleJob(jobSpecURI); } newSchedule = doScheduleJob(jobSpec, runnableWithTriggerCallback); _schedules.put(jobSpecURI, newSchedule); } _callbacksDispatcher.onJobScheduled(newSchedule); return newSchedule; } /** {@inheritDoc} */ @Override public JobSpecSchedule scheduleOnce(JobSpec jobSpec, Runnable jobRunnable) { _log.info("Scheduling once JobSpec " + jobSpec); Runnable runOnceRunnable = new RunOnceRunnable(jobSpec.getUri(), jobRunnable); return scheduleJob(jobSpec, runOnceRunnable); } /** {@inheritDoc} */ @Override public void unscheduleJob(URI jobSpecURI) { JobSpecSchedule existingSchedule = null; synchronized (this) { existingSchedule = _schedules.get(jobSpecURI); if (null != existingSchedule) { _log.info("Unscheduling " + existingSchedule); this._schedules.remove(jobSpecURI); doUnschedule(existingSchedule); } } if (null != existingSchedule) { _callbacksDispatcher.onJobUnscheduled(existingSchedule); } } /** Actual implementation of scheduling */ protected abstract JobSpecSchedule doScheduleJob(JobSpec jobSpec, Runnable jobRunnable); /** Implementations should override this method */ protected abstract void doUnschedule(JobSpecSchedule existingSchedule); /** {@inheritDoc} */ @Override public Map<URI, JobSpecSchedule> getSchedules() { return Collections.unmodifiableMap(_schedules); } public Logger getLog() { return _log; } /** * A helper class for run-once jobs. It will run the runnable associated with a schedule and * remove the schedule automatically. * */ public class RunOnceRunnable implements Runnable { private final URI _jobSpecURI; private final Runnable _scheduleRunnable; public RunOnceRunnable(URI jobSpecURI, Runnable innerRunnable) { Preconditions.checkNotNull(jobSpecURI); Preconditions.checkNotNull(innerRunnable); _jobSpecURI = jobSpecURI; _scheduleRunnable = innerRunnable; } @Override public void run() { try { _scheduleRunnable.run(); } finally { unscheduleJob(_jobSpecURI); } } } protected class TriggerRunnable implements Runnable { private final JobSpec _jobSpec; private final Runnable _jobRunnable; public TriggerRunnable(JobSpec jobSpec, Runnable jobRunnable) { _jobSpec = jobSpec; _jobRunnable = jobRunnable; } @Override public void run() { _callbacksDispatcher.onJobTriggered(_jobSpec); _jobRunnable.run(); } } @Override protected void startUp() throws TimeoutException { // Do nothing by default } @Override protected void shutDown() throws TimeoutException { try { _callbacksDispatcher.close(); } catch (IOException ioe) { _log.error("Failed to shut down " + this.getClass().getName(), ioe); } } }
1,450
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/scheduler/JobSpecSchedulerListeners.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.scheduler; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.api.JobSpecSchedulerListener; import org.apache.gobblin.runtime.api.JobSpecSchedulerListenersContainer; import org.apache.gobblin.util.callbacks.CallbacksDispatcher; /** * Manages a list of {@link JobSpecSchedulerListener}s and can dispatch callbacks to them. */ public class JobSpecSchedulerListeners implements JobSpecSchedulerListenersContainer, JobSpecSchedulerListener, Closeable { private CallbacksDispatcher<JobSpecSchedulerListener> _dispatcher; public JobSpecSchedulerListeners(Optional<ExecutorService> execService, Optional<Logger> log) { _dispatcher = new CallbacksDispatcher<>(execService, log); } public JobSpecSchedulerListeners(Logger log) { _dispatcher = new CallbacksDispatcher<>(log); } public JobSpecSchedulerListeners() { _dispatcher = new CallbacksDispatcher<>(); } /** {@inheritDoc} */ @Override public void registerJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _dispatcher.addListener(listener); } /** {@inheritDoc} */ @Override public void unregisterJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _dispatcher.removeListener(listener); } /** {@inheritDoc} */ @Override public List<JobSpecSchedulerListener> getJobSpecSchedulerListeners() { return _dispatcher.getListeners(); } @Override public void onJobScheduled(JobSpecSchedule jobSchedule) { try { _dispatcher.execCallbacks(new JobScheduledCallback(jobSchedule)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onJobScheduled interrupted."); } } @Override public void onJobTriggered(JobSpec jobSpec) { try { _dispatcher.execCallbacks(new JobTriggeredCallback(jobSpec)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onJobTriggered interrupted."); } } @Override public void onJobUnscheduled(JobSpecSchedule jobSchedule) { try { _dispatcher.execCallbacks(new JobUnscheduledCallback(jobSchedule)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onJobUnscheduled interrupted."); } } @Override public void registerWeakJobSpecSchedulerListener(JobSpecSchedulerListener listener) { _dispatcher.addWeakListener(listener); } @Override public void close() throws IOException { _dispatcher.close(); } }
1,451
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/scheduler/ImmediateJobSpecScheduler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.scheduler; import java.util.concurrent.ThreadFactory; import org.slf4j.Logger; import com.google.common.base.Optional; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.api.JobSpecScheduler; import org.apache.gobblin.runtime.std.DefaultJobSpecScheduleImpl; import org.apache.gobblin.util.LoggingUncaughtExceptionHandler; /** * A simple implementation of a {@link JobSpecScheduler} which schedules the job immediately. * Note that job runnable is scheduled immediately but this happens in a separate thread so it is * asynchronous. */ public class ImmediateJobSpecScheduler extends AbstractJobSpecScheduler { private final ThreadFactory _jobRunnablesThreadFactory; public ImmediateJobSpecScheduler(Optional<Logger> log) { super(log); _jobRunnablesThreadFactory = (new ThreadFactoryBuilder()) .setDaemon(false) .setNameFormat(getLog().getName() + "-thread-%d") .setUncaughtExceptionHandler(new LoggingUncaughtExceptionHandler(Optional.of(getLog()))) .build(); } @Override protected JobSpecSchedule doScheduleJob(JobSpec jobSpec, Runnable jobRunnable) { Thread runThread = _jobRunnablesThreadFactory.newThread(jobRunnable); getLog().info("Starting JobSpec " + jobSpec + " in thread " + runThread.getName()); JobSpecSchedule schedule = DefaultJobSpecScheduleImpl.createImmediateSchedule(jobSpec, jobRunnable); runThread.start(); return schedule; } @Override protected void doUnschedule(JobSpecSchedule existingSchedule) { // nothing to do } }
1,452
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/scheduler/QuartzJobSpecScheduler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.scheduler; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.quartz.CronScheduleBuilder; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.slf4j.Logger; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import org.apache.gobblin.runtime.api.JobSpecScheduler; import org.apache.gobblin.scheduler.SchedulerService; import org.apache.gobblin.util.service.StandardServiceConfig; import lombok.Data; /** * A {@link JobSpecScheduler} using Quartz. */ public class QuartzJobSpecScheduler extends AbstractJobSpecScheduler { public static final Config DEFAULT_CFG = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder() .put(StandardServiceConfig.STARTUP_TIMEOUT_MS_PROP, 1 * 1000) // 1 second .put(StandardServiceConfig.SHUTDOWN_TIMEOUT_MS_PROP, 1 * 60 * 1000) // 1 minute .build()); protected static final String JOB_SPEC_KEY = "jobSpec"; protected static final String JOB_RUNNABLE_KEY = "jobRunnable"; // A Quartz scheduler @VisibleForTesting final SchedulerService _scheduler; private final StandardServiceConfig _cfg; public QuartzJobSpecScheduler(Optional<Logger> log, Config cfg, Optional<SchedulerService> scheduler) { super(log); _scheduler = scheduler.isPresent() ? scheduler.get() : createDefaultSchedulerService(cfg); _cfg = new StandardServiceConfig(cfg.withFallback(DEFAULT_CFG)); } public QuartzJobSpecScheduler() { this(Optional.<Logger>absent(), ConfigFactory.empty(), Optional.<SchedulerService>absent()); } public QuartzJobSpecScheduler(Logger log) { this(Optional.of(log), ConfigFactory.empty(), Optional.<SchedulerService>absent()); } public QuartzJobSpecScheduler(Logger log, Config cfg) { this(Optional.of(log), cfg, Optional.<SchedulerService>absent()); } public QuartzJobSpecScheduler(GobblinInstanceEnvironment env) { this(Optional.of(env.getLog()), env.getSysConfig().getConfig(), Optional.<SchedulerService>absent()); } protected static SchedulerService createDefaultSchedulerService(Config cfg) { return new SchedulerService(cfg); } /** {@inheritDoc} */ @Override protected JobSpecSchedule doScheduleJob(JobSpec jobSpec, Runnable jobRunnable) { // Build a data map that gets passed to the job JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(JOB_SPEC_KEY, jobSpec); jobDataMap.put(JOB_RUNNABLE_KEY, jobRunnable); // Build a Quartz job JobDetail job = JobBuilder.newJob(QuartzJob.class) .withIdentity(jobSpec.getUri().toString()) .withDescription(Strings.nullToEmpty(jobSpec.getDescription())) .usingJobData(jobDataMap) .build(); Trigger jobTrigger = createTrigger(job.getKey(), jobSpec); QuartzJobSchedule jobSchedule = new QuartzJobSchedule(jobSpec, jobRunnable, jobTrigger); try { _scheduler.getScheduler().scheduleJob(job, jobTrigger); getLog().info(String.format("Scheduled job %s next two fire times: %s , %s.", jobSpec, jobTrigger.getNextFireTime(), jobTrigger.getFireTimeAfter(jobTrigger.getNextFireTime()))); } catch (SchedulerException e) { throw new RuntimeException("Scheduling failed for " + jobSpec + ":" + e, e); } return jobSchedule; } /** {@inheritDoc} */ @Override protected void doUnschedule(JobSpecSchedule existingSchedule) { Preconditions.checkNotNull(existingSchedule); Preconditions.checkArgument(existingSchedule instanceof QuartzJobSchedule); QuartzJobSchedule quartzSchedule = (QuartzJobSchedule)existingSchedule; try { _scheduler.getScheduler().deleteJob(quartzSchedule.getQuartzTrigger().getJobKey()); } catch (SchedulerException e) { throw new RuntimeException("Unscheduling failed for " + existingSchedule.getJobSpec() + ":" + e, e); } } @Override protected void startUp() throws TimeoutException { super.startUp(); _scheduler.startAsync(); // Start-up should not take long getLog().info("Waiting QuartzJobSpecScheduler to run. Timeout is {} ms", _cfg.getStartUpTimeoutMs()); long startTime = System.currentTimeMillis(); _scheduler.awaitRunning(_cfg.getStartUpTimeoutMs(), TimeUnit.MILLISECONDS); getLog().info("QuartzJobSpecScheduler runs. Time waited is {} ms", System.currentTimeMillis() - startTime); } @Override protected void shutDown() throws TimeoutException { super.shutDown(); _scheduler.stopAsync(); _scheduler.awaitTerminated(_cfg.getShutDownTimeoutMs(), TimeUnit.MILLISECONDS); } /** * Create a {@link Trigger} from the given {@link JobSpec} */ private Trigger createTrigger(JobKey jobKey, JobSpec jobSpec) { // Build a trigger for the job with the given cron-style schedule return TriggerBuilder.newTrigger() .withIdentity("Cron for " + jobSpec.getUri()) .forJob(jobKey) .withSchedule(CronScheduleBuilder.cronSchedule( jobSpec.getConfig().getString(ConfigurationKeys.JOB_SCHEDULE_KEY))) .build(); } @Data static class QuartzJobSchedule implements JobSpecSchedule { private final JobSpec jobSpec; private final Runnable jobRunnable; private final Trigger quartzTrigger; @Override public Optional<Long> getNextRunTimeMillis() { Date nextRuntime = this.quartzTrigger.getNextFireTime(); return null != nextRuntime ? Optional.<Long>of(nextRuntime.getTime()) : Optional.<Long>absent(); } } /** * A Gobblin job to be run inside quartz. */ @DisallowConcurrentExecution public static class QuartzJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap dataMap = context.getJobDetail().getJobDataMap(); JobSpec jobSpec = (JobSpec) dataMap.get(JOB_SPEC_KEY); Runnable jobRunnable = (Runnable) dataMap.get(JOB_RUNNABLE_KEY); try { jobRunnable.run(); } catch (Throwable t) { throw new JobExecutionException("Job runable for " + jobSpec + " failed.", t); } } } }
1,453
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/DefaultJobCatalogListenerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.net.URI; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.api.JobCatalogListener; import org.apache.gobblin.runtime.api.JobSpec; /** * Default NOOP implementation for {@link JobCatalogListener}. It can log the callbacks. Other * implementing classes can use this as a base to override only the methods they care about. */ public class DefaultJobCatalogListenerImpl implements JobCatalogListener { protected final Optional<Logger> _log; /** * Constructor * @param log if no log is specified, the logging will be done. Logging level is INFO. */ public DefaultJobCatalogListenerImpl(Optional<Logger> log) { _log = log; } public DefaultJobCatalogListenerImpl(Logger log) { this(Optional.of(log)); } /** Constructor with no logging */ public DefaultJobCatalogListenerImpl() { this(Optional.<Logger>absent()); } /** {@inheritDoc} */ @Override public void onAddJob(JobSpec addedJob) { if (_log.isPresent()) { _log.get().info("New JobSpec detected: " + addedJob.toShortString()); } } /** {@inheritDoc} */ @Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { if (_log.isPresent()) { _log.get().info("JobSpec deleted: " + deletedJobURI + "/" + deletedJobVersion); } } /** {@inheritDoc} */ @Override public void onUpdateJob(JobSpec updatedJob) { if (_log.isPresent()) { _log.get().info("JobSpec changed: " + updatedJob.toShortString()); } } }
1,454
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/JobExecutionUpdatable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.net.URI; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.api.JobExecution; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.util.JobLauncherUtils; import lombok.AllArgsConstructor; import lombok.Data; /** * Identifies a specific execution of a {@link JobSpec} */ @Alpha @Data @AllArgsConstructor public class JobExecutionUpdatable implements JobExecution { /** The URI of the job being executed */ protected final URI jobSpecURI; /** The version of the JobSpec being launched */ protected final String jobSpecVersion; /** The millisecond timestamp when the job was launched */ protected final long launchTimeMillis; /** Unique (for the given JobExecutionLauncher) id for this execution */ protected final String executionId; public static JobExecutionUpdatable createFromJobSpec(JobSpec jobSpec) { return new JobExecutionUpdatable(jobSpec.getUri(), jobSpec.getVersion(), System.currentTimeMillis(), JobLauncherUtils.newJobId(JobState.getJobNameFromProps(jobSpec.getConfigAsProperties()))); } }
1,455
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/DefaultConfigurableImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.util.Properties; import com.typesafe.config.Config; import org.apache.gobblin.runtime.api.Configurable; import org.apache.gobblin.util.ConfigUtils; /** * Default immutable implementation for {@link Configurable} interface. */ public class DefaultConfigurableImpl implements Configurable { final Config _config; final Properties _props; protected DefaultConfigurableImpl(Config config, Properties props) { _config = config; _props = props; } /** {@inheritDoc} */ @Override public Config getConfig() { return _config; } /** {@inheritDoc} */ @Override public Properties getConfigAsProperties() { return _props; } public static DefaultConfigurableImpl createFromConfig(Config srcConfig) { return new DefaultConfigurableImpl(srcConfig, ConfigUtils.configToProperties(srcConfig)); } public static DefaultConfigurableImpl createFromProperties(Properties srcConfig) { return new DefaultConfigurableImpl(ConfigUtils.propertiesToConfig(srcConfig), srcConfig); } }
1,456
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/DefaultJobLifecycleListenerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.net.URI; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.JobExecutionDriver; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobLifecycleListener; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; /** * Default NOOP implementation for {@link JobLifecycleListener}. It can log the callbacks. Other * implementing classes can use this as a base to override only the methods they care about. */ public class DefaultJobLifecycleListenerImpl implements JobLifecycleListener { protected final Optional<Logger> _log; /** * Constructor * @param log if no log is specified, the logging will be done. Logging level is INFO. */ public DefaultJobLifecycleListenerImpl(Optional<Logger> log) { _log = log; } public DefaultJobLifecycleListenerImpl(Logger log) { this(Optional.of(log)); } /** Constructor with no logging */ public DefaultJobLifecycleListenerImpl() { this(Optional.<Logger>absent()); } /** {@inheritDoc} */ @Override public void onAddJob(JobSpec addedJob) { if (_log.isPresent()) { _log.get().info("New JobSpec detected: " + addedJob.toShortString()); } } /** {@inheritDoc} */ @Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { if (_log.isPresent()) { _log.get().info("JobSpec deleted: " + deletedJobURI + "/" + deletedJobVersion); } } /** {@inheritDoc} */ @Override public void onUpdateJob(JobSpec updatedJob) { if (_log.isPresent()) { _log.get().info("JobSpec changed: " + updatedJob.toShortString()); } } /** {@inheritDoc} */ @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (_log.isPresent()) { _log.get().info("JobExection status change for " + state.getJobSpec().toShortString() + ": " + previousStatus + " --> " + newStatus); } } /** {@inheritDoc} */ @Override public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { if (_log.isPresent()) { _log.get().info("JobExection stage change for " + state.getJobSpec().toShortString() + ": " + previousStage + " --> " + newStage); } } /** {@inheritDoc} */ @Override public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { if (_log.isPresent()) { _log.get().info("JobExection metadata change for " + state.getJobSpec().toShortString() + key + ": '" + oldValue + "' --> '" + newValue + "'"); } } @Override public void onJobScheduled(JobSpecSchedule jobSchedule) { if (_log.isPresent()) { _log.get().info("job scheduled: " + jobSchedule); } } @Override public void onJobUnscheduled(JobSpecSchedule jobSchedule) { if (_log.isPresent()) { _log.get().info("job unscheduled: " + jobSchedule); } } @Override public void onJobTriggered(JobSpec jobSpec) { if (_log.isPresent()) { _log.get().info("job triggered: " + jobSpec); } } @Override public void onJobLaunch(JobExecutionDriver jobDriver) { if (_log.isPresent()) { _log.get().info("job launched: " + jobDriver); } } }
1,457
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/DefaultJobExecutionStateListenerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobExecutionStateListener; /** * Default NOOP implementation for a {@link JobExecutionStateListener}. The implementation can * optionally log the callbacks. */ public class DefaultJobExecutionStateListenerImpl implements JobExecutionStateListener { protected final Optional<Logger> _log; /** * Constructor * @param log if present, the implementation will log each callback at INFO level */ public DefaultJobExecutionStateListenerImpl(Optional<Logger> log) { _log = log; } public DefaultJobExecutionStateListenerImpl(Logger log) { this(Optional.of(log)); } /** Constructor with no logging */ public DefaultJobExecutionStateListenerImpl() { this(Optional.<Logger>absent()); } /** {@inheritDoc} */ @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (_log.isPresent()) { _log.get().info("JobExection status change for " + state.getJobSpec().toShortString() + ": " + previousStatus + " --> " + newStatus); } } /** {@inheritDoc} */ @Override public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { if (_log.isPresent()) { _log.get().info("JobExection stage change for " + state.getJobSpec().toShortString() + ": " + previousStage + " --> " + newStage); } } /** {@inheritDoc} */ @Override public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { if (_log.isPresent()) { _log.get().info("JobExection metadata change for " + state.getJobSpec().toShortString() + key + ": '" + oldValue + "' --> '" + newValue + "'"); } } }
1,458
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/FilteredJobLifecycleListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.net.URI; import com.google.common.base.Predicate; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.JobExecutionDriver; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobLifecycleListener; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import lombok.AllArgsConstructor; /** * A listener that can delegate to another {@link JobLifecycleListener} only callbacks that * are relevant to a specific Jobs. * */ @AllArgsConstructor public class FilteredJobLifecycleListener implements JobLifecycleListener { private final Predicate<JobSpec> filter; private final JobLifecycleListener delegate; /** {@inheritDoc} */ @Override public void onAddJob(JobSpec addedJob) { if (this.filter.apply(addedJob)) { this.delegate.onAddJob(addedJob); } } /** * {@inheritDoc} * * NOTE: For this callback only conditions on the URI and version will be used. * */ @Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { JobSpec fakeJobSpec = JobSpec.builder(deletedJobURI).withVersion(deletedJobVersion).build(); if (this.filter.apply(fakeJobSpec)) { this.delegate.onDeleteJob(deletedJobURI, deletedJobVersion); } } /** {@inheritDoc} */ @Override public void onUpdateJob(JobSpec updatedJob) { if (this.filter.apply(updatedJob)) { this.delegate.onUpdateJob(updatedJob); } } /** {@inheritDoc} */ @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (this.filter.apply(state.getJobSpec())) { this.delegate.onStatusChange(state, previousStatus, newStatus); } } /** {@inheritDoc} */ @Override public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { if (this.filter.apply(state.getJobSpec())) { this.delegate.onStageTransition(state, previousStage, newStage); } } /** {@inheritDoc} */ @Override public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { if (this.filter.apply(state.getJobSpec())) { this.delegate.onMetadataChange(state, key, oldValue, newValue); } } @Override public void onJobScheduled(JobSpecSchedule jobSchedule) { if (this.filter.apply(jobSchedule.getJobSpec())) { this.delegate.onJobScheduled(jobSchedule); } } @Override public void onJobUnscheduled(JobSpecSchedule jobSchedule) { if (this.filter.apply(jobSchedule.getJobSpec())) { this.delegate.onJobUnscheduled(jobSchedule); } } @Override public void onJobTriggered(JobSpec jobSpec) { if (this.filter.apply(jobSpec)) { this.delegate.onJobTriggered(jobSpec); } } @Override public void onJobLaunch(JobExecutionDriver jobDriver) { if (this.filter.apply(jobDriver.getJobExecutionState().getJobSpec())) { this.delegate.onJobLaunch(jobDriver); } } }
1,459
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/DefaultJobSpecScheduleImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import com.google.common.base.Optional; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecSchedule; import lombok.Data; /** * Simple POJO implementation of {@link JobSpecSchedule} */ @Data public class DefaultJobSpecScheduleImpl implements JobSpecSchedule { private final JobSpec jobSpec; private final Runnable jobRunnable; private final Optional<Long> nextRunTimeMillis; /** Creates a schedule denoting that the job is to be executed immediately */ public static DefaultJobSpecScheduleImpl createImmediateSchedule(JobSpec jobSpec, Runnable jobRunnable) { return new DefaultJobSpecScheduleImpl(jobSpec, jobRunnable, Optional.of(System.currentTimeMillis())); } /** Creates a schedule denoting that the job is not to be executed */ public static DefaultJobSpecScheduleImpl createNoSchedule(JobSpec jobSpec, Runnable jobRunnable) { return new DefaultJobSpecScheduleImpl(jobSpec, jobRunnable, Optional.<Long>absent()); } }
1,460
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/JobLifecycleListenersList.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.JobCatalogListenersContainer; import org.apache.gobblin.runtime.api.JobExecutionDriver; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobExecutionStateListener.MetadataChangeCallback; import org.apache.gobblin.runtime.api.JobExecutionStateListener.StageTransitionCallback; import org.apache.gobblin.runtime.api.JobExecutionStateListener.StatusChangeCallback; import org.apache.gobblin.runtime.api.JobLifecycleListener; import org.apache.gobblin.runtime.api.JobLifecycleListenersContainer; import org.apache.gobblin.runtime.api.JobSpecSchedulerListenersContainer; import org.apache.gobblin.util.callbacks.CallbacksDispatcher; /** * A default implementation to manage a list of {@link JobLifecycleListener} * */ public class JobLifecycleListenersList implements JobLifecycleListenersContainer, Closeable { private final CallbacksDispatcher<JobLifecycleListener> _dispatcher; private final JobCatalogListenersContainer _jobCatalogDelegate; private final JobSpecSchedulerListenersContainer _jobSchedulerDelegate; public JobLifecycleListenersList(JobCatalogListenersContainer jobCatalogDelegate, JobSpecSchedulerListenersContainer jobSchedulerDelegate, Optional<ExecutorService> execService, Optional<Logger> log) { _dispatcher = new CallbacksDispatcher<>(execService, log); _jobCatalogDelegate = jobCatalogDelegate; _jobSchedulerDelegate = jobSchedulerDelegate; } public JobLifecycleListenersList(JobCatalogListenersContainer jobCatalogDelegate, JobSpecSchedulerListenersContainer jobSchedulerDelegate, Logger log) { this(jobCatalogDelegate, jobSchedulerDelegate, Optional.<ExecutorService>absent(), Optional.of(log)); } public JobLifecycleListenersList(JobCatalogListenersContainer jobCatalogDelegate, JobSpecSchedulerListenersContainer jobSchedulerDelegate) { this(jobCatalogDelegate, jobSchedulerDelegate, Optional.<ExecutorService>absent(), Optional.<Logger>absent()); } /** {@inheritDoc} */ @Override public void registerJobLifecycleListener(JobLifecycleListener listener) { _dispatcher.addListener(listener); _jobCatalogDelegate.addListener(listener); _jobSchedulerDelegate.registerJobSpecSchedulerListener(listener); } /** {@inheritDoc} */ @Override public void unregisterJobLifecycleListener(JobLifecycleListener listener) { _jobSchedulerDelegate.unregisterJobSpecSchedulerListener(listener); _jobCatalogDelegate.removeListener(listener); _dispatcher.removeListener(listener); } @Override public void close() throws IOException { _dispatcher.close(); } /** {@inheritDoc} */ @Override public List<JobLifecycleListener> getJobLifecycleListeners() { return _dispatcher.getListeners(); } public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { try { _dispatcher.execCallbacks(new StatusChangeCallback(state, previousStatus, newStatus)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onStatusChange interrupted."); } } public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { try { _dispatcher.execCallbacks(new StageTransitionCallback(state, previousStage, newStage)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onStageTransition interrupted."); } } public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { try { _dispatcher.execCallbacks(new MetadataChangeCallback(state, key, oldValue, newValue)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onMetadataChange interrupted."); } } public void onJobLaunch(JobExecutionDriver driver) { try { _dispatcher.execCallbacks(new JobLifecycleListener.JobLaunchCallback(driver)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onJobLaunch interrupted."); } } @Override public void registerWeakJobLifecycleListener(JobLifecycleListener listener) { _dispatcher.addWeakListener(listener); _jobCatalogDelegate.registerWeakJobCatalogListener(listener); _jobSchedulerDelegate.registerWeakJobSpecSchedulerListener(listener); } }
1,461
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/JobSpecFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.net.URI; import java.net.URISyntaxException; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import org.apache.gobblin.runtime.api.JobSpec; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * A helper class to create JobSpec predicates. */ @AllArgsConstructor public class JobSpecFilter implements Predicate<JobSpec> { private final Optional<Predicate<URI>> uriPredicate; private final Optional<Predicate<String>> versionPredicate; @Override public boolean apply(JobSpec input) { Preconditions.checkNotNull(input); boolean res = true; if (this.uriPredicate.isPresent()) { res &= this.uriPredicate.get().apply(input.getUri()); } if (res && this.versionPredicate.isPresent()) { res &= this.versionPredicate.get().apply(input.getVersion()); } return res; } public static Builder builder() { return new Builder(); } public static JobSpecFilter eqJobSpecURI(URI jobSpecURI) { return builder().eqURI(jobSpecURI).build(); } public static JobSpecFilter eqJobSpecURI(String jobSpecURI) { return builder().eqURI(jobSpecURI).build(); } @Getter @Setter public static class Builder { private Predicate<URI> uriPredicate; private Predicate<String> versionPredicate; public Builder eqURI(URI uri) { this.uriPredicate = Predicates.equalTo(uri); return this; } public Builder eqURI(String uri) { try { this.uriPredicate = Predicates.equalTo(new URI(uri)); } catch (URISyntaxException e) { throw new RuntimeException("invalid URI: " + uri, e); } return this; } public Builder eqVersion(String version) { this.versionPredicate = Predicates.equalTo(version); return this; } public JobSpecFilter build() { return new JobSpecFilter(Optional.fromNullable(this.uriPredicate), Optional.fromNullable(this.versionPredicate)); } } }
1,462
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/std/JobExecutionStateListeners.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.std; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.JobState.RunningState; import org.apache.gobblin.runtime.api.JobExecutionState; import org.apache.gobblin.runtime.api.JobExecutionStateListener; import org.apache.gobblin.runtime.api.JobExecutionStateListenerContainer; import org.apache.gobblin.util.callbacks.CallbacksDispatcher; /** * A helper class to maintain a list of {@link JobExecutionStateListener} instances. It itself * implements the JobExecutionStateListener interface so all calls are dispatched to the children * listeners. */ public class JobExecutionStateListeners implements JobExecutionStateListener, JobExecutionStateListenerContainer, Closeable { private CallbacksDispatcher<JobExecutionStateListener> _dispatcher; public JobExecutionStateListeners(Optional<ExecutorService> execService, Optional<Logger> log) { _dispatcher = new CallbacksDispatcher<>(execService, log); } public JobExecutionStateListeners(Logger log) { _dispatcher = new CallbacksDispatcher<>(log); } public JobExecutionStateListeners() { _dispatcher = new CallbacksDispatcher<>(); } /** {@inheritDoc} */ @Override public void registerStateListener(JobExecutionStateListener listener) { _dispatcher.addListener(listener); } /** {@inheritDoc} */ @Override public void unregisterStateListener(JobExecutionStateListener listener) { _dispatcher.removeListener(listener); } /** {@inheritDoc} */ @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { try { _dispatcher.execCallbacks(new StatusChangeCallback(state, previousStatus, newStatus)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onStatusChange interrupted."); } } /** {@inheritDoc} */ @Override public void onStageTransition(JobExecutionState state, String previousStage, String newStage) { try { _dispatcher.execCallbacks(new StageTransitionCallback(state, previousStage, newStage)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onStageTransition interrupted."); } } /** {@inheritDoc} */ @Override public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) { try { _dispatcher.execCallbacks(new MetadataChangeCallback(state, key, oldValue, newValue)); } catch (InterruptedException e) { _dispatcher.getLog().warn("onMetadataChange interrupted."); } } @Override public void registerWeakStateListener(JobExecutionStateListener listener) { _dispatcher.addWeakListener(listener); } @Override public void close() throws IOException { _dispatcher.close(); } }
1,463
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/FSSpecStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_store; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.typesafe.config.Config; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.InstrumentedSpecStore; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.api.SpecSerDe; import org.apache.gobblin.util.PathUtils; /** * The Spec Store for file system to persist the Spec information. * Note: * 1. This implementation has no support for caching. * 2. This implementation does not performs implicit version management. * For implicit version management, please use a wrapper FSSpecStore. */ public class FSSpecStore extends InstrumentedSpecStore { /*** * Configuration properties related to Spec Store */ public static final String SPECSTORE_FS_DIR_KEY = "specStore.fs.dir"; protected final Logger log; protected final Config sysConfig; protected final FileSystem fs; protected final String fsSpecStoreDir; protected final Path fsSpecStoreDirPath; protected final SpecSerDe specSerDe; public FSSpecStore(GobblinInstanceEnvironment env, SpecSerDe specSerDe) throws IOException { this(env.getSysConfig().getConfig(), specSerDe, Optional.<Logger>absent()); } public FSSpecStore(Config sysConfig, SpecSerDe specSerDe) throws IOException { this(sysConfig, specSerDe, Optional.<Logger>absent()); } public FSSpecStore(GobblinInstanceEnvironment env, SpecSerDe specSerDe, Optional<Logger> log) throws IOException { this(env.getSysConfig().getConfig(), specSerDe, log); } public FSSpecStore(Config sysConfig, SpecSerDe specSerDe, Optional<Logger> log) throws IOException { super(sysConfig, specSerDe); Preconditions.checkArgument(sysConfig.hasPath(SPECSTORE_FS_DIR_KEY), "FS SpecStore path must be specified."); this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass()); this.sysConfig = sysConfig; this.specSerDe = specSerDe; this.fsSpecStoreDir = this.sysConfig.getString(SPECSTORE_FS_DIR_KEY); this.fsSpecStoreDirPath = new Path(this.fsSpecStoreDir); this.log.info("FSSpecStore directory is: " + this.fsSpecStoreDir); try { this.fs = this.fsSpecStoreDirPath.getFileSystem(new Configuration()); } catch (IOException e) { throw new RuntimeException("Unable to detect job config directory file system: " + e, e); } if (!this.fs.exists(this.fsSpecStoreDirPath)) { this.log.info("FSSpecStore directory: " + this.fsSpecStoreDir + " did not exist. Creating it."); this.fs.mkdirs(this.fsSpecStoreDirPath); } } /** * @param specUri path of the spec * @return empty string for topology spec, as topologies do not have a group, * group name for flow spec */ public static String getSpecGroup(Path specUri) { return specUri.getParent().getName(); } public static String getSpecName(Path specUri) { return Files.getNameWithoutExtension(specUri.getName()); } private Collection<Spec> getAllVersionsOfSpec(Path spec) { Collection<Spec> specs = Lists.newArrayList(); try { specs.add(readSpecFromFile(spec)); } catch (IOException e) { log.warn("Spec {} not found.", spec); } return specs; } /** * Returns all versions of the spec defined by specUri. * Currently, multiple versions are not supported, so this should return exactly one spec. * @param specUri URI for the {@link Spec} to be retrieved. * @return all versions of the spec. */ @Override public Collection<Spec> getAllVersionsOfSpec(URI specUri) { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); Path specPath = getPathForURI(this.fsSpecStoreDirPath, specUri, FlowSpec.Builder.DEFAULT_VERSION); return getAllVersionsOfSpec(specPath); } @Override public boolean existsImpl(URI specUri) throws IOException { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); Path specPath = getPathForURI(this.fsSpecStoreDirPath, specUri, FlowSpec.Builder.DEFAULT_VERSION); return fs.exists(specPath); } @Override public void addSpecImpl(Spec spec) throws IOException { Preconditions.checkArgument(null != spec, "Spec should not be null"); log.info(String.format("Adding Spec with URI: %s in FSSpecStore: %s", spec.getUri(), this.fsSpecStoreDirPath)); Path specPath = getPathForURI(this.fsSpecStoreDirPath, spec.getUri(), spec.getVersion()); writeSpecToFile(specPath, spec); } @Override public boolean deleteSpec(Spec spec) throws IOException { Preconditions.checkArgument(null != spec, "Spec should not be null"); return deleteSpec(spec.getUri(), spec.getVersion()); } @Override public boolean deleteSpecImpl(URI specUri) throws IOException { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); return deleteSpec(specUri, FlowSpec.Builder.DEFAULT_VERSION); } @Override public boolean deleteSpec(URI specUri, String version) throws IOException { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); Preconditions.checkArgument(null != version, "Version should not be null"); try { log.info(String.format("Deleting Spec with URI: %s in FSSpecStore: %s", specUri, this.fsSpecStoreDirPath)); Path specPath = getPathForURI(this.fsSpecStoreDirPath, specUri, version); return fs.delete(specPath, false); } catch (IOException e) { throw new IOException(String.format("Issue in removing Spec: %s for Version: %s", specUri, version), e); } } @Override public Spec updateSpecImpl(Spec spec) throws IOException, SpecNotFoundException { addSpec(spec); return spec; } @Override public Spec getSpecImpl(URI specUri) throws SpecNotFoundException { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); Collection<Spec> specs = getAllVersionsOfSpec(specUri); Spec highestVersionSpec = null; for (Spec spec : specs) { if (null == highestVersionSpec) { highestVersionSpec = spec; } else if (null != spec.getVersion() && spec.getVersion().compareTo(spec.getVersion()) > 0) { highestVersionSpec = spec; } } if (null == highestVersionSpec) { throw new SpecNotFoundException(specUri); } return highestVersionSpec; } @Override public Spec getSpec(URI specUri, String version) throws IOException, SpecNotFoundException { Preconditions.checkArgument(null != specUri, "Spec URI should not be null"); Preconditions.checkArgument(null != version, "Version should not be null"); Path specPath = getPathForURI(this.fsSpecStoreDirPath, specUri, version); if (!fs.exists(specPath)) { throw new SpecNotFoundException(specUri); } return readSpecFromFile(specPath); } @Override public Collection<Spec> getSpecsImpl() throws IOException { Collection<Spec> specs = Lists.newArrayList(); try { getSpecs(this.fsSpecStoreDirPath, specs); } catch (Exception e) { throw new IOException(e); } return specs; } @Override public Iterator<URI> getSpecURIsImpl() throws IOException { final RemoteIterator<LocatedFileStatus> it = fs.listFiles(this.fsSpecStoreDirPath, true); return new Iterator<URI>() { @Override public boolean hasNext() { try { return it.hasNext(); } catch (IOException ioe) { throw new RuntimeException("Failed to determine if there's next element available due to:", ioe); } } @Override public URI next() { try { return getURIFromPath(it.next().getPath(), fsSpecStoreDirPath); } catch (IOException ioe) { throw new RuntimeException("Failed to fetch next element due to:", ioe); } } }; } @Override public Iterator<URI> getSpecURIsWithTagImpl(String tag) throws IOException { throw new UnsupportedOperationException("Loading specs with tag is not supported in FS-Implementation of SpecStore"); } @Override public Optional<URI> getSpecStoreURI() { return Optional.of(this.fsSpecStoreDirPath.toUri()); } /** * For multiple {@link FlowSpec}s to be loaded, catch Exceptions when one of them failed to be loaded and * continue with the rest. * * The {@link IOException} thrown from standard FileSystem call will be propagated, while the file-specific * exception will be caught to ensure other files being able to deserialized. * * @param directory The directory that contains specs to be deserialized * @param specs Container of specs. */ private void getSpecs(Path directory, Collection<Spec> specs) throws Exception { FileStatus[] fileStatuses = fs.listStatus(directory); for (FileStatus fileStatus : fileStatuses) { if (fileStatus.isDirectory()) { getSpecs(fileStatus.getPath(), specs); } else { try { specs.add(readSpecFromFile(fileStatus.getPath())); } catch (Exception e) { log.warn(String.format("Path[%s] cannot be correctly deserialized as Spec", fileStatus.getPath()), e); } } } } /*** * Read and deserialized Spec from a file. * @param path File containing serialized Spec. * @return Spec * @throws IOException */ protected Spec readSpecFromFile(Path path) throws IOException { Spec spec; try (FSDataInputStream fis = fs.open(path)) { spec = this.specSerDe.deserialize(ByteStreams.toByteArray(fis)); } return spec; } /*** * Serialize and write Spec to a file. * @param specPath Spec file name. * @param spec Spec object to write. * @throws IOException */ protected void writeSpecToFile(Path specPath, Spec spec) throws IOException { byte[] serializedSpec = this.specSerDe.serialize(spec); try (FSDataOutputStream os = fs.create(specPath, true)) { os.write(serializedSpec); } } /** * Construct a file path given URI and version of a spec. * * @param fsSpecStoreDirPath The directory path for specs. * @param uri Uri as the identifier of JobSpec * @return */ protected Path getPathForURI(Path fsSpecStoreDirPath, URI uri, String version) { return PathUtils.addExtension(PathUtils.mergePaths(fsSpecStoreDirPath, new Path(uri)), version); } /** * Recover {@link Spec}'s URI from a file path. * Note that there's no version awareness of this method, as Spec's version is currently not supported. * * @param fsPath The given file path to get URI from. * @return The exact URI of a Spec. */ protected URI getURIFromPath(Path fsPath, Path fsSpecStoreDirPath) { return PathUtils.relativizePath(fsPath, fsSpecStoreDirPath).toUri(); } public int getSizeImpl() throws IOException { return getSizeImpl(this.fsSpecStoreDirPath); } @Override public Collection<Spec> getSpecsPaginatedImpl(int startOffset, int batchSize) throws IOException { if (startOffset < 0 || batchSize < 0) { throw new IllegalArgumentException(String.format("Received negative offset or batch size value when they should be >= 0. " + "Offset is %s and batch size is %s", startOffset, batchSize)); } // Obtain sorted list of spec uris to paginate from Iterator<URI> uriIterator = getSpecURIsImpl(); List<URI> sortedUris = new ArrayList<>(); while (uriIterator.hasNext()) { sortedUris.add(uriIterator.next()); } sortedUris.sort(URI::compareTo); int numElements = 0; List<Spec> batchOfSpecs = new ArrayList<>(); URI currentURI; while (startOffset + numElements < sortedUris.size() && numElements < batchSize) { currentURI = sortedUris.get(startOffset + numElements); try { batchOfSpecs.add(getSpecImpl(currentURI)); } catch (SpecNotFoundException e) { log.warn("Unable to find spec for uri {} so proceeding to next URI. Stacktrace {}", currentURI, e); continue; } numElements += 1; } return batchOfSpecs; } private int getSizeImpl(Path directory) throws IOException { int specs = 0; FileStatus[] fileStatuses = fs.listStatus(directory); for (FileStatus fileStatus : fileStatuses) { if (fileStatus.isDirectory()) { specs += getSizeImpl(fileStatus.getPath()); } else { specs++; } } return specs; } }
1,464
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/MysqlBaseSpecStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_store; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import com.typesafe.config.Config; import com.zaxxer.hikari.HikariDataSource; import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.broker.SharedResourcesBrokerFactory; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metastore.MysqlDataSourceFactory; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.InstrumentedSpecStore; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.api.SpecSerDe; import org.apache.gobblin.runtime.api.SpecSerDeException; import org.apache.gobblin.runtime.api.SpecStore; /** * Implementation of {@link SpecStore} that stores specs in MySQL as a serialized BLOB, per the provided {@link SpecSerDe}. * Note: versions are unsupported, so the version parameter is ignored in methods that have it. * * A tag column is added into implementation to serve certain filtering purposes in MySQL-based SpecStore. * For example, in DR mode of GaaS, we would only want certain {@link Spec}s to be eligible for orchestrated * by alternative GaaS instances. Another example is allow-listing/deny-listing {@link Spec}s temporarily * but not removing it from {@link SpecStore}. * * The {@link MysqlSpecStore} is a specialization enhanced for {@link FlowSpec} search and retrieval. */ @Slf4j public class MysqlBaseSpecStore extends InstrumentedSpecStore { /** `j.u.Function` variant for an operation that may @throw IOException or SQLException: preserves method signature checked exceptions */ @FunctionalInterface protected interface CheckedFunction<T, R> { R apply(T t) throws IOException, SQLException; } public static final String CONFIG_PREFIX = "mysqlBaseSpecStore"; public static final String DEFAULT_TAG_VALUE = ""; private static final String EXISTS_STATEMENT = "SELECT EXISTS(SELECT * FROM %s WHERE spec_uri = ?)"; protected static final String INSERT_STATEMENT = "INSERT INTO %s (spec_uri, tag, spec) " + "VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE spec = VALUES(spec)"; // Keep previous syntax that update only update spec and spec_json //todo: do we need change this behavior so that everything can be updated protected static final String UPDATE_STATEMENT = "UPDATE %s SET spec=?,spec_json=? WHERE spec_uri=? AND UNIX_TIMESTAMP(modified_time) < ?"; private static final String DELETE_STATEMENT = "DELETE FROM %s WHERE spec_uri = ?"; private static final String GET_STATEMENT_BASE = "SELECT spec_uri, spec FROM %s WHERE "; private static final String GET_ALL_STATEMENT = "SELECT spec_uri, spec, modified_time FROM %s"; private static final String GET_ALL_URIS_STATEMENT = "SELECT spec_uri FROM %s"; private static final String GET_ALL_URIS_WITH_TAG_STATEMENT = "SELECT spec_uri FROM %s WHERE tag = ?"; private static final String GET_SPECS_BATCH_STATEMENT = "SELECT spec_uri, spec, modified_time FROM %s ORDER BY spec_uri ASC LIMIT ? OFFSET ?"; private static final String GET_SIZE_STATEMENT = "SELECT COUNT(*) FROM %s "; // NOTE: using max length of a `FlowSpec` URI, as it's believed to be the longest of existing `Spec` types private static final String CREATE_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS %s (spec_uri VARCHAR(" + FlowSpec.Utils.maxFlowSpecUriLength() + ") NOT NULL, tag VARCHAR(128) NOT NULL, modified_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE " + "CURRENT_TIMESTAMP, spec LONGBLOB, PRIMARY KEY (spec_uri))"; /** * The main point of difference with base classes is the DB schema and hence certain of the DML and queries. Given the interrelation * between statements, collect them within this inner class that enables selective, per-statement override, and delivers them as a unit. */ protected class SqlStatements { public final String updateStatement = String.format(getTablelessUpdateStatement(), MysqlBaseSpecStore.this.tableName); public final String existsStatement = String.format(getTablelessExistsStatement(), MysqlBaseSpecStore.this.tableName); public final String insertStatement = String.format(getTablelessInsertStatement(), MysqlBaseSpecStore.this.tableName); public final String deleteStatement = String.format(getTablelessDeleteStatement(), MysqlBaseSpecStore.this.tableName); public final String getStatementBase = String.format(getTablelessGetStatementBase(), MysqlBaseSpecStore.this.tableName); public final String getAllStatement = String.format(getTablelessGetAllStatement(), MysqlBaseSpecStore.this.tableName); public final String getAllURIsStatement = String.format(getTablelessGetAllURIsStatement(), MysqlBaseSpecStore.this.tableName); public final String getAllURIsWithTagStatement = String.format(getTablelessGetAllURIsWithTagStatement(), MysqlBaseSpecStore.this.tableName); public final String getBatchStatement = String.format(getTablelessGetBatchStatement(), MysqlBaseSpecStore.this.tableName); public final String getSizeStatement = String.format(getTablelessGetSizeStatement(), MysqlBaseSpecStore.this.tableName); public final String createTableStatement = String.format(getTablelessCreateTableStatement(), MysqlBaseSpecStore.this.tableName); public void completeInsertPreparedStatement(PreparedStatement statement, Spec spec, String tagValue) throws SQLException { URI specUri = spec.getUri(); int i = 0; statement.setString(++i, specUri.toString()); statement.setString(++i, tagValue); statement.setBlob(++i, new ByteArrayInputStream(MysqlBaseSpecStore.this.specSerDe.serialize(spec))); } public Spec extractSpec(ResultSet rs) throws SQLException, IOException { return MysqlBaseSpecStore.this.specSerDe.deserialize(ByteStreams.toByteArray(rs.getBlob(2).getBinaryStream())); } public Spec extractSpecWithModificationTime(ResultSet rs) throws SQLException, IOException { Spec spec = MysqlBaseSpecStore.this.specSerDe.deserialize(ByteStreams.toByteArray(rs.getBlob(2).getBinaryStream())); // Set modified timestamp in flowSpec properties list if (spec instanceof FlowSpec) { long timestamp = rs.getTimestamp(FlowSpec.MODIFICATION_TIME_KEY).getTime(); FlowSpec flowSpec = (FlowSpec) spec; Properties properties = flowSpec.getConfigAsProperties(); properties.setProperty(FlowSpec.MODIFICATION_TIME_KEY, String.valueOf(timestamp)); return flowSpec; } return spec; } public void completeGetBatchStatement(PreparedStatement statement, int startOffset, int batchSize) throws SQLException { int i = 0; statement.setInt(++i, batchSize); statement.setInt(++i, startOffset); } protected String getTablelessExistsStatement() { return MysqlBaseSpecStore.EXISTS_STATEMENT; } protected String getTablelessUpdateStatement() { return MysqlBaseSpecStore.UPDATE_STATEMENT; } protected String getTablelessInsertStatement() { return MysqlBaseSpecStore.INSERT_STATEMENT; } protected String getTablelessDeleteStatement() { return MysqlBaseSpecStore.DELETE_STATEMENT; } protected String getTablelessGetStatementBase() { return MysqlBaseSpecStore.GET_STATEMENT_BASE; } protected String getTablelessGetAllStatement() { return MysqlBaseSpecStore.GET_ALL_STATEMENT; } protected String getTablelessGetAllURIsStatement() { return MysqlBaseSpecStore.GET_ALL_URIS_STATEMENT; } protected String getTablelessGetAllURIsWithTagStatement() { return MysqlBaseSpecStore.GET_ALL_URIS_WITH_TAG_STATEMENT; } protected String getTablelessGetBatchStatement() {return MysqlBaseSpecStore.GET_SPECS_BATCH_STATEMENT; } protected String getTablelessGetSizeStatement() { return MysqlBaseSpecStore.GET_SIZE_STATEMENT; } protected String getTablelessCreateTableStatement() { return MysqlBaseSpecStore.CREATE_TABLE_STATEMENT; } } protected final DataSource dataSource; protected final String tableName; private final URI specStoreURI; protected final SpecSerDe specSerDe; protected final SqlStatements sqlStatements; public MysqlBaseSpecStore(Config config, SpecSerDe specSerDe) throws IOException { super(config, specSerDe); String configPrefix = getConfigPrefix(); if (config.hasPath(configPrefix)) { config = config.getConfig(configPrefix).withFallback(config); } this.dataSource = MysqlDataSourceFactory.get(config, SharedResourcesBrokerFactory.getImplicitBroker()); this.tableName = config.getString(ConfigurationKeys.STATE_STORE_DB_TABLE_KEY); this.specStoreURI = URI.create(config.getString(ConfigurationKeys.STATE_STORE_DB_URL_KEY)); this.specSerDe = specSerDe; this.sqlStatements = createSqlStatements(); withPreparedStatement(this.sqlStatements.createTableStatement, statement -> statement.executeUpdate() ); } protected String getConfigPrefix() { return MysqlBaseSpecStore.CONFIG_PREFIX; } protected SqlStatements createSqlStatements() { return new SqlStatements(); } @Override public boolean existsImpl(URI specUri) throws IOException { return withPreparedStatement(this.sqlStatements.existsStatement, statement -> { statement.setString(1, specUri.toString()); try (ResultSet rs = statement.executeQuery()) { rs.next(); return rs.getBoolean(1); } }); } @Override public void addSpecImpl(Spec spec) throws IOException { this.addSpec(spec, DEFAULT_TAG_VALUE); } /** * Temporarily only used for testing since tag it not exposed in endpoint of {@link org.apache.gobblin.runtime.api.FlowSpec} */ public void addSpec(Spec spec, String tagValue) throws IOException { withPreparedStatement(this.sqlStatements.insertStatement, statement -> { this.sqlStatements.completeInsertPreparedStatement(statement, spec, tagValue); statement.executeUpdate(); return null; // (type: `Void`) }, true); } @Override public boolean deleteSpec(Spec spec) throws IOException { return deleteSpec(spec.getUri()); } @Override public boolean deleteSpecImpl(URI specUri) throws IOException { return withPreparedStatement(this.sqlStatements.deleteStatement, statement -> { statement.setString(1, specUri.toString()); int result = statement.executeUpdate(); return result != 0; }, true); } @Override public boolean deleteSpec(URI specUri, String version) throws IOException { return deleteSpec(specUri); } @Override // TODO: fix to obey the `SpecStore` contract of returning the *updated* `Spec` public Spec updateSpecImpl(Spec spec) throws IOException { addSpec(spec); return spec; } @Override public Spec getSpecImpl(URI specUri) throws IOException, SpecNotFoundException { Iterator<Spec> resultSpecs = withPreparedStatement(this.sqlStatements.getAllStatement + " WHERE spec_uri = ?", statement -> { statement.setString(1, specUri.toString()); return retrieveSpecsWithModificationTime(statement).iterator(); }); if (resultSpecs.hasNext()) { return resultSpecs.next(); } else { throw new SpecNotFoundException(specUri); } } @Override public Spec getSpec(URI specUri, String version) throws IOException, SpecNotFoundException { return getSpec(specUri); // `version` ignored, as mentioned in javadoc } @Override public Collection<Spec> getAllVersionsOfSpec(URI specUri) throws IOException, SpecNotFoundException { return Lists.newArrayList(getSpec(specUri)); } @Override public Collection<Spec> getSpecsImpl() throws IOException { return withPreparedStatement(this.sqlStatements.getAllStatement, statement -> { return retrieveSpecs(statement); }); } protected final Collection<Spec> retrieveSpecs(PreparedStatement statement) throws IOException { List<Spec> specs = new ArrayList<>(); try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { specs.add(this.sqlStatements.extractSpec(rs)); } } catch (SQLException | SpecSerDeException e) { log.error("Failed to deserialize spec", e); throw new IOException(e); } return specs; } protected final Collection<Spec> retrieveSpecsWithModificationTime(PreparedStatement statement) throws IOException { List<Spec> specs = new ArrayList<>(); try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { specs.add(this.sqlStatements.extractSpecWithModificationTime(rs)); } } catch (SQLException | SpecSerDeException e) { log.error("Failed to deserialize spec", e); throw new IOException(e); } return specs; } @Override public Iterator<URI> getSpecURIsImpl() throws IOException { return withPreparedStatement(this.sqlStatements.getAllURIsStatement, statement -> { return retrieveURIs(statement).iterator(); }); } @Override public int getSizeImpl() throws IOException { return withPreparedStatement(this.sqlStatements.getSizeStatement, statement -> { try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); return resultSet.getInt(1); } }); } @Override public Collection<Spec> getSpecsPaginatedImpl(int startOffset, int batchSize) throws IOException, IllegalArgumentException { if (startOffset < 0 || batchSize < 0) { throw new IllegalArgumentException(String.format("Received negative offset or batch size value when they should be >= 0. " + "Offset is %s and batch size is %s", startOffset, batchSize)); } return withPreparedStatement(this.sqlStatements.getBatchStatement, statement -> { this.sqlStatements.completeGetBatchStatement(statement, startOffset, batchSize); return retrieveSpecsWithModificationTime(statement); }); } @Override public Iterator<URI> getSpecURIsWithTagImpl(String tag) throws IOException { return withPreparedStatement(this.sqlStatements.getAllURIsWithTagStatement, statement -> { statement.setString(1, tag); return retrieveURIs(statement).iterator(); }); } private List<URI> retrieveURIs(PreparedStatement statement) throws SQLException { List<URI> uris = new ArrayList<>(); try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { URI specURI = URI.create(rs.getString(1)); uris.add(specURI); } } return uris; } @Override public Optional<URI> getSpecStoreURI() { return Optional.of(this.specStoreURI); } // TODO: migrate this class to use common util {@link DBStatementExecutor} /** Abstracts recurring pattern around resource management and exception re-mapping. */ protected <T> T withPreparedStatement(String sql, CheckedFunction<PreparedStatement, T> f, boolean shouldCommit) throws IOException { try (Connection connection = this.dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { T result = f.apply(statement); if (shouldCommit) { connection.commit(); } return result; } catch (SQLException e) { // TODO: revisit use of connection test query following verification of successful connection pool migration: // If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers // that do not support the JDBC4 Connection.isValid() API; see: // https://github.com/brettwooldridge/HikariCP#gear-configuration-knobs-baby log.warn("Received SQL exception that can result from invalid connection. Checking if validation query is set {} Exception is {}", ((HikariDataSource) this.dataSource).getConnectionTestQuery(), e); throw new IOException(e); } } /** Abstracts recurring pattern, while not presuming to DB `commit()`. */ protected final <T> T withPreparedStatement(String sql, CheckedFunction<PreparedStatement, T> f) throws IOException { return withPreparedStatement(sql, f, false); } }
1,465
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/MysqlSpecStoreWithUpdate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_store; import com.google.common.base.Charsets; import com.typesafe.config.Config; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecSerDe; public class MysqlSpecStoreWithUpdate extends MysqlSpecStore{ // In this case, when we try to insert but key is existed, we will throw exception protected static final String INSERT_STATEMENT_WITHOUT_UPDATE = "INSERT INTO %s (spec_uri, flow_group, flow_name, template_uri, " + "user_to_proxy, source_identifier, destination_identifier, schedule, tag, isRunImmediately, owning_group, spec, spec_json) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; public MysqlSpecStoreWithUpdate(Config config, SpecSerDe specSerDe) throws IOException { super(config, specSerDe); } /** Bundle all changes following from schema differences against the base class. */ protected class SpecificSqlStatementsWithUpdate extends SpecificSqlStatements { public void completeUpdatePreparedStatement(PreparedStatement statement, Spec spec, long modifiedWatermark) throws SQLException { FlowSpec flowSpec = (FlowSpec) spec; URI specUri = flowSpec.getUri(); int i = 0; statement.setBlob(++i, new ByteArrayInputStream(MysqlSpecStoreWithUpdate.this.specSerDe.serialize(flowSpec))); statement.setString(++i, new String(MysqlSpecStoreWithUpdate.this.specSerDe.serialize(flowSpec), Charsets.UTF_8)); statement.setString(++i, specUri.toString()); statement.setLong(++i, modifiedWatermark); } @Override protected String getTablelessInsertStatement() { return INSERT_STATEMENT_WITHOUT_UPDATE; } } @Override protected SqlStatements createSqlStatements() { return new SpecificSqlStatementsWithUpdate(); } @Override // TODO: fix to obey the `SpecStore` contract of returning the *updated* `Spec` public Spec updateSpecImpl(Spec spec) throws IOException { updateSpecImpl(spec, Long.MAX_VALUE); return spec; } @Override // TODO: fix to obey the `SpecStore` contract of returning the *updated* `Spec` // Update {@link Spec} in the {@link SpecStore} when current modification time is smaller than {@link modifiedWatermark}. public Spec updateSpecImpl(Spec spec, long modifiedWatermark) throws IOException { withPreparedStatement(this.sqlStatements.updateStatement, statement -> { ((SpecificSqlStatementsWithUpdate)this.sqlStatements).completeUpdatePreparedStatement(statement, spec, modifiedWatermark); int i = statement.executeUpdate(); if (i == 0) { throw new IOException("Spec does not exist or concurrent update happens, please check current spec and update again"); } return null; // (type: `Void`) }, true); return spec; } }
1,466
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/MysqlSpecStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.spec_store; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.Properties; import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import com.typesafe.config.Config; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecSearchObject; import org.apache.gobblin.runtime.api.SpecSerDe; import org.apache.gobblin.runtime.api.SpecStore; import org.apache.gobblin.service.ServiceConfigKeys; import org.apache.gobblin.util.ConfigUtils; import static org.apache.gobblin.service.ServiceConfigKeys.FLOW_DESTINATION_IDENTIFIER_KEY; import static org.apache.gobblin.service.ServiceConfigKeys.FLOW_SOURCE_IDENTIFIER_KEY; /** * Implementation of {@link SpecStore} that stores specs in MySQL both as a serialized BLOB and as a JSON string, and extends * {@link MysqlBaseSpecStore} with enhanced FlowSpec search/retrieval capabilities. The {@link SpecSerDe}'s serialized output * is presumed suitable for a MySql `JSON` column. As in the base, versions are unsupported and ignored. * * ETYMOLOGY: this class might better be named `MysqlFlowSpecStore` while the base be `MysqlSpecStore`, but the `MysqlSpecStore` name's * association with this class's semantics predates the refactoring/generalization into `MysqlBaseSpecStore`. Thus, to maintain * b/w-compatibility and avoid surprising legacy users who already refer to it (e.g. by name, in configuration), that original name remains intact. */ @Slf4j public class MysqlSpecStore extends MysqlBaseSpecStore { public static final String CONFIG_PREFIX = "mysqlSpecStore"; // Historical Note: the `spec_json` column didn't always exist and was introduced for GOBBLIN-1150; the impl. thus allows that not every // record may contain data there... though in practice, all should, given the passage of time (amidst the usual retention expiry). protected static final String SPECIFIC_INSERT_STATEMENT = "INSERT INTO %s (spec_uri, flow_group, flow_name, template_uri, " + "user_to_proxy, source_identifier, destination_identifier, schedule, tag, isRunImmediately, owning_group, spec, spec_json) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE spec = VALUES(spec), spec_json = VALUES(spec_json)"; private static final String SPECIFIC_GET_STATEMENT_BASE = "SELECT spec_uri, spec, spec_json FROM %s WHERE "; private static final String SPECIFIC_GET_ALL_STATEMENT = "SELECT spec_uri, spec, spec_json, modified_time FROM %s"; private static final String SPECIFIC_GET_SPECS_BATCH_STATEMENT = "SELECT spec_uri, spec, spec_json, modified_time FROM %s ORDER BY spec_uri ASC LIMIT ? OFFSET ?"; private static final String SPECIFIC_CREATE_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS %s (spec_uri VARCHAR(" + FlowSpec.Utils.maxFlowSpecUriLength() + ") NOT NULL, flow_group VARCHAR(" + ServiceConfigKeys.MAX_FLOW_GROUP_LENGTH + "), flow_name VARCHAR(" + ServiceConfigKeys.MAX_FLOW_GROUP_LENGTH + "), " + "template_uri VARCHAR(128), user_to_proxy VARCHAR(128), " + "source_identifier VARCHAR(128), " + "destination_identifier VARCHAR(128), schedule VARCHAR(128), " + "tag VARCHAR(128) NOT NULL, modified_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE " + "CURRENT_TIMESTAMP, isRunImmediately BOOLEAN, timezone VARCHAR(128), owning_group VARCHAR(128), spec LONGBLOB, " + "spec_json JSON, PRIMARY KEY (spec_uri))"; /** Bundle all changes following from schema differences against the base class. */ protected class SpecificSqlStatements extends SqlStatements { @Override public void completeInsertPreparedStatement(PreparedStatement statement, Spec spec, String tagValue) throws SQLException { FlowSpec flowSpec = (FlowSpec) spec; URI specUri = flowSpec.getUri(); Config flowConfig = flowSpec.getConfig(); String flowGroup = flowConfig.getString(ConfigurationKeys.FLOW_GROUP_KEY); String flowName = flowConfig.getString(ConfigurationKeys.FLOW_NAME_KEY); String templateURI = new Gson().toJson(flowSpec.getTemplateURIs()); String userToProxy = ConfigUtils.getString(flowSpec.getConfig(), "user.to.proxy", null); String sourceIdentifier = flowConfig.getString(FLOW_SOURCE_IDENTIFIER_KEY); String destinationIdentifier = flowConfig.getString(FLOW_DESTINATION_IDENTIFIER_KEY); String schedule = ConfigUtils.getString(flowConfig, ConfigurationKeys.JOB_SCHEDULE_KEY, null); String owningGroup = ConfigUtils.getString(flowConfig, ConfigurationKeys.FLOW_OWNING_GROUP_KEY, null); boolean isRunImmediately = ConfigUtils.getBoolean(flowConfig, ConfigurationKeys.FLOW_RUN_IMMEDIATELY, false); int i = 0; statement.setString(++i, specUri.toString()); statement.setString(++i, flowGroup); statement.setString(++i, flowName); statement.setString(++i, templateURI); statement.setString(++i, userToProxy); statement.setString(++i, sourceIdentifier); statement.setString(++i, destinationIdentifier); statement.setString(++i, schedule); statement.setString(++i, tagValue); statement.setBoolean(++i, isRunImmediately); statement.setString(++i, owningGroup); statement.setBlob(++i, new ByteArrayInputStream(MysqlSpecStore.this.specSerDe.serialize(flowSpec))); statement.setString(++i, new String(MysqlSpecStore.this.specSerDe.serialize(flowSpec), Charsets.UTF_8)); } @Override public Spec extractSpec(ResultSet rs) throws SQLException, IOException { return rs.getString(3) == null ? MysqlSpecStore.this.specSerDe.deserialize(ByteStreams.toByteArray(rs.getBlob(2).getBinaryStream())) : MysqlSpecStore.this.specSerDe.deserialize(rs.getString(3).getBytes(Charsets.UTF_8)); } @Override public Spec extractSpecWithModificationTime(ResultSet rs) throws SQLException, IOException { Spec spec = rs.getString(3) == null ? MysqlSpecStore.this.specSerDe.deserialize(ByteStreams.toByteArray(rs.getBlob(2).getBinaryStream())) : MysqlSpecStore.this.specSerDe.deserialize(rs.getString(3).getBytes(Charsets.UTF_8)); // Set modified timestamp in flowSpec properties list if (spec instanceof FlowSpec) { long timestamp = rs.getTimestamp(FlowSpec.MODIFICATION_TIME_KEY).getTime(); FlowSpec flowSpec = (FlowSpec) spec; Properties properties = flowSpec.getConfigAsProperties(); properties.setProperty(FlowSpec.MODIFICATION_TIME_KEY, String.valueOf(timestamp)); return flowSpec; } return spec; } @Override protected String getTablelessInsertStatement() { return MysqlSpecStore.SPECIFIC_INSERT_STATEMENT; } @Override protected String getTablelessGetStatementBase() { return MysqlSpecStore.SPECIFIC_GET_STATEMENT_BASE; } @Override protected String getTablelessGetAllStatement() { return MysqlSpecStore.SPECIFIC_GET_ALL_STATEMENT; } @Override protected String getTablelessGetBatchStatement() { return MysqlSpecStore.SPECIFIC_GET_SPECS_BATCH_STATEMENT; } @Override protected String getTablelessCreateTableStatement() { return MysqlSpecStore.SPECIFIC_CREATE_TABLE_STATEMENT; } } public MysqlSpecStore(Config config, SpecSerDe specSerDe) throws IOException { super(config, specSerDe); } @Override protected String getConfigPrefix() { return MysqlSpecStore.CONFIG_PREFIX; } @Override protected SqlStatements createSqlStatements() { return new SpecificSqlStatements(); } /** Support search, unlike base class (presumably via a {@link org.apache.gobblin.runtime.api.FlowSpecSearchObject}). */ @Override public Collection<Spec> getSpecsImpl(SpecSearchObject specSearchObject) throws IOException { return withPreparedStatement(specSearchObject.augmentBaseGetStatement(this.sqlStatements.getStatementBase), statement -> { specSearchObject.completePreparedStatement(statement); return retrieveSpecs(statement); }); } }
1,467
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/CliEmbeddedGobblin.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.apache.commons.cli.CommandLine; import com.google.common.base.Strings; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.runtime.embedded.EmbeddedGobblin; import org.apache.gobblin.util.ClassAliasResolver; import lombok.extern.slf4j.Slf4j; /** * A {@link CliApplication} that runs a Gobblin flow using {@link EmbeddedGobblin}. * * Usage: * java -jar gobblin.jar run [app] [OPTIONS] * * The cli can run arbitrary applications by either setting each configuration manually (using the -setConfiguration * option), or with the help of a template (using the -setTemplate option). However, since this requires knowing * the exact configurations needed for a job, developers can implement more specific applications with simpler options * for the user. * * {@link CliEmbeddedGobblin} will create an {@link EmbeddedGobblin} using a {@link EmbeddedGobblinCliFactory} * found by class name or {@link Alias}. It will * parse command line arguments using the options obtained from {@link EmbeddedGobblinCliFactory#getOptions()}, then * instantiate {@link EmbeddedGobblin} using {@link EmbeddedGobblinCliFactory#buildObject(CommandLine)}, and * finally run the application synchronously. */ @Alias(value = "run", description = "Run a Gobblin application.") @Slf4j public class CliEmbeddedGobblin implements CliApplication { public static final String LIST_QUICK_APPS = "listQuickApps"; @Override public void run(String[] args) throws IOException { int startOptions = 1; Class<? extends EmbeddedGobblinCliFactory> factoryClass; String alias = ""; if (args.length >= 2 && !args[1].startsWith("-")) { alias = args[1]; startOptions = 2; } if (alias.equals(LIST_QUICK_APPS)) { listQuickApps(); return; } EmbeddedGobblinCliFactory factory; if (!Strings.isNullOrEmpty(alias)) { try { ClassAliasResolver<EmbeddedGobblinCliFactory> resolver = new ClassAliasResolver<>(EmbeddedGobblinCliFactory.class); factoryClass = resolver.resolveClass(alias); factory = factoryClass.newInstance(); } catch (ReflectiveOperationException roe) { System.out.println("Error: Could not find job with alias " + alias); System.out.println("For a list of jobs available: \"gobblin run " + LIST_QUICK_APPS + "\""); return; } } else { factory = new EmbeddedGobblin.CliFactory(); } String usage; if (Strings.isNullOrEmpty(alias)) { usage = "gobblin run [listQuickApps] [<quick-app>] " + factory.getUsageString(); } else { usage = "gobblin run " + alias + " " + factory.getUsageString(); } EmbeddedGobblin embeddedGobblin = factory.buildObject(args, startOptions, true, usage); try { embeddedGobblin.run(); } catch (InterruptedException | TimeoutException | ExecutionException exc) { throw new RuntimeException("Failed to run Gobblin job.", exc); } } private List<Alias> getAllAliases() { ClassAliasResolver<EmbeddedGobblinCliFactory> resolver = new ClassAliasResolver<>(EmbeddedGobblinCliFactory.class); return resolver.getAliasObjects(); } private void listQuickApps() { List<Alias> aliases = getAllAliases(); System.out.println("Usage: gobblin cli run <quick-app-name> [OPTIONS]"); System.out.println("Available quick apps:"); for (Alias thisAlias : aliases) { System.out.println(String.format("\t%s\t-\t%s", thisAlias.value(), thisAlias.description())); } } }
1,468
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/CliOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import java.io.IOException; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration.ConfigurationException; import org.apache.gobblin.util.JobConfigurationUtils; /** * Utility class for parsing command line options for Gobblin cli jobs. */ public class CliOptions { public final static Option SYS_CONFIG_OPTION = Option.builder().argName("system configuration file") .desc("Gobblin system configuration file").hasArgs().longOpt("sysconfig").build(); public final static Option JOB_CONFIG_OPTION = Option.builder().argName("job configuration file") .desc("Gobblin job configuration file").hasArgs().longOpt("jobconfig").build(); public final static Option HELP_OPTION = Option.builder("h").argName("help").desc("Display usage information").longOpt("help").build(); /** * Parse command line arguments and return a {@link java.util.Properties} object for the gobblin job found. * @param caller Class of the calling main method. Used for error logs. * @param args Command line arguments. * @return Instance of {@link Properties} for the Gobblin job to run. * @throws IOException */ public static Properties parseArgs(Class<?> caller, String[] args) throws IOException { try { // Parse command-line options CommandLine cmd = new DefaultParser().parse(options(), args); if (cmd.hasOption(HELP_OPTION.getOpt())) { printUsage(caller); System.exit(0); } if (!cmd.hasOption(SYS_CONFIG_OPTION.getLongOpt()) || !cmd.hasOption(JOB_CONFIG_OPTION.getLongOpt())) { printUsage(caller); System.exit(1); } // Load system and job configuration properties Properties sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(SYS_CONFIG_OPTION.getLongOpt())); Properties jobConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(JOB_CONFIG_OPTION.getLongOpt())); return JobConfigurationUtils.combineSysAndJobProperties(sysConfig, jobConfig); } catch (ParseException | ConfigurationException e) { throw new IOException(e); } } /** * Prints the usage of cli. * @param caller Class of the main method called. Used in printing the usage message. */ public static void printUsage(Class<?> caller) { new HelpFormatter().printHelp(caller.getSimpleName(), options()); } private static Options options() { Options options = new Options(); options.addOption(SYS_CONFIG_OPTION); options.addOption(JOB_CONFIG_OPTION); options.addOption(HELP_OPTION); return options; } }
1,469
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/ConstructorAndPublicMethodsGobblinCliFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import org.apache.commons.cli.Option; import org.apache.gobblin.runtime.embedded.EmbeddedGobblin; /** * A helper class for automatically inferring {@link Option}s from the constructor and public methods in a class. * * For method inference, see {@link PublicMethodsGobblinCliFactory}. * * {@link Option}s are inferred from the constructor as follows: * 1. The helper will search for exactly one constructor with only String arguments and which is annotated with * {@link CliObjectSupport}. * 2. For each parameter of the constructor, the helper will create a required {@link Option}. * * For an example usage see {@link EmbeddedGobblin.CliFactory}. */ public abstract class ConstructorAndPublicMethodsGobblinCliFactory extends ConstructorAndPublicMethodsCliObjectFactory<EmbeddedGobblin> implements EmbeddedGobblinCliFactory { public ConstructorAndPublicMethodsGobblinCliFactory(Class<? extends EmbeddedGobblin> klazz) { super(klazz); } }
1,470
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/PublicMethodsGobblinCliFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import java.io.IOException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.embedded.EmbeddedGobblin; /** * A helper class for automatically inferring {@link Option}s from the public methods in a class. * * For each public method in the class to infer with exactly zero or one String parameter, the helper will create * an optional {@link Option}. Using the annotation {@link CliObjectOption} the helper can automatically * add a description to the {@link Option}. Annotating a method with {@link NotOnCli} will prevent the helper from * creating an {@link Option} from it. * * For an example usage see {@link EmbeddedGobblin.CliFactory} */ public abstract class PublicMethodsGobblinCliFactory extends PublicMethodsCliObjectFactory<EmbeddedGobblin> implements EmbeddedGobblinCliFactory{ public PublicMethodsGobblinCliFactory(Class<? extends EmbeddedGobblin> klazz) { super(klazz); } @Override public EmbeddedGobblin constructObject(CommandLine cli) throws IOException { try { return constructEmbeddedGobblin(cli); } catch (JobTemplate.TemplateException exc) { throw new IOException(exc); } } public abstract EmbeddedGobblin constructEmbeddedGobblin(CommandLine cli) throws JobTemplate.TemplateException, IOException; }
1,471
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/JobStateStoreCLI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.typesafe.config.Config; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metastore.FsStateStoreFactory; import org.apache.gobblin.metastore.StateStore; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.util.JobStateToJsonConverter; import org.apache.gobblin.util.ClassAliasResolver; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.JobConfigurationUtils; @Slf4j @Alias(value = "job-state-store", description = "View or delete JobState in state store") public class JobStateStoreCLI implements CliApplication { Option sysConfigOption = Option.builder("sc").argName("system configuration file") .desc("Gobblin system configuration file (required if no state store URL specified)").longOpt("sysconfig").hasArg().build(); Option storeUrlOption = Option.builder("u").argName("gobblin state store URL") .desc("Gobblin state store root path URL (required if no sysconfig specified)").longOpt("storeurl").hasArg().build(); Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name").longOpt("name") .hasArg().build(); Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id").hasArg().build(); Option helpOption = Option.builder("h").argName("help").desc("Usage").longOpt("help").hasArg().build(); Option deleteOption = Option.builder("d").argName("delete state").desc("Deletes a state from the state store with a job id") .longOpt("delete").build(); Option bulkDeleteOption = Option.builder("bd").argName("bulk delete") .desc("Deletes states from the state store based on a file with job ids to delete, separated by newline") .longOpt("bulkDelete").hasArg().build(); // For reading state store in json format Option getAsJsonOption = Option.builder("r").argName("read job state").desc("Converts a job state to json").longOpt("read-job-state").build(); Option convertAllOption = Option.builder("a").desc("Whether to convert all past job states of the given job when viewing as json").longOpt("all").build(); Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties when viewing as json").longOpt("keepConfig").build(); Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name when viewing as json").longOpt("toFile").hasArg().build(); private static final Logger LOGGER = LoggerFactory.getLogger(JobStateStoreCLI.class); private StateStore<? extends JobState> jobStateStore; CommandLine initializeOptions(String[] args) { Options options = new Options(); options.addOption(sysConfigOption); options.addOption(storeUrlOption); options.addOption(jobNameOption); options.addOption(jobIdOption); options.addOption(deleteOption); options.addOption(getAsJsonOption); options.addOption(convertAllOption); options.addOption(keepConfigOption); options.addOption(outputToFile); options.addOption(bulkDeleteOption); CommandLine cmd = null; try { CommandLineParser parser = new DefaultParser(); cmd = parser.parse(options, Arrays.copyOfRange(args, 1, args.length)); } catch (ParseException pe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateStoreCLI", options); throw new RuntimeException(pe); } if (!cmd.hasOption(sysConfigOption.getLongOpt()) && !cmd.hasOption(storeUrlOption.getLongOpt()) ){ System.out.println("State store configuration or state store url options missing"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateStoreCLI", options); return null; } if (cmd.hasOption(getAsJsonOption.getOpt()) && !cmd.hasOption(jobNameOption.getOpt())) { System.out.println("Job name option missing for reading job states as json"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateStoreCLI", options); return null; } if (cmd.hasOption(deleteOption.getOpt()) && !cmd.hasOption(jobNameOption.getOpt())) { System.out.println("Job name option missing for delete job id"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateStoreCLI", options); return null; } if (cmd.hasOption(helpOption.getOpt())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JobStateStoreCLI", options); return null; } return cmd; } @Override public void run(String[] args) throws Exception { CommandLine cmd = initializeOptions(args); if (cmd == null) { return; // incorrect args were called } Properties props = new Properties(); if (cmd.hasOption(sysConfigOption.getOpt())) { props = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getOpt())); } String storeUrl = cmd.getOptionValue(storeUrlOption.getLongOpt()); if (StringUtils.isNotBlank(storeUrl)) { props.setProperty(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, storeUrl); } Config stateStoreConfig = ConfigUtils.propertiesToConfig(props); ClassAliasResolver<StateStore.Factory> resolver = new ClassAliasResolver<>(StateStore.Factory.class); StateStore.Factory stateStoreFactory; try { stateStoreFactory = resolver.resolveClass(ConfigUtils.getString(stateStoreConfig, ConfigurationKeys.STATE_STORE_TYPE_KEY, FsStateStoreFactory.class.getName())).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } this.jobStateStore = stateStoreFactory.createStateStore(stateStoreConfig, JobState.class); if (cmd.hasOption(getAsJsonOption.getOpt())) { this.viewStateAsJson(cmd); } else if (cmd.hasOption(bulkDeleteOption.getOpt())) { this.deleteJobBulk(cmd.getOptionValue(bulkDeleteOption.getOpt())); } else if (cmd.hasOption(deleteOption.getOpt())) { this.deleteJob(cmd.getOptionValue(jobNameOption.getOpt())); } } private void deleteJobBulk(String path) throws IOException { Path filePath = new Path(path); try (BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(filePath.toString()), Charset.forName("UTF-8")))) { String jobName; while ((jobName = br.readLine()) != null) { System.out.println("Deleting " + jobName); try { this.jobStateStore.delete(jobName); } catch (IOException e) { System.out.println("Could not delete job name: " + jobName + " due to " + e.getMessage()); } } } } private void deleteJob(String jobName) { System.out.println("Deleting " + jobName); try { this.jobStateStore.delete(jobName); } catch (IOException e) { System.out.println("Could not delete job name: " + jobName + " due to " + e.getMessage()); } } private void viewStateAsJson(CommandLine cmd) throws IOException { JobStateToJsonConverter converter = new JobStateToJsonConverter(this.jobStateStore, cmd.hasOption("kc")); converter.outputToJson(cmd); } }
1,472
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/PasswordManagerCLI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import org.apache.gobblin.annotation.Alias; import org.apache.gobblin.util.CLIPasswordEncryptor; /** * An application that uses {@link org.apache.gobblin.password.PasswordManager} to encrypt and decrypt strings. */ @Alias(value = "passwordManager", description = "Encrypt or decrypt strings for the password manager.") public class PasswordManagerCLI implements CliApplication { @Override public void run(String[] args) { try { CLIPasswordEncryptor.main(args); } catch (Throwable t) { throw new RuntimeException(t); } } }
1,473
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/cli/EmbeddedGobblinCliFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.cli; import org.apache.gobblin.runtime.embedded.EmbeddedGobblin; /** * A factory for {@link EmbeddedGobblin} instances. */ public interface EmbeddedGobblinCliFactory extends CliObjectFactory<EmbeddedGobblin> { }
1,474
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/local/LocalJobLauncher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.local; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.gobblin.metrics.event.CountEventBuilder; import org.apache.gobblin.metrics.event.JobEvent; import org.apache.gobblin.runtime.job.JobInterruptionPredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ServiceManager; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes; import org.apache.gobblin.broker.iface.SharedResourcesBroker; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.metrics.event.TimingEvent; import org.apache.gobblin.runtime.AbstractJobLauncher; import org.apache.gobblin.runtime.GobblinMultiTaskAttempt; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.TaskExecutor; import org.apache.gobblin.runtime.TaskStateTracker; import org.apache.gobblin.runtime.api.Configurable; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.source.workunit.WorkUnit; import org.apache.gobblin.util.JobConfigurationUtils; import org.apache.gobblin.runtime.util.MultiWorkUnitUnpackingIterator; import org.apache.gobblin.source.workunit.WorkUnitStream; /** * An implementation of {@link org.apache.gobblin.runtime.JobLauncher} for launching and running jobs * locally on a single node. * * @author Yinan Li */ @Slf4j public class LocalJobLauncher extends AbstractJobLauncher { private static final Logger LOG = LoggerFactory.getLogger(LocalJobLauncher.class); private final TaskExecutor taskExecutor; private final TaskStateTracker taskStateTracker; // Service manager to manage dependent services private final ServiceManager serviceManager; private Integer workUnitCount; public LocalJobLauncher(Properties jobProps) throws Exception { this(jobProps, null, ImmutableList.of()); } public LocalJobLauncher(Properties jobProps, SharedResourcesBroker<GobblinScopeTypes> instanceBroker) throws Exception { this(jobProps, instanceBroker, ImmutableList.of()); } public LocalJobLauncher(Properties jobProps, SharedResourcesBroker<GobblinScopeTypes> instanceBroker, List<? extends Tag<?>> metadataTags) throws Exception { super(jobProps, metadataTags, instanceBroker); log.debug("Local job launched with properties: {}", jobProps); TimingEvent jobLocalSetupTimer = this.eventSubmitter.getTimingEvent(TimingEvent.RunJobTimings.JOB_LOCAL_SETUP); this.taskExecutor = new TaskExecutor(jobProps); this.taskStateTracker = new LocalTaskStateTracker(jobProps, this.jobContext.getJobState(), this.taskExecutor, this.eventBus); this.serviceManager = new ServiceManager(Lists.newArrayList( // The order matters due to dependencies between services this.taskExecutor, this.taskStateTracker)); // Start all dependent services this.serviceManager.startAsync().awaitHealthy(5, TimeUnit.SECONDS); startCancellationExecutor(); jobLocalSetupTimer.stop(); } public LocalJobLauncher(Configurable instanceConf, JobSpec jobSpec) throws Exception { this(JobConfigurationUtils.combineSysAndJobProperties(instanceConf.getConfigAsProperties(), jobSpec.getConfigAsProperties())); } @Override public void close() throws IOException { try { // Stop all dependent services this.serviceManager.stopAsync().awaitStopped(5, TimeUnit.SECONDS); } catch (TimeoutException te) { LOG.warn("Timed out while waiting for the service manager to be stopped", te); } finally { super.close(); } } @Override protected void runWorkUnits(List<WorkUnit> workUnits) throws Exception { // This should never happen throw new UnsupportedOperationException(); } @Override protected void runWorkUnitStream(WorkUnitStream workUnitStream) throws Exception { String jobId = this.jobContext.getJobId(); final JobState jobState = this.jobContext.getJobState(); Iterator<WorkUnit> workUnitIterator = workUnitStream.getWorkUnits(); if (!workUnitIterator.hasNext()) { LOG.warn("No work units to run"); CountEventBuilder countEventBuilder = new CountEventBuilder(JobEvent.WORK_UNITS_EMPTY, 0); this.eventSubmitter.submit(countEventBuilder); return; } TimingEvent workUnitsRunTimer = this.eventSubmitter.getTimingEvent(TimingEvent.RunJobTimings.WORK_UNITS_RUN); Iterator<WorkUnit> flattenedWorkUnits = new MultiWorkUnitUnpackingIterator(workUnitStream.getWorkUnits()); Iterator<WorkUnit> workUnitsWithJobState = Iterators.transform(flattenedWorkUnits, new Function<WorkUnit, WorkUnit>() { @Override public WorkUnit apply(WorkUnit workUnit) { workUnit.addAllIfNotExist(jobState); return workUnit; } }); Thread thisThread = Thread.currentThread(); JobInterruptionPredicate jobInterruptionPredicate = new JobInterruptionPredicate(jobState, () -> thisThread.interrupt(), true); GobblinMultiTaskAttempt.runWorkUnits(this.jobContext, workUnitsWithJobState, this.taskStateTracker, this.taskExecutor, GobblinMultiTaskAttempt.CommitPolicy.IMMEDIATE); jobInterruptionPredicate.stopAsync(); if (this.cancellationRequested) { // Wait for the cancellation execution if it has been requested synchronized (this.cancellationExecution) { if (this.cancellationExecuted) { return; } } } workUnitsRunTimer.stop(); LOG.info(String.format("All tasks of job %s have completed", jobId)); if (jobState.getState() == JobState.RunningState.RUNNING) { jobState.setState(JobState.RunningState.SUCCESSFUL); } } @Override protected void executeCancellation() { } }
1,475
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/local/CliLocalJobLauncher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.local; import java.io.IOException; import java.util.Properties; import java.util.UUID; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.Closer; import org.apache.gobblin.runtime.JobException; import org.apache.gobblin.runtime.JobLauncher; import org.apache.gobblin.runtime.app.ApplicationException; import org.apache.gobblin.runtime.app.ApplicationLauncher; import org.apache.gobblin.runtime.app.ServiceBasedAppLauncher; import org.apache.gobblin.runtime.cli.CliOptions; import org.apache.gobblin.runtime.listeners.JobListener; /** * Launcher for creating a Gobblin job from command line or IDE. */ public class CliLocalJobLauncher implements ApplicationLauncher, JobLauncher { private static final Logger LOG = LoggerFactory.getLogger(CliLocalJobLauncher.class); private final Closer closer = Closer.create(); private final ApplicationLauncher applicationLauncher; private final LocalJobLauncher localJobLauncher; private CliLocalJobLauncher(Properties properties) throws Exception { this.applicationLauncher = this.closer.register(new ServiceBasedAppLauncher(properties, properties.getProperty(ServiceBasedAppLauncher.APP_NAME, "CliLocalJob-" + UUID.randomUUID()))); this.localJobLauncher = this.closer.register(new LocalJobLauncher(properties)); } public void run() throws ApplicationException, JobException, IOException { try { start(); launchJob(null); } finally { try { stop(); } finally { close(); } } } public static void main(String[] args) throws Exception { Properties jobProperties = CliOptions.parseArgs(CliLocalJobLauncher.class, args); LOG.debug(String.format("Running job with properties:%n%s", jobProperties)); new CliLocalJobLauncher(jobProperties).run(); } @Override public void start() throws ApplicationException { this.applicationLauncher.start(); } @Override public void stop() throws ApplicationException { this.applicationLauncher.stop(); } @Override public void launchJob(@Nullable JobListener jobListener) throws JobException { this.localJobLauncher.launchJob(jobListener); } @Override public void cancelJob(@Nullable JobListener jobListener) throws JobException { this.localJobLauncher.cancelJob(jobListener); } @Override public void close() throws IOException { this.closer.close(); } }
1,476
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/local/LocalTaskStateTracker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.local; import java.util.Map; import java.util.Properties; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.eventbus.EventBus; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.runtime.AbstractTaskStateTracker; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.NewTaskCompletionEvent; import org.apache.gobblin.runtime.Task; import org.apache.gobblin.runtime.TaskExecutor; /** * A concrete extension to {@link AbstractTaskStateTracker} for standalone mode. * * @author Yinan Li */ public class LocalTaskStateTracker extends AbstractTaskStateTracker { private static final Logger LOG = LoggerFactory.getLogger(LocalTaskStateTracker.class); private final JobState jobState; // This is used to retry failed tasks // Life cycle of this object is managed by the same ServiceManager managing the life cycle of LocalStateTracker private final TaskExecutor taskExecutor; // Mapping between tasks and the task state reporters associated with them private final Map<String, ScheduledFuture<?>> scheduledReporters = Maps.newHashMap(); private final EventBus eventBus; // Maximum number of task retries allowed private final int maxTaskRetries; public LocalTaskStateTracker(Properties properties, JobState jobState, TaskExecutor taskExecutor, EventBus eventBus) { super(properties, LOG); this.jobState = jobState; this.taskExecutor = taskExecutor; this.eventBus = eventBus; this.maxTaskRetries = Integer.parseInt(properties.getProperty( ConfigurationKeys.MAX_TASK_RETRIES_KEY, Integer.toString(ConfigurationKeys.DEFAULT_MAX_TASK_RETRIES))); } @Override public void registerNewTask(Task task) { try { if (GobblinMetrics.isEnabled(task.getTaskState().getWorkunit())) { this.scheduledReporters.put(task.getTaskId(), scheduleTaskMetricsUpdater(new TaskMetricsUpdater(task), task)); } } catch (RejectedExecutionException ree) { LOG.error(String.format("Scheduling of task state reporter for task %s was rejected", task.getTaskId())); } } @Override public void onTaskRunCompletion(Task task) { try { // Check the task state and handle task retry if task failed and // it has not reached the maximum number of retries WorkUnitState.WorkingState state = task.getTaskState().getWorkingState(); if (state == WorkUnitState.WorkingState.FAILED && task.getRetryCount() < this.maxTaskRetries) { this.taskExecutor.retry(task); return; } } catch (Throwable t) { LOG.error("Failed to process a task completion callback", t); } // Mark the completion of this task task.markTaskCompletion(); } @Override public void onTaskCommitCompletion(Task task) { try { if (GobblinMetrics.isEnabled(task.getTaskState().getWorkunit())) { // Update record-level metrics after the task is done task.updateRecordMetrics(); task.updateByteMetrics(); } // Cancel the task state reporter associated with this task. The reporter might // not be found for the given task because the task fails before the task is // registered. So we need to make sure the reporter exists before calling cancel. if (this.scheduledReporters.containsKey(task.getTaskId())) { this.scheduledReporters.remove(task.getTaskId()).cancel(false); } } catch (Throwable t) { LOG.error("Failed to process a task completion callback", t); } // Add the TaskState of the completed task to the JobState so when the control // returns to the launcher, it sees the TaskStates of all completed tasks. this.jobState.addTaskState(task.getTaskState()); // Notify the listeners for the completion of the task this.eventBus.post(new NewTaskCompletionEvent(ImmutableList.of(task.getTaskState()))); // At this point, the task is considered being completed. LOG.info(String.format("Task %s completed in %dms with state %s", task.getTaskId(), task.getTaskState().getTaskDuration(), task.getTaskState().getWorkingState())); } }
1,477
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/PackagedTemplatesJobCatalogDecorator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.template.ResourceBasedJobTemplate; import org.apache.gobblin.util.Decorator; import lombok.experimental.Delegate; /** * A {@link Decorator} for {@link JobCatalog} that loads {@link JobTemplate}s from classpath (resources and classes). * * This decorator will intercept {@link JobTemplate} requests with schemes "resource" or "class", and will load them * from classpath. * * A class template has uri "class://fully.qualified.class.name", and will instantiate that class and attempt to cast * as {@link JobTemplate}. * * A resource template has uri "resource:///path/to/template/in/resources.template", and the decorator will attempt to * parse it as a {@link ResourceBasedJobTemplate}. * * Any other scheme will be delegated to the underlying job catalog if it implements {@link JobCatalogWithTemplates}, * or a {@link SpecNotFoundException} will be thrown. */ public class PackagedTemplatesJobCatalogDecorator implements Decorator, JobCatalogWithTemplates { public static final String RESOURCE = "resource"; public static final String CLASS = "class"; /** * Creates a {@link PackagedTemplatesJobCatalogDecorator} with an underlying empty {@link InMemoryJobCatalog}. */ public PackagedTemplatesJobCatalogDecorator() { this(new InMemoryJobCatalog()); } @Delegate private final JobCatalog underlying; public PackagedTemplatesJobCatalogDecorator(JobCatalog underlying) { this.underlying = underlying != null ? underlying : new InMemoryJobCatalog(); } @Override public Object getDecoratedObject() { return this.underlying; } @Override public JobTemplate getTemplate(URI uri) throws SpecNotFoundException, JobTemplate.TemplateException { if (RESOURCE.equals(uri.getScheme())) { try { // resources are accessed by relative uris, make the uri relative (get path, strip initial /) URI actualResourceUri = new URI(uri.getPath().substring(1)); return ResourceBasedJobTemplate.forURI(actualResourceUri, this); } catch (URISyntaxException use) { throw new RuntimeException("Error when computing resource path.", use); } catch (IOException ioe) { throw new SpecNotFoundException(uri, ioe); } } else if(CLASS.equals(uri.getScheme())) { try { return ((Class<? extends JobTemplate>) Class.forName(uri.getAuthority())).newInstance(); } catch (ReflectiveOperationException roe) { throw new SpecNotFoundException(uri, roe); } } if (this.underlying != null && this.underlying instanceof JobCatalogWithTemplates) { JobTemplate template = ((JobCatalogWithTemplates) this.underlying).getTemplate(uri); if (template == null) { throw new SpecNotFoundException(uri); } return template; } throw new SpecNotFoundException(uri); } @Override public Collection<JobTemplate> getAllTemplates() { throw new UnsupportedOperationException(); } }
1,478
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/MutableJobCatalogBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.net.URI; import org.slf4j.Logger; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.MutableJobCatalog; /** * A base for {@link MutableJobCatalog}s. Handles notifications to listeners on calls to {@link #put}, {@link #remove}, * as well as the state of the {@link com.google.common.util.concurrent.Service}. */ public abstract class MutableJobCatalogBase extends JobCatalogBase implements MutableJobCatalog { public MutableJobCatalogBase() { } public MutableJobCatalogBase(Optional<Logger> log) { super(log); } public MutableJobCatalogBase(GobblinInstanceEnvironment env) { super(env); } public MutableJobCatalogBase(Optional<Logger> log, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) { super(log, parentMetricContext, instrumentationEnabled); } @Override public void put(JobSpec jobSpec) { Preconditions.checkState(allowMutationsBeforeStartup() || state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); JobSpec oldSpec = doPut(jobSpec); if (null == oldSpec) { this.listeners.onAddJob(jobSpec); } else { this.listeners.onUpdateJob(jobSpec); } } /** * Add the {@link JobSpec} to the catalog. If a {@link JobSpec} already existed with that {@link URI}, it should be * replaced and the old one returned. * @return if a {@link JobSpec} already existed with that {@link URI}, return the old {@link JobSpec}. Otherwise return * null. */ protected abstract JobSpec doPut(JobSpec jobSpec); @Override public void remove(URI uri) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(uri); JobSpec jobSpec = doRemove(uri); if (null != jobSpec) { this.listeners.onDeleteJob(jobSpec.getUri(), jobSpec.getVersion()); } } /** * Remove the {@link JobSpec} with the given {@link URI} from the catalog. * @return The removed {@link JobSpec}, or null if no {@link JobSpec} with the given {@link URI} existed. */ protected abstract JobSpec doRemove(URI uri); /** * Specifies whether the catalog can be mutated (add or remove {@link JobSpec}) before it has been started. */ protected boolean allowMutationsBeforeStartup() { return true; } }
1,479
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/JobCatalogBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.AbstractIdleService; import com.typesafe.config.Config; import org.apache.gobblin.instrumented.Instrumented; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogListener; import org.apache.gobblin.runtime.api.JobSpec; /** * An abstract base for {@link JobCatalog}s implementing boilerplate methods (metrics, listeners, etc.) */ public abstract class JobCatalogBase extends AbstractIdleService implements JobCatalog { protected final JobCatalogListenersList listeners; protected final Logger log; protected final MetricContext metricContext; protected final StandardMetrics metrics; public JobCatalogBase() { this(Optional.<Logger>absent()); } public JobCatalogBase(Optional<Logger> log) { this(log, Optional.<MetricContext>absent(), true); } public JobCatalogBase(GobblinInstanceEnvironment env) { this(Optional.of(env.getLog()), Optional.of(env.getMetricContext()), env.isInstrumentationEnabled()); } public JobCatalogBase(Optional<Logger> log, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) { this(log, parentMetricContext, instrumentationEnabled, Optional.absent()); } public JobCatalogBase(Optional<Logger> log, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled, Optional<Config> sysConfig) { this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass()); this.listeners = new JobCatalogListenersList(log); if (instrumentationEnabled) { MetricContext realParentCtx = parentMetricContext.or(Instrumented.getMetricContext(new org.apache.gobblin.configuration.State(), getClass())); this.metricContext = realParentCtx.childBuilder(JobCatalog.class.getSimpleName()).build(); this.metrics = createStandardMetrics(sysConfig); this.addListener(this.metrics); } else { this.metricContext = null; this.metrics = null; } } protected StandardMetrics createStandardMetrics(Optional<Config> sysConfig) { return new StandardMetrics(this, sysConfig); } @Override protected void startUp() throws IOException { notifyAllListeners(); } @Override protected void shutDown() throws IOException { this.listeners.close(); } protected void notifyAllListeners() { Collection<JobSpec> jobSpecs = getJobsWithTimeUpdate(); for (JobSpec jobSpec : jobSpecs) { this.listeners.onAddJob(jobSpec); } } private Collection<JobSpec> getJobsWithTimeUpdate() { long startTime = System.currentTimeMillis(); Collection<JobSpec> jobSpecs = getJobs(); this.metrics.updateGetJobTime(startTime); return jobSpecs; } private Iterator<JobSpec> getJobSpecsWithTimeUpdate() { long startTime = System.currentTimeMillis(); Iterator<JobSpec> jobSpecs = getJobSpecIterator(); this.metrics.updateGetJobTime(startTime); return jobSpecs; } /**{@inheritDoc}*/ @Override public synchronized void addListener(JobCatalogListener jobListener) { Preconditions.checkNotNull(jobListener); this.listeners.addListener(jobListener); if (state() == State.RUNNING) { Iterator<JobSpec> jobSpecItr = getJobSpecsWithTimeUpdate(); while (jobSpecItr.hasNext()) { JobSpec jobSpec = jobSpecItr.next(); if (jobSpec != null) { JobCatalogListener.AddJobCallback addJobCallback = new JobCatalogListener.AddJobCallback(jobSpec); this.listeners.callbackOneListener(addJobCallback, jobListener); } } } } /**{@inheritDoc}*/ @Override public synchronized void removeListener(JobCatalogListener jobListener) { this.listeners.removeListener(jobListener); } @Override public void registerWeakJobCatalogListener(JobCatalogListener jobListener) { this.listeners.registerWeakJobCatalogListener(jobListener); } @Override public MetricContext getMetricContext() { return this.metricContext; } @Override public boolean isInstrumentationEnabled() { return null != this.metricContext; } @Override public List<Tag<?>> generateTags(org.apache.gobblin.configuration.State state) { return Collections.emptyList(); } @Override public void switchMetricContext(List<Tag<?>> tags) { throw new UnsupportedOperationException(); } @Override public void switchMetricContext(MetricContext context) { throw new UnsupportedOperationException(); } @Override public StandardMetrics getMetrics() { return this.metrics; } }
1,480
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/FSJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogWithTemplates; import org.apache.gobblin.runtime.api.JobTemplate; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.template.HOCONInputStreamJobTemplate; import org.apache.gobblin.util.PathUtils; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URI; import java.util.Collection; import java.util.Map; import java.util.UUID; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; import org.apache.gobblin.runtime.api.MutableJobCatalog; import org.apache.gobblin.util.filesystem.PathAlterationObserver; /** * The job Catalog for file system to persist the job configuration information. * This implementation has no support for caching. */ public class FSJobCatalog extends ImmutableFSJobCatalog implements MutableJobCatalog, JobCatalogWithTemplates { private static final Logger LOGGER = LoggerFactory.getLogger(FSJobCatalog.class); public static final String CONF_EXTENSION = ".conf"; private static final String FS_SCHEME = "FS"; protected final MutableStandardMetrics mutableMetrics; /** * Initialize the JobCatalog, fetch all jobs in jobConfDirPath. * @param sysConfig * @throws Exception */ public FSJobCatalog(Config sysConfig) throws IOException { super(sysConfig); this.mutableMetrics = (MutableStandardMetrics)metrics; } public FSJobCatalog(GobblinInstanceEnvironment env) throws IOException { super(env); this.mutableMetrics = (MutableStandardMetrics)metrics; } public FSJobCatalog(Config sysConfig, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) throws IOException{ super(sysConfig, null, parentMetricContext, instrumentationEnabled); this.mutableMetrics = (MutableStandardMetrics)metrics; } @Override protected JobCatalog.StandardMetrics createStandardMetrics(Optional<Config> sysConfig) { log.info("create standard metrics {} for {}", MutableStandardMetrics.class.getName(), this.getClass().getName()); return new MutableStandardMetrics(this, sysConfig); } /** * The expose of observer is used for testing purpose, so that * the checkAndNotify method can be revoked manually, instead of waiting for * the scheduling timing. * @param sysConfig The same as general constructor. * @param observer The user-initialized observer. * @throws Exception */ @VisibleForTesting protected FSJobCatalog(Config sysConfig, PathAlterationObserver observer) throws IOException { super(sysConfig, observer); this.mutableMetrics = (MutableStandardMetrics)this.metrics; } /** * Allow user to programmatically add a new JobSpec. * The method will materialized the jobSpec into real file. * * @param jobSpec The target JobSpec Object to be materialized. * Noted that the URI return by getUri is a relative path. */ @Override public synchronized void put(JobSpec jobSpec) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); try { long startTime = System.currentTimeMillis(); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobSpec.getUri()); materializedJobSpec(jobSpecPath, jobSpec, this.fs); this.mutableMetrics.updatePutJobTime(startTime); } catch (IOException e) { throw new RuntimeException("When persisting a new JobSpec, unexpected issues happen:" + e.getMessage()); } catch (JobSpecNotFoundException e) { throw new RuntimeException("When replacing a existed JobSpec, unexpected issue happen:" + e.getMessage()); } } /** * Allow user to programmatically delete a new JobSpec. * This method is designed to be reentrant. * @param jobURI The relative Path that specified by user, need to make it into complete path. */ @Override public synchronized void remove(URI jobURI) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); try { long startTime = System.currentTimeMillis(); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobURI); if (fs.exists(jobSpecPath)) { fs.delete(jobSpecPath, false); this.mutableMetrics.updateRemoveJobTime(startTime); } else { LOGGER.warn("No file with URI:" + jobSpecPath + " is found. Deletion failed."); } } catch (IOException e) { throw new RuntimeException("When removing a JobConf. file, issues unexpected happen:" + e.getMessage()); } } /** * It is InMemoryJobCatalog's responsibility to inform the gobblin instance driver about the file change. * Here it is internal detector's responsibility. */ @Override public boolean shouldLoadGlobalConf() { return false; } @Override public Path getPathForURI(Path jobConfDirPath, URI uri) { return super.getPathForURI(jobConfDirPath, uri).suffix(CONF_EXTENSION); } @Override protected Optional<String> getInjectedExtension() { return Optional.of(CONF_EXTENSION); } /** * Used for shadow copying in the process of updating a existing job configuration file, * which requires deletion of the pre-existed copy of file and create a new one with the same name. * Steps: * Create a new one in /tmp. * Safely deletion of old one. * copy the newly created configuration file to jobConfigDir. * Delete the shadow file. */ synchronized void materializedJobSpec(Path jobSpecPath, JobSpec jobSpec, FileSystem fs) throws IOException, JobSpecNotFoundException { Path shadowDirectoryPath = new Path("/tmp"); Path shadowFilePath = new Path(shadowDirectoryPath, UUID.randomUUID().toString()); /* If previously existed, should delete anyway */ if (fs.exists(shadowFilePath)) { fs.delete(shadowFilePath, false); } ImmutableMap.Builder mapBuilder = ImmutableMap.builder(); mapBuilder.put(ImmutableFSJobCatalog.DESCRIPTION_KEY_IN_JOBSPEC, jobSpec.getDescription()) .put(ImmutableFSJobCatalog.VERSION_KEY_IN_JOBSPEC, jobSpec.getVersion()); if (jobSpec.getTemplateURI().isPresent()) { mapBuilder.put(ConfigurationKeys.JOB_TEMPLATE_PATH, jobSpec.getTemplateURI().get().toString()); } Map<String, String> injectedKeys = mapBuilder.build(); String renderedConfig = ConfigFactory.parseMap(injectedKeys).withFallback(jobSpec.getConfig()) .root().render(ConfigRenderOptions.defaults()); try (DataOutputStream os = fs.create(shadowFilePath); Writer writer = new OutputStreamWriter(os, Charsets.UTF_8)) { writer.write(renderedConfig); } /* (Optionally:Delete oldSpec) and copy the new one in. */ if (fs.exists(jobSpecPath)) { if (! fs.delete(jobSpecPath, false)) { throw new IOException("Unable to delete existing job file: " + jobSpecPath); } } if (!fs.rename(shadowFilePath, jobSpecPath)) { throw new IOException("Unable to rename job file: " + shadowFilePath + " to " + jobSpecPath); } } @Override public JobTemplate getTemplate(URI uri) throws SpecNotFoundException, JobTemplate.TemplateException { if (!uri.getScheme().equals(FS_SCHEME)) { throw new RuntimeException("Expected scheme " + FS_SCHEME + " got unsupported scheme " + uri.getScheme()); } // path of uri is location of template file relative to the job configuration root directory Path templateFullPath = PathUtils.mergePaths(jobConfDirPath, new Path(uri.getPath())); try (InputStream is = fs.open(templateFullPath)) { return new HOCONInputStreamJobTemplate(is, uri, this); } catch (IOException ioe) { throw new SpecNotFoundException(uri, ioe); } } @Override public Collection<JobTemplate> getAllTemplates() { throw new UnsupportedOperationException(); } }
1,481
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/FSPathAlterationListenerAdaptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.IOException; import java.net.URI; import org.apache.hadoop.fs.Path; import com.typesafe.config.Config; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.util.PullFileLoader; import org.apache.gobblin.util.filesystem.PathAlterationListenerAdaptor; public class FSPathAlterationListenerAdaptor extends PathAlterationListenerAdaptor { private final Path jobConfDirPath; private final PullFileLoader loader; private final Config sysConfig; private final JobCatalogListenersList listeners; private final ImmutableFSJobCatalog.JobSpecConverter converter; FSPathAlterationListenerAdaptor(Path jobConfDirPath, PullFileLoader loader, Config sysConfig, JobCatalogListenersList listeners, ImmutableFSJobCatalog.JobSpecConverter converter) { this.jobConfDirPath = jobConfDirPath; this.loader = loader; this.sysConfig = sysConfig; this.listeners = listeners; this.converter = converter; } /** * Transform the event triggered by file creation into JobSpec Creation for Driver (One of the JobCatalogListener ) * Create a new JobSpec object and notify each of member inside JobCatalogListenersList * @param rawPath This could be complete path to the newly-created configuration file. */ @Override public void onFileCreate(Path rawPath) { try { JobSpec newJobSpec = this.converter.apply(loader.loadPullFile(rawPath, sysConfig, false)); listeners.onAddJob(newJobSpec); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } /** * For already deleted job configuration file, the only identifier is path * it doesn't make sense to loadJobConfig Here. * @param rawPath This could be the complete path to the newly-deleted configuration file. */ @Override public void onFileDelete(Path rawPath) { URI jobSpecUri = this.converter.computeURI(rawPath); // TODO: fix version listeners.onDeleteJob(jobSpecUri, null); } @Override public void onFileChange(Path rawPath) { try { JobSpec updatedJobSpec = this.converter.apply(loader.loadPullFile(rawPath, sysConfig, false)); listeners.onUpdateJob(updatedJobSpec); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } }
1,482
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/CachingJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.util.concurrent.AbstractIdleService; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogListener; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; /** * A JobCatalog decorator that caches all JobSpecs in memory. * */ public class CachingJobCatalog extends AbstractIdleService implements JobCatalog { protected final JobCatalog _fallback; protected final InMemoryJobCatalog _cache; protected final Logger _log; public CachingJobCatalog(JobCatalog fallback, Optional<Logger> log) { _log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass()); _fallback = fallback; _cache = new InMemoryJobCatalog(log); _fallback.addListener(new FallbackCatalogListener()); } /** {@inheritDoc} */ @Override public Collection<JobSpec> getJobs() { return _cache.getJobs(); } /** {@inheritDoc} */ @Override public JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException { try { return _cache.getJobSpec(uri); } catch (RuntimeException e) { return _fallback.getJobSpec(uri); } } @Override protected void startUp() { _cache.startAsync(); try { _cache.awaitRunning(2, TimeUnit.SECONDS); } catch (TimeoutException te) { throw new RuntimeException("Failed to start " + CachingJobCatalog.class.getName(), te); } } @Override protected void shutDown() { _cache.stopAsync(); try { _cache.awaitTerminated(2, TimeUnit.SECONDS); } catch (TimeoutException te) { throw new RuntimeException("Failed to stop " + CachingJobCatalog.class.getName(), te); } } /** {@inheritDoc} */ @Override public void addListener(JobCatalogListener jobListener) { _cache.addListener(jobListener); } /** {@inheritDoc} */ @Override public void removeListener(JobCatalogListener jobListener) { _cache.removeListener(jobListener); } /** Refreshes the cache if the underlying fallback catalog changes. */ private class FallbackCatalogListener implements JobCatalogListener { @Override public void onAddJob(JobSpec addedJob) { _cache.put(addedJob); } @Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { _cache.remove(deletedJobURI); } @Override public void onUpdateJob(JobSpec updatedJob) { _cache.put(updatedJob); } } @Override public void registerWeakJobCatalogListener(JobCatalogListener jobListener) { _cache.registerWeakJobCatalogListener(jobListener); } @Override public MetricContext getMetricContext() { return _fallback.getMetricContext(); } @Override public boolean isInstrumentationEnabled() { return _fallback.isInstrumentationEnabled(); } @Override public List<Tag<?>> generateTags(org.apache.gobblin.configuration.State state) { return _fallback.generateTags(state); } @Override public void switchMetricContext(List<Tag<?>> tags) { _fallback.switchMetricContext(tags); } @Override public void switchMetricContext(MetricContext context) { _fallback.switchMetricContext(context); } @Override public StandardMetrics getMetrics() { return _fallback.getMetrics(); } }
1,483
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/MysqlJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import com.typesafe.config.Config; import java.io.IOException; import java.net.URI; import java.util.Iterator; import java.util.List; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; import org.apache.gobblin.runtime.api.MutableJobCatalog; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.spec_serde.GsonJobSpecSerDe; import org.apache.gobblin.runtime.spec_store.MysqlBaseSpecStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MySQL-backed Job Catalog for persisting {@link JobSpec} job configuration information, which fully supports (mutation) * listeners and metrics. */ public class MysqlJobCatalog extends JobCatalogBase implements MutableJobCatalog { private static final Logger LOGGER = LoggerFactory.getLogger(MysqlJobCatalog.class); public static final String DB_CONFIG_PREFIX = "mysqlJobCatalog"; protected final MutableJobCatalog.MutableStandardMetrics mutableMetrics; protected final MysqlBaseSpecStore jobSpecStore; /** * Initialize, with DB config contextualized by `DB_CONFIG_PREFIX`. */ public MysqlJobCatalog(Config sysConfig) throws IOException { this(sysConfig, Optional.<MetricContext>absent(), GobblinMetrics.isEnabled(sysConfig)); } public MysqlJobCatalog(GobblinInstanceEnvironment env) throws IOException { super(env); this.mutableMetrics = (MutableJobCatalog.MutableStandardMetrics) metrics; this.jobSpecStore = createJobSpecStore(env.getSysConfig().getConfig()); } public MysqlJobCatalog(Config sysConfig, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) throws IOException { super(Optional.of(LOGGER), parentMetricContext, instrumentationEnabled, Optional.of(sysConfig)); this.mutableMetrics = (MutableJobCatalog.MutableStandardMetrics) metrics; this.jobSpecStore = createJobSpecStore(sysConfig); } @Override protected JobCatalog.StandardMetrics createStandardMetrics(Optional<Config> sysConfig) { log.info("create standard metrics {} for {}", MutableJobCatalog.MutableStandardMetrics.class.getName(), this.getClass().getName()); return new MutableJobCatalog.MutableStandardMetrics(this, sysConfig); } protected MysqlBaseSpecStore createJobSpecStore(Config sysConfig) { try { return new MysqlBaseSpecStore(sysConfig, new GsonJobSpecSerDe()) { @Override protected String getConfigPrefix() { return MysqlJobCatalog.DB_CONFIG_PREFIX; } }; } catch (IOException e) { throw new RuntimeException("unable to create `JobSpec` store", e); } } /** @return all {@link JobSpec}s */ @Override public List<JobSpec> getJobs() { try { return (List) jobSpecStore.getSpecs(); } catch (IOException e) { throw new RuntimeException("error getting (all) job specs", e); } } /** * Obtain an iterator to fetch all job specifications. Unlike {@link #getJobs()}, this method avoids loading * all job configs into memory in the very beginning. * Interleaving notes: jobs added/modified/deleted between `Iterator` creation and exhaustion MAY or MAY NOT be reflected. * * @return an iterator for (all) present {@link JobSpec}s */ @Override public Iterator<JobSpec> getJobSpecIterator() { try { return Iterators.<Optional<JobSpec>, JobSpec>transform( Iterators.filter( Iterators.transform(jobSpecStore.getSpecURIs(), uri -> { try { return Optional.of(MysqlJobCatalog.this.getJobSpec(uri)); } catch (JobSpecNotFoundException e) { MysqlJobCatalog.this.log.info("unable to retrieve previously identified JobSpec by URI '{}'", uri); return Optional.absent(); }}), Optional::isPresent), Optional::get); } catch (IOException e) { throw new RuntimeException("error iterating (all) job specs", e); } } /** * Fetch single {@link JobSpec} by URI. * @return the `JobSpec` * @throws {@link JobSpecNotFoundException} */ @Override public JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException { Preconditions.checkNotNull(uri); try { return (JobSpec) jobSpecStore.getSpec(uri); } catch (IOException e) { throw new RuntimeException(String.format("error accessing job spec '%s'", uri), e); } catch (SpecNotFoundException e) { throw new JobSpecNotFoundException(uri); } } /** * Add or update (when an existing) {@link JobSpec}, triggering the appropriate * {@link org.apache.gobblin.runtime.api.JobCatalogListener} callback. * * NOTE: `synchronized` (w/ `remove()`) for integrity of (existence) check-then-update. */ @Override public synchronized void put(JobSpec jobSpec) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); try { long startTime = System.currentTimeMillis(); boolean isUpdate = jobSpecStore.exists(jobSpec.getUri()); if (isUpdate) { try { jobSpecStore.updateSpec(jobSpec); this.mutableMetrics.updatePutJobTime(startTime); this.listeners.onUpdateJob(jobSpec); } catch (SpecNotFoundException e) { // should never happen (since `synchronized`) throw new RuntimeException(String.format("error finding spec to update '%s'", jobSpec.getUri()), e); } } else { jobSpecStore.addSpec(jobSpec); this.mutableMetrics.updatePutJobTime(startTime); this.listeners.onAddJob(jobSpec); } } catch (IOException e) { throw new RuntimeException(String.format("error updating or adding JobSpec '%s'", jobSpec.getUri()), e); } } /** * Delete (an existing) {@link JobSpec}, triggering the appropriate {@link org.apache.gobblin.runtime.api.JobCatalogListener} callback. * * NOTE: `synchronized` w/ `put()` to protect its check-then-update. */ @Override public synchronized void remove(URI jobURI) { remove(jobURI, false); } /** * NOTE: `synchronized` w/ `put()` to protect its check-then-update. * * @param alwaysTriggerListeners whether invariably to trigger {@link org.apache.gobblin.runtime.api.JobCatalogListener#onCancelJob(URI)} */ @Override public synchronized void remove(URI jobURI, boolean alwaysTriggerListeners) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobURI); try { long startTime = System.currentTimeMillis(); JobSpec jobSpec = (JobSpec) jobSpecStore.getSpec(jobURI); jobSpecStore.deleteSpec(jobURI); this.mutableMetrics.updateRemoveJobTime(startTime); this.listeners.onDeleteJob(jobURI, jobSpec.getVersion()); } catch (SpecNotFoundException e) { LOGGER.warn("Unknown job spec URI: '" + jobURI + "'. Deletion failed."); } catch (IOException e) { throw new RuntimeException("When removing a JobConf. file, issues unexpected happen:" + e.getMessage()); } finally { // HelixRetriggeringJobCallable deletes the job file after submitting it to helix, // so trigger listeners regardless of its existence. if (alwaysTriggerListeners) { this.listeners.onCancelJob(jobURI); } } } }
1,484
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/InMemoryJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; /** * Simple implementation of a Gobblin job catalog that stores all JobSpecs in memory. No persistence * is provided. */ public class InMemoryJobCatalog extends MutableJobCatalogBase { protected final Map<URI, JobSpec> jobSpecs = new HashMap<>(); public InMemoryJobCatalog() { this(Optional.<Logger>absent()); } public InMemoryJobCatalog(Optional<Logger> log) { this(log, Optional.<MetricContext>absent(), true); } public InMemoryJobCatalog(GobblinInstanceEnvironment env) { this(Optional.of(env.getLog()), Optional.of(env.getMetricContext()), env.isInstrumentationEnabled()); } public InMemoryJobCatalog(Optional<Logger> log, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) { super(log, parentMetricContext, instrumentationEnabled); } /**{@inheritDoc}*/ @Override public synchronized Collection<JobSpec> getJobs() { return new ArrayList<>(this.jobSpecs.values()); } /**{@inheritDoc}*/ @Override public synchronized JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException { if (this.jobSpecs.containsKey(uri)) { return this.jobSpecs.get(uri); } else { throw new JobSpecNotFoundException(uri); } } @Override protected JobSpec doPut(JobSpec jobSpec) { return this.jobSpecs.put(jobSpec.getUri(), jobSpec); } @Override protected JobSpec doRemove(URI uri) { return this.jobSpecs.remove(uri); } }
1,485
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/MutableCachingJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.net.URI; import org.slf4j.Logger; import com.google.common.base.Optional; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.MutableJobCatalog; /** * Implements a write-through cache of a decorated JobCatalog */ public class MutableCachingJobCatalog extends CachingJobCatalog implements MutableJobCatalog { public MutableCachingJobCatalog(MutableJobCatalog fallback, Optional<Logger> log) { super(fallback, log); } /** {@inheritDoc} */ @Override public void put(JobSpec jobSpec) { ((MutableJobCatalog)_fallback).put(jobSpec); } /** {@inheritDoc} */ @Override public void remove(URI uri) { ((MutableJobCatalog)_fallback).remove(uri); } }
1,486
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/ImmutableFSJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.typesafe.config.Config; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; import org.apache.gobblin.util.PathUtils; import org.apache.gobblin.util.PullFileLoader; import org.apache.gobblin.util.filesystem.PathAlterationListener; import org.apache.gobblin.util.filesystem.PathAlterationObserverScheduler; import org.apache.gobblin.util.filesystem.PathAlterationObserver; import lombok.AllArgsConstructor; import lombok.Getter; public class ImmutableFSJobCatalog extends JobCatalogBase implements JobCatalog { protected final FileSystem fs; protected final Config sysConfig; protected static final Logger LOGGER = LoggerFactory.getLogger(ImmutableFSJobCatalog.class); protected final PullFileLoader loader; /* The root configuration directory path.*/ protected final Path jobConfDirPath; private final ImmutableFSJobCatalog.JobSpecConverter converter; // A monitor for changes to job conf files for general FS // This embedded monitor is monitoring job configuration files instead of JobSpec Object. protected final PathAlterationObserverScheduler pathAlterationDetector; public static final String FS_CATALOG_KEY_PREFIX = "gobblin.fsJobCatalog"; public static final String VERSION_KEY_IN_JOBSPEC = "gobblin.fsJobCatalog.version"; // Key used in the metadata of JobSpec. public static final String DESCRIPTION_KEY_IN_JOBSPEC = "gobblin.fsJobCatalog.description"; public ImmutableFSJobCatalog(Config sysConfig) throws IOException { this(sysConfig, null); } public ImmutableFSJobCatalog(GobblinInstanceEnvironment env) throws IOException { this(env.getSysConfig().getConfig(), null, Optional.of(env.getMetricContext()), env.isInstrumentationEnabled()); } public ImmutableFSJobCatalog(GobblinInstanceEnvironment env, PathAlterationObserver observer) throws IOException { this(env.getSysConfig().getConfig(), observer, Optional.of(env.getMetricContext()), env.isInstrumentationEnabled()); } public ImmutableFSJobCatalog(Config sysConfig, PathAlterationObserver observer) throws IOException { this(sysConfig, observer, Optional.<MetricContext>absent(), GobblinMetrics.isEnabled(sysConfig)); } public ImmutableFSJobCatalog(Config sysConfig, PathAlterationObserver observer, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) throws IOException { super(Optional.of(LOGGER), parentMetricContext, instrumentationEnabled, Optional.of(sysConfig)); this.sysConfig = sysConfig; ConfigAccessor cfgAccessor = new ConfigAccessor(this.sysConfig); this.jobConfDirPath = cfgAccessor.getJobConfDirPath(); this.fs = cfgAccessor.getJobConfDirFileSystem(); this.loader = new PullFileLoader(jobConfDirPath, jobConfDirPath.getFileSystem(new Configuration()), cfgAccessor.getJobConfigurationFileExtensions(), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); this.converter = new ImmutableFSJobCatalog.JobSpecConverter(this.jobConfDirPath, getInjectedExtension()); long pollingInterval = cfgAccessor.getPollingInterval(); if (pollingInterval == ConfigurationKeys.DISABLED_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL) { this.pathAlterationDetector = null; } else { this.pathAlterationDetector = new PathAlterationObserverScheduler(pollingInterval); // If absent, the Optional object will be created automatically by addPathAlterationObserver Optional<PathAlterationObserver> observerOptional = Optional.fromNullable(observer); this.pathAlterationDetector.addPathAlterationObserver(getListener(), observerOptional, this.jobConfDirPath); } } protected PathAlterationListener getListener() { return new FSPathAlterationListenerAdaptor(this.jobConfDirPath, this.loader, this.sysConfig, this.listeners, this.converter); } @Override protected void startUp() throws IOException { super.startUp(); if (this.pathAlterationDetector != null) { this.pathAlterationDetector.start(); } } @Override protected void shutDown() throws IOException { try { if (this.pathAlterationDetector != null) { this.pathAlterationDetector.stop(); } } catch (InterruptedException exc) { throw new RuntimeException("Failed to stop " + ImmutableFSJobCatalog.class.getName(), exc); } super.shutDown(); } /** * Fetch all the job files under the jobConfDirPath * @return A collection of JobSpec */ @Override public synchronized List<JobSpec> getJobs() { return Lists.transform(Lists.newArrayList( loader.loadPullFilesRecursively(loader.getRootDirectory(), this.sysConfig, shouldLoadGlobalConf())), this.converter); } /** * Return an iterator that can fetch all the job specifications. * Different than {@link #getJobs()}, this method prevents loading * all the job configs into memory in the very beginning. Instead it * only loads file paths initially and creates the JobSpec and the * underlying {@link Config} during the iteration. * * @return an iterator that contains job specs (job specs can be null). */ @Override public synchronized Iterator<JobSpec> getJobSpecIterator() { List<Path> jobFiles = loader.fetchJobFilesRecursively(loader.getRootDirectory()); Iterator<JobSpec> jobSpecIterator = Iterators.transform(jobFiles.iterator(), new Function<Path, JobSpec>() { @Nullable @Override public JobSpec apply(@Nullable Path jobFile) { if (jobFile == null) { return null; } try { Config config = ImmutableFSJobCatalog.this.loader.loadPullFile(jobFile, ImmutableFSJobCatalog.this.sysConfig, ImmutableFSJobCatalog.this.shouldLoadGlobalConf()); return ImmutableFSJobCatalog.this.converter.apply(config); } catch (IOException e) { log.error("Cannot load job from {} due to {}", jobFile, ExceptionUtils.getFullStackTrace(e)); return null; } } }); return jobSpecIterator; } /** * Fetch single job file based on its URI, * @param uri The relative Path to the target job configuration. * @return */ @Override public synchronized JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException { try { Path targetJobSpecFullPath = getPathForURI(this.jobConfDirPath, uri); return this.converter.apply(loader.loadPullFile(targetJobSpecFullPath, this.sysConfig, shouldLoadGlobalConf())); } catch (FileNotFoundException e) { throw new JobSpecNotFoundException(uri); } catch (IOException e) { throw new RuntimeException("IO exception thrown on loading single job configuration file:" + e.getMessage()); } } /** * For immutable job catalog, * @return */ public boolean shouldLoadGlobalConf() { return true; } /** * * @param jobConfDirPath The directory path for job cofniguration files. * @param uri Uri as the identifier of JobSpec * @return */ protected Path getPathForURI(Path jobConfDirPath, URI uri) { return PathUtils.mergePaths(jobConfDirPath, new Path(uri)); } protected Optional<String> getInjectedExtension() { return Optional.absent(); } @Getter public static class ConfigAccessor { private final Config cfg; private final long pollingInterval; private final String jobConfDir; private final Path jobConfDirPath; private final FileSystem jobConfDirFileSystem; private final Set<String> JobConfigurationFileExtensions; public ConfigAccessor(Config cfg) { this.cfg = cfg; this.pollingInterval = this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY) ? this.cfg.getLong(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY) : ConfigurationKeys.DEFAULT_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL; if (this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) { this.jobConfDir = this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY); } else if (this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY)) { File localJobConfigDir = new File(this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY)); this.jobConfDir = "file://" + localJobConfigDir.getAbsolutePath(); } else { throw new IllegalArgumentException("Expected " + ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY + " or " + ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY + " properties."); } this.jobConfDirPath = new Path(this.jobConfDir); try { this.jobConfDirFileSystem = this.jobConfDirPath.getFileSystem(new Configuration()); } catch (IOException e) { throw new RuntimeException("Unable to detect job config directory file system: " + e, e); } this.JobConfigurationFileExtensions = ImmutableSet.<String>copyOf(Splitter.on(",") .omitEmptyStrings() .trimResults() .split(getJobConfigurationFileExtensionsString())); } private String getJobConfigurationFileExtensionsString() { String propValue = this.cfg.hasPath(ConfigurationKeys.JOB_CONFIG_FILE_EXTENSIONS_KEY) ? this.cfg.getString(ConfigurationKeys.JOB_CONFIG_FILE_EXTENSIONS_KEY).toLowerCase() : ConfigurationKeys.DEFAULT_JOB_CONFIG_FILE_EXTENSIONS; return propValue; } } /** * Instance of this function is passed as a parameter into other transform function, * for converting Properties object into JobSpec object. */ @AllArgsConstructor public static class JobSpecConverter implements Function<Config, JobSpec> { private final Path jobConfigDirPath; private final Optional<String> extensionToStrip; public URI computeURI(Path filePath) { // Make sure this is relative URI uri = PathUtils.relativizePath(filePath, jobConfigDirPath).toUri(); if (this.extensionToStrip.isPresent()) { uri = PathUtils.removeExtension(new Path(uri), this.extensionToStrip.get()).toUri(); } return uri; } @Nullable @Override public JobSpec apply(Config rawConfig) { URI jobConfigURI = computeURI(new Path(rawConfig.getString(ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY))); // Points to noted: // 1.To ensure the transparency of JobCatalog, need to remove the addtional // options that added through the materialization process. // 2. For files that created by user directly in the file system, there might not be // version and description provided. Set them to default then, according to JobSpec constructor. String version; if (rawConfig.hasPath(VERSION_KEY_IN_JOBSPEC)) { version = rawConfig.getString(VERSION_KEY_IN_JOBSPEC); } else { // Set the version as default. version = "1"; } String description; if (rawConfig.hasPath(DESCRIPTION_KEY_IN_JOBSPEC)) { description = rawConfig.getString(DESCRIPTION_KEY_IN_JOBSPEC); } else { // Set description as default. description = "Gobblin job " + jobConfigURI; } Config filteredConfig = rawConfig.withoutPath(FS_CATALOG_KEY_PREFIX); // The builder has null-checker. Leave the checking there. JobSpec.Builder builder = JobSpec.builder(jobConfigURI).withConfig(filteredConfig) .withDescription(description) .withVersion(version); if (rawConfig.hasPath(ConfigurationKeys.JOB_TEMPLATE_PATH)) { try { builder.withTemplate(new URI(rawConfig.getString(ConfigurationKeys.JOB_TEMPLATE_PATH))); } catch (URISyntaxException e) { throw new RuntimeException("Bad job template URI " + e, e); } } return builder.build(); } } }
1,487
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/NonObservingFSJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.IOException; import java.net.URI; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.typesafe.config.Config; import com.typesafe.config.ConfigValueFactory; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; import org.apache.gobblin.runtime.api.SpecNotFoundException; /** * The job Catalog for file system to persist the job configuration information. * This implementation does not observe for file system changes */ public class NonObservingFSJobCatalog extends FSJobCatalog { private static final Logger LOGGER = LoggerFactory.getLogger(NonObservingFSJobCatalog.class); /** * Initialize the JobCatalog, fetch all jobs in jobConfDirPath. * @param sysConfig * @throws Exception */ public NonObservingFSJobCatalog(Config sysConfig) throws IOException { super(sysConfig.withValue(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY, ConfigValueFactory.fromAnyRef(ConfigurationKeys.DISABLED_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL))); } public NonObservingFSJobCatalog(GobblinInstanceEnvironment env) throws IOException { super(env); } public NonObservingFSJobCatalog(Config sysConfig, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled) throws IOException{ super(sysConfig.withValue(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY, ConfigValueFactory.fromAnyRef(ConfigurationKeys.DISABLED_JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL)), parentMetricContext, instrumentationEnabled); } /** * Allow user to programmatically add a new JobSpec. * The method will materialized the jobSpec into real file. * * @param jobSpec The target JobSpec Object to be materialized. * Noted that the URI return by getUri is a relative path. */ @Override public synchronized void put(JobSpec jobSpec) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); try { long startTime = System.currentTimeMillis(); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobSpec.getUri()); boolean isUpdate = fs.exists(jobSpecPath); materializedJobSpec(jobSpecPath, jobSpec, this.fs); this.mutableMetrics.updatePutJobTime(startTime); if (isUpdate) { this.listeners.onUpdateJob(jobSpec); } else { this.listeners.onAddJob(jobSpec); } } catch (IOException e) { throw new RuntimeException("When persisting a new JobSpec, unexpected issues happen:" + e.getMessage()); } catch (JobSpecNotFoundException e) { throw new RuntimeException("When replacing a existed JobSpec, unexpected issue happen:" + e.getMessage()); } } /** * Allow user to programmatically delete a new JobSpec. * This method is designed to be reentrant. * @param jobURI The relative Path that specified by user, need to make it into complete path. */ @Override public synchronized void remove(URI jobURI) { remove(jobURI, false); } public synchronized void remove(URI jobURI, boolean alwaysTriggerListeners) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); try { long startTime = System.currentTimeMillis(); JobSpec jobSpec = getJobSpec(jobURI); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobURI); if (fs.exists(jobSpecPath)) { fs.delete(jobSpecPath, false); this.mutableMetrics.updateRemoveJobTime(startTime); this.listeners.onDeleteJob(jobURI, jobSpec.getVersion()); } else { LOGGER.warn("No file with URI:" + jobSpecPath + " is found. Deletion failed."); } } catch (IOException e) { throw new RuntimeException("When removing a JobConf. file, issues unexpected happen:" + e.getMessage()); } catch (SpecNotFoundException e) { LOGGER.warn("No file with URI:" + jobURI + " is found. Deletion failed."); } finally { // HelixRetriggeringJobCallable deletes the job file after submitting it to helix, // so we will have to trigger listeners regardless the existence of job file to cancel the job if (alwaysTriggerListeners) { this.listeners.onCancelJob(jobURI); } } } }
1,488
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/JobCatalogListenersList.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import org.apache.gobblin.runtime.api.JobCatalog; import org.apache.gobblin.runtime.api.JobCatalogListener; import org.apache.gobblin.runtime.api.JobCatalogListenersContainer; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.util.callbacks.CallbacksDispatcher; /** A helper class to manage a list of {@link JobCatalogListener}s for a * {@link JobCatalog}. It will dispatch the callbacks to each listener sequentially.*/ public class JobCatalogListenersList implements JobCatalogListener, JobCatalogListenersContainer, Closeable { private final CallbacksDispatcher<JobCatalogListener> _disp; public JobCatalogListenersList() { this(Optional.<Logger>absent()); } public JobCatalogListenersList(Optional<Logger> log) { _disp = new CallbacksDispatcher<JobCatalogListener>(Optional.<ExecutorService>absent(), log); } public Logger getLog() { return _disp.getLog(); } public synchronized List<JobCatalogListener> getListeners() { return _disp.getListeners(); } @Override public synchronized void addListener(JobCatalogListener newListener) { _disp.addListener(newListener); } @Override public synchronized void removeListener(JobCatalogListener oldListener) { _disp.removeListener(oldListener); } @Override public synchronized void onAddJob(JobSpec addedJob) { Preconditions.checkNotNull(addedJob); try { _disp.execCallbacks(new AddJobCallback(addedJob)); } catch (InterruptedException e) { getLog().warn("onAddJob interrupted."); } } @Override public synchronized void onDeleteJob(URI deletedJobURI, String deletedJobVersion) { Preconditions.checkNotNull(deletedJobURI); try { _disp.execCallbacks(new DeleteJobCallback(deletedJobURI, deletedJobVersion)); } catch (InterruptedException e) { getLog().warn("onDeleteJob interrupted."); } } @Override public synchronized void onUpdateJob(JobSpec updatedJob) { Preconditions.checkNotNull(updatedJob); try { _disp.execCallbacks(new UpdateJobCallback(updatedJob)); } catch (InterruptedException e) { getLog().warn("onUpdateJob interrupted."); } } @Override public synchronized void onCancelJob(URI cancelledJobURI) { Preconditions.checkNotNull(cancelledJobURI); try { _disp.execCallbacks(new CancelJobCallback(cancelledJobURI)); } catch (InterruptedException e) { getLog().warn("onCancelJob interrupted."); } } @Override public void close() throws IOException { _disp.close(); } public void callbackOneListener(Function<JobCatalogListener, Void> callback, JobCatalogListener listener) { try { _disp.execCallbacks(callback, listener); } catch (InterruptedException e) { getLog().warn("callback interrupted: "+ callback); } } @Override public void registerWeakJobCatalogListener(JobCatalogListener jobListener) { _disp.addWeakListener(jobListener); } }
1,489
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/StaticJobCatalog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.job_catalog; import java.net.URI; import java.util.Collection; import java.util.Map; import org.slf4j.Logger; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment; import org.apache.gobblin.runtime.api.JobCatalogListener; import org.apache.gobblin.runtime.api.JobSpec; import org.apache.gobblin.runtime.api.JobSpecNotFoundException; /** * A {@link org.apache.gobblin.runtime.api.JobCatalog} with a static collection of {@link JobSpec}s defined at construction time. */ public class StaticJobCatalog extends JobCatalogBase { private final Map<URI, JobSpec> jobs; public StaticJobCatalog(Collection<JobSpec> jobSpecs) { this.jobs = parseJobs(jobSpecs); } public StaticJobCatalog(Optional<Logger> log, Collection<JobSpec> jobSpecs) { super(log); this.jobs = parseJobs(jobSpecs); } public StaticJobCatalog(GobblinInstanceEnvironment env, Collection<JobSpec> jobSpecs) { super(env); this.jobs = parseJobs(jobSpecs); } public StaticJobCatalog(Optional<Logger> log, Optional<MetricContext> parentMetricContext, boolean instrumentationEnabled, Collection<JobSpec> jobSpecs) { super(log, parentMetricContext, instrumentationEnabled); this.jobs = parseJobs(jobSpecs); } private Map<URI, JobSpec> parseJobs(Collection<JobSpec> jobSpecs) { ImmutableMap.Builder<URI, JobSpec> mapBuilder = ImmutableMap.builder(); for (JobSpec jobSpec : jobSpecs) { mapBuilder.put(jobSpec.getUri(), jobSpec); } return mapBuilder.build(); } @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR", justification = "Uninitialized variable has been checked.") @Override public void addListener(JobCatalogListener jobListener) { if (this.jobs == null) { return; } for (Map.Entry<URI, JobSpec> entry : this.jobs.entrySet()) { jobListener.onAddJob(entry.getValue()); } } @Override public Collection<JobSpec> getJobs() { return this.jobs.values(); } @Override public void removeListener(JobCatalogListener jobListener) { // NOOP } @Override public JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException { return this.jobs.get(uri); } }
1,490
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/JobIssueEventHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.Objects; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.typesafe.config.Config; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.metrics.GobblinTrackingEvent; import org.apache.gobblin.metrics.event.TimingEvent; import org.apache.gobblin.runtime.util.GsonUtils; import org.apache.gobblin.util.ConfigUtils; /** * This class will forward issues received from job events to shared repository. * * It will additionally log received issues, so that they can be processed by an analytical systems to determine * the overall platform health. * */ @Slf4j public class JobIssueEventHandler { public static final String CONFIG_PREFIX = "gobblin.troubleshooter.jobIssueEventHandler."; public static final String LOG_RECEIVED_EVENTS = CONFIG_PREFIX + "logReceivedEvents"; private static final Logger issueLogger = LoggerFactory.getLogger("org.apache.gobblin.runtime.troubleshooter.JobIssueLogger"); private final MultiContextIssueRepository issueRepository; private final boolean logReceivedEvents; @Inject public JobIssueEventHandler(MultiContextIssueRepository issueRepository, Config config) { this(issueRepository, ConfigUtils.getBoolean(config, LOG_RECEIVED_EVENTS, true)); } public JobIssueEventHandler(MultiContextIssueRepository issueRepository, boolean logReceivedEvents) { this.issueRepository = Objects.requireNonNull(issueRepository); this.logReceivedEvents = logReceivedEvents; } public void processEvent(GobblinTrackingEvent event) { if (!IssueEventBuilder.isIssueEvent(event)) { return; } String contextId; try { Properties metadataProperties = new Properties(); metadataProperties.putAll(event.getMetadata()); contextId = TroubleshooterUtils.getContextIdForJob(metadataProperties); } catch (Exception ex) { log.warn("Failed to extract context id from Gobblin tracking event with timestamp " + event.getTimestamp(), ex); return; } IssueEventBuilder issueEvent = IssueEventBuilder.fromEvent(event); try { issueRepository.put(contextId, issueEvent.getIssue()); } catch (TroubleshooterException e) { log.warn(String.format("Failed to save issue to repository. Issue time: %s, code: %s", issueEvent.getIssue().getTime(), issueEvent.getIssue().getCode()), e); } if (logReceivedEvents) { logEvent(issueEvent); } } private void logEvent(IssueEventBuilder issueEvent) { ImmutableMap<String, String> metadata = issueEvent.getMetadata(); JobIssueLogEntry logEntry = new JobIssueLogEntry(); logEntry.issue = issueEvent.getIssue(); logEntry.flowGroup = metadata.getOrDefault(TimingEvent.FlowEventConstants.FLOW_GROUP_FIELD, null); logEntry.flowName = metadata.getOrDefault(TimingEvent.FlowEventConstants.FLOW_NAME_FIELD, null); logEntry.flowExecutionId = metadata.getOrDefault(TimingEvent.FlowEventConstants.FLOW_EXECUTION_ID_FIELD, null); logEntry.jobName = metadata.getOrDefault(TimingEvent.FlowEventConstants.JOB_NAME_FIELD, null); String serializedIssueEvent = GsonUtils.GSON_WITH_DATE_HANDLING.toJson(logEntry); issueLogger.info(serializedIssueEvent); } private static class JobIssueLogEntry { String flowName; String flowGroup; String flowExecutionId; String jobName; Issue issue; } }
1,491
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/NoopAutomaticTroubleshooter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import javax.inject.Singleton; import org.apache.gobblin.metrics.event.EventSubmitter; @Singleton public class NoopAutomaticTroubleshooter implements AutomaticTroubleshooter { private final NoopIssueRepository noopIssueRepository = new NoopIssueRepository(); @Override public void start() { } @Override public void stop() { } @Override public void reportJobIssuesAsEvents(EventSubmitter eventSubmitter) throws TroubleshooterException { } @Override public void refineIssues() throws TroubleshooterException { } @Override public void logIssueSummary() throws TroubleshooterException { } @Override public void logIssueDetails() throws TroubleshooterException { } @Override public String getIssueSummaryMessage() throws TroubleshooterException { return ""; } @Override public String getIssueDetailsMessage() throws TroubleshooterException { return ""; } @Override public IssueRepository getIssueRepository() { return noopIssueRepository; } }
1,492
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/MultiContextIssueRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.List; import com.google.common.util.concurrent.Service; /** * Stores issues from multiple jobs, flows and other contexts. * * For each context, there can only be one issue with a specific code. * * @see AutomaticTroubleshooter * */ public interface MultiContextIssueRepository extends Service { /** * Will return issues in the same order as they were put into the repository. * */ List<Issue> getAll(String contextId) throws TroubleshooterException; void put(String contextId, Issue issue) throws TroubleshooterException; void put(String contextId, List<Issue> issues) throws TroubleshooterException; void remove(String contextId, String issueCode) throws TroubleshooterException; }
1,493
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/InMemoryIssueRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import lombok.extern.slf4j.Slf4j; /** * In-memory repository of troubleshooter issues. * * This repository has a maximum size to avoid running out of memory when application code produces * unexpectedly large number of issues. When the repository is full, new issues will be ignored. * * When multiple issues with the same issue code are put into the repository, only the first one * will be stored. Others will be treated as duplicates, and will be discarded. * * */ @Singleton @Slf4j public class InMemoryIssueRepository implements IssueRepository { public static final int DEFAULT_MAX_SIZE = 100; private final LinkedHashMap<String, Issue> issues = new LinkedHashMap<>(); private final int maxSize; private boolean reportedOverflow = false; @Inject public InMemoryIssueRepository() { this(DEFAULT_MAX_SIZE); } public InMemoryIssueRepository(int maxSize) { this.maxSize = maxSize; } @Override public synchronized List<Issue> getAll() throws TroubleshooterException { return new ArrayList<>(issues.values()); } @Override public synchronized void put(Issue issue) throws TroubleshooterException { if (issues.size() >= maxSize) { if (!reportedOverflow) { reportedOverflow = true; log.warn("In-memory issue repository has {} elements and is now full. New issues will be ignored.", issues.size()); } return; } if (!issues.containsKey(issue.getCode())) { issues.put(issue.getCode(), issue); } } @Override public synchronized void put(Collection<Issue> issues) throws TroubleshooterException { for (Issue issue : issues) { put(issue); } } @Override public synchronized void remove(String code) throws TroubleshooterException { issues.remove(code); } @Override public synchronized void removeAll() throws TroubleshooterException { issues.clear(); } @Override public synchronized void replaceAll(Collection<Issue> issues) throws TroubleshooterException { removeAll(); put(issues); } }
1,494
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/IssueSeverity.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; public enum IssueSeverity { DEBUG, INFO, WARN, ERROR, FATAL; public boolean isEqualOrHigherThan(IssueSeverity severity) { return this.compareTo(severity) >= 0; } public boolean isEqualOrLowerThan(IssueSeverity severity) { return this.compareTo(severity) <= 0; } }
1,495
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/IssueRefinery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.List; import com.google.common.collect.ImmutableList; /** * Refinery will filter, prioritize and enhance the issues to make them more meaningful for the user. */ public interface IssueRefinery { List<Issue> refine(ImmutableList<Issue> issues); }
1,496
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/NoopIssueRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.Collection; import java.util.Collections; import java.util.List; public class NoopIssueRepository implements IssueRepository { @Override public List<Issue> getAll() throws TroubleshooterException { return Collections.emptyList(); } @Override public void put(Issue issue) throws TroubleshooterException { } @Override public void put(Collection<Issue> issues) throws TroubleshooterException { } @Override public void remove(String issueCode) throws TroubleshooterException { } @Override public void removeAll() throws TroubleshooterException { } @Override public void replaceAll(Collection<Issue> issues) throws TroubleshooterException { } }
1,497
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/TroubleshooterException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; public class TroubleshooterException extends Exception { public TroubleshooterException() { } public TroubleshooterException(String message) { super(message); } public TroubleshooterException(String message, Throwable cause) { super(message, cause); } public TroubleshooterException(Throwable cause) { super(cause); } }
1,498
0
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime
Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/troubleshooter/AutomaticTroubleshooterConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.runtime.troubleshooter; import java.util.Objects; import com.typesafe.config.Config; import javax.inject.Inject; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.util.ConfigUtils; /** * See documentation in {@link ConfigurationKeys} for explanation of settings. * */ @Getter @Builder @AllArgsConstructor public class AutomaticTroubleshooterConfig { private final boolean disabled; private final boolean disableEventReporting; @Builder.Default private int inMemoryRepositoryMaxSize = ConfigurationKeys.DEFAULT_TROUBLESHOOTER_IN_MEMORY_ISSUE_REPOSITORY_MAX_SIZE; @Inject public AutomaticTroubleshooterConfig(Config config) { Objects.requireNonNull(config, "Config cannot be null"); disabled = ConfigUtils.getBoolean(config, ConfigurationKeys.TROUBLESHOOTER_DISABLED, false); disableEventReporting = ConfigUtils.getBoolean(config, ConfigurationKeys.TROUBLESHOOTER_DISABLE_EVENT_REPORTING, false); inMemoryRepositoryMaxSize = ConfigUtils .getInt(config, ConfigurationKeys.TROUBLESHOOTER_IN_MEMORY_ISSUE_REPOSITORY_MAX_SIZE, ConfigurationKeys.DEFAULT_TROUBLESHOOTER_IN_MEMORY_ISSUE_REPOSITORY_MAX_SIZE); } }
1,499