Search in sources :

Example 1 with PeerStatus

use of org.apache.nifi.remote.PeerStatus in project nifi by apache.

the class HttpClient method fetchRemotePeerStatuses.

@Override
public Set<PeerStatus> fetchRemotePeerStatuses(PeerDescription peerDescription) throws IOException {
    // Each node should has the same URL structure and network reach-ability with the proxy configuration.
    try (final SiteToSiteRestApiClient apiClient = new SiteToSiteRestApiClient(config.getSslContext(), config.getHttpProxy(), config.getEventReporter())) {
        final String scheme = peerDescription.isSecure() ? "https" : "http";
        apiClient.setBaseUrl(scheme, peerDescription.getHostname(), peerDescription.getPort());
        final int timeoutMillis = (int) config.getTimeout(TimeUnit.MILLISECONDS);
        apiClient.setConnectTimeoutMillis(timeoutMillis);
        apiClient.setReadTimeoutMillis(timeoutMillis);
        apiClient.setCacheExpirationMillis(config.getCacheExpiration(TimeUnit.MILLISECONDS));
        apiClient.setLocalAddress(config.getLocalAddress());
        final Collection<PeerDTO> peers = apiClient.getPeers();
        if (peers == null || peers.size() == 0) {
            throw new IOException("Couldn't get any peer to communicate with. " + apiClient.getBaseUrl() + " returned zero peers.");
        }
        // was added in NiFi 1.0.0, which means that peer-to-peer queries are always allowed.
        return peers.stream().map(p -> new PeerStatus(new PeerDescription(p.getHostname(), p.getPort(), p.isSecure()), p.getFlowFileCount(), true)).collect(Collectors.toSet());
    }
}
Also used : PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) LoggerFactory(org.slf4j.LoggerFactory) SiteToSiteRestApiClient(org.apache.nifi.remote.util.SiteToSiteRestApiClient) StringUtils(org.apache.commons.lang3.StringUtils) SiteToSiteClientConfig(org.apache.nifi.remote.client.SiteToSiteClientConfig) HashSet(java.util.HashSet) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) PeerStatus(org.apache.nifi.remote.PeerStatus) PeerStatusProvider(org.apache.nifi.remote.client.PeerStatusProvider) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) URI(java.net.URI) PeerSelector(org.apache.nifi.remote.client.PeerSelector) ThreadFactory(java.util.concurrent.ThreadFactory) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) AbstractSiteToSiteClient(org.apache.nifi.remote.client.AbstractSiteToSiteClient) TransferDirection(org.apache.nifi.remote.TransferDirection) Logger(org.slf4j.Logger) PeerDescription(org.apache.nifi.remote.PeerDescription) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Transaction(org.apache.nifi.remote.Transaction) Executors(java.util.concurrent.Executors) ProtocolException(org.apache.nifi.remote.exception.ProtocolException) TimeUnit(java.util.concurrent.TimeUnit) HttpClientTransaction(org.apache.nifi.remote.protocol.http.HttpClientTransaction) PeerDTO(org.apache.nifi.web.api.dto.remote.PeerDTO) Peer(org.apache.nifi.remote.Peer) Collections(java.util.Collections) HttpCommunicationsSession(org.apache.nifi.remote.io.http.HttpCommunicationsSession) PeerDescription(org.apache.nifi.remote.PeerDescription) PeerStatus(org.apache.nifi.remote.PeerStatus) SiteToSiteRestApiClient(org.apache.nifi.remote.util.SiteToSiteRestApiClient) IOException(java.io.IOException) PeerDTO(org.apache.nifi.web.api.dto.remote.PeerDTO)

Example 2 with PeerStatus

use of org.apache.nifi.remote.PeerStatus in project nifi by apache.

the class HttpClient method createTransaction.

