Search in sources :

Example 56 with NiFiProperties

use of org.apache.nifi.util.NiFiProperties in project nifi by apache.

the class NodeClusterCoordinator method afterRequest.

/**
 * Callback that is called after an HTTP Request has been replicated to
 * nodes in the cluster. This allows us to disconnect nodes that did not
 * complete the request, if applicable.
 */
@Override
public void afterRequest(final String uriPath, final String method, final Set<NodeResponse> nodeResponses) {
    // as the cluster coordinator is responsible for performing the actual request replication.
    if (!isActiveClusterCoordinator()) {
        return;
    }
    final boolean mutableRequest = isMutableRequest(method);
    /*
         * Nodes that encountered issues handling the request are marked as
         * disconnected for mutable requests (e.g., post, put, delete). For
         * other requests (e.g., get, head), the nodes remain in their current
         * state even if they had problems handling the request.
         */
    if (mutableRequest) {
        final HttpResponseMapper responseMerger = new StandardHttpResponseMapper(nifiProperties);
        final Set<NodeResponse> problematicNodeResponses = responseMerger.getProblematicNodeResponses(nodeResponses);
        // all nodes failed
        final boolean allNodesFailed = problematicNodeResponses.size() == nodeResponses.size();
        // some nodes had a problematic response because of a missing counter, ensure the are not disconnected
        final boolean someNodesFailedMissingCounter = !problematicNodeResponses.isEmpty() && problematicNodeResponses.size() < nodeResponses.size() && isMissingCounter(problematicNodeResponses, uriPath);
        // ensure nodes stay connected in certain scenarios
        if (allNodesFailed) {
            logger.warn("All nodes failed to process URI {} {}. As a result, no node will be disconnected from cluster", method, uriPath);
            return;
        }
        if (someNodesFailedMissingCounter) {
            return;
        }
        // disconnect problematic nodes
        if (!problematicNodeResponses.isEmpty() && problematicNodeResponses.size() < nodeResponses.size()) {
            final Set<NodeIdentifier> failedNodeIds = problematicNodeResponses.stream().map(response -> response.getNodeId()).collect(Collectors.toSet());
            logger.warn(String.format("The following nodes failed to process URI %s '%s'.  Requesting each node disconnect from cluster.", uriPath, failedNodeIds));
            for (final NodeIdentifier nodeId : failedNodeIds) {
                requestNodeDisconnect(nodeId, DisconnectionCode.FAILED_TO_SERVICE_REQUEST, "Failed to process request " + method + " " + uriPath);
            }
        }
    }
}
Also used : NodeProtocolSender(org.apache.nifi.cluster.protocol.NodeProtocolSender) ConnectionResponseMessage(org.apache.nifi.cluster.protocol.message.ConnectionResponseMessage) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) RequestCompletionCallback(org.apache.nifi.cluster.coordination.http.replication.RequestCompletionCallback) LoggerFactory(org.slf4j.LoggerFactory) FlowService(org.apache.nifi.services.FlowService) StringUtils(org.apache.commons.lang3.StringUtils) Map(java.util.Map) ReconnectionRequestMessage(org.apache.nifi.cluster.protocol.message.ReconnectionRequestMessage) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) ConnectionRequestMessage(org.apache.nifi.cluster.protocol.message.ConnectionRequestMessage) ProtocolHandler(org.apache.nifi.cluster.protocol.ProtocolHandler) NodeEvent(org.apache.nifi.cluster.event.NodeEvent) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseMapper(org.apache.nifi.cluster.coordination.http.HttpResponseMapper) Set(java.util.Set) RevisionManager(org.apache.nifi.web.revision.RevisionManager) UUID(java.util.UUID) StandardHttpResponseMapper(org.apache.nifi.cluster.coordination.http.StandardHttpResponseMapper) Collectors(java.util.stream.Collectors) StandardDataFlow(org.apache.nifi.cluster.protocol.StandardDataFlow) ClusterCoordinationProtocolSenderListener(org.apache.nifi.cluster.protocol.impl.ClusterCoordinationProtocolSenderListener) List(java.util.List) ConnectionResponse(org.apache.nifi.cluster.protocol.ConnectionResponse) Pattern(java.util.regex.Pattern) ComponentRevision(org.apache.nifi.cluster.protocol.ComponentRevision) DataFlow(org.apache.nifi.cluster.protocol.DataFlow) ConnectionRequest(org.apache.nifi.cluster.protocol.ConnectionRequest) ClusterWorkloadResponseMessage(org.apache.nifi.cluster.protocol.message.ClusterWorkloadResponseMessage) LeaderElectionManager(org.apache.nifi.controller.leader.election.LeaderElectionManager) Event(org.apache.nifi.cluster.event.Event) HashMap(java.util.HashMap) NodeConnectionStatusResponseMessage(org.apache.nifi.cluster.protocol.message.NodeConnectionStatusResponseMessage) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) CircularFifoQueue(org.apache.commons.collections4.queue.CircularFifoQueue) IllegalNodeDisconnectionException(org.apache.nifi.cluster.manager.exception.IllegalNodeDisconnectionException) ClusterCoordinator(org.apache.nifi.cluster.coordination.ClusterCoordinator) MessageType(org.apache.nifi.cluster.protocol.message.ProtocolMessage.MessageType) ClusterNodeFirewall(org.apache.nifi.cluster.firewall.ClusterNodeFirewall) NoClusterCoordinatorException(org.apache.nifi.cluster.exception.NoClusterCoordinatorException) Logger(org.slf4j.Logger) IOException(java.io.IOException) NodeStatusChangeMessage(org.apache.nifi.cluster.protocol.message.NodeStatusChangeMessage) DisconnectMessage(org.apache.nifi.cluster.protocol.message.DisconnectMessage) AtomicLong(java.util.concurrent.atomic.AtomicLong) FlowElection(org.apache.nifi.cluster.coordination.flow.FlowElection) ProtocolException(org.apache.nifi.cluster.protocol.ProtocolException) EventReporter(org.apache.nifi.events.EventReporter) NiFiProperties(org.apache.nifi.util.NiFiProperties) ClusterWorkloadRequestMessage(org.apache.nifi.cluster.protocol.message.ClusterWorkloadRequestMessage) Severity(org.apache.nifi.reporting.Severity) Collections(java.util.Collections) ProtocolMessage(org.apache.nifi.cluster.protocol.message.ProtocolMessage) HttpResponseMapper(org.apache.nifi.cluster.coordination.http.HttpResponseMapper) StandardHttpResponseMapper(org.apache.nifi.cluster.coordination.http.StandardHttpResponseMapper) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) StandardHttpResponseMapper(org.apache.nifi.cluster.coordination.http.StandardHttpResponseMapper)

