public GrpcServerStrategy(GrpcURL providerUrl, Object protocolImpl){ if (protocolImpl instanceof BindableService) { this.exporter = new GrpcStubServerExporter(); this.protocolClass = protocolImpl.getClass(); } else { Class<?> protocol; try { protocol = ReflectUtils.name2class(providerUrl.getServiceInterface()); if (!protocol.isAssignableFrom(protocolImpl.getClass())) { throw new IllegalStateException("protocolClass " + providerUrl.getServiceInterface() + " is not implemented by protocolImpl which is of class " + protocolImpl.getClass()); } } catch (ClassNotFoundException e) { protocol = protocolImpl.getClass(); } this.protocolClass = protocol; this.exporter = new DefaultProxyExporter(providerUrl); } this.protocolImpl = protocolImpl; }
@Test public void getPortReturnsServerPortForRunningServer() throws Exception { final int configPort = ThreadLocalRandom.current().nextInt(1000, 2000); final int serverPort = ThreadLocalRandom.current().nextInt(2000, 3000); final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10); final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000); final ApplicationContext applicationContext = mock(ApplicationContext.class); final Server server = mock(Server.class, new TriesToReturnSelf()); final GrpcServerFactory factory = (p, s) -> server; final Map<String, Object> services = IntStream.range(0, serviceCount) .mapToObj(i -> mock(BindableService.class)) .collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s)); when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services); when(server.getPort()).thenReturn(serverPort); GrpcServerHost runner = new GrpcServerHost(configPort, shutdownWaitTimeInMillis, factory); runner.setApplicationContext(applicationContext); runner.start(); assertThat(runner.getPort()).isEqualTo(serverPort); }
private void loadService() { LOG.info("Load service definition is starting..."); //find and get all ServiceExporter-enabled beans try { getBeanNamesByTypeWithAnnotation(ServiceExporter.class, BindableService.class) .forEach(name->{ BindableService srv = SpringContainer.getContext().getBeanFactory().getBean(name, BindableService.class); ServerServiceDefinition serviceDefinition = srv.bindService(); //GRpcService gRpcServiceAnn = SpringContainer.getContext().findAnnotationOnBean(name, ServiceExporter.class); //serviceDefinition = bindInterceptors(serviceDefinition,gRpcServiceAnn,globalInterceptors); //serverBuilder.addService(serviceDefinition); //log.info("'{}' service has been registered.", srv.getClass().getName()); services.add(new GrpcServiceDefinition(serviceDefinition)); }); } catch (Exception e) { LOG.warn("Exception happened when loading all service definitions", e); } LOG.info("Load service denifition is finished, total {} service are found.", services.size()); }
@Override public Collection<GrpcServiceDefinition> findGrpcServices() { Collection<String> beanNames = findGrpcServiceBeanNames(); List<GrpcServiceDefinition> definitions = new ArrayList<GrpcServiceDefinition>( beanNames.size()); for (String beanName : beanNames) { Object bean = this.applicationContext.getBean(beanName); Class<?> beanClazz = bean.getClass(); if (!BindableService.class.isAssignableFrom(beanClazz)) { throw new IllegalStateException(beanClazz.getName() + " does not seem to extend a generated base implementation nor implements BindableService"); } definitions.add(new GrpcServiceDefinition(beanName, (BindableService) bean)); } return definitions; }
@Override public ServerServiceDefinition export(Class<?> protocol, Object protocolImpl) { Object obj = protocolImpl; if (!(obj instanceof BindableService)) { throw new IllegalStateException(" Object is not io.grpc.BindableService,can not export " + obj); } else { BindableService bindableService = (BindableService) obj; log.info("'{}' service has been registered.", bindableService.getClass().getName()); return bindableService.bindService(); } }
@Override public Server buildServerForServices(int port, Collection<BindableService> services) { ServerBuilder builder = ServerBuilder.forPort(port); setupServer(builder); services.forEach(service -> registerService(builder, service)); return builder.build(); }
/** * Start the gRPC {@link Server}. * * @throws IOException if unable to bind to server address or port * @throws IllegalStateException if any non-{@link BindableService} classes are annotated with {@link GrpcService} */ public void start() throws IOException { if (serverFactory == null) { serverFactory = findServerFactory(); } final Collection<BindableService> services = getServicesFromApplicationContext(); if (services.isEmpty()) { throw new IOException("gRPC server not started because no services were found in the application context."); } server = serverFactory.buildServerForServices(port, services); server.start(); }
private Collection<BindableService> getServicesFromApplicationContext() { Map<String, Object> possibleServices = new HashMap<>(); for (Class<? extends Annotation> annotation : serverFactory.forAnnotations()) { possibleServices.putAll(applicationContext.getBeansWithAnnotation(annotation)); } Collection<String> invalidServiceNames = possibleServices.entrySet().stream() .filter(e -> !(e.getValue() instanceof BindableService)) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!invalidServiceNames.isEmpty()) { throw new IllegalStateException((format( "The following beans are annotated with @GrpcService, but are not BindableServices: %s", String.join(", ", invalidServiceNames)))); } return possibleServices.values().stream().map(s -> (BindableService) s).collect(Collectors.toList()); }
@Test public void startStartsServerWithServices() throws Exception { final int port = ThreadLocalRandom.current().nextInt(1000, 10000); final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10); final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000); final ApplicationContext applicationContext = mock(ApplicationContext.class); final Server server = mock(Server.class, new TriesToReturnSelf()); when(server.getPort()).thenReturn(port); final Map<String, Object> services = IntStream.range(0, serviceCount) .mapToObj(i -> mock(BindableService.class)) .collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s)); AtomicBoolean built = new AtomicBoolean(false); GrpcServerFactory fakeFactory = (p, s) -> { built.set(true); assertThat(p).isEqualTo(port); s.forEach(ss -> assertThat(services.values().contains(ss)).isTrue()); return server; }; when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services); GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis, fakeFactory); runner.setApplicationContext(applicationContext); runner.start(); assertThat(built.get()).isTrue(); verify(server).start(); assertThat(runner.server()).isEqualTo(server); }
@Override public Server allocatePortAndCreate(BindableService service, ApiServiceDescriptor.Builder builder) throws IOException { String name = String.format("InProcessServer_%s", serviceNameUniqifier.getAndIncrement()); builder.setUrl(name); return InProcessServerBuilder.forName(name).addService(service).build().start(); }
@Override public Server create(BindableService service, ApiServiceDescriptor serviceDescriptor) throws IOException { return InProcessServerBuilder.forName(serviceDescriptor.getUrl()) .addService(service) .build() .start(); }
@Override public Server allocatePortAndCreate( BindableService service, Endpoints.ApiServiceDescriptor.Builder apiServiceDescriptor) throws IOException { InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); Server server = createServer(service, address); apiServiceDescriptor.setUrl( HostAndPort.fromParts(address.getHostName(), server.getPort()).toString()); return server; }
@Override public Server create(BindableService service, Endpoints.ApiServiceDescriptor serviceDescriptor) throws IOException { SocketAddress socketAddress = SocketAddressFactory.createFrom(serviceDescriptor.getUrl()); checkArgument( socketAddress instanceof InetSocketAddress, "%s %s requires a host:port socket address, got %s", getClass().getSimpleName(), ServerFactory.class.getSimpleName(), serviceDescriptor.getUrl()); return createServer(service, (InetSocketAddress) socketAddress); }
private static Server createServer(BindableService service, InetSocketAddress socket) throws IOException { Server server = NettyServerBuilder.forPort(socket.getPort()) .addService(service) // Set the message size to max value here. The actual size is governed by the // buffer size in the layers above. .maxMessageSize(Integer.MAX_VALUE) .build(); server.start(); return server; }
@Override public DropwizardServerBuilder addService(final BindableService bindableService) { // TODO configure io.grpc.ServerInterceptor to collect dropwizard metrics // TODO configure io.grpc.ServerInterceptor to send rpc call and exception events to logback origin.addService(bindableService); return this; }
/** * Check if the given gRPC service is scheduled for the deployment in this container. * * <p>Note, that the given gRPC service will become available to the clients, * once the gRPC container is started. * * <p>To find out, whether the service is already available for calls, * use {@link #isLive(BindableService)} method. * * @param service the gRPC service to check * @return {@code true}, if the given gRPC service for deployment; {@code false} otherwise */ public boolean isScheduledForDeployment(BindableService service) { final String nameOfInterest = service.bindService() .getServiceDescriptor() .getName(); boolean serviceIsPresent = false; for (ServerServiceDefinition serverServiceDefinition : services) { final String scheduledServiceName = serverServiceDefinition.getServiceDescriptor() .getName(); serviceIsPresent = serviceIsPresent || scheduledServiceName.equals(nameOfInterest); } return serviceIsPresent; }
@SuppressWarnings("MagicNumber") @Test public void add_and_remove_parameters_from_builder() { final GrpcContainer.Builder builder = GrpcContainer.newBuilder() .setPort(8080) .setPort(60); assertEquals(60, builder.getPort()); int count = 3; final List<ServerServiceDefinition> definitions = new ArrayList<>(count); for (int i = 0; i < count; i++) { final BindableService mockService = mock(BindableService.class); final ServerServiceDefinition mockDefinition = ServerServiceDefinition .builder(format("service-%s", i)) .build(); when(mockService.bindService()).thenReturn(mockDefinition); definitions.add(mockDefinition); builder.addService(mockService); } count--; // Perform removal and check that the return value is builder itself. assertEquals(builder, builder.removeService(definitions.get(count))); final Set<ServerServiceDefinition> serviceSet = builder.getServices(); assertSize(count, serviceSet); final GrpcContainer container = builder.build(); assertNotNull(container); }
/** * Register Host Service, Used for unit testing purposes. * * @return An instance of binding Host service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(HostServiceNBServerInternal.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
/** * Register Application Service, Used for unit testing purposes. * * @return An instance of binding Application service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(GrpcNbApplicationService.ApplicationServiceNbServerInternal.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
/** * Register Device Service, Used for unit testing purposes. * * @return An instance of binding Device service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(GrpcNbDeviceService.DeviceServiceNbServerInternal.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
/** * Register ComponentConfig Service, Used for unit testing purposes. * * @return An instance of binding ComponentConfig service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(ComponentConfigServiceNbServerInternal.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
/** * Register Link Service, used for unit testing purposes. * * @return An instance of binding Link service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(LinkServiceNb.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
/** * Register Region Service, used for unit testing purposes. * * @return An instance of binding Region service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(GrpcNbRegionService.RegionServiceNbServerInternal.class); inprocessServer.addServiceToBind(getInnerClassInstance()); return inprocessServer; }
/** * Register Mastership Service, used for unit testing purposes. * * @return an instance of binding Mastership service */ public InProcessServer<BindableService> registerInProcessServer() { InProcessServer<BindableService> inprocessServer = new InProcessServer(GrpcNbMastershipService.MastershipServiceNbServerInternal.class); inprocessServer.addServiceToBind(getInnerInstance()); return inprocessServer; }
@Override public boolean register(BindableService service) { synchronized (registeredServices) { if (!registeredServices.containsKey(service.getClass())) { registeredServices.put(service.getClass(), service); } else { log.warn("The specified class \"{}\" was not added becuase an " + "instance of the class is already registered.", service.getClass().toString()); return false; } } return restartServer(listeningPort); }
@Override public boolean unregister(BindableService service) { synchronized (registeredServices) { if (registeredServices.containsKey(service.getClass())) { registeredServices.remove(service.getClass()); } else { log.warn("The specified class \"{}\" was not removed because it " + "was not present.", service.getClass().toString()); return false; } } return restartServer(listeningPort); }
@Override public final T addService(BindableService bindableService) { if (bindableService instanceof InternalNotifyOnServerBuild) { notifyOnBuildList.add((InternalNotifyOnServerBuild) bindableService); } return addService(bindableService.bindService()); }
@Test public void simpleLookupWithBindable() { BindableService bindableService = new BindableService() { @Override public ServerServiceDefinition bindService() { return basicServiceDefinition; } }; assertNull(registry.addService(bindableService)); ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/flow"); assertSame(flowMethodDefinition, method); }
GrpcStartable(int port, BindableService... services) { ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port); Arrays.stream(services).forEach(serverBuilder::addService); server = serverBuilder.build(); }
public NodeServer(List<BindableService> bindableServices, ChannelServerProperties properties, EthereumConfig ethereumConfig, ContractsManagerFactory factory) { this.bindableServices = bindableServices; this.properties = properties; this.ethereumConfig = ethereumConfig; this.factory = factory; }
/** The gRPC services to bind. */ List<BindableService> services();
@Multibinds abstract Set<BindableService> grpcServices();
/** * Override this method to override how a {@link BindableService} is added to the {@link ServerBuilder}. */ protected void registerService(ServerBuilder builder, BindableService service) { builder.addService(service); }
public GrpcServiceDefinition(String beanName, BindableService service) { this.beanName = beanName; this.service = service; }
public BindableService getService() { return service; }
static Server newServer(BindableService service) { return NettyServerBuilder .forPort(1234) .addService(service) .build(); }
public Builder addService(BindableService service) { serviceDefinitions.add(service.bindService()); return this; }
@Override public boolean containsService(Class<BindableService> serviceClass) { return registeredServices.containsKey(serviceClass); }
public static BindableService newInstance() { return new ProtoReflectionService(); }
/** * Gets the health check service created in the constructor. */ public BindableService getHealthService() { return healthService; }