Search in sources :

Example 6 with FlowFileCodec

use of org.apache.nifi.remote.codec.FlowFileCodec in project nifi by apache.

the class RemoteResourceManager method isCodecSupported.

public static boolean isCodecSupported(final String codecName, final int version) {
    if (!isCodecSupported(codecName)) {
        return false;
    }
    final FlowFileCodec codec = createCodec(codecName);
    final VersionNegotiator negotiator = codec.getVersionNegotiator();
    return (negotiator.isVersionSupported(version));
}
Also used : FlowFileCodec(org.apache.nifi.remote.codec.FlowFileCodec)

Example 7 with FlowFileCodec

use of org.apache.nifi.remote.codec.FlowFileCodec in project nifi by apache.

the class StandardRootGroupPort method onTrigger.

private void onTrigger(final ProcessContext context, final ProcessSession session, final FlowFileRequest flowFileRequest) {
    final ServerProtocol protocol = flowFileRequest.getProtocol();
    final BlockingQueue<ProcessingResult> responseQueue = flowFileRequest.getResponseQueue();
    if (flowFileRequest.isExpired()) {
        final String message = String.format("%s Cannot service request from %s because the request has timed out", this, flowFileRequest.getPeer());
        logger.warn(message);
        eventReporter.reportEvent(Severity.WARNING, CATEGORY, message);
        responseQueue.add(new ProcessingResult(new RequestExpiredException()));
        return;
    }
    final Peer peer = flowFileRequest.getPeer();
    final CommunicationsSession commsSession = peer.getCommunicationsSession();
    final String sourceDn = commsSession.getUserDn();
    logger.debug("{} Servicing request for {} (DN={})", this, peer, sourceDn);
    final PortAuthorizationResult authorizationResult = checkUserAuthorization(sourceDn);
    if (!authorizationResult.isAuthorized()) {
        final String message = String.format("%s Cannot service request from %s (DN=%s) because peer is not authorized to communicate with this port: %s", this, flowFileRequest.getPeer(), flowFileRequest.getPeer().getCommunicationsSession().getUserDn(), authorizationResult.getExplanation());
        logger.error(message);
        eventReporter.reportEvent(Severity.ERROR, CATEGORY, message);
        responseQueue.add(new ProcessingResult(new NotAuthorizedException(authorizationResult.getExplanation())));
        return;
    }
    final FlowFileCodec codec = protocol.getPreNegotiatedCodec();
    if (codec == null) {
        responseQueue.add(new ProcessingResult(new BadRequestException("None of the supported FlowFile Codecs supplied is compatible with this instance")));
        return;
    }
    final int transferCount;
    try {
        if (getConnectableType() == ConnectableType.INPUT_PORT) {
            transferCount = receiveFlowFiles(context, session, codec, flowFileRequest);
        } else {
            transferCount = transferFlowFiles(context, session, codec, flowFileRequest);
        }
    } catch (final IOException e) {
        session.rollback();
        responseQueue.add(new ProcessingResult(e));
        return;
    } catch (final Exception e) {
        session.rollback();
        responseQueue.add(new ProcessingResult(e));
        return;
    }
    // TODO: Comfirm this. Session.commit here is not required since it has been committed inside receiveFlowFiles/transferFlowFiles.
    // session.commit();
    responseQueue.add(new ProcessingResult(transferCount));
}
Also used : RequestExpiredException(org.apache.nifi.remote.exception.RequestExpiredException) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) NotAuthorizedException(org.apache.nifi.remote.exception.NotAuthorizedException) IOException(java.io.IOException) ServerProtocol(org.apache.nifi.remote.protocol.ServerProtocol) FlowFileCodec(org.apache.nifi.remote.codec.FlowFileCodec) BadRequestException(org.apache.nifi.remote.exception.BadRequestException) ProtocolException(org.apache.nifi.remote.exception.ProtocolException) TransmissionDisabledException(org.apache.nifi.remote.exception.TransmissionDisabledException) NotAuthorizedException(org.apache.nifi.remote.exception.NotAuthorizedException) ProcessException(org.apache.nifi.processor.exception.ProcessException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) RequestExpiredException(org.apache.nifi.remote.exception.RequestExpiredException) BadRequestException(org.apache.nifi.remote.exception.BadRequestException)

