org.apache.nifi.controller.ReportingTaskNode Java Examples

The following examples show how to use org.apache.nifi.controller.ReportingTaskNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReportingTaskAuditor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Audits the creation of reporting task via createReportingTask().
 *
 * This method only needs to be run 'after returning'. However, in Java 7 the order in which these methods are returned from Class.getDeclaredMethods (even though there is no order guaranteed)
 * seems to differ from Java 6. SpringAOP depends on this ordering to determine advice precedence. By normalizing all advice into Around advice we can alleviate this issue.
 *
 * @param proceedingJoinPoint joinpoint
 * @return node
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ReportingTaskDAO+) && "
        + "execution(org.apache.nifi.controller.ReportingTaskNode createReportingTask(org.apache.nifi.web.api.dto.ReportingTaskDTO))")
public ReportingTaskNode createReportingTaskAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // update the reporting task state
    ReportingTaskNode reportingTask = (ReportingTaskNode) proceedingJoinPoint.proceed();

    // if no exceptions were thrown, add the reporting task action...
    final Action action = generateAuditRecord(reportingTask, Operation.Add);

    // save the actions
    if (action != null) {
        saveAction(action, logger);
    }

    return reportingTask;
}
 
Example #2
Source File: ReportingTaskAuditor.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Audits the creation of reporting task via createReportingTask().
 *
 * This method only needs to be run 'after returning'. However, in Java 7 the order in which these methods are returned from Class.getDeclaredMethods (even though there is no order guaranteed)
 * seems to differ from Java 6. SpringAOP depends on this ordering to determine advice precedence. By normalizing all advice into Around advice we can alleviate this issue.
 *
 * @param proceedingJoinPoint joinpoint
 * @return node
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ReportingTaskDAO+) && "
        + "execution(org.apache.nifi.controller.ReportingTaskNode createReportingTask(org.apache.nifi.web.api.dto.ReportingTaskDTO))")
public ReportingTaskNode createReportingTaskAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // update the reporting task state
    ReportingTaskNode reportingTask = (ReportingTaskNode) proceedingJoinPoint.proceed();

    // if no exceptions were thrown, add the reporting task action...
    final Action action = generateAuditRecord(reportingTask, Operation.Add);

    // save the actions
    if (action != null) {
        saveAction(action, logger);
    }

    return reportingTask;
}
 
Example #3
Source File: StandardControllerServiceProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyCanScheduleReferencingComponents(final ControllerServiceNode serviceNode) {
    final List<ControllerServiceNode> referencingServices = serviceNode.getReferences().findRecursiveReferences(ControllerServiceNode.class);
    final List<ReportingTaskNode> referencingReportingTasks = serviceNode.getReferences().findRecursiveReferences(ReportingTaskNode.class);
    final List<ProcessorNode> referencingProcessors = serviceNode.getReferences().findRecursiveReferences(ProcessorNode.class);

    final Set<ControllerServiceNode> referencingServiceSet = new HashSet<>(referencingServices);

    for (final ReportingTaskNode taskNode : referencingReportingTasks) {
        if (taskNode.getScheduledState() != ScheduledState.DISABLED) {
            taskNode.verifyCanStart(referencingServiceSet);
        }
    }

    for (final ProcessorNode procNode : referencingProcessors) {
        if (procNode.getScheduledState() != ScheduledState.DISABLED) {
            procNode.verifyCanStart(referencingServiceSet);
        }
    }
}
 
Example #4
Source File: StandardReportingTaskDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void updateBundle(ReportingTaskNode reportingTask, ReportingTaskDTO reportingTaskDTO) {
    final BundleDTO bundleDTO = reportingTaskDTO.getBundle();
    if (bundleDTO != null) {
        final ExtensionManager extensionManager = reportingTaskProvider.getExtensionManager();
        final BundleCoordinate incomingCoordinate = BundleUtils.getBundle(extensionManager, reportingTask.getCanonicalClassName(), bundleDTO);
        final BundleCoordinate existingCoordinate = reportingTask.getBundleCoordinate();
        if (!existingCoordinate.getCoordinate().equals(incomingCoordinate.getCoordinate())) {
            try {
                // we need to use the property descriptors from the temp component here in case we are changing from a ghost component to a real component
                final ConfigurableComponent tempComponent = extensionManager.getTempComponent(reportingTask.getCanonicalClassName(), incomingCoordinate);
                final Set<URL> additionalUrls = reportingTask.getAdditionalClasspathResources(tempComponent.getPropertyDescriptors());
                reloadComponent.reload(reportingTask, reportingTask.getCanonicalClassName(), incomingCoordinate, additionalUrls);
            } catch (ReportingTaskInstantiationException e) {
                throw new NiFiCoreException(String.format("Unable to update reporting task %s from %s to %s due to: %s",
                        reportingTaskDTO.getId(), reportingTask.getBundleCoordinate().getCoordinate(), incomingCoordinate.getCoordinate(), e.getMessage()), e);
            }
        }
    }
}
 
