Search in sources :

Example 16 with StatusException

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException in project grpc-java by grpc.

the class OkHttpClientTransport method start.

@Override
public Runnable start(Listener listener) {
    this.listener = Preconditions.checkNotNull(listener, "listener");
    if (enableKeepAlive) {
        scheduler = SharedResourceHolder.get(TIMER_SERVICE);
        keepAliveManager = new KeepAliveManager(new ClientKeepAlivePinger(this), scheduler, keepAliveTimeNanos, keepAliveTimeoutNanos, keepAliveWithoutCalls);
        keepAliveManager.onTransportStarted();
    }
    if (isForTest()) {
        synchronized (lock) {
            frameWriter = new ExceptionHandlingFrameWriter(OkHttpClientTransport.this, testFrameWriter, testFrameLogger);
            outboundFlow = new OutboundFlowController(OkHttpClientTransport.this, frameWriter);
        }
        serializingExecutor.execute(new Runnable() {

            @Override
            public void run() {
                if (connectingCallback != null) {
                    connectingCallback.run();
                }
                clientFrameHandler = new ClientFrameHandler(testFrameReader, testFrameLogger);
                executor.execute(clientFrameHandler);
                synchronized (lock) {
                    maxConcurrentStreams = Integer.MAX_VALUE;
                    startPendingStreams();
                }
                connectedFuture.set(null);
            }
        });
        return null;
    }
    final AsyncSink asyncSink = AsyncSink.sink(serializingExecutor, this);
    final Variant variant = new Http2();
    FrameWriter rawFrameWriter = variant.newWriter(Okio.buffer(asyncSink), true);
    synchronized (lock) {
        frameWriter = new ExceptionHandlingFrameWriter(this, rawFrameWriter);
        outboundFlow = new OutboundFlowController(this, frameWriter);
    }
    final CountDownLatch latch = new CountDownLatch(1);
    // Connecting in the serializingExecutor, so that some stream operations like synStream
    // will be executed after connected.
    serializingExecutor.execute(new Runnable() {

        @Override
        public void run() {
            // initial preface.
            try {
                latch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            // Use closed source on failure so that the reader immediately shuts down.
            BufferedSource source = Okio.buffer(new Source() {

                @Override
                public long read(Buffer sink, long byteCount) {
                    return -1;
                }

                @Override
                public Timeout timeout() {
                    return Timeout.NONE;
                }

                @Override
                public void close() {
                }
            });
            Socket sock;
            SSLSession sslSession = null;
            try {
                if (proxiedAddr == null) {
                    sock = socketFactory.createSocket(address.getAddress(), address.getPort());
                } else {
                    if (proxiedAddr.getProxyAddress() instanceof InetSocketAddress) {
                        sock = createHttpProxySocket(proxiedAddr.getTargetAddress(), (InetSocketAddress) proxiedAddr.getProxyAddress(), proxiedAddr.getUsername(), proxiedAddr.getPassword());
                    } else {
                        throw Status.INTERNAL.withDescription("Unsupported SocketAddress implementation " + proxiedAddr.getProxyAddress().getClass()).asException();
                    }
                }
                if (sslSocketFactory != null) {
                    SSLSocket sslSocket = OkHttpTlsUpgrader.upgrade(sslSocketFactory, hostnameVerifier, sock, getOverridenHost(), getOverridenPort(), connectionSpec);
                    sslSession = sslSocket.getSession();
                    sock = sslSocket;
                }
                sock.setTcpNoDelay(true);
                source = Okio.buffer(Okio.source(sock));
                asyncSink.becomeConnected(Okio.sink(sock), sock);
                // The return value of OkHttpTlsUpgrader.upgrade is an SSLSocket that has this info
                attributes = attributes.toBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, sock.getRemoteSocketAddress()).set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, sock.getLocalSocketAddress()).set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).set(GrpcAttributes.ATTR_SECURITY_LEVEL, sslSession == null ? SecurityLevel.NONE : SecurityLevel.PRIVACY_AND_INTEGRITY).build();
            } catch (StatusException e) {
                startGoAway(0, ErrorCode.INTERNAL_ERROR, e.getStatus());
                return;
            } catch (Exception e) {
                onException(e);
                return;
            } finally {
                clientFrameHandler = new ClientFrameHandler(variant.newReader(source, true));
            }
            synchronized (lock) {
                socket = Preconditions.checkNotNull(sock, "socket");
                if (sslSession != null) {
                    securityInfo = new InternalChannelz.Security(new InternalChannelz.Tls(sslSession));
                }
            }
        }
    });
    // Schedule to send connection preface & settings before any other write.
    try {
        sendConnectionPrefaceAndSettings();
    } finally {
        latch.countDown();
    }
    serializingExecutor.execute(new Runnable() {

        @Override
        public void run() {
            // ClientFrameHandler need to be started after connectionPreface / settings, otherwise it
            // may send goAway immediately.
            executor.execute(clientFrameHandler);
            synchronized (lock) {
                maxConcurrentStreams = Integer.MAX_VALUE;
                startPendingStreams();
            }
        }
    });
    return null;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) BufferedSource(okio.BufferedSource) Source(okio.Source) StatusException(io.grpc.StatusException) ClientKeepAlivePinger(io.grpc.internal.KeepAliveManager.ClientKeepAlivePinger) KeepAliveManager(io.grpc.internal.KeepAliveManager) BufferedSource(okio.BufferedSource) Buffer(okio.Buffer) Http2(io.grpc.okhttp.internal.framed.Http2) SSLSession(javax.net.ssl.SSLSession) CountDownLatch(java.util.concurrent.CountDownLatch) FrameWriter(io.grpc.okhttp.internal.framed.FrameWriter) EOFException(java.io.EOFException) StatusException(io.grpc.StatusException) IOException(java.io.IOException) Variant(io.grpc.okhttp.internal.framed.Variant) InternalChannelz(io.grpc.InternalChannelz) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 17 with StatusException

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException in project grpc-java by grpc.

