Search in sources :

Example 46 with Server

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

the class HostnameServer method main.

public static void main(String[] args) throws IOException, InterruptedException {
    int port = 50051;
    String hostname = null;
    if (args.length >= 1) {
        try {
            port = Integer.parseInt(args[0]);
        } catch (NumberFormatException ex) {
            System.err.println("Usage: [port [hostname]]");
            System.err.println("");
            System.err.println("  port      The listen port. Defaults to " + port);
            System.err.println("  hostname  The name clients will see in greet responses. ");
            System.err.println("            Defaults to the machine's hostname");
            System.exit(1);
        }
    }
    if (args.length >= 2) {
        hostname = args[1];
    }
    HealthStatusManager health = new HealthStatusManager();
    final Server server = ServerBuilder.forPort(port).addService(new HostnameGreeter(hostname)).addService(ProtoReflectionService.newInstance()).addService(health.getHealthService()).build().start();
    System.out.println("Listening on port " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            // Start graceful shutdown
            server.shutdown();
            try {
                // Wait for RPCs to complete processing
                if (!server.awaitTermination(30, TimeUnit.SECONDS)) {
                    // That was plenty of time. Let's cancel the remaining RPCs
                    server.shutdownNow();
                    // shutdownNow isn't instantaneous, so give a bit of time to clean resources up
                    // gracefully. Normally this will be well under a second.
                    server.awaitTermination(5, TimeUnit.SECONDS);
                }
            } catch (InterruptedException ex) {
                server.shutdownNow();
            }
        }
    });
    // This would normally be tied to the service's dependencies. For example, if HostnameGreeter
    // used a Channel to contact a required service, then when 'channel.getState() ==
    // TRANSIENT_FAILURE' we'd want to set NOT_SERVING. But HostnameGreeter has no dependencies, so
    // hard-coding SERVING is appropriate.
    health.setStatus("", ServingStatus.SERVING);
    server.awaitTermination();
}
Also used : HealthStatusManager(io.grpc.services.HealthStatusManager) Server(io.grpc.Server)

Example 47 with Server

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

the class DetailErrorSample method run.

void run() throws Exception {
    Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {

        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            Metadata trailers = new Metadata();
            trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO);
            responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC).asRuntimeException(trailers));
        }
    }).build().start();
    channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
    blockingCall();
    futureCallDirect();
    futureCallCallback();
    asyncCall();
    advancedAsyncCall();
    channel.shutdown();
    server.shutdown();
    channel.awaitTermination(1, TimeUnit.SECONDS);
    server.awaitTermination();
}
Also used : Server(io.grpc.Server) HelloRequest(io.grpc.examples.helloworld.HelloRequest) Metadata(io.grpc.Metadata) GreeterGrpc(io.grpc.examples.helloworld.GreeterGrpc) HelloReply(io.grpc.examples.helloworld.HelloReply)

Example 48 with Server

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

the class ManualFlowControlServer method main.