Example #5
Source File: StandardControllerServiceProvider.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyCanScheduleReferencingComponents(final ControllerServiceNode serviceNode) {
    final List<ControllerServiceNode> referencingServices = findRecursiveReferences(serviceNode, ControllerServiceNode.class);
    final List<ReportingTaskNode> referencingReportingTasks = findRecursiveReferences(serviceNode, ReportingTaskNode.class);
    final List<ProcessorNode> referencingProcessors = findRecursiveReferences(serviceNode, ProcessorNode.class);

    final Set<ControllerServiceNode> referencingServiceSet = new HashSet<>(referencingServices);

    for (final ReportingTaskNode taskNode : referencingReportingTasks) {
        if (taskNode.getScheduledState() != ScheduledState.DISABLED) {
            taskNode.verifyCanStart(referencingServiceSet);
        }
    }

    for (final ProcessorNode procNode : referencingProcessors) {
        if (procNode.getScheduledState() != ScheduledState.DISABLED) {
            procNode.verifyCanStart(referencingServiceSet);
        }
    }
}
 
Example #6
Source File: StandardFlowManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void removeReportingTask(final ReportingTaskNode reportingTaskNode) {
    final ReportingTaskNode existing = allReportingTasks.get(reportingTaskNode.getIdentifier());
    if (existing == null || existing != reportingTaskNode) {
        throw new IllegalStateException("Reporting Task " + reportingTaskNode + " does not exist in this Flow");
    }

    reportingTaskNode.verifyCanDelete();

    final Class<?> taskClass = reportingTaskNode.getReportingTask().getClass();
    try (final NarCloseable x = NarCloseable.withComponentNarLoader(flowController.getExtensionManager(), taskClass, reportingTaskNode.getReportingTask().getIdentifier())) {
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, reportingTaskNode.getReportingTask(), reportingTaskNode.getConfigurationContext());
    }

    for (final Map.Entry<PropertyDescriptor, String> entry : reportingTaskNode.getEffectivePropertyValues().entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null) {
            final String value = entry.getValue() == null ? descriptor.getDefaultValue() : entry.getValue();
            if (value != null) {
                final ControllerServiceNode serviceNode = flowController.getControllerServiceProvider().getControllerServiceNode(value);
                if (serviceNode != null) {
                    serviceNode.removeReference(reportingTaskNode, descriptor);
                }
            }
        }
    }

    allReportingTasks.remove(reportingTaskNode.getIdentifier());
    LogRepositoryFactory.removeRepository(reportingTaskNode.getIdentifier());
    processScheduler.onReportingTaskRemoved(reportingTaskNode);

    flowController.getExtensionManager().removeInstanceClassLoader(reportingTaskNode.getIdentifier());
}
 
Example #7
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ReportingTaskEntity createReportingTaskEntity(final ReportingTaskNode reportingTask) {
    final RevisionDTO revision = dtoFactory.createRevisionDTO(revisionManager.getRevision(reportingTask.getIdentifier()));
    final PermissionsDTO permissions = dtoFactory.createPermissionsDto(reportingTask);
    final List<BulletinDTO> bulletins = dtoFactory.createBulletinDtos(bulletinRepository.findBulletinsForSource(reportingTask.getIdentifier()));
    final List<BulletinEntity> bulletinEntities = bulletins.stream().map(bulletin -> entityFactory.createBulletinEntity(bulletin, permissions.getCanRead())).collect(Collectors.toList());
    return entityFactory.createReportingTaskEntity(dtoFactory.createReportingTaskDto(reportingTask), revision, permissions, bulletinEntities);
}
 
Example #8
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ComponentStateDTO getReportingTaskState(final String reportingTaskId) {
    final StateMap clusterState = isClustered() ? reportingTaskDAO.getState(reportingTaskId, Scope.CLUSTER) : null;
    final StateMap localState = reportingTaskDAO.getState(reportingTaskId, Scope.LOCAL);

    // reporting task will be non null as it was already found when getting the state
    final ReportingTaskNode reportingTask = reportingTaskDAO.getReportingTask(reportingTaskId);
    return dtoFactory.createComponentStateDTO(reportingTaskId, reportingTask.getReportingTask().getClass(), localState, clusterState);
}
 