Example 8 with FlowFileCodec

use of org.apache.nifi.remote.codec.FlowFileCodec in project nifi by apache.

the class TestHttpFlowFileServerProtocol method transferFlowFiles.

private Peer transferFlowFiles(final HttpFlowFileServerProtocol serverProtocol, final String transactionId, final Peer peer, final Function<MockProcessSession, Collection<MockFlowFile>> flowFileGenerator) throws IOException {
    setupMockProcessSession();
    // Enqueue flow files to be transferred.
    final Collection<MockFlowFile> flowFiles = flowFileGenerator.apply(processSession);
    for (final MockFlowFile flowFile : flowFiles) {
        sessionState.getFlowFileQueue().offer(flowFile);
    }
    final HttpRemoteSiteListener remoteSiteListener = HttpRemoteSiteListener.getInstance(NiFiProperties.createBasicNiFiProperties(null, null));
    serverProtocol.handshake(peer);
    assertTrue(serverProtocol.isHandshakeSuccessful());
    final FlowFileCodec negotiatedCoded = serverProtocol.negotiateCodec(peer);
    // Execute test using mock
    final int flowFileSent = serverProtocol.transferFlowFiles(peer, processContext, processSession, negotiatedCoded);
    assertEquals(flowFiles.size(), flowFileSent);
    assertTrue(remoteSiteListener.isTransactionActive(transactionId));
    return peer;
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) HttpRemoteSiteListener(org.apache.nifi.remote.HttpRemoteSiteListener) FlowFileCodec(org.apache.nifi.remote.codec.FlowFileCodec) StandardFlowFileCodec(org.apache.nifi.remote.codec.StandardFlowFileCodec)

Example 9 with FlowFileCodec

use of org.apache.nifi.remote.codec.FlowFileCodec in project nifi by apache.

the class EndpointConnectionPool method getEndpointConnection.