Example 57 with NiFiProperties

use of org.apache.nifi.util.NiFiProperties in project nifi by apache.

the class TestPopularVoteFlowElection method getNiFiProperties.

private NiFiProperties getNiFiProperties() {
    final NiFiProperties nifiProperties = mock(NiFiProperties.class);
    when(nifiProperties.getProperty(StringEncryptor.NF_SENSITIVE_PROPS_ALGORITHM)).thenReturn("PBEWITHMD5AND256BITAES-CBC-OPENSSL");
    when(nifiProperties.getProperty(StringEncryptor.NF_SENSITIVE_PROPS_PROVIDER)).thenReturn("BC");
    when(nifiProperties.getProperty(anyString(), anyString())).then(invocation -> invocation.getArgumentAt(1, String.class));
    return nifiProperties;
}
Also used : NiFiProperties(org.apache.nifi.util.NiFiProperties) Matchers.anyString(org.mockito.Matchers.anyString)

Example 58 with NiFiProperties

use of org.apache.nifi.util.NiFiProperties in project nifi by apache.

the class TestThreadPoolRequestReplicator method testMutableRequestRequiresAllNodesConnected.

@Test
public void testMutableRequestRequiresAllNodesConnected() throws URISyntaxException {
    final ClusterCoordinator coordinator = createClusterCoordinator();
    // build a map of connection state to node ids
    final Map<NodeConnectionState, List<NodeIdentifier>> nodeMap = new HashMap<>();
    final List<NodeIdentifier> connectedNodes = new ArrayList<>();
    connectedNodes.add(new NodeIdentifier("1", "localhost", 8100, "localhost", 8101, "localhost", 8102, 8103, false));
    connectedNodes.add(new NodeIdentifier("2", "localhost", 8200, "localhost", 8201, "localhost", 8202, 8203, false));
    nodeMap.put(NodeConnectionState.CONNECTED, connectedNodes);
    final List<NodeIdentifier> otherState = new ArrayList<>();
    otherState.add(new NodeIdentifier("3", "localhost", 8300, "localhost", 8301, "localhost", 8302, 8303, false));
    nodeMap.put(NodeConnectionState.CONNECTING, otherState);
    when(coordinator.getConnectionStates()).thenReturn(nodeMap);
    final NiFiProperties props = NiFiProperties.createBasicNiFiProperties(null, null);
    final ThreadPoolRequestReplicator replicator = new ThreadPoolRequestReplicator(2, 5, 100, ClientBuilder.newClient(), coordinator, "1 sec", "1 sec", null, null, props) {

        @Override
        public AsyncClusterResponse replicate(Set<NodeIdentifier> nodeIds, String method, URI uri, Object entity, Map<String, String> headers, boolean indicateReplicated, boolean verify) {
            return null;
        }
    };
    try {
        // set the user
        final Authentication authentication = new NiFiAuthenticationToken(new NiFiUserDetails(StandardNiFiUser.ANONYMOUS));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        try {
            replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
            Assert.fail("Expected ConnectingNodeMutableRequestException");
        } catch (final ConnectingNodeMutableRequestException e) {
        // expected behavior
        }
        nodeMap.remove(NodeConnectionState.CONNECTING);
        nodeMap.put(NodeConnectionState.DISCONNECTED, otherState);
        try {
            replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
            Assert.fail("Expected DisconnectedNodeMutableRequestException");
        } catch (final DisconnectedNodeMutableRequestException e) {
        // expected behavior
        }
        nodeMap.remove(NodeConnectionState.DISCONNECTED);
        nodeMap.put(NodeConnectionState.DISCONNECTING, otherState);
        try {
            replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
            Assert.fail("Expected DisconnectedNodeMutableRequestException");
        } catch (final DisconnectedNodeMutableRequestException e) {
        // expected behavior
        }
        // should not throw an Exception because it's a GET
        replicator.replicate(HttpMethod.GET, new URI("http://localhost:80/processors/1"), new MultiValueMap<>(), new HashMap<>());
        // should not throw an Exception because all nodes are now connected
        nodeMap.remove(NodeConnectionState.DISCONNECTING);
        replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
    } finally {
        replicator.shutdown();
    }
}
Also used : NiFiProperties(org.apache.nifi.util.NiFiProperties) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ConnectingNodeMutableRequestException(org.apache.nifi.cluster.manager.exception.ConnectingNodeMutableRequestException) ArrayList(java.util.ArrayList) ClusterCoordinator(org.apache.nifi.cluster.coordination.ClusterCoordinator) NodeConnectionState(org.apache.nifi.cluster.coordination.node.NodeConnectionState) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) URI(java.net.URI) NiFiAuthenticationToken(org.apache.nifi.web.security.token.NiFiAuthenticationToken) Authentication(org.springframework.security.core.Authentication) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) List(java.util.List) ArrayList(java.util.ArrayList) DisconnectedNodeMutableRequestException(org.apache.nifi.cluster.manager.exception.DisconnectedNodeMutableRequestException) Map(java.util.Map) HashMap(java.util.HashMap) MultiValueMap(org.apache.commons.collections4.map.MultiValueMap) NiFiUserDetails(org.apache.nifi.authorization.user.NiFiUserDetails) Test(org.junit.Test)