public static void main(String[] args) throws InterruptedException, IOException {
    // Service class implementation
    StreamingGreeterGrpc.StreamingGreeterImplBase svc = new StreamingGreeterGrpc.StreamingGreeterImplBase() {

        @Override
        public StreamObserver<HelloRequest> sayHelloStreaming(final StreamObserver<HelloReply> responseObserver) {
            // Set up manual flow control for the request stream. It feels backwards to configure the request
            // stream's flow control using the response stream's observer, but this is the way it is.
            final ServerCallStreamObserver<HelloReply> serverCallStreamObserver = (ServerCallStreamObserver<HelloReply>) responseObserver;
            serverCallStreamObserver.disableAutoRequest();
            // else message processing throughput will suffer.
            class OnReadyHandler implements Runnable {

                // Guard against spurious onReady() calls caused by a race between onNext() and onReady(). If the transport
                // toggles isReady() from false to true while onNext() is executing, but before onNext() checks isReady(),
                // request(1) would be called twice - once by onNext() and once by the onReady() scheduled during onNext()'s
                // execution.
                private boolean wasReady = false;

                @Override
                public void run() {
                    if (serverCallStreamObserver.isReady() && !wasReady) {
                        wasReady = true;
                        logger.info("READY");
                        // Signal the request sender to send one message. This happens when isReady() turns true, signaling that
                        // the receive buffer has enough free space to receive more messages. Calling request() serves to prime
                        // the message pump.
                        serverCallStreamObserver.request(1);
                    }
                }
            }
            final OnReadyHandler onReadyHandler = new OnReadyHandler();
            serverCallStreamObserver.setOnReadyHandler(onReadyHandler);
            // Give gRPC a StreamObserver that can observe and process incoming requests.
            return new StreamObserver<HelloRequest>() {

                @Override
                public void onNext(HelloRequest request) {
                    // Process the request and send a response or an error.
                    try {
                        // Accept and enqueue the request.
                        String name = request.getName();
                        logger.info("--> " + name);
                        // Simulate server "work"
                        Thread.sleep(100);
                        // Send a response.
                        String message = "Hello " + name;
                        logger.info("<-- " + message);
                        HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
                        responseObserver.onNext(reply);
                        // Check the provided ServerCallStreamObserver to see if it is still ready to accept more messages.
                        if (serverCallStreamObserver.isReady()) {
                            // Signal the sender to send another request. As long as isReady() stays true, the server will keep
                            // cycling through the loop of onNext() -> request(1)...onNext() -> request(1)... until the client runs
                            // out of messages and ends the loop (via onCompleted()).
                            // 
                            // If request() was called here with the argument of more than 1, the server might runs out of receive
                            // buffer space, and isReady() will turn false. When the receive buffer has sufficiently drained,
                            // isReady() will turn true, and the serverCallStreamObserver's onReadyHandler will be called to restart
                            // the message pump.
                            serverCallStreamObserver.request(1);
                        } else {
                            // If not, note that back-pressure has begun.
                            onReadyHandler.wasReady = false;
                        }
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                        responseObserver.onError(Status.UNKNOWN.withDescription("Error handling request").withCause(throwable).asException());
                    }
                }

                @Override
                public void onError(Throwable t) {
                    // End the response stream if the client presents an error.
                    t.printStackTrace();
                    responseObserver.onCompleted();
                }

                @Override
                public void onCompleted() {
                    // Signal the end of work when the client ends the request stream.
                    logger.info("COMPLETED");
                    responseObserver.onCompleted();
                }
            };
        }
    };
    final Server server = ServerBuilder.forPort(50051).addService(svc).build().start();
    logger.info("Listening on " + server.getPort());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("Shutting down");
            try {
                server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
        }
    });
    server.awaitTermination();
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Server(io.grpc.Server)

Example 49 with Server

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

the class HealthCheckingLoadBalancerFactoryTest method setup.

@Before
@SuppressWarnings("unchecked")
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
        HealthImpl healthImpl = new HealthImpl();
        healthImpls[i] = healthImpl;
        Server server = InProcessServerBuilder.forName("health-check-test-" + i).addService(healthImpl).directExecutor().build().start();
        servers[i] = server;
        ManagedChannel channel = InProcessChannelBuilder.forName("health-check-test-" + i).directExecutor().build();
        channels[i] = channel;
        EquivalentAddressGroup eag = new EquivalentAddressGroup(new FakeSocketAddress("address-" + i));
        eags[i] = eag;
        List<EquivalentAddressGroup> eagList = Arrays.asList(eag);
        eagLists[i] = eagList;
        mockStateListeners[i] = mock(SubchannelStateListener.class);
    }
    resolvedAddressList = Arrays.asList(eags);
    when(backoffPolicyProvider.get()).thenReturn(backoffPolicy1, backoffPolicy2);
    when(backoffPolicy1.nextBackoffNanos()).thenReturn(11L, 21L, 31L);
    when(backoffPolicy2.nextBackoffNanos()).thenReturn(12L, 22L, 32L);
    hcLbFactory = new HealthCheckingLoadBalancerFactory(origLbFactory, backoffPolicyProvider, clock.getStopwatchSupplier());
    hcLb = hcLbFactory.newLoadBalancer(origHelper);
    // Make sure all calls into the hcLb is from the syncContext
    hcLbEventDelivery = new LoadBalancer() {

        // Per LoadBalancer API, no more callbacks will be called after shutdown() is called.
        boolean shutdown;

        @Override
        public void handleResolvedAddresses(final ResolvedAddresses resolvedAddresses) {
            syncContext.execute(new Runnable() {

                @Override
                public void run() {
                    if (!shutdown) {
                        hcLb.handleResolvedAddresses(resolvedAddresses);
                    }
                }
            });
        }

        @Override
        public void handleNameResolutionError(Status error) {
            throw new AssertionError("Not supposed to be called");
        }

        @Override
        public void shutdown() {
            syncContext.execute(new Runnable() {

                @Override
                public void run() {
                    if (!shutdown) {
                        shutdown = true;
                        hcLb.shutdown();
                    }
                }
            });
        }
    };
    verify(origLbFactory).newLoadBalancer(any(Helper.class));
}
Also used : Status(io.grpc.Status) ServingStatus(io.grpc.health.v1.HealthCheckResponse.ServingStatus) SubchannelStateListener(io.grpc.LoadBalancer.SubchannelStateListener) Server(io.grpc.Server) LoadBalancer(io.grpc.LoadBalancer) Helper(io.grpc.LoadBalancer.Helper) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) ManagedChannel(io.grpc.ManagedChannel) ResolvedAddresses(io.grpc.LoadBalancer.ResolvedAddresses) Before(org.junit.Before)

