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();
}
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();
}
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();
}
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));
}
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));
}
Aggregations