Search in sources :

Example 36 with Channel

use of io.grpc.Channel in project toolkit by googleapis.

the class Pubsub method gapic.

private static void gapic(final Settings settings) throws Exception {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // In real clients, InstantiatingChannelProvider is responsible for adding interceptors.
    // We can't use it here because InstantiatingChannelProvider doesn't have sslContext method.
    // Instead, we imitate HeaderInterceptor.
    ClientInterceptor headerInterceptor = new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
            return new SimpleForwardingClientCall<ReqT, RespT>(call) {

                @Override
                public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    headers.put(X_GOOG_HEADER_KEY, X_GOOG_HEADER_VALUE);
                    super.start(responseListener, headers);
                }
            };
        }
    };
    ManagedChannel channel = NettyChannelBuilder.forTarget(settings.endpoint()).executor(executor).sslContext(GrpcSslContexts.forClient().trustManager(new File(settings.cert())).build()).intercept(headerInterceptor).build();
    final Semaphore semaphore = new Semaphore(settings.numWorkers());
    final TopicAdminClient client = TopicAdminClient.create(TopicAdminSettings.defaultBuilder().setChannelProvider(FixedChannelProvider.create(channel)).setExecutorProvider(FixedExecutorProvider.create(executor)).build());
    final AtomicLong resetTime = new AtomicLong();
    final AtomicLong numCalls = new AtomicLong();
    final AtomicLong numErrs = new AtomicLong();
    long endTime = System.nanoTime() + settings.warmDurNano() + settings.targetDurNano();
    Thread resetter = new Thread(() -> {
        try {
            Thread.sleep(settings.warmDurNano() / MILLION);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        numCalls.set(0);
        numErrs.set(0);
        resetTime.set(System.nanoTime());
    });
    resetter.start();
    while (System.nanoTime() < endTime) {
        semaphore.acquire(1);
        ApiFutures.addCallback(client.getTopicCallable().futureCall(GetTopicRequest.newBuilder().setTopicWithTopicName(TOPIC_NAME_RESOURCE).build()), new ApiFutureCallback<Topic>() {

            @Override
            public void onSuccess(Topic topic) {
                if (!topic.getName().equals(TOPIC_NAME_STRING)) {
                    numErrs.incrementAndGet();
                }
                both();
            }

            @Override
            public void onFailure(Throwable t) {
                numErrs.incrementAndGet();
                both();
            }

            void both() {
                numCalls.incrementAndGet();
                semaphore.release(1);
            }
        });
    }
    long nCalls = numCalls.get();
    long nErrs = numErrs.get();
    long runDurNano = System.nanoTime() - resetTime.get();
    System.out.println("errors: " + nErrs);
    System.out.println("calls: " + nCalls);
    System.out.println("time per call (ns): " + (runDurNano / nCalls));
    System.out.println("QPS: " + (nCalls * BILLION / runDurNano));
    client.close();
    channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
}
Also used : ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Semaphore(java.util.concurrent.Semaphore) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) TopicAdminClient(com.google.cloud.pubsub.spi.v1.TopicAdminClient) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) Topic(com.google.pubsub.v1.Topic) File(java.io.File) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 37 with Channel

use of io.grpc.Channel in project incubator-skywalking by apache.

the class AppAndServiceRegisterClient method statusChanged.

@Override
public void statusChanged(GRPCChannelStatus status) {
    if (GRPCChannelStatus.CONNECTED.equals(status)) {
        Channel channel = ServiceManager.INSTANCE.findService(GRPCChannelManager.class).getChannel();
        applicationRegisterServiceBlockingStub = ApplicationRegisterServiceGrpc.newBlockingStub(channel);
        instanceDiscoveryServiceBlockingStub = InstanceDiscoveryServiceGrpc.newBlockingStub(channel);
        serviceNameDiscoveryServiceBlockingStub = ServiceNameDiscoveryServiceGrpc.newBlockingStub(channel);
        networkAddressRegisterServiceBlockingStub = NetworkAddressRegisterServiceGrpc.newBlockingStub(channel);
    } else {
        applicationRegisterServiceBlockingStub = null;
        instanceDiscoveryServiceBlockingStub = null;
        serviceNameDiscoveryServiceBlockingStub = null;
    }
    this.status = status;
}
Also used : Channel(io.grpc.Channel)

Example 38 with Channel

use of io.grpc.Channel in project incubator-skywalking by apache.

the class TraceSegmentServiceClient method statusChanged.