@Override
public Transaction createTransaction(final TransferDirection direction) throws HandshakeException, PortNotRunningException, ProtocolException, UnknownPortException, IOException {
    final int timeoutMillis = (int) config.getTimeout(TimeUnit.MILLISECONDS);
    PeerStatus peerStatus;
    while ((peerStatus = peerSelector.getNextPeerStatus(direction)) != null) {
        logger.debug("peerStatus={}", peerStatus);
        final CommunicationsSession commSession = new HttpCommunicationsSession();
        final String nodeApiUrl = resolveNodeApiUrl(peerStatus.getPeerDescription());
        final StringBuilder clusterUrls = new StringBuilder();
        config.getUrls().forEach(url -> {
            if (clusterUrls.length() > 0) {
                clusterUrls.append(",");
                clusterUrls.append(url);
            }
        });
        final Peer peer = new Peer(peerStatus.getPeerDescription(), commSession, nodeApiUrl, clusterUrls.toString());
        final int penaltyMillis = (int) config.getPenalizationPeriod(TimeUnit.MILLISECONDS);
        String portId = config.getPortIdentifier();
        if (StringUtils.isEmpty(portId)) {
            portId = siteInfoProvider.getPortIdentifier(config.getPortName(), direction);
            if (StringUtils.isEmpty(portId)) {
                peer.close();
                throw new IOException("Failed to determine the identifier of port " + config.getPortName());
            }
        }
        final SiteToSiteRestApiClient apiClient = new SiteToSiteRestApiClient(config.getSslContext(), config.getHttpProxy(), config.getEventReporter());
        apiClient.setBaseUrl(peer.getUrl());
        apiClient.setConnectTimeoutMillis(timeoutMillis);
        apiClient.setReadTimeoutMillis(timeoutMillis);
        apiClient.setCacheExpirationMillis(config.getCacheExpiration(TimeUnit.MILLISECONDS));
        apiClient.setLocalAddress(config.getLocalAddress());
        apiClient.setCompress(config.isUseCompression());
        apiClient.setRequestExpirationMillis(config.getIdleConnectionExpiration(TimeUnit.MILLISECONDS));
        apiClient.setBatchCount(config.getPreferredBatchCount());
        apiClient.setBatchSize(config.getPreferredBatchSize());
        apiClient.setBatchDurationMillis(config.getPreferredBatchDuration(TimeUnit.MILLISECONDS));
        final String transactionUrl;
        try {
            transactionUrl = apiClient.initiateTransaction(direction, portId);
            commSession.setUserDn(apiClient.getTrustedPeerDn());
        } catch (final Exception e) {
            apiClient.close();
            logger.warn("Penalizing a peer {} due to {}", peer, e.toString());
            peerSelector.penalize(peer, penaltyMillis);
            // Following exceptions will be thrown even if we tried other peers, so throw it.
            if (e instanceof UnknownPortException || e instanceof PortNotRunningException || e instanceof HandshakeException) {
                throw e;
            }
            logger.debug("Continue trying other peers...");
            continue;
        }
        // We found a valid peer to communicate with.
        final Integer transactionProtocolVersion = apiClient.getTransactionProtocolVersion();
        final HttpClientTransaction transaction = new HttpClientTransaction(transactionProtocolVersion, peer, direction, config.isUseCompression(), portId, penaltyMillis, config.getEventReporter()) {

            @Override
            protected void close() throws IOException {
                try {
                    super.close();
                } finally {
                    activeTransactions.remove(this);
                }
            }
        };
        try {
            transaction.initialize(apiClient, transactionUrl);
        } catch (final Exception e) {
            transaction.error();
            throw e;
        }
        activeTransactions.add(transaction);
        return transaction;
    }
    logger.info("Couldn't find a valid peer to communicate with.");
    return null;
}
Also used : HttpCommunicationsSession(org.apache.nifi.remote.io.http.HttpCommunicationsSession) Peer(org.apache.nifi.remote.Peer) SiteToSiteRestApiClient(org.apache.nifi.remote.util.SiteToSiteRestApiClient) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) HttpCommunicationsSession(org.apache.nifi.remote.io.http.HttpCommunicationsSession) IOException(java.io.IOException) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) IOException(java.io.IOException) ProtocolException(org.apache.nifi.remote.exception.ProtocolException) PeerStatus(org.apache.nifi.remote.PeerStatus) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) HttpClientTransaction(org.apache.nifi.remote.protocol.http.HttpClientTransaction)

Example 3 with PeerStatus

use of org.apache.nifi.remote.PeerStatus in project nifi by apache.

the class SocketClientProtocol method getPeerStatuses.

@Override
public Set<PeerStatus> getPeerStatuses(final Peer peer) throws IOException {
    if (!handshakeComplete) {
        throw new IllegalStateException("Handshake has not been performed");
    }
    logger.debug("{} Get Peer Statuses from {}", this, peer);
    final CommunicationsSession commsSession = peer.getCommunicationsSession();
    final DataInputStream dis = new DataInputStream(commsSession.getInput().getInputStream());
    final DataOutputStream dos = new DataOutputStream(commsSession.getOutput().getOutputStream());
    final boolean queryPeersForOtherPeers = getVersionNegotiator().getVersion() >= 6;
    RequestType.REQUEST_PEER_LIST.writeRequestType(dos);
    dos.flush();
    final int numPeers = dis.readInt();
    final Set<PeerStatus> peers = new HashSet<>(numPeers);
    for (int i = 0; i < numPeers; i++) {
        final String hostname = dis.readUTF();
        final int port = dis.readInt();
        final boolean secure = dis.readBoolean();
        final int flowFileCount = dis.readInt();
        peers.add(new PeerStatus(new PeerDescription(hostname, port, secure), flowFileCount, queryPeersForOtherPeers));
    }
    logger.debug("{} Received {} Peer Statuses from {}", this, peers.size(), peer);
    return peers;
}
Also used : PeerDescription(org.apache.nifi.remote.PeerDescription) DataOutputStream(java.io.DataOutputStream) PeerStatus(org.apache.nifi.remote.PeerStatus) CommunicationsSession(org.apache.nifi.remote.protocol.CommunicationsSession) DataInputStream(java.io.DataInputStream) HashSet(java.util.HashSet)