Example 59 with NiFiProperties

use of org.apache.nifi.util.NiFiProperties in project nifi by apache.

the class Cluster method createNode.

public Node createNode() {
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.ZOOKEEPER_CONNECT_STRING, getZooKeeperConnectString());
    addProps.put(NiFiProperties.CLUSTER_IS_NODE, "true");
    final NiFiProperties nifiProperties = NiFiProperties.createBasicNiFiProperties("src/test/resources/conf/nifi.properties", addProps);
    final FingerprintFactory fingerprintFactory = new FingerprintFactory(StringEncryptor.createEncryptor(nifiProperties));
    final FlowElection flowElection = new PopularVoteFlowElection(flowElectionTimeoutMillis, TimeUnit.MILLISECONDS, flowElectionMaxNodes, fingerprintFactory);
    final Node node = new Node(nifiProperties, flowElection);
    node.start();
    nodes.add(node);
    return node;
}
Also used : NiFiProperties(org.apache.nifi.util.NiFiProperties) PopularVoteFlowElection(org.apache.nifi.cluster.coordination.flow.PopularVoteFlowElection) HashMap(java.util.HashMap) FingerprintFactory(org.apache.nifi.fingerprint.FingerprintFactory) PopularVoteFlowElection(org.apache.nifi.cluster.coordination.flow.PopularVoteFlowElection) FlowElection(org.apache.nifi.cluster.coordination.flow.FlowElection)

