org.apache.nifi.reporting.Severity Java Examples

The following examples show how to use org.apache.nifi.reporting.Severity. 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: ScriptedActionHandlerTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyContextActionHandler() throws InitializationException {
    actionHandler = initTask("src/test/resources/groovy/test_propertycontext_action_handler.groovy");
    mockScriptedBulletinRepository = new MockScriptedBulletinRepository();
    reportingContext = mock(ReportingContext.class);
    when(reportingContext.getBulletinRepository()).thenReturn(mockScriptedBulletinRepository);
    when(reportingContext.createBulletin(anyString(), Mockito.any(Severity.class), anyString()))
            .thenAnswer(invocation -> BulletinFactory.createBulletin(invocation.getArgument(0), invocation.getArgument(1).toString(), invocation.getArgument(2)));
    actionHandler.onEnabled(context);
    List<Action> actions = Arrays.asList(new Action("LOG", attrs), new Action("ALERT", attrs));
    actions.forEach(action -> actionHandler.execute(reportingContext, action, facts));

    // Verify instead of a bulletin being added, a fact was added (not the intended operation of ActionHandler, but testable)
    List<Bulletin> bulletinList = mockScriptedBulletinRepository.bulletinList;
    assertEquals(2, bulletinList.size());
}
 
Example #2
Source File: NodeClusterCoordinator.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void reportEvent(final NodeIdentifier nodeId, final Severity severity, final String event) {
    eventReporter.reportEvent(severity, EVENT_CATEGORY, nodeId == null ? event : "Event Reported for " + nodeId + " -- " + event);
    if (nodeId != null) {
        addNodeEvent(nodeId, severity, event);
    }

    final String message = nodeId == null ? event : "Event Reported for " + nodeId + " -- " + event;
    switch (severity) {
        case ERROR:
            logger.error(message);
            break;
        case WARNING:
            logger.warn(message);
            break;
        case INFO:
            logger.info(message);
            break;
    }
}
 
Example #3
Source File: NodeClusterCoordinator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void disconnectionRequestedByNode(final NodeIdentifier nodeId, final DisconnectionCode disconnectionCode, final String explanation) {
    logger.info("{} requested disconnection from cluster due to {}", nodeId, explanation == null ? disconnectionCode : explanation);
    updateNodeStatus(new NodeConnectionStatus(nodeId, disconnectionCode, explanation));

    final Severity severity;
    switch (disconnectionCode) {
        case STARTUP_FAILURE:
        case MISMATCHED_FLOWS:
        case UNKNOWN:
            severity = Severity.ERROR;
            break;
        case LACK_OF_HEARTBEAT:
            severity = Severity.WARNING;
            break;
        default:
            severity = Severity.INFO;
            break;
    }

    reportEvent(nodeId, severity, "Node disconnected from cluster due to " + explanation);
}
 
Example #4
Source File: StandardPublicPort.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public PortAuthorizationResult checkUserAuthorization(final String dn) {
    if (!secure) {
        return new StandardPortAuthorizationResult(true, "Site-to-Site is not Secure");
    }

    if (dn == null) {
        final String message = String.format("%s authorization failed for user %s because the DN is unknown", this, dn);
        logger.warn(message);
        eventReporter.reportEvent(Severity.WARNING, CATEGORY, message);
        return new StandardPortAuthorizationResult(false, "User DN is not known");
    }

    final String identity = IdentityMappingUtil.mapIdentity(dn, identityMappings);
    final Set<String> groups = UserGroupUtil.getUserGroups(authorizer, identity);
    return checkUserAuthorization(new Builder().identity(identity).groups(groups).build());
}
 
Example #5
Source File: NodeClusterCoordinator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void reportEvent(final NodeIdentifier nodeId, final Severity severity, final String event) {
    eventReporter.reportEvent(severity, EVENT_CATEGORY, nodeId == null ? event : "Event Reported for " + nodeId + " -- " + event);
    if (nodeId != null) {
        addNodeEvent(nodeId, severity, event);
    }

    final String message = nodeId == null ? event : "Event Reported for " + nodeId + " -- " + event;
    switch (severity) {
        case ERROR:
            logger.error(message);
            break;
        case WARNING:
            logger.warn(message);
            break;
        case INFO:
            logger.info(message);
            break;
    }
}
 