Example #9
Source File: TimerDrivenSchedulingAgent.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void doUnschedule(final ReportingTaskNode taskNode, final LifecycleState scheduleState) {
    for (final ScheduledFuture<?> future : scheduleState.getFutures()) {
        // stop scheduling to run but do not interrupt currently running tasks.
        future.cancel(false);
    }

    logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
}
 
Example #10
Source File: StatusConfigReporter.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private static void handleReportingTaskRequest(RequestItem requestItem, FlowController flowController, List<ReportingTaskStatus> reportingTaskStatusList, Logger logger) {
    Set<ReportingTaskNode> reportingTaskNodes = flowController.getAllReportingTasks();

    if (!reportingTaskNodes.isEmpty()) {
        for (ReportingTaskNode reportingTaskNode : reportingTaskNodes) {
            reportingTaskStatusList.add(parseReportingTaskStatusRequest(reportingTaskNode.getIdentifier(), reportingTaskNode, requestItem.options, flowController, logger));
        }
    }
}
 
Example #11
Source File: StatusConfigReporterTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void addReportingTaskNodeVariables(ReportingTaskNode reportingTaskNode) {
    when(reportingTaskNode.getValidationErrors()).thenReturn(Collections.emptyList());
    when(reportingTaskNode.getActiveThreadCount()).thenReturn(1);
    when(reportingTaskNode.getScheduledState()).thenReturn(ScheduledState.RUNNING);
    when(reportingTaskNode.getIdentifier()).thenReturn("ReportProvenance");
    when(reportingTaskNode.getName()).thenReturn("ReportProvenance");

}
 
Example #12
Source File: StandardProcessScheduler.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public synchronized void disableReportingTask(final ReportingTaskNode taskNode) {
    if (taskNode.getScheduledState() != ScheduledState.STOPPED) {
        throw new IllegalStateException("Reporting Task cannot be disabled because its state is set to " + taskNode.getScheduledState()
                + " but transition to DISABLED state is allowed only from the STOPPED state");
    }

    taskNode.setScheduledState(ScheduledState.DISABLED);
}
 
Example #13
Source File: StandardProcessScheduler.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public synchronized void enableReportingTask(final ReportingTaskNode taskNode) {
    if (taskNode.getScheduledState() != ScheduledState.DISABLED) {
        throw new IllegalStateException("Reporting Task cannot be enabled because it is not disabled");
    }

    taskNode.setScheduledState(ScheduledState.STOPPED);
}
 
Example #14
Source File: TimerDrivenSchedulingAgent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void doSchedule(final ReportingTaskNode taskNode, final ScheduleState scheduleState) {
    final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, scheduleState);
    final long schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);

    final ScheduledFuture<?> future = flowEngine.scheduleWithFixedDelay(reportingTaskWrapper, 0L, schedulingNanos, TimeUnit.NANOSECONDS);
    final List<ScheduledFuture<?>> futures = new ArrayList<>(1);
    futures.add(future);
    scheduleState.setFutures(futures);

    logger.info("{} started.", taskNode.getReportingTask());
}
 
Example #15
Source File: TimerDrivenSchedulingAgent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void doUnschedule(final ReportingTaskNode taskNode, final ScheduleState scheduleState) {
    for (final ScheduledFuture<?> future : scheduleState.getFutures()) {
        // stop scheduling to run but do not interrupt currently running tasks.
        future.cancel(false);
    }

    logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
}
 
Example #16
Source File: StatusConfigReporterTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void populateReportingTask(boolean addBulletins, boolean validationErrors) {
    if (addBulletins) {
        addBulletins("Bulletin message", "ReportProvenance");
    }

    ReportingTaskNode reportingTaskNode = mock(ReportingTaskNode.class);
    addReportingTaskNodeVariables(reportingTaskNode);

    HashSet<ReportingTaskNode> reportingTaskNodes = new HashSet<>();
    reportingTaskNodes.add(reportingTaskNode);

    when(mockFlowController.getAllReportingTasks()).thenReturn(reportingTaskNodes);

    if (validationErrors) {
        ValidationResult validationResult = new ValidationResult.Builder()
                .input("input")
                .subject("subject")
                .explanation("is not valid")
                .build();

        ValidationResult validationResult2 = new ValidationResult.Builder()
                .input("input2")
                .subject("subject2")
                .explanation("is not valid too")
                .build();

        List<ValidationResult> validationResultList = new ArrayList<>();
        validationResultList.add(validationResult);
        validationResultList.add(validationResult2);

        when(reportingTaskNode.getValidationErrors()).thenReturn(validationResultList);
    } else {
        when(reportingTaskNode.getValidationErrors()).thenReturn(Collections.EMPTY_LIST);
    }
}
 