Example 50 with Server

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

the class ProtoReflectionServiceTest method sharedServiceBetweenServers.

@Test
public void sharedServiceBetweenServers() throws IOException, ExecutionException, InterruptedException {
    Server anotherServer = InProcessServerBuilder.forName("proto-reflection-test-2").directExecutor().addService(reflectionService).addService(new AnotherReflectableServiceGrpc.AnotherReflectableServiceImplBase() {
    }).build().start();
    grpcCleanupRule.register(anotherServer);
    ManagedChannel anotherChannel = grpcCleanupRule.register(InProcessChannelBuilder.forName("proto-reflection-test-2").directExecutor().build());
    ServerReflectionGrpc.ServerReflectionStub stub2 = ServerReflectionGrpc.newStub(anotherChannel);
    ServerReflectionRequest request = ServerReflectionRequest.newBuilder().setHost(TEST_HOST).setListServices("services").build();
    StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create();
    StreamObserver<ServerReflectionRequest> requestObserver = stub2.serverReflectionInfo(responseObserver);
    requestObserver.onNext(request);
    requestObserver.onCompleted();
    List<ServiceResponse> response = responseObserver.firstValue().get().getListServicesResponse().getServiceList();
    assertEquals(new HashSet<>(Arrays.asList(ServiceResponse.newBuilder().setName("grpc.reflection.v1alpha.ServerReflection").build(), ServiceResponse.newBuilder().setName("grpc.reflection.testing.AnotherReflectableService").build())), new HashSet<>(response));
}
Also used : Server(io.grpc.Server) ServerReflectionRequest(io.grpc.reflection.v1alpha.ServerReflectionRequest) ServiceResponse(io.grpc.reflection.v1alpha.ServiceResponse) AnotherReflectableServiceGrpc(io.grpc.reflection.testing.AnotherReflectableServiceGrpc) ManagedChannel(io.grpc.ManagedChannel) ServerReflectionGrpc(io.grpc.reflection.v1alpha.ServerReflectionGrpc) ServerReflectionResponse(io.grpc.reflection.v1alpha.ServerReflectionResponse) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)76 Server (io.grpc.Server)68 IOException (java.io.IOException)27 ByteString (org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString)24 ArrayList (java.util.ArrayList)21 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)21 ExecutionException (java.util.concurrent.ExecutionException)20 TimeoutException (java.util.concurrent.TimeoutException)20 CountDownLatch (java.util.concurrent.CountDownLatch)19 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)19 Server (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Server)18 StatusException (io.grpc.StatusException)17 Metadata (io.grpc.Metadata)12 List (java.util.List)12 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)12 FilterChain (io.grpc.xds.EnvoyServerProtoData.FilterChain)11 ExecutorService (java.util.concurrent.ExecutorService)11 ParallelInstruction (com.google.api.services.dataflow.model.ParallelInstruction)10 ServerCall (io.grpc.ServerCall)10 StreamObserver (io.grpc.stub.StreamObserver)10