Example #6
Source File: TestHttpClientTransaction.java    From nifi with Apache License 2.0 6 votes vote down vote up
private HttpClientTransaction getClientTransaction(InputStream is, OutputStream os, SiteToSiteRestApiClient apiClient, TransferDirection direction, String transactionUrl) throws IOException {
    PeerDescription description = null;
    String peerUrl = "";

    HttpCommunicationsSession commsSession = new HttpCommunicationsSession();
    ((HttpInput)commsSession.getInput()).setInputStream(is);
    ((HttpOutput)commsSession.getOutput()).setOutputStream(os);

    String clusterUrl = "";
    Peer peer = new Peer(description, commsSession, peerUrl, clusterUrl);
    String portId = "portId";
    boolean useCompression = false;
    int penaltyMillis = 1000;
    EventReporter eventReporter = new EventReporter() {
        @Override
        public void reportEvent(Severity severity, String category, String message) {
            logger.info("Reporting event... severity={}, category={}, message={}", severity, category, message);
        }
    };
    int protocolVersion = 5;

    HttpClientTransaction transaction = new HttpClientTransaction(protocolVersion, peer, direction, useCompression, portId, penaltyMillis, eventReporter);
    transaction.initialize(apiClient, transactionUrl);

    return transaction;
}
 
Example #7
Source File: WriteAheadProvenanceRepository.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void registerEvents(final Iterable<ProvenanceEventRecord> events) {
    final StorageResult storageResult;

    try {
        storageResult = eventStore.addEvents(events);
    } catch (final IOException e) {
        logger.error("Failed to write events to the Event Store", e);
        eventReporter.reportEvent(Severity.ERROR, EVENT_CATEGORY, "Failed to write Provenance Events to the repository. See logs for more details.");
        return;
    }

    final Map<ProvenanceEventRecord, StorageSummary> locationMap = storageResult.getStorageLocations();
    if (!locationMap.isEmpty()) {
        eventIndex.addEvents(locationMap);
    }
}
 
Example #8
Source File: ScriptedActionHandlerTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testActionHandlerNotPropertyContextActionHandler() throws InitializationException {
    actionHandler = initTask("src/test/resources/groovy/test_action_handler.groovy");
    mockScriptedBulletinRepository = new MockScriptedBulletinRepository();
    reportingContext = mock(ReportingContext.class);
    when(reportingContext.getBulletinRepository()).thenReturn(mockScriptedBulletinRepository);
    when(reportingContext.createBulletin(anyString(), Mockito.any(Severity.class), anyString()))
            .thenAnswer(invocation -> BulletinFactory.createBulletin(invocation.getArgument(0), invocation.getArgument(1).toString(), invocation.getArgument(2)));
    actionHandler.onEnabled(context);
    List<Action> actions = Arrays.asList(new Action("LOG", attrs), new Action("ALERT", attrs));
    actions.forEach(action -> actionHandler.execute(reportingContext, action, facts));

    // Verify instead of a bulletin being added, a fact was added (not the intended operation of ActionHandler, but testable)
    assertTrue(mockScriptedBulletinRepository.bulletinList.isEmpty());
    assertEquals(42, facts.get("testFact"));
}
 
Example #9
Source File: ScriptedActionHandlerTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void setupTestRunner() throws Exception {
    runner = TestRunners.newTestRunner(TestProcessor.class);
    MockScriptedActionHandler handler = initTask("src/test/resources/groovy/test_propertycontext_action_handler.groovy");
    mockScriptedBulletinRepository = new MockScriptedBulletinRepository();
    Map<String, String> properties = new HashMap<>();
    properties.put(handler.getScriptingComponentHelper().SCRIPT_ENGINE.getName(), "Groovy");
    properties.put(ScriptingComponentUtils.SCRIPT_FILE.getName(), "src/test/resources/groovy/test_propertycontext_action_handler.groovy");
    runner.addControllerService("MockAlertHandler", handler, properties);
    runner.enableControllerService(handler);
    actionHandler = (MockScriptedActionHandler) runner.getProcessContext()
            .getControllerServiceLookup()
            .getControllerService("MockAlertHandler");
    reportingContext = mock(ReportingContext.class);
    when(reportingContext.getBulletinRepository()).thenReturn(mockScriptedBulletinRepository);
    when(reportingContext.createBulletin(anyString(), Mockito.any(Severity.class), anyString()))
            .thenAnswer(invocation -> BulletinFactory.createBulletin(invocation.getArgument(0), invocation.getArgument(1).toString(), invocation.getArgument(2)));
}
 