Example #17
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public PropertyDescriptorDTO getReportingTaskPropertyDescriptor(final String id, final String property) {
    final ReportingTaskNode reportingTask = reportingTaskDAO.getReportingTask(id);
    PropertyDescriptor descriptor = reportingTask.getReportingTask().getPropertyDescriptor(property);

    // return an invalid descriptor if the reporting task doesn't support this property
    if (descriptor == null) {
        descriptor = new PropertyDescriptor.Builder().name(property).addValidator(Validator.INVALID).dynamic(true).build();
    }

    return dtoFactory.createPropertyDescriptorDto(descriptor, null);
}
 
Example #18
Source File: StatusRequestParser.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
static ReportingTaskStatus parseReportingTaskStatusRequest(String id, ReportingTaskNode reportingTaskNode, String statusTypes, FlowController flowController, Logger logger) {
    ReportingTaskStatus reportingTaskStatus = new ReportingTaskStatus();
    reportingTaskStatus.setName(id);

    String[] statusSplits = statusTypes.split(",");
    List<Bulletin> bulletinList = flowController.getBulletinRepository().findBulletins(
            new BulletinQuery.Builder()
                    .sourceIdMatches(id)
                    .build());
    for (String statusType : statusSplits) {
        switch (statusType.toLowerCase().trim()) {
            case "health":
                ReportingTaskHealth reportingTaskHealth = new ReportingTaskHealth();

                reportingTaskHealth.setScheduledState(reportingTaskNode.getScheduledState().name());
                reportingTaskHealth.setActiveThreads(reportingTaskNode.getActiveThreadCount());
                reportingTaskHealth.setHasBulletins(!bulletinList.isEmpty());

                Collection<ValidationResult> validationResults = reportingTaskNode.getValidationErrors();
                reportingTaskHealth.setValidationErrorList(transformValidationResults(validationResults));

                reportingTaskStatus.setReportingTaskHealth(reportingTaskHealth);
                break;
            case "bulletins":
                reportingTaskStatus.setBulletinList(transformBulletins(bulletinList));
                break;
        }
    }
    return reportingTaskStatus;
}
 
Example #19
Source File: StandardProcessScheduler.java    From nifi with Apache License 2.0 5 votes vote down vote up
public synchronized void enableReportingTask(final ReportingTaskNode taskNode) {
    if (taskNode.getScheduledState() != ScheduledState.DISABLED) {
        throw new IllegalStateException("Reporting Task cannot be enabled because it is not disabled");
    }

    taskNode.setScheduledState(ScheduledState.STOPPED);
}
 
Example #20
Source File: ComponentStateAuditor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Audits clearing of state from a Processor.
 *
 * @param proceedingJoinPoint join point
 * @param reportingTask the reporting task
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ComponentStateDAO+) && "
    + "execution(void clearState(org.apache.nifi.controller.ReportingTaskNode)) && "
    + "args(reportingTask)")
public StateMap clearReportingTaskStateAdvice(ProceedingJoinPoint proceedingJoinPoint, ReportingTaskNode reportingTask) throws Throwable {

    // update the reporting task state
    final StateMap stateMap = (StateMap) proceedingJoinPoint.proceed();

    // if no exception were thrown, add the clear action...

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {
        Collection<Action> actions = new ArrayList<>();

        // create the reporting task details
        FlowChangeExtensionDetails reportingTaskDetails = new FlowChangeExtensionDetails();
        reportingTaskDetails.setType(reportingTask.getReportingTask().getClass().getSimpleName());

        // create the clear action
        FlowChangeAction configAction = new FlowChangeAction();
        configAction.setUserIdentity(user.getIdentity());
        configAction.setOperation(Operation.ClearState);
        configAction.setTimestamp(new Date());
        configAction.setSourceId(reportingTask.getIdentifier());
        configAction.setSourceName(reportingTask.getName());
        configAction.setSourceType(Component.ReportingTask);
        configAction.setComponentDetails(reportingTaskDetails);
        actions.add(configAction);

        // record the action
        saveActions(actions, logger);
    }

    return stateMap;
}
 
