Search in sources :

Example 16 with JobConfig

use of com.hazelcast.jet.config.JobConfig in project hazelcast by hazelcast.

the class MySqlCdcIntegrationTest method restart.

@Test
@Category(NightlyTest.class)
public void restart() throws Exception {
    // given
    List<String> expectedRecords = Arrays.asList("1004/1:UPDATE:Customer {id=1004, firstName=Anne Marie, lastName=Kretchmar, email=annek@noanswer.org}", "1005/0:INSERT:Customer {id=1005, firstName=Jason, lastName=Bourne, email=jason@bourne.org}", "1005/1:DELETE:Customer {id=1005, firstName=Jason, lastName=Bourne, email=jason@bourne.org}");
    Pipeline pipeline = Pipeline.create();
    pipeline.readFrom(source("customers")).withNativeTimestamps(0).<ChangeRecord>customTransform("filter_timestamps", filterTimestampsProcessorSupplier()).groupingKey(record -> (Integer) record.key().toMap().get("id")).mapStateful(LongAccumulator::new, (accumulator, customerId, record) -> {
        long count = accumulator.get();
        accumulator.add(1);
        Operation operation = record.operation();
        RecordPart value = record.value();
        Customer customer = value.toObject(Customer.class);
        return entry(customerId + "/" + count, operation + ":" + customer);
    }).setLocalParallelism(1).writeTo(Sinks.map("results"));
    // when
    HazelcastInstance hz = createHazelcastInstances(2)[0];
    JobConfig jobConfig = new JobConfig().setProcessingGuarantee(ProcessingGuarantee.AT_LEAST_ONCE);
    Job job = hz.getJet().newJob(pipeline, jobConfig);
    JetTestSupport.assertJobStatusEventually(job, JobStatus.RUNNING);
    assertEqualsEventually(() -> hz.getMap("results").size(), 4);
    // then
    hz.getMap("results").destroy();
    // when
    assertEqualsEventually(() -> hz.getMap("results").size(), 0);
    // then
    job.restart();
    // when
    JetTestSupport.assertJobStatusEventually(job, JobStatus.RUNNING);
    // then update a record
    try (Connection connection = getConnection(mysql, "inventory")) {
        Statement statement = connection.createStatement();
        statement.addBatch("UPDATE customers SET first_name='Anne Marie' WHERE id=1004");
        statement.addBatch("INSERT INTO customers VALUES (1005, 'Jason', 'Bourne', 'jason@bourne.org')");
        statement.addBatch("DELETE FROM customers WHERE id=1005");
        statement.executeBatch();
    }
    // then
    try {
        assertEqualsEventually(() -> mapResultsToSortedList(hz.getMap("results")), expectedRecords);
    } finally {
        job.cancel();
        assertJobStatusEventually(job, JobStatus.FAILED);
    }
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Arrays(java.util.Arrays) Connection(java.sql.Connection) QuickTest(com.hazelcast.test.annotation.QuickTest) Date(java.util.Date) StreamSource(com.hazelcast.jet.pipeline.StreamSource) CdcSinks(com.hazelcast.jet.cdc.CdcSinks) ParsingException(com.hazelcast.jet.cdc.ParsingException) Operation(com.hazelcast.jet.cdc.Operation) Util.entry(com.hazelcast.jet.Util.entry) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ChangeRecord(com.hazelcast.jet.cdc.ChangeRecord) JobStatus(com.hazelcast.jet.core.JobStatus) Nonnull(javax.annotation.Nonnull) Job(com.hazelcast.jet.Job) HazelcastInstance(com.hazelcast.core.HazelcastInstance) NightlyTest(com.hazelcast.test.annotation.NightlyTest) Pipeline(com.hazelcast.jet.pipeline.Pipeline) JetTestSupport(com.hazelcast.jet.core.JetTestSupport) JobConfig(com.hazelcast.jet.config.JobConfig) Sinks(com.hazelcast.jet.pipeline.Sinks) RecordPart(com.hazelcast.jet.cdc.RecordPart) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) LongAccumulator(com.hazelcast.jet.accumulator.LongAccumulator) Statement(java.sql.Statement) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) Statement(java.sql.Statement) Connection(java.sql.Connection) Operation(com.hazelcast.jet.cdc.Operation) JobConfig(com.hazelcast.jet.config.JobConfig) Pipeline(com.hazelcast.jet.pipeline.Pipeline) LongAccumulator(com.hazelcast.jet.accumulator.LongAccumulator) HazelcastInstance(com.hazelcast.core.HazelcastInstance) RecordPart(com.hazelcast.jet.cdc.RecordPart) Job(com.hazelcast.jet.Job) ChangeRecord(com.hazelcast.jet.cdc.ChangeRecord) Category(org.junit.experimental.categories.Category) QuickTest(com.hazelcast.test.annotation.QuickTest) NightlyTest(com.hazelcast.test.annotation.NightlyTest) Test(org.junit.Test)

Example 17 with JobConfig