Example #10
Source File: StandardRootGroupPort.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public PortAuthorizationResult checkUserAuthorization(final String dn) {
    if (!secure) {
        return new StandardPortAuthorizationResult(true, "Site-to-Site is not Secure");
    }

    if (dn == null) {
        final String message = String.format("%s authorization failed for user %s because the DN is unknown", this, dn);
        logger.warn(message);
        eventReporter.reportEvent(Severity.WARNING, CATEGORY, message);
        return new StandardPortAuthorizationResult(false, "User DN is not known");
    }

    final String identity = IdentityMappingUtil.mapIdentity(dn, identityMappings);

    return checkUserAuthorization(new StandardNiFiUser(identity));
}
 
Example #11
Source File: TestHttpClientTransaction.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private HttpClientTransaction getClientTransaction(InputStream is, OutputStream os, SiteToSiteRestApiClient apiClient, TransferDirection direction, String transactionUrl) throws IOException {
    PeerDescription description = null;
    String peerUrl = "";

    HttpCommunicationsSession commsSession = new HttpCommunicationsSession();
    ((HttpInput)commsSession.getInput()).setInputStream(is);
    ((HttpOutput)commsSession.getOutput()).setOutputStream(os);

    String clusterUrl = "";
    Peer peer = new Peer(description, commsSession, peerUrl, clusterUrl);
    String portId = "portId";
    boolean useCompression = false;
    int penaltyMillis = 1000;
    EventReporter eventReporter = new EventReporter() {
        @Override
        public void reportEvent(Severity severity, String category, String message) {
            logger.info("Reporting event... severity={}, category={}, message={}", severity, category, message);
        }
    };
    int protocolVersion = 5;

    HttpClientTransaction transaction = new HttpClientTransaction(protocolVersion, peer, direction, useCompression, portId, penaltyMillis, eventReporter);
    transaction.initialize(apiClient, transactionUrl);

    return transaction;
}
 
Example #12
Source File: TestAlertHandler.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws InitializationException {
    runner = TestRunners.newTestRunner(TestProcessor.class);
    mockComponentLog = new MockComponentLog();
    AlertHandler handler = new MockAlertHandler(mockComponentLog);
    mockAlertBulletinRepository = new MockAlertBulletinRepository();
    runner.addControllerService("MockAlertHandler", handler);
    runner.enableControllerService(handler);
    alertHandler = (AlertHandler) runner.getProcessContext()
            .getControllerServiceLookup()
            .getControllerService("MockAlertHandler");
    reportingContext = Mockito.mock(ReportingContext.class);
    Mockito.when(reportingContext.getBulletinRepository()).thenReturn(mockAlertBulletinRepository);
    Mockito.when(reportingContext.createBulletin(anyString(), Mockito.any(Severity.class), anyString()))
            .thenAnswer(invocation ->
            BulletinFactory.createBulletin(invocation.getArgument(0), invocation.getArgument(1).toString(), invocation.getArgument(2)));
}
 
Example #13
Source File: Event.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an event.
 *
 * @param source the source
 * @param message the description
 * @param severity the event category
 * @param timestamp the time of occurrence
 */