Example 4 with PeerStatus

use of org.apache.nifi.remote.PeerStatus in project nifi by apache.

the class TestPeerSelector method testFormulateDestinationListForOutput.

@Test
public void testFormulateDestinationListForOutput() throws IOException {
    final Set<PeerStatus> collection = new HashSet<>();
    collection.add(new PeerStatus(new PeerDescription("HasMedium", 1111, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("HasLots", 2222, true), 10240, true));
    collection.add(new PeerStatus(new PeerDescription("HasLittle", 3333, true), 1024, true));
    collection.add(new PeerStatus(new PeerDescription("HasMedium", 4444, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("HasMedium", 5555, true), 4096, true));
    PeerStatusProvider peerStatusProvider = Mockito.mock(PeerStatusProvider.class);
    PeerSelector peerSelector = new PeerSelector(peerStatusProvider, null);
    final List<PeerStatus> destinations = peerSelector.formulateDestinationList(collection, TransferDirection.RECEIVE);
    final Map<String, Integer> selectedCounts = calculateAverageSelectedCount(collection, destinations);
    logger.info("selectedCounts={}", selectedCounts);
    assertTrue("HasLots should send lots", selectedCounts.get("HasLots") > selectedCounts.get("HasMedium"));
    assertTrue("HasMedium should send medium", selectedCounts.get("HasMedium") > selectedCounts.get("HasLittle"));
}
Also used : PeerDescription(org.apache.nifi.remote.PeerDescription) PeerStatus(org.apache.nifi.remote.PeerStatus) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with PeerStatus

use of org.apache.nifi.remote.PeerStatus in project nifi by apache.

the class TestPeerSelector method testFormulateDestinationListForOutputEven.

@Test
public void testFormulateDestinationListForOutputEven() throws IOException {
    final Set<PeerStatus> collection = new HashSet<>();
    collection.add(new PeerStatus(new PeerDescription("Node1", 1111, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("Node2", 2222, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("Node3", 3333, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("Node4", 4444, true), 4096, true));
    collection.add(new PeerStatus(new PeerDescription("Node5", 5555, true), 4096, true));
    PeerStatusProvider peerStatusProvider = Mockito.mock(PeerStatusProvider.class);
    PeerSelector peerSelector = new PeerSelector(peerStatusProvider, null);
    final List<PeerStatus> destinations = peerSelector.formulateDestinationList(collection, TransferDirection.RECEIVE);
    final Map<String, Integer> selectedCounts = calculateAverageSelectedCount(collection, destinations);
    logger.info("selectedCounts={}", selectedCounts);
    int consecutiveSamePeerCount = 0;
    PeerStatus previousPeer = null;
    for (PeerStatus peer : destinations) {
        if (previousPeer != null && peer.getPeerDescription().equals(previousPeer.getPeerDescription())) {
            consecutiveSamePeerCount++;
            // The same peer shouldn't be used consecutively (number of nodes - 1) times or more.
            if (consecutiveSamePeerCount >= (collection.size() - 1)) {
                fail("The same peer is returned consecutively too frequently.");
            }
        } else {
            consecutiveSamePeerCount = 0;
        }
        previousPeer = peer;
    }
}
Also used : PeerDescription(org.apache.nifi.remote.PeerDescription) PeerStatus(org.apache.nifi.remote.PeerStatus) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

PeerStatus (org.apache.nifi.remote.PeerStatus)18 PeerDescription (org.apache.nifi.remote.PeerDescription)13 HashSet (java.util.HashSet)11 IOException (java.io.IOException)9 Peer (org.apache.nifi.remote.Peer)5 CommunicationsSession (org.apache.nifi.remote.protocol.CommunicationsSession)5 Test (org.junit.Test)5 DataInputStream (java.io.DataInputStream)3 DataOutputStream (java.io.DataOutputStream)3 URI (java.net.URI)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Set (java.util.Set)3 TimeUnit (java.util.concurrent.TimeUnit)3 Collectors (java.util.stream.Collectors)3 TransferDirection (org.apache.nifi.remote.TransferDirection)3 PeerStatusCache (org.apache.nifi.remote.util.PeerStatusCache)3 BufferedOutputStream (java.io.BufferedOutputStream)2 BufferedReader (java.io.BufferedReader)2 FileInputStream (java.io.FileInputStream)2