Example 60 with NiFiProperties

use of org.apache.nifi.util.NiFiProperties in project nifi by apache.

the class NarUnpackerTest method testUnpackNars.

@Test
public void testUnpackNars() {
    NiFiProperties properties = loadSpecifiedProperties("/NarUnpacker/conf/nifi.properties", Collections.EMPTY_MAP);
    assertEquals("./target/NarUnpacker/lib/", properties.getProperty("nifi.nar.library.directory"));
    assertEquals("./target/NarUnpacker/lib2/", properties.getProperty("nifi.nar.library.directory.alt"));
    final ExtensionMapping extensionMapping = NarUnpacker.unpackNars(properties, SystemBundle.create(properties));
    assertEquals(2, extensionMapping.getAllExtensionNames().size());
    assertTrue(extensionMapping.getAllExtensionNames().keySet().contains("org.apache.nifi.processors.dummy.one"));
    assertTrue(extensionMapping.getAllExtensionNames().keySet().contains("org.apache.nifi.processors.dummy.two"));
    final File extensionsWorkingDir = properties.getExtensionsWorkingDirectory();
    File[] extensionFiles = extensionsWorkingDir.listFiles();
    Set<String> expectedNars = new HashSet<>();
    expectedNars.add("dummy-one.nar-unpacked");
    expectedNars.add("dummy-two.nar-unpacked");
    assertEquals(expectedNars.size(), extensionFiles.length);
    for (File extensionFile : extensionFiles) {
        Assert.assertTrue(expectedNars.contains(extensionFile.getName()));
    }
}
Also used : NiFiProperties(org.apache.nifi.util.NiFiProperties) File(java.io.File) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

NiFiProperties (org.apache.nifi.util.NiFiProperties)98 Test (org.junit.Test)63 HashMap (java.util.HashMap)28 Properties (java.util.Properties)24 File (java.io.File)16 Bundle (org.apache.nifi.bundle.Bundle)13 Matchers.anyString (org.mockito.Matchers.anyString)13 IOException (java.io.IOException)10 HashSet (java.util.HashSet)10 Map (java.util.Map)8 X509Certificate (java.security.cert.X509Certificate)7 Mockito.anyString (org.mockito.Mockito.anyString)7 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 SystemBundle (org.apache.nifi.nar.SystemBundle)6 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 IdentityMapping (org.apache.nifi.authorization.util.IdentityMapping)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 FileInputStream (java.io.FileInputStream)4