Search in sources :

Example 36 with Notification

use of io.cdap.cdap.proto.Notification in project cdap by caskdata.

the class RuntimeServiceMainTest method createProgramStateWriter.

/**
 * Creates a {@link ProgramStateWriter} that writes to {@link RuntimeClient} directly.
 *
 * @param injector the injector for creating the {@link RuntimeClient}
 * @param programRunId the {@link ProgramRunId} for the program state change
 * @return a {@link ProgramStateWriter}
 */
private ProgramStateWriter createProgramStateWriter(Injector injector, ProgramRunId programRunId) {
    RuntimeClient runtimeClient = injector.getInstance(RuntimeClient.class);
    // We write to the record event directly to skip the app-fabric to process it
    // This is because we don't follow the normal event flow here for testing
    TopicId topicId = NamespaceId.SYSTEM.topic(injector.getInstance(CConfiguration.class).get(Constants.AppFabric.PROGRAM_STATUS_RECORD_EVENT_TOPIC));
    RetryStrategy retryStrategy = RetryStrategies.timeLimit(5, TimeUnit.SECONDS, RetryStrategies.fixDelay(200, TimeUnit.MILLISECONDS));
    return new MessagingProgramStateWriter((notificationType, properties) -> {
        Notification notification = new Notification(notificationType, properties);
        try {
            Retries.callWithRetries((Retries.Callable<Void, Exception>) () -> {
                runtimeClient.sendMessages(programRunId, topicId, Collections.singleton(createMessage(notification)).iterator());
                return null;
            }, retryStrategy, t -> t instanceof IOException || t instanceof RetryableException);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : RuntimeClient(io.cdap.cdap.internal.app.runtime.monitor.RuntimeClient) RetryableException(io.cdap.cdap.api.retry.RetryableException) Retries(io.cdap.cdap.common.service.Retries) TopicId(io.cdap.cdap.proto.id.TopicId) IOException(java.io.IOException) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) RetryStrategy(io.cdap.cdap.common.service.RetryStrategy) Notification(io.cdap.cdap.proto.Notification) RetryableException(io.cdap.cdap.api.retry.RetryableException) IOException(java.io.IOException)

Example 37 with Notification

use of io.cdap.cdap.proto.Notification in project cdap by caskdata.

the class CoreSchedulerServiceTest method testScheduleUpdate.

private void testScheduleUpdate(String howToUpdate) throws Exception {
    int runs = getRuns(WORKFLOW_2, ProgramRunStatus.ALL);
    final ScheduleId scheduleId2 = APP_ID.schedule(AppWithFrequentScheduledWorkflows.DATASET_PARTITION_SCHEDULE_2);
    // send one notification to it
    long minPublishTime = System.currentTimeMillis();
    publishNotification(dataEventTopic, NamespaceId.DEFAULT, AppWithFrequentScheduledWorkflows.DATASET_NAME2);
    waitUntilProcessed(dataEventTopic, minPublishTime);
    // A pending job will be created, but it won't run
    Assert.assertTrue("Expected a PENDING_TRIGGER job for " + scheduleId2, Iterables.any(getAllJobs(), job -> {
        if (!(job.getSchedule().getTrigger() instanceof ProtoTrigger.PartitionTrigger)) {
            return false;
        }
        return scheduleId2.equals(job.getJobKey().getScheduleId()) && job.getState() == Job.State.PENDING_TRIGGER;
    }));
    Assert.assertEquals(runs, getRuns(WORKFLOW_2, ProgramRunStatus.ALL));
    if ("disable".equals(howToUpdate)) {
        // disabling and enabling the schedule should remove the job
        disableSchedule(AppWithFrequentScheduledWorkflows.DATASET_PARTITION_SCHEDULE_2);
        enableSchedule(AppWithFrequentScheduledWorkflows.DATASET_PARTITION_SCHEDULE_2);
    } else {
        ProgramSchedule schedule = scheduler.getSchedule(scheduleId2);
        Map<String, String> updatedProperties = ImmutableMap.<String, String>builder().putAll(schedule.getProperties()).put(howToUpdate, howToUpdate).build();
        ProgramSchedule updatedSchedule = new ProgramSchedule(schedule.getName(), schedule.getDescription(), schedule.getProgramId(), updatedProperties, schedule.getTrigger(), schedule.getConstraints());
        if ("update".equals(howToUpdate)) {
            scheduler.updateSchedule(updatedSchedule);
            Assert.assertEquals(ProgramScheduleStatus.SCHEDULED, scheduler.getScheduleStatus(scheduleId2));
        } else if ("delete".equals(howToUpdate)) {
            scheduler.deleteSchedule(scheduleId2);
            scheduler.addSchedule(updatedSchedule);
            enableSchedule(scheduleId2.getSchedule());
        } else {
            Assert.fail("invalid howToUpdate: " + howToUpdate);
        }
    }
    // single notification should not trigger workflow 2 yet (if it does, then the job was not removed)
    minPublishTime = System.currentTimeMillis();
    publishNotification(dataEventTopic, NamespaceId.DEFAULT, AppWithFrequentScheduledWorkflows.DATASET_NAME2);
    waitUntilProcessed(dataEventTopic, minPublishTime);
    // Again, a pending job will be created, but it won't run since updating the schedule would remove pending trigger
    Assert.assertTrue("Expected a PENDING_TRIGGER job for " + scheduleId2, Iterables.any(getAllJobs(), job -> {
        if (!(job.getSchedule().getTrigger() instanceof ProtoTrigger.PartitionTrigger)) {
            return false;
        }
        return scheduleId2.equals(job.getJobKey().getScheduleId()) && job.getState() == Job.State.PENDING_TRIGGER;
    }));
    Assert.assertEquals(runs, getRuns(WORKFLOW_2, ProgramRunStatus.ALL));
    // publish one more notification, this should kick off the workflow
    publishNotification(dataEventTopic, NamespaceId.DEFAULT, AppWithFrequentScheduledWorkflows.DATASET_NAME2);
    waitForCompleteRuns(runs + 1, WORKFLOW_2);
}
Also used : RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) WorkflowTokenDetailCodec(io.cdap.cdap.proto.codec.WorkflowTokenDetailCodec) TypeToken(com.google.gson.reflect.TypeToken) StoreRequestBuilder(io.cdap.cdap.messaging.client.StoreRequestBuilder) TransactionRunners(io.cdap.cdap.spi.data.transaction.TransactionRunners) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Notification(io.cdap.cdap.proto.Notification) HttpResponse(io.cdap.common.http.HttpResponse) XSlowTests(io.cdap.cdap.test.XSlowTests) Bytes(io.cdap.cdap.api.common.Bytes) AlreadyExistsException(io.cdap.cdap.common.AlreadyExistsException) GsonBuilder(com.google.gson.GsonBuilder) ProgramScheduleStatus(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) AppWithFrequentScheduledWorkflows(io.cdap.cdap.AppWithFrequentScheduledWorkflows) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) DatasetId(io.cdap.cdap.proto.id.DatasetId) ScheduleId(io.cdap.cdap.proto.id.ScheduleId) Gson(com.google.gson.Gson) ArtifactSummary(io.cdap.cdap.api.artifact.ArtifactSummary) WorkflowTokenDetail(io.cdap.cdap.proto.WorkflowTokenDetail) Map(java.util.Map) AppWithMultipleSchedules(io.cdap.cdap.AppWithMultipleSchedules) ClassRule(org.junit.ClassRule) Tasks(io.cdap.cdap.common.utils.Tasks) AfterClass(org.junit.AfterClass) ImmutableMap(com.google.common.collect.ImmutableMap) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) MessagingService(io.cdap.cdap.messaging.MessagingService) PartitionKey(io.cdap.cdap.api.dataset.lib.PartitionKey) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) Category(org.junit.experimental.categories.Category) Id(io.cdap.cdap.common.id.Id) MessageId(io.cdap.cdap.messaging.data.MessageId) List(java.util.List) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) Constants(io.cdap.cdap.common.conf.Constants) ProfileId(io.cdap.cdap.proto.id.ProfileId) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) TimeTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.TimeTrigger) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) NotFoundException(io.cdap.cdap.common.NotFoundException) RunRecord(io.cdap.cdap.proto.RunRecord) TriggerInfo(io.cdap.cdap.api.schedule.TriggerInfo) ProfileConflictException(io.cdap.cdap.common.ProfileConflictException) Iterables(com.google.common.collect.Iterables) WorkflowId(io.cdap.cdap.proto.id.WorkflowId) BeforeClass(org.junit.BeforeClass) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) AppFabricTestBase(io.cdap.cdap.internal.app.services.http.AppFabricTestBase) JobQueueTable(io.cdap.cdap.internal.app.runtime.schedule.queue.JobQueueTable) TopicId(io.cdap.cdap.proto.id.TopicId) ProgramType(io.cdap.cdap.proto.ProgramType) WorkflowToken(io.cdap.cdap.api.workflow.WorkflowToken) PartitionTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.PartitionTrigger) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) TriggeringScheduleInfoAdapter(io.cdap.cdap.internal.app.runtime.schedule.TriggeringScheduleInfoAdapter) Profile(io.cdap.cdap.proto.profile.Profile) SystemArguments(io.cdap.cdap.internal.app.runtime.SystemArguments) TriggeringScheduleInfo(io.cdap.cdap.api.schedule.TriggeringScheduleInfo) Nullable(javax.annotation.Nullable) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) RunIds(io.cdap.cdap.common.app.RunIds) ProgramId(io.cdap.cdap.proto.id.ProgramId) Config(io.cdap.cdap.api.Config) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) Test(org.junit.Test) ConflictException(io.cdap.cdap.common.ConflictException) ProjectInfo(io.cdap.cdap.common.utils.ProjectInfo) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Service(com.google.common.util.concurrent.Service) ProgramSchedule(io.cdap.cdap.internal.app.runtime.schedule.ProgramSchedule) Store(io.cdap.cdap.app.store.Store) Job(io.cdap.cdap.internal.app.runtime.schedule.queue.Job) TimeUnit(java.util.concurrent.TimeUnit) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) AppRequest(io.cdap.cdap.proto.artifact.AppRequest) Assert(org.junit.Assert) Collections(java.util.Collections) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) TemporaryFolder(org.junit.rules.TemporaryFolder) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) ProgramSchedule(io.cdap.cdap.internal.app.runtime.schedule.ProgramSchedule) ScheduleId(io.cdap.cdap.proto.id.ScheduleId) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint)

