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/troubleshooter/Issue.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.time.ZonedDateTime;
import java.util.Map;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
/**
* Issue describes a specific unique problem in the job or application.
*
* Issue can be generated from log entries, health checks, and other places.
*
* @see AutomaticTroubleshooter
*/
@Builder
@Getter
@EqualsAndHashCode
@ToString
public class Issue {
public static final int MAX_ISSUE_CODE_LENGTH = 100;
public static final int MAX_CLASSNAME_LENGTH = 1000;
private final ZonedDateTime time;
private final IssueSeverity severity;
/**
* Unique code that identifies a specific problem.
*
* It can be used for making programmatic decisions on how to handle and recover from this issue.
*
* The code length should be less than {@link Issue.MAX_ISSUE_CODE_LENGTH}
* */
private final String code;
/**
* Short, human-readable description of the issue.
*
* It should focus on what is the root cause of the problem, and what steps the user should do to resolve it.
*/
private final String summary;
/**
* Human-readable issue details that can include exception stack trace and additional information about the problem.
*/
private final String details;
/**
* Unique name of the component that produced the issue.
*
* This is a full name of the class that logged the error or generated the issue.
*
* The class name length should be less than {@link Issue.MAX_CLASSNAME_LENGTH}
* */
private final String sourceClass;
/**
* If the issue was generated from an exception, then a full exception class name should be stored here.
*
* The class name length should be less than {@link Issue.MAX_CLASSNAME_LENGTH}
*/
private final String exceptionClass;
/**
* Additional machine-readable properties of the issue.
*
* Those can be used to forward information to the system that will analyze the issues across the platform.
*/
private final Map<String, String> properties;
}
| 1,500 |
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/AutomaticTroubleshooter.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 org.apache.gobblin.metrics.event.EventSubmitter;
/**
* Automatic troubleshooter will identify and prioritize the problems with the job, and display a summary to the user.
*
* Troubleshooter will collect errors & warnings from logs and combine them with various health checks. After that
* you can {@link #refineIssues()} to prioritize them and filter out noise, and then {@link #logIssueSummary()}
* to show a human-readable list of issues.
*
* Implementation and architecture notes:
*
* We convert log messages and health check results to {@link Issue}s. They will be shown to the user at the end of
* the job log. To avoid overwhelming the user, we will only collect a fixed number of issues, and will de-duplicate
* them, so that each type of problem is shown only once.
*
* Issues will be emitted in GobblinTrackingEvents at the end of the job, so that they can be collected by Gobblin
* service, and used for future platform-wide analysis.
*
* */
public interface AutomaticTroubleshooter {
/**
* Sends the current collection of issues as GobblinTrackingEvents.
*
* Those events can be consumed by upstream and analytical systems.
*
* Can be disabled with
* {@link org.apache.gobblin.configuration.ConfigurationKeys.TROUBLESHOOTER_DISABLE_EVENT_REPORTING}.
* */
void reportJobIssuesAsEvents(EventSubmitter eventSubmitter)
throws TroubleshooterException;
/**
* This method will sort, filter and enhance the list of issues to make it more meaningful for the user.
*/
void refineIssues()
throws TroubleshooterException;
/**
* Logs a human-readable prioritized list of issues.
*
* The message will include the minimal important information about each issue.
*/
void logIssueSummary()
throws TroubleshooterException;
/**
* Logs a human-readable prioritized list of issues, including extra details.
*
* The message will include extended information about each issue, such as a stack trace and extra properties.
*/
void logIssueDetails()
throws TroubleshooterException;
/**
* Returns a human-readable prioritized list of issues as text.
*
* The message will include the minimal important information about the issue.
*
* @see #getIssueDetailsMessage()
*/
String getIssueSummaryMessage()
throws TroubleshooterException;
/**
* Returns a human-readable prioritized list of issues as text.
*
* The output includes additional information like stack traces, log sources and extra properties
*
* @see #getIssueSummaryMessage()
*/
String getIssueDetailsMessage()
throws TroubleshooterException;
IssueRepository getIssueRepository();
void start();
void stop();
}
| 1,501 |
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/NoopIssueRefinery.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 com.google.common.collect.ImmutableList;
public class NoopIssueRefinery implements IssueRefinery {
@Override
public ImmutableList<Issue> refine(ImmutableList<Issue> issues) {
return issues;
}
}
| 1,502 |
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/InMemoryMultiContextIssueRepository.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.Collections;
import java.util.List;
import java.util.Objects;
import org.apache.commons.collections4.map.LRUMap;
import com.google.common.util.concurrent.AbstractIdleService;
import com.typesafe.config.Config;
import javax.inject.Inject;
import javax.inject.Singleton;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.gobblin.service.ServiceConfigKeys;
/**
* Stores issues from multiple jobs, flows or other contexts in memory.
*
* To limit the memory consumption, it will keep only the last {@link Configuration#maxContextCount} contexts,
* and older ones will be discarded.
* */
@Singleton
public class InMemoryMultiContextIssueRepository extends AbstractIdleService implements MultiContextIssueRepository {
private final LRUMap<String, InMemoryIssueRepository> contextIssues;
private final Configuration configuration;
public InMemoryMultiContextIssueRepository() {
this(Configuration.builder().build());
}
@Inject
public InMemoryMultiContextIssueRepository(Configuration configuration) {
this.configuration = Objects.requireNonNull(configuration);
contextIssues = new LRUMap<>(configuration.getMaxContextCount());
}
@Override
public synchronized List<Issue> getAll(String contextId)
throws TroubleshooterException {
InMemoryIssueRepository issueRepository = contextIssues.getOrDefault(contextId, null);
if (issueRepository != null) {
return issueRepository.getAll();
}
return Collections.emptyList();
}
@Override
public synchronized void put(String contextId, Issue issue)
throws TroubleshooterException {
InMemoryIssueRepository issueRepository = contextIssues
.computeIfAbsent(contextId, s -> new InMemoryIssueRepository(configuration.getMaxIssuesPerContext()));
issueRepository.put(issue);
}
@Override
public synchronized void put(String contextId, List<Issue> issues)
throws TroubleshooterException {
InMemoryIssueRepository issueRepository = contextIssues
.computeIfAbsent(contextId, s -> new InMemoryIssueRepository(configuration.getMaxIssuesPerContext()));
issueRepository.put(issues);
}
@Override
public synchronized void remove(String contextId, String issueCode)
throws TroubleshooterException {
InMemoryIssueRepository issueRepository = contextIssues.getOrDefault(contextId, null);
if (issueRepository != null) {
issueRepository.remove(issueCode);
}
}
@Override
protected void startUp()
throws Exception {
}
@Override
protected void shutDown()
throws Exception {
}
@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public static class Configuration {
@Builder.Default
private int maxContextCount = ServiceConfigKeys.DEFAULT_MEMORY_ISSUE_REPO_MAX_CONTEXT_COUNT;
@Builder.Default
private int maxIssuesPerContext = ServiceConfigKeys.DEFAULT_MEMORY_ISSUE_REPO_MAX_ISSUE_PER_CONTEXT;
@Inject
public Configuration(Config innerConfig) {
this();
if (innerConfig.hasPath(ServiceConfigKeys.MEMORY_ISSUE_REPO_MAX_CONTEXT_COUNT)) {
maxContextCount = innerConfig.getInt(ServiceConfigKeys.MEMORY_ISSUE_REPO_MAX_CONTEXT_COUNT);
}
if (innerConfig.hasPath(ServiceConfigKeys.MEMORY_ISSUE_REPO_MAX_ISSUE_PER_CONTEXT)) {
maxIssuesPerContext = innerConfig.getInt(ServiceConfigKeys.MEMORY_ISSUE_REPO_MAX_ISSUE_PER_CONTEXT);
}
}
}
}
| 1,503 |
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/IssueRepository.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.List;
import javax.annotation.concurrent.ThreadSafe;
/**
* Collection of issues used by {@link AutomaticTroubleshooter}.
*
* The design assumes that there will typically be a few dozen issues per job, and the number of issues will never go
* above a few hundreds. Since the issues are displayed to the user, there is no point in overwhelming them with too
* many discovered problems.
*/
@ThreadSafe
public interface IssueRepository {
List<Issue> getAll()
throws TroubleshooterException;
/**
* Saves an issue to the repository, if it is not yet present.
*
* This method will ignore the issue, if another issues with the same code is already registered.
*/
void put(Issue issue)
throws TroubleshooterException;
/**
* @see #put(Issue)
*/
void put(Collection<Issue> issues)
throws TroubleshooterException;
void remove(String issueCode)
throws TroubleshooterException;
void removeAll()
throws TroubleshooterException;
/**
* Replaces all issues in the repository with a new collection
*/
void replaceAll(Collection<Issue> issues)
throws TroubleshooterException;
}
| 1,504 |
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/TroubleshooterUtils.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.Properties;
import org.apache.gobblin.metrics.event.TimingEvent;
public final class TroubleshooterUtils {
private TroubleshooterUtils() {
}
public static String getContextIdForJob(String flowGroup, String flowName, String flowExecutionId, String jobName) {
return flowGroup + ":" + flowName + ":" + flowExecutionId + ":" + jobName;
}
public static String getContextIdForJob(Properties props) {
return getContextIdForJob(props.getProperty(TimingEvent.FlowEventConstants.FLOW_GROUP_FIELD),
props.getProperty(TimingEvent.FlowEventConstants.FLOW_NAME_FIELD),
props.getProperty(TimingEvent.FlowEventConstants.FLOW_EXECUTION_ID_FIELD),
props.getProperty(TimingEvent.FlowEventConstants.JOB_NAME_FIELD));
}
}
| 1,505 |
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/AutomaticTroubleshooterFactory.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 com.typesafe.config.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.util.reflection.GobblinConstructorUtils;
@Slf4j
public class AutomaticTroubleshooterFactory {
private static final String TROUBLESHOOTER_CLASS = "org.apache.gobblin.troubleshooter.AutomaticTroubleshooterImpl";
/**
* Configures a troubleshooter that will be used inside Gobblin job or task.
*
* Troubleshooter will only be enabled if "gobblin-troubleshooter" modules is referenced in the application.
* If this module is missing, troubleshooter will default to a no-op implementation.
*
* In addition, even when the "gobblin-troubleshooter" module is present, troubleshooter can still be disabled
* with {@link ConfigurationKeys.TROUBLESHOOTER_DISABLED} setting.
* */
public static AutomaticTroubleshooter createForJob(Config config) {
AutomaticTroubleshooterConfig troubleshooterConfig = new AutomaticTroubleshooterConfig(config);
Class troubleshooterClass = tryGetTroubleshooterClass();
/* Automatic troubleshooter works by intercepting log4j messages, and depends on log4j package.
* Some users of Gobblin library have different version of log4j in their projects. If multiple versions of log4j
* are present in a single application, it will work incorrectly. To prevent that, we moved the troubleshooter code
* that uses log4j to a separate module. Applications that have incompatible log4j should not reference it to
* prevent log4j problems.
* */
if (troubleshooterClass == null) {
log.info("To enable Gobblin automatic troubleshooter, reference 'gobblin-troubleshooter' module in your project. "
+ "Troubleshooter will summarize the errors and warnings in the logs. "
+ "It will also identify root causes of certain problems.");
return new NoopAutomaticTroubleshooter();
} else if (troubleshooterConfig.isDisabled()) {
log.info("Gobblin automatic troubleshooter is disabled. Remove the following property to re-enable it: "
+ ConfigurationKeys.TROUBLESHOOTER_DISABLED);
return new NoopAutomaticTroubleshooter();
} else {
InMemoryIssueRepository issueRepository = new InMemoryIssueRepository();
DefaultIssueRefinery issueRefinery = new DefaultIssueRefinery();
try {
return (AutomaticTroubleshooter) GobblinConstructorUtils
.invokeLongestConstructor(troubleshooterClass, troubleshooterConfig, issueRepository, issueRefinery);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Cannot create troubleshooter instance", e);
}
}
}
private static Class tryGetTroubleshooterClass() {
try {
return Class.forName(TROUBLESHOOTER_CLASS);
} catch (ClassNotFoundException e) {
return null;
}
}
}
| 1,506 |
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/IssueEventBuilder.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.Map;
import org.apache.commons.lang.StringUtils;
import lombok.Getter;
import lombok.Setter;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.event.GobblinEventBuilder;
import org.apache.gobblin.runtime.util.GsonUtils;
/**
* The builder builds builds a specific {@link GobblinTrackingEvent} whose metadata has
* {@value GobblinEventBuilder#EVENT_TYPE} to be {@value #ISSUE_EVENT_TYPE}
*
* <p>
* Note: A {@link IssueEventBuilder} instance is not reusable
*/
public class IssueEventBuilder extends GobblinEventBuilder {
public static final String JOB_ISSUE = "JobIssue";
private static final String ISSUE_EVENT_TYPE = "IssueEvent";
private static final String METADATA_ISSUE = "issue";
@Getter
@Setter
private Issue issue;
public IssueEventBuilder(String name) {
this(name, NAMESPACE);
}
public IssueEventBuilder(String name, String namespace) {
super(name, namespace);
metadata.put(EVENT_TYPE, ISSUE_EVENT_TYPE);
}
public static boolean isIssueEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(ISSUE_EVENT_TYPE);
}
/**
* Create a {@link IssueEventBuilder} from a {@link GobblinTrackingEvent}.
* Will return null if the event is not of the correct type.
*/
public static IssueEventBuilder fromEvent(GobblinTrackingEvent event) {
if (!isIssueEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
IssueEventBuilder issueEventBuilder = new IssueEventBuilder(event.getName(), event.getNamespace());
metadata.forEach((key, value) -> {
if (METADATA_ISSUE.equals(key)) {
issueEventBuilder.issue = GsonUtils.GSON_WITH_DATE_HANDLING.fromJson(value, Issue.class);
} else {
issueEventBuilder.addMetadata(key, value);
}
});
return issueEventBuilder;
}
public static Issue getIssueFromEvent(GobblinTrackingEvent event) {
String serializedIssue = event.getMetadata().get(METADATA_ISSUE);
return GsonUtils.GSON_WITH_DATE_HANDLING.fromJson(serializedIssue, Issue.class);
}
public GobblinTrackingEvent build() {
if (this.issue == null) {
throw new IllegalStateException("Issue must be set");
}
String serializedIssue = GsonUtils.GSON_WITH_DATE_HANDLING.toJson(issue);
addMetadata(METADATA_ISSUE, serializedIssue);
return super.build();
}
}
| 1,507 |
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/DefaultIssueRefinery.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.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.ImmutableList;
/**
* Provides basic issue sorting and cleanup.
*
* Issue refining will be improved in future PRs
*/
public class DefaultIssueRefinery implements IssueRefinery {
@Override
public List<Issue> refine(ImmutableList<Issue> sourceIssues) {
LinkedList<Issue> issues = new LinkedList<>(sourceIssues);
issues.sort(Comparator.comparing(Issue::getSeverity).reversed().thenComparing(Issue::getTime));
// Kafka warnings usually don't impact the job outcome, so we are hiding them from the user
issues.removeIf(i -> i.getSeverity().isEqualOrLowerThan(IssueSeverity.WARN) && StringUtils
.containsIgnoreCase(i.getSourceClass(), "com.linkedin.kafka"));
issues.removeIf(i -> i.getSeverity().isEqualOrLowerThan(IssueSeverity.WARN) && StringUtils
.containsIgnoreCase(i.getSourceClass(), "org.apache.kafka"));
// Metrics-related issues usually don't impact the outcome of the job
moveToBottom(issues, i -> StringUtils.containsIgnoreCase(i.getSourceClass(), "org.apache.gobblin.metrics"));
return issues;
}
private void moveToBottom(LinkedList<Issue> issues, java.util.function.Predicate<Issue> predicate) {
Collection<Issue> movedIssues = issues.stream().filter(predicate).collect(Collectors.toList());
issues.removeAll(movedIssues);
issues.addAll(movedIssues);
}
}
| 1,508 |
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/kafka/HighLevelConsumer.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.kafka;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import com.codahale.metrics.Counter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AbstractIdleService;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.kafka.client.DecodeableKafkaRecord;
import org.apache.gobblin.kafka.client.GobblinConsumerRebalanceListener;
import org.apache.gobblin.kafka.client.GobblinKafkaConsumerClient;
import org.apache.gobblin.kafka.client.KafkaConsumerRecord;
import org.apache.gobblin.metrics.ContextAwareGauge;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.runtime.metrics.RuntimeMetrics;
import org.apache.gobblin.source.extractor.extract.kafka.KafkaPartition;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.ExecutorsUtils;
/**
* A high level consumer for Kafka topics. Subclasses should implement {@link HighLevelConsumer#processMessage(DecodeableKafkaRecord)}
*
* Note: each thread (queue) will block for each message until {@link #processMessage(DecodeableKafkaRecord)} returns
*
* If threads(queues) > partitions in topic, extra threads(queues) will be idle.
*
*/
@Slf4j
public abstract class HighLevelConsumer<K,V> extends AbstractIdleService {
public static final String CONSUMER_CLIENT_FACTORY_CLASS_KEY = "kafka.consumerClientClassFactory";
private static final String DEFAULT_CONSUMER_CLIENT_FACTORY_CLASS =
"org.apache.gobblin.kafka.client.Kafka09ConsumerClient$Factory";
public static final String ENABLE_AUTO_COMMIT_KEY = "enable.auto.commit";
public static final boolean DEFAULT_AUTO_COMMIT_VALUE = false;
public static final String GROUP_ID_KEY = "group.id";
// NOTE: changing this will break stored offsets
private static final String DEFAULT_GROUP_ID = "KafkaJobSpecMonitor";
public static final String OFFSET_COMMIT_NUM_RECORDS_THRESHOLD_KEY = "offsets.commit.num.records.threshold";
public static final int DEFAULT_OFFSET_COMMIT_NUM_RECORDS_THRESHOLD = 100;
public static final String OFFSET_COMMIT_TIME_THRESHOLD_SECS_KEY = "offsets.commit.time.threshold.secs";
public static final int DEFAULT_OFFSET_COMMIT_TIME_THRESHOLD_SECS = 10;
@Getter
protected final String topic;
protected final Config config;
private final int numThreads;
/**
* {@link MetricContext} for the consumer. Note this is instantiated when {@link #startUp()} is called, so
* {@link com.codahale.metrics.Metric}s used by subclasses should be instantiated in the {@link #createMetrics()} method.
*/
@Getter
private MetricContext metricContext;
protected Counter messagesRead;
@Getter
private final GobblinKafkaConsumerClient gobblinKafkaConsumerClient;
private final ScheduledExecutorService consumerExecutor;
private final ExecutorService queueExecutor;
private final BlockingQueue[] queues;
private ContextAwareGauge[] queueSizeGauges;
private final AtomicInteger recordsProcessed;
private final Map<KafkaPartition, Long> partitionOffsetsToCommit;
private final boolean enableAutoCommit;
private final int offsetsCommitNumRecordsThreshold;
private final int offsetsCommitTimeThresholdSecs;
private long lastCommitTime = System.currentTimeMillis();
protected volatile boolean shutdownRequested = false;
private static final Config FALLBACK =
ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
.put(GROUP_ID_KEY, DEFAULT_GROUP_ID)
.put(ENABLE_AUTO_COMMIT_KEY, DEFAULT_AUTO_COMMIT_VALUE)
.put(CONSUMER_CLIENT_FACTORY_CLASS_KEY, DEFAULT_CONSUMER_CLIENT_FACTORY_CLASS)
.put(OFFSET_COMMIT_NUM_RECORDS_THRESHOLD_KEY, DEFAULT_OFFSET_COMMIT_NUM_RECORDS_THRESHOLD)
.put(OFFSET_COMMIT_TIME_THRESHOLD_SECS_KEY, DEFAULT_OFFSET_COMMIT_TIME_THRESHOLD_SECS)
.build());
public HighLevelConsumer(String topic, Config config, int numThreads) {
this.topic = topic;
this.numThreads = numThreads;
this.config = config.withFallback(FALLBACK);
this.gobblinKafkaConsumerClient = createConsumerClient(this.config);
assignTopicPartitions();
this.consumerExecutor = Executors.newSingleThreadScheduledExecutor(ExecutorsUtils.newThreadFactory(Optional.of(log), Optional.of("HighLevelConsumerThread")));
this.queueExecutor = Executors.newFixedThreadPool(this.numThreads, ExecutorsUtils.newThreadFactory(Optional.of(log), Optional.of("QueueProcessor-%d")));
this.queues = new LinkedBlockingQueue[numThreads];
for(int i = 0; i < queues.length; i++) {
this.queues[i] = new LinkedBlockingQueue();
}
this.recordsProcessed = new AtomicInteger(0);
this.partitionOffsetsToCommit = new ConcurrentHashMap<>();
this.enableAutoCommit = ConfigUtils.getBoolean(config, ENABLE_AUTO_COMMIT_KEY, DEFAULT_AUTO_COMMIT_VALUE);
this.offsetsCommitNumRecordsThreshold = ConfigUtils.getInt(config, OFFSET_COMMIT_NUM_RECORDS_THRESHOLD_KEY, DEFAULT_OFFSET_COMMIT_NUM_RECORDS_THRESHOLD);
this.offsetsCommitTimeThresholdSecs = ConfigUtils.getInt(config, OFFSET_COMMIT_TIME_THRESHOLD_SECS_KEY, DEFAULT_OFFSET_COMMIT_TIME_THRESHOLD_SECS);
}
protected GobblinKafkaConsumerClient createConsumerClient(Config config) {
String kafkaConsumerClientClass = config.getString(CONSUMER_CLIENT_FACTORY_CLASS_KEY);
log.info("Creating consumer client of class {} with config {}", kafkaConsumerClientClass, config);
try {
Class clientFactoryClass = Class.forName(kafkaConsumerClientClass);
final GobblinKafkaConsumerClient.GobblinKafkaConsumerClientFactory factory =
(GobblinKafkaConsumerClient.GobblinKafkaConsumerClientFactory)
ConstructorUtils.invokeConstructor(clientFactoryClass);
return factory.create(config);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Failed to instantiate Kafka consumer client " + kafkaConsumerClientClass, e);
}
}
/*
The default implementation of this method subscribes to the given topic and uses the default Kafka logic to split
partitions of the topic among all consumers in the group and start consuming from the last committed offset for the
partition. Override this method to assign partitions and initialize offsets using different logic.
*/
protected void assignTopicPartitions() {
// On Partition rebalance, commit existing offsets and reset.
this.gobblinKafkaConsumerClient.subscribe(this.topic, new GobblinConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<KafkaPartition> partitions) {
copyAndCommit();
partitionOffsetsToCommit.clear();
}
@Override
public void onPartitionsAssigned(Collection<KafkaPartition> partitions) {
// No op
}
});
}
/**
* Called once on {@link #startUp()} to start metrics.
*/
@VisibleForTesting
protected void buildMetricsContextAndMetrics() {
this.metricContext = Instrumented.getMetricContext(new org.apache.gobblin.configuration.State(ConfigUtils.configToProperties(config)),
this.getClass(), getTagsForMetrics());
createMetrics();
}
@VisibleForTesting
protected void shutdownMetrics() throws IOException {
if (this.metricContext != null) {
this.metricContext.close();
}
}
/**
* Instantiates {@link com.codahale.metrics.Metric}s. Called once in {@link #startUp()}. Subclasses should override
* this method to instantiate their own metrics.
*/
protected void createMetrics() {
String prefix = getMetricsPrefix();
this.messagesRead = this.metricContext.counter(prefix +
RuntimeMetrics.GOBBLIN_KAFKA_HIGH_LEVEL_CONSUMER_MESSAGES_READ);
this.queueSizeGauges = new ContextAwareGauge[numThreads];
for (int i = 0; i < numThreads; i++) {
// An 'effectively' final variable is needed inside the lambda expression below
int finalI = i;
this.queueSizeGauges[i] = this.metricContext.newContextAwareGauge(prefix +
RuntimeMetrics.GOBBLIN_KAFKA_HIGH_LEVEL_CONSUMER_QUEUE_SIZE_PREFIX + "-" + i,
() -> queues[finalI].size());
}
}
/**
* Used by child classes to distinguish prefixes from one another
*/
protected String getMetricsPrefix() {
return "";
}
/**
* @return Tags to be applied to the {@link MetricContext} in this object. Called once in {@link #startUp()}.
* Subclasses should override this method to add additional tags.
*/
protected List<Tag<?>> getTagsForMetrics() {
List<Tag<?>> tags = Lists.newArrayList();
tags.add(new Tag<>(RuntimeMetrics.TOPIC, this.topic));
tags.add(new Tag<>(RuntimeMetrics.GROUP_ID, this.config.getString(GROUP_ID_KEY)));
return tags;
}
/**
* Called every time a message is read from the queue. Implementation must be thread-safe if {@link #numThreads} is
* set larger than 1.
*/
protected abstract void processMessage(DecodeableKafkaRecord<K,V> message);
@Override
protected void startUp() {
buildMetricsContextAndMetrics();
// Method that starts threads that processes queues
processQueues();
// Main thread that constantly polls messages from kafka
consumerExecutor.execute(() -> {
while (!shutdownRequested) {
consume();
}
});
}
/**
* Consumes {@link KafkaConsumerRecord}s and adds to a queue
* Note: All records from a KafkaPartition are added to the same queue.
* A queue can contain records from multiple partitions if partitions > numThreads(queues)
*/
private void consume() {
try {
Iterator<KafkaConsumerRecord> itr = gobblinKafkaConsumerClient.consume();
// TODO: we may be committing too early and only want to commit after process messages
if(!enableAutoCommit) {
commitOffsets();
}
while (itr.hasNext()) {
KafkaConsumerRecord record = itr.next();
int idx = record.getPartition() % numThreads;
queues[idx].put(record);
}
} catch (InterruptedException e) {
log.warn("Exception encountered while consuming records and adding to queue {}", e);
Thread.currentThread().interrupt();
}
}
/**
* Assigns a queue to each thread of the {@link #queueExecutor}
* Note: Assumption here is that {@link #numThreads} is same a number of queues
*/
private void processQueues() {
for(BlockingQueue queue : queues) {
queueExecutor.execute(new QueueProcessor(queue));
}
}
/**
* Commits offsets to kafka
*/
private void commitOffsets() {
if(shouldCommitOffsets()) {
copyAndCommit();
}
}
@VisibleForTesting
protected void commitOffsets(Map<KafkaPartition, Long> partitionOffsets) {
this.gobblinKafkaConsumerClient.commitOffsetsAsync(partitionOffsets);
}
private void copyAndCommit() {
Map<KafkaPartition, Long> copy = new HashMap<>(partitionOffsetsToCommit);
recordsProcessed.set(0);
lastCommitTime = System.currentTimeMillis();
commitOffsets(copy);
}
private boolean shouldCommitOffsets() {
return recordsProcessed.intValue() >= offsetsCommitNumRecordsThreshold || ((System.currentTimeMillis() - lastCommitTime) / 1000 >= offsetsCommitTimeThresholdSecs);
}
@Override
public void shutDown() {
shutdownRequested = true;
ExecutorsUtils.shutdownExecutorService(this.consumerExecutor, Optional.of(log), 5000, TimeUnit.MILLISECONDS);
ExecutorsUtils.shutdownExecutorService(this.queueExecutor, Optional.of(log), 5000, TimeUnit.MILLISECONDS);
try {
this.gobblinKafkaConsumerClient.close();
this.shutdownMetrics();
} catch (IOException e) {
log.warn("Failed to shut down consumer client or metrics ", e);
}
}
/**
* Polls a {@link BlockingQueue} indefinitely for {@link KafkaConsumerRecord}
* Processes each record and maintains a count for #recordsProcessed
* Also records the latest offset for every {@link KafkaPartition} if auto commit is disabled
* Note: Messages in this queue will always be in order for every {@link KafkaPartition}
*/
class QueueProcessor implements Runnable {
private final BlockingQueue<KafkaConsumerRecord> queue;
public QueueProcessor(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
log.info("Starting queue processing.. " + Thread.currentThread().getName());
try {
while (true) {
KafkaConsumerRecord record = queue.take();
messagesRead.inc();
HighLevelConsumer.this.processMessage((DecodeableKafkaRecord)record);
recordsProcessed.incrementAndGet();
if(!HighLevelConsumer.this.enableAutoCommit) {
KafkaPartition partition = new KafkaPartition.Builder().withId(record.getPartition()).withTopicName(HighLevelConsumer.this.topic).build();
// Committed offset should always be the offset of the next record to be read (hence +1)
partitionOffsetsToCommit.put(partition, record.getOffset() + 1);
}
}
} catch (InterruptedException e) {
log.warn("Encountered exception while processing queue ", e);
// TODO: evaluate whether we should interrupt the thread or continue processing
Thread.currentThread().interrupt();
}
}
}
public Long calcMillisSince(Long timestamp) {
return System.currentTimeMillis() - timestamp;
}
}
| 1,509 |
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/task/TaskFactory.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.task;
import org.apache.gobblin.publisher.DataPublisher;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.TaskContext;
/**
* Builds {@link TaskIFace} and {@link DataPublisher}s for a Gobblin execution.
*/
public interface TaskFactory {
/**
* Builds a {@link TaskIFace} for the input {@link TaskContext}.
*/
TaskIFace createTask(TaskContext taskContext);
/**
* Build a {@link DataPublisher} for the input {@link org.apache.gobblin.runtime.JobState.DatasetState}.
*/
DataPublisher createDataPublisher(JobState.DatasetState datasetState);
}
| 1,510 |
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/task/NoopTask.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.task;
import org.apache.gobblin.publisher.DataPublisher;
import org.apache.gobblin.publisher.NoopPublisher;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.TaskContext;
import org.apache.gobblin.source.workunit.WorkUnit;
/**
* A task that does nothing. Usually used for transferring state from one job to the next.
*/
public class NoopTask extends BaseAbstractTask {
/**
* @return A {@link WorkUnit} that will run a {@link NoopTask}.
*/
public static WorkUnit noopWorkunit() {
WorkUnit workUnit = new WorkUnit();
TaskUtils.setTaskFactoryClass(workUnit, Factory.class);
return workUnit;
}
@Override
public boolean isSpeculativeExecutionSafe() {
return true;
}
/**
* The factory for a {@link NoopTask}.
*/
public static class Factory implements TaskFactory {
@Override
public TaskIFace createTask(TaskContext taskContext) {
return new NoopTask(taskContext);
}
@Override
public DataPublisher createDataPublisher(JobState.DatasetState datasetState) {
return new NoopPublisher(datasetState);
}
}
private NoopTask(TaskContext taskContext) {
super(taskContext);
}
}
| 1,511 |
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/task/FailedTask.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.task;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.publisher.DataPublisher;
import org.apache.gobblin.publisher.NoopPublisher;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.TaskContext;
import org.apache.gobblin.source.workunit.WorkUnit;
/**
* A task which raise an exception when run
*/
public class FailedTask extends BaseAbstractTask {
public FailedTask (TaskContext taskContext) {
super(taskContext);
}
public void commit() {
this.workingState = WorkUnitState.WorkingState.FAILED;
}
@Override
public void run() {
this.workingState = WorkUnitState.WorkingState.FAILED;
}
public static class FailedWorkUnit extends WorkUnit {
public FailedWorkUnit () {
super ();
TaskUtils.setTaskFactoryClass(this, FailedTaskFactory.class);
}
}
public static class FailedTaskFactory implements TaskFactory {
@Override
public TaskIFace createTask(TaskContext taskContext) {
return new FailedTask(taskContext);
}
@Override
public DataPublisher createDataPublisher(JobState.DatasetState datasetState) {
return new NoopPublisher(datasetState);
}
}
}
| 1,512 |
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/task/BaseAbstractTask.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.task;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.runtime.TaskContext;
import org.apache.gobblin.runtime.util.TaskMetrics;
/**
* A base implementation of {@link TaskIFace}.
*/
public abstract class BaseAbstractTask implements TaskIFace {
protected WorkUnitState.WorkingState workingState = WorkUnitState.WorkingState.PENDING;
protected MetricContext metricContext;
public BaseAbstractTask(TaskContext taskContext) {
this.metricContext = TaskMetrics.get(taskContext.getTaskState()).getMetricContext();
}
/**
* Overriding methods should implement the logic of this task
* and update the {@link BaseAbstractTask#workingState} accordingly
*/
@Override
public void run() {
this.workingState = WorkUnitState.WorkingState.SUCCESSFUL;
}
/**
* The logic to run at committing phase.
* Overriding methods should update the {@link BaseAbstractTask#workingState} based on the execution state of the task
*/
@Override
public void commit() {
this.workingState = WorkUnitState.WorkingState.SUCCESSFUL;
}
@Override
public State getPersistentState() {
return new State();
}
@Override
public State getExecutionMetadata() {
return new State();
}
@Override
public WorkUnitState.WorkingState getWorkingState() {
return this.workingState;
}
@Override
public void shutdown() {
if (getWorkingState() == WorkUnitState.WorkingState.PENDING
|| getWorkingState() == WorkUnitState.WorkingState.RUNNING) {
this.workingState = WorkUnitState.WorkingState.CANCELLED;
}
}
@Override
public boolean awaitShutdown(long timeoutMillis) {
return true;
}
@Override
public String getProgress() {
return getWorkingState().toString();
}
@Override
public boolean isSpeculativeExecutionSafe() {
return false;
}
}
| 1,513 |
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/task/TaskIFaceWrapper.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.task;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.runtime.Task;
import org.apache.gobblin.runtime.TaskContext;
import org.apache.gobblin.runtime.TaskState;
import org.apache.gobblin.runtime.TaskStateTracker;
import org.apache.gobblin.runtime.fork.Fork;
/**
* An extension of {@link Task} that wraps a generic {@link TaskIFace} for backwards compatibility.
*/
public class TaskIFaceWrapper extends Task {
private final TaskIFace underlyingTask;
private final TaskContext taskContext;
private final String jobId;
private final String taskId;
private final CountDownLatch countDownLatch;
private final TaskStateTracker taskStateTracker;
private int retryCount = 0;
public TaskIFaceWrapper(TaskIFace underlyingTask, TaskContext taskContext, CountDownLatch countDownLatch,
TaskStateTracker taskStateTracker) {
super();
this.underlyingTask = underlyingTask;
this.taskContext = taskContext;
this.jobId = taskContext.getTaskState().getJobId();
this.taskId = taskContext.getTaskState().getTaskId();
this.countDownLatch = countDownLatch;
this.taskStateTracker = taskStateTracker;
}
@Override
public boolean awaitShutdown(long timeoutInMillis) throws InterruptedException {
return this.underlyingTask.awaitShutdown(timeoutInMillis);
}
@Override
public void shutdown() {
this.underlyingTask.shutdown();
}
@Override
public String getProgress() {
return this.underlyingTask.getProgress();
}
@Override
public void run() {
try {
this.underlyingTask.run();
} finally {
this.taskStateTracker.onTaskRunCompletion(this);
}
}
@Override
public String getJobId() {
return this.jobId;
}
@Override
public String getTaskId() {
return this.taskId;
}
@Override
public TaskContext getTaskContext() {
return this.taskContext;
}
@Override
public TaskState getTaskState() {
TaskState taskState = this.taskContext.getTaskState();
taskState.setTaskId(getTaskId());
taskState.setJobId(getJobId());
taskState.setWorkingState(getWorkingState());
taskState.addAll(getExecutionMetadata());
taskState.addAll(getPersistentState());
return taskState;
}
@Override
public State getPersistentState() {
return this.underlyingTask.getPersistentState();
}
@Override
public State getExecutionMetadata() {
return this.underlyingTask.getExecutionMetadata();
}
@Override
public WorkUnitState.WorkingState getWorkingState() {
return this.underlyingTask.getWorkingState();
}
@Override
public List<Optional<Fork>> getForks() {
return Lists.newArrayList();
}
@Override
public void updateRecordMetrics() {
}
@Override
public void updateByteMetrics() {
}
@Override
public void incrementRetryCount() {
this.retryCount++;
}
@Override
public int getRetryCount() {
return this.retryCount;
}
@Override
public void markTaskCompletion() {
if (this.countDownLatch != null) {
this.countDownLatch.countDown();
}
}
@Override
public String toString() {
return this.underlyingTask.toString();
}
@Override
public void commit() {
this.underlyingTask.commit();
this.taskStateTracker.onTaskCommitCompletion(this);
}
@Override
protected void submitTaskCommittedEvent() {
}
@Override
public boolean isSpeculativeExecutionSafe() {
return this.underlyingTask.isSpeculativeExecutionSafe();
}
/**
* return true if the task is successfully cancelled.
* This method is a copy of the method in parent class.
* We need this copy so TaskIFaceWrapper variables are not shared between this class and its parent class
* @return
*/
@Override
public synchronized boolean cancel() {
if (this.taskFuture != null && this.taskFuture.cancel(true)) {
this.taskStateTracker.onTaskRunCompletion(this);
return true;
} else {
return false;
}
}
}
| 1,514 |
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/task/TaskIFace.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.task;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* The interface that a task to be run in Gobblin should implement.
*/
@Alpha
public interface TaskIFace extends Runnable {
/**
* Execute the bulk of the work for this task. Due to possible speculative execution, all operations in this method
* should be attempt-isolated.
*/
void run();
/**
* Commit the data to the job staging location. This method is guaranteed to be called only once per task, even if
* a task is attempted in multiple containers.
*/
void commit();
/**
* @return The persistent state for this task. This is the state that will be available in the next Gobblin execution.
*/
State getPersistentState();
/**
* @return The metadata corresponding to this task execution. This metadata will be available to the publisher and may
* be viewable by the user, but may not be stored for the next Gobblin execution.
*/
State getExecutionMetadata();
/**
* @return The current working state of the task.
*/
WorkUnitState.WorkingState getWorkingState();
/**
* Prematurely shutdown the task.
*/
void shutdown();
/**
* Block until the task finishes shutting down. This method is guaranteed to only be called after {@link #shutdown()}
* is called.
* @param timeoutMillis The method should return after this many millis regardless of the shutdown of the task.
* @return true if the task shut down correctly.
* @throws InterruptedException
*/
boolean awaitShutdown(long timeoutMillis) throws InterruptedException;
/**
* @return a string describing the progress of this task.
*/
String getProgress();
/**
* @return true if the {@link #run()} method is safe to be executed in various executors at the same time.
*/
boolean isSpeculativeExecutionSafe();
}
| 1,515 |
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/task/TaskUtils.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.task;
import com.google.common.base.Optional;
import org.apache.gobblin.configuration.State;
/**
* Task utilities.
*/
public class TaskUtils {
private static final String TASK_FACTORY_CLASS = "org.apache.gobblin.runtime.taskFactoryClass";
/**
* Parse the {@link TaskFactory} in the state if one is defined.
*/
public static Optional<TaskFactory> getTaskFactory(State state) {
try {
if (state.contains(TASK_FACTORY_CLASS)) {
return Optional.of((TaskFactory) Class.forName(state.getProp(TASK_FACTORY_CLASS)).newInstance());
} else {
return Optional.absent();
}
} catch (ReflectiveOperationException roe) {
throw new RuntimeException("Could not create task factory.", roe);
}
}
/**
* Define the {@link TaskFactory} that should be used to run this task.
*/
public static void setTaskFactoryClass(State state, Class<? extends TaskFactory> klazz) {
state.setProp(TASK_FACTORY_CLASS, klazz.getName());
}
}
| 1,516 |
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/instance/StandardGobblinInstanceDriver.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.instance;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Service;
import com.google.common.util.concurrent.ServiceManager;
import com.typesafe.config.ConfigFactory;
import org.apache.gobblin.broker.SharedResourcesBrokerFactory;
import org.apache.gobblin.broker.SharedResourcesBrokerImpl;
import org.apache.gobblin.broker.SimpleScope;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.runtime.api.Configurable;
import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment;
import org.apache.gobblin.runtime.api.GobblinInstanceLauncher;
import org.apache.gobblin.runtime.api.GobblinInstancePlugin;
import org.apache.gobblin.runtime.api.GobblinInstancePluginFactory;
import org.apache.gobblin.runtime.api.JobCatalog;
import org.apache.gobblin.runtime.api.JobExecutionLauncher;
import org.apache.gobblin.runtime.api.JobSpecScheduler;
import org.apache.gobblin.runtime.job_catalog.FSJobCatalog;
import org.apache.gobblin.runtime.job_catalog.ImmutableFSJobCatalog;
import org.apache.gobblin.runtime.job_catalog.InMemoryJobCatalog;
import org.apache.gobblin.runtime.job_exec.JobLauncherExecutionDriver;
import org.apache.gobblin.runtime.plugins.email.EmailNotificationPlugin;
import org.apache.gobblin.runtime.scheduler.ImmediateJobSpecScheduler;
import org.apache.gobblin.runtime.scheduler.QuartzJobSpecScheduler;
import org.apache.gobblin.runtime.std.DefaultConfigurableImpl;
import org.apache.gobblin.util.ClassAliasResolver;
import org.apache.gobblin.util.ConfigUtils;
/** A simple wrapper {@link DefaultGobblinInstanceDriverImpl} that will instantiate necessary
* sub-components (e.g. {@link JobCatalog}, {@link JobSpecScheduler}, {@link JobExecutionLauncher}
* and it will manage their lifecycle. */
public class StandardGobblinInstanceDriver extends DefaultGobblinInstanceDriverImpl {
public static final String INSTANCE_CFG_PREFIX = "gobblin.instance";
/** A comma-separated list of class names or aliases of {@link GobblinInstancePluginFactory} for
* plugins to be instantiated with this instance. */
public static final String PLUGINS_KEY = "plugins";
public static final String PLUGINS_FULL_KEY = INSTANCE_CFG_PREFIX + "." + PLUGINS_KEY;
private ServiceManager _subservices;
private final List<GobblinInstancePlugin> _plugins;
protected StandardGobblinInstanceDriver(String instanceName, Configurable sysConfig,
JobCatalog jobCatalog,
JobSpecScheduler jobScheduler, JobExecutionLauncher jobLauncher,
Optional<MetricContext> instanceMetricContext,
Optional<Logger> log,
List<GobblinInstancePluginFactory> plugins,
SharedResourcesBroker<GobblinScopeTypes> instanceBroker) {
super(instanceName, sysConfig, jobCatalog, jobScheduler, jobLauncher, instanceMetricContext, log, instanceBroker);
List<Service> componentServices = new ArrayList<>();
checkComponentService(getJobCatalog(), componentServices);
checkComponentService(getJobScheduler(), componentServices);
checkComponentService(getJobLauncher(), componentServices);
_plugins = createPlugins(plugins, componentServices);
if (componentServices.size() > 0) {
_subservices = new ServiceManager(componentServices);
}
}
private List<GobblinInstancePlugin> createPlugins(List<GobblinInstancePluginFactory> plugins,
List<Service> componentServices) {
List<GobblinInstancePlugin> res = new ArrayList<>();
for (GobblinInstancePluginFactory pluginFactory: plugins) {
Optional<GobblinInstancePlugin> plugin = createPlugin(this, pluginFactory, componentServices);
if (plugin.isPresent()) {
res.add(plugin.get());
}
}
return res;
}
static Optional<GobblinInstancePlugin> createPlugin(StandardGobblinInstanceDriver instance,
GobblinInstancePluginFactory pluginFactory, List<Service> componentServices) {
instance.getLog().info("Instantiating a plugin of type: " + pluginFactory);
try {
GobblinInstancePlugin plugin = pluginFactory.createPlugin(instance);
componentServices.add(plugin);
instance.getLog().info("Instantiated plugin: " + plugin);
return Optional.of(plugin);
}
catch (RuntimeException e) {
instance.getLog().warn("Failed to create plugin: " + e, e);
}
return Optional.absent();
}
@Override
protected void startUp() throws Exception {
getLog().info("Starting driver ...");
if (null != _subservices) {
getLog().info("Starting subservices. Timeout is {} ms", getInstanceCfg().getStartTimeoutMs());
long startTime = System.currentTimeMillis();
_subservices.startAsync();
_subservices.awaitHealthy(getInstanceCfg().getStartTimeoutMs(), TimeUnit.MILLISECONDS);
getLog().info("All subservices have been started. Time waited is {} ms", System.currentTimeMillis() - startTime);
}
else {
getLog().info("No subservices found.");
}
super.startUp();
}
private void checkComponentService(Object component, List<Service> componentServices) {
if (component instanceof Service) {
componentServices.add((Service)component);
}
}
@Override protected void shutDown() throws Exception {
getLog().info("Shutting down driver ...");
super.shutDown();
if (null != _subservices) {
getLog().info("Shutting down subservices ...");
_subservices.stopAsync();
_subservices.awaitStopped(getInstanceCfg().getShutdownTimeoutMs(), TimeUnit.MILLISECONDS);
getLog().info("All subservices have been shutdown.");
}
}
public static Builder builder() {
return new Builder();
}
/**
* A builder for StandardGobblinInstanceDriver instances. The goal is to be convention driven
* rather than configuration.
*
* <p>Conventions:
* <ul>
* <li> Logger uses the instance name as a category
* <li> Default implementations of JobCatalog, JobSpecScheduler, JobExecutionLauncher use the
* logger as their logger.
* </ul>
*
*/
public static class Builder implements GobblinInstanceEnvironment {
private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger(0);
private Optional<GobblinInstanceEnvironment> _instanceEnv =
Optional.<GobblinInstanceEnvironment>absent();
private Optional<String> _instanceName = Optional.absent();
private Optional<Logger> _log = Optional.absent();
private Optional<JobCatalog> _jobCatalog = Optional.absent();
private Optional<JobSpecScheduler> _jobScheduler = Optional.absent();
private Optional<JobExecutionLauncher> _jobLauncher = Optional.absent();
private Optional<MetricContext> _metricContext = Optional.absent();
private Optional<Boolean> _instrumentationEnabled = Optional.absent();
private Optional<SharedResourcesBroker<GobblinScopeTypes>> _instanceBroker = Optional.absent();
private List<GobblinInstancePluginFactory> _plugins = new ArrayList<>();
private final ClassAliasResolver<GobblinInstancePluginFactory> _aliasResolver =
new ClassAliasResolver<>(GobblinInstancePluginFactory.class);
public Builder(Optional<GobblinInstanceEnvironment> instanceLauncher) {
_instanceEnv = instanceLauncher;
}
/** Constructor with no Gobblin instance launcher */
public Builder() {
}
/** Constructor with a launcher */
public Builder(GobblinInstanceLauncher instanceLauncher) {
this();
withInstanceEnvironment(instanceLauncher);
}
public Builder withInstanceEnvironment(GobblinInstanceEnvironment instanceLauncher) {
Preconditions.checkNotNull(instanceLauncher);
_instanceEnv = Optional.of(instanceLauncher);
return this;
}
public Optional<GobblinInstanceEnvironment> getInstanceEnvironment() {
return _instanceEnv;
}
public String getDefaultInstanceName() {
if (_instanceEnv.isPresent()) {
return _instanceEnv.get().getInstanceName();
}
else {
return StandardGobblinInstanceDriver.class.getName() + "-" +
INSTANCE_COUNTER.getAndIncrement();
}
}
@Override
public String getInstanceName() {
if (! _instanceName.isPresent()) {
_instanceName = Optional.of(getDefaultInstanceName());
}
return _instanceName.get();
}
public Builder withInstanceName(String instanceName) {
_instanceName = Optional.of(instanceName);
return this;
}
public Logger getDefaultLog() {
return _instanceEnv.isPresent() ? _instanceEnv.get().getLog() :
LoggerFactory.getLogger(getInstanceName());
}
@Override
public Logger getLog() {
if (! _log.isPresent()) {
_log = Optional.of(getDefaultLog());
}
return _log.get();
}
public Builder withLog(Logger log) {
_log = Optional.of(log);
return this;
}
public JobCatalog getDefaultJobCatalog() {
return new InMemoryJobCatalog(this);
}
public JobCatalog getJobCatalog() {
if (! _jobCatalog.isPresent()) {
_jobCatalog = Optional.of(getDefaultJobCatalog());
}
return _jobCatalog.get();
}
public Builder withJobCatalog(JobCatalog jobCatalog) {
_jobCatalog = Optional.of(jobCatalog);
return this;
}
public Builder withInMemoryJobCatalog() {
return withJobCatalog(new InMemoryJobCatalog(this));
}
public Builder withFSJobCatalog() {
try {
return withJobCatalog(new FSJobCatalog(this));
} catch (IOException e) {
throw new RuntimeException("Unable to create FS Job Catalog: " + e, e);
}
}
public Builder withImmutableFSJobCatalog() {
try {
return withJobCatalog(new ImmutableFSJobCatalog(this));
} catch (IOException e) {
throw new RuntimeException("Unable to create FS Job Catalog: " + e, e);
}
}
public JobSpecScheduler getDefaultJobScheduler() {
return new ImmediateJobSpecScheduler(Optional.of(getLog()));
}
public JobSpecScheduler getJobScheduler() {
if (!_jobScheduler.isPresent()) {
_jobScheduler = Optional.of(getDefaultJobScheduler());
}
return _jobScheduler.get();
}
public Builder withJobScheduler(JobSpecScheduler jobScheduler) {
_jobScheduler = Optional.of(jobScheduler);
return this;
}
public Builder withImmediateJobScheduler() {
return withJobScheduler(new ImmediateJobSpecScheduler(Optional.of(getLog())));
}
public Builder withQuartzJobScheduler() {
return withJobScheduler(new QuartzJobSpecScheduler(this));
}
public JobExecutionLauncher getDefaultJobLauncher() {
JobLauncherExecutionDriver.Launcher res =
new JobLauncherExecutionDriver.Launcher().withGobblinInstanceEnvironment(this);
return res;
}
public JobExecutionLauncher getJobLauncher() {
if (! _jobLauncher.isPresent()) {
_jobLauncher = Optional.of(getDefaultJobLauncher());
}
return _jobLauncher.get();
}
public Builder withJobLauncher(JobExecutionLauncher jobLauncher) {
_jobLauncher = Optional.of(jobLauncher);
return this;
}
public Builder withMetricContext(MetricContext instanceMetricContext) {
_metricContext = Optional.of(instanceMetricContext);
return this;
}
@Override
public MetricContext getMetricContext() {
if (!_metricContext.isPresent()) {
_metricContext = Optional.of(getDefaultMetricContext());
}
return _metricContext.get();
}
public MetricContext getDefaultMetricContext() {
org.apache.gobblin.configuration.State fakeState =
new org.apache.gobblin.configuration.State(getSysConfig().getConfigAsProperties());
List<Tag<?>> tags = new ArrayList<>();
tags.add(new Tag<>(StandardMetrics.INSTANCE_NAME_TAG, getInstanceName()));
MetricContext res = Instrumented.getMetricContext(fakeState,
StandardGobblinInstanceDriver.class, tags);
return res;
}
public Builder withInstanceBroker(SharedResourcesBroker<GobblinScopeTypes> broker) {
_instanceBroker = Optional.of(broker);
return this;
}
@Override
public SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker() {
if (!_instanceBroker.isPresent()) {
_instanceBroker = Optional.of(getDefaultInstanceBroker());
}
return _instanceBroker.get();
}
public SharedResourcesBroker<GobblinScopeTypes> getDefaultInstanceBroker() {
SharedResourcesBrokerImpl<GobblinScopeTypes> globalBroker =
SharedResourcesBrokerFactory.createDefaultTopLevelBroker(getSysConfig().getConfig(),
GobblinScopeTypes.GLOBAL.defaultScopeInstance());
return globalBroker.newSubscopedBuilder(new SimpleScope<>(GobblinScopeTypes.INSTANCE, getInstanceName())).build();
}
public StandardGobblinInstanceDriver build() {
Configurable sysConfig = getSysConfig();
return new StandardGobblinInstanceDriver(getInstanceName(), sysConfig, getJobCatalog(),
getJobScheduler(),
getJobLauncher(),
isInstrumentationEnabled() ? Optional.of(getMetricContext()) :
Optional.<MetricContext>absent(),
Optional.of(getLog()),
getPlugins(),
getInstanceBroker()
);
}
@Override public Configurable getSysConfig() {
return _instanceEnv.isPresent() ? _instanceEnv.get().getSysConfig() :
DefaultConfigurableImpl.createFromConfig(ConfigFactory.load());
}
public Builder withInstrumentationEnabled(boolean enabled) {
_instrumentationEnabled = Optional.of(enabled);
return this;
}
public boolean getDefaultInstrumentationEnabled() {
return GobblinMetrics.isEnabled(getSysConfig().getConfig());
}
@Override
public boolean isInstrumentationEnabled() {
if (!_instrumentationEnabled.isPresent()) {
_instrumentationEnabled = Optional.of(getDefaultInstrumentationEnabled());
}
return _instrumentationEnabled.get();
}
@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();
}
/**
* Returns the list of plugins as defined in the system configuration. These are the
* defined in the PLUGINS_FULL_KEY config option.
* The list also includes plugins that are automatically added by gobblin.
* */
public List<GobblinInstancePluginFactory> getDefaultPlugins() {
List<String> pluginNames =
ConfigUtils.getStringList(getSysConfig().getConfig(), PLUGINS_FULL_KEY);
List<GobblinInstancePluginFactory> pluginFactories = Lists.newArrayList();
// By default email notification plugin is added.
if (!ConfigUtils.getBoolean(getSysConfig().getConfig(), EmailNotificationPlugin.EMAIL_NOTIFICATIONS_DISABLED_KEY,
EmailNotificationPlugin.EMAIL_NOTIFICATIONS_DISABLED_DEFAULT)) {
pluginFactories.add(new EmailNotificationPlugin.Factory());
}
pluginFactories.addAll(Lists.transform(pluginNames, new Function<String, GobblinInstancePluginFactory>() {
@Override public GobblinInstancePluginFactory apply(String input) {
Class<? extends GobblinInstancePluginFactory> factoryClass;
try {
factoryClass = _aliasResolver.resolveClass(input);
return factoryClass.newInstance();
} catch (ClassNotFoundException|InstantiationException|IllegalAccessException e) {
throw new RuntimeException("Unable to instantiate plugin factory " + input + ": " + e, e);
}
}
}));
return pluginFactories;
}
public List<GobblinInstancePluginFactory> getPlugins() {
List<GobblinInstancePluginFactory> res = new ArrayList<>(getDefaultPlugins());
res.addAll(_plugins);
return res;
}
public Builder addPlugin(GobblinInstancePluginFactory pluginFactory) {
_plugins.add(pluginFactory);
return this;
}
}
public List<GobblinInstancePlugin> getPlugins() {
return _plugins;
}
}
| 1,517 |
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/instance/DefaultGobblinInstanceDriverImpl.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.instance;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractIdleService;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.runtime.JobState.RunningState;
import org.apache.gobblin.runtime.api.Configurable;
import org.apache.gobblin.runtime.api.GobblinInstanceDriver;
import org.apache.gobblin.runtime.api.GobblinInstanceLauncher.ConfigAccessor;
import org.apache.gobblin.runtime.api.JobCatalog;
import org.apache.gobblin.runtime.api.JobExecutionDriver;
import org.apache.gobblin.runtime.api.JobExecutionLauncher;
import org.apache.gobblin.runtime.api.JobExecutionMonitor;
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.JobSpecMonitorFactory;
import org.apache.gobblin.runtime.api.JobSpecScheduler;
import org.apache.gobblin.runtime.api.MutableJobCatalog;
import org.apache.gobblin.runtime.job_exec.JobLauncherExecutionDriver;
import org.apache.gobblin.runtime.job_spec.ResolvedJobSpec;
import org.apache.gobblin.runtime.std.DefaultJobCatalogListenerImpl;
import org.apache.gobblin.runtime.std.DefaultJobExecutionStateListenerImpl;
import org.apache.gobblin.runtime.std.JobLifecycleListenersList;
import org.apache.gobblin.util.ExecutorsUtils;
/**
* A default implementation of {@link GobblinInstanceDriver}. It accepts already instantiated
* {@link JobCatalog}, {@link JobSpecMonitorFactory}, {@link JobSpecScheduler},
* {@link JobExecutionLauncher}. It is responsibility of the caller to manage those (e.g. start,
* shutdown, etc.)
*
*/
public class DefaultGobblinInstanceDriverImpl extends AbstractIdleService
implements GobblinInstanceDriver {
protected final Logger _log;
protected final String _instanceName;
protected final Configurable _sysConfig;
protected final JobCatalog _jobCatalog;
protected final JobSpecScheduler _jobScheduler;
protected final JobExecutionLauncher _jobLauncher;
protected final ConfigAccessor _instanceCfg;
protected final JobLifecycleListenersList _callbacksDispatcher;
private final boolean _instrumentationEnabled;
protected final MetricContext _metricCtx;
protected JobSpecListener _jobSpecListener;
private final StandardMetrics _metrics;
private final SharedResourcesBroker<GobblinScopeTypes> _instanceBroker;
public DefaultGobblinInstanceDriverImpl(String instanceName,
Configurable sysConfig, JobCatalog jobCatalog,
JobSpecScheduler jobScheduler,
JobExecutionLauncher jobLauncher,
Optional<MetricContext> baseMetricContext,
Optional<Logger> log,
SharedResourcesBroker<GobblinScopeTypes> instanceBroker) {
Preconditions.checkNotNull(jobCatalog);
Preconditions.checkNotNull(jobScheduler);
Preconditions.checkNotNull(jobLauncher);
Preconditions.checkNotNull(sysConfig);
_instanceName = instanceName;
_log = log.or(LoggerFactory.getLogger(getClass()));
_metricCtx = baseMetricContext.or(constructMetricContext(sysConfig, _log));
_instrumentationEnabled = null != _metricCtx && GobblinMetrics.isEnabled(sysConfig.getConfig());
_jobCatalog = jobCatalog;
_jobScheduler = jobScheduler;
_jobLauncher = jobLauncher;
_sysConfig = sysConfig;
_instanceCfg = ConfigAccessor.createFromGlobalConfig(_sysConfig.getConfig());
_callbacksDispatcher = new JobLifecycleListenersList(_jobCatalog, _jobScheduler, _log);
_instanceBroker = instanceBroker;
_metrics = new StandardMetrics(this);
}
private MetricContext constructMetricContext(Configurable sysConfig, Logger log) {
org.apache.gobblin.configuration.State tmpState = new org.apache.gobblin.configuration.State(sysConfig.getConfigAsProperties());
return GobblinMetrics.isEnabled(sysConfig.getConfig()) ?
Instrumented.getMetricContext(tmpState, getClass())
: null;
}
/** {@inheritDoc} */
@Override public JobCatalog getJobCatalog() {
return _jobCatalog;
}
/** {@inheritDoc} */
@Override public MutableJobCatalog getMutableJobCatalog() {
return (MutableJobCatalog)_jobCatalog;
}
/** {@inheritDoc} */
@Override public JobSpecScheduler getJobScheduler() {
return _jobScheduler;
}
/** {@inheritDoc} */
@Override public JobExecutionLauncher getJobLauncher() {
return _jobLauncher;
}
/** {@inheritDoc} */
@Override public Configurable getSysConfig() {
return _sysConfig;
}
/** {@inheritDoc} */
@Override public SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker() {
return _instanceBroker;
}
/** {@inheritDoc} */
@Override public Logger getLog() {
return _log;
}
@Override protected void startUp() throws Exception {
getLog().info("Default driver: starting ...");
_jobSpecListener = new JobSpecListener();
_jobCatalog.addListener(_jobSpecListener);
getLog().info("Default driver: started.");
}
@Override protected void shutDown() throws Exception {
getLog().info("Default driver: shuttind down ...");
if (null != _jobSpecListener) {
_jobCatalog.removeListener(_jobSpecListener);
}
_callbacksDispatcher.close();
getLog().info("Default driver: shut down.");
}
/** Keeps track of a job execution */
class JobStateTracker extends DefaultJobExecutionStateListenerImpl {
public JobStateTracker() {
super(LoggerFactory.getLogger(DefaultGobblinInstanceDriverImpl.this._log.getName() +
"_jobExecutionListener"));
}
@Override public String toString() {
return _log.get().getName();
}
@Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) {
super.onStatusChange(state, previousStatus, newStatus);
_callbacksDispatcher.onStatusChange(state, previousStatus, newStatus);
}
@Override
public void onStageTransition(JobExecutionState state, String previousStage, String newStage) {
super.onStageTransition(state, previousStage, newStage);
_callbacksDispatcher.onStageTransition(state, previousStage, newStage);
}
@Override
public void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue) {
super.onMetadataChange(state, key, oldValue, newValue);
_callbacksDispatcher.onMetadataChange(state, key, oldValue, newValue);
}
}
/** The runnable invoked by the Job scheduler */
class JobSpecRunnable implements Runnable {
private final JobSpec _jobSpec;
private final GobblinInstanceDriver _instanceDriver;
public JobSpecRunnable(JobSpec jobSpec, GobblinInstanceDriver instanceDriver) {
_jobSpec = jobSpec;
_instanceDriver = instanceDriver;
}
@Override
public void run() {
try {
JobExecutionMonitor monitor = _jobLauncher.launchJob(new ResolvedJobSpec(_jobSpec, _instanceDriver));
if (!(monitor instanceof JobLauncherExecutionDriver.JobExecutionMonitorAndDriver)) {
throw new UnsupportedOperationException(JobLauncherExecutionDriver.JobExecutionMonitorAndDriver.class.getName() + " is expected.");
}
JobExecutionDriver driver = ((JobLauncherExecutionDriver.JobExecutionMonitorAndDriver) monitor).getDriver();
_callbacksDispatcher.onJobLaunch(driver);
driver.registerStateListener(new JobStateTracker());
ExecutorsUtils.newThreadFactory(Optional.of(_log), Optional.of("gobblin-instance-driver")).newThread(driver).start();
}
catch (Throwable t) {
_log.error("Job launch failed: " + t, t);
}
}
}
/** Listens to changes in the Job catalog and schedules/un-schedules jobs. */
protected class JobSpecListener extends DefaultJobCatalogListenerImpl {
public JobSpecListener() {
super(LoggerFactory.getLogger(DefaultGobblinInstanceDriverImpl.this._log.getName() +
"_jobSpecListener"));
}
@Override public String toString() {
return _log.get().getName();
}
@Override public void onAddJob(JobSpec addedJob) {
super.onAddJob(addedJob);
_jobScheduler.scheduleJob(addedJob, createJobSpecRunnable(addedJob));
}
@Override public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) {
super.onDeleteJob(deletedJobURI, deletedJobVersion);
_jobScheduler.unscheduleJob(deletedJobURI);
}
@Override public void onUpdateJob(JobSpec updatedJob) {
super.onUpdateJob(updatedJob);
_jobScheduler.scheduleJob(updatedJob, createJobSpecRunnable(updatedJob));
}
}
@VisibleForTesting JobSpecRunnable createJobSpecRunnable(JobSpec addedJob) {
return new JobSpecRunnable(addedJob, this);
}
ConfigAccessor getInstanceCfg() {
return _instanceCfg;
}
@Override
public void registerJobLifecycleListener(JobLifecycleListener listener) {
_callbacksDispatcher.registerJobLifecycleListener(listener);
}
@Override
public void unregisterJobLifecycleListener(JobLifecycleListener listener) {
_callbacksDispatcher.unregisterJobLifecycleListener(listener);
}
@Override
public List<JobLifecycleListener> getJobLifecycleListeners() {
return _callbacksDispatcher.getJobLifecycleListeners();
}
@Override
public void registerWeakJobLifecycleListener(JobLifecycleListener listener) {
_callbacksDispatcher.registerWeakJobLifecycleListener(listener);
}
@Override public MetricContext getMetricContext() {
return _metricCtx;
}
@Override public boolean isInstrumentationEnabled() {
return _instrumentationEnabled;
}
@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 _metrics;
}
@Override
public String getInstanceName() {
return _instanceName;
}
}
| 1,518 |
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/instance/SimpleGobblinInstanceEnvironment.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.instance;
import java.util.List;
import org.slf4j.Logger;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.runtime.api.Configurable;
import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment;
import javax.annotation.Nonnull;
import lombok.Data;
/**
* A barebones implementation of {@link GobblinInstanceEnvironment} used to inject system configurations to
* {@link StandardGobblinInstanceDriver}.
*/
@Data
public class SimpleGobblinInstanceEnvironment implements GobblinInstanceEnvironment {
private final String instanceName;
private final Logger log;
private final Configurable sysConfig;
@Nonnull
@Override
public MetricContext getMetricContext() {
throw new UnsupportedOperationException();
}
@Override
public boolean isInstrumentationEnabled() {
return false;
}
@Override
public List<Tag<?>> generateTags(State state) {
return null;
}
@Override
public void switchMetricContext(List<Tag<?>> tags) {
throw new UnsupportedOperationException();
}
@Override
public void switchMetricContext(MetricContext context) {
throw new UnsupportedOperationException();
}
@Override
public SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker() {
throw new UnsupportedOperationException();
}
}
| 1,519 |
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/instance/StandardGobblinInstanceLauncher.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.instance;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.AbstractIdleService;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.SimpleScope;
import org.apache.gobblin.broker.SharedResourcesBrokerFactory;
import org.apache.gobblin.broker.SharedResourcesBrokerImpl;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.runtime.api.Configurable;
import org.apache.gobblin.runtime.api.GobblinInstanceDriver;
import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment;
import org.apache.gobblin.runtime.api.GobblinInstanceLauncher;
import org.apache.gobblin.runtime.std.DefaultConfigurableImpl;
/**
* A standard implementation that expects the instance configuration to be passed from the outside.
* As a driver, it uses {@link StandardGobblinInstanceDriver}.
*/
public class StandardGobblinInstanceLauncher extends AbstractIdleService
implements GobblinInstanceLauncher {
private final Logger _log;
private final String _name;
private final Configurable _instanceConf;
private final StandardGobblinInstanceDriver _driver;
private final MetricContext _metricContext;
private final boolean _instrumentationEnabled;
private final SharedResourcesBroker<GobblinScopeTypes> _instanceBroker;
protected StandardGobblinInstanceLauncher(String name,
Configurable instanceConf,
StandardGobblinInstanceDriver.Builder driverBuilder,
Optional<MetricContext> metricContext,
Optional<Logger> log,
SharedResourcesBroker<GobblinScopeTypes> instanceBroker) {
_log = log.or(LoggerFactory.getLogger(getClass()));
_name = name;
_instanceConf = instanceConf;
_driver = driverBuilder.withInstanceEnvironment(this).build();
_instrumentationEnabled = metricContext.isPresent();
_metricContext = metricContext.orNull();
_instanceBroker = instanceBroker;
}
/** {@inheritDoc} */
@Override
public Config getConfig() {
return _instanceConf.getConfig();
}
/** {@inheritDoc} */
@Override
public Properties getConfigAsProperties() {
return _instanceConf.getConfigAsProperties();
}
/** {@inheritDoc} */
@Override
public GobblinInstanceDriver getDriver() throws IllegalStateException {
return _driver;
}
/** {@inheritDoc} */
@Override
public String getInstanceName() {
return _name;
}
/** {@inheritDoc} */
@Override
public SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker() {
return _instanceBroker;
}
/** {@inheritDoc} */
@Override
protected void startUp() throws Exception {
_driver.startUp();
}
/** {@inheritDoc} */
@Override
protected void shutDown() throws Exception {
_driver.shutDown();
}
public static Builder builder() {
return new Builder();
}
public static class Builder implements GobblinInstanceEnvironment {
final static AtomicInteger INSTANCE_COUNT = new AtomicInteger(1);
Optional<String> _name = Optional.absent();
Optional<Logger> _log = Optional.absent();
StandardGobblinInstanceDriver.Builder _driver = new StandardGobblinInstanceDriver.Builder();
Optional<? extends Configurable> _instanceConfig = Optional.absent();
Optional<Boolean> _instrumentationEnabled = Optional.absent();
Optional<MetricContext> _metricContext = Optional.absent();
Optional<SharedResourcesBroker<GobblinScopeTypes>> _instanceBroker = Optional.absent();
public Builder() {
_driver.withInstanceEnvironment(this);
}
public String getDefaultInstanceName() {
return StandardGobblinInstanceLauncher.class.getSimpleName() + "-" +
INSTANCE_COUNT.getAndIncrement();
}
@Override
public String getInstanceName() {
if (! _name.isPresent()) {
_name = Optional.of(getDefaultInstanceName());
}
return _name.get();
}
public Builder withInstanceName(String instanceName) {
_name = Optional.of(instanceName);
return this;
}
public Logger getDefaultLog() {
return LoggerFactory.getLogger(getInstanceName());
}
@Override
public Logger getLog() {
if (! _log.isPresent()) {
_log = Optional.of(getDefaultLog());
}
return _log.get();
}
public Builder withLog(Logger log) {
_log = Optional.of(log);
return this;
}
public StandardGobblinInstanceDriver.Builder driver() {
return _driver;
}
/** Uses the configuration provided by {@link ConfigFactory#load()} */
public Configurable getDefaultSysConfig() {
return DefaultConfigurableImpl.createFromConfig(ConfigFactory.load());
}
@Override public Configurable getSysConfig() {
if (! _instanceConfig.isPresent()) {
_instanceConfig = Optional.of(getDefaultSysConfig());
}
return _instanceConfig.get();
}
public Builder withSysConfig(Config instanceConfig) {
_instanceConfig = Optional.of(DefaultConfigurableImpl.createFromConfig(instanceConfig));
return this;
}
public Builder withSysConfig(Properties instanceConfig) {
_instanceConfig = Optional.of(DefaultConfigurableImpl.createFromProperties(instanceConfig));
return this;
}
public Builder setInstrumentationEnabled(boolean enabled) {
_instrumentationEnabled = Optional.of(enabled);
return this;
}
@Override
public boolean isInstrumentationEnabled() {
if (!_instrumentationEnabled.isPresent()) {
_instrumentationEnabled = Optional.of(getDefaultInstrumentationEnabled());
}
return _instrumentationEnabled.get();
}
public Builder setMetricContext(MetricContext metricContext) {
_metricContext = Optional.of(metricContext);
return this;
}
@Override
public MetricContext getMetricContext() {
if (!_metricContext.isPresent()) {
_metricContext = Optional.of(getDefaultMetricContext());
}
return _metricContext.get();
}
private MetricContext getDefaultMetricContext() {
org.apache.gobblin.configuration.State fakeState =
new org.apache.gobblin.configuration.State(getSysConfig().getConfigAsProperties());
return Instrumented.getMetricContext(fakeState, StandardGobblinInstanceLauncher.class);
}
private boolean getDefaultInstrumentationEnabled() {
return GobblinMetrics.isEnabled(getSysConfig().getConfig());
}
public StandardGobblinInstanceLauncher.Builder withInstanceBroker(SharedResourcesBroker<GobblinScopeTypes> broker) {
_instanceBroker = Optional.of(broker);
return this;
}
public SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker() {
if (!_instanceBroker.isPresent()) {
_instanceBroker = Optional.of(getDefaultInstanceBroker());
}
return _instanceBroker.get();
}
public SharedResourcesBroker<GobblinScopeTypes> getDefaultInstanceBroker() {
SharedResourcesBrokerImpl<GobblinScopeTypes> globalBroker =
SharedResourcesBrokerFactory.createDefaultTopLevelBroker(getSysConfig().getConfig(),
GobblinScopeTypes.GLOBAL.defaultScopeInstance());
return globalBroker.newSubscopedBuilder(new SimpleScope<>(GobblinScopeTypes.INSTANCE, getInstanceName())).build();
}
public StandardGobblinInstanceLauncher build() {
return new StandardGobblinInstanceLauncher(getInstanceName(), getSysConfig(), driver(),
isInstrumentationEnabled() ? Optional.of(getMetricContext()) : Optional.<MetricContext>absent(),
Optional.of(getLog()), getInstanceBroker());
}
@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 MetricContext getMetricContext() {
return _metricContext;
}
@Override public boolean isInstrumentationEnabled() {
return _instrumentationEnabled;
}
@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 Logger getLog() {
return _log;
}
@Override
public Configurable getSysConfig() {
return this;
}
}
| 1,520 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/instance | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/instance/plugin/BaseIdlePluginImpl.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.instance.plugin;
import com.google.common.util.concurrent.AbstractIdleService;
import org.apache.gobblin.annotation.Alias;
import org.apache.gobblin.runtime.api.GobblinInstanceDriver;
import org.apache.gobblin.runtime.api.GobblinInstancePlugin;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* A base implementation of a plugin that works as {@link AbstractIdleService}. Subclasses must
* implement the startUp() method and can optionally override shutDown().
*
*/
@AllArgsConstructor
public abstract class BaseIdlePluginImpl extends AbstractIdleService implements GobblinInstancePlugin {
@Getter protected final GobblinInstanceDriver instance;
/** {@inheritDoc} */
@Override
protected void shutDown() throws Exception {
instance.getLog().info("Plugin shutdown: " + this);
}
@Override
public String toString() {
Alias alias = getClass().getAnnotation(Alias.class);
return null != alias ? alias.value() : getClass().getName();
}
}
| 1,521 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/instance | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/instance/hadoop/HadoopConfigLoader.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.instance.hadoop;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;
/**
* A helper class to load hadoop configuration with possible overrides in typesafe config.
*/
public class HadoopConfigLoader {
/**
* Properties in this context will be added to the Hadoop configuration. One can add a suffix
* ".ROOT" to a property which will be automatically stripped. This is to avoid an incompatibility
* between typesafe config and Properties where the latter allows "a.b" and "a.b.c" but the former
* does not. In that case, one can use "a.b.ROOT" and "a.b.c".
*/
public static final String HADOOP_CONF_OVERRIDES_ROOT = "hadoop-inject";
public static final String STRIP_SUFFIX = ".ROOT";
private final Configuration _conf = new Configuration();
public HadoopConfigLoader() {
this(ConfigFactory.load());
}
public HadoopConfigLoader(Config rootConfig) {
if (rootConfig.hasPath(HADOOP_CONF_OVERRIDES_ROOT)) {
addOverrides(_conf, rootConfig.getConfig(HADOOP_CONF_OVERRIDES_ROOT));
}
}
/** Get a copy of the Hadoop configuration with any overrides applied. Note that this is a private
* copy of the configuration and can be further modified. */
public Configuration getConf() {
return new Configuration(_conf);
}
static void addOverrides(Configuration conf, Config config) {
for(Map.Entry<String, ConfigValue> entry: config.entrySet()) {
String propName = entry.getKey();
if (propName.endsWith(STRIP_SUFFIX)) {
propName = propName.substring(0, propName.length() - STRIP_SUFFIX.length());
}
conf.set(propName, entry.getValue().unwrapped().toString());
}
}
}
| 1,522 |
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/JobProgress.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;
import java.util.List;
import org.apache.gobblin.runtime.JobState;
/**
* Type used to retrieve the progress of a Gobblin job.
*/
public interface JobProgress {
String getJobId();
int getTaskCount();
int getCompletedTasks();
long getElapsedTime();
JobState.RunningState getState();
List<? extends TaskProgress> getTaskProgress();
}
| 1,523 |
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/JobInterruptionPredicate.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;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.util.ReflectivePredicateEvaluator;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.AbstractScheduledService;
import lombok.extern.slf4j.Slf4j;
/**
* This class evaluates a predicate on the {@link JobProgress} of a job and calls a job interruption hook when the
* predicate is satisfied.
*
* It is used to preemptively stop jobs after they satisfy some completion predicate (e.g. more than 15 minutes have
* elapsed and at least 75% of tasks have finished).
*/
@Slf4j
public class JobInterruptionPredicate extends AbstractScheduledService {
public static final String INTERRUPTION_SQL = "org.apache.gobblin.jobInterruptionPredicate.sql";
private final String sql;
private final ReflectivePredicateEvaluator evaluator;
private final JobProgress jobProgress;
private final Runnable jobInterruptionHook;
public JobInterruptionPredicate(JobState jobState, Runnable jobInterruptionHook, boolean autoStart) {
this(jobState, jobState.getProp(INTERRUPTION_SQL), jobInterruptionHook, autoStart);
}
protected JobInterruptionPredicate(JobProgress jobProgress, String predicate,
Runnable jobInterruptionHook, boolean autoStart) {
this.sql = predicate;
ReflectivePredicateEvaluator tmpEval = null;
if (this.sql != null) {
try {
tmpEval = new ReflectivePredicateEvaluator(this.sql, JobProgress.class, TaskProgress.class);
} catch (SQLException exc) {
log.warn("Job interruption predicate is invalid, will not preemptively interrupt job.", exc);
}
}
this.evaluator = tmpEval;
this.jobProgress = jobProgress;
this.jobInterruptionHook = jobInterruptionHook;
if (autoStart && this.sql != null) {
startAsync();
}
}
@Override
protected void runOneIteration() {
if (this.evaluator == null) {
stopAsync();
return;
}
switch (this.jobProgress.getState()) {
case PENDING:
return;
case RUNNING:
try {
List<Object> objects = Stream.concat(Stream.<Object>of(this.jobProgress), this.jobProgress.getTaskProgress().stream()).collect(
Collectors.toList());
if (this.evaluator.evaluate(objects)) {
log.info("Interrupting job due to satisfied job interruption predicate. Predicate: " + this.sql);
this.jobInterruptionHook.run();
stopAsync();
}
} catch (Throwable exc) {
log.warn("Failed to evaluate job interruption predicate. Will not preemptively interrupt job.", exc);
throw Throwables.propagate(exc);
}
break;
default:
log.info(String.format("Detected job finished with state %s. Stopping job interruption predicate.",
this.jobProgress.getState()));
stopAsync();
}
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedDelaySchedule(30, 30, TimeUnit.SECONDS);
}
}
| 1,524 |
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/GobblinJobFiniteStateMachine.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;
import java.io.IOException;
import org.apache.gobblin.fsm.FiniteStateMachine;
import org.apache.gobblin.fsm.StateWithCallbacks;
import org.apache.gobblin.runtime.JobState;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
/**
* A {@link FiniteStateMachine} implementation to track the state of a Gobblin job executor.
*/
@Slf4j
public class GobblinJobFiniteStateMachine extends FiniteStateMachine<GobblinJobFiniteStateMachine.JobFSMState> {
/**
* Types of state the job can be in.
*/
public enum StateType {
PREPARING, RUNNING, INTERRUPTED, CANCELLED, SUCCESS, FAILED
}
/**
* State of a job.
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(of = "stateType")
@ToString
@Getter
public static class JobFSMState {
private final StateType stateType;
}
/**
* A special {@link JobFSMState} that is aware of how to interrupt a running job.
*/
private class RunnableState extends JobFSMState implements StateWithCallbacks<JobFSMState> {
private final JobInterruptionPredicate jobInterruptionPredicate;
public RunnableState() {
super(StateType.RUNNING);
if (GobblinJobFiniteStateMachine.this.interruptGracefully == null) {
this.jobInterruptionPredicate = null;
} else {
this.jobInterruptionPredicate = new JobInterruptionPredicate(GobblinJobFiniteStateMachine.this.jobState,
GobblinJobFiniteStateMachine.this::interruptRunningJob, false);
}
}
@Override
public void onEnterState(@Nullable JobFSMState previousState) {
if (this.jobInterruptionPredicate != null) {
this.jobInterruptionPredicate.startAsync();
}
}
@Override
public void onLeaveState(JobFSMState nextState) {
if (this.jobInterruptionPredicate != null) {
this.jobInterruptionPredicate.stopAsync();
}
}
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
/**
* A runnable that allows for {@link IOException}s.
*/
@FunctionalInterface
public interface RunnableWithIoException {
void run() throws IOException;
}
private final JobState jobState;
private final RunnableWithIoException interruptGracefully;
private final RunnableWithIoException killJob;
@lombok.Builder
private GobblinJobFiniteStateMachine(JobState jobState, RunnableWithIoException interruptGracefully,
RunnableWithIoException killJob) {
super(buildAllowedTransitions(), Sets.newHashSet(new JobFSMState(StateType.CANCELLED)), new JobFSMState(StateType.FAILED),
new JobFSMState(StateType.PREPARING));
if (jobState == null) {
throw new IllegalArgumentException("Job state is required.");
}
this.jobState = jobState;
this.interruptGracefully = interruptGracefully;
this.killJob = killJob;
}
/**
* Callers should use this method to obtain the {@link JobFSMState} for a particular {@link StateType}, as the
* {@link JobFSMState} might contain additional functionality like running other services, etc.
* @param stateType
* @return
*/
public JobFSMState getEndStateForType(StateType stateType) {
switch (stateType) {
case RUNNING:
return new RunnableState();
default:
return new JobFSMState(stateType);
}
}
private void interruptRunningJob() {
log.info("Interrupting job execution.");
try (FiniteStateMachine<JobFSMState>.Transition transition = startTransition(getEndStateForType(StateType.INTERRUPTED))) {
try {
this.interruptGracefully.run();
} catch (IOException ioe) {
transition.changeEndState(getEndStateForType(StateType.FAILED));
}
} catch (FiniteStateMachine.UnallowedTransitionException exc) {
log.error("Cannot interrupt job.", exc);
} catch (InterruptedException | FailedTransitionCallbackException exc) {
log.error("Cannot finish graceful job interruption. Killing job.", exc);
try {
this.killJob.run();
} catch (IOException ioe) {
log.error("Failed to kill job.", ioe);
}
if (exc instanceof FailedTransitionCallbackException) {
((FailedTransitionCallbackException) exc).getTransition().switchEndStateToErrorState();
((FailedTransitionCallbackException) exc).getTransition().closeWithoutCallbacks();
}
}
}
private static SetMultimap<JobFSMState, JobFSMState> buildAllowedTransitions() {
SetMultimap<JobFSMState, JobFSMState> transitions = HashMultimap.create();
transitions.put(new JobFSMState(StateType.PREPARING), new JobFSMState(StateType.RUNNING));
transitions.put(new JobFSMState(StateType.PREPARING), new JobFSMState(StateType.FAILED));
transitions.put(new JobFSMState(StateType.PREPARING), new JobFSMState(StateType.INTERRUPTED));
transitions.put(new JobFSMState(StateType.RUNNING), new JobFSMState(StateType.SUCCESS));
transitions.put(new JobFSMState(StateType.RUNNING), new JobFSMState(StateType.FAILED));
transitions.put(new JobFSMState(StateType.RUNNING), new JobFSMState(StateType.INTERRUPTED));
return transitions;
}
}
| 1,525 |
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/TaskProgress.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;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* Interface used to retrieve the progress of a task in a Gobblin job.
*/
public interface TaskProgress {
String getJobId();
String getTaskId();
WorkUnitState.WorkingState getWorkingState();
boolean isCompleted();
}
| 1,526 |
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/api/MysqlMultiActiveLeaseArbiter.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.api;
import com.google.inject.Inject;
import com.typesafe.config.Config;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import lombok.Data;
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.service.ServiceConfigKeys;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.DBStatementExecutor;
/**
* MySQL based implementation of the {@link MultiActiveLeaseArbiter} which uses a MySQL store to resolve ownership of
* a flow event amongst multiple competing participants. A MySQL table is used to store flow identifying information as
* well as the flow action associated with it. It uses two additional values of the `event_timestamp` and
* `lease_acquisition_timestamp` to indicate an active lease, expired lease, and state of no longer leasing. The table
* schema is as follows:
* [flow_group | flow_name | flow_action | event_timestamp | lease_acquisition_timestamp]
* (----------------------primary key------------------------)
* We also maintain another table in the database with two constants that allow us to coordinate between participants
* and ensure they are using the same values to base their coordination off of.
* [epsilon | linger]
* `epsilon` - time within we consider two event timestamps to be overlapping and can consolidate
* `linger` - minimum time to occur before another host may attempt a lease on a flow event. It should be much greater
* than epsilon and encapsulate executor communication latency including retry attempts
*
* The `event_timestamp` is the time of the flow_action event request.
* --- Database event_timestamp laundering ---
* We only use the participant's local event_timestamp internally to identify the particular flow_action event, but
* after interacting with the database utilize the CURRENT_TIMESTAMP of the database to insert or keep
* track of our event, "laundering" or replacing the local timestamp with the database one. This is to avoid any
* discrepancies due to clock drift between participants as well as variation in local time and database time for
* future comparisons.
* --- Event consolidation ---
* Note that for the sake of simplification, we only allow one event associated with a particular flow's flow_action
* (ie: only one LAUNCH for example of flow FOO, but there can be a LAUNCH, KILL, & RESUME for flow FOO at once) during
* the time it takes to execute the flow action. In most cases, the execution time should be so negligible that this
* event consolidation of duplicate flow action requests is not noticed and even during executor downtime this behavior
* is acceptable as the user generally expects a timely execution of the most recent request rather than one execution
* per request.
*
* The `lease_acquisition_timestamp` is the time a host acquired ownership of this flow action, and it is valid for
* `linger` period of time after which it expires and any host can re-attempt ownership. In most cases, the original
* host should actually complete its work while having the lease and then mark the flow action as NULL to indicate no
* further leasing should be done for the event.
*/
@Slf4j
public class MysqlMultiActiveLeaseArbiter implements MultiActiveLeaseArbiter {
protected final DataSource dataSource;
private final DBStatementExecutor dbStatementExecutor;
private final String leaseArbiterTableName;
private final String constantsTableName;
private final int epsilonMillis;
private final int lingerMillis;
private final long retentionPeriodMillis;
private String thisTableRetentionStatement;
private String thisTableGetInfoStatement;
private String thisTableGetInfoStatementForReminder;
private String thisTableSelectAfterInsertStatement;
private String thisTableAcquireLeaseIfMatchingAllStatement;
private String thisTableAcquireLeaseIfFinishedStatement;
/*
Notes:
- Set `event_timestamp` default value to turn off timestamp auto-updates for row modifications which alters this col
in an unexpected way upon completing the lease
- MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current
time zone for retrieval. https://dev.mysql.com/doc/refman/8.0/en/datetime.html
- Thus, for reading any timestamps from MySQL we convert the timezone from session (default) to UTC to always
use epoch-millis in UTC locally
- Similarly, for inserting/updating any timestamps we convert the timezone from UTC to session (as it will be
(interpreted automatically as session time zone) and explicitly set all timestamp columns to avoid using the
default auto-update/initialization values
- We desire millisecond level precision and denote that with `(3)` for the TIMESTAMP types
*/
private static final String CREATE_LEASE_ARBITER_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS %s ("
+ "flow_group varchar(" + ServiceConfigKeys.MAX_FLOW_GROUP_LENGTH + ") NOT NULL, flow_name varchar("
+ ServiceConfigKeys.MAX_FLOW_GROUP_LENGTH + ") NOT NULL, " + " flow_action varchar(100) NOT NULL, "
+ "event_timestamp TIMESTAMP(3) NOT NULL, "
+ "lease_acquisition_timestamp TIMESTAMP(3) NULL, "
+ "PRIMARY KEY (flow_group,flow_name,flow_action))";
// Deletes rows older than retention time period regardless of lease status as they should all be invalid or completed
// since retention >> linger
private static final String LEASE_ARBITER_TABLE_RETENTION_STATEMENT = "DELETE FROM %s WHERE event_timestamp < "
+ "DATE_SUB(CURRENT_TIMESTAMP(3), INTERVAL %s * 1000 MICROSECOND)";
private static final String CREATE_CONSTANTS_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS %s "
+ "(primary_key INT, epsilon INT, linger INT, PRIMARY KEY (primary_key))";
// Only insert epsilon and linger values from config if this table does not contain a pre-existing values already.
private static final String UPSERT_CONSTANTS_TABLE_STATEMENT = "INSERT INTO %s (primary_key, epsilon, linger) "
+ "VALUES(1, ?, ?) ON DUPLICATE KEY UPDATE epsilon=VALUES(epsilon), linger=VALUES(linger)";
protected static final String WHERE_CLAUSE_TO_MATCH_KEY = "WHERE flow_group=? AND flow_name=? AND flow_action=?";
protected static final String WHERE_CLAUSE_TO_MATCH_ROW = WHERE_CLAUSE_TO_MATCH_KEY
+ " AND event_timestamp=CONVERT_TZ(?, '+00:00', @@session.time_zone)"
+ " AND lease_acquisition_timestamp=CONVERT_TZ(?, '+00:00', @@session.time_zone)";
protected static final String SELECT_AFTER_INSERT_STATEMENT = "SELECT "
+ "CONVERT_TZ(`event_timestamp`, @@session.time_zone, '+00:00') as utc_event_timestamp, "
+ "CONVERT_TZ(`lease_acquisition_timestamp`, @@session.time_zone, '+00:00') as utc_lease_acquisition_timestamp, "
+ "linger FROM %s, %s " + WHERE_CLAUSE_TO_MATCH_KEY;
// Does a cross join between the two tables to have epsilon and linger values available. Returns the following values:
// event_timestamp, lease_acquisition_timestamp, isWithinEpsilon (boolean if new event timestamp (current timestamp in
// db) is within epsilon of event_timestamp in the table), leaseValidityStatus (1 if lease has not expired, 2 if
// expired, 3 if column is NULL or no longer leasing)
protected static final String GET_EVENT_INFO_STATEMENT = "SELECT "
+ "CONVERT_TZ(`event_timestamp`, @@session.time_zone, '+00:00') as utc_event_timestamp, "
+ "CONVERT_TZ(`lease_acquisition_timestamp`, @@session.time_zone, '+00:00') as utc_lease_acquisition_timestamp, "
+ "ABS(TIMESTAMPDIFF(microsecond, event_timestamp, CURRENT_TIMESTAMP(3))) / 1000 <= epsilon as is_within_epsilon, CASE "
+ "WHEN CURRENT_TIMESTAMP(3) < DATE_ADD(lease_acquisition_timestamp, INTERVAL linger*1000 MICROSECOND) then 1 "
+ "WHEN CURRENT_TIMESTAMP(3) >= DATE_ADD(lease_acquisition_timestamp, INTERVAL linger*1000 MICROSECOND) then 2 "
+ "ELSE 3 END as lease_validity_status, linger, "
+ "CONVERT_TZ(CURRENT_TIMESTAMP(3), @@session.time_zone, '+00:00') as utc_current_timestamp FROM %s, %s "
+ WHERE_CLAUSE_TO_MATCH_KEY;
// Same as query above, except that isWithinEpsilon is True if the reminder event timestamp (provided by caller) is
// OLDER than or equal to the db event_timestamp and within epsilon away from it.
protected static final String GET_EVENT_INFO_STATEMENT_FOR_REMINDER = "SELECT "
+ "CONVERT_TZ(`event_timestamp`, @@session.time_zone, '+00:00') as utc_event_timestamp, "
+ "CONVERT_TZ(`lease_acquisition_timestamp`, @@session.time_zone, '+00:00') as utc_lease_acquisition_timestamp, "
+ "TIMESTAMPDIFF(microsecond, event_timestamp, CONVERT_TZ(?, '+00:00', @@session.time_zone)) / 1000 <= epsilon as is_within_epsilon, CASE "
+ "WHEN CURRENT_TIMESTAMP(3) < DATE_ADD(lease_acquisition_timestamp, INTERVAL linger*1000 MICROSECOND) then 1 "
+ "WHEN CURRENT_TIMESTAMP(3) >= DATE_ADD(lease_acquisition_timestamp, INTERVAL linger*1000 MICROSECOND) then 2 "
+ "ELSE 3 END as lease_validity_status, linger, "
+ "CONVERT_TZ(CURRENT_TIMESTAMP(3), @@session.time_zone, '+00:00') as utc_current_timestamp FROM %s, %s "
+ WHERE_CLAUSE_TO_MATCH_KEY;
// Insert or update row to acquire lease if values have not changed since the previous read
// Need to define three separate statements to handle cases where row does not exist or has null values to check
protected static final String ACQUIRE_LEASE_IF_NEW_ROW_STATEMENT = "INSERT INTO %s (flow_group, flow_name, "
+ "flow_action, event_timestamp, lease_acquisition_timestamp) VALUES(?, ?, ?, CURRENT_TIMESTAMP(3), "
+ "CURRENT_TIMESTAMP(3))";
protected static final String CONDITIONALLY_ACQUIRE_LEASE_IF_FINISHED_LEASING_STATEMENT = "UPDATE %s "
+ "SET event_timestamp=CURRENT_TIMESTAMP(3), lease_acquisition_timestamp=CURRENT_TIMESTAMP(3) "
+ WHERE_CLAUSE_TO_MATCH_KEY + " AND event_timestamp=CONVERT_TZ(?, '+00:00', @@session.time_zone) AND "
+ "lease_acquisition_timestamp is NULL";
protected static final String CONDITIONALLY_ACQUIRE_LEASE_IF_MATCHING_ALL_COLS_STATEMENT = "UPDATE %s "
+ "SET event_timestamp=CURRENT_TIMESTAMP(3), lease_acquisition_timestamp=CURRENT_TIMESTAMP(3) "
+ WHERE_CLAUSE_TO_MATCH_ROW;
// Complete lease acquisition if values have not changed since lease was acquired
protected static final String CONDITIONALLY_COMPLETE_LEASE_STATEMENT = "UPDATE %s SET "
+ "event_timestamp=event_timestamp, lease_acquisition_timestamp = NULL " + WHERE_CLAUSE_TO_MATCH_ROW;
private static final ThreadLocal<Calendar> UTC_CAL =
ThreadLocal.withInitial(() -> Calendar.getInstance(TimeZone.getTimeZone("UTC")));
@Inject
public MysqlMultiActiveLeaseArbiter(Config config) throws IOException {
if (config.hasPath(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX)) {
config = config.getConfig(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX).withFallback(config);
} else {
throw new IOException(String.format("Please specify the config for MysqlMultiActiveLeaseArbiter using prefix %s "
+ "before all properties", ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX));
}
this.leaseArbiterTableName = ConfigUtils.getString(config, ConfigurationKeys.SCHEDULER_LEASE_DETERMINATION_STORE_DB_TABLE_KEY,
ConfigurationKeys.DEFAULT_SCHEDULER_LEASE_DETERMINATION_STORE_DB_TABLE);
this.constantsTableName = ConfigUtils.getString(config, ConfigurationKeys.MULTI_ACTIVE_SCHEDULER_CONSTANTS_DB_TABLE_KEY,
ConfigurationKeys.DEFAULT_MULTI_ACTIVE_SCHEDULER_CONSTANTS_DB_TABLE);
this.epsilonMillis = ConfigUtils.getInt(config, ConfigurationKeys.SCHEDULER_EVENT_EPSILON_MILLIS_KEY,
ConfigurationKeys.DEFAULT_SCHEDULER_EVENT_EPSILON_MILLIS);
this.lingerMillis = ConfigUtils.getInt(config, ConfigurationKeys.SCHEDULER_EVENT_LINGER_MILLIS_KEY,
ConfigurationKeys.DEFAULT_SCHEDULER_EVENT_LINGER_MILLIS);
this.retentionPeriodMillis = ConfigUtils.getLong(config, ConfigurationKeys.SCHEDULER_LEASE_DETERMINATION_TABLE_RETENTION_PERIOD_MILLIS_KEY,
ConfigurationKeys.DEFAULT_SCHEDULER_LEASE_DETERMINATION_TABLE_RETENTION_PERIOD_MILLIS);
this.thisTableRetentionStatement = String.format(LEASE_ARBITER_TABLE_RETENTION_STATEMENT, this.leaseArbiterTableName,
retentionPeriodMillis);
this.thisTableGetInfoStatement = String.format(GET_EVENT_INFO_STATEMENT, this.leaseArbiterTableName,
this.constantsTableName);
this.thisTableGetInfoStatementForReminder = String.format(GET_EVENT_INFO_STATEMENT_FOR_REMINDER,
this.leaseArbiterTableName, this.constantsTableName);
this.thisTableSelectAfterInsertStatement = String.format(SELECT_AFTER_INSERT_STATEMENT, this.leaseArbiterTableName,
this.constantsTableName);
this.thisTableAcquireLeaseIfMatchingAllStatement =
String.format(CONDITIONALLY_ACQUIRE_LEASE_IF_MATCHING_ALL_COLS_STATEMENT, this.leaseArbiterTableName);
this.thisTableAcquireLeaseIfFinishedStatement =
String.format(CONDITIONALLY_ACQUIRE_LEASE_IF_FINISHED_LEASING_STATEMENT, this.leaseArbiterTableName);
this.dataSource = MysqlDataSourceFactory.get(config, SharedResourcesBrokerFactory.getImplicitBroker());
this.dbStatementExecutor = new DBStatementExecutor(this.dataSource, log);
String createArbiterStatement = String.format(
CREATE_LEASE_ARBITER_TABLE_STATEMENT, leaseArbiterTableName);
try (Connection connection = dataSource.getConnection();
PreparedStatement createStatement = connection.prepareStatement(createArbiterStatement)) {
createStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
throw new IOException("Table creation failure for " + leaseArbiterTableName, e);
}
initializeConstantsTable();
// Periodically deletes all rows in the table with event_timestamp older than the retention period defined by config.
dbStatementExecutor.repeatSqlCommandExecutionAtInterval(thisTableRetentionStatement, 4, TimeUnit.HOURS);
log.info("MysqlMultiActiveLeaseArbiter initialized");
}
// Initialize Constants table if needed and insert row into it if one does not exist
private void initializeConstantsTable() throws IOException {
String createConstantsStatement = String.format(CREATE_CONSTANTS_TABLE_STATEMENT, this.constantsTableName);
dbStatementExecutor.withPreparedStatement(createConstantsStatement, createStatement -> createStatement.executeUpdate(),
true);
String insertConstantsStatement = String.format(UPSERT_CONSTANTS_TABLE_STATEMENT, this.constantsTableName);
dbStatementExecutor.withPreparedStatement(insertConstantsStatement, insertStatement -> {
int i = 0;
insertStatement.setInt(++i, epsilonMillis);
insertStatement.setInt(++i, lingerMillis);
return insertStatement.executeUpdate();
}, true);
}
@Override
public LeaseAttemptStatus tryAcquireLease(DagActionStore.DagAction flowAction, long eventTimeMillis,
boolean isReminderEvent) throws IOException {
log.info("Multi-active scheduler about to handle trigger event: [{}, is: {}, triggerEventTimestamp: {}]",
flowAction, isReminderEvent ? "reminder" : "original", eventTimeMillis);
// Query lease arbiter table about this flow action
Optional<GetEventInfoResult> getResult = getExistingEventInfo(flowAction, isReminderEvent, eventTimeMillis);
try {
if (!getResult.isPresent()) {
log.debug("tryAcquireLease for [{}, is; {}, eventTimestamp: {}] - CASE 1: no existing row for this flow action,"
+ " then go ahead and insert", flowAction, isReminderEvent ? "reminder" : "original", eventTimeMillis);
int numRowsUpdated = attemptLeaseIfNewRow(flowAction);
return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, Optional.empty(), isReminderEvent);
}
// Extract values from result set
Timestamp dbEventTimestamp = getResult.get().getDbEventTimestamp();
Timestamp dbLeaseAcquisitionTimestamp = getResult.get().getDbLeaseAcquisitionTimestamp();
boolean isWithinEpsilon = getResult.get().isWithinEpsilon();
int leaseValidityStatus = getResult.get().getLeaseValidityStatus();
// Used to calculate minimum amount of time until a participant should check whether a lease expired
int dbLinger = getResult.get().getDbLinger();
Timestamp dbCurrentTimestamp = getResult.get().getDbCurrentTimestamp();
// For reminder event, we can stop early if the reminder eventTimeMillis is older than the current event in the db
// because db laundering tells us that the currently worked on db event is newer and will have its own reminders
if (isReminderEvent) {
if (eventTimeMillis < dbEventTimestamp.getTime()) {
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - dbEventTimeMillis: {} - A new event trigger "
+ "is being worked on, so this older reminder will be dropped.", flowAction,
isReminderEvent ? "reminder" : "original", eventTimeMillis, dbEventTimestamp);
return new NoLongerLeasingStatus();
}
if (eventTimeMillis > dbEventTimestamp.getTime()) {
// TODO: emit metric here to capture this unexpected behavior
log.warn("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - dbEventTimeMillis: {} - Severe constraint "
+ "violation encountered: a reminder event newer than db event was found when db laundering should "
+ "ensure monotonically increasing laundered event times.", flowAction,
isReminderEvent ? "reminder" : "original", eventTimeMillis, dbEventTimestamp.getTime());
}
if (eventTimeMillis == dbEventTimestamp.getTime()) {
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - dbEventTimeMillis: {} - Reminder event time "
+ "is the same as db event.", flowAction, isReminderEvent ? "reminder" : "original",
eventTimeMillis, dbEventTimestamp);
}
}
log.info("Multi-active arbiter replacing local trigger event timestamp [{}, is: {}, triggerEventTimestamp: {}] "
+ "with database eventTimestamp {} (in epoch-millis)", flowAction, isReminderEvent ? "reminder" : "original",
eventTimeMillis, dbCurrentTimestamp.getTime());
// Lease is valid
if (leaseValidityStatus == 1) {
if (isWithinEpsilon) {
DagActionStore.DagAction updatedFlowAction = flowAction.updateFlowExecutionId(dbEventTimestamp.getTime());
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - CASE 2: Same event, lease is valid",
updatedFlowAction, isReminderEvent ? "reminder" : "original", dbCurrentTimestamp.getTime());
// Utilize db timestamp for reminder
return new LeasedToAnotherStatus(updatedFlowAction,
dbLeaseAcquisitionTimestamp.getTime() + dbLinger - dbCurrentTimestamp.getTime());
}
DagActionStore.DagAction updatedFlowAction = flowAction.updateFlowExecutionId(dbCurrentTimestamp.getTime());
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - CASE 3: Distinct event, lease is valid",
updatedFlowAction, isReminderEvent ? "reminder" : "original", dbCurrentTimestamp.getTime());
// Utilize db lease acquisition timestamp for wait time
return new LeasedToAnotherStatus(updatedFlowAction,
dbLeaseAcquisitionTimestamp.getTime() + dbLinger - dbCurrentTimestamp.getTime());
} // Lease is invalid
else if (leaseValidityStatus == 2) {
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - CASE 4: Lease is out of date (regardless of "
+ "whether same or distinct event)", flowAction, isReminderEvent ? "reminder" : "original",
dbCurrentTimestamp.getTime());
if (isWithinEpsilon && !isReminderEvent) {
log.warn("Lease should not be out of date for the same trigger event since epsilon << linger for flowAction"
+ " {}, db eventTimestamp {}, db leaseAcquisitionTimestamp {}, linger {}", flowAction,
dbEventTimestamp, dbLeaseAcquisitionTimestamp, dbLinger);
}
// Use our event to acquire lease, check for previous db eventTimestamp and leaseAcquisitionTimestamp
int numRowsUpdated = attemptLeaseIfExistingRow(thisTableAcquireLeaseIfMatchingAllStatement, flowAction,
true,true, dbEventTimestamp, dbLeaseAcquisitionTimestamp);
return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, Optional.of(dbCurrentTimestamp), isReminderEvent);
} // No longer leasing this event
if (isWithinEpsilon) {
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - CASE 5: Same event, no longer leasing event"
+ " in db", flowAction, isReminderEvent ? "reminder" : "original", dbCurrentTimestamp.getTime());
return new NoLongerLeasingStatus();
}
log.debug("tryAcquireLease for [{}, is: {}, eventTimestamp: {}] - CASE 6: Distinct event, no longer leasing "
+ "event in db", flowAction, isReminderEvent ? "reminder" : "original", dbCurrentTimestamp.getTime());
// Use our event to acquire lease, check for previous db eventTimestamp and NULL leaseAcquisitionTimestamp
int numRowsUpdated = attemptLeaseIfExistingRow(thisTableAcquireLeaseIfFinishedStatement, flowAction,
true, false, dbEventTimestamp, null);
return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, Optional.of(dbCurrentTimestamp), isReminderEvent);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Checks leaseArbiterTable for an existing entry for this flow action and event time
*/
protected Optional<GetEventInfoResult> getExistingEventInfo(DagActionStore.DagAction flowAction,
boolean isReminderEvent, long eventTimeMillis) throws IOException {
return dbStatementExecutor.withPreparedStatement(isReminderEvent ? thisTableGetInfoStatementForReminder : thisTableGetInfoStatement,
getInfoStatement -> {
int i = 0;
if (isReminderEvent) {
getInfoStatement.setTimestamp(++i, new Timestamp(eventTimeMillis), UTC_CAL.get());
}
getInfoStatement.setString(++i, flowAction.getFlowGroup());
getInfoStatement.setString(++i, flowAction.getFlowName());
getInfoStatement.setString(++i, flowAction.getFlowActionType().toString());
ResultSet resultSet = getInfoStatement.executeQuery();
try {
if (!resultSet.next()) {
return Optional.<GetEventInfoResult>empty();
}
return Optional.of(createGetInfoResult(resultSet));
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}, true);
}
protected GetEventInfoResult createGetInfoResult(ResultSet resultSet) throws IOException {
try {
// Extract values from result set
Timestamp dbEventTimestamp = resultSet.getTimestamp("utc_event_timestamp", UTC_CAL.get());
Timestamp dbLeaseAcquisitionTimestamp = resultSet.getTimestamp("utc_lease_acquisition_timestamp", UTC_CAL.get());
boolean withinEpsilon = resultSet.getBoolean("is_within_epsilon");
int leaseValidityStatus = resultSet.getInt("lease_validity_status");
int dbLinger = resultSet.getInt("linger");
Timestamp dbCurrentTimestamp = resultSet.getTimestamp("utc_current_timestamp", UTC_CAL.get());
return new GetEventInfoResult(dbEventTimestamp, dbLeaseAcquisitionTimestamp, withinEpsilon, leaseValidityStatus,
dbLinger, dbCurrentTimestamp);
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new IOException(e);
}
}
}
}
/**
* Called by participant to try to acquire lease for a flow action that does not have an attempt in progress or in
* near past for it.
* @return int corresponding to number of rows updated by INSERT statement to acquire lease
*/
protected int attemptLeaseIfNewRow(DagActionStore.DagAction flowAction) throws IOException {
String formattedAcquireLeaseNewRowStatement =
String.format(ACQUIRE_LEASE_IF_NEW_ROW_STATEMENT, this.leaseArbiterTableName);
return dbStatementExecutor.withPreparedStatement(formattedAcquireLeaseNewRowStatement,
insertStatement -> {
completeInsertPreparedStatement(insertStatement, flowAction);
try {
return insertStatement.executeUpdate();
} catch (SQLIntegrityConstraintViolationException e) {
if (!e.getMessage().contains("Duplicate entry")) {
throw e;
}
return 0;
}
}, true);
}
/**
* Called by participant to try to acquire lease for a flow action that has an existing, completed, or expired lease
* attempt for the flow action in the table.
* @return int corresponding to number of rows updated by INSERT statement to acquire lease
*/
protected int attemptLeaseIfExistingRow(String acquireLeaseStatement, DagActionStore.DagAction flowAction,
boolean needEventTimeCheck, boolean needLeaseAcquisition, Timestamp dbEventTimestamp,
Timestamp dbLeaseAcquisitionTimestamp) throws IOException {
return dbStatementExecutor.withPreparedStatement(acquireLeaseStatement,
insertStatement -> {
completeUpdatePreparedStatement(insertStatement, flowAction, needEventTimeCheck, needLeaseAcquisition,
dbEventTimestamp, dbLeaseAcquisitionTimestamp);
return insertStatement.executeUpdate();
}, true);
}
/**
* Checks leaseArbiter table for a row corresponding to this flow action to determine if the lease acquisition attempt
* was successful or not.
*/
protected SelectInfoResult getRowInfo(DagActionStore.DagAction flowAction) throws IOException {
return dbStatementExecutor.withPreparedStatement(thisTableSelectAfterInsertStatement,
selectStatement -> {
completeWhereClauseMatchingKeyPreparedStatement(selectStatement, flowAction);
ResultSet resultSet = selectStatement.executeQuery();
try {
return createSelectInfoResult(resultSet);
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}, true);
}
protected static SelectInfoResult createSelectInfoResult(ResultSet resultSet) throws IOException {
try {
if (!resultSet.next()) {
throw new IOException("Expected resultSet containing row information for the lease that was attempted but "
+ "received nothing.");
}
if (resultSet.getTimestamp("utc_event_timestamp", UTC_CAL.get()) == null) {
throw new IOException("event_timestamp should never be null (it is always set to current timestamp)");
}
long eventTimeMillis = resultSet.getTimestamp("utc_event_timestamp", UTC_CAL.get()).getTime();
// Lease acquisition timestamp is null if another participant has completed the lease
Optional<Long> leaseAcquisitionTimeMillis =
resultSet.getTimestamp("utc_lease_acquisition_timestamp", UTC_CAL.get()) == null ? Optional.empty() :
Optional.of(resultSet.getTimestamp("utc_lease_acquisition_timestamp", UTC_CAL.get()).getTime());
int dbLinger = resultSet.getInt("linger");
return new SelectInfoResult(eventTimeMillis, leaseAcquisitionTimeMillis, dbLinger);
} catch (SQLException e) {
throw new IOException(e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new IOException(e);
}
}
}
}
/**
* Parse result of attempted insert/update to obtain a lease for a
* {@link org.apache.gobblin.runtime.api.DagActionStore.DagAction} event by selecting values corresponding to that
* event from the table to return the corresponding status based on successful insert/update or not.
* @throws SQLException
* @throws IOException
*/
protected LeaseAttemptStatus evaluateStatusAfterLeaseAttempt(int numRowsUpdated,
DagActionStore.DagAction flowAction, Optional<Timestamp> dbCurrentTimestamp, boolean isReminderEvent)
throws SQLException, IOException {
// Fetch values in row after attempted insert
SelectInfoResult selectInfoResult = getRowInfo(flowAction);
// Another participant won the lease in between
if (!selectInfoResult.getLeaseAcquisitionTimeMillis().isPresent()) {
return new NoLongerLeasingStatus();
}
DagActionStore.DagAction updatedFlowAction = flowAction.updateFlowExecutionId(selectInfoResult.eventTimeMillis);
if (numRowsUpdated == 1) {
log.info("Obtained lease for [{}, is: {}, eventTimestamp: {}] successfully!", updatedFlowAction,
isReminderEvent ? "reminder" : "original", selectInfoResult.eventTimeMillis);
return new LeaseObtainedStatus(updatedFlowAction, selectInfoResult.getLeaseAcquisitionTimeMillis().get());
}
log.info("Another participant acquired lease in between for [{}, is: {}, eventTimestamp: {}] - num rows updated: {}",
updatedFlowAction, isReminderEvent ? "reminder" : "original", selectInfoResult.eventTimeMillis, numRowsUpdated);
// Another participant acquired lease in between
return new LeasedToAnotherStatus(updatedFlowAction,
selectInfoResult.getLeaseAcquisitionTimeMillis().get() + selectInfoResult.getDbLinger()
- (dbCurrentTimestamp.isPresent() ? dbCurrentTimestamp.get().getTime() : System.currentTimeMillis()));
}
/**
* Complete the INSERT statement for a new flow action lease where the flow action is not present in the table
* @param statement
* @param flowAction
* @throws SQLException
*/
protected static void completeInsertPreparedStatement(PreparedStatement statement,
DagActionStore.DagAction flowAction) throws SQLException {
int i = 0;
// Values to set in new row
statement.setString(++i, flowAction.getFlowGroup());
statement.setString(++i, flowAction.getFlowName());
statement.setString(++i, flowAction.getFlowActionType().toString());
}
/**
* Complete the WHERE clause to match a flow action in a select statement
* @param statement
* @param flowAction
* @throws SQLException
*/
protected static void completeWhereClauseMatchingKeyPreparedStatement(PreparedStatement statement,
DagActionStore.DagAction flowAction) throws SQLException {
int i = 0;
statement.setString(++i, flowAction.getFlowGroup());
statement.setString(++i, flowAction.getFlowName());
statement.setString(++i, flowAction.getFlowActionType().toString());
}
/**
* Complete the UPDATE prepared statements for a flow action that already exists in the table that needs to be
* updated.
* @param statement
* @param flowAction
* @param needEventTimeCheck true if need to compare `originalEventTimestamp` with db event_timestamp
* @param needLeaseAcquisitionTimeCheck true if need to compare `originalLeaseAcquisitionTimestamp` with db one
* @param originalEventTimestamp value to compare to db one, null if not needed
* @param originalLeaseAcquisitionTimestamp value to compare to db one, null if not needed
* @throws SQLException
*/
protected static void completeUpdatePreparedStatement(PreparedStatement statement,
DagActionStore.DagAction flowAction, boolean needEventTimeCheck, boolean needLeaseAcquisitionTimeCheck,
Timestamp originalEventTimestamp, Timestamp originalLeaseAcquisitionTimestamp) throws SQLException {
int i = 0;
// Values to check if existing row matches previous read
statement.setString(++i, flowAction.getFlowGroup());
statement.setString(++i, flowAction.getFlowName());
statement.setString(++i, flowAction.getFlowActionType().toString());
// Values that may be needed depending on the insert statement
if (needEventTimeCheck) {
statement.setTimestamp(++i, originalEventTimestamp, UTC_CAL.get());
}
if (needLeaseAcquisitionTimeCheck) {
statement.setTimestamp(++i, originalLeaseAcquisitionTimestamp, UTC_CAL.get());
}
}
@Override
public boolean recordLeaseSuccess(LeaseObtainedStatus status)
throws IOException {
DagActionStore.DagAction flowAction = status.getFlowAction();
String flowGroup = flowAction.getFlowGroup();
String flowName = flowAction.getFlowName();
DagActionStore.FlowActionType flowActionType = flowAction.getFlowActionType();
return dbStatementExecutor.withPreparedStatement(String.format(CONDITIONALLY_COMPLETE_LEASE_STATEMENT, leaseArbiterTableName),
updateStatement -> {
int i = 0;
updateStatement.setString(++i, flowGroup);
updateStatement.setString(++i, flowName);
updateStatement.setString(++i, flowActionType.toString());
updateStatement.setTimestamp(++i, new Timestamp(status.getEventTimeMillis()), UTC_CAL.get());
updateStatement.setTimestamp(++i, new Timestamp(status.getLeaseAcquisitionTimestamp()), UTC_CAL.get());
int numRowsUpdated = updateStatement.executeUpdate();
if (numRowsUpdated == 0) {
log.info("Multi-active lease arbiter lease attempt: [{}, eventTimestamp: {}] - FAILED to complete because "
+ "lease expired or event cleaned up before host completed required actions", flowAction,
status.getEventTimeMillis());
return false;
}
if( numRowsUpdated == 1) {
log.info("Multi-active lease arbiter lease attempt: [{}, eventTimestamp: {}] - COMPLETED, no longer leasing"
+ " this event after this.", flowAction, status.getEventTimeMillis());
return true;
};
throw new IOException(String.format("Attempt to complete lease use: [%s, eventTimestamp: %s] - updated more "
+ "rows than expected", flowAction, status.getEventTimeMillis()));
}, true);
}
/**
* DTO for arbiter's current lease state for a FlowActionEvent
*/
@Data
static class GetEventInfoResult {
private final Timestamp dbEventTimestamp;
private final Timestamp dbLeaseAcquisitionTimestamp;
private final boolean withinEpsilon;
private final int leaseValidityStatus;
private final int dbLinger;
private final Timestamp dbCurrentTimestamp;
}
/**
DTO for result of SELECT query used to determine status of lease acquisition attempt
*/
@Data
static class SelectInfoResult {
private final long eventTimeMillis;
private final Optional<Long> leaseAcquisitionTimeMillis;
private final int dbLinger;
}
}
| 1,527 |
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/api/FlowSpecSearchObject.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.api;
import java.io.IOException;
import java.net.URI;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Splitter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.service.FlowId;
/**
* This is a class to package all the parameters that should be used to search {@link FlowSpec} in a {@link SpecStore}
*/
@Getter
@Builder
@ToString
@AllArgsConstructor
@Slf4j
public class FlowSpecSearchObject implements SpecSearchObject {
private final URI flowSpecUri;
private final String flowGroup;
private final String flowName;
private final String templateURI;
private final String userToProxy;
private final String sourceIdentifier;
private final String destinationIdentifier;
private final String schedule;
private final String modifiedTimestamp;
private final Boolean isRunImmediately;
private final String owningGroup;
private final String propertyFilter;
private final int start;
private final int count;
public static FlowSpecSearchObject fromFlowId(FlowId flowId) {
return FlowSpecSearchObject.builder().flowGroup(flowId.getFlowGroup()).flowName(flowId.getFlowName()).build();
}
/** This expects at least one parameter of `this` to be not null */
@Override
public String augmentBaseGetStatement(String baseStatement)
throws IOException {
List<String> conditions = new ArrayList<>();
List<String> limitAndOffset = new ArrayList<>();
/*
* IMPORTANT: the order of `conditions` added must align with the order of parameter binding later in `completePreparedStatement`!
*/
if (this.getFlowSpecUri() != null) {
conditions.add("spec_uri = ?");
}
if (this.getFlowGroup() != null) {
conditions.add("flow_group = ?");
}
if (this.getFlowName() != null) {
conditions.add("flow_name = ?");
}
if (this.getTemplateURI() != null) {
conditions.add("template_uri = ?");
}
if (this.getUserToProxy() != null) {
conditions.add("user_to_proxy = ?");
}
if (this.getSourceIdentifier() != null) {
conditions.add("source_identifier = ?");
}
if (this.getDestinationIdentifier() != null) {
conditions.add("destination_identifier = ?");
}
if (this.getSchedule() != null) {
conditions.add("schedule = ?");
}
if (this.getModifiedTimestamp() != null) {
conditions.add("modified_time = ?");
}
if (this.getIsRunImmediately() != null) {
conditions.add("isRunImmediately = ?");
}
if (this.getOwningGroup() != null) {
conditions.add("owning_group = ?");
}
if (this.getCount() > 0) {
// Order by two fields to make a full order by
limitAndOffset.add(" ORDER BY spec_uri ASC LIMIT ?");
if (this.getStart() > 0) {
limitAndOffset.add(" OFFSET ?");
}
}
// If the propertyFilter is myKey=myValue, it looks for a config where key is `myKey` and value contains string `myValue`.
// If the propertyFilter string does not have `=`, it considers the string as a key and just looks for its existence.
// Multiple occurrences of `=` in propertyFilter are not supported and ignored completely.
if (this.getPropertyFilter() != null) {
String propertyFilter = this.getPropertyFilter();
Splitter commaSplitter = Splitter.on(",").trimResults().omitEmptyStrings();
for (String property : commaSplitter.splitToList(propertyFilter)) {
if (property.contains("=")) {
String[] keyValue = property.split("=");
if (keyValue.length != 2) {
log.error("Incorrect flow config search query");
continue;
}
conditions.add("spec_json->'$.configAsProperties.\"" + keyValue[0] + "\"' like " + "'%" + keyValue[1] + "%'");
} else {
conditions.add("spec_json->'$.configAsProperties.\"" + property + "\"' is not null");
}
}
}
if (conditions.size() == 0 && limitAndOffset.size() == 0) {
throw new IOException("At least one condition is required to query flow configs.");
}
return baseStatement + String.join(" AND ", conditions) + String.join(" ", limitAndOffset);
}
@Override
public void completePreparedStatement(PreparedStatement statement)
throws SQLException {
int i = 0;
/*
* IMPORTANT: the order of binding params must align with the order of building the conditions earlier in `augmentBaseGetStatement`!
*/
if (this.getFlowSpecUri() != null) {
statement.setString(++i, this.getFlowSpecUri().toString());
}
if (this.getFlowGroup() != null) {
statement.setString(++i, this.getFlowGroup());
}
if (this.getFlowName() != null) {
statement.setString(++i, this.getFlowName());
}
if (this.getTemplateURI() != null) {
statement.setString(++i, this.getTemplateURI());
}
if (this.getUserToProxy() != null) {
statement.setString(++i, this.getUserToProxy());
}
if (this.getSourceIdentifier() != null) {
statement.setString(++i, this.getSourceIdentifier());
}
if (this.getDestinationIdentifier() != null) {
statement.setString(++i, this.getDestinationIdentifier());
}
if (this.getSchedule() != null) {
statement.setString(++i, this.getSchedule());
}
if (this.getIsRunImmediately() != null) {
statement.setBoolean(++i, this.getIsRunImmediately());
}
if (this.getOwningGroup() != null) {
statement.setString(++i, this.getOwningGroup());
}
if (this.getCount() > 0) {
statement.setInt(++i, this.getCount());
if (this.getStart() > 0) {
statement.setInt(++i, this.getStart());
}
}
}
}
| 1,528 |
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/api/FlowSpec.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.api;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.linkedin.data.template.StringMap;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.service.FlowConfig;
import org.apache.gobblin.service.FlowId;
import org.apache.gobblin.service.Schedule;
import org.apache.gobblin.service.ServiceConfigKeys;
import org.apache.gobblin.util.ConfigUtils;
/**
* Defines a Gobblin Flow (potentially collection of {@link FlowSpec}) that can be run once, or multiple times.
* A {@link FlowSpec} is {@link Configurable} so it has an associated {@link Config}, along with
* other mandatory properties such as a uri, description, and version. A {@link FlowSpec} is
* uniquely identified by its uri (containing group and name).
*
*/
@Alpha
@Data
@EqualsAndHashCode(exclude={"compilationErrors"})
@SuppressFBWarnings(value="SE_BAD_FIELD",
justification = "FindBugs complains about Config not being serializable, but the implementation of Config is serializable")
public class FlowSpec implements Configurable, Spec {
// Key for Property associated with modified_time
public static final String MODIFICATION_TIME_KEY = "modified_time";
private static final long serialVersionUID = -5511988862945107734L;
/** An URI identifying the flow. */
final URI uri;
/** The implementation-defined version of this spec. */
final String version;
/** Human-readable description of the flow spec */
final String description;
/** Flow config as a typesafe config object */
final Config config;
/** Flow config as a properties collection for backwards compatibility */
// Note that this property is not strictly necessary as it can be generated from the typesafe
// config. We use it as a cache until typesafe config is more widely adopted in Gobblin.
final Properties configAsProperties;
/** URI of {@link org.apache.gobblin.runtime.api.JobTemplate} to use. */
final Optional<Set<URI>> templateURIs;
/** Child {@link Spec}s to this {@link FlowSpec} **/
// Note that a FlowSpec can be materialized into multiple FlowSpec or JobSpec hierarchy
final Optional<List<Spec>> childSpecs;
/** List of exceptions that occurred during compilation of this FlowSpec **/
final List<CompilationError> compilationErrors = new ArrayList<>();
public static FlowSpec.Builder builder(URI flowSpecUri) {
return new FlowSpec.Builder(flowSpecUri);
}
public static FlowSpec.Builder builder(String flowSpecUri) {
return new FlowSpec.Builder(flowSpecUri);
}
public static FlowSpec.Builder builder() {
return new FlowSpec.Builder();
}
/** Creates a builder for the FlowSpec based on values in a flow properties config. */
public static FlowSpec.Builder builder(URI catalogURI, Properties flowProps) {
String name = flowProps.getProperty(ConfigurationKeys.FLOW_NAME_KEY);
String group = flowProps.getProperty(ConfigurationKeys.FLOW_GROUP_KEY, "default");
try {
URI flowURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(),
"/" + group + "/" + name, null);
FlowSpec.Builder builder = new FlowSpec.Builder(flowURI).withConfigAsProperties(flowProps);
String descr = flowProps.getProperty(ConfigurationKeys.FLOW_DESCRIPTION_KEY, null);
if (null != descr) {
builder = builder.withDescription(descr);
}
return builder;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create a FlowSpec URI: " + e, e);
}
}
public void addCompilationError(String src, String dst, String errorMessage, int numberOfHops) {
this.compilationErrors.add(new CompilationError(getConfig(), src, dst, errorMessage, numberOfHops));
}
public void addCompilationError(String src, String dst, String errorMessage) {
this.compilationErrors.add(new CompilationError(getConfig(), src, dst, errorMessage));
}
public void clearCompilationErrors() {
this.compilationErrors.clear();
}
@EqualsAndHashCode
public static class CompilationError {
public int errorPriority;
public String errorMessage;
// Increment the error priority by 1 to eliminate flows with a self edge from having the same priority as a single hop flow edge.
// E.g. Cluster1 -> Cluster2 is the desired edge. Cluster1 -> Cluster2 would have error priority of 0, Cluster1 -> Cluster1 -> Cluster2 would have error priority of 1
public CompilationError(Config config, String src, String dst, String errorMessage, int numberOfHops) {
this(config, src, dst, errorMessage);
if (numberOfHops > 1) {
errorPriority++;
}
}
public CompilationError(Config config, String src, String dst, String errorMessage) {
errorPriority = 0;
if (!src.equals(ConfigUtils.getString(config, ServiceConfigKeys.FLOW_SOURCE_IDENTIFIER_KEY, ""))){
errorPriority++;
}
if (!ConfigUtils.getStringList(config, ServiceConfigKeys.FLOW_DESTINATION_IDENTIFIER_KEY)
.containsAll(Arrays.asList(StringUtils.split(dst, ",")))){
errorPriority++;
}
this.errorMessage = errorMessage;
}
public CompilationError(int errorPriority, String errorMessage) {
this.errorPriority = errorPriority;
this.errorMessage = errorMessage;
}
}
public String toShortString() {
return getUri().toString() + "/" + getVersion();
}
public String toLongString() {
return getUri().toString() + "/" + getVersion() + "[" + getDescription() + "]";
}
@Override
public String toString() {
return toShortString();
}
/**
* Builder for {@link FlowSpec}s.
* <p> Defaults/conventions:
* <ul>
* <li> Default flowCatalogURI is {@link #DEFAULT_FLOW_CATALOG_SCHEME}:
* <li> Convention for FlowSpec URI: <flowCatalogURI>/config.get({@link ConfigurationKeys#FLOW_GROUP_KEY})/config.get({@link ConfigurationKeys#FLOW_NAME_KEY})
* <li> Convention for Description: config.get({@link ConfigurationKeys#FLOW_DESCRIPTION_KEY})
* <li> Default version: empty
* </ul>
*/
public static class Builder {
public static final String DEFAULT_FLOW_CATALOG_SCHEME = "gobblin-flow";
public static final String DEFAULT_VERSION = "";
@VisibleForTesting
private Optional<Config> config = Optional.absent();
private Optional<Properties> configAsProperties = Optional.absent();
private Optional<URI> uri;
private String version = FlowSpec.Builder.DEFAULT_VERSION;
private Optional<String> description = Optional.absent();
private Optional<URI> flowCatalogURI = Optional.absent();
private Optional<Set<URI>> templateURIs = Optional.absent();
private Optional<List<Spec>> childSpecs = Optional.absent();
public Builder(URI flowSpecUri) {
Preconditions.checkNotNull(flowSpecUri);
this.uri = Optional.of(flowSpecUri);
}
public Builder(String flowSpecUri) {
Preconditions.checkNotNull(flowSpecUri);
Preconditions.checkNotNull(flowSpecUri);
try {
this.uri = Optional.of(new URI(flowSpecUri));
}
catch (URISyntaxException e) {
throw new RuntimeException("Invalid FlowSpec config: " + e, e);
}
}
public Builder() {
this.uri = Optional.absent();
}
public FlowSpec build() {
Preconditions.checkNotNull(this.uri);
Preconditions.checkArgument(null != version, "Version should not be null");
return new FlowSpec(getURI(), getVersion(), getDescription(), getConfig(),
getConfigAsProperties(), getTemplateURIs(), getChildSpecs());
}
/** The scheme and authority of the flow catalog URI are used to generate FlowSpec URIs from
* flow configs. */
public FlowSpec.Builder withFlowCatalogURI(URI flowCatalogURI) {
this.flowCatalogURI = Optional.of(flowCatalogURI);
return this;
}
public FlowSpec.Builder withFlowCatalogURI(String flowCatalogURI) {
try {
this.flowCatalogURI = Optional.of(new URI(flowCatalogURI));
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to set flow catalog URI: " + e, e);
}
return this;
}
public URI getDefaultFlowCatalogURI() {
try {
return new URI(DEFAULT_FLOW_CATALOG_SCHEME, null, "/", null, null);
} catch (URISyntaxException e) {
// should not happen
throw new Error("Unexpected exception: " + e, e);
}
}
public URI getFlowCatalogURI() {
if (! this.flowCatalogURI.isPresent()) {
this.flowCatalogURI = Optional.of(getDefaultFlowCatalogURI());
}
return this.flowCatalogURI.get();
}
public URI getDefaultURI() {
URI flowCatalogURI = getFlowCatalogURI();
Config flowCfg = getConfig();
String name = flowCfg.hasPath(ConfigurationKeys.FLOW_NAME_KEY) ?
flowCfg.getString(ConfigurationKeys.FLOW_NAME_KEY) :
"default";
String group = flowCfg.hasPath(ConfigurationKeys.FLOW_GROUP_KEY) ?
flowCfg.getString(ConfigurationKeys.FLOW_GROUP_KEY) :
"default";
try {
return new URI(flowCatalogURI.getScheme(), flowCatalogURI.getAuthority(),
"/" + group + "/" + name, null, null);
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create default FlowSpec URI:" + e, e);
}
}
public URI getURI() {
if (! this.uri.isPresent()) {
this.uri = Optional.of(getDefaultURI());
}
return this.uri.get();
}
public FlowSpec.Builder withVersion(String version) {
Preconditions.checkNotNull(version);
this.version = version;
return this;
}
public String getVersion() {
return this.version;
}
public FlowSpec.Builder withDescription(String flowDescription) {
Preconditions.checkNotNull(flowDescription);
this.description = Optional.of(flowDescription);
return this;
}
public String getDefaultDescription() {
Config flowConf = getConfig();
return flowConf.hasPath(ConfigurationKeys.FLOW_DESCRIPTION_KEY) ?
flowConf.getString(ConfigurationKeys.FLOW_DESCRIPTION_KEY) :
"Gobblin flow " + getURI();
}
public String getDescription() {
if (! this.description.isPresent()) {
this.description = Optional.of(getDefaultDescription());
}
return this.description.get();
}
public Config getDefaultConfig() {
return ConfigFactory.empty();
}
public Config getConfig() {
if (!this.config.isPresent()) {
this.config = this.configAsProperties.isPresent() ?
Optional.of(ConfigUtils.propertiesToTypedConfig(this.configAsProperties.get(),
Optional.<String>absent())) :
Optional.of(getDefaultConfig());
}
return this.config.get();
}
public FlowSpec.Builder withConfig(Config flowConfig) {
Preconditions.checkNotNull(flowConfig);
this.config = Optional.of(flowConfig);
return this;
}
public Properties getConfigAsProperties() {
if (!this.configAsProperties.isPresent()) {
this.configAsProperties = Optional.of(ConfigUtils.configToProperties(this.config.get()));
}
return this.configAsProperties.get();
}
public FlowSpec.Builder withConfigAsProperties(Properties flowConfig) {
Preconditions.checkNotNull(flowConfig);
this.configAsProperties = Optional.of(flowConfig);
return this;
}
public Optional<Set<URI>> getTemplateURIs() {
return this.templateURIs;
}
public FlowSpec.Builder withTemplate(URI templateURI) {
Preconditions.checkNotNull(templateURI);
if (!this.templateURIs.isPresent()) {
Set<URI> templateURISet = Sets.newHashSet();
this.templateURIs = Optional.of(templateURISet);
}
this.templateURIs.get().add(templateURI);
return this;
}
public FlowSpec.Builder withTemplates(Collection templateURIs) {
Preconditions.checkNotNull(templateURIs);
if (!this.templateURIs.isPresent()) {
Set<URI> templateURISet = Sets.newHashSet();
this.templateURIs = Optional.of(templateURISet);
}
this.templateURIs.get().addAll(templateURIs);
return this;
}
public Optional<List<Spec>> getChildSpecs() {
return this.childSpecs;
}
public FlowSpec.Builder withChildSpec(Spec childSpec) {
Preconditions.checkNotNull(childSpec);
if (!this.childSpecs.isPresent()) {
List<Spec> childSpecsList = Lists.newArrayList();
this.childSpecs = Optional.of(childSpecsList);
}
this.childSpecs.get().add(childSpec);
return this;
}
public FlowSpec.Builder withChildSpecs(List<Spec> childSpecs) {
Preconditions.checkNotNull(childSpecs);
if (!this.childSpecs.isPresent()) {
List<Spec> childSpecsList = Lists.newArrayList();
this.childSpecs = Optional.of(childSpecsList);
}
this.childSpecs.get().addAll(childSpecs);
return this;
}
}
/**
* get the private uri as the primary key for this object.
* @return URI of the FlowSpec
*/
public URI getUri() {
return this.uri;
}
public Boolean isExplain() {
return ConfigUtils.getBoolean(getConfig(), ConfigurationKeys.FLOW_EXPLAIN_KEY, false);
}
public boolean isScheduled() {
return getConfig().hasPath(ConfigurationKeys.JOB_SCHEDULE_KEY);
}
@Slf4j
public static class Utils {
private final static String URI_SCHEME = "gobblin-flow";
private final static String URI_AUTHORITY = null;
private final static String URI_PATH_SEPARATOR = "/";
private final static String URI_QUERY = null;
private final static String URI_FRAGMENT = null;
private final static int EXPECTED_NUM_URI_PATH_TOKENS = 3;
public static URI createFlowSpecUri(FlowId flowId)
throws URISyntaxException {
return new URI(URI_SCHEME, URI_AUTHORITY, createUriPath(flowId), URI_QUERY, URI_FRAGMENT);
}
private static String createUriPath(FlowId flowId) {
return URI_PATH_SEPARATOR + flowId.getFlowGroup() + URI_PATH_SEPARATOR + flowId.getFlowName();
}
/**
* returns the flow name from the flowUri
* @param flowUri FlowUri
* @return null if the provided flowUri is not valid
*/
public static String getFlowName(URI flowUri) {
String[] uriTokens = flowUri.getPath().split("/");
if (uriTokens.length != EXPECTED_NUM_URI_PATH_TOKENS) {
log.error("Invalid URI {}.", flowUri);
return null;
}
return uriTokens[EXPECTED_NUM_URI_PATH_TOKENS - 1];
}
/**
* returns the flow group from the flowUri
* @param flowUri FlowUri
* @return null if the provided flowUri is not valid
*/
public static String getFlowGroup(URI flowUri) {
String[] uriTokens = flowUri.getPath().split("/");
if (uriTokens.length != EXPECTED_NUM_URI_PATH_TOKENS) {
log.error("Invalid URI {}.", flowUri);
return null;
}
return uriTokens[EXPECTED_NUM_URI_PATH_TOKENS - 2];
}
/**
* Create a {@link FlowConfig} from a {@link Spec}.
* The {@link Spec} must have {@link ConfigurationKeys#FLOW_GROUP_KEY} and {@link ConfigurationKeys#FLOW_NAME_KEY} set.
* @param spec spec
* @return {@link FlowConfig}
*/
public static FlowConfig toFlowConfig(Spec spec) {
FlowSpec flowSpec = (FlowSpec) spec;
FlowConfig flowConfig = new FlowConfig();
Properties flowProps = flowSpec.getConfigAsProperties();
Schedule schedule = null;
if (flowProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) {
schedule = new Schedule();
schedule.setCronSchedule(flowProps.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY));
}
if (flowProps.containsKey(ConfigurationKeys.JOB_TEMPLATE_PATH)) {
flowConfig.setTemplateUris(flowProps.getProperty(ConfigurationKeys.JOB_TEMPLATE_PATH));
} else if (flowSpec.getTemplateURIs().isPresent()) {
flowConfig.setTemplateUris(StringUtils.join(flowSpec.getTemplateURIs().get(), ","));
} else {
flowConfig.setTemplateUris("NA");
}
if (schedule != null) {
if (flowProps.containsKey(ConfigurationKeys.FLOW_RUN_IMMEDIATELY)) {
schedule.setRunImmediately(Boolean.valueOf(flowProps.getProperty(ConfigurationKeys.FLOW_RUN_IMMEDIATELY)));
}
flowConfig.setSchedule(schedule);
}
if (flowProps.containsKey(ConfigurationKeys.FLOW_OWNING_GROUP_KEY)) {
flowConfig.setOwningGroup(flowProps.getProperty(ConfigurationKeys.FLOW_OWNING_GROUP_KEY));
}
// remove keys that were injected as part of flowSpec creation
flowProps.remove(ConfigurationKeys.JOB_SCHEDULE_KEY);
flowProps.remove(ConfigurationKeys.JOB_TEMPLATE_PATH);
StringMap flowPropsAsStringMap = new StringMap();
flowPropsAsStringMap.putAll(Maps.fromProperties(flowProps));
return flowConfig.setId(new FlowId()
.setFlowGroup(flowProps.getProperty(ConfigurationKeys.FLOW_GROUP_KEY))
.setFlowName(flowProps.getProperty(ConfigurationKeys.FLOW_NAME_KEY)))
.setProperties(flowPropsAsStringMap);
}
public static int maxFlowSpecUriLength() {
return URI_SCHEME.length() + ":".length() // URI separator
+ URI_PATH_SEPARATOR.length() + ServiceConfigKeys.MAX_FLOW_NAME_LENGTH + URI_PATH_SEPARATOR.length() + ServiceConfigKeys.MAX_FLOW_GROUP_LENGTH;
}
}
}
| 1,529 |
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/api/GobblinInstancePluginFactory.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.api;
/**
* Creates a {@link GobblinInstancePlugin} for a specific {@link GobblinInstanceDriver} .
*
* <p><b>IMPORTANT:</b> Implementations of {@link GobblinInstancePluginFactory} must have a
* default public constructor.
*/
public interface GobblinInstancePluginFactory {
/** Creates an instance of the plugin for a specific Gobblin instance */
GobblinInstancePlugin createPlugin(GobblinInstanceDriver instance);
}
| 1,530 |
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/api/JobExecutionResult.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.api;
import com.google.common.base.Preconditions;
import org.apache.gobblin.runtime.JobState.RunningState;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Represents the result of the execution of a Gobblin job.
*/
@AllArgsConstructor(access=AccessLevel.PROTECTED)
@Getter
public class JobExecutionResult implements ExecutionResult {
private final RunningState finalState;
private final Throwable errorCause;
// TODO add TaskExecutionResults
public boolean isCancelled() {
return RunningState.CANCELLED == getFinalState();
}
public boolean isSuccessful() {
return RunningState.COMMITTED == getFinalState();
}
public boolean isFailed() {
return RunningState.FAILED == getFinalState();
}
public static JobExecutionResult createSuccessResult() {
return new JobExecutionResult(RunningState.COMMITTED, null);
}
public static JobExecutionResult createFailureResult(Throwable cause) {
return new JobExecutionResult(RunningState.FAILED, cause);
}
public static JobExecutionResult createCancelledResult() {
return new JobExecutionResult(RunningState.CANCELLED, null);
}
public static JobExecutionResult createFromState(JobExecutionState state) {
Preconditions.checkArgument(null != state.getRunningState());
Preconditions.checkArgument(state.getRunningState().isDone());
if (state.getRunningState().isSuccess()) {
return JobExecutionResult.createSuccessResult();
}
else if (state.getRunningState().isCancelled()) {
return JobExecutionResult.createCancelledResult();
}
else {
// FIXME we need to capture error(s)
return JobExecutionResult.createFailureResult(
new RuntimeException("Gobblin job failed:" + state.getJobExecution()));
}
}
}
| 1,531 |
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/api/JobExecutionMonitor.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.api;
import java.util.concurrent.Future;
/**
* A simple monitoring and future object. This object can be used as a normal {@link Future} object to get {@link ExecutionResult}.
*
* It can also be used to get current job running status, which is described by {@link MonitoredObject}.
*/
public interface JobExecutionMonitor extends Future<ExecutionResult> {
MonitoredObject getRunningState();
}
| 1,532 |
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/api/JobSpecScheduler.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.api;
import java.net.URI;
import java.util.Map;
import org.apache.gobblin.annotation.Alpha;
/**
* Early alpha of the scheduler interface which is responsible of deciding when to run next the
* GobblinJob identified by a JobSpec. The scheduler maintains one {@link JobSpecSchedule} per
* JobSpec URI. Which means that scheduling a new version of JobSpec will override the schedule of
* the previous version.
*
* The scheduler is fire-and-forget. It is caller's responsibility (typically,
* {@link GobblinInstanceDriver}) to keep track of the outcome of the execution.
*/
@Alpha
public interface JobSpecScheduler extends JobSpecSchedulerListenersContainer {
/**
* Add a Gobblin job for scheduling. If the job is configured appropriately (scheduler-dependent),
* it will be executed repeatedly.
*
* @param jobSpec the JobSpec of the job
* @param jobRunnable a runnable that will execute the job
*/
public JobSpecSchedule scheduleJob(JobSpec jobSpec, Runnable jobRunnable);
/**
* Add a Gobblin job for scheduling. Job is guaranteed to run only once regardless of job outcome.
*
* @param jobSpec the JobSpec of the job
* @param jobRunnable a runnable that will execute the job
*/
public JobSpecSchedule scheduleOnce(JobSpec jobSpec, Runnable jobRunnable);
/**
* Remove a job from scheduling. This will not affect any executions that are currently running.
* @param jobSpecURI the URI of the Gobblin job to unschedule.
* */
public void unscheduleJob(URI jobSpecURI);
/** The outstanding job schedules. This is represents a snapshot in time and will not be updated
* as new schedules are added/removed.
* @return a map with the URIs of the scheduled jobs for keys and the schedules for values */
public Map<URI, JobSpecSchedule> getSchedules();
}
| 1,533 |
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/api/MultiEventMetadataGenerator.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.api;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.gobblin.metrics.event.EventName;
import org.apache.gobblin.runtime.JobContext;
import org.apache.gobblin.util.ClassAliasResolver;
/**
* A class to add metadata from multiple {@link EventMetadataGenerator}s.
* {@link EventMetadataGenerator}s are supposed to be provided by a comma separated string.
* If multiple {@link EventMetadataGenerator}s add the same metadata, the one that comes later will take precedence.
*/
public class MultiEventMetadataGenerator {
private final List<EventMetadataGenerator> eventMetadataGenerators = Lists.newArrayList();
public MultiEventMetadataGenerator(List<String> multiEventMetadataGeneratorList) {
for (String eventMetadatadataGeneratorClassName : multiEventMetadataGeneratorList) {
try {
ClassAliasResolver<EventMetadataGenerator> aliasResolver = new ClassAliasResolver<>(EventMetadataGenerator.class);
this.eventMetadataGenerators.add(aliasResolver.resolveClass(eventMetadatadataGeneratorClassName).newInstance());
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Could not construct EventMetadataGenerator " + eventMetadatadataGeneratorClassName, e);
}
}
}
public Map<String, String> getMetadata(JobContext jobContext, EventName eventName) {
Map<String, String> metadata = Maps.newHashMap();
for (EventMetadataGenerator eventMetadataGenerator : eventMetadataGenerators) {
metadata.putAll(eventMetadataGenerator.getMetadata(jobContext, eventName));
}
return metadata;
}
}
| 1,534 |
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/api/JobExecutionState.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.api;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.JobState.RunningState;
import javax.annotation.Nonnull;
import lombok.Getter;
/**
* TODO
*
*/
@Alpha
public class JobExecutionState implements JobExecutionStatus {
public static final String UKNOWN_STAGE = "unkown";
private static final Map<RunningState, Set<RunningState>>
EXPECTED_PRE_TRANSITION_STATES = ImmutableMap.<RunningState, Set<RunningState>>builder()
.put(RunningState.PENDING, ImmutableSet.<RunningState>builder().build())
.put(RunningState.RUNNING, ImmutableSet.<RunningState>builder().add(RunningState.PENDING).build())
.put(RunningState.SUCCESSFUL, ImmutableSet.<RunningState>builder().add(RunningState.RUNNING).build())
.put(RunningState.COMMITTED, ImmutableSet.<RunningState>builder().add(RunningState.SUCCESSFUL).build())
.put(RunningState.FAILED,
ImmutableSet.<RunningState>builder()
.add(RunningState.PENDING).add(RunningState.RUNNING).add(RunningState.SUCCESSFUL).build())
.put(RunningState.CANCELLED,
ImmutableSet.<RunningState>builder()
.add(RunningState.PENDING).add(RunningState.RUNNING).add(RunningState.SUCCESSFUL).build())
.build();
public static final Predicate<JobExecutionState> EXECUTION_DONE_PREDICATE =
new Predicate<JobExecutionState>() {
@Override public boolean apply(@Nonnull JobExecutionState state) {
return null != state.getRunningState() && state.getRunningState().isDone();
}
@Override public String toString() {
return "runningState().isDone()";
}
};
@Getter private final JobExecution jobExecution;
private final Optional<JobExecutionStateListener> listener;
@Getter final JobSpec jobSpec;
// We use a lock instead of synchronized so that we can add different conditional variables if
// needed.
private final Lock changeLock = new ReentrantLock();
private final Condition runningStateChanged = changeLock.newCondition();
private JobState.RunningState runningState;
/** Arbitrary execution stage, e.g. setup, workUnitGeneration, taskExecution, publishing */
private String stage;
private Map<String, Object> executionMetadata;
public JobExecutionState(JobSpec jobSpec, JobExecution jobExecution,
Optional<JobExecutionStateListener> listener) {
this.jobExecution = jobExecution;
this.runningState = null;
this.stage = UKNOWN_STAGE;
this.jobSpec = jobSpec;
this.listener = listener;
// TODO default implementation
this.executionMetadata = new HashMap<>();
}
public Map<String, Object> getExecutionMetadata() {
this.changeLock.lock();
try {
return Collections.unmodifiableMap(this.executionMetadata);
}
finally {
this.changeLock.unlock();
}
}
@Override public String toString() {
this.changeLock.lock();
try {
return MoreObjects.toStringHelper(JobExecutionState.class.getSimpleName())
.add("jobExecution", this.jobExecution)
.add("runningState", this.runningState)
.add("stage", this.stage)
.toString();
}
finally {
this.changeLock.unlock();
}
}
@Override public JobState.RunningState getRunningState() {
this.changeLock.lock();
try {
return this.runningState;
}
finally {
this.changeLock.unlock();
}
}
@Override
public String getStage() {
this.changeLock.lock();
try {
return this.stage;
}
finally {
this.changeLock.unlock();
}
}
public void setRunningState(JobState.RunningState runningState) {
doRunningStateChange(runningState);
}
public void switchToPending() {
doRunningStateChange(RunningState.PENDING);
}
public void switchToRunning() {
doRunningStateChange(RunningState.RUNNING);
}
public void switchToSuccessful() {
doRunningStateChange(RunningState.SUCCESSFUL);
}
public void switchToFailed() {
doRunningStateChange(RunningState.FAILED);
}
public void switchToCommitted() {
doRunningStateChange(RunningState.COMMITTED);
}
public void switchToCancelled() {
doRunningStateChange(RunningState.CANCELLED);
}
// This must be called only when holding changeLock
private void doRunningStateChange(RunningState newState) {
RunningState oldState = null;
JobExecutionStateListener stateListener = null;
this.changeLock.lock();
try {
// verify transition
if (null == this.runningState) {
Preconditions.checkState(RunningState.PENDING == newState);
}
else {
Preconditions.checkState(EXPECTED_PRE_TRANSITION_STATES.get(newState).contains(this.runningState),
"unexpected state transition " + this.runningState + " --> " + newState);
}
oldState = this.runningState;
this.runningState = newState;
if (this.listener.isPresent()) {
stateListener = this.listener.get();
}
this.runningStateChanged.signalAll();
}
finally {
this.changeLock.unlock();
}
if (null != stateListener) {
stateListener.onStatusChange(this, oldState, newState);
}
}
public void setStage(String newStage) {
this.changeLock.lock();
try {
String oldStage = this.stage;
this.stage = newStage;
if (this.listener.isPresent()) {
this.listener.get().onStageTransition(this, oldStage, this.stage);
}
}
finally {
this.changeLock.unlock();
}
}
public void setMedatata(String key, Object value) {
this.changeLock.lock();
try {
Object oldValue = this.executionMetadata.get(key);
this.executionMetadata.put(key, value);
if (this.listener.isPresent()) {
this.listener.get().onMetadataChange(this, key, oldValue, value);
}
}
finally {
this.changeLock.unlock();
}
}
public void awaitForDone(long timeoutMs) throws InterruptedException, TimeoutException {
awaitForStatePredicate(EXECUTION_DONE_PREDICATE, timeoutMs);
}
public void awaitForState(final RunningState targetState, long timeoutMs)
throws InterruptedException, TimeoutException {
awaitForStatePredicate(new Predicate<JobExecutionState>() {
@Override public boolean apply(JobExecutionState state) {
return null != state.getRunningState() && state.getRunningState().equals(targetState);
}
@Override public String toString() {
return "runningState == " + targetState;
}
}, timeoutMs);
}
/**
* Waits till a predicate on {@link #getRunningState()} becomes true or timeout is reached.
*
* @param predicate the predicate to evaluate. Note that even though the predicate
* is applied on the entire object, it will be evaluated only when
* the running state changes.
* @param timeoutMs the number of milliseconds to wait for the predicate to become
* true; 0 means wait forever.
* @throws InterruptedException if the waiting was interrupted
* @throws TimeoutException if we reached the timeout before the predicate was satisfied.
*/
public void awaitForStatePredicate(Predicate<JobExecutionState> predicate, long timeoutMs)
throws InterruptedException, TimeoutException {
Preconditions.checkArgument(timeoutMs >= 0);
if (0 == timeoutMs) {
timeoutMs = Long.MAX_VALUE;
}
long startTimeMs = System.currentTimeMillis();
long millisRemaining = timeoutMs;
this.changeLock.lock();
try {
while (!predicate.apply(this) && millisRemaining > 0) {
if (!this.runningStateChanged.await(millisRemaining, TimeUnit.MILLISECONDS)) {
// Not necessary but shuts up FindBugs RV_RETURN_VALUE_IGNORED_BAD_PRACTICE
break;
}
millisRemaining = timeoutMs - (System.currentTimeMillis() - startTimeMs);
}
if (!predicate.apply(this)) {
throw new TimeoutException("Timeout waiting for state predicate: " + predicate);
}
}
finally {
this.changeLock.unlock();
}
}
}
| 1,535 |
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/api/JobExecutionLauncher.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.api;
import java.util.concurrent.Future;
import com.codahale.metrics.Gauge;
import lombok.Getter;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.instrumented.Instrumentable;
import org.apache.gobblin.metrics.ContextAwareGauge;
import org.apache.gobblin.metrics.ContextAwareMeter;
/**
* A factory for {@link JobExecutionDriver}s.
*/
@Alpha
public interface JobExecutionLauncher extends Instrumentable {
/**
* This method is to launch the job specified by {@param jobSpec}
* The simplest way is to run a {@link JobExecutionDriver} and upon completion return a
* {@link org.apache.gobblin.runtime.job_exec.JobLauncherExecutionDriver.JobExecutionMonitorAndDriver}.
*
* If {@link JobExecutionDriver} does not run within the same process/node of {@link JobExecutionLauncher}, a simple monitoring
* future object ({@link JobExecutionMonitor}) can be returned. This object can do two things:
*
* 1) Wait for computation of final {@link ExecutionResult} by invoking {@link Future#get()}.
* 2) Monitor current job running status by invoking {@link JobExecutionMonitor#getRunningState()}.
*
* @see JobExecutionMonitor
*/
JobExecutionMonitor launchJob(JobSpec jobSpec);
/**
* Common metrics for all launcher implementations.
*/
StandardMetrics getMetrics();
public static class StandardMetrics {
public static final String NUM_JOBS_LAUNCHED = "numJobsLaunched";
public static final String NUM_JOBS_COMPLETED = "numJobsCompleted";
public static final String NUM_JOBS_COMMITTED = "numJobsCommitted";
public static final String NUM_JOBS_FAILED = "numJobsFailed";
public static final String NUM_JOBS_CANCELLED = "numJobsCancelled";
public static final String NUM_JOBS_RUNNING = "numJobsRunning";
public static final String TIMER_FOR_COMPLETED_JOBS = "timeForCompletedJobs";
public static final String TIMER_FOR_FAILED_JOBS = "timeForFailedJobs";
public static final String TIMER_FOR_COMMITTED_JOBS = "timerForCommittedJobs";
public static final String EXECUTOR_ACTIVE_COUNT = "executorActiveCount";
public static final String EXECUTOR_MAX_POOL_SIZE = "executorMaximumPoolSize";
public static final String EXECUTOR_POOL_SIZE = "executorPoolSize";
public static final String EXECUTOR_CORE_POOL_SIZE = "executorCorePoolSize";
public static final String EXECUTOR_QUEUE_SIZE = "executorQueueSize";
@Getter private final ContextAwareMeter numJobsLaunched;
@Getter private final ContextAwareMeter numJobsCompleted;
@Getter private final ContextAwareMeter numJobsCommitted;
@Getter private final ContextAwareMeter numJobsFailed;
@Getter private final ContextAwareMeter numJobsCancelled;
@Getter private final ContextAwareGauge<Integer> numJobsRunning;
public StandardMetrics(final JobExecutionLauncher parent) {
this.numJobsLaunched = parent.getMetricContext().contextAwareMeter(NUM_JOBS_LAUNCHED);
this.numJobsCompleted = parent.getMetricContext().contextAwareMeter(NUM_JOBS_COMPLETED);
this.numJobsCommitted = parent.getMetricContext().contextAwareMeter(NUM_JOBS_COMMITTED);
this.numJobsFailed = parent.getMetricContext().contextAwareMeter(NUM_JOBS_FAILED);
this.numJobsCancelled = parent.getMetricContext().contextAwareMeter(NUM_JOBS_CANCELLED);
this.numJobsRunning = parent.getMetricContext().newContextAwareGauge(NUM_JOBS_RUNNING,
new Gauge<Integer>() {
@Override public Integer getValue() {
return (int)(StandardMetrics.this.getNumJobsLaunched().getCount() -
StandardMetrics.this.getNumJobsCompleted().getCount() -
StandardMetrics.this.getNumJobsCancelled().getCount());
}
});
}
}
}
| 1,536 |
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/api/InstrumentedSpecStore.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.api;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.ServiceMetricNames;
import org.apache.gobblin.util.ConfigUtils;
/**
* Instrumented version of {@link SpecStore} automatically capturing certain metrics.
* Subclasses should implement addSpecImpl instead of addSpec and so on.
*/
public abstract class InstrumentedSpecStore implements SpecStore {
/** Record timing for an operation, when an `Optional<Timer>.isPresent()`, otherwise simply perform the operation w/o timing */
static class OptionallyTimingInvoker {
/** `j.u.function.Supplier` variant for an operation that may @throw IOException: preserves method signature, including checked exceptions */
@FunctionalInterface
public interface SupplierMayThrowIO<T> {
public T get() throws IOException;
}
/** `j.u.function.Supplier` variant for an operation that may @throw IOException or SpecNotFoundException: preserves method signature exceptions */
@FunctionalInterface
public interface SupplierMayThrowBoth<T> {
public T get() throws IOException, SpecNotFoundException;
}
private final Optional<Timer> timer;
public OptionallyTimingInvoker(Optional<Timer> timer) {
this.timer = timer != null ? timer : Optional.absent();
}
public <T> T invokeMayThrowIO(SupplierMayThrowIO<T> f) throws IOException {
try {
return invokeMayThrowBoth(() -> f.get());
} catch (SpecNotFoundException e) {
throw new RuntimeException("IMPOSSIBLE - prohibited by static checking!", e);
}
}
public <T> T invokeMayThrowBoth(SupplierMayThrowBoth<T> f) throws IOException, SpecNotFoundException {
if (timer.isPresent()) {
final long startTimeNanos = System.nanoTime(); // ns resolution, being internal granularity of `metrics.Timer`
final T result = f.get();
timer.get().update(System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS);
return result;
} else { // skip timing, when no `Timer`
return f.get();
}
}
}
private OptionallyTimingInvoker getTimer;
private OptionallyTimingInvoker existsTimer;
private OptionallyTimingInvoker deleteTimer;
private OptionallyTimingInvoker addTimer;
private OptionallyTimingInvoker updateTimer;
private OptionallyTimingInvoker getAllTimer;
private OptionallyTimingInvoker getSizeTimer;
private OptionallyTimingInvoker getURIsTimer;
private OptionallyTimingInvoker getURIsWithTagTimer;
private MetricContext metricContext;
private final boolean instrumentationEnabled;
public InstrumentedSpecStore(Config config, SpecSerDe specSerDe) {
this.instrumentationEnabled = GobblinMetrics.isEnabled(new State(ConfigUtils.configToProperties(config)));
this.metricContext = Instrumented.getMetricContext(new State(), getClass());
this.getTimer = createTimingInvoker("-GET");
this.existsTimer = createTimingInvoker("-EXISTS");
this.deleteTimer = createTimingInvoker("-DELETE");
this.addTimer = createTimingInvoker("-ADD");
this.updateTimer = createTimingInvoker("-UPDATE");
this.getAllTimer = createTimingInvoker("-GETALL");
this.getSizeTimer = createTimingInvoker("-GETCOUNT");
this.getURIsTimer = createTimingInvoker("-GETURIS");
this.getURIsWithTagTimer = createTimingInvoker("-GETURISWITHTAG");
}
private OptionallyTimingInvoker createTimingInvoker(String suffix) {
return new OptionallyTimingInvoker(createTimer(suffix));
}
private Optional<Timer> createTimer(String suffix) {
return instrumentationEnabled
? Optional.of(this.metricContext.timer(MetricRegistry.name(ServiceMetricNames.GOBBLIN_SERVICE_PREFIX, getClass().getSimpleName(), suffix)))
: Optional.absent();
}
@Override
public boolean exists(URI specUri) throws IOException {
return this.existsTimer.invokeMayThrowIO(() -> existsImpl(specUri));
}
@Override
public void addSpec(Spec spec) throws IOException {
this.addTimer.invokeMayThrowIO(() -> { addSpecImpl(spec); /* sadly, unable to infer `SupplierMayThrowIO<Void>`, thus explicitly... */ return null; });
}
@Override
public boolean deleteSpec(URI specUri) throws IOException {
return this.deleteTimer.invokeMayThrowIO(() -> deleteSpecImpl(specUri));
}
@Override
public Spec getSpec(URI specUri) throws IOException, SpecNotFoundException {
return this.getTimer.invokeMayThrowBoth(() -> getSpecImpl(specUri));
}
@Override
public Collection<Spec> getSpecs(SpecSearchObject specSearchObject) throws IOException {
// NOTE: uses same `getTimer` as `getSpec`; TODO: explore separating, since measuring different operation
return this.getTimer.invokeMayThrowIO(() -> getSpecsImpl(specSearchObject));
}
@Override
public Spec updateSpec(Spec spec) throws IOException, SpecNotFoundException {
return this.updateTimer.invokeMayThrowBoth(() -> updateSpecImpl(spec));
}
@Override
public Spec updateSpec(Spec spec, long modifiedWatermark) throws IOException, SpecNotFoundException {
return this.updateTimer.invokeMayThrowBoth(() -> updateSpecImpl(spec, modifiedWatermark));
}
@Override
public Collection<Spec> getSpecs() throws IOException {
return this.getAllTimer.invokeMayThrowIO(() -> getSpecsImpl());
}
@Override
public Iterator<URI> getSpecURIs() throws IOException {
return this.getURIsTimer.invokeMayThrowIO(() -> getSpecURIsImpl());
}
@Override
public Iterator<URI> getSpecURIsWithTag(String tag) throws IOException {
return this.getURIsWithTagTimer.invokeMayThrowIO(() -> getSpecURIsWithTagImpl(tag));
}
@Override
public Collection<Spec> getSpecsPaginated(int startOffset, int batchSize) throws IOException, IllegalArgumentException {
return this.getTimer.invokeMayThrowIO(() -> getSpecsPaginatedImpl(startOffset, batchSize));
}
@Override
public int getSize() throws IOException {
return this.getSizeTimer.invokeMayThrowIO(() -> getSizeImpl());
}
public Spec updateSpecImpl(Spec spec, long modifiedWatermark) throws IOException, SpecNotFoundException{
return updateSpecImpl(spec);
}
public abstract void addSpecImpl(Spec spec) throws IOException;
public abstract Spec updateSpecImpl(Spec spec) throws IOException, SpecNotFoundException;
public abstract boolean existsImpl(URI specUri) throws IOException;
public abstract Spec getSpecImpl(URI specUri) throws IOException, SpecNotFoundException;
public abstract boolean deleteSpecImpl(URI specUri) throws IOException;
public abstract Collection<Spec> getSpecsImpl() throws IOException;
public abstract Iterator<URI> getSpecURIsImpl() throws IOException;
public abstract Iterator<URI> getSpecURIsWithTagImpl(String tag) throws IOException;
public abstract int getSizeImpl() throws IOException;
public abstract Collection<Spec> getSpecsPaginatedImpl(int startOffset, int batchSize) throws IOException, IllegalArgumentException;
/** child classes can implement this if they want to get specs using {@link SpecSearchObject} */
public Collection<Spec> getSpecsImpl(SpecSearchObject specUri) throws IOException {
throw new UnsupportedOperationException();
}
}
| 1,537 |
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/api/JobSpec.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.api;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.template.ResourceBasedJobTemplate;
import org.apache.gobblin.runtime.template.StaticJobTemplate;
import org.apache.gobblin.util.ConfigUtils;
import com.google.common.annotations.VisibleForTesting;
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 lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
/**
* Defines a Gobblin Job that can be run once, or multiple times. A {@link JobSpec} is
* {@link Configurable} so it has an associated {@link Config}, along with other mandatory
* properties such as a uri, description, and version. A {@link JobSpec} is
* uniquely identified by its uri (containing group and name).
*
*/
@Alpha
@Data
@AllArgsConstructor
public class JobSpec implements Configurable, Spec {
private static final long serialVersionUID = 6074793380396465963L;
/** An URI identifying the job. */
URI uri;
/** The implementation-defined version of this spec. */
String version;
/** Human-readable description of the job spec */
String description;
/** Job config as a typesafe config object*/
Config config;
/** Job config as a properties collection for backwards compatibility */
// Note that this property is not strictly necessary as it can be generated from the typesafe
// config. We use it as a cache until typesafe config is more widely adopted in Gobblin.
Properties configAsProperties;
/** URI of {@link org.apache.gobblin.runtime.api.JobTemplate} to use. */
Optional<URI> templateURI;
/** Specific instance of template. */
transient Optional<JobTemplate> jobTemplate;
/** Metadata can contain properties which are not a part of config, e.g. Verb */
Map<String, String> metadata;
/** A Verb identifies if the Spec is for Insert/Update/Delete */
private static final String IN_MEMORY_TEMPLATE_URI = "inmemory";
public static Builder builder(URI jobSpecUri) {
return new Builder(jobSpecUri);
}
public static Builder builder(String jobSpecUri) {
return new Builder(jobSpecUri);
}
public static Builder builder() {
return new Builder();
}
/** Creates a builder for the JobSpec based on values in a job properties config. */
public static Builder builder(URI catalogURI, Properties jobProps) {
String name = JobState.getJobNameFromProps(jobProps);
String group = JobState.getJobGroupFromProps(jobProps);
if (null == group) {
group = "default";
}
try {
URI jobURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(),
"/" + group + "/" + name, null);
Builder builder = new Builder(jobURI).withConfigAsProperties(jobProps);
String descr = JobState.getJobDescriptionFromProps(jobProps);
if (null != descr) {
builder.withDescription(descr);
}
return builder;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create a JobSpec URI: " + e, e);
}
}
public String toShortString() {
return getUri().toString() + "/" + getVersion();
}
public String toLongString() {
return getUri().toString() + "/" + getVersion() + "[" + getDescription() + "]";
}
@Override
public String toString() {
return toShortString();
}
/**
* Builder for {@link JobSpec}s.
* <p> Defaults/conventions:
* <ul>
* <li> Default jobCatalogURI is {@link #DEFAULT_JOB_CATALOG_SCHEME}:
* <li> Convention for JobSpec URI: <jobCatalogURI>/config.get({@link ConfigurationKeys#JOB_GROUP_KEY})/config.get({@link ConfigurationKeys#JOB_NAME_KEY})
* <li> Convention for Description: config.get({@link ConfigurationKeys#JOB_DESCRIPTION_KEY})
* <li> Default version: 1
* </ul>
*/
public static class Builder {
public static final String DEFAULT_JOB_CATALOG_SCHEME = "gobblin-job";
@VisibleForTesting
private Optional<Config> config = Optional.absent();
private Optional<Properties> configAsProperties = Optional.absent();
private Optional<URI> uri;
private String version = "1";
private Optional<String> description = Optional.absent();
private Optional<URI> jobCatalogURI = Optional.absent();
private Optional<URI> templateURI = Optional.absent();
private Optional<JobTemplate> jobTemplate = Optional.absent();
private Optional<Map> metadata = Optional.absent();
public Builder(URI jobSpecUri) {
Preconditions.checkNotNull(jobSpecUri);
this.uri = Optional.of(jobSpecUri);
}
public Builder(String jobSpecUri) {
Preconditions.checkNotNull(jobSpecUri);
Preconditions.checkNotNull(jobSpecUri);
try {
this.uri = Optional.of(new URI(jobSpecUri));
}
catch (URISyntaxException e) {
throw new RuntimeException("Invalid JobSpec config: " + e, e);
}
}
public Builder() {
this.uri = Optional.absent();
}
public JobSpec build() {
Preconditions.checkNotNull(this.uri);
Preconditions.checkNotNull(this.version);
return new JobSpec(getURI(), getVersion(), getDescription(), getConfig(),
getConfigAsProperties(), getTemplateURI(), getTemplate(), getMetadata());
}
/** The scheme and authority of the job catalog URI are used to generate JobSpec URIs from
* job configs. */
public Builder withJobCatalogURI(URI jobCatalogURI) {
this.jobCatalogURI = Optional.of(jobCatalogURI);
return this;
}
public Builder withJobCatalogURI(String jobCatalogURI) {
try {
this.jobCatalogURI = Optional.of(new URI(jobCatalogURI));
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to set job catalog URI: " + e, e);
}
return this;
}
public URI getDefaultJobCatalogURI() {
try {
return new URI(DEFAULT_JOB_CATALOG_SCHEME, null, "/", null, null);
} catch (URISyntaxException e) {
// should not happen
throw new Error("Unexpected exception: " + e, e);
}
}
public URI getJobCatalogURI() {
if (! this.jobCatalogURI.isPresent()) {
this.jobCatalogURI = Optional.of(getDefaultJobCatalogURI());
}
return this.jobCatalogURI.get();
}
public URI getDefaultURI() {
URI jobCatalogURI = getJobCatalogURI();
Config jobCfg = getConfig();
String name = jobCfg.hasPath(ConfigurationKeys.JOB_NAME_KEY) ?
jobCfg.getString(ConfigurationKeys.JOB_NAME_KEY) :
"default";
String group = jobCfg.hasPath(ConfigurationKeys.JOB_GROUP_KEY) ?
jobCfg.getString(ConfigurationKeys.JOB_GROUP_KEY) :
"default";
try {
return new URI(jobCatalogURI.getScheme(), jobCatalogURI.getAuthority(),
"/" + group + "/" + name, null, null);
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create default JobSpec URI:" + e, e);
}
}
public URI getURI() {
if (! this.uri.isPresent()) {
this.uri = Optional.of(getDefaultURI());
}
return this.uri.get();
}
public Builder withVersion(String version) {
Preconditions.checkNotNull(version);
this.version = version;
return this;
}
public String getVersion() {
return this.version;
}
public Builder withDescription(String jobDescription) {
Preconditions.checkNotNull(jobDescription);
this.description = Optional.of(jobDescription);
return this;
}
public String getDefaultDescription() {
Config jobConf = getConfig();
return jobConf.hasPath(ConfigurationKeys.JOB_DESCRIPTION_KEY) ?
jobConf.getString(ConfigurationKeys.JOB_DESCRIPTION_KEY) :
"Gobblin job " + getURI();
}
public String getDescription() {
if (! this.description.isPresent()) {
this.description = Optional.of(getDefaultDescription());
}
return this.description.get();
}
public Config getDefaultConfig() {
return ConfigFactory.empty();
}
public Config getConfig() {
if (!this.config.isPresent()) {
this.config = this.configAsProperties.isPresent() ?
Optional.of(ConfigUtils.propertiesToTypedConfig(this.configAsProperties.get(),
Optional.<String>absent())) :
Optional.of(getDefaultConfig());
}
return this.config.get();
}
public Builder withConfig(Config jobConfig) {
Preconditions.checkNotNull(jobConfig);
this.config = Optional.of(jobConfig);
return this;
}
public Properties getConfigAsProperties() {
if (!this.configAsProperties.isPresent()) {
this.configAsProperties = Optional.of(ConfigUtils.configToProperties(this.config.get()));
}
return this.configAsProperties.get();
}
public Builder withConfigAsProperties(Properties jobConfig) {
Preconditions.checkNotNull(jobConfig);
this.configAsProperties = Optional.of(jobConfig);
return this;
}
public Optional<URI> getTemplateURI() {
return this.templateURI;
}
public Builder withTemplate(URI templateURI) {
Preconditions.checkNotNull(templateURI);
this.templateURI = Optional.of(templateURI);
return this;
}
/**
* As the public interface of {@link JobSpec} doesn't really support multiple templates,
* for incoming list of template uris we will consolidate them as well as resolving. The resolved Config
* will not be materialized but reside only in memory through the lifecycle.
*
* Restriction: This method assumes no customized jobTemplateCatalog and uses classpath resources as the input.
* Also, the order of list matters: The former one will be overwritten by the latter.
*/
public Builder withResourceTemplates(List<URI> templateURIs) {
try {
List<JobTemplate> templates = new ArrayList<>(templateURIs.size());
for(URI uri : templateURIs) {
templates.add(ResourceBasedJobTemplate.forResourcePath(uri.getPath()));
}
this.jobTemplate = Optional.of(new StaticJobTemplate(new URI(IN_MEMORY_TEMPLATE_URI), "", "",
ConfigFactory.empty(), templates));
} catch (URISyntaxException | SpecNotFoundException | JobTemplate.TemplateException | IOException e) {
throw new RuntimeException("Fatal exception: Templates couldn't be resolved properly, ", e);
}
return this;
}
public Optional<JobTemplate> getTemplate() {
return this.jobTemplate;
}
public Builder withTemplate(JobTemplate template) {
Preconditions.checkNotNull(template);
this.jobTemplate = Optional.of(template);
return this;
}
public Map getDefaultMetadata() {
log.debug("Job Spec Verb is not provided, using type 'UNKNOWN'.");
return ImmutableMap.of(SpecExecutor.VERB_KEY, SpecExecutor.Verb.UNKNOWN.name());
}
public Map getMetadata() {
if (!this.metadata.isPresent()) {
this.metadata = Optional.of(getDefaultMetadata());
}
return this.metadata.get();
}
public Builder withMetadata(Map<String, String> metadata) {
Preconditions.checkNotNull(metadata);
this.metadata = Optional.of(metadata);
return this;
}
}
/**
* get the private uri as the primary key for this object.
* @return
*/
public URI getUri() {
return this.uri;
}
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(uri);
stream.writeObject(version);
stream.writeObject(description);
stream.writeObject(templateURI.isPresent() ? templateURI.get() : null);
stream.writeObject(configAsProperties);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
uri = (URI) stream.readObject();
version = (String) stream.readObject();
description = (String) stream.readObject();
templateURI = Optional.fromNullable((URI) stream.readObject());
configAsProperties = (Properties) stream.readObject();
config = ConfigUtils.propertiesToConfig(configAsProperties);
}
}
| 1,538 |
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/api/SpecCatalog.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.api;
import java.net.URI;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.typesafe.config.Config;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.instrumented.GobblinMetricsKeys;
import org.apache.gobblin.instrumented.Instrumentable;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.instrumented.StandardMetricsBridge;
import org.apache.gobblin.metrics.ContextAwareGauge;
import org.apache.gobblin.metrics.ContextAwareTimer;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.runtime.spec_catalog.AddSpecResponse;
import org.apache.gobblin.util.ConfigUtils;
public interface SpecCatalog extends SpecCatalogListenersContainer, Instrumentable, StandardMetricsBridge {
/**
* Returns an immutable {@link Collection} of {@link Spec}s that are known to the catalog.
* This method should only be used for short list of {@link Spec}s, otherwise it would risk overusing memory.
* */
Collection<Spec> getSpecs();
int getSize();
/** Metrics for the spec catalog; null if
* ({@link #isInstrumentationEnabled()}) is false. */
SpecCatalog.StandardMetrics getMetrics();
default Collection<StandardMetricsBridge.StandardMetrics> getStandardMetricsCollection() {
SpecCatalog.StandardMetrics standardMetrics = getMetrics();
return standardMetrics == null? ImmutableList.of() : ImmutableList.of(standardMetrics);
}
/**
* Get a {@link Spec} by uri.
* @throws SpecNotFoundException if no such Spec exists
**/
Spec getSpecs(URI uri) throws SpecNotFoundException;
/**
* Get a {@link Spec} by {@link SpecSearchObject}.
**/
default Collection<Spec> getSpecs(SpecSearchObject specSearchObject) {
throw new UnsupportedOperationException();
}
@Slf4j
class StandardMetrics extends StandardMetricsBridge.StandardMetrics implements SpecCatalogListener {
public static final String NUM_ACTIVE_SPECS_NAME = "numActiveSpecs";
public static final String TOTAL_ADD_CALLS = "totalAddCalls";
public static final String TOTAL_DELETE_CALLS = "totalDeleteCalls";
public static final String TOTAL_UPDATE_CALLS = "totalUpdateCalls";
public static final String TRACKING_EVENT_NAME = "SpecCatalogEvent";
public static final String SPEC_ADDED_OPERATION_TYPE = "SpecAdded";
public static final String SPEC_DELETED_OPERATION_TYPE = "SpecDeleted";
public static final String SPEC_UPDATED_OPERATION_TYPE = "SpecUpdated";
public static final String TIME_FOR_SPEC_CATALOG_GET = "timeForSpecCatalogGet";
private final MetricContext metricsContext;
protected final int timeWindowSizeInMinutes;
@Getter private final AtomicLong totalAddedSpecs;
@Getter private final AtomicLong totalDeletedSpecs;
@Getter private final AtomicLong totalUpdatedSpecs;
@Getter private final ContextAwareGauge<Long> totalAddCalls;
@Getter private final ContextAwareGauge<Long> totalDeleteCalls;
@Getter private final ContextAwareGauge<Long> totalUpdateCalls;
@Getter private final ContextAwareGauge<Integer> numActiveSpecs;
@Getter private final ContextAwareTimer timeForSpecCatalogGet;
public StandardMetrics(final SpecCatalog specCatalog, Optional<Config> sysConfig) {
this.timeWindowSizeInMinutes = sysConfig.isPresent()?
ConfigUtils.getInt(sysConfig.get(), ConfigurationKeys.METRIC_TIMER_WINDOW_SIZE_IN_MINUTES, ConfigurationKeys.DEFAULT_METRIC_TIMER_WINDOW_SIZE_IN_MINUTES) :
ConfigurationKeys.DEFAULT_METRIC_TIMER_WINDOW_SIZE_IN_MINUTES;
this.metricsContext = specCatalog.getMetricContext();
this.timeForSpecCatalogGet = metricsContext.contextAwareTimer(TIME_FOR_SPEC_CATALOG_GET, timeWindowSizeInMinutes, TimeUnit.MINUTES);
this.totalAddedSpecs = new AtomicLong(0);
this.totalDeletedSpecs = new AtomicLong(0);
this.totalUpdatedSpecs = new AtomicLong(0);
this.numActiveSpecs = metricsContext.newContextAwareGauge(NUM_ACTIVE_SPECS_NAME, ()->{
long startTime = System.currentTimeMillis();
int size = specCatalog.getSize();
updateGetSpecTime(startTime);
return size;
});
this.totalAddCalls = metricsContext.newContextAwareGauge(TOTAL_ADD_CALLS, ()->this.totalAddedSpecs.get());
this.totalUpdateCalls = metricsContext.newContextAwareGauge(TOTAL_UPDATE_CALLS, ()->this.totalUpdatedSpecs.get());
this.totalDeleteCalls = metricsContext.newContextAwareGauge(TOTAL_DELETE_CALLS, ()->this.totalDeletedSpecs.get());
this.contextAwareMetrics.add(numActiveSpecs);
this.contextAwareMetrics.add(totalAddCalls);
this.contextAwareMetrics.add(totalUpdateCalls);
this.contextAwareMetrics.add(totalDeleteCalls);
this.contextAwareMetrics.add(timeForSpecCatalogGet);
}
public void updateGetSpecTime(long startTime) {
log.debug("updateGetSpecTime...");
Instrumented.updateTimer(Optional.of(this.timeForSpecCatalogGet), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
@Override public AddSpecResponse onAddSpec(Spec addedSpec) {
this.totalAddedSpecs.incrementAndGet();
submitTrackingEvent(addedSpec, SPEC_ADDED_OPERATION_TYPE);
return new AddSpecResponse(null);
}
private void submitTrackingEvent(Spec spec, String operType) {
submitTrackingEvent(spec.getUri(), spec.getVersion(), operType);
}
private void submitTrackingEvent(URI specSpecURI, String specSpecVersion, String operType) {
GobblinTrackingEvent e = GobblinTrackingEvent.newBuilder()
.setName(TRACKING_EVENT_NAME)
.setNamespace(SpecCatalog.class.getName())
.setMetadata(ImmutableMap.<String, String>builder()
.put(GobblinMetricsKeys.OPERATION_TYPE_META, operType)
.put(GobblinMetricsKeys.SPEC_URI_META, specSpecURI.toString())
.put(GobblinMetricsKeys.SPEC_VERSION_META, specSpecVersion)
.build())
.build();
this.metricsContext.submitEvent(e);
}
@Override
public void onDeleteSpec(URI deletedSpecURI, String deletedSpecVersion, Properties headers) {
this.totalDeletedSpecs.incrementAndGet();
submitTrackingEvent(deletedSpecURI, deletedSpecVersion, SPEC_DELETED_OPERATION_TYPE);
}
@Override
public void onUpdateSpec(Spec updatedSpec) {
this.totalUpdatedSpecs.incrementAndGet();
submitTrackingEvent(updatedSpec, SPEC_UPDATED_OPERATION_TYPE);
}
}
}
| 1,539 |
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/api/JobCatalogListener.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.api;
import com.google.common.base.MoreObjects;
import java.net.URI;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.util.callbacks.Callback;
/**
* A listener for changes to the {@link JobSpec}s of a {@link JobCatalog}.
*/
@Alpha
public interface JobCatalogListener {
/** Invoked when a new JobSpec is added to the catalog and for all pre-existing jobs on registration
* of the listener.*/
void onAddJob(JobSpec addedJob);
/**
* Invoked when a JobSpec gets removed from the catalog.
*/
public void onDeleteJob(URI deletedJobURI, String deletedJobVersion);
default void onCancelJob(URI cancelledJobURI) {
}
/**
* Invoked when the contents of a JobSpec gets updated in the catalog.
*/
public void onUpdateJob(JobSpec updatedJob);
/** A standard implementation of onAddJob as a functional object */
public static class AddJobCallback extends Callback<JobCatalogListener, Void> {
private final JobSpec _addedJob;
public AddJobCallback(JobSpec addedJob) {
super(MoreObjects.toStringHelper("onAddJob").add("addedJob", addedJob).toString());
_addedJob = addedJob;
}
@Override public Void apply(JobCatalogListener listener) {
listener.onAddJob(_addedJob);
return null;
}
}
/** A standard implementation of onDeleteJob as a functional object */
public static class DeleteJobCallback extends Callback<JobCatalogListener, Void> {
private final URI _deletedJobURI;
private final String _deletedJobVersion;
public DeleteJobCallback(URI deletedJobURI, String deletedJobVersion) {
super(MoreObjects.toStringHelper("onDeleteJob")
.add("deletedJobURI", deletedJobURI)
.add("deletedJobVersion", deletedJobVersion)
.toString());
_deletedJobURI = deletedJobURI;
_deletedJobVersion = deletedJobVersion;
}
@Override public Void apply(JobCatalogListener listener) {
listener.onDeleteJob(_deletedJobURI, _deletedJobVersion);
return null;
}
}
public static class CancelJobCallback extends Callback<JobCatalogListener, Void> {
private final URI _cancelledJobURI;
public CancelJobCallback(URI cancelledJobURI) {
super(MoreObjects.toStringHelper("onCancelJob").add("cancelJob", cancelledJobURI).toString());
_cancelledJobURI = cancelledJobURI;
}
@Override
public Void apply(JobCatalogListener listener) {
listener.onCancelJob(_cancelledJobURI);
return null;
}
}
public static class UpdateJobCallback extends Callback<JobCatalogListener, Void> {
private final JobSpec _updatedJob;
public UpdateJobCallback(JobSpec updatedJob) {
super(MoreObjects.toStringHelper("onUpdateJob")
.add("updatedJob", updatedJob).toString());
_updatedJob = updatedJob;
}
@Override
public Void apply(JobCatalogListener listener) {
listener.onUpdateJob(_updatedJob);
return null;
}
}
}
| 1,540 |
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/api/MultiActiveLeaseArbiter.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.api;
import java.io.IOException;
import lombok.Data;
/**
* This interface defines a generic approach to a non-blocking, multiple active thread or host system, in which one or
* more active participants compete to take responsibility for a particular flow's event. The type of flow event in
* question does not impact the algorithm other than to uniquely identify the flow event. Each participant uses the
* interface to initiate an attempt at ownership over the flow event and receives a response indicating the status of
* the attempt.
*
* At a high level the lease arbiter works as follows:
* 1. Multiple participants independently learn of a flow action event to act upon
* 2. Each participant attempts to acquire rights or `a lease` to be the sole participant acting on the event by
* calling the tryAcquireLease method below and receives the resulting status. The status indicates whether this
* participant has
* a) LeaseObtainedStatus -> this participant will attempt to carry out the required action before the lease expires
* b) LeasedToAnotherStatus -> another will attempt to carry out the required action before the lease expires
* c) NoLongerLeasingStatus -> flow event no longer needs to be acted upon (terminal state)
* 3. If another participant has acquired the lease before this one could, then the present participant must check back
* in at the time of lease expiry to see if it needs to attempt the lease again [status (b) above]. We refer to this
* check-in as a 'reminder event'.
* 4. Once the participant which acquired the lease completes its work on the flow event, it calls recordLeaseSuccess
* to indicate to all other participants that the flow event no longer needs to be acted upon [status (c) above]
*/
public interface MultiActiveLeaseArbiter {
/**
* This method attempts to insert an entry into store for a particular flow action event if one does not already
* exist in the store for the flow action or has expired. Regardless of the outcome it also reads the lease
* acquisition timestamp of the entry for that flow action event (it could have pre-existed in the table or been newly
* added by the previous write). Based on the transaction results, it will return {@link LeaseAttemptStatus} to
* determine the next action.
* @param flowAction uniquely identifies the flow and the present action upon it
* @param eventTimeMillis is the time this flow action was triggered
* @param isReminderEvent true if the flow action event we're checking on is a reminder event
* @return LeaseAttemptStatus
* @throws IOException
*/
LeaseAttemptStatus tryAcquireLease(DagActionStore.DagAction flowAction, long eventTimeMillis, boolean isReminderEvent)
throws IOException;
/**
* This method is used to indicate the owner of the lease has successfully completed required actions while holding
* the lease of the flow action event. It marks the lease as "no longer leasing", if the eventTimeMillis and
* leaseAcquisitionTimeMillis values have not changed since this owner acquired the lease (indicating the lease did
* not expire).
* @return true if successfully updated, indicating no further actions need to be taken regarding this event.
* false if failed to update the lease properly, the caller should continue seeking to acquire the lease as
* if any actions it did successfully accomplish, do not count
*/
boolean recordLeaseSuccess(LeaseObtainedStatus status) throws IOException;
/*
Class used to encapsulate status of lease acquisition attempt and derivations should contain information specific to
the status that results.
*/
abstract class LeaseAttemptStatus {}
class NoLongerLeasingStatus extends LeaseAttemptStatus {}
/*
The participant calling this method acquired the lease for the event in question. `Flow action`'s flow execution id
is the timestamp associated with the lease and the time the caller obtained the lease is stored within the
`leaseAcquisitionTimestamp` field.
*/
@Data
class LeaseObtainedStatus extends LeaseAttemptStatus {
private final DagActionStore.DagAction flowAction;
private final long leaseAcquisitionTimestamp;
/**
* @return event time in millis since epoch for the event of this lease acquisition
*/
public long getEventTimeMillis() {
return Long.parseLong(flowAction.getFlowExecutionId());
}
}
/*
This flow action event already has a valid lease owned by another participant.
`Flow action`'s flow execution id is the timestamp the lease is associated with, however the flow action event it
corresponds to may be a different and distinct occurrence of the same event.
`minimumLingerDurationMillis` is the minimum amount of time to wait before this participant should return to check if
the lease has completed or expired
*/
@Data
class LeasedToAnotherStatus extends LeaseAttemptStatus {
private final DagActionStore.DagAction flowAction;
private final long minimumLingerDurationMillis;
/**
* Returns event time in millis since epoch for the event whose lease was obtained by another participant.
* @return
*/
public long getEventTimeMillis() {
return Long.parseLong(flowAction.getFlowExecutionId());
}
}
}
| 1,541 |
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/api/Configurable.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.api;
import java.util.Properties;
import com.typesafe.config.Config;
import org.apache.gobblin.annotation.Alpha;
/** A generic interface for any class that can be configured using a {@link Config}. */
@Alpha
public interface Configurable {
/** The configuration */
public Config getConfig();
/** The configuration as properties collection for backwards compatibility. */
public Properties getConfigAsProperties();
}
| 1,542 |
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/api/MutableSpecCatalog.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.api;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.ContextAwareTimer;
import org.apache.gobblin.runtime.spec_catalog.AddSpecResponse;
/**
* A {@link SpecCatalog} that can have its {@link Collection} of {@link Spec}s modified
* programmatically. Note that specs in a spec catalog can change from the outside. This is covered
* by the base SpecCatalog interface.
*/
public interface MutableSpecCatalog extends SpecCatalog {
/**
* Registers a new {@link Spec}. If a {@link Spec} with the same {@link Spec#getUri()} exists,
* it will be replaced.
* @param spec
* @return a map containing an entry for each {@link SpecCatalogListener} of the {@link SpecCatalog}, for which an action is triggered
* on adding a {@link Spec} to the {@link SpecCatalog}. The key for each entry is the name of the {@link SpecCatalogListener}
* and the value is the result of the the action taken by the listener returned as an instance of {@link AddSpecResponse}.
* */
Map<String, AddSpecResponse> put(Spec spec) throws Throwable;
/**
* Removes an existing {@link Spec} with the given URI.
* Throws SpecNotFoundException if such {@link Spec} does not exist.
*/
void remove(URI uri, Properties headers) throws SpecNotFoundException;
@Slf4j
class MutableStandardMetrics extends StandardMetrics {
public static final String TIME_FOR_SPEC_CATALOG_REMOVE = "timeForSpecCatalogRemove";
public static final String TIME_FOR_SPEC_CATALOG_PUT = "timeForSpecCatalogPut";
@Getter private final ContextAwareTimer timeForSpecCatalogPut;
@Getter private final ContextAwareTimer timeForSpecCatalogRemove;
public MutableStandardMetrics(SpecCatalog catalog, Optional<Config> sysConfig) {
super(catalog, sysConfig);
timeForSpecCatalogPut = catalog.getMetricContext().contextAwareTimer(TIME_FOR_SPEC_CATALOG_PUT, this.timeWindowSizeInMinutes, TimeUnit.MINUTES);
timeForSpecCatalogRemove = catalog.getMetricContext().contextAwareTimer(TIME_FOR_SPEC_CATALOG_REMOVE, this.timeWindowSizeInMinutes, TimeUnit.MINUTES);
this.contextAwareMetrics.add(timeForSpecCatalogPut);
this.contextAwareMetrics.add(timeForSpecCatalogRemove);
}
public void updatePutSpecTime(long startTime) {
log.info("updatePutSpecTime...");
Instrumented.updateTimer(Optional.of(this.timeForSpecCatalogPut), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
public void updateRemoveSpecTime(long startTime) {
log.info("updateRemoveSpecTime...");
Instrumented.updateTimer(Optional.of(this.timeForSpecCatalogRemove), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
}
}
| 1,543 |
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/api/EventMetadataGenerator.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.api;
import java.util.Map;
import org.apache.gobblin.metrics.event.EventName;
import org.apache.gobblin.runtime.JobContext;
/**
* For generating additional event metadata to associate with an event.
*/
public interface EventMetadataGenerator {
/**
* Generate a map of additional metadata for the specified event name.
* @param eventName the event name used to determine which additional metadata should be emitted
* @return {@link Map} with the additional metadata
*/
Map<String, String> getMetadata(JobContext jobContext, EventName eventName);
}
| 1,544 |
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/api/JobExecutionStateListener.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.api;
import com.google.common.base.MoreObjects;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.JobState.RunningState;
import org.apache.gobblin.util.callbacks.Callback;
/**
* Notification for changes in the execution state
*
*/
public interface JobExecutionStateListener {
void onStatusChange(JobExecutionState state, JobState.RunningState previousStatus, JobState.RunningState newStatus);
void onStageTransition(JobExecutionState state, String previousStage, String newStage);
void onMetadataChange(JobExecutionState state, String key, Object oldValue, Object newValue);
/** A standard implementation of {@link JobExecutionStateListener#onStatusChange(JobExecutionState, RunningState, RunningState)}
* as a functional object. */
static class StatusChangeCallback extends Callback<JobExecutionStateListener, Void> {
private final JobExecutionState state;
private final RunningState previousStatus;
private final RunningState newStatus;
public StatusChangeCallback(final JobExecutionState state,
final RunningState previousStatus,
final RunningState newStatus) {
super(MoreObjects.toStringHelper("onStatusChange")
.add("state", state)
.add("previousStatus", previousStatus)
.add("newStatus", newStatus)
.toString());
this.state = state;
this.previousStatus = previousStatus;
this.newStatus = newStatus;
}
@Override public Void apply(JobExecutionStateListener input) {
input.onStatusChange(this.state, this.previousStatus, this.newStatus);
return null;
}
}
/** A standard implementation of {@link JobExecutionStateListener#onStageTransition(JobExecutionState, String, String)}
* as a functional object. */
static class StageTransitionCallback extends
Callback<JobExecutionStateListener, Void> {
private final JobExecutionState state;
private final String previousStage;
private final String newStage;
public StageTransitionCallback(final JobExecutionState state, final String previousStage,
final String newStage) {
super(MoreObjects.toStringHelper("onStageTransition")
.add("state", state)
.add("previousStage", previousStage)
.add("newStage", newStage)
.toString());
this.state = state;
this.previousStage = previousStage;
this.newStage = newStage;
}
@Override
public Void apply(JobExecutionStateListener input) {
input.onStageTransition(this.state, this.previousStage, this.newStage);
return null;
}
}
/** A standard implementation of {@link JobExecutionStateListener#onMetadataChange(JobExecutionState, String, Object, Object)}
* as a functional object. */
static class MetadataChangeCallback extends Callback<JobExecutionStateListener, Void> {
private final JobExecutionState state;
private final String key;
private final Object oldValue;
private final Object newValue;
public MetadataChangeCallback(final JobExecutionState state, final String key,
final Object oldValue, final Object newValue) {
super(MoreObjects.toStringHelper("onMetadataChange")
.add("state", state)
.add("key", key)
.add("oldValue", oldValue)
.add("newValue", newValue)
.toString());
this.state = state;
this.key = key;
this.oldValue = oldValue;
this.newValue = newValue;
}
@Override
public Void apply(JobExecutionStateListener input) {
input.onMetadataChange(state, key, oldValue, newValue);
return null;
}
}
}
| 1,545 |
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/api/MutableJobCatalog.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.api;
import java.net.URI;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.metrics.ContextAwareTimer;
/**
* A {@link JobCatalog} that can have its {@link Collection} of {@link JobSpec}s modified
* programmatically. Note that jobs in a job catalog can change from the outside. This is covered
* by the base JobCatalog interface.
*/
@Alpha
public interface MutableJobCatalog extends JobCatalog {
/**
* Registers a new JobSpec. If a JobSpec with the same {@link JobSpec#getUri()} exists,
* it will be replaced.
* */
public void put(JobSpec jobSpec);
default void remove(URI uri, boolean alwaysTriggerListeners) {
throw new UnsupportedOperationException("Method not implemented by " + this.getClass());
}
/**
* Removes an existing JobSpec with the given URI. A no-op if such JobSpec does not exist.
*/
void remove(URI uri);
@Slf4j
public static class MutableStandardMetrics extends JobCatalog.StandardMetrics {
public static final String TIME_FOR_JOB_CATALOG_REMOVE = "timeForJobCatalogRemove";
public static final String TIME_FOR_JOB_CATALOG_PUT = "timeForJobCatalogPut";
@Getter private final ContextAwareTimer timeForJobCatalogPut;
@Getter private final ContextAwareTimer timeForJobCatalogRemove;
public MutableStandardMetrics(JobCatalog catalog, Optional<Config> sysConfig) {
super(catalog, sysConfig);
timeForJobCatalogPut = catalog.getMetricContext().contextAwareTimer(TIME_FOR_JOB_CATALOG_PUT, timeWindowSizeInMinutes, TimeUnit.MINUTES);
timeForJobCatalogRemove = catalog.getMetricContext().contextAwareTimer(TIME_FOR_JOB_CATALOG_REMOVE, this.timeWindowSizeInMinutes, TimeUnit.MINUTES);
this.contextAwareMetrics.add(timeForJobCatalogPut);
this.contextAwareMetrics.add(timeForJobCatalogRemove);
}
public void updatePutJobTime(long startTime) {
log.info("updatePutJobTime...");
Instrumented.updateTimer(Optional.of(this.timeForJobCatalogPut), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
public void updateRemoveJobTime(long startTime) {
log.info("updateRemoveJobTime...");
Instrumented.updateTimer(Optional.of(this.timeForJobCatalogRemove), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
}
}
| 1,546 |
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/api/SpecStore.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.api;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import com.google.common.base.Optional;
public interface SpecStore {
/***
* Check if a {@link Spec} exists in {@link SpecStore} by URI.
* @param specUri URI for the {@link Spec} to be checked.
* @throws IOException Exception in checking if {@link Spec} exists.
*/
boolean exists(URI specUri) throws IOException;
/***
* Persist {@link Spec} in the {@link SpecStore} for durability.
* @param spec {@link Spec} to be persisted.
* @throws IOException Exception in persisting.
*/
void addSpec(Spec spec) throws IOException;
/***
* Delete {@link Spec} from the {@link SpecStore}.
* If {@link Spec} is not found, it is a no-op.
* @param spec {@link Spec} to be deleted.
* @return true if {@link Spec} was deleted else false.
* @throws IOException Exception in deleting.
*/
boolean deleteSpec(Spec spec) throws IOException;
/***
* Delete all versions of the {@link Spec} from the {@link SpecStore}.
* If {@link Spec} is not found, it is a no-op.
* @param specUri URI for the {@link Spec} to be deleted.
* @return true if {@link Spec} was deleted else false.
* @throws IOException Exception in deleting.
*/
boolean deleteSpec(URI specUri) throws IOException;
/***
* Delete specifid version of {@link Spec} from the {@link SpecStore}.
* If {@link Spec} is not found, it is a no-op.
* @param specUri URI for the {@link Spec} to be deleted.
* @param version Version for the {@link Spec} to be deleted.
* @return true if {@link Spec} was deleted else false.
* @throws IOException Exception in deleting.
*/
boolean deleteSpec(URI specUri, String version) throws IOException;
/***
* Update {@link Spec} in the {@link SpecStore}.
* @param spec {@link Spec} to be updated.
* @throws IOException Exception in updating the {@link Spec}.
* @return Updated {@link Spec}.
* @throws SpecNotFoundException If {@link Spec} being updated is not present in store.
*/
Spec updateSpec(Spec spec) throws IOException, SpecNotFoundException;
/***
* Update {@link Spec} in the {@link SpecStore} when modification time of current entry is smaller than {@link modifiedWatermark}.
* @param spec {@link Spec} to be updated.
* @param modifiedWatermark largest modifiedWatermark that current spec should be
* @throws IOException Exception in updating the {@link Spec}.
* @return Updated {@link Spec}.
* @throws SpecNotFoundException If {@link Spec} being updated is not present in store.
*/
default Spec updateSpec(Spec spec, long modifiedWatermark) throws IOException, SpecNotFoundException {return updateSpec(spec);};
/***
* Retrieve the latest version of the {@link Spec} by URI from the {@link SpecStore}.
* @param specUri URI for the {@link Spec} to be retrieved.
* @throws IOException Exception in retrieving the {@link Spec}.
* @throws SpecNotFoundException If {@link Spec} being retrieved is not present in store.
*/
Spec getSpec(URI specUri) throws IOException, SpecNotFoundException;
/***
* Retrieve {@link Spec}s by {@link SpecSearchObject} from the {@link SpecStore}.
* @param specSearchObject {@link SpecSearchObject} for the {@link Spec} to be retrieved.
* @throws IOException Exception in retrieving the {@link Spec}.
*/
Collection<Spec> getSpecs(SpecSearchObject specSearchObject) throws IOException;
/***
* Retrieve specified version of the {@link Spec} by URI from the {@link SpecStore}.
* @param specUri URI for the {@link Spec} to be retrieved.
* @param version Version for the {@link Spec} to be retrieved.
* @throws IOException Exception in retrieving the {@link Spec}.
* @throws SpecNotFoundException If {@link Spec} being retrieved is not present in store.
*/
Spec getSpec(URI specUri, String version) throws IOException, SpecNotFoundException;
/***
* Retrieve all versions of the {@link Spec} by URI from the {@link SpecStore}.
* @param specUri URI for the {@link Spec} to be retrieved.
* @throws IOException Exception in retrieving the {@link Spec}.
* @throws SpecNotFoundException If {@link Spec} being retrieved is not present in store.
*/
Collection<Spec> getAllVersionsOfSpec(URI specUri) throws IOException, SpecNotFoundException;
/***
* Get all {@link Spec}s from the {@link SpecStore}.
* @throws IOException Exception in retrieving {@link Spec}s.
*/
Collection<Spec> getSpecs() throws IOException;
/***
* Retrieve a batch of {@link Spec}s of at most size batchSize beginning at startOffset after creating a unique
* ordering of the specs based on primary key spec_uri.
* @param startOffset starting row to batch the specs returned from, startOffset >= 0
* @param batchSize max number of specs returned in the batch, batchSize >= 0
* @throws IOException
* @throws IllegalArgumentException in retrieving the {@link Spec} or if startOffset < 0, batchSize < 0
*/
Collection<Spec> getSpecsPaginated(int startOffset, int batchSize) throws IOException, IllegalArgumentException;
/**
* Return an iterator of Spec URIs(Spec identifiers)
*/
Iterator<URI> getSpecURIs() throws IOException;
/**
* Return an iterator of Spec URIS with certain tag.
* Tag can be an implementation details, but provide an example here with {@link org.apache.gobblin.runtime.spec_store.MysqlSpecStore}:
* We could add Tag field in MySQL table, it stores value for convenience of filtering in Mysql statement level:
* Select * from <TABLE> Where tag == ?
*
* This type of filtering will be needed when we want to opt-out some specs in loading, or we want to only
* whitelist several specs in loading, etc.
*
*/
Iterator<URI> getSpecURIsWithTag(String tag) throws IOException;
/**
* @return A URI to identify the SpecStore itself.
* e.g. For File-System based implementation of {@link SpecStore}, the URI will be associated
* with root-level FileSystem directory.
*/
Optional<URI> getSpecStoreURI();
/***
* Returns the number of {@link Spec}s in the {@link SpecStore}.
* @throws IOException Exception in retrieving the count of {@link Spec}s.
*/
int getSize() throws IOException;
}
| 1,547 |
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/api/GobblinInstancePlugin.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.api;
import com.google.common.util.concurrent.Service;
/**
* The interfaces for Gobblin instance plugins. Plugins are objects the share configuration and
* lifespan with a specific Gobblin instance and can be used to extend its functionality. Examples
* of plugins maybe providing a REST interface, authentication and so on.
*/
public interface GobblinInstancePlugin extends Service {
/** Override this method to provide a human-readable description of the plugin */
@Override String toString();
}
| 1,548 |
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/api/MonitoredObject.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.api;
/**
* An object which is currently monitored. This object can be retrieved by {@link JobExecutionMonitor}
*/
public interface MonitoredObject {
}
| 1,549 |
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/api/FsSpecConsumer.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.api;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Future;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.mapred.FsInput;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.typesafe.config.Config;
import javax.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.runtime.job_spec.AvroJobSpec;
import org.apache.gobblin.util.AvroUtils;
import org.apache.gobblin.util.CompletedFuture;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.filters.AndPathFilter;
import org.apache.gobblin.util.filters.HiddenFilter;
@Slf4j
public class FsSpecConsumer implements SpecConsumer<Spec> {
public static final String SPEC_PATH_KEY = "gobblin.cluster.specConsumer.path";
private final Path specDirPath;
private final FileSystem fs;
private Map<URI, Path> specToPathMap = new HashMap<>();
public FsSpecConsumer(Config config) {
this(null, config);
}
public FsSpecConsumer(@Nullable FileSystem fs, Config config) {
this.specDirPath = new Path(config.getString(SPEC_PATH_KEY));
try {
this.fs = (fs == null) ? FileSystem.get(new Configuration()) : fs;
if (!this.fs.exists(specDirPath)) {
this.fs.mkdirs(specDirPath);
}
} catch (IOException e) {
throw new RuntimeException("Unable to detect spec directory file system: " + e, e);
}
}
/** List of newly changed {@link Spec}s for execution on {@link SpecExecutor}.
* The {@link Spec}s are returned in the increasing order of their modification times.
*/
@Override
public Future<? extends List<Pair<SpecExecutor.Verb, Spec>>> changedSpecs() {
List<Pair<SpecExecutor.Verb, Spec>> specList = new ArrayList<>();
FileStatus[] fileStatuses;
try {
fileStatuses = this.fs.listStatus(this.specDirPath,
new AndPathFilter(new HiddenFilter(), new AvroUtils.AvroPathFilter()));
} catch (IOException e) {
log.error("Error when listing files at path: {}", this.specDirPath.toString(), e);
return null;
}
log.info("Found {} files at path {}", fileStatuses.length, this.specDirPath.toString());
//Sort the {@link JobSpec}s in increasing order of their modification times.
//This is done so that the {JobSpec}s can be handled in FIFO order by the
//JobConfigurationManager and eventually, the GobblinHelixJobScheduler.
Arrays.sort(fileStatuses, Comparator.comparingLong(FileStatus::getModificationTime));
for (FileStatus fileStatus : fileStatuses) {
DataFileReader<AvroJobSpec> dataFileReader;
try {
dataFileReader = new DataFileReader<>(new FsInput(fileStatus.getPath(), this.fs.getConf()), new SpecificDatumReader<>());
} catch (IOException e) {
log.error("Error creating DataFileReader for: {}", fileStatus.getPath().toString(), e);
continue;
}
AvroJobSpec avroJobSpec = null;
while (dataFileReader.hasNext()) {
avroJobSpec = dataFileReader.next();
break;
}
if (avroJobSpec != null) {
JobSpec.Builder jobSpecBuilder = new JobSpec.Builder(avroJobSpec.getUri());
Properties props = new Properties();
props.putAll(avroJobSpec.getProperties());
jobSpecBuilder.withJobCatalogURI(avroJobSpec.getUri())
.withVersion(avroJobSpec.getVersion())
.withDescription(avroJobSpec.getDescription())
.withConfigAsProperties(props)
.withConfig(ConfigUtils.propertiesToConfig(props));
try {
if (!avroJobSpec.getTemplateUri().isEmpty()) {
jobSpecBuilder.withTemplate(new URI(avroJobSpec.getTemplateUri()));
}
} catch (URISyntaxException u) {
log.error("Error building a job spec: ", u);
continue;
}
String verbName = avroJobSpec.getMetadata().get(SpecExecutor.VERB_KEY);
SpecExecutor.Verb verb = SpecExecutor.Verb.valueOf(verbName);
JobSpec jobSpec = jobSpecBuilder.build();
log.debug("Successfully built jobspec: {}", jobSpec.getUri().toString());
specList.add(new ImmutablePair<SpecExecutor.Verb, Spec>(verb, jobSpec));
this.specToPathMap.put(jobSpec.getUri(), fileStatus.getPath());
}
}
return new CompletedFuture<>(specList, null);
}
@Override
public void commit(Spec spec) throws IOException {
Path path = this.specToPathMap.get(spec.getUri());
if (path != null) {
log.debug("Calling delete on path: {}", path.toString());
this.fs.delete(path, false);
} else {
log.error("No path found for job: {}", spec.getUri().toString());
}
}
}
| 1,550 |
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/api/JobExecution.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.api;
import java.net.URI;
import org.apache.gobblin.annotation.Alpha;
/**
* Identifies a specific execution of a {@link JobSpec}
*/
@Alpha
public interface JobExecution {
/** The URI of the job being executed */
URI getJobSpecURI();
/** The version of the JobSpec being launched */
String getJobSpecVersion();
/** The millisecond timestamp when the job was launched */
long getLaunchTimeMillis();
/** Unique (for the given JobExecutionLauncher) id for this execution */
String getExecutionId();
}
| 1,551 |
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/api/JobCatalogListenersContainer.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.api;
/**
* Manages a collection of {@link JobCatalogListener}s .
*/
public interface JobCatalogListenersContainer {
/**
* Adds a {@link JobCatalogListener} that will be invoked upon updates on the
* {@link JobCatalog}. Upon registration {@link JobCatalogListener#onAddJob(JobSpec)} will be
* invoked for all pre-existing jobs in the JobCatalog.
*/
void addListener(JobCatalogListener jobListener);
/**
* Like {@link #addListener(JobCatalogListener)} but it will create a weak reference. The
* implementation will automatically remove the listener registration once the listener object
* gets GCed.
*
* <p>Note that weak listeners cannot be removed using {@link #removeListener(JobCatalogListener)}.
*/
void registerWeakJobCatalogListener(JobCatalogListener jobListener);
/**
* Removes the specified listener. No-op if not registered.
*/
void removeListener(JobCatalogListener jobListener);
}
| 1,552 |
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/api/JobSpecMonitor.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.api;
import com.google.common.util.concurrent.Service;
/**
* Discovers jobs to execute and generates JobSpecs for each one.
*/
public interface JobSpecMonitor extends Service {
}
| 1,553 |
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/api/JobExecutionDriver.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.api;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.Service;
/**
* Defines an implementation which knows how to run a GobblinJob and keep track of the progress.
*
* <p> The class utilizes the {@link Service} interface.
* <ul>
* <li> {@link Service#startAsync()} starts the execution.
* <li> {@link Service#stopAsync()} cancels the execution if running; if the job has completed, it
* is a NO-OP
* <li> {@link Service#awaitTerminated(long, java.util.concurrent.TimeUnit)} - waits for the job
* to complete or get canceled.
* <ul>
*/
public interface JobExecutionDriver
extends JobExecutionStateListenerContainer, ListenableFuture<JobExecutionResult>, RunnableFuture<JobExecutionResult> {
/** The job execution ID */
JobExecution getJobExecution();
/** The job execution status */
JobExecutionStatus getJobExecutionStatus();
/** The job execution state */
JobExecutionState getJobExecutionState();
//TODO add:
//void stopForcefully();
/** {@inheritDoc} */
@Override JobExecutionResult get() throws InterruptedException;
/** {@inheritDoc} */
@Override JobExecutionResult get(long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException;
}
| 1,554 |
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/api/SpecSerDeException.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.api;
/**
* An exception when {@link Spec} cannot be correctly serialized/deserialized from underlying storage.
*/
public class SpecSerDeException extends RuntimeException {
public SpecSerDeException(Spec spec, Throwable cause) {
super("Error occurred when loading Spec with URI " + spec.getUri(), cause);
}
public SpecSerDeException(Throwable cause) {
super("Error occurred when loading Spec", cause);
}
public SpecSerDeException(String message) {
super(message);
}
}
| 1,555 |
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/api/DagActionStore.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.api;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import lombok.Data;
import org.apache.gobblin.service.FlowId;
public interface DagActionStore {
enum FlowActionType {
KILL, // Kill invoked through API call
RESUME, // Resume flow invoked through API call
LAUNCH, // Launch new flow execution invoked adhoc or through scheduled trigger
RETRY, // Invoked through DagManager for flows configured to allow retries
CANCEL, // Invoked through DagManager if flow has been stuck in Orchestrated state for a while
ADVANCE // Launch next step in multi-hop dag
}
@Data
class DagAction {
final String flowGroup;
final String flowName;
final String flowExecutionId;
final FlowActionType flowActionType;
public FlowId getFlowId() {
return new FlowId().setFlowGroup(this.flowGroup).setFlowName(this.flowName);
}
/**
* Replace flow execution id with agreed upon event time to easily track the flow
*/
public DagAction updateFlowExecutionId(long eventTimeMillis) {
return new DagAction(this.getFlowGroup(), this.getFlowName(),
String.valueOf(eventTimeMillis), this.getFlowActionType());
}
}
/**
* Check if an action exists in dagAction store by flow group, flow name and flow execution id.
* @param flowGroup flow group for the dag action
* @param flowName flow name for the dag action
* @param flowExecutionId flow execution for the dag action
* @param flowActionType the value of the dag action
* @throws IOException
*/
boolean exists(String flowGroup, String flowName, String flowExecutionId, FlowActionType flowActionType) throws IOException, SQLException;
/**
* Persist the dag action in {@link DagActionStore} for durability
* @param flowGroup flow group for the dag action
* @param flowName flow name for the dag action
* @param flowExecutionId flow execution for the dag action
* @param flowActionType the value of the dag action
* @throws IOException
*/
void addDagAction(String flowGroup, String flowName, String flowExecutionId, FlowActionType flowActionType) throws IOException;
/**
* delete the dag action from {@link DagActionStore}
* @param DagAction containing all information needed to identify dag and specific action value
* @throws IOException
* @return true if we successfully delete one record, return false if the record does not exist
*/
boolean deleteDagAction(DagAction dagAction) throws IOException;
/***
* Get all {@link DagAction}s from the {@link DagActionStore}.
* @throws IOException Exception in retrieving {@link DagAction}s.
*/
Collection<DagAction> getDagActions() throws IOException;
}
| 1,556 |
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/api/GobblinInstanceDriver.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.api;
import java.util.concurrent.Executor;
import com.codahale.metrics.Gauge;
import com.google.common.util.concurrent.Service;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.metrics.ContextAwareCounter;
import org.apache.gobblin.metrics.ContextAwareGauge;
import lombok.Getter;
/**
* An interface that defines a Gobblin Instance driver which knows how to monitor for Gobblin
* {@link JobSpec}s and run them.
* */
@Alpha
public interface GobblinInstanceDriver extends Service, JobLifecycleListenersContainer,
GobblinInstanceEnvironment {
/** The service that keeps track of jobs that are known to Gobblin */
JobCatalog getJobCatalog();
/**
* Returns a mutable instance of the job catalog
* (if it implements the {@link MutableJobCatalog} interface). Implementation will throw
* ClassCastException if the current catalog is not mutable.
*/
MutableJobCatalog getMutableJobCatalog();
/** The service the determine when jobs should be executed.*/
JobSpecScheduler getJobScheduler();
/** The service for executing Gobblin jobs */
JobExecutionLauncher getJobLauncher();
/** Metrics for instance */
StandardMetrics getMetrics();
public class StandardMetrics extends Service.Listener {
public static final String INSTANCE_NAME_TAG = "instanceName";
public static final String UPTIMEMS_NAME = "uptimeMs";
public static final String UPFLAG_NAME = "upFlag";
public static final String NUM_UNCLASSIFIED_ERRORS_NAME = "numUnclassifiedErrors";
/** The time in milliseconds since the instance started or 0 if not running. */
@Getter private final ContextAwareGauge<Long> uptimeMs;
/** 1 if running, -1 if stopped due to error, 0 if not started or shutdown */
@Getter private final ContextAwareGauge<Integer> upFlag;
/** Total error count detected by this instance which have not been classified and tracked in
* a dedicated counter. */
@Getter private final ContextAwareCounter numUnclassifiedErrors;
private long startTimeMs;
public StandardMetrics(final GobblinInstanceDriver parent) {
this.uptimeMs = parent.getMetricContext().newContextAwareGauge(UPTIMEMS_NAME, new Gauge<Long>() {
@Override public Long getValue() {
return startTimeMs > 0 ? System.currentTimeMillis() - startTimeMs : 0;
}
});
this.upFlag = parent.getMetricContext().newContextAwareGauge(UPFLAG_NAME, new Gauge<Integer>() {
@Override public Integer getValue() {
switch (parent.state()) {
case RUNNING: return 1;
case FAILED: return -1;
default: return 0;
}
}
});
this.numUnclassifiedErrors = parent.getMetricContext().contextAwareCounter(NUM_UNCLASSIFIED_ERRORS_NAME);
parent.addListener(this, new Executor() {
@Override public void execute(Runnable command) {
command.run();
}
});
}
@Override public void running() {
this.startTimeMs = System.currentTimeMillis();
}
@Override public void terminated(State from) {
this.startTimeMs = 0;
}
@Override public void failed(State from, Throwable failure) {
this.startTimeMs = 0;
}
}
}
| 1,557 |
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/api/JobLifecycleListenersContainer.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.api;
import java.util.List;
/**
* An interface for managing instances of {@link JobLifecycleListener}.
*/
public interface JobLifecycleListenersContainer {
void registerJobLifecycleListener(JobLifecycleListener listener);
/**
* Like {@link #registerJobLifecycleListener(JobLifecycleListener)} but it will create a weak
* reference. The implementation will automatically remove the listener registration once the
* listener object gets GCed.
*
* <p>Note that weak listeners cannot be removed using {@link #unregisterJobLifecycleListener(JobLifecycleListener)}.
*/
void registerWeakJobLifecycleListener(JobLifecycleListener listener);
void unregisterJobLifecycleListener(JobLifecycleListener listener);
List<JobLifecycleListener> getJobLifecycleListeners();
}
| 1,558 |
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/api/FsSpecProducer.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.api;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Future;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.typesafe.config.Config;
import javax.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.runtime.job_spec.AvroJobSpec;
import org.apache.gobblin.util.AvroUtils;
import org.apache.gobblin.util.CompletedFuture;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.HadoopUtils;
/**
* An implementation of {@link SpecProducer} that produces {@link JobSpec}s to the {@value FsSpecConsumer#SPEC_PATH_KEY}
* for consumption by the {@link FsSpecConsumer}.
*
* The pair {@link FsSpecProducer} and {@link FsSpecConsumer} assumes serialization format as Avro. More specifically,
* {@link JobSpec}s will be serialized as ".avro" file by {@link FsSpecProducer} and {@link FsSpecConsumer} filtered
* all files without proper postfix to avoid loading corrupted {@link JobSpec}s that could possibly existed due to
* ungraceful exits of the application or weak file system semantics.
*
*/
@Slf4j
public class FsSpecProducer implements SpecProducer<Spec> {
private Path specConsumerPath;
private FileSystem fs;
public FsSpecProducer(Config config) {
this(null, config);
}
public FsSpecProducer(@Nullable FileSystem fs, Config config) {
String specConsumerDir = ConfigUtils.getString(config, FsSpecConsumer.SPEC_PATH_KEY, "");
Preconditions.checkArgument(!Strings.isNullOrEmpty(specConsumerDir), "Missing argument: " + FsSpecConsumer.SPEC_PATH_KEY);
this.specConsumerPath = new Path(specConsumerDir);
try {
this.fs = (fs == null) ? FileSystem.get(new Configuration()) : fs;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Add a {@link Spec} for execution on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param addedSpec*/
@Override
public Future<?> addSpec(Spec addedSpec) {
return writeSpec(addedSpec, SpecExecutor.Verb.ADD);
}
/** Update a {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param updatedSpec*/
@Override
public Future<?> updateSpec(Spec updatedSpec) {
return writeSpec(updatedSpec, SpecExecutor.Verb.UPDATE);
}
private Future<?> writeSpec(Spec spec, SpecExecutor.Verb verb) {
if (spec instanceof JobSpec) {
try {
AvroJobSpec avroJobSpec = convertToAvroJobSpec((JobSpec) spec, verb);
writeAvroJobSpec(avroJobSpec);
return new CompletedFuture<>(Boolean.TRUE, null);
} catch (IOException e) {
log.error("Exception encountered when adding Spec {}", spec);
return new CompletedFuture<>(Boolean.TRUE, e);
}
} else {
throw new RuntimeException("Unsupported spec type " + spec.getClass());
}
}
/** Delete a {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param deletedSpecURI
* @param headers*/
@Override
public Future<?> deleteSpec(URI deletedSpecURI, Properties headers) {
AvroJobSpec avroJobSpec = AvroJobSpec.newBuilder().setUri(deletedSpecURI.toString())
.setMetadata(ImmutableMap.of(SpecExecutor.VERB_KEY, SpecExecutor.Verb.DELETE.name()))
.setProperties(Maps.fromProperties(headers)).build();
try {
writeAvroJobSpec(avroJobSpec);
return new CompletedFuture<>(Boolean.TRUE, null);
} catch (IOException e) {
log.error("Exception encountered when writing DELETE spec");
return new CompletedFuture<>(Boolean.TRUE, e);
}
}
/** List all {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}. */
@Override
public Future<? extends List<Spec>> listSpecs() {
throw new UnsupportedOperationException();
}
private AvroJobSpec convertToAvroJobSpec(JobSpec jobSpec, SpecExecutor.Verb verb) {
return AvroJobSpec.newBuilder().
setUri(jobSpec.getUri().toString()).
setProperties(Maps.fromProperties(jobSpec.getConfigAsProperties())).
setTemplateUri("FS:///").
setDescription(jobSpec.getDescription()).
setVersion(jobSpec.getVersion()).
setMetadata(ImmutableMap.of(SpecExecutor.VERB_KEY, verb.name())).build();
}
private void writeAvroJobSpec(AvroJobSpec jobSpec) throws IOException {
DatumWriter<AvroJobSpec> datumWriter = new SpecificDatumWriter<>(AvroJobSpec.SCHEMA$);
DataFileWriter<AvroJobSpec> dataFileWriter = new DataFileWriter<>(datumWriter);
Path jobSpecPath = new Path(this.specConsumerPath, annotateSpecFileName(jobSpec.getUri()));
//Write the new JobSpec to a temporary path first.
Path tmpDir = new Path(this.specConsumerPath, UUID.randomUUID().toString());
if (!fs.exists(tmpDir)) {
fs.mkdirs(tmpDir);
}
Path tmpJobSpecPath = new Path(tmpDir, jobSpec.getUri());
OutputStream out = fs.create(tmpJobSpecPath);
dataFileWriter.create(AvroJobSpec.SCHEMA$, out);
dataFileWriter.append(jobSpec);
dataFileWriter.close();
//Rename the JobSpec from temporary to final location.
HadoopUtils.renamePath(fs, tmpJobSpecPath, jobSpecPath, true);
//Delete the temporary path once the jobspec has been moved to its final publish location.
log.info("Deleting {}", tmpJobSpecPath.getParent().toString());
fs.delete(tmpJobSpecPath.getParent(), true);
}
private String annotateSpecFileName(String rawName) {
return rawName + AvroUtils.AVRO_SUFFIX;
}
} | 1,559 |
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/api/JobSpecSchedulerListenersContainer.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.api;
import java.util.List;
/**
* Implemented by classes that can manage a collection of {@link JobSpecSchedulerListener}
* instances.
*/
public interface JobSpecSchedulerListenersContainer {
void registerJobSpecSchedulerListener(JobSpecSchedulerListener listener);
/** Like {@link #registerJobSpecSchedulerListener(JobSpecSchedulerListener)} but it will create a
* weak reference. The implementation will automatically remove the listener registration once the
* listener object gets GCed.
*
* <p>Note that weak listeners cannot be removed used {@link #unregisterJobSpecSchedulerListener(JobSpecSchedulerListener)}.*/
void registerWeakJobSpecSchedulerListener(JobSpecSchedulerListener listener);
void unregisterJobSpecSchedulerListener(JobSpecSchedulerListener listener);
List<JobSpecSchedulerListener> getJobSpecSchedulerListeners();
}
| 1,560 |
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/api/JobSpecMonitorFactory.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.api;
import java.io.IOException;
/**
* A fact
*/
public interface JobSpecMonitorFactory {
/**
* Add a {@link JobSpecMonitor} that will be notified of new jobs. {@link JobSpecMonitor}
* will call put for any new / updated jobs, and remove for any deleted jobs.
* @param instanceDriver the GobblinInstanceDriver managing the job catalog; this can be
* used to access the environment for configuration
* @param jobCatalog the job catalog to be notified for JobSpec operations.
*/
JobSpecMonitor forJobCatalog(GobblinInstanceDriver instanceDriver, MutableJobCatalog jobCatalog) throws IOException;
}
| 1,561 |
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/api/JobCatalog.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.api;
import java.net.URI;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.typesafe.config.Config;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.instrumented.GobblinMetricsKeys;
import org.apache.gobblin.instrumented.Instrumentable;
import org.apache.gobblin.instrumented.Instrumented;
import org.apache.gobblin.instrumented.StandardMetricsBridge;
import org.apache.gobblin.metrics.ContextAwareGauge;
import org.apache.gobblin.metrics.ContextAwareTimer;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.util.ConfigUtils;
/**
* A catalog of all the {@link JobSpec}s a Gobblin instance is currently aware of.
*/
@Alpha
public interface JobCatalog extends JobCatalogListenersContainer, Instrumentable, StandardMetricsBridge {
/** Returns an immutable {@link Collection} of {@link JobSpec}s that are known to the catalog. */
Collection<JobSpec> getJobs();
default Iterator<JobSpec> getJobSpecIterator() {
return getJobs().iterator();
}
/** Metrics for the job catalog; null if
* ({@link #isInstrumentationEnabled()}) is false. */
JobCatalog.StandardMetrics getMetrics();
default Collection<StandardMetricsBridge.StandardMetrics> getStandardMetricsCollection() {
JobCatalog.StandardMetrics standardMetrics = getMetrics();
return standardMetrics == null? ImmutableList.of() : ImmutableList.of(standardMetrics);
}
/**
* Get a {@link JobSpec} by uri.
* @throws JobSpecNotFoundException if no such JobSpec exists
**/
JobSpec getJobSpec(URI uri) throws JobSpecNotFoundException;
@Slf4j
public static class StandardMetrics extends StandardMetricsBridge.StandardMetrics implements JobCatalogListener {
public static final String NUM_ACTIVE_JOBS_NAME = "numActiveJobs";
public static final String TOTAL_ADD_CALLS = "totalAddCalls";
public static final String TOTAL_DELETE_CALLS = "totalDeleteCalls";
public static final String TOTAL_UPDATE_CALLS = "totalUpdateCalls";
public static final String TIME_FOR_JOB_CATALOG_GET = "timeForJobCatalogGet";
public static final String TRACKING_EVENT_NAME = "JobCatalogEvent";
public static final String JOB_ADDED_OPERATION_TYPE = "JobAdded";
public static final String JOB_DELETED_OPERATION_TYPE = "JobDeleted";
public static final String JOB_UPDATED_OPERATION_TYPE = "JobUpdated";
private final MetricContext metricsContext;
protected final int timeWindowSizeInMinutes;
@Getter private final AtomicLong totalAddedJobs;
@Getter private final AtomicLong totalDeletedJobs;
@Getter private final AtomicLong totalUpdatedJobs;
@Getter private final ContextAwareTimer timeForJobCatalogGet;
@Getter private final ContextAwareGauge<Long> totalAddCalls;
@Getter private final ContextAwareGauge<Long> totalDeleteCalls;
@Getter private final ContextAwareGauge<Long> totalUpdateCalls;
@Getter private final ContextAwareGauge<Integer> numActiveJobs;
public StandardMetrics(final JobCatalog jobCatalog, Optional<Config> sysConfig) {
// timer window size
this.timeWindowSizeInMinutes = sysConfig.isPresent()?
ConfigUtils.getInt(sysConfig.get(), ConfigurationKeys.METRIC_TIMER_WINDOW_SIZE_IN_MINUTES, ConfigurationKeys.DEFAULT_METRIC_TIMER_WINDOW_SIZE_IN_MINUTES) :
ConfigurationKeys.DEFAULT_METRIC_TIMER_WINDOW_SIZE_IN_MINUTES;
this.metricsContext = jobCatalog.getMetricContext();
this.totalAddedJobs = new AtomicLong(0);
this.totalDeletedJobs = new AtomicLong(0);
this.totalUpdatedJobs = new AtomicLong(0);
this.timeForJobCatalogGet = metricsContext.contextAwareTimer(TIME_FOR_JOB_CATALOG_GET, timeWindowSizeInMinutes, TimeUnit.MINUTES);
this.totalAddCalls = metricsContext.newContextAwareGauge(TOTAL_ADD_CALLS, ()->this.totalAddedJobs.get());
this.totalUpdateCalls = metricsContext.newContextAwareGauge(TOTAL_UPDATE_CALLS, ()->this.totalUpdatedJobs.get());
this.totalDeleteCalls = metricsContext.newContextAwareGauge(TOTAL_DELETE_CALLS, ()->this.totalDeletedJobs.get());
this.numActiveJobs = metricsContext.newContextAwareGauge(NUM_ACTIVE_JOBS_NAME, ()->(int)(totalAddedJobs.get() - totalDeletedJobs.get()));
this.contextAwareMetrics.add(timeForJobCatalogGet);
this.contextAwareMetrics.add(totalAddCalls);
this.contextAwareMetrics.add(totalDeleteCalls);
this.contextAwareMetrics.add(totalUpdateCalls);
this.contextAwareMetrics.add(numActiveJobs);
}
public void updateGetJobTime(long startTime) {
log.info("updateGetJobTime...");
Instrumented.updateTimer(Optional.of(this.timeForJobCatalogGet), System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
@Override public void onAddJob(JobSpec addedJob) {
this.totalAddedJobs.incrementAndGet();
submitTrackingEvent(addedJob, JOB_ADDED_OPERATION_TYPE);
}
private void submitTrackingEvent(JobSpec job, String operType) {
submitTrackingEvent(job.getUri(), job.getVersion(), operType);
}
private void submitTrackingEvent(URI jobSpecURI, String jobSpecVersion, String operType) {
GobblinTrackingEvent e = GobblinTrackingEvent.newBuilder()
.setName(TRACKING_EVENT_NAME)
.setNamespace(JobCatalog.class.getName())
.setMetadata(ImmutableMap.<String, String>builder()
.put(GobblinMetricsKeys.OPERATION_TYPE_META, operType)
.put(GobblinMetricsKeys.JOB_SPEC_URI_META, jobSpecURI.toString())
.put(GobblinMetricsKeys.JOB_SPEC_VERSION_META, jobSpecVersion)
.build())
.build();
this.metricsContext.submitEvent(e);
}
@Override
public void onDeleteJob(URI deletedJobURI, String deletedJobVersion) {
this.totalDeletedJobs.incrementAndGet();
submitTrackingEvent(deletedJobURI, deletedJobVersion, JOB_DELETED_OPERATION_TYPE);
}
@Override
public void onUpdateJob(JobSpec updatedJob) {
this.totalUpdatedJobs.incrementAndGet();
submitTrackingEvent(updatedJob, JOB_UPDATED_OPERATION_TYPE);
}
}
}
| 1,562 |
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/api/JobSpecNotFoundException.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.api;
import java.net.URI;
/**
* An exception thrown when a JobSpec with a given URI is not found.
*/
public class JobSpecNotFoundException extends SpecNotFoundException {
public JobSpecNotFoundException(URI missingJobSpecURI) {
super(missingJobSpecURI);
}
}
| 1,563 |
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/api/SpecCatalogListenersContainer.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.api;
public interface SpecCatalogListenersContainer {
/**
* Adds a {@link SpecCatalogListener} that will be invoked upon updates on the
* {@link SpecCatalog}. Upon registration {@link SpecCatalogListener#onAddSpec(Spec)} will be
* invoked for all pre-existing specs in the SpecCatalog.
*/
void addListener(SpecCatalogListener specListener);
/**
* Like {@link #addListener(SpecCatalogListener)} but it will create a weak reference. The
* implementation will automatically remove the listener registration once the listener object
* gets GCed.
*
* <p>Note that weak listeners cannot be removed using {@link #removeListener(SpecCatalogListener)}.
*/
void registerWeakSpecCatalogListener(SpecCatalogListener specCatalogListener);
/**
* Removes the specified listener. No-op if not registered.
*/
void removeListener(SpecCatalogListener specCatalogListener);
}
| 1,564 |
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/api/JobTemplate.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.api;
import com.typesafe.config.Config;
import java.util.Collection;
/**
* An interface for claiming methods used for
* retrieving template configs
* and properties that are required by user to fit in.
* <p>
* Each data source may have its own Job Template.
* Examples are available based on requests.
* </p>
*
*/
public interface JobTemplate extends Spec {
/**
* Retrieve all configuration inside pre-written template.
* @return
*/
Config getRawTemplateConfig() throws SpecNotFoundException, TemplateException;
/**
* Retrieve all configs that are required from user to fill.
* @return
*/
Collection<String> getRequiredConfigList() throws SpecNotFoundException, TemplateException;
/**
* Retrieve all job names that this job depends on. Useful for building a dag of
* JobTemplates.
*/
Collection<String> getDependencies();
/**
* Return the combine configuration of template and user customized attributes.
*
* Note, do not use this method directly, instead use {@link org.apache.gobblin.runtime.job_spec.ResolvedJobSpec}.
*/
Config getResolvedConfig(Config userProps) throws SpecNotFoundException, TemplateException;
/**
* The Exception thrown while occurring error when loading/resolving a template.
* Note that the template here is not necessary to be a JobTemplate, it could be a FlowTemplate in the
* context of Gobblin Service.
*/
class TemplateException extends Exception {
public TemplateException(String message, Throwable cause) {
super(message, cause);
}
public TemplateException(String message) {
super(message);
}
}
}
| 1,565 |
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/api/SpecCatalogListener.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.api;
import com.google.common.base.MoreObjects;
import java.net.URI;
import java.util.Properties;
import org.apache.gobblin.runtime.spec_catalog.AddSpecResponse;
import org.apache.gobblin.util.callbacks.Callback;
public interface SpecCatalogListener {
/** Invoked when a new {@link Spec} is added to the catalog and for all pre-existing specs on registration
* of the listener.*/
AddSpecResponse onAddSpec(Spec addedSpec);
/**
* Invoked when a {@link Spec} gets removed from the catalog.
*/
public void onDeleteSpec(URI deletedSpecURI, String deletedSpecVersion, Properties headers);
/**
* Invoked when the contents of a {@link Spec} gets updated in the catalog.
*/
public void onUpdateSpec(Spec updatedSpec);
/** A standard implementation of onAddSpec as a functional object */
public static class AddSpecCallback extends Callback<SpecCatalogListener, AddSpecResponse> {
private final Spec _addedSpec;
public AddSpecCallback(Spec addedSpec) {
super(MoreObjects.toStringHelper("onAddSpec").add("addedSpec", addedSpec).toString());
_addedSpec = addedSpec;
}
@Override
public AddSpecResponse apply(SpecCatalogListener listener) {
return listener.onAddSpec(_addedSpec);
}
}
/** A standard implementation of onDeleteSpec as a functional object */
public static class DeleteSpecCallback extends Callback<SpecCatalogListener, Void> {
private final URI _deletedSpecURI;
private final String _deletedSpecVersion;
private final Properties _headers;
public DeleteSpecCallback(URI deletedSpecURI, String deletedSpecVersion, Properties headers) {
super(MoreObjects.toStringHelper("onDeleteSpec")
.add("deletedSpecURI", deletedSpecURI)
.add("deletedSpecVersion", deletedSpecVersion)
.toString());
_deletedSpecURI = deletedSpecURI;
_deletedSpecVersion = deletedSpecVersion;
_headers = headers;
}
@Override public Void apply(SpecCatalogListener listener) {
listener.onDeleteSpec(_deletedSpecURI, _deletedSpecVersion, _headers);
return null;
}
}
public static class UpdateSpecCallback extends Callback<SpecCatalogListener, Void> {
private final Spec _updatedSpec;
public UpdateSpecCallback(Spec updatedSpec) {
super(MoreObjects.toStringHelper("onUpdateSpec")
.add("updatedSpec", updatedSpec).toString());
_updatedSpec = updatedSpec;
}
@Override
public Void apply(SpecCatalogListener listener) {
listener.onUpdateSpec(_updatedSpec);
return null;
}
}
/**
* A default implementation to return the name of the {@link SpecCatalogListener}.
* @return
*/
default String getName() {
return getClass().getName();
}
}
| 1,566 |
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/api/TopologySpec.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.api;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.annotation.concurrent.NotThreadSafe;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.util.ClassAliasResolver;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.runtime.spec_executorInstance.InMemorySpecExecutor;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Data model representation that describes a topology ie. a {@link SpecExecutor} and its
* capabilities tuple .
*
*/
@Alpha
@Data
@AllArgsConstructor
@NotThreadSafe
public class TopologySpec implements Configurable, Spec {
public static final String DEFAULT_SPEC_EXECUTOR_INSTANCE = InMemorySpecExecutor.class.getCanonicalName();
public static final String SPEC_EXECUTOR_INSTANCE_KEY = "specExecutorInstance.class";
private static final long serialVersionUID = 6106269076155338046L;
/** An URI identifying the topology. */
final URI uri;
/** The implementation-defined version of this spec. */
final String version;
/** Human-readable description of the topology spec */
final String description;
/** Topology config as a typesafe config object*/
@SuppressWarnings(justification="No bug", value="SE_BAD_FIELD")
final Config config;
/** Topology config as a properties collection for backwards compatibility */
// Note that this property is not strictly necessary as it can be generated from the typesafe
// config. We use it as a cache until typesafe config is more widely adopted in Gobblin.
final Properties configAsProperties;
/** Underlying executor instance such as Gobblin cluster or Azkaban */
@SuppressWarnings(justification="Initialization handled by getter", value="SE_TRANSIENT_FIELD_NOT_RESTORED")
transient SpecExecutor specExecutorInstance;
/**
* @return A {@link SpecExecutor}'s instance defined by <Technology, Location, Communication Mechanism>
*/
public synchronized SpecExecutor getSpecExecutor() {
if (null == specExecutorInstance) {
String specExecutorClass = DEFAULT_SPEC_EXECUTOR_INSTANCE;
if (config.hasPath(SPEC_EXECUTOR_INSTANCE_KEY)) {
specExecutorClass = config.getString(SPEC_EXECUTOR_INSTANCE_KEY);
}
try {
ClassAliasResolver<SpecExecutor> _aliasResolver =
new ClassAliasResolver<>(SpecExecutor.class);
specExecutorInstance = (SpecExecutor) ConstructorUtils
.invokeConstructor(Class.forName(_aliasResolver
.resolve(specExecutorClass)), config);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
| ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
return specExecutorInstance;
}
public static TopologySpec.Builder builder(URI topologySpecUri) {
return new TopologySpec.Builder(topologySpecUri);
}
public static TopologySpec.Builder builder(String topologySpecUri) {
return new TopologySpec.Builder(topologySpecUri);
}
public static TopologySpec.Builder builder() {
return new TopologySpec.Builder();
}
/** Creates a builder for the TopologySpec based on values in a topology properties config. */
public static TopologySpec.Builder builder(URI catalogURI, Properties topologyProps) {
String name = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_NAME_KEY);
String group = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_GROUP_KEY, "default");
try {
URI topologyURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(),
"/" + group + "/" + name, null);
TopologySpec.Builder builder = new TopologySpec.Builder(topologyURI).withConfigAsProperties(topologyProps);
String descr = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_DESCRIPTION_KEY, null);
if (null != descr) {
builder = builder.withDescription(descr);
}
return builder;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create a TopologySpec URI: " + e, e);
}
}
public String toShortString() {
return getUri().toString() + "/" + getVersion();
}
public String toLongString() {
return getUri().toString() + "/" + getVersion() + "[" + getDescription() + "]";
}
@Override
public String toString() {
return toShortString();
}
/**
* Builder for {@link TopologySpec}s.
* <p> Defaults/conventions:
* <ul>
* <li> Default topologyCatalogURI is {@link #DEFAULT_TOPOLOGY_CATALOG_SCHEME}:
* <li> Convention for TopologySpec URI: <topologyCatalogURI>/config.get({@link ConfigurationKeys#TOPOLOGY_GROUP_KEY})/config.get({@link ConfigurationKeys#TOPOLOGY_NAME_KEY})
* <li> Convention for Description: config.get({@link ConfigurationKeys#TOPOLOGY_DESCRIPTION_KEY})
* <li> Default version: 1
* </ul>
*/
public static class Builder {
public static final String DEFAULT_TOPOLOGY_CATALOG_SCHEME = "gobblin-topology";
@VisibleForTesting
private Optional<Config> config = Optional.absent();
private Optional<Properties> configAsProperties = Optional.absent();
private Optional<URI> uri;
private String version = "1";
private Optional<String> description = Optional.absent();
private Optional<URI> topologyCatalogURI = Optional.absent();
private Optional<SpecExecutor> specExecutorInstance = Optional.absent();
public Builder(URI topologySpecUri) {
Preconditions.checkNotNull(topologySpecUri);
this.uri = Optional.of(topologySpecUri);
}
public Builder(String topologySpecUri) {
Preconditions.checkNotNull(topologySpecUri);
Preconditions.checkNotNull(topologySpecUri);
try {
this.uri = Optional.of(new URI(topologySpecUri));
}
catch (URISyntaxException e) {
throw new RuntimeException("Invalid TopologySpec config: " + e, e);
}
}
public Builder() {
this.uri = Optional.absent();
}
public TopologySpec build() {
Preconditions.checkNotNull(this.uri);
Preconditions.checkNotNull(this.version);
return new TopologySpec(getURI(), getVersion(), getDescription(), getConfig(), getConfigAsProperties(),
getSpecExceutorInstance());
}
/** The scheme and authority of the topology catalog URI are used to generate TopologySpec URIs from
* topology configs. */
public TopologySpec.Builder withTopologyCatalogURI(URI topologyCatalogURI) {
this.topologyCatalogURI = Optional.of(topologyCatalogURI);
return this;
}
public TopologySpec.Builder withTopologyCatalogURI(String topologyCatalogURI) {
try {
this.topologyCatalogURI = Optional.of(new URI(topologyCatalogURI));
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to set topology catalog URI: " + e, e);
}
return this;
}
public URI getDefaultTopologyCatalogURI() {
try {
return new URI(DEFAULT_TOPOLOGY_CATALOG_SCHEME, null, "/", null, null);
} catch (URISyntaxException e) {
// should not happen
throw new Error("Unexpected exception: " + e, e);
}
}
public URI getTopologyCatalogURI() {
if (! this.topologyCatalogURI.isPresent()) {
this.topologyCatalogURI = Optional.of(getDefaultTopologyCatalogURI());
}
return this.topologyCatalogURI.get();
}
public URI getDefaultURI() {
URI topologyCatalogURI = getTopologyCatalogURI();
Config topologyCfg = getConfig();
String name = topologyCfg.hasPath(ConfigurationKeys.TOPOLOGY_NAME_KEY) ?
topologyCfg.getString(ConfigurationKeys.TOPOLOGY_NAME_KEY) :
"default";
String group = topologyCfg.hasPath(ConfigurationKeys.TOPOLOGY_GROUP_KEY) ?
topologyCfg.getString(ConfigurationKeys.TOPOLOGY_GROUP_KEY) :
"default";
try {
return new URI(topologyCatalogURI.getScheme(), topologyCatalogURI.getAuthority(),
"/" + group + "/" + name, null, null);
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create default TopologySpec URI:" + e, e);
}
}
public URI getURI() {
if (! this.uri.isPresent()) {
this.uri = Optional.of(getDefaultURI());
}
return this.uri.get();
}
public TopologySpec.Builder withVersion(String version) {
Preconditions.checkNotNull(version);
this.version = version;
return this;
}
public String getVersion() {
return this.version;
}
public TopologySpec.Builder withDescription(String topologyDescription) {
Preconditions.checkNotNull(topologyDescription);
this.description = Optional.of(topologyDescription);
return this;
}
public String getDefaultDescription() {
Config topologyConf = getConfig();
return topologyConf.hasPath(ConfigurationKeys.TOPOLOGY_DESCRIPTION_KEY) ?
topologyConf.getString(ConfigurationKeys.TOPOLOGY_DESCRIPTION_KEY) :
"Gobblin topology " + getURI();
}
public String getDescription() {
if (! this.description.isPresent()) {
this.description = Optional.of(getDefaultDescription());
}
return this.description.get();
}
public Config getDefaultConfig() {
return ConfigFactory.empty();
}
public Config getConfig() {
if (!this.config.isPresent()) {
this.config = this.configAsProperties.isPresent() ?
Optional.of(ConfigUtils.propertiesToTypedConfig(this.configAsProperties.get(),
Optional.<String>absent())) :
Optional.of(getDefaultConfig());
}
return this.config.get();
}
public TopologySpec.Builder withConfig(Config topologyConfig) {
Preconditions.checkNotNull(topologyConfig);
this.config = Optional.of(topologyConfig);
return this;
}
public Properties getConfigAsProperties() {
if (!this.configAsProperties.isPresent()) {
this.configAsProperties = Optional.of(ConfigUtils.configToProperties(this.config.get()));
}
return this.configAsProperties.get();
}
public TopologySpec.Builder withConfigAsProperties(Properties topologyConfig) {
Preconditions.checkNotNull(topologyConfig);
this.configAsProperties = Optional.of(topologyConfig);
return this;
}
public SpecExecutor getSpecExceutorInstance() {
if (!this.specExecutorInstance.isPresent()) {
// TODO: Try to init SpecProducer from config if not initialized via builder.
throw new RuntimeException("SpecExecutor not initialized.");
}
return this.specExecutorInstance.get();
}
public TopologySpec.Builder withSpecExecutor(SpecExecutor specExecutor) {
Preconditions.checkNotNull(specExecutor);
this.specExecutorInstance = Optional.of(specExecutor);
return this;
}
}
/**
* get the private uri as the primary key for this object.
* @return
*/
public URI getUri() {
return this.uri;
}
} | 1,567 |
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/api/JobCatalogWithTemplates.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.api;
import java.net.URI;
import java.util.Collection;
/**
* A {@link JobTemplate} that supports loading {@link JobTemplate}s.
*/
public interface JobCatalogWithTemplates extends JobCatalog {
/**
* Get {@link JobTemplate} with given {@link URI}.
* @throws SpecNotFoundException if a {@link JobTemplate} with given {@link URI} cannot be found.
*/
JobTemplate getTemplate(URI uri) throws SpecNotFoundException, JobTemplate.TemplateException;
/**
* List all {@link JobTemplate}s available.
*/
Collection<JobTemplate> getAllTemplates();
}
| 1,568 |
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/api/JobSpecSchedulerListener.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.api;
import com.google.common.base.MoreObjects;
import org.apache.gobblin.util.callbacks.Callback;
/**
* {@link JobSpecScheduler} callbacks.
*/
public interface JobSpecSchedulerListener {
/** Called just before a job gets added to the scheduler */
void onJobScheduled(JobSpecSchedule jobSchedule);
/** Called just before a job gets removed from the scheduler */
void onJobUnscheduled(JobSpecSchedule jobSchedule);
/** Called just before the job (runnable) gets triggered by the scheduler */
void onJobTriggered(JobSpec jobSpec);
public class JobScheduledCallback extends Callback<JobSpecSchedulerListener, Void> {
private final JobSpecSchedule _jobSchedule;
public JobScheduledCallback(JobSpecSchedule jobSchedule) {
super(MoreObjects.toStringHelper("onJobScheduled").add("jobSchedule", jobSchedule).toString());
_jobSchedule = jobSchedule;
}
@Override public Void apply(JobSpecSchedulerListener listener) {
listener.onJobScheduled(_jobSchedule);
return null;
}
}
public class JobUnscheduledCallback extends Callback<JobSpecSchedulerListener, Void> {
private final JobSpecSchedule _jobSchedule;
public JobUnscheduledCallback(JobSpecSchedule jobSchedule) {
super(MoreObjects.toStringHelper("onJobUnscheduled").add("jobSchedule", jobSchedule).toString());
_jobSchedule = jobSchedule;
}
@Override public Void apply(JobSpecSchedulerListener listener) {
listener.onJobUnscheduled(_jobSchedule);
return null;
}
}
public class JobTriggeredCallback extends Callback<JobSpecSchedulerListener, Void> {
private final JobSpec _jobSpec;
public JobTriggeredCallback(JobSpec jobSpec) {
super(MoreObjects.toStringHelper("onJobTriggered").add("jobSpec", jobSpec).toString());
_jobSpec = jobSpec;
}
@Override public Void apply(JobSpecSchedulerListener listener) {
listener.onJobTriggered(_jobSpec);
return null;
}
}
}
| 1,569 |
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/api/JobLifecycleListener.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.api;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.util.callbacks.Callback;
/**
* A listener that can track the full lifecycle of a job: from the registering of the jobspec to
* completion of any of the job executions.
*/
@Alpha
public interface JobLifecycleListener
extends JobCatalogListener, JobSpecSchedulerListener, JobExecutionStateListener {
/** Called before the job driver gets started. */
void onJobLaunch(JobExecutionDriver jobDriver);
public static class JobLaunchCallback extends Callback<JobLifecycleListener, Void> {
private final JobExecutionDriver _jobDriver;
public JobLaunchCallback(JobExecutionDriver jobDriver) {
super(MoreObjects.toStringHelper("onJobLaunch").add("jobDriver", jobDriver).toString());
Preconditions.checkNotNull(jobDriver);
_jobDriver = jobDriver;
}
@Override public Void apply(JobLifecycleListener listener) {
listener.onJobLaunch(_jobDriver);
return null;
}
}
}
| 1,570 |
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/api/JobSpecSchedule.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.api;
import com.google.common.base.Optional;
/**
* The schedule for a job
*
*/
public interface JobSpecSchedule {
/** The JobSpec of the Gobblin job to be run */
JobSpec getJobSpec();
/** The runnable that should be invoked by the scheduler */
Runnable getJobRunnable();
/** The millisecond timestamp of the next execution of this schedule if any. */
Optional<Long> getNextRunTimeMillis();
}
| 1,571 |
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/api/SpecSearchObject.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.api;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* This is an interface to package all the parameters that should be used to search {@link Spec} in a {@link SpecStore}
*/
public interface SpecSearchObject {
/** @returns `baseStatement`, further constrained by the search object's restrictions (e.g. through (unbound) `WHERE` clause conditions) */
String augmentBaseGetStatement(String baseStatement) throws IOException;
/** Bind all placeholders in `statement`, which must have been prepared from the result of {@link this.augmentBaseGetStatment()} */
public void completePreparedStatement(PreparedStatement statement) throws SQLException;
}
| 1,572 |
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/api/GobblinInstanceEnvironment.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.api;
import org.slf4j.Logger;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.instrumented.Instrumentable;
/**
* Defines Gobblin a set of standard configuration features for a gobblin instance. Passing an
* instance of this interface can be used to configure Gobbling components like {@link JobCatalog},
* {@link JobSpecScheduler} or {@link JobExecutionLauncher}.
*/
public interface GobblinInstanceEnvironment extends Instrumentable {
/** The instance name (for debugging/logging purposes) */
String getInstanceName();
/** The logger used by this instance*/
Logger getLog();
/** The global system-wide configuration, typically provided by the {@link GobblinInstanceLauncher} */
Configurable getSysConfig();
/** The {@link SharedResourcesBroker} for this instance. */
SharedResourcesBroker<GobblinScopeTypes> getInstanceBroker();
}
| 1,573 |
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/api/JobExecutionStatus.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.api;
public interface JobExecutionStatus {
public static final String UKNOWN_STAGE = "unkown";
JobExecution getJobExecution();
MonitoredObject getRunningState();
/** Arbitrary execution stage, e.g. setup, workUnitGeneration, taskExecution, publishing */
String getStage();
}
| 1,574 |
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/api/GobblinInstanceLauncher.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.api;
import com.google.common.util.concurrent.Service;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.gobblin.annotation.Alpha;
import lombok.Getter;
/**
* Main class instantiated by the JVM or running framework. Reads application level
* configurations, instantiates and runs the Gobblin instance driver.
*/
@Alpha
public interface GobblinInstanceLauncher extends Service, Configurable, GobblinInstanceEnvironment {
/**
* Creates a new Gobblin instance to run Gobblin jobs.
* @throws IllegalStateException if {@link #isRunning()} is false.*/
GobblinInstanceDriver getDriver() throws IllegalStateException;
// Standard configuration for Gobblin instances
@Getter
public static class ConfigAccessor {
static final String RESOURCE_NAME =
GobblinInstanceLauncher.class.getPackage().getName().replaceAll("[.]", "/")
+ "/"
+ GobblinInstanceLauncher.class.getSimpleName()
+ ".conf";
/** The namespace for all config options */
static final String CONFIG_PREFIX = "gobblin.instance";
/** The time to wait for gobblin instance components to start in milliseconds. */
static final String START_TIMEOUT_MS = "startTimeoutMs";
/** The time wait for Gobblin components to shutdown in milliseconds. */
static final String SHUTDOWN_TIMEOUT_MS = "shutdownTimeoutMs";
private final long startTimeoutMs;
private final long shutdownTimeoutMs;
/** Config accessor from a no namespaced typesafe config. */
public ConfigAccessor(Config cfg) {
Config effectiveCfg = cfg.withFallback(getDefaultConfig().getConfig(CONFIG_PREFIX));
this.startTimeoutMs = effectiveCfg.getLong(START_TIMEOUT_MS);
this.shutdownTimeoutMs = effectiveCfg.getLong(SHUTDOWN_TIMEOUT_MS);
}
public static Config getDefaultConfig() {
return ConfigFactory.parseResources(GobblinInstanceLauncher.class,
GobblinInstanceLauncher.class.getSimpleName() + ".conf").withFallback(ConfigFactory.load());
}
public static ConfigAccessor createFromGlobalConfig(Config cfg) {
Config localCfg = cfg.hasPath(CONFIG_PREFIX) ? cfg.getConfig(CONFIG_PREFIX) :
ConfigFactory.empty();
return new ConfigAccessor(localCfg);
}
}
}
| 1,575 |
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/api/SecureJobTemplate.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.api;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* A secure template is a {@link JobTemplate} which only allows the user configuration to specify a static set of
* keys. This allows most of the template to be non overridable to tightly control how a job executes.
*/
public interface SecureJobTemplate extends JobTemplate {
/**
* Filter the user config to only preserve the keys allowed by a secure template.
*/
static Config filterUserConfig(SecureJobTemplate template, Config userConfig, Logger logger) {
if (!template.isSecure()) {
return userConfig;
}
Config survivingConfig = ConfigFactory.empty();
for (String key : template.overridableProperties()) {
if (userConfig.hasPath(key)) {
survivingConfig = survivingConfig.withValue(key, userConfig.getValue(key));
userConfig = userConfig.withoutPath(key);
}
}
if (!userConfig.isEmpty()) {
logger.warn(String.format("Secure template %s ignored the following keys because they are not overridable: %s",
template.getUri().toString(),
userConfig.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.joining(", "))));
}
return survivingConfig;
}
/**
* @return Whether the template is secure.
*/
boolean isSecure();
/**
* @return If the template is secure, the collection of keys that can be overriden by the user.
*/
Collection<String> overridableProperties();
}
| 1,576 |
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/api/ExecutionResult.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.api;
/**
* An object which describes the result after job completion. This can be retrieved by {@link JobExecutionMonitor#get()}
*
* @see JobExecutionResult as a derived class.
*/
public interface ExecutionResult {
}
| 1,577 |
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/api/SpecSerDe.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.api;
/**
* A Serializer / Deserializer for {@link Spec}.
*/
public interface SpecSerDe {
/***
* Serializes the {@link Spec} into byte array.
* @param spec {@link Spec} to serialize.
* @return byte array of serialized {@link Spec}.
*/
byte[] serialize(Spec spec) throws SpecSerDeException;
/***
* Deserialize byte array into a {@link Spec}.
* @param spec byte array to deserialize.
* @return deserialized {@link Spec}.
*/
Spec deserialize(byte[] spec) throws SpecSerDeException;
} | 1,578 |
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/api/JobExecutionStateListenerContainer.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.api;
import org.apache.gobblin.annotation.Alpha;
/**
* Defines an interface for managing a collection of {@JobExecutionStateListener}s
*/
@Alpha
public interface JobExecutionStateListenerContainer {
void registerStateListener(JobExecutionStateListener listener);
/** Like {@link #registerStateListener(JobExecutionStateListener)} but it will create a weak
* reference. The implementation will automatically remove the listener registration once the
* listener object gets GCed.
*
* <p>Note that weak listeners cannot be removed using {@link #unregisterStateListener(JobExecutionStateListener)}.
**/
void registerWeakStateListener(JobExecutionStateListener listener);
void unregisterStateListener(JobExecutionStateListener listener);
}
| 1,579 |
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/api/SpecNotFoundException.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.api;
import java.net.URI;
/**
* An {@link Exception} thrown when a {@link Spec} with the given {@link URI} cannot be found.
*/
public class SpecNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
private final URI _missingJobSpecURI;
public SpecNotFoundException(URI missingJobSpecURI) {
super("No JobSpec with URI " + missingJobSpecURI);
_missingJobSpecURI = missingJobSpecURI;
}
public SpecNotFoundException(URI missingJobSpecURI, Throwable cause) {
super("No JobSpec with URI " + missingJobSpecURI, cause);
_missingJobSpecURI = missingJobSpecURI;
}
public URI getMissingJobSpecURI() {
return _missingJobSpecURI;
}
}
| 1,580 |
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/api/package-info.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.
*/
/**
* The Gobblin Execution Model.
*
* <p>The Gobblin launcher components:
* <dl>
* <dt>Gobblin instance</dt>
* <dd>A self-contained context for running alike Gobblin jobs. These jobs share location where
* they are stored and managed, how they are scheduled, and how they are run.
* <dl>
* <dt>Gobblin instance driver ({@link org.apache.gobblin.runtime.api.GobblinInstanceDriver})</dt>
* <dd>Starts all global Gobblin services, instantiates Job Catalog, Job Launcher, and scheduler.
* Interprets job specs to schedule via the executor or run immediately. (Similar to original
* JobScheduler class).</dd>
* </dl>
* <dt>Gobblin instance launcher ({@link org.apache.gobblin.runtime.api.GobblinInstanceLauncher})<dt>
* <dd>Main class instantiated by the JVM or running framework. Reads application level
* configurations, instantiates and runs the Gobblin instance driver.
* Examples: JavaMainAppLauncher (original SchedulerDaemon), AzkabanAppLauncher (original
* AzkabanJobLauncher).</dd>
* </dd>
* <dt>Gobblin job</dt>
* <dd>An execution unit that can ingest and process data from a single source.
* <dl>
* <dt>JobSpec</dt>
* <dd>The static part of a job, describes the job name, group, and associated configuration.</dd>
* <dt>JobExecution</dt>
* <dd>A specific execution of the job.</dd>
* <dt>JobExecution Driver</dt>
* <dd>Executes the job and its tasks. This can be done locally in a thread-pool,
* or as a M/R job, as a Yarn job using the Helix task execution framework, etc. This
* concept replaces the previous {@link org.apache.gobblin.runtime.JobLauncher}. </dd>
* <dt>JobExecution Launcher ({@link org.apache.gobblin.runtime.api.JobExecutionLauncher})</dt>
* <dd>Instantiates the JobExecution Driver. The driver may be instantiated locally, or it
* can be launched in a remote container (similarly to Oozie). JobExecutionLauncher should not
* be confused with the legacy {@link org.apache.gobblin.runtime.JobLauncher}. Essentially, we decided to
* roughly split the JobLauncher into JobExecutionLauncher and a JobExecutionDriver. This
* allows us to abstract the aspect of instantiating and running the JobExecutionDriver. Thus,
* we have the option of running the driver locally or remotely. </dd>
* </dl>
* </dd>
* <dt>Job catalog ({@link org.apache.gobblin.runtime.api.JobCatalog})</dt>
* <dd>Maintains the collection of JobSpecs known to a specific Gobblin instance.
* <dl>
* <dt>JobSpec Monitor ({@link org.apache.gobblin.runtime.api.JobSpecMonitorFactory})</dt>
* <dd>Discovers jobs to execute and generates job specs for each one.</dd>
* </dl>
* </dd>
* <dt>Job Scheduler ({@link org.apache.gobblin.runtime.api.JobSpecScheduler})</dt>
* <dd>A pluggable scheduler implementation that triggers job executions on a schedule.
* Examples: Quartz, pass-through.
* </dd>
* </dl>
*
* <p>Overall, in the current design, Gobblin defines an execution hierarchy: a Gobblin Instance
* runs zero, one or more Gobblin Jobs which consist of zero, one or more tasks. For each of the
* levels in the hierarchy, there is a Driver which is responsible of running the children
* components and a Launcher which is responsible for instantiating and invoking the Driver.
*/
package org.apache.gobblin.runtime.api; | 1,581 |
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_executorInstance/AbstractSpecExecutor.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_executorInstance;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.AbstractIdleService;
import com.typesafe.config.Config;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.api.SpecConsumer;
import org.apache.gobblin.service.ServiceConfigKeys;
import org.apache.gobblin.util.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.runtime.api.GobblinInstanceEnvironment;
import org.apache.gobblin.runtime.api.ServiceNode;
import org.apache.gobblin.runtime.api.SpecExecutor;
import org.apache.gobblin.runtime.api.SpecProducer;
import org.apache.gobblin.util.CompletedFuture;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* An abstract implementation of SpecExecutor without specifying communication mechanism.
*
* Normally in the implementation of {@link AbstractSpecExecutor}, it is necessary to specify:
* {@link SpecProducer}
* {@link SpecConsumer}
* {@link Closer}
*/
public abstract class AbstractSpecExecutor extends AbstractIdleService implements SpecExecutor {
private static final Splitter SPLIT_BY_COMMA = Splitter.on(",").omitEmptyStrings().trimResults();
private static final Splitter SPLIT_BY_COLON = Splitter.on(":").omitEmptyStrings().trimResults();
protected final transient Logger log;
// Executor Instance identifier
protected final URI specExecutorInstanceUri;
@SuppressWarnings(justification = "No bug", value = "SE_BAD_FIELD")
protected final Config config;
protected final Map<ServiceNode, ServiceNode> capabilities;
/**
* While AbstractSpecExecutor is up, for most producer implementations (like SimpleKafkaSpecProducer),
* they implements {@link java.io.Closeable} which requires registration and close methods.
* {@link Closer} is mainly used for managing {@link SpecProducer} and {@link SpecConsumer}.
*/
protected Optional<Closer> optionalCloser;
public AbstractSpecExecutor(Config config) {
this(config, Optional.<Logger>absent());
}
public AbstractSpecExecutor(Config config, GobblinInstanceEnvironment env) {
this(config, Optional.of(env.getLog()));
}
public AbstractSpecExecutor(Config config, Optional<Logger> log) {
/**
* Since URI is regarded as the unique identifier for {@link SpecExecutor}(Used in equals method)
* it is dangerous to use default URI.
*/
if (!config.hasPath(ConfigurationKeys.SPECEXECUTOR_INSTANCE_URI_KEY)) {
if (log.isPresent()) {
log.get().warn("The SpecExecutor doesn't specify URI, using the default one.");
}
}
try {
specExecutorInstanceUri =
new URI(ConfigUtils.getString(config, ConfigurationKeys.SPECEXECUTOR_INSTANCE_URI_KEY, "NA"));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
this.config = config;
this.capabilities = Maps.newHashMap();
if (config.hasPath(ConfigurationKeys.SPECEXECUTOR_INSTANCE_CAPABILITIES_KEY)) {
String capabilitiesStr = config.getString(ConfigurationKeys.SPECEXECUTOR_INSTANCE_CAPABILITIES_KEY);
List<String> capabilities = SPLIT_BY_COMMA.splitToList(capabilitiesStr);
for (String capability : capabilities) {
List<String> currentCapability = SPLIT_BY_COLON.splitToList(capability);
Preconditions.checkArgument(currentCapability.size() == 2,
"Only one source:destination pair is supported " + "per capability, found: " + currentCapability);
this.capabilities.put(new BaseServiceNodeImpl(currentCapability.get(0)),
new BaseServiceNodeImpl(currentCapability.get(1)));
}
}
optionalCloser = Optional.absent();
}
@Override
public URI getUri() {
return specExecutorInstanceUri;
}
/**
* The definition of attributes are the technology that a {@link SpecExecutor} is using and
* the physical location that it runs on.
*
* These attributes are supposed to be static and read-only.
*/
@Override
public Config getAttrs() {
Preconditions.checkArgument(this.config.hasPath(ServiceConfigKeys.ATTRS_PATH_IN_CONFIG),
"Input configuration doesn't contains SpecExecutor Attributes path.");
return this.config.getConfig(ServiceConfigKeys.ATTRS_PATH_IN_CONFIG);
}
@Override
public Future<Config> getConfig() {
return new CompletedFuture(this.config, null);
}
@Override
public Future<? extends Map<ServiceNode, ServiceNode>> getCapabilities() {
return new CompletedFuture(this.capabilities, null);
}
/**
* Two {@link SpecExecutor}s with the same {@link #specExecutorInstanceUri}
* should be considered as the same {@link SpecExecutor}.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractSpecExecutor that = (AbstractSpecExecutor) o;
return specExecutorInstanceUri.equals(that.specExecutorInstanceUri);
}
@Override
public int hashCode() {
return specExecutorInstanceUri.hashCode();
}
/**
* @return In default implementation we just return 'Healthy'.
*/
@Override
public Future<String> getHealth() {
return new CompletedFuture("Healthy", null);
}
abstract protected void startUp() throws Exception;
abstract protected void shutDown() throws Exception;
abstract public Future<? extends SpecProducer<Spec>> getProducer();
abstract public Future<String> getDescription();
}
| 1,582 |
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_executorInstance/LocalFsSpecExecutor.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_executorInstance;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import java.util.concurrent.Future;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.api.JobSpec;
import org.apache.gobblin.runtime.api.SpecConsumer;
import org.apache.gobblin.runtime.api.SpecExecutor;
import org.apache.gobblin.runtime.api.SpecProducer;
import org.apache.gobblin.util.CompletedFuture;
import org.slf4j.Logger;
/**
* An {@link SpecExecutor} implementation that keep {@link JobSpec} as a file to be consumed up by Gobblin Standalone
* Therefore there's no necessity to install {@link SpecConsumer} in this case.
*/
public class LocalFsSpecExecutor extends AbstractSpecExecutor {
// Communication mechanism components.
// Not specifying final for further extension based on this implementation.
private SpecProducer<Spec> specProducer;
public LocalFsSpecExecutor(Config config) {
this(config, Optional.absent());
}
public LocalFsSpecExecutor(Config config, Optional<Logger> log) {
super(config, log);
specProducer = new LocalFsSpecProducer(config);
}
@Override
public Future<String> getDescription() {
return new CompletedFuture("Local File System SpecExecutor", null);
}
@Override
public Future<? extends SpecProducer<Spec>> getProducer(){
return new CompletedFuture<>(this.specProducer, null);
}
@Override
protected void startUp() throws Exception {
// Nothing to do in the abstract implementation.
}
@Override
protected void shutDown() throws Exception {
// Nothing to do in the abstract implementation.
}
} | 1,583 |
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_executorInstance/InMemorySpecExecutor.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_executorInstance;
import java.net.URI;
import java.util.Properties;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import com.google.common.base.Optional;
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.Spec;
import org.apache.gobblin.runtime.api.SpecConsumer;
import org.apache.gobblin.runtime.api.SpecExecutor;
import org.apache.gobblin.runtime.api.SpecProducer;
import org.apache.gobblin.util.CompletedFuture;
/**
* An {@link SpecExecutor} implementation that keep provisioned {@link Spec} in memory.
* Therefore there's no necessity to install {@link SpecConsumer} in this case.
*/
public class InMemorySpecExecutor extends AbstractSpecExecutor {
// Communication mechanism components.
// Not specifying final for further extension based on this implementation.
private SpecProducer<Spec> inMemorySpecProducer;
public InMemorySpecExecutor(Config config){
this(config, Optional.absent());
}
public InMemorySpecExecutor(Config config, GobblinInstanceEnvironment env){
this(config, Optional.of(env.getLog()));
}
public InMemorySpecExecutor(Config config, Optional<Logger> log) {
super(config, log);
inMemorySpecProducer = new InMemorySpecProducer(config);
}
/**
* A creator that create a SpecExecutor only specifying URI for uniqueness.
* @param uri
*/
public static SpecExecutor createDummySpecExecutor(URI uri) {
Properties properties = new Properties();
properties.setProperty(ConfigurationKeys.SPECEXECUTOR_INSTANCE_URI_KEY, uri.toString());
return new InMemorySpecExecutor(ConfigFactory.parseProperties(properties));
}
@Override
public Future<String> getDescription() {
return new CompletedFuture("InMemory SpecExecutor", null);
}
@Override
public Future<? extends SpecProducer<Spec>> getProducer(){
return new CompletedFuture<>(this.inMemorySpecProducer, null);
}
@Override
protected void startUp() throws Exception {
// Nothing to do in the abstract implementation.
}
@Override
protected void shutDown() throws Exception {
// Nothing to do in the abstract implementation.
}
} | 1,584 |
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_executorInstance/BaseServiceNodeImpl.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_executorInstance;
import java.util.Properties;
import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import lombok.Setter;
import org.apache.gobblin.runtime.api.ServiceNode;
import org.apache.gobblin.service.ServiceConfigKeys;
import org.apache.gobblin.util.ConfigUtils;
import lombok.Getter;
/**
* A base implementation for {@link ServiceNode} with default secured setting.
*/
public class BaseServiceNodeImpl implements ServiceNode {
@Getter
public String nodeName;
/**
* Contains read-only properties of an {@link ServiceNode}
*/
@Getter
public Config nodeProps;
/**
* One of mutable properties of Node.
* Initialization: Obtained from {@link ServiceConfigKeys}.
* Getter/Setter: Simply thur. {@link BaseServiceNodeImpl}.
*/
@Getter
@Setter
private boolean isNodeSecure;
/**
* For nodes missing configuration
* @param nodeName
*/
public BaseServiceNodeImpl(String nodeName) {
this(nodeName, new Properties());
}
public BaseServiceNodeImpl(String nodeName, Properties props) {
Preconditions.checkNotNull(nodeName);
this.nodeName = nodeName;
isNodeSecure = Boolean.parseBoolean
(props.getProperty(ServiceConfigKeys.NODE_SECURITY_KEY, ServiceConfigKeys.DEFAULT_NODE_SECURITY));
nodeProps = ConfigUtils.propertiesToConfig(props);
}
/**
* By default each node is acceptable to use in path-finding.
*/
@Override
public boolean isNodeEnabled() {
return true;
}
/**
* The comparison between two nodes should involve the configuration.
* Node name is the identifier for the node.
* */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BaseServiceNodeImpl that = (BaseServiceNodeImpl) o;
return nodeName.equals(that.nodeName);
}
@Override
public int hashCode() {
return nodeName.hashCode();
}
@Override
public String toString() {
return nodeName;
}
} | 1,585 |
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_executorInstance/InMemorySpecProducer.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_executorInstance;
import java.io.Serializable;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.typesafe.config.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.api.SpecProducer;
import org.apache.gobblin.util.CompletedFuture;
@Slf4j
public class InMemorySpecProducer implements SpecProducer<Spec>, Serializable {
private final Map<URI, Spec> provisionedSpecs;
private transient Config config;
private static final long serialVersionUID = 6106269076155338045L;
public InMemorySpecProducer(Config config) {
this.config = config;
this.provisionedSpecs = Maps.newHashMap();
}
@Override
public Future<?> addSpec(Spec addedSpec) {
provisionedSpecs.put(addedSpec.getUri(), addedSpec);
log.info(String.format("Added Spec: %s with Uri: %s for execution on this executor.", addedSpec, addedSpec.getUri()));
return new CompletedFuture(Boolean.TRUE, null);
}
@Override
public Future<?> updateSpec(Spec updatedSpec) {
if (!provisionedSpecs.containsKey(updatedSpec.getUri())) {
throw new RuntimeException("Spec not found: " + updatedSpec.getUri());
}
provisionedSpecs.put(updatedSpec.getUri(), updatedSpec);
log.info(String.format("Updated Spec: %s with Uri: %s for execution on this executor.", updatedSpec, updatedSpec.getUri()));
return new CompletedFuture(Boolean.TRUE, null);
}
@Override
public Future<?> deleteSpec(URI deletedSpecURI, Properties headers) {
if (!provisionedSpecs.containsKey(deletedSpecURI)) {
throw new RuntimeException("Spec not found: " + deletedSpecURI);
}
provisionedSpecs.remove(deletedSpecURI);
log.info(String.format("Deleted Spec with Uri: %s from this executor.", deletedSpecURI));
return new CompletedFuture(Boolean.TRUE, null);
}
@Override
public Future<? extends List<Spec>> listSpecs() {
return new CompletedFuture<>(Lists.newArrayList(provisionedSpecs.values()), null);
}
@Override
public String serializeAddSpecResponse(Future future) {
CompletedFuture<Boolean> completedFuture = (CompletedFuture) future;
try {
return completedFuture.get().toString();
} catch (ExecutionException e) {
log.error("Error during future serialization in {}.", getClass(), e);
return "";
}
}
@Override
public Future<?> deserializeAddSpecResponse(String serializedResponse) {
return new CompletedFuture(Boolean.valueOf(serializedResponse), null);
}
} | 1,586 |
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_executorInstance/LocalFsSpecProducer.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_executorInstance;
import com.typesafe.config.Config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.runtime.api.JobSpec;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.api.SpecExecutor;
import org.apache.gobblin.runtime.api.SpecProducer;
import org.apache.gobblin.util.CompletedFuture;
/**
* An implementation of {@link SpecProducer} that produces {@link JobSpec}s to the {@value #LOCAL_FS_PRODUCER_PATH_KEY}
*/
@Slf4j
public class LocalFsSpecProducer implements SpecProducer<Spec> {
private String specProducerPath;
public static final String LOCAL_FS_PRODUCER_PATH_KEY = "localFsSpecProducer.dir";
public LocalFsSpecProducer(Config config) {
this.specProducerPath = config.getString(LOCAL_FS_PRODUCER_PATH_KEY);
File parentDir = new File(specProducerPath);
if (!parentDir.exists()) {
if (parentDir.mkdirs()) {
log.info("Creating directory path at {}", this.specProducerPath);
} else {
throw new RuntimeException(String.format("Unable to create folder to write specs to at %s", this.specProducerPath));
}
}
}
/** Add a {@link Spec} for execution on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param addedSpec*/
@Override
public Future<?> addSpec(Spec addedSpec) {
return writeSpec(addedSpec, SpecExecutor.Verb.ADD);
}
/** Update a {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param updatedSpec*/
@Override
public Future<?> updateSpec(Spec updatedSpec) {
return writeSpec(updatedSpec, SpecExecutor.Verb.UPDATE);
}
private Future<?> writeSpec(Spec spec, SpecExecutor.Verb verb) {
if (spec instanceof JobSpec) {
// format the JobSpec to have file of <flowGroup>_<flowName>.job
String flowExecutionId = ((JobSpec) spec).getConfigAsProperties().getProperty(ConfigurationKeys.FLOW_EXECUTION_ID_KEY);
String jobFileName = getJobFileName(spec.getUri(), flowExecutionId);
try (
FileOutputStream fStream = new FileOutputStream(this.specProducerPath + File.separatorChar + jobFileName);
) {
((JobSpec) spec).getConfigAsProperties().store(fStream, null);
log.info("Writing job {} to {}", jobFileName, this.specProducerPath);
return new CompletedFuture<>(Boolean.TRUE, null);
} catch (IOException e) {
log.error("Exception encountered when adding Spec {}", spec);
return new CompletedFuture<>(Boolean.TRUE, e);
}
} else {
throw new RuntimeException("Unsupported spec type " + spec.getClass());
}
}
/** Delete a {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}.
* @param deletedSpecURI
* @param headers
*/
@Override
public Future<?> deleteSpec(URI deletedSpecURI, Properties headers) {
String prefix = String.join("_", deletedSpecURI.getPath().split("/"));
// delete all of the jobs related to the spec
File dir = new File(this.specProducerPath);
File[] foundFiles = dir.listFiles((File file, String name) -> {
// only delete the jobs in progress
return name.startsWith(prefix) && name.endsWith(".job");
});
for (int i = 0; i < foundFiles.length; i++) {
Boolean didDelete = foundFiles[i].delete();
if (!didDelete) {
return new CompletedFuture<>(Boolean.TRUE, new RuntimeException(String.format("Failed to delete file with uri %s", deletedSpecURI)));
}
}
return new CompletedFuture<>(Boolean.TRUE, null);
}
/** List all {@link Spec} being executed on {@link org.apache.gobblin.runtime.api.SpecExecutor}. */
@Override
public Future<? extends List<Spec>> listSpecs() {
throw new UnsupportedOperationException();
}
public static String getJobFileName(URI specUri, String flowExecutionId) {
String[] uriTokens = specUri.getPath().split("/");
return String.join("_", uriTokens) + "_" + flowExecutionId + ".job";
}
} | 1,587 |
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/messaging/DynamicWorkUnitProducer.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.messaging;
import java.io.IOException;
import org.apache.gobblin.runtime.messaging.data.DynamicWorkUnitMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Producer runs in each task runner for sending {@link DynamicWorkUnitMessage} over a {@link MessageBuffer}
* to be consumed by {@link DynamicWorkUnitConsumer} in the AM<br><br>
*
* A {@link DynamicWorkUnitProducer} has a tight coupling with the {@link DynamicWorkUnitConsumer}
* since both producer / consumer should be using the same {@link MessageBuffer}
* from the same {@link MessageBuffer.Factory} and using the same channel name
*/
public class DynamicWorkUnitProducer {
private static final Logger LOG = LoggerFactory.getLogger(DynamicWorkUnitConsumer.class);
private final MessageBuffer<DynamicWorkUnitMessage> messageBuffer;
public DynamicWorkUnitProducer(MessageBuffer<DynamicWorkUnitMessage> messageBuffer) {
this.messageBuffer = messageBuffer;
}
/**
* Send a {@link DynamicWorkUnitMessage} to be consumed by a {@link DynamicWorkUnitConsumer}
* @param message Message to be sent over the message buffer
*/
public boolean produce(DynamicWorkUnitMessage message) throws IOException {
LOG.debug("Sending message over message buffer, messageBuffer={}, message={}",
messageBuffer.getClass().getSimpleName(), message);
try {
messageBuffer.publish(message);
return true;
} catch (IOException e) {
LOG.debug("Failed to publish message. exception=", e);
return false;
}
}
}
| 1,588 |
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/messaging/DynamicWorkUnitConsumer.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.messaging;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import org.apache.gobblin.runtime.messaging.data.DynamicWorkUnitMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Receives {@link DynamicWorkUnitMessage} sent by {@link DynamicWorkUnitProducer}.
* The class is used as a callback for the {@link MessageBuffer}. All business logic
* is done in the {@link DynamicWorkUnitMessage.Handler}.<br><br>
*
* {@link DynamicWorkUnitConsumer#accept(List)} is the entrypoint for processing {@link DynamicWorkUnitMessage}
* received by the {@link MessageBuffer} after calling {@link MessageBuffer#subscribe(Consumer)}<br><br>
*
* Each newly published {@link DynamicWorkUnitMessage} is passed to a {@link DynamicWorkUnitMessage.Handler}
* and will call {@link DynamicWorkUnitMessage.Handler#handle(DynamicWorkUnitMessage)} to do business logic
*/
public class DynamicWorkUnitConsumer implements Consumer<List<DynamicWorkUnitMessage>> {
private static final Logger LOG = LoggerFactory.getLogger(DynamicWorkUnitConsumer.class);
private final List<DynamicWorkUnitMessage.Handler> messageHandlers;
public DynamicWorkUnitConsumer(Collection<DynamicWorkUnitMessage.Handler> handlers) {
this.messageHandlers = new ArrayList<>(handlers);
}
/**
* Entry point for processing messages sent by {@link DynamicWorkUnitProducer} via {@link MessageBuffer}. This
* calls {@link DynamicWorkUnitMessage.Handler#handle(DynamicWorkUnitMessage)} method for each handler added via
* {@link DynamicWorkUnitConsumer#DynamicWorkUnitConsumer(Collection<DynamicWorkUnitMessage.Handler>)
*/
@Override
public void accept(List<DynamicWorkUnitMessage> messages) {
for (DynamicWorkUnitMessage msg : messages) {
handleMessage(msg);
}
}
private void handleMessage(DynamicWorkUnitMessage msg) {
LOG.debug("{} handling message={}", DynamicWorkUnitConsumer.class.getSimpleName(), msg);
for (DynamicWorkUnitMessage.Handler handler : this.messageHandlers) {
handler.handle(msg);
}
}
}
| 1,589 |
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/messaging/MessageBuffer.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.messaging;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
/**
* Unidirectional buffer for sending messages from container to container.
* Example use case is for sending messages from taskrunner -> AM. If messages need to be
* sent bi-directionally, use multiple message buffers with different channel names.<br><br>
*
* {@link MessageBuffer} should only be instantiated using {@link MessageBuffer.Factory#getBuffer(String)} and not via constructor.
* A {@link MessageBuffer} will only communicate with other {@link MessageBuffer}(s) created by the same {@link MessageBuffer.Factory}
* and the same channel name.
*
* This interface provides the following guarantees:
* <ul>
* <li>No guaranteed order delivery</li>
* <li>Single reader calling subscribe method</li>
* <li>Multiple concurrent writers calling publish</li>
* <li>Messages delivered at most once</li>
* </ul>
*/
public interface MessageBuffer<T> {
/**
* Alias for the message buffer. Message buffers will only communicate with other message buffers
* using the same channel name and coming from the same {@link MessageBuffer.Factory}
*
* i.e. When 2 containers use the same factory implementation to create a {@link MessageBuffer} with the same
* {@link MessageBuffer#getChannelName()}, they should be able to send messages uni-directionally from
* publisher to subscriber.
* @return channel name
*/
String getChannelName();
/**
* Publish item to message buffer for consumption by subscribers
* @param item item to publish to subscribers
* @return Is item successfully added to buffer
* @throws IOException if unable to add message to buffer
*/
void publish(T item) throws IOException;
/**
* Add callback {@link Consumer} object that will consume all published {@link T}. It is safe to subscribe multiple
* consumer objects but only one container should be calling this method per channel. This is
* because the message buffer API supports at-most once delivery and one reader, so reads are destructive
*/
void subscribe(Consumer<List<T>> consumer);
/**
* Factory for instantiating {@link MessageBuffer} with a specific channel name. Message buffers produced by the same
* factory and using the same channel name are able to communicate with each other.
* @param <T>
*/
interface Factory<T> {
/**
* Create {@link MessageBuffer} with specific channel name. {@link MessageBuffer}(s) with the same channel name and
* from the same factory will exclusively communicate with eachother.
* @param channelName channel namespace
* @return Message Buffer
*/
MessageBuffer<T> getBuffer(String channelName);
}
}
| 1,590 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging/handler/SplitMessageHandler.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.messaging.handler;
import org.apache.gobblin.runtime.messaging.data.DynamicWorkUnitMessage;
import org.apache.gobblin.runtime.messaging.data.SplitWorkUnitMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handler that runs on the AM for processing {@link SplitWorkUnitMessage} and re-computing
* workunit to multiple smaller work units.
*/
public class SplitMessageHandler implements DynamicWorkUnitMessage.Handler {
private static final Logger LOG = LoggerFactory.getLogger(SplitMessageHandler.class);
@Override
public void handle(DynamicWorkUnitMessage message) {
if (message instanceof SplitWorkUnitMessage) {
handleSplit((SplitWorkUnitMessage) message);
}
}
private void handleSplit(SplitWorkUnitMessage message) {
//TODO: GOBBLIN-1688 Recompute workunit based on message.
LOG.info("Handling {}, message={}", SplitWorkUnitMessage.class.getSimpleName(), message);
}
}
| 1,591 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging/data/SplitWorkUnitMessage.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.messaging.data;
import java.util.List;
import lombok.Builder;
import lombok.Value;
/**
* Message for the task runner to request the AM to split a workunit into multiple workunits
* because a subset of topic partitions are lagging in the specified workunit.
*/
@Value
@Builder
public class SplitWorkUnitMessage implements DynamicWorkUnitMessage {
/**
* Workunit ID of the work unit that should be split into multiple smaller workunits
*/
String workUnitId;
/**
* Topic partitions that have been lagging in the workunit
*/
List<String> laggingTopicPartitions;
}
| 1,592 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging/data/DynamicWorkUnitSerde.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.messaging.data;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.nio.charset.Charset;
import lombok.NonNull;
/**
* Library for serializing / deserializing {@link DynamicWorkUnitMessage}. This solution maintains implementation
* specific fields not specified in the interface and is dependent on {@link Gson} to do the serialization / deserialization
*/
public final class DynamicWorkUnitSerde {
private static final Gson GSON = new Gson();
private static final String PROPS_PREFIX = "DynamicWorkUnit.Props";
private static final String MESSAGE_IMPLEMENTATION = PROPS_PREFIX + ".MessageImplementationClass";
private static final Charset DEFAULT_CHAR_ENCODING = Charsets.UTF_8;
// Suppresses default constructor, ensuring non-instantiability.
private DynamicWorkUnitSerde() { }
/**
* Serialize message into bytes. To deserialize, use {@link DynamicWorkUnitSerde#deserialize(byte[])}.
* Serialization preserves underlying properties of the {@link DynamicWorkUnitMessage} implementation.<br><br>
* For example, the {@link SplitWorkUnitMessage} implements
* {@link DynamicWorkUnitMessage} and has implementation specific properties such as
* {@link SplitWorkUnitMessage#getLaggingTopicPartitions()}. These properties will be maintained after serde.
* @param msg message to serialize
* @return message as bytes
*/
public static byte[] serialize(DynamicWorkUnitMessage msg) {
Preconditions.checkNotNull(msg, "Input message cannot be null");
return toJsonObject(msg)
.toString()
.getBytes(DEFAULT_CHAR_ENCODING);
}
/**
* Deserialize bytes into message object. Input message byte array should have been serialized using
* {@link DynamicWorkUnitSerde#serialize(DynamicWorkUnitMessage)}.
* @param serializedMessage message that has been serialized by {@link DynamicWorkUnitSerde#serialize(DynamicWorkUnitMessage)}
* @return DynamicWorkUnitMessage object
*/
public static DynamicWorkUnitMessage deserialize(byte[] serializedMessage) {
String json = new String(serializedMessage, DEFAULT_CHAR_ENCODING);
JsonObject jsonObject = GSON.fromJson(json, JsonObject.class);
return toDynamicWorkUnitMessage(jsonObject);
}
/**
* Helper method for deserializing {@link JsonObject} to {@link DynamicWorkUnitMessage}
* @param json Message serialized using {@link DynamicWorkUnitSerde#toJsonObject}
* @return {@link DynamicWorkUnitMessage} POJO representation of the given json
*/
private static <T extends DynamicWorkUnitMessage> DynamicWorkUnitMessage toDynamicWorkUnitMessage(JsonObject json) {
Preconditions.checkNotNull(json, "Serialized msg cannot be null");
try {
if (!json.has(MESSAGE_IMPLEMENTATION)) {
throw new DynamicWorkUnitDeserializationException(
String.format("Unable to deserialize json to %s. Ensure that %s "
+ "is used for serialization. %s does not have the key=%s used for deserializing to correct message "
+ "implementation. json=%s",
DynamicWorkUnitMessage.class.getSimpleName(),
"DynamicWorkSerde#serialize(DynamicWorkUnitMessage msg)",
json.getClass().getSimpleName(),
MESSAGE_IMPLEMENTATION,
json));
}
Class<T> clazz = (Class<T>) Class.forName(json.get(MESSAGE_IMPLEMENTATION).getAsString());
return GSON.fromJson(json, clazz);
} catch (ClassNotFoundException e) {
throw new DynamicWorkUnitDeserializationException(
String.format("Input param %s contains invalid value for key=%s. This can be caused by the deserializer having"
+ " different dependencies from the serializer. json=%s",
json.getClass(),
MESSAGE_IMPLEMENTATION,
json), e);
}
}
/**
* Helper method for serializing {@link DynamicWorkUnitMessage} to {@link JsonObject}
* @param msg Message to serialize
* @return json representation of message
*/
private static JsonObject toJsonObject(@NonNull DynamicWorkUnitMessage msg) {
Preconditions.checkNotNull(msg, "Input message cannot be null");
JsonElement json = GSON.toJsonTree(msg);
JsonObject obj = json.getAsJsonObject();
obj.addProperty(MESSAGE_IMPLEMENTATION, msg.getClass().getName());
return obj;
}
}
| 1,593 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging/data/DynamicWorkUnitMessage.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.messaging.data;
import gobblin.source.workunit.WorkUnit;
/**
* Generic message for sending updates about a workunit during runtime. Implementations can
* extend this interface with other getters / properties to piggyback information specific to the message subtype.
*
* For example, the {@link SplitWorkUnitMessage} extends this interface by adding fields that are not specified in this
* interface.
*/
public interface DynamicWorkUnitMessage {
/**
* The WorkUnit Id this message is associated with. Same as {@link WorkUnit#getId()}
* @return WorkUnit Id
*/
String getWorkUnitId();
/**
* Handler for processing messages and implementing business logic
*/
interface Handler {
/**
* Process this message by handling business logic
* @param message
*/
void handle(DynamicWorkUnitMessage message);
}
}
| 1,594 |
0 | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging | Create_ds/gobblin/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/messaging/data/DynamicWorkUnitDeserializationException.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.messaging.data;
/**
* An exception when {@link DynamicWorkUnitMessage} cannot be correctly deserialized from underlying message storage
*/
public class DynamicWorkUnitDeserializationException extends RuntimeException {
public DynamicWorkUnitDeserializationException(String message) {
super(message);
}
public DynamicWorkUnitDeserializationException(String message, Throwable e) {
super(message, e);
}
}
| 1,595 |
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/mapreduce/MRTaskStateTracker.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.mapreduce;
import java.util.Map;
import java.util.concurrent.RejectedExecutionException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.runtime.AbstractTaskStateTracker;
import org.apache.gobblin.runtime.Task;
import org.apache.gobblin.runtime.util.JobMetrics;
import org.apache.gobblin.runtime.util.MetricGroup;
import org.apache.gobblin.source.workunit.WorkUnit;
/**
* A concrete extension to {@link org.apache.gobblin.runtime.AbstractTaskStateTracker} for Hadoop MapReduce based runtime.
*
* @author Yinan Li
*/
public class MRTaskStateTracker extends AbstractTaskStateTracker {
private static final Logger LOG = LoggerFactory.getLogger(MRTaskStateTracker.class);
// Mapper context used to signal progress and update counters
private final Mapper<LongWritable, Text, NullWritable, NullWritable>.Context context;
public MRTaskStateTracker(Mapper<LongWritable, Text, NullWritable, NullWritable>.Context context) {
super(context.getConfiguration(), LOG);
this.context = context;
}
@Override
public void registerNewTask(Task task) {
try {
if (GobblinMetrics.isEnabled(task.getTaskState().getWorkunit())) {
scheduleTaskMetricsUpdater(new MRTaskMetricsUpdater(task, this.context), 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) {
task.markTaskCompletion();
}
@Override
public void onTaskCommitCompletion(Task task) {
WorkUnit workUnit = task.getTaskState().getWorkunit();
if (GobblinMetrics.isEnabled(workUnit)) {
task.updateRecordMetrics();
task.updateByteMetrics();
if (workUnit.getPropAsBoolean(ConfigurationKeys.MR_REPORT_METRICS_AS_COUNTERS_KEY,
ConfigurationKeys.DEFAULT_MR_REPORT_METRICS_AS_COUNTERS)) {
updateCounters(task);
}
}
LOG.info(String
.format("Task %s completed running in %dms with state %s", task.getTaskId(), task.getTaskState().getTaskDuration(),
task.getTaskState().getWorkingState()));
}
/**
* An extension to {@link AbstractTaskStateTracker.TaskMetricsUpdater} for updating task metrics
* in the Hadoop MapReduce setting.
*/
private class MRTaskMetricsUpdater extends AbstractTaskStateTracker.TaskMetricsUpdater {
private final Mapper<LongWritable, Text, NullWritable, NullWritable>.Context context;
MRTaskMetricsUpdater(Task task, Mapper<LongWritable, Text, NullWritable, NullWritable>.Context context) {
super(task);
this.context = context;
}
@Override
protected void updateTaskMetrics() {
super.updateTaskMetrics();
WorkUnit workUnit = this.task.getTaskState().getWorkunit();
if (GobblinMetrics.isEnabled(workUnit)) {
if (workUnit.getPropAsBoolean(ConfigurationKeys.MR_REPORT_METRICS_AS_COUNTERS_KEY,
ConfigurationKeys.DEFAULT_MR_REPORT_METRICS_AS_COUNTERS)) {
updateCounters(this.task);
}
}
// Tell the TaskTracker it's making progress
this.context.progress();
}
}
private void updateCounters(Task task) {
updateCounters(task, MetricGroupFilter.JOB);
updateCounters(task, MetricGroupFilter.TASK);
}
private void updateCounters(Task task, MetricGroupFilter filter) {
Map<String, Counter> counters = JobMetrics.get(null, task.getJobId()).getMetricContext().getCounters(filter);
if (counters != null) {
for (Map.Entry<String, Counter> entry : counters.entrySet()) {
this.context.getCounter(filter.getGroupName(), entry.getKey()).setValue(entry.getValue().getCount());
}
}
}
private enum MetricGroupFilter implements MetricFilter {
JOB() {
@Override
public String getGroupName() {
return MetricGroup.JOB.toString();
}
},
TASK() {
@Override
public String getGroupName() {
return MetricGroup.TASK.toString();
}
};
@Override
public boolean matches(String name, Metric metric) {
return name.startsWith(this.toString()) ? true : false;
}
public abstract String getGroupName();
}
}
| 1,596 |
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/mapreduce/MRTaskFactory.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.mapreduce;
import org.apache.gobblin.publisher.DataPublisher;
import org.apache.gobblin.publisher.NoopPublisher;
import org.apache.gobblin.runtime.JobState;
import org.apache.gobblin.runtime.TaskContext;
import org.apache.gobblin.runtime.task.TaskFactory;
import org.apache.gobblin.runtime.task.TaskIFace;
/**
* A {@link TaskFactory} that runs an {@link MRTask}. This factory is intended to publish data in the task directly, and
* uses a {@link NoopPublisher}.
*/
public class MRTaskFactory implements TaskFactory {
@Override
public TaskIFace createTask(TaskContext taskContext) {
return new MRTask(taskContext);
}
@Override
public DataPublisher createDataPublisher(JobState.DatasetState datasetState) {
return new NoopPublisher(datasetState);
}
}
| 1,597 |
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/mapreduce/CustomizedProgresserBase.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.mapreduce;
import org.apache.hadoop.mapreduce.Mapper;
/**
* A customized progresser that reports static value, dummy implementation of {@link CustomizedProgresser}
* while still useful to prevent direct reporting of 1.0f to MR framework.
*
* Customized application implementation should extends this class instead of implementing {@link CustomizedProgresser}
* directly as the interface could be changed if we are attempting to add Reducer's progress as well.
*/
public class CustomizedProgresserBase implements CustomizedProgresser {
private static final String STATIC_PROGRESS = "customizedProgress.staticProgressValue";
private static final float DEFAULT_STATIC_PROGRESS = 0.5f;
private float staticProgress;
public static class BaseFactory implements CustomizedProgresser.Factory {
@Override
public CustomizedProgresser createCustomizedProgresser(Mapper.Context mapperContext) {
return new CustomizedProgresserBase(mapperContext);
}
}
public CustomizedProgresserBase(Mapper.Context mapperContext) {
this.staticProgress = mapperContext.getConfiguration().getFloat(STATIC_PROGRESS, DEFAULT_STATIC_PROGRESS);
}
@Override
public float getCustomizedProgress() {
return staticProgress;
}
}
| 1,598 |
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/mapreduce/GobblinOutputFormat.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.mapreduce;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
/**
* Hadoop {@link org.apache.hadoop.mapreduce.OutputFormat} implementation with a custom {@link OutputCommitter}
*/
public class GobblinOutputFormat extends NullOutputFormat<NullWritable, NullWritable> {
@Override
public OutputCommitter getOutputCommitter(TaskAttemptContext context) {
return new GobblinOutputCommitter();
}
}
| 1,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.