Example #21
Source File: ReportingTaskAuditor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the values for the configured properties from the specified ReportingTask.
 *
 * @param reportingTask task
 * @param reportingTaskDTO dto
 * @return properties of task
 */
private Map<String, String> extractConfiguredPropertyValues(ReportingTaskNode reportingTask, ReportingTaskDTO reportingTaskDTO) {
    Map<String, String> values = new HashMap<>();

    if (reportingTaskDTO.getName() != null) {
        values.put(NAME, reportingTask.getName());
    }
    if (reportingTaskDTO.getAnnotationData() != null) {
        values.put(ANNOTATION_DATA, reportingTask.getAnnotationData());
    }
    if (reportingTaskDTO.getProperties() != null) {
        // for each property specified, extract its configured value
        Map<String, String> properties = reportingTaskDTO.getProperties();
        Map<PropertyDescriptor, String> configuredProperties = reportingTask.getProperties();
        for (String propertyName : properties.keySet()) {
            // build a descriptor for getting the configured value
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor.Builder().name(propertyName).build();
            String configuredPropertyValue = configuredProperties.get(propertyDescriptor);

            // if the configured value couldn't be found, use the default value from the actual descriptor
            if (configuredPropertyValue == null) {
                propertyDescriptor = locatePropertyDescriptor(configuredProperties.keySet(), propertyDescriptor);
                configuredPropertyValue = propertyDescriptor.getDefaultValue();
            }
            values.put(propertyName, configuredPropertyValue);
        }
    }

    return values;
}
 
Example #22
Source File: StandardProcessScheduler.java    From nifi with Apache License 2.0 5 votes vote down vote up
public synchronized void disableReportingTask(final ReportingTaskNode taskNode) {
    if (taskNode.getScheduledState() != ScheduledState.STOPPED) {
        throw new IllegalStateException("Reporting Task cannot be disabled because its state is set to " + taskNode.getScheduledState()
                + " but transition to DISABLED state is allowed only from the STOPPED state");
    }

    taskNode.setScheduledState(ScheduledState.DISABLED);
}
 
Example #23
Source File: TimerDrivenSchedulingAgent.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void doSchedule(final ReportingTaskNode taskNode, final LifecycleState scheduleState) {
    final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, scheduleState, flowController.getExtensionManager());
    final long schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);

    final ScheduledFuture<?> future = flowEngine.scheduleWithFixedDelay(reportingTaskWrapper, 0L, schedulingNanos, TimeUnit.NANOSECONDS);
    final List<ScheduledFuture<?>> futures = new ArrayList<>(1);
    futures.add(future);
    scheduleState.setFutures(futures);

    logger.info("{} started.", taskNode.getReportingTask());
}
 
Example #24
Source File: StandardFlowManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void verifyCanPurge() {
    for (final ControllerServiceNode serviceNode : getAllControllerServices()) {
        serviceNode.verifyCanDelete();
    }

    for (final ReportingTaskNode reportingTask : getAllReportingTasks()) {
        reportingTask.verifyCanDelete();
    }

    final ProcessGroup rootGroup = getRootGroup();
    rootGroup.verifyCanDelete(true, true);
}
 
Example #25
Source File: StandardReportingTaskDAO.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void configureReportingTask(final ReportingTaskNode reportingTask, final ReportingTaskDTO reportingTaskDTO) {
    final String name = reportingTaskDTO.getName();
    final String schedulingStrategy = reportingTaskDTO.getSchedulingStrategy();
    final String schedulingPeriod = reportingTaskDTO.getSchedulingPeriod();
    final String annotationData = reportingTaskDTO.getAnnotationData();
    final String comments = reportingTaskDTO.getComments();
    final Map<String, String> properties = reportingTaskDTO.getProperties();

    // ensure scheduling strategy is set first
    if (isNotNull(schedulingStrategy)) {
        reportingTask.setSchedulingStrategy(SchedulingStrategy.valueOf(schedulingStrategy));
    }

    if (isNotNull(name)) {
        reportingTask.setName(name);
    }
    if (isNotNull(schedulingPeriod)) {
        reportingTask.setSchedulingPeriod(schedulingPeriod);
    }
    if (isNotNull(annotationData)) {
        reportingTask.setAnnotationData(annotationData);
    }
    if (isNotNull(comments)) {
        reportingTask.setComments(comments);
    }
    if (isNotNull(properties)) {
        reportingTask.setProperties(properties);
    }
}
 