public Event(final String source, final String message, final Severity severity, final long timestamp) {
    if (StringUtils.isBlank(source)) {
        throw new IllegalArgumentException("Source may not be empty or null.");
    } else if (StringUtils.isBlank(message)) {
        throw new IllegalArgumentException("Event message may not be empty or null.");
    } else if (severity == null) {
        throw new IllegalArgumentException("Event category may not be null.");
    } else if (timestamp < 0) {
        throw new IllegalArgumentException("Timestamp may not be negative: " + timestamp);
    }

    this.source = source;
    this.message = message;
    this.severity = severity;
    this.timestamp = timestamp;
}
 
Example #14
Source File: MigrateDefunctIndex.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final File tempIndexDir = new File(indexDirectory.getParentFile(), TEMP_FILENAME_PREFIX + indexDirectory.getName());
    final File migratedIndexDir = new File(indexDirectory.getParentFile(), MIGRATED_FILENAME_PREFIX + indexDirectory.getName());

    final boolean preconditionsMet = verifyPreconditions(tempIndexDir, migratedIndexDir);
    if (!preconditionsMet) {
        rebuildCount.incrementAndGet(); // increment count so that reporting is accurate
        return;
    }

    // Rebuild the directory or report the error
    try {
        rebuildIndex(tempIndexDir, migratedIndexDir);
        directoryManager.replaceDirectory(indexDirectory, migratedIndexDir, true);

        logger.info("Successfully rebuilt Lucene Index {} as {}; {} of {} indices remain to be rebuilt", indexDirectory, migratedIndexDir,
            totalCount - rebuildCount.incrementAndGet(), totalCount);
    } catch (final Exception e) {
        logger.error("Failed to migrate event index {} to {} after successfully re-indexing {} events", indexDirectory, tempIndexDir, successCount, e);
        eventReporter.reportEvent(Severity.ERROR, "Provenance Event Index Migration", "Failed to  migrate event index " + indexDirectory + " - see logs for more details.");
        rebuildCount.incrementAndGet(); // increment count so that reporting is accurate
    }
}
 
Example #15
Source File: Event.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an event.
 *
 * @param source the source
 * @param message the description
 * @param severity the event category
 * @param timestamp the time of occurrence
 */
public Event(final String source, final String message, final Severity severity, final long timestamp) {
    if (StringUtils.isBlank(source)) {
        throw new IllegalArgumentException("Source may not be empty or null.");
    } else if (StringUtils.isBlank(message)) {
        throw new IllegalArgumentException("Event message may not be empty or null.");
    } else if (severity == null) {
        throw new IllegalArgumentException("Event category may not be null.");
    } else if (timestamp < 0) {
        throw new IllegalArgumentException("Timestamp may not be negative: " + timestamp);
    }

    this.source = source;
    this.message = message;
    this.severity = severity;
    this.timestamp = timestamp;
}
 
