Search in sources :

Example 1 with StatusException

use of io.grpc.StatusException in project grpc-java by grpc.

the class GoogleAuthLibraryCallCredentials method applyRequestMetadata.

@Override
public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor, final MetadataApplier applier) {
    String authority = checkNotNull(attrs.get(ATTR_AUTHORITY), "authority");
    final URI uri;
    try {
        uri = serviceUri(authority, method);
    } catch (StatusException e) {
        applier.fail(e.getStatus());
        return;
    }
    appExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                // Credentials is expected to manage caching internally if the metadata is fetched over
                // the network.
                //
                // TODO(zhangkun83): we don't know whether there is valid cache data. If there is, we
                // would waste a context switch by always scheduling in executor. However, we have to
                // do so because we can't risk blocking the network thread. This can be resolved after
                // https://github.com/google/google-auth-library-java/issues/3 is resolved.
                //
                // Some implementations may return null here.
                Map<String, List<String>> metadata = creds.getRequestMetadata(uri);
                // 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;
                synchronized (GoogleAuthLibraryCallCredentials.this) {
                    if (lastMetadata == null || lastMetadata != metadata) {
                        lastMetadata = metadata;
                        lastHeaders = toHeaders(metadata);
                    }
                    headers = lastHeaders;
                }
                applier.apply(headers);
            } catch (Throwable e) {
                applier.fail(Status.UNAUTHENTICATED.withCause(e));
            }
        }
    });
}
Also used : StatusException(io.grpc.StatusException) Metadata(io.grpc.Metadata) URI(java.net.URI) Map(java.util.Map)

Example 2 with StatusException

use of io.grpc.StatusException in project grpc-java by grpc.

the class NettyClientHandler method createStream.

/**
   * Attempts to create a new stream from the given command. If there are too many active streams,
   * the creation request is queued.
   */
private void createStream(CreateStreamCommand command, final ChannelPromise promise) throws Exception {
    if (lifecycleManager.getShutdownThrowable() != null) {
        // The connection is going away, just terminate the stream now.
        promise.setFailure(lifecycleManager.getShutdownThrowable());
        return;
    }
    // Get the stream ID for the new stream.
    final int streamId;
    try {
        streamId = incrementAndGetNextStreamId();
    } catch (StatusException e) {
        // Stream IDs have been exhausted for this connection. Fail the promise immediately.
        promise.setFailure(e);
        // Initiate a graceful shutdown if we haven't already.
        if (!connection().goAwaySent()) {
            logger.fine("Stream IDs have been exhausted for this connection. " + "Initiating graceful shutdown of the connection.");
            lifecycleManager.notifyShutdown(e.getStatus());
            close(ctx(), ctx().newPromise());
        }
        return;
    }
    final NettyClientStream.TransportState stream = command.stream();
    final Http2Headers headers = command.headers();
    stream.setId(streamId);
    // Create an intermediate promise so that we can intercept the failure reported back to the
    // application.
    ChannelPromise tempPromise = ctx().newPromise();
    encoder().writeHeaders(ctx(), streamId, headers, 0, false, tempPromise).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // The http2Stream will be null in case a stream buffered in the encoder
                // was canceled via RST_STREAM.
                Http2Stream http2Stream = connection().stream(streamId);
                if (http2Stream != null) {
                    stream.getStatsTraceContext().clientHeadersSent();
                    http2Stream.setProperty(streamKey, stream);
                    // Attach the client stream to the HTTP/2 stream object as user data.
                    stream.setHttp2Stream(http2Stream);
                }
                // Otherwise, the stream has been cancelled and Netty is sending a
                // RST_STREAM frame which causes it to purge pending writes from the
                // flow-controller and delete the http2Stream. The stream listener has already
                // been notified of cancellation so there is nothing to do.
                // Just forward on the success status to the original promise.
                promise.setSuccess();
            } else {
                final Throwable cause = future.cause();
                if (cause instanceof StreamBufferingEncoder.Http2GoAwayException) {
                    StreamBufferingEncoder.Http2GoAwayException e = (StreamBufferingEncoder.Http2GoAwayException) cause;
                    lifecycleManager.notifyShutdown(statusFromGoAway(e.errorCode(), e.debugData()));
                    promise.setFailure(lifecycleManager.getShutdownThrowable());
                } else {
                    promise.setFailure(cause);
                }
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) StreamBufferingEncoder(io.netty.handler.codec.http2.StreamBufferingEncoder) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2Exception(io.netty.handler.codec.http2.Http2Exception) StatusException(io.grpc.StatusException) ClosedChannelException(java.nio.channels.ClosedChannelException) StatusException(io.grpc.StatusException) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Example 3 with StatusException