the class GoogleAuthLibraryCallCredentials method applyRequestMetadata.

@Override
public void applyRequestMetadata(RequestInfo info, Executor appExecutor, final MetadataApplier applier) {
    SecurityLevel security = info.getSecurityLevel();
    if (requirePrivacy && security != SecurityLevel.PRIVACY_AND_INTEGRITY) {
        applier.fail(Status.UNAUTHENTICATED.withDescription("Credentials require channel with PRIVACY_AND_INTEGRITY security level. " + "Observed security level: " + security));
        return;
    }
    String authority = checkNotNull(info.getAuthority(), "authority");
    final URI uri;
    try {
        uri = serviceUri(authority, info.getMethodDescriptor());
    } catch (StatusException e) {
        applier.fail(e.getStatus());
        return;
    }
    // Credentials is expected to manage caching internally if the metadata is fetched over
    // the network.
    creds.getRequestMetadata(uri, appExecutor, new RequestMetadataCallback() {

        @Override
        public void onSuccess(Map<String, List<String>> metadata) {
            // Some implementations may pass null metadata.
            // Re-use the headers if getRequestMetadata() returns the same map. It may return a
            // different map based on the provided URI, i.e., for JWT. However, today it does not
            // cache JWT and so we won't bother tring to save its return value based on the URI.
            Metadata headers;
            try {
                synchronized (GoogleAuthLibraryCallCredentials.this) {
                    if (lastMetadata == null || lastMetadata != metadata) {
                        lastHeaders = toHeaders(metadata);
                        lastMetadata = metadata;
                    }
                    headers = lastHeaders;
                }
            } catch (Throwable t) {
                applier.fail(Status.UNAUTHENTICATED.withDescription("Failed to convert credential metadata").withCause(t));
                return;
            }
            applier.apply(headers);
        }

        @Override
        public void onFailure(Throwable e) {
            if (e instanceof IOException) {
                // Since it's an I/O failure, let the call be retried with UNAVAILABLE.
                applier.fail(Status.UNAVAILABLE.withDescription("Credentials failed to obtain metadata").withCause(e));
            } else {
                applier.fail(Status.UNAUTHENTICATED.withDescription("Failed computing credential metadata").withCause(e));
            }
        }
    });
}
Also used : StatusException(io.grpc.StatusException) SecurityLevel(io.grpc.SecurityLevel) Metadata(io.grpc.Metadata) ArrayList(java.util.ArrayList) List(java.util.List) RequestMetadataCallback(com.google.auth.RequestMetadataCallback) IOException(java.io.IOException) URI(java.net.URI)

Example 18 with StatusException

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException in project grpc-java by grpc.

the class Inbound method onTransportReady.

final void onTransportReady() {
    // Report transport readiness to the listener, and the outbound data.
    Outbound outbound = null;
    StreamListener listener = null;
    synchronized (this) {
        outbound = this.outbound;
        listener = this.listener;
    }
    if (listener != null) {
        listener.onReady();
    }
    if (outbound != null) {
        try {
            synchronized (outbound) {
                outbound.onTransportReady();
            }
        } catch (StatusException se) {
            synchronized (this) {
                closeAbnormal(se.getStatus());
            }
        }
    }
}
Also used : StatusException(io.grpc.StatusException) ServerStreamListener(io.grpc.internal.ServerStreamListener) StreamListener(io.grpc.internal.StreamListener) ClientStreamListener(io.grpc.internal.ClientStreamListener)