Example #26
Source File: StandardAuthorizableLookup.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigurableComponentAuthorizable getReportingTaskByType(String type) {
    try {
        final ReportingTaskNode reportingTask = controllerFacade.createTemporaryReportingTask(type);
        return new ReportingTaskConfigurableComponentAuthorizable(reportingTask);
    } catch (final Exception e) {
        throw new AccessDeniedException("Unable to create reporting to verify if it references any Controller Services.");
    }
}
 
Example #27
Source File: StandardAuthorizableLookup.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public ReportingTaskConfigurableComponentAuthorizable(ReportingTaskNode reportingTaskNode) {
    this.reportingTaskNode = reportingTaskNode;
}
 
Example #28
Source File: ReportingTaskWrapper.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public ReportingTaskWrapper(final ReportingTaskNode taskNode, final ScheduleState scheduleState) {
    this.taskNode = taskNode;
    this.scheduleState = scheduleState;
}
 
Example #29
Source File: StandardProcessScheduler.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void schedule(final ReportingTaskNode taskNode) {
    final ScheduleState scheduleState = getScheduleState(requireNonNull(taskNode));
    if (scheduleState.isScheduled()) {
        return;
    }

    final int activeThreadCount = scheduleState.getActiveThreadCount();
    if (activeThreadCount > 0) {
        throw new IllegalStateException("Reporting Task " + taskNode.getName() + " cannot be started because it has " + activeThreadCount + " threads still running");
    }

    if (!taskNode.isValid()) {
        throw new IllegalStateException("Reporting Task " + taskNode.getName() + " is not in a valid state for the following reasons: " + taskNode.getValidationErrors());
    }

    final SchedulingAgent agent = getSchedulingAgent(taskNode.getSchedulingStrategy());
    scheduleState.setScheduled(true);

    final Runnable startReportingTaskRunnable = new Runnable() {
        @Override
        public void run() {
            final long lastStopTime = scheduleState.getLastStopTime();
            final ReportingTask reportingTask = taskNode.getReportingTask();

            // Continually attempt to start the Reporting Task, and if we fail sleep for a bit each time.
            while (true) {
                try {
                    synchronized (scheduleState) {
                        // if no longer scheduled to run, then we're finished. This can happen, for example,
                        // if the @OnScheduled method throws an Exception and the user stops the reporting task
                        // while we're administratively yielded.
                        // we also check if the schedule state's last start time is equal to what it was before.
                        // if not, then means that the reporting task has been stopped and started again, so we should just
                        // bail; another thread will be responsible for invoking the @OnScheduled methods.
                        if (!scheduleState.isScheduled() || scheduleState.getLastStopTime() != lastStopTime) {
                            return;
                        }

                        try (final NarCloseable x = NarCloseable.withComponentNarLoader(reportingTask.getClass(), reportingTask.getIdentifier())) {
                            ReflectionUtils.invokeMethodsWithAnnotation(OnScheduled.class, reportingTask, taskNode.getConfigurationContext());
                        }

                        agent.schedule(taskNode, scheduleState);
                        return;
                    }
                } catch (final Exception e) {
                    final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e;
                    final ComponentLog componentLog = new SimpleProcessLogger(reportingTask.getIdentifier(), reportingTask);
                    componentLog.error("Failed to invoke @OnEnabled method due to {}", cause);

                    LOG.error("Failed to invoke the On-Scheduled Lifecycle methods of {} due to {}; administratively yielding this "
                            + "ReportingTask and will attempt to schedule it again after {}",
                            new Object[]{reportingTask, e.toString(), administrativeYieldDuration}, e);

                    ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnUnscheduled.class, reportingTask, taskNode.getConfigurationContext());
                    ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnStopped.class, reportingTask, taskNode.getConfigurationContext());

                    try {
                        Thread.sleep(administrativeYieldMillis);
                    } catch (final InterruptedException ie) {
                    }
                }
            }
        }
    };

    componentLifeCycleThreadPool.execute(startReportingTaskRunnable);
    taskNode.setScheduledState(ScheduledState.RUNNING);
}
 
Example #30
Source File: EventDrivenSchedulingAgent.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void doSchedule(final ReportingTaskNode taskNode, ScheduleState scheduleState) {
    throw new UnsupportedOperationException("ReportingTasks cannot be scheduled in Event-Driven Mode");
}