Example 38 with Notification

use of io.cdap.cdap.proto.Notification in project cdap by caskdata.

the class CoreSchedulerServiceTest method publishNotification.

private void publishNotification(TopicId topicId, NamespaceId namespaceId, String dataset) throws Exception {
    DatasetId datasetId = namespaceId.dataset(dataset);
    PartitionKey partitionKey = PartitionKey.builder().addIntField("part1", 1).build();
    Notification notification = Notification.forPartitions(datasetId, ImmutableList.of(partitionKey));
    messagingService.publish(StoreRequestBuilder.of(topicId).addPayload(GSON.toJson(notification)).build());
}
Also used : PartitionKey(io.cdap.cdap.api.dataset.lib.PartitionKey) Notification(io.cdap.cdap.proto.Notification) DatasetId(io.cdap.cdap.proto.id.DatasetId)

Example 39 with Notification

use of io.cdap.cdap.proto.Notification in project cdap by caskdata.

the class ProgramStatusEventPublisherTest method provideMockedMessages.

private Iterator<ImmutablePair<String, Notification>> provideMockedMessages() {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    InputStream notificationIS = classLoader.getResourceAsStream(MOCKED_NOTIFICATION_FILENAME);
    Assert.assertNotNull(notificationIS);
    String notificationJson = new BufferedReader(new InputStreamReader(notificationIS)).lines().collect(Collectors.joining(System.lineSeparator()));
    Notification notification = GSON.fromJson(notificationJson, Notification.class);
    ImmutablePair<String, Notification> message = new ImmutablePair<>("test", notification);
    List<ImmutablePair<String, Notification>> messageList = new ArrayList<>();
    messageList.add(message);
    return messageList.iterator();
}
Also used : InputStreamReader(java.io.InputStreamReader) ImmutablePair(io.cdap.cdap.common.utils.ImmutablePair) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) Notification(io.cdap.cdap.proto.Notification)