Example 19 with StatusException

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException in project grpc-java by grpc.

the class NettyClientTransportTest method tlsNegotiationFailurePropagatesToStatus.

@Test
public void tlsNegotiationFailurePropagatesToStatus() throws Exception {
    File serverCert = TestUtils.loadCert("server1.pem");
    File serverKey = TestUtils.loadCert("server1.key");
    // Don't trust ca.pem, so that client auth fails
    SslContext sslContext = GrpcSslContexts.forServer(serverCert, serverKey).ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE).clientAuth(ClientAuth.REQUIRE).build();
    negotiator = ProtocolNegotiators.serverTls(sslContext);
    startServer();
    File caCert = TestUtils.loadCert("ca.pem");
    File clientCert = TestUtils.loadCert("client.pem");
    File clientKey = TestUtils.loadCert("client.key");
    SslContext clientContext = GrpcSslContexts.forClient().trustManager(caCert).ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE).keyManager(clientCert, clientKey).build();
    ProtocolNegotiator negotiator = ProtocolNegotiators.tls(clientContext);
    final NettyClientTransport transport = newTransport(negotiator);
    callMeMaybe(transport.start(clientTransportListener));
    Rpc rpc = new Rpc(transport).halfClose();
    try {
        rpc.waitForClose();
        fail("expected exception");
    } catch (ExecutionException ex) {
        StatusException sre = (StatusException) ex.getCause();
        assertEquals(Status.Code.UNAVAILABLE, sre.getStatus().getCode());
        if (sre.getCause() instanceof SSLHandshakeException) {
            assertThat(sre).hasCauseThat().isInstanceOf(SSLHandshakeException.class);
            assertThat(sre).hasCauseThat().hasMessageThat().contains("SSLV3_ALERT_HANDSHAKE_FAILURE");
        } else {
            // Client cert verification is after handshake in TLSv1.3
            assertThat(sre).hasCauseThat().hasCauseThat().isInstanceOf(SSLException.class);
            assertThat(sre).hasCauseThat().hasMessageThat().contains("CERTIFICATE_REQUIRED");
        }
    }
}
Also used : StatusException(io.grpc.StatusException) ExecutionException(java.util.concurrent.ExecutionException) File(java.io.File) SSLException(javax.net.ssl.SSLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SslContext(io.netty.handler.ssl.SslContext) TrackingObjectPoolForTest(io.grpc.netty.NettyTestUtil.TrackingObjectPoolForTest) Test(org.junit.Test)

Example 20 with StatusException

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException in project grpc-java by grpc.

the class HealthServiceImpl method check.

@Override
public void check(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) {
    ServingStatus status = statusMap.get(request.getService());
    if (status == null) {
        responseObserver.onError(new StatusException(Status.NOT_FOUND.withDescription("unknown service " + request.getService())));
    } else {
        HealthCheckResponse response = HealthCheckResponse.newBuilder().setStatus(status).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}
Also used : StatusException(io.grpc.StatusException) ServingStatus(io.grpc.health.v1.HealthCheckResponse.ServingStatus) HealthCheckResponse(io.grpc.health.v1.HealthCheckResponse)

Aggregations

StatusException (io.grpc.StatusException)45 Test (org.junit.Test)20 Status (io.grpc.Status)9 IOException (java.io.IOException)9 StatusException (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusException)9 ExecutionException (java.util.concurrent.ExecutionException)8 PinpointGrpcServer (com.navercorp.pinpoint.collector.receiver.grpc.PinpointGrpcServer)6 Metadata (io.grpc.Metadata)6 StatusRuntimeException (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.StatusRuntimeException)5 HealthCheckResponse (io.grpc.health.v1.HealthCheckResponse)4 TrackingObjectPoolForTest (io.grpc.netty.NettyTestUtil.TrackingObjectPoolForTest)4 TimeoutException (java.util.concurrent.TimeoutException)4 StatusRuntimeException (io.grpc.StatusRuntimeException)3 InetSocketAddress (java.net.InetSocketAddress)3 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)3 RunnerApi (org.apache.beam.model.pipeline.v1.RunnerApi)3 AgentInfo (com.navercorp.pinpoint.collector.cluster.AgentInfo)2 PCmdMessage (com.navercorp.pinpoint.grpc.trace.PCmdMessage)2 PCmdRequest (com.navercorp.pinpoint.grpc.trace.PCmdRequest)2 PCmdResponse (com.navercorp.pinpoint.grpc.trace.PCmdResponse)2