use of com.hazelcast.jet.config.JobConfig in project hazelcast by hazelcast.

the class JobClassLoaderService method createProcessorClassLoaders.

private Map<String, ClassLoader> createProcessorClassLoaders(long jobId, JobConfig jobConfig, ClassLoader parent) {
    logger.fine("Create processor classloader map for job " + idToString(jobId));
    String customLibDir = nodeEngine.getProperties().getString(ClusterProperty.PROCESSOR_CUSTOM_LIB_DIR);
    Map<String, ClassLoader> classLoaderMap = new HashMap<>();
    for (Entry<String, List<String>> entry : jobConfig.getCustomClassPaths().entrySet()) {
        List<URL> list = entry.getValue().stream().map(jar -> {
            try {
                Path path = Paths.get(customLibDir, jar);
                return path.toUri().toURL();
            } catch (MalformedURLException e) {
                throw new JetException(e);
            }
        }).collect(Collectors.toList());
        URL[] urls = list.toArray(new URL[] {});
        classLoaderMap.put(entry.getKey(), new ChildFirstClassLoader(urls, parent));
    }
    return unmodifiableMap(classLoaderMap);
}
Also used : URL(java.net.URL) LoggingUtil.logFinest(com.hazelcast.jet.impl.util.LoggingUtil.logFinest) HashMap(java.util.HashMap) JetDelegatingClassLoader(com.hazelcast.jet.impl.deployment.JetDelegatingClassLoader) JetException(com.hazelcast.jet.JetException) ILogger(com.hazelcast.logging.ILogger) Map(java.util.Map) ChildFirstClassLoader(com.hazelcast.jet.impl.deployment.ChildFirstClassLoader) Nonnull(javax.annotation.Nonnull) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) JetConfig(com.hazelcast.jet.config.JetConfig) HazelcastException(com.hazelcast.core.HazelcastException) NodeEngine(com.hazelcast.spi.impl.NodeEngine) MalformedURLException(java.net.MalformedURLException) JobConfig(com.hazelcast.jet.config.JobConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) ClusterProperty(com.hazelcast.spi.properties.ClusterProperty) List(java.util.List) Util.idToString(com.hazelcast.jet.Util.idToString) Paths(java.nio.file.Paths) LoggingUtil.logFine(com.hazelcast.jet.impl.util.LoggingUtil.logFine) Entry(java.util.Map.Entry) JetClassLoader(com.hazelcast.jet.impl.deployment.JetClassLoader) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) AccessController(java.security.AccessController) Collections(java.util.Collections) Util(com.hazelcast.jet.Util) Path(java.nio.file.Path) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Util.idToString(com.hazelcast.jet.Util.idToString) JetException(com.hazelcast.jet.JetException) URL(java.net.URL) ChildFirstClassLoader(com.hazelcast.jet.impl.deployment.ChildFirstClassLoader) JetDelegatingClassLoader(com.hazelcast.jet.impl.deployment.JetDelegatingClassLoader) ChildFirstClassLoader(com.hazelcast.jet.impl.deployment.ChildFirstClassLoader) JetClassLoader(com.hazelcast.jet.impl.deployment.JetClassLoader) List(java.util.List)

Example 18 with JobConfig

use of com.hazelcast.jet.config.JobConfig in project hazelcast by hazelcast.

the class JobRepository method completeJob.

/**
 * Puts a JobResult for the given job and deletes the JobRecord.
 *
 * @throws JobNotFoundException  if the JobRecord is not found
 * @throws IllegalStateException if the JobResult is already present
 */
void completeJob(@Nonnull MasterContext masterContext, @Nullable List<RawJobMetrics> terminalMetrics, @Nullable Throwable error, long completionTime) {
    long jobId = masterContext.jobId();
    JobConfig config = masterContext.jobRecord().getConfig();
    long creationTime = masterContext.jobRecord().getCreationTime();
    JobResult jobResult = new JobResult(jobId, config, creationTime, completionTime, toErrorMsg(error));
    if (terminalMetrics != null) {
        try {
            List<RawJobMetrics> prevMetrics = jobMetrics.get().put(jobId, terminalMetrics);
            if (prevMetrics != null) {
                logger.warning("Overwriting job metrics for job " + jobResult);
            }
        } catch (Exception e) {
            logger.warning("Storing the job metrics failed, ignoring: " + e, e);
        }
    }
    for (; ; ) {
        // keep trying to store the JobResult until it succeeds
        try {
            jobResults.get().set(jobId, jobResult);
            break;
        } catch (Exception e) {
            // if the local instance was shut down, re-throw the error
            LifecycleService lifecycleService = instance.getLifecycleService();
            if (e instanceof HazelcastInstanceNotActiveException && (!lifecycleService.isRunning())) {
                throw e;
            }
            // retry otherwise, after a delay
            long retryTimeoutSeconds = 1;
            logger.warning("Failed to store JobResult, will retry in " + retryTimeoutSeconds + " seconds: " + e, e);
            LockSupport.parkNanos(SECONDS.toNanos(retryTimeoutSeconds));
        }
    }
    deleteJob(jobId);
}
Also used : HazelcastInstanceNotActiveException(com.hazelcast.core.HazelcastInstanceNotActiveException) LifecycleService(com.hazelcast.core.LifecycleService) RawJobMetrics(com.hazelcast.jet.impl.metrics.RawJobMetrics) JobConfig(com.hazelcast.jet.config.JobConfig) HazelcastInstanceNotActiveException(com.hazelcast.core.HazelcastInstanceNotActiveException) URISyntaxException(java.net.URISyntaxException) FileNotFoundException(java.io.FileNotFoundException) JetException(com.hazelcast.jet.JetException) JobNotFoundException(com.hazelcast.jet.core.JobNotFoundException) IOException(java.io.IOException)

