Search in sources :

Example 6 with HandshakeException

use of org.apache.nifi.remote.exception.HandshakeException in project nifi by apache.

the class TestHttpFlowFileServerProtocol method testUnauthorized.

@Test
public void testUnauthorized() throws Exception {
    final HttpFlowFileServerProtocol serverProtocol = getDefaultHttpFlowFileServerProtocol();
    final Peer peer = getDefaultPeer();
    ((HttpServerCommunicationsSession) peer.getCommunicationsSession()).putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, "port-identifier");
    final ProcessGroup processGroup = mock(ProcessGroup.class);
    final RootGroupPort port = mock(RootGroupPort.class);
    final PortAuthorizationResult authResult = mock(PortAuthorizationResult.class);
    doReturn(true).when(processGroup).isRootGroup();
    doReturn(port).when(processGroup).getOutputPort("port-identifier");
    doReturn(authResult).when(port).checkUserAuthorization(any(String.class));
    serverProtocol.setRootProcessGroup(processGroup);
    try {
        serverProtocol.handshake(peer);
        fail();
    } catch (final HandshakeException e) {
        assertEquals(ResponseCode.UNAUTHORIZED, e.getResponseCode());
    }
    assertFalse(serverProtocol.isHandshakeSuccessful());
}
Also used : HttpServerCommunicationsSession(org.apache.nifi.remote.io.http.HttpServerCommunicationsSession) RootGroupPort(org.apache.nifi.remote.RootGroupPort) Peer(org.apache.nifi.remote.Peer) ProcessGroup(org.apache.nifi.groups.ProcessGroup) PortAuthorizationResult(org.apache.nifi.remote.PortAuthorizationResult) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) Test(org.junit.Test)

Example 7 with HandshakeException

use of org.apache.nifi.remote.exception.HandshakeException 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 8 with HandshakeException

use of org.apache.nifi.remote.exception.HandshakeException in project nifi by apache.

the class SiteToSiteRestApiClient method handleErrResponse.

private IOException handleErrResponse(final int responseCode, final InputStream in) throws IOException {
    if (in == null) {
        return new IOException("Unexpected response code: " + responseCode);
    }
    final TransactionResultEntity errEntity = readResponse(in);
    final ResponseCode errCode = ResponseCode.fromCode(errEntity.getResponseCode());
    switch(errCode) {
        case UNKNOWN_PORT:
            return new UnknownPortException(errEntity.getMessage());
        case PORT_NOT_IN_VALID_STATE:
            return new PortNotRunningException(errEntity.getMessage());
        default:
            switch(responseCode) {
                case RESPONSE_CODE_FORBIDDEN:
                    return new HandshakeException(errEntity.getMessage());
                default:
                    return new IOException("Unexpected response code: " + responseCode + " errCode:" + errCode + " errMessage:" + errEntity.getMessage());
            }
    }
}
Also used : TransactionResultEntity(org.apache.nifi.web.api.entity.TransactionResultEntity) ResponseCode(org.apache.nifi.remote.protocol.ResponseCode) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) IOException(java.io.IOException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException)

Example 9 with HandshakeException

use of org.apache.nifi.remote.exception.HandshakeException in project nifi by apache.

the class TestDataTransferResource method testCreateTransactionPortNotFound.

@Test
public void testCreateTransactionPortNotFound() throws Exception {
    final HttpServletRequest req = createCommonHttpServletRequest();
    final DataTransferResource resource = getDataTransferResource();
    final HttpFlowFileServerProtocol serverProtocol = resource.getHttpFlowFileServerProtocol(null);
    doThrow(new HandshakeException(ResponseCode.UNKNOWN_PORT, "Not found.")).when(serverProtocol).handshake(any());
    final ServletContext context = null;
    final UriInfo uriInfo = null;
    final InputStream inputStream = null;
    final Response response = resource.createPortTransaction("input-ports", "port-id", req, context, uriInfo, inputStream);
    TransactionResultEntity resultEntity = (TransactionResultEntity) response.getEntity();
    assertEquals(404, response.getStatus());
    assertEquals(ResponseCode.UNKNOWN_PORT.getCode(), resultEntity.getResponseCode());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) TransactionResultEntity(org.apache.nifi.web.api.entity.TransactionResultEntity) InputStream(java.io.InputStream) HttpFlowFileServerProtocol(org.apache.nifi.remote.protocol.http.HttpFlowFileServerProtocol) ServletContext(javax.servlet.ServletContext) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) UriInfo(javax.ws.rs.core.UriInfo) Test(org.junit.Test)

Example 10 with HandshakeException

use of org.apache.nifi.remote.exception.HandshakeException in project nifi by apache.

the class TestDataTransferResource method testCreateTransactionPortNotInValidState.

@Test
public void testCreateTransactionPortNotInValidState() throws Exception {
    final HttpServletRequest req = createCommonHttpServletRequest();
    final DataTransferResource resource = getDataTransferResource();
    final HttpFlowFileServerProtocol serverProtocol = resource.getHttpFlowFileServerProtocol(null);
    doThrow(new HandshakeException(ResponseCode.PORT_NOT_IN_VALID_STATE, "Not in valid state.")).when(serverProtocol).handshake(any());
    final ServletContext context = null;
    final UriInfo uriInfo = null;
    final InputStream inputStream = null;
    final Response response = resource.createPortTransaction("input-ports", "port-id", req, context, uriInfo, inputStream);
    TransactionResultEntity resultEntity = (TransactionResultEntity) response.getEntity();
    assertEquals(503, response.getStatus());
    assertEquals(ResponseCode.PORT_NOT_IN_VALID_STATE.getCode(), resultEntity.getResponseCode());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) TransactionResultEntity(org.apache.nifi.web.api.entity.TransactionResultEntity) InputStream(java.io.InputStream) HttpFlowFileServerProtocol(org.apache.nifi.remote.protocol.http.HttpFlowFileServerProtocol) ServletContext(javax.servlet.ServletContext) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) UriInfo(javax.ws.rs.core.UriInfo) Test(org.junit.Test)

Aggregations

HandshakeException (org.apache.nifi.remote.exception.HandshakeException)26 Peer (org.apache.nifi.remote.Peer)13 IOException (java.io.IOException)10 Test (org.junit.Test)10 TransactionResultEntity (org.apache.nifi.web.api.entity.TransactionResultEntity)9 HttpFlowFileServerProtocol (org.apache.nifi.remote.protocol.http.HttpFlowFileServerProtocol)8 HttpServerCommunicationsSession (org.apache.nifi.remote.io.http.HttpServerCommunicationsSession)7 UnknownHostException (java.net.UnknownHostException)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 AccessDeniedException (org.apache.nifi.authorization.AccessDeniedException)6 BadRequestException (org.apache.nifi.remote.exception.BadRequestException)6 NotAuthorizedException (org.apache.nifi.remote.exception.NotAuthorizedException)6 RequestExpiredException (org.apache.nifi.remote.exception.RequestExpiredException)6 ApiOperation (io.swagger.annotations.ApiOperation)5 ApiResponses (io.swagger.annotations.ApiResponses)5 DataInputStream (java.io.DataInputStream)5 DataOutputStream (java.io.DataOutputStream)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 ProtocolException (org.apache.nifi.remote.exception.ProtocolException)5