Example #16
Source File: Node.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private NodeClusterCoordinator createClusterCoordinator() {
    final EventReporter eventReporter = new EventReporter() {
        @Override
        public void reportEvent(Severity severity, String category, String message) {
            reportedEvents.add(new ReportedEvent(nodeId, severity, message));
        }
    };

    final ServerSocketConfiguration serverSocketConfiguration = new ServerSocketConfiguration();
    serverSocketConfiguration.setSocketTimeout(5000);
    final ProtocolContext<ProtocolMessage> protocolContext = new JaxbProtocolContext<>(JaxbProtocolUtils.JAXB_CONTEXT);

    protocolListener = new SocketProtocolListener(3, Integer.parseInt(nodeProperties.getProperty(NiFiProperties.CLUSTER_NODE_PROTOCOL_PORT)), serverSocketConfiguration, protocolContext);
    try {
        protocolListener.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    final ClusterCoordinationProtocolSenderListener protocolSenderListener = new ClusterCoordinationProtocolSenderListener(createCoordinatorProtocolSender(), protocolListener);
    return new NodeClusterCoordinator(protocolSenderListener, eventReporter, electionManager, flowElection, null,
            revisionManager, nodeProperties, protocolSender);
}
 
Example #17
Source File: ReportingTaskLogObserver.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onLogMessage(final LogMessage message) {
    // Map LogLevel.WARN to Severity.WARNING so that we are consistent with the Severity enumeration. Else, just use whatever
    // the LogLevel is (INFO and ERROR map directly and all others we will just accept as they are).
    final String bulletinLevel = message.getLevel() == LogLevel.WARN ? Severity.WARNING.name() : message.getLevel().toString();

    final Bulletin bulletin = BulletinFactory.createBulletin(null, taskNode.getIdentifier(), ComponentType.REPORTING_TASK,
        taskNode.getName(), "Log Message", bulletinLevel, message.getMessage());
    bulletinRepository.addBulletin(bulletin);
}
 
Example #18
Source File: NodeClusterCoordinator.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void requestNodeConnect(final NodeIdentifier nodeId, final String userDn) {
    if (requireElection && !flowElection.isElectionComplete() && flowElection.isVoteCounted(nodeId)) {
        // If we receive a heartbeat from a node that we already know, we don't want to request that it reconnect
        // to the cluster because no flow has yet been elected. However, if the node has not yet voted, we want to send
        // a reconnect request because we want this node to cast its vote for the flow, and this happens on connection
        logger.debug("Received heartbeat for {} and node is not connected. Will not request node connect to cluster, "
            + "though, because the Flow Election is still in progress", nodeId);
        return;
    }

    if (userDn == null) {
        reportEvent(nodeId, Severity.INFO, "Requesting that node connect to cluster");
    } else {
        reportEvent(nodeId, Severity.INFO, "Requesting that node connect to cluster on behalf of " + userDn);
    }

    updateNodeStatus(new NodeConnectionStatus(nodeId, NodeConnectionState.CONNECTING, null, null, null, System.currentTimeMillis()));

    // create the request
    final ReconnectionRequestMessage request = new ReconnectionRequestMessage();
    request.setNodeId(nodeId);
    request.setInstanceId(instanceId);

    // If we still are requiring that an election take place, we do not want to include our local dataflow, because we don't
    // yet know what the cluster's dataflow looks like. However, if we don't require election, then we've connected to the
    // cluster, which means that our flow is correct.
    final boolean includeDataFlow = !requireElection;
    requestReconnectionAsynchronously(request, 10, 5, includeDataFlow);
}
 
Example #19
Source File: ITestPersistentProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void printTestName() {
    System.out.println("\n\n\n***********************  " + name.getMethodName() + "  *****************************");

    reportedEvents.clear();
    eventReporter = new EventReporter() {
        private static final long serialVersionUID = 1L;

        @Override
        public void reportEvent(Severity severity, String category, String message) {
            reportedEvents.add(new ReportedEvent(severity, category, message));
            System.out.println(severity + " : " + category + " : " + message);
        }
    };
}
 
Example #20
Source File: EventIndexTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final List<StoredDocument> toIndex = new ArrayList<>(MAX_DOCUMENTS_PER_THREAD);

    while (!shutdown) {
        try {
            // Get the Documents that we want to index.
            toIndex.clear();
            fetchDocuments(toIndex);

            if (toIndex.isEmpty()) {
                continue;
            }

            // Write documents to the currently active index.
            final Map<String, List<StoredDocument>> docsByPartition = toIndex.stream()
                .collect(Collectors.groupingBy(doc -> doc.getStorageSummary().getPartitionName().get()));

            for (final Map.Entry<String, List<StoredDocument>> entry : docsByPartition.entrySet()) {
                final String partitionName = entry.getKey();
                final List<StoredDocument> docs = entry.getValue();

                index(docs, partitionName);
            }
        } catch (final Exception e) {
            logger.error("Failed to index Provenance Events", e);
            eventReporter.reportEvent(Severity.ERROR, EVENT_CATEGORY, "Failed to index Provenance Events. See logs for more information.");
        }
    }

    final CompletableFuture<Void> future = this.shutdownComplete;
    if (future != null) {
        future.complete(null);
    }
}
 