public EndpointConnection getEndpointConnection(final TransferDirection direction, final SiteToSiteClientConfig config) throws IOException {
    // 
    // Attempt to get a connection state that already exists for this URL.
    // 
    FlowFileCodec codec = null;
    CommunicationsSession commsSession = null;
    SocketClientProtocol protocol = null;
    EndpointConnection connection;
    Peer peer = null;
    final URI clusterUrl;
    try {
        clusterUrl = siteInfoProvider.getActiveClusterUrl();
    } catch (final IOException ioe) {
        throw new UnreachableClusterException("Unable to refresh details from any of the configured remote instances.", ioe);
    }
    do {
        final List<EndpointConnection> addBack = new ArrayList<>();
        logger.debug("{} getting next peer status", this);
        final PeerStatus peerStatus = peerSelector.getNextPeerStatus(direction);
        logger.debug("{} next peer status = {}", this, peerStatus);
        if (peerStatus == null) {
            return null;
        }
        final PeerDescription peerDescription = peerStatus.getPeerDescription();
        BlockingQueue<EndpointConnection> connectionQueue = connectionQueueMap.get(peerDescription);
        if (connectionQueue == null) {
            connectionQueue = new LinkedBlockingQueue<>();
            BlockingQueue<EndpointConnection> existing = connectionQueueMap.putIfAbsent(peerDescription, connectionQueue);
            if (existing != null) {
                connectionQueue = existing;
            }
        }
        try {
            connection = connectionQueue.poll();
            logger.debug("{} Connection State for {} = {}", this, clusterUrl, connection);
            final String portId = getPortIdentifier(direction);
            if (connection == null && !addBack.isEmpty()) {
                // all available connections have been penalized.
                logger.debug("{} all Connections for {} are penalized; returning no Connection", this, portId);
                return null;
            }
            if (connection != null && connection.getPeer().isPenalized(portId)) {
                // we have a connection, but it's penalized. We want to add it back to the queue
                // when we've found one to use.
                addBack.add(connection);
                continue;
            }
            // if we can't get an existing Connection, create one
            if (connection == null) {
                logger.debug("{} No Connection available for Port {}; creating new Connection", this, portId);
                protocol = new SocketClientProtocol();
                protocol.setDestination(new IdEnrichedRemoteDestination(remoteDestination, portId));
                protocol.setEventReporter(eventReporter);
                final long penalizationMillis = remoteDestination.getYieldPeriod(TimeUnit.MILLISECONDS);
                try {
                    logger.debug("{} Establishing site-to-site connection with {}", this, peerStatus);
                    commsSession = establishSiteToSiteConnection(peerStatus);
                } catch (final IOException ioe) {
                    peerSelector.penalize(peerStatus.getPeerDescription(), penalizationMillis);
                    throw ioe;
                }
                final DataInputStream dis = new DataInputStream(commsSession.getInput().getInputStream());
                final DataOutputStream dos = new DataOutputStream(commsSession.getOutput().getOutputStream());
                try {
                    logger.debug("{} Negotiating protocol", this);
                    RemoteResourceInitiator.initiateResourceNegotiation(protocol, dis, dos);
                } catch (final HandshakeException e) {
                    try {
                        commsSession.close();
                    } catch (final IOException ioe) {
                        throw e;
                    }
                }
                final String peerUrl = "nifi://" + peerDescription.getHostname() + ":" + peerDescription.getPort();
                peer = new Peer(peerDescription, commsSession, peerUrl, clusterUrl.toString());
                // set properties based on config
                if (config != null) {
                    protocol.setTimeout((int) config.getTimeout(TimeUnit.MILLISECONDS));
                    protocol.setPreferredBatchCount(config.getPreferredBatchCount());
                    protocol.setPreferredBatchSize(config.getPreferredBatchSize());
                    protocol.setPreferredBatchDuration(config.getPreferredBatchDuration(TimeUnit.MILLISECONDS));
                }
                // perform handshake
                try {
                    logger.debug("{} performing handshake", this);
                    protocol.handshake(peer);
                    // handle error cases
                    if (protocol.isDestinationFull()) {
                        logger.warn("{} {} indicates that port {}'s destination is full; penalizing peer", this, peer, config.getPortName() == null ? config.getPortIdentifier() : config.getPortName());
                        peerSelector.penalize(peer, penalizationMillis);
                        try {
                            peer.close();
                        } catch (final IOException ioe) {
                        }
                        continue;
                    } else if (protocol.isPortInvalid()) {
                        peerSelector.penalize(peer, penalizationMillis);
                        cleanup(protocol, peer);
                        throw new PortNotRunningException(peer.toString() + " indicates that port " + portId + " is not running");
                    } else if (protocol.isPortUnknown()) {
                        peerSelector.penalize(peer, penalizationMillis);
                        cleanup(protocol, peer);
                        throw new UnknownPortException(peer.toString() + " indicates that port " + portId + " is not known");
                    }
                    // negotiate the FlowFileCodec to use
                    logger.debug("{} negotiating codec", this);
                    codec = protocol.negotiateCodec(peer);
                    logger.debug("{} negotiated codec is {}", this, codec);
                } catch (final PortNotRunningException | UnknownPortException e) {
                    throw e;
                } catch (final Exception e) {
                    peerSelector.penalize(peer, penalizationMillis);
                    cleanup(protocol, peer);
                    final String message = String.format("%s failed to communicate with %s due to %s", this, peer == null ? clusterUrl : peer, e.toString());
                    error(logger, eventReporter, message);
                    if (logger.isDebugEnabled()) {
                        logger.error("", e);
                    }
                    throw e;
                }
                connection = new EndpointConnection(peer, protocol, codec);
            } else {
                final long lastTimeUsed = connection.getLastTimeUsed();
                final long millisSinceLastUse = System.currentTimeMillis() - lastTimeUsed;
                if (commsTimeout > 0L && millisSinceLastUse >= commsTimeout) {
                    cleanup(connection.getSocketClientProtocol(), connection.getPeer());
                    connection = null;
                } else {
                    codec = connection.getCodec();
                    peer = connection.getPeer();
                    commsSession = peer.getCommunicationsSession();
                    protocol = connection.getSocketClientProtocol();
                }
            }
        } catch (final Throwable t) {
            if (commsSession != null) {
                try {
                    commsSession.close();
                } catch (final IOException ioe) {
                }
            }
            throw t;
        } finally {
            if (!addBack.isEmpty()) {
                connectionQueue.addAll(addBack);
                addBack.clear();
            }
        }
    } while (connection == null || codec == null || commsSession == null || protocol == null);
    activeConnections.add(connection);
    return connection;
}
Also used : DataOutputStream(java.io.DataOutputStream) ArrayList(java.util.ArrayList) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) SocketChannelCommunicationsSession(org.apache.nifi.remote.io.socket.SocketChannelCommunicationsSession) SSLSocketChannelCommunicationsSession(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannelCommunicationsSession) URI(java.net.URI) FlowFileCodec(org.apache.nifi.remote.codec.FlowFileCodec) PeerStatus(org.apache.nifi.remote.PeerStatus) UnreachableClusterException(org.apache.nifi.remote.exception.UnreachableClusterException) PeerDescription(org.apache.nifi.remote.PeerDescription) Peer(org.apache.nifi.remote.Peer) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) SocketClientProtocol(org.apache.nifi.remote.protocol.socket.SocketClientProtocol) UnreachableClusterException(org.apache.nifi.remote.exception.UnreachableClusterException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) TransmissionDisabledException(org.apache.nifi.remote.exception.TransmissionDisabledException) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException)