Example 19 with JobConfig

use of com.hazelcast.jet.config.JobConfig in project hazelcast by hazelcast.

the class Util method copyMapUsingJob.

// used in jet-enterprise
@SuppressWarnings("WeakerAccess")
public static CompletableFuture<Void> copyMapUsingJob(HazelcastInstance instance, int queueSize, String sourceMap, String targetMap) {
    DAG dag = new DAG();
    Vertex source = dag.newVertex("readMap(" + sourceMap + ')', readMapP(sourceMap));
    Vertex sink = dag.newVertex("writeMap(" + targetMap + ')', writeMapP(targetMap));
    dag.edge(between(source, sink).setConfig(new EdgeConfig().setQueueSize(queueSize)));
    JobConfig jobConfig = new JobConfig().setName("copy-" + sourceMap + "-to-" + targetMap);
    return instance.getJet().newJob(dag, jobConfig).getFuture();
}
Also used : Vertex(com.hazelcast.jet.core.Vertex) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) DAG(com.hazelcast.jet.core.DAG) JobConfig(com.hazelcast.jet.config.JobConfig)

Example 20 with JobConfig

use of com.hazelcast.jet.config.JobConfig in project hazelcast by hazelcast.

the class MapIndexScanPTest method test_whenFilterAndSpecificProjectionExists_sorted.

@Test
public void test_whenFilterAndSpecificProjectionExists_sorted() {
    List<JetSqlRow> expected = new ArrayList<>();
    for (int i = count; i > 0; i--) {
        map.put(i, new Person("value-" + i, i));
        if (i > count / 2) {
            expected.add(jetRow((count - i + 1), "value-" + (count - i + 1), (count - i + 1)));
        }
    }
    IndexConfig indexConfig = new IndexConfig(IndexType.SORTED, "age").setName(randomName());
    map.addIndex(indexConfig);
    IndexFilter filter = new IndexRangeFilter(intValue(0), true, intValue(count / 2), true);
    MapIndexScanMetadata metadata = metadata(indexConfig.getName(), filter, 0, false);
    TestSupport.verifyProcessor(adaptSupplier(MapIndexScanP.readMapIndexSupplier(metadata))).hazelcastInstance(instance()).jobConfig(new JobConfig().setArgument(SQL_ARGUMENTS_KEY_NAME, emptyList())).outputChecker(LENIENT_SAME_ITEMS_IN_ORDER).disableSnapshots().disableProgressAssertion().expectOutput(expected);
}
Also used : IndexRangeFilter(com.hazelcast.sql.impl.exec.scan.index.IndexRangeFilter) IndexConfig(com.hazelcast.config.IndexConfig) ArrayList(java.util.ArrayList) MapIndexScanMetadata(com.hazelcast.sql.impl.exec.scan.MapIndexScanMetadata) JetSqlRow(com.hazelcast.sql.impl.row.JetSqlRow) IndexFilter(com.hazelcast.sql.impl.exec.scan.index.IndexFilter) JobConfig(com.hazelcast.jet.config.JobConfig) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Aggregations

JobConfig (com.hazelcast.jet.config.JobConfig)254 Test (org.junit.Test)196 Job (com.hazelcast.jet.Job)160 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)111 QuickTest (com.hazelcast.test.annotation.QuickTest)109 Pipeline (com.hazelcast.jet.pipeline.Pipeline)70 HazelcastInstance (com.hazelcast.core.HazelcastInstance)64 MockPS (com.hazelcast.jet.core.TestProcessors.MockPS)46 Category (org.junit.experimental.categories.Category)45 Assert.assertEquals (org.junit.Assert.assertEquals)43 DAG (com.hazelcast.jet.core.DAG)41 JobRepository (com.hazelcast.jet.impl.JobRepository)40 List (java.util.List)36 NoOutputSourceP (com.hazelcast.jet.core.TestProcessors.NoOutputSourceP)35 Config (com.hazelcast.config.Config)33 Assert.assertTrue (org.junit.Assert.assertTrue)32 ArrayList (java.util.ArrayList)31 Sinks (com.hazelcast.jet.pipeline.Sinks)28 RUNNING (com.hazelcast.jet.core.JobStatus.RUNNING)27 RunWith (org.junit.runner.RunWith)27