Example #21
Source File: StandardPublicPort.java    From nifi with Apache License 2.0 5 votes vote down vote up
public StandardPublicPort(final String id, final String name,
                          final TransferDirection direction, final ConnectableType type, final Authorizer authorizer,
                          final BulletinRepository bulletinRepository, final ProcessScheduler scheduler, final boolean secure,
                          final String yieldPeriod, final List<IdentityMapping> identityMappings) {

    super(id, name, type, scheduler);

    setScheduldingPeriod(MINIMUM_SCHEDULING_NANOS + " nanos");
    this.authorizer = authorizer;
    this.secure = secure;
    this.identityMappings = identityMappings;
    this.bulletinRepository = bulletinRepository;
    this.scheduler = scheduler;
    this.direction = direction;
    setYieldPeriod(yieldPeriod);
    eventReporter = new EventReporter() {
        private static final long serialVersionUID = 1L;

        @Override
        public void reportEvent(final Severity severity, final String category, final String message) {
            final String groupId = StandardPublicPort.this.getProcessGroup().getIdentifier();
            final String groupName = StandardPublicPort.this.getProcessGroup().getName();
            final String sourceId = StandardPublicPort.this.getIdentifier();
            final String sourceName = StandardPublicPort.this.getName();
            final ComponentType componentType = direction == TransferDirection.RECEIVE ? ComponentType.INPUT_PORT : ComponentType.OUTPUT_PORT;
            bulletinRepository.addBulletin(BulletinFactory.createBulletin(groupId, groupName, sourceId, componentType, sourceName, category, severity.name(), message));
        }
    };

    relationships = direction == TransferDirection.RECEIVE ? Collections.singleton(AbstractPort.PORT_RELATIONSHIP) : Collections.emptySet();
}
 
Example #22
Source File: AlertHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected void executeAction(PropertyContext propertyContext, Action action, Map<String, Object> facts) {
    ComponentLog logger = getLogger();
    if (propertyContext instanceof ReportingContext) {

        ReportingContext context = (ReportingContext) propertyContext;
        Map<String, String> attributes = action.getAttributes();
        if (context.getBulletinRepository() != null) {
            final String category = attributes.getOrDefault("category", defaultCategory);
            final String message = getMessage(attributes.getOrDefault("message", defaultMessage), facts);
            final String level = attributes.getOrDefault("severity", attributes.getOrDefault("logLevel", defaultLogLevel));
            Severity severity;
            try {
                severity = Severity.valueOf(level.toUpperCase());
            } catch (IllegalArgumentException iae) {
                severity = Severity.INFO;
            }
            BulletinRepository bulletinRepository = context.getBulletinRepository();
            bulletinRepository.addBulletin(context.createBulletin(category, severity, message));

        } else {
            logger.warn("Bulletin Repository is not available which is unusual. Cannot send a bulletin.");
        }

    } else {
        logger.warn("Reporting context was not provided to create bulletins.");
    }
}
 
Example #23
Source File: NodeClusterCoordinator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void offloadAsynchronously(final OffloadMessage request, final int attempts, final int retrySeconds) {
    final Thread offloadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final NodeIdentifier nodeId = request.getNodeId();

            for (int i = 0; i < attempts; i++) {
                try {
                    senderListener.offload(request);
                    reportEvent(nodeId, Severity.INFO, "Node was offloaded due to " + request.getExplanation());
                    return;
                } catch (final Exception e) {
                    logger.error("Failed to notify {} that it has been offloaded due to {}", request.getNodeId(), request.getExplanation(), e);

                    try {
                        Thread.sleep(retrySeconds * 1000L);
                    } catch (final InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
        }
    }, "Offload " + request.getNodeId());

    offloadThread.start();
}
 
Example #24
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
Example #25
Source File: FlowController.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private static EventReporter createEventReporter(final BulletinRepository bulletinRepository) {
    return new EventReporter() {
        private static final long serialVersionUID = 1L;

        @Override
        public void reportEvent(final Severity severity, final String category, final String message) {
            final Bulletin bulletin = BulletinFactory.createBulletin(category, severity.name(), message);
            bulletinRepository.addBulletin(bulletin);
        }
    };
}
 