use of 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(this, scheduler, keepAliveDelayNanos, keepAliveTimeoutNanos, false);
        keepAliveManager.onTransportStarted();
    }
    frameWriter = new AsyncFrameWriter(this, serializingExecutor);
    outboundFlow = new OutboundFlowController(this, frameWriter);
    // Connecting in the serializingExecutor, so that some stream operations like synStream
    // will be executed after connected.
    serializingExecutor.execute(new Runnable() {

        @Override
        public void run() {
            if (isForTest()) {
                if (connectingCallback != null) {
                    connectingCallback.run();
                }
                clientFrameHandler = new ClientFrameHandler(testFrameReader);
                executor.execute(clientFrameHandler);
                synchronized (lock) {
                    maxConcurrentStreams = Integer.MAX_VALUE;
                    startPendingStreams();
                }
                frameWriter.becomeConnected(testFrameWriter, socket);
                connectedFuture.set(null);
                return;
            }
            // 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() {
                }
            });
            Variant variant = new Http2();
            BufferedSink sink;
            Socket sock;
            try {
                if (proxyAddress == null) {
                    sock = new Socket(address.getAddress(), address.getPort());
                } else {
                    sock = createHttpProxySocket(address, proxyAddress, proxyUsername, proxyPassword);
                }
                if (sslSocketFactory != null) {
                    sock = OkHttpTlsUpgrader.upgrade(sslSocketFactory, sock, getOverridenHost(), getOverridenPort(), connectionSpec);
                }
                sock.setTcpNoDelay(true);
                source = Okio.buffer(Okio.source(sock));
                sink = Okio.buffer(Okio.sink(sock));
            } 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));
                executor.execute(clientFrameHandler);
            }
            FrameWriter rawFrameWriter;
            synchronized (lock) {
                socket = sock;
                maxConcurrentStreams = Integer.MAX_VALUE;
                startPendingStreams();
            }
            rawFrameWriter = variant.newWriter(sink, true);
            frameWriter.becomeConnected(rawFrameWriter, socket);
            try {
                // Do these with the raw FrameWriter, so that they will be done in this thread,
                // and before any possible pending stream operations.
                rawFrameWriter.connectionPreface();
                Settings settings = new Settings();
                rawFrameWriter.settings(settings);
            } catch (Exception e) {
                onException(e);
                return;
            }
        }
    });
    return null;
}
Also used : Buffer(okio.Buffer) Http2(io.grpc.okhttp.internal.framed.Http2) BufferedSink(okio.BufferedSink) BufferedSource(okio.BufferedSource) Source(okio.Source) EOFException(java.io.EOFException) StatusException(io.grpc.StatusException) IOException(java.io.IOException) FrameWriter(io.grpc.okhttp.internal.framed.FrameWriter) Variant(io.grpc.okhttp.internal.framed.Variant) StatusException(io.grpc.StatusException) KeepAliveManager(io.grpc.internal.KeepAliveManager) Socket(java.net.Socket) Settings(io.grpc.okhttp.internal.framed.Settings) BufferedSource(okio.BufferedSource)

Example 4 with StatusException

use of io.grpc.StatusException in project grpc-java by grpc.

the class HealthStatusManagerTest method checkStatusNotFound.

@Test
public void checkStatusNotFound() throws Exception {
    //setup
    manager.setStatus("", status);
    HealthCheckRequest request = HealthCheckRequest.newBuilder().setService("invalid").build();
    @SuppressWarnings("unchecked") StreamObserver<HealthCheckResponse> observer = mock(StreamObserver.class);
    //test
    health.check(request, observer);
    //verify
    ArgumentCaptor<StatusException> exception = ArgumentCaptor.forClass(StatusException.class);
    verify(observer, times(1)).onError(exception.capture());
    assertEquals(Status.NOT_FOUND, exception.getValue().getStatus());
    verify(observer, never()).onCompleted();
}
Also used : StatusException(io.grpc.StatusException) HealthCheckResponse(io.grpc.health.v1.HealthCheckResponse) HealthCheckRequest(io.grpc.health.v1.HealthCheckRequest) Test(org.junit.Test)

Example 5 with StatusException

use of io.grpc.StatusException in project grpc-java by grpc.

the class HealthStatusManagerTest method notFoundForClearedStatus.

@Test
public void notFoundForClearedStatus() throws Exception {
    //setup
    manager.setStatus("", status);
    manager.clearStatus("");
    HealthCheckRequest request = HealthCheckRequest.newBuilder().setService("").build();
    @SuppressWarnings("unchecked") StreamObserver<HealthCheckResponse> observer = mock(StreamObserver.class);
    //test
    health.check(request, observer);
    //verify
    ArgumentCaptor<StatusException> exception = ArgumentCaptor.forClass(StatusException.class);
    verify(observer, times(1)).onError(exception.capture());
    assertEquals(Status.NOT_FOUND, exception.getValue().getStatus());
    verify(observer, never()).onCompleted();
}
Also used : StatusException(io.grpc.StatusException) HealthCheckResponse(io.grpc.health.v1.HealthCheckResponse) HealthCheckRequest(io.grpc.health.v1.HealthCheckRequest) Test(org.junit.Test)

Aggregations

StatusException (io.grpc.StatusException)13 Test (org.junit.Test)9 Metadata (io.grpc.Metadata)3 HealthCheckResponse (io.grpc.health.v1.HealthCheckResponse)3 IOException (java.io.IOException)3 HealthCheckRequest (io.grpc.health.v1.HealthCheckRequest)2 ByteString (com.google.protobuf.ByteString)1 Status (io.grpc.Status)1 StatusRuntimeException (io.grpc.StatusRuntimeException)1 ServingStatus (io.grpc.health.v1.HealthCheckResponse.ServingStatus)1 KeepAliveManager (io.grpc.internal.KeepAliveManager)1 FrameWriter (io.grpc.okhttp.internal.framed.FrameWriter)1 Http2 (io.grpc.okhttp.internal.framed.Http2)1 Settings (io.grpc.okhttp.internal.framed.Settings)1 Variant (io.grpc.okhttp.internal.framed.Variant)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 ChannelPromise (io.netty.channel.ChannelPromise)1 Http2Exception (io.netty.handler.codec.http2.Http2Exception)1 Http2Headers (io.netty.handler.codec.http2.Http2Headers)1