@Override
public void statusChanged(GRPCChannelStatus status) {
    if (CONNECTED.equals(status)) {
        Channel channel = ServiceManager.INSTANCE.findService(GRPCChannelManager.class).getChannel();
        serviceStub = TraceSegmentServiceGrpc.newStub(channel);
    }
    this.status = status;
}
Also used : Channel(io.grpc.Channel)

Example 39 with Channel

use of io.grpc.Channel in project thingsboard by thingsboard.

the class RpcSessionActor method initSession.

private void initSession(RpcSessionCreateRequestMsg msg) {
    log.info("[{}] Initializing session", context().self());
    ServerAddress remoteServer = msg.getRemoteAddress();
    listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self());
    if (msg.getRemoteAddress() == null) {
        // Server session
        session = new GrpcSession(listener);
        session.setOutputStream(msg.getResponseObserver());
        session.initInputStream();
        session.initOutputStream();
        systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream());
    } else {
        // Client session
        Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort()).usePlaintext(true).build();
        session = new GrpcSession(remoteServer, listener);
        session.initInputStream();
        ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel);
        StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub.handlePluginMsgs(session.getInputStream());
        session.setOutputStream(outputStream);
        session.initOutputStream();
        outputStream.onNext(toConnectMsg());
    }
}
Also used : GrpcSession(org.thingsboard.server.service.cluster.rpc.GrpcSession) Channel(io.grpc.Channel) ServerAddress(org.thingsboard.server.common.msg.cluster.ServerAddress) ClusterRpcServiceGrpc(org.thingsboard.server.gen.cluster.ClusterRpcServiceGrpc)

Example 40 with Channel

use of io.grpc.Channel in project dble by actiontech.

the class AlarmAppender method append.

@Override
public void append(LogEvent event) {
    if (stub == null && DbleStartup.isInitZKend()) {
        // only if the dbleserver init config file finished than the config can be use for alert
        try {
            AlarmConfig config = DbleServer.getInstance().getConfig().getAlarm();
            if (config != null && config.getUrl() != null) {
                grpcLevel = "error".equalsIgnoreCase(config.getLevel()) ? 200 : 300;
                serverId = config.getServerId();
                port = Integer.parseInt(config.getPort());
                grpcUrl = config.getUrl();
                alertComponentId = config.getComponentId();
                ushardCode = config.getComponentType();
                Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel);
            }
        } catch (Exception e) {
            // config not ready yeat
            return;
        }
    }
    if (stub != null) {
        if (grpcLevel >= event.getLevel().intLevel()) {
            String data = new String(getLayout().toByteArray(event));
            String[] d = data.split("::");
            if (d.length >= 2) {
                String level = event.getLevel().intLevel() == 300 ? "WARN" : "CRITICAL";
                UcoreInterface.AlertInput inpurt = UcoreInterface.AlertInput.newBuilder().setCode(d[0]).setDesc(d[1]).setLevel(level).setSourceComponentType(ushardCode).setSourceComponentId(alertComponentId).setAlertComponentId(alertComponentId).setAlertComponentType(ushardCode).setServerId(serverId).setTimestampUnix(System.currentTimeMillis() * 1000000).build();
                stub.alert(inpurt);
            }
        }
    }
}
Also used : Channel(io.grpc.Channel) UcoreInterface(com.actiontech.dble.log.alarm.UcoreInterface) AlarmConfig(com.actiontech.dble.config.model.AlarmConfig)

Aggregations

Channel (io.grpc.Channel)60 CallOptions (io.grpc.CallOptions)37 Test (org.junit.Test)33 Metadata (io.grpc.Metadata)25 MethodDescriptor (io.grpc.MethodDescriptor)20 ClientInterceptor (io.grpc.ClientInterceptor)19 ManagedChannel (io.grpc.ManagedChannel)17 ClientCall (io.grpc.ClientCall)14 SocketAddress (java.net.SocketAddress)8 ByteString (com.google.protobuf.ByteString)7 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)7 NoopClientCall (io.grpc.internal.NoopClientCall)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 Duration (com.google.protobuf.Duration)5 ChannelLogger (io.grpc.ChannelLogger)5 Status (io.grpc.Status)5 ClientStreamTracer (io.grpc.ClientStreamTracer)4 ForwardingClientCall (io.grpc.ForwardingClientCall)4 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)4 Subchannel (io.grpc.LoadBalancer.Subchannel)4