Example #26
Source File: StandardFlowSynchronizer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void applyExistingReportingTaskScheduleState(final FlowController controller, final ReportingTaskDTO dto, final ReportingTaskNode taskNode) {
    if (!taskNode.getScheduledState().name().equals(dto.getState())) {
        try {
            switch (ScheduledState.valueOf(dto.getState())) {
                case DISABLED:
                    if (taskNode.isRunning()) {
                        controller.stopReportingTask(taskNode);
                    }
                    controller.disableReportingTask(taskNode);
                    break;
                case RUNNING:
                    if (taskNode.getScheduledState() == ScheduledState.DISABLED) {
                        controller.enableReportingTask(taskNode);
                    }
                    controller.startReportingTask(taskNode);
                    break;
                case STOPPED:
                    if (taskNode.getScheduledState() == ScheduledState.DISABLED) {
                        controller.enableReportingTask(taskNode);
                    } else if (taskNode.getScheduledState() == ScheduledState.RUNNING) {
                        controller.stopReportingTask(taskNode);
                    }
                    break;
            }
        } catch (final IllegalStateException ise) {
            logger.error("Failed to change Scheduled State of {} from {} to {} due to {}", taskNode, taskNode.getScheduledState().name(), dto.getState(), ise.toString());
            logger.error("", ise);

            // create bulletin for the Processor Node
            controller.getBulletinRepository().addBulletin(BulletinFactory.createBulletin("Node Reconnection", Severity.ERROR.name(),
                    "Failed to change Scheduled State of " + taskNode + " from " + taskNode.getScheduledState().name() + " to " + dto.getState() + " due to " + ise.toString()));

            // create bulletin at Controller level.
            controller.getBulletinRepository().addBulletin(BulletinFactory.createBulletin("Node Reconnection", Severity.ERROR.name(),
                    "Failed to change Scheduled State of " + taskNode + " from " + taskNode.getScheduledState().name() + " to " + dto.getState() + " due to " + ise.toString()));
        }
    }
}
 
Example #27
Source File: ProcessorLogObserver.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onLogMessage(final LogMessage message) {
    // Map LogLevel.WARN to Severity.WARNING so that we are consistent with the Severity enumeration. Else, just use whatever
    // the LogLevel is (INFO and ERROR map directly and all others we will just accept as they are).
    final String bulletinLevel = (message.getLevel() == LogLevel.WARN) ? Severity.WARNING.name() : message.getLevel().toString();

    bulletinRepository.addBulletin(BulletinFactory.createBulletin(processorNode, CATEGORY, bulletinLevel, message.getMessage()));
}
 
Example #28
Source File: FlowController.java    From nifi with Apache License 2.0 5 votes vote down vote up
public EventReporter createEventReporter() {
    return new EventReporter() {
        private static final long serialVersionUID = 1L;

        @Override
        public void reportEvent(final Severity severity, final String category, final String message) {
            final Bulletin bulletin = BulletinFactory.createBulletin(category, severity.name(), message);
            bulletinRepository.addBulletin(bulletin);
        }
    };
}
 
Example #29
Source File: NodeClusterCoordinator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void disconnectAsynchronously(final DisconnectMessage request, final int attempts, final int retrySeconds) {
    final Thread disconnectThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final NodeIdentifier nodeId = request.getNodeId();

            for (int i = 0; i < attempts; i++) {
                try {
                    senderListener.disconnect(request);
                    reportEvent(nodeId, Severity.INFO, "Node disconnected due to " + request.getExplanation());
                    return;
                } catch (final Exception e) {
                    logger.error("Failed to notify {} that it has been disconnected from the cluster due to {}", request.getNodeId(), request.getExplanation());

                    try {
                        Thread.sleep(retrySeconds * 1000L);
                    } catch (final InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
        }
    }, "Disconnect " + request.getNodeId());

    disconnectThread.start();
}
 
Example #30
Source File: StandardReportingContext.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Bulletin createBulletin(final String componentId, final String category, final Severity severity, final String message) {
    final Connectable connectable = flowController.getFlowManager().findConnectable(componentId);
    if (connectable == null) {
        throw new IllegalStateException("Cannot create Component-Level Bulletin because no component can be found with ID " + componentId);
    }
    return BulletinFactory.createBulletin(connectable, category, severity.name(), message);
}