Example 40 with Notification

use of io.cdap.cdap.proto.Notification in project cdap by caskdata.

the class ProgramStatusEventPublisher method processMessages.

@Override
protected void processMessages(StructuredTableContext structuredTableContext, Iterator<ImmutablePair<String, Notification>> messages) {
    List<ProgramStatusEvent> programStatusEvents = new ArrayList<>();
    long publishTime = System.currentTimeMillis();
    messages.forEachRemaining(message -> {
        Notification notification = message.getSecond();
        if (!notification.getNotificationType().equals(Notification.Type.PROGRAM_STATUS)) {
            return;
        }
        Map<String, String> properties = notification.getProperties();
        // get program run ID
        String programStatus = properties.get(ProgramOptionConstants.PROGRAM_STATUS);
        if (programStatus == null) {
            return;
        }
        ProgramRunStatus programRunStatus = ProgramRunStatus.valueOf(programStatus);
        String programRun = properties.get(ProgramOptionConstants.PROGRAM_RUN_ID);
        ProgramRunId programRunId = GSON.fromJson(programRun, ProgramRunId.class);
        // Should event publish happen for this status
        if (!shouldPublish(programRunId)) {
            return;
        }
        ProgramStatusEventDetails.Builder builder = ProgramStatusEventDetails.getBuilder(programRunId.getRun(), programRunId.getApplication(), programRunId.getProgram(), programRunId.getNamespace(), programStatus, RunIds.getTime(programRunId.getRun(), TimeUnit.MILLISECONDS));
        String userArgsString = properties.get(ProgramOptionConstants.USER_OVERRIDES);
        String sysArgsString = properties.get(ProgramOptionConstants.SYSTEM_OVERRIDES);
        Type argsMapType = new TypeToken<Map<String, String>>() {
        }.getType();
        builder = builder.withUserArgs(GSON.fromJson(userArgsString, argsMapType)).withSystemArgs(GSON.fromJson(sysArgsString, argsMapType));
        if (programRunStatus.isEndState()) {
            builder = populateErrorDetailsAndMetrics(builder, properties, programRunStatus, programRunId);
        }
        ProgramStatusEventDetails programStatusEventDetails = builder.build();
        ProgramStatusEvent programStatusEvent = new ProgramStatusEvent(publishTime, EVENT_VERSION, instanceName, projectName, programStatusEventDetails);
        programStatusEvents.add(programStatusEvent);
    });
    this.eventWriters.forEach(eventWriter -> eventWriter.write(programStatusEvents));
}
Also used : ArrayList(java.util.ArrayList) Notification(io.cdap.cdap.proto.Notification) Type(java.lang.reflect.Type) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) Map(java.util.Map)

Aggregations

Notification (io.cdap.cdap.proto.Notification)52 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)14 IOException (java.io.IOException)14 Map (java.util.Map)14 Test (org.junit.Test)14 MessagingService (io.cdap.cdap.messaging.MessagingService)12 ProgramRunStatus (io.cdap.cdap.proto.ProgramRunStatus)12 Gson (com.google.gson.Gson)10 ProgramStateWriter (io.cdap.cdap.app.runtime.ProgramStateWriter)10 RunIds (io.cdap.cdap.common.app.RunIds)10 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)10 Constants (io.cdap.cdap.common.conf.Constants)10 MessagingProgramStateWriter (io.cdap.cdap.internal.app.program.MessagingProgramStateWriter)10 ProgramOptionConstants (io.cdap.cdap.internal.app.runtime.ProgramOptionConstants)10 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)10 ArrayList (java.util.ArrayList)10 Collections (java.util.Collections)10 List (java.util.List)10 TimeUnit (java.util.concurrent.TimeUnit)10 Nullable (javax.annotation.Nullable)10