Example 10 with FlowFileCodec

use of org.apache.nifi.remote.codec.FlowFileCodec in project nifi by apache.

the class SocketClientProtocol method negotiateCodec.

@Override
public FlowFileCodec negotiateCodec(final Peer peer) throws IOException, ProtocolException {
    if (!handshakeComplete) {
        throw new IllegalStateException("Handshake has not been performed");
    }
    logger.debug("{} Negotiating Codec with {}", this, peer);
    final CommunicationsSession commsSession = peer.getCommunicationsSession();
    final DataInputStream dis = new DataInputStream(commsSession.getInput().getInputStream());
    final DataOutputStream dos = new DataOutputStream(commsSession.getOutput().getOutputStream());
    RequestType.NEGOTIATE_FLOWFILE_CODEC.writeRequestType(dos);
    FlowFileCodec codec = new StandardFlowFileCodec();
    try {
        codec = (FlowFileCodec) RemoteResourceInitiator.initiateResourceNegotiation(codec, dis, dos);
    } catch (HandshakeException e) {
        throw new ProtocolException(e.toString());
    }
    logger.debug("{} negotiated FlowFileCodec {} with {}", new Object[] { this, codec, commsSession });
    return codec;
}
Also used : ProtocolException(org.apache.nifi.remote.exception.ProtocolException) DataOutputStream(java.io.DataOutputStream) StandardFlowFileCodec(org.apache.nifi.remote.codec.StandardFlowFileCodec) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) DataInputStream(java.io.DataInputStream) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) FlowFileCodec(org.apache.nifi.remote.codec.FlowFileCodec) StandardFlowFileCodec(org.apache.nifi.remote.codec.StandardFlowFileCodec)

Aggregations

FlowFileCodec (org.apache.nifi.remote.codec.FlowFileCodec)10 StandardFlowFileCodec (org.apache.nifi.remote.codec.StandardFlowFileCodec)6 Peer (org.apache.nifi.remote.Peer)4 ProcessContext (org.apache.nifi.processor.ProcessContext)3 ProcessSession (org.apache.nifi.processor.ProcessSession)3 CommunicationsSession (org.apache.nifi.remote.protocol.CommunicationsSession)3 MockProcessContext (org.apache.nifi.util.MockProcessContext)3 MockProcessSession (org.apache.nifi.util.MockProcessSession)3 Test (org.junit.Test)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 DataInputStream (java.io.DataInputStream)2 DataOutputStream (java.io.DataOutputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 HttpRemoteSiteListener (org.apache.nifi.remote.HttpRemoteSiteListener)2 HandshakeException (org.apache.nifi.remote.exception.HandshakeException)2 ProtocolException (org.apache.nifi.remote.exception.ProtocolException)2 TransmissionDisabledException (org.apache.nifi.remote.exception.TransmissionDisabledException)2 HttpInput (org.apache.nifi.remote.io.http.HttpInput)2 HttpServerCommunicationsSession (org.apache.nifi.remote.io.http.HttpServerCommunicationsSession)2