Search in sources :

Example 1 with RpcType

use of io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType in project grpc-java by grpc.

the class XdsTestClient method parseMetadata.

private static EnumMap<RpcType, Metadata> parseMetadata(String metadataArg) {
    EnumMap<RpcType, Metadata> rpcMetadata = new EnumMap<>(RpcType.class);
    for (String metadata : Splitter.on(',').omitEmptyStrings().split(metadataArg)) {
        List<String> parts = Splitter.on(':').splitToList(metadata);
        if (parts.size() != 3) {
            throw new IllegalArgumentException("Invalid metadata: '" + metadata + "'");
        }
        RpcType rpc = parseRpc(parts.get(0));
        String key = parts.get(1);
        String value = parts.get(2);
        Metadata md = new Metadata();
        md.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value);
        if (rpcMetadata.containsKey(rpc)) {
            rpcMetadata.get(rpc).merge(md);
        } else {
            rpcMetadata.put(rpc, md);
        }
    }
    return rpcMetadata;
}
Also used : RpcType(io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType) Metadata(io.grpc.Metadata) EnumMap(java.util.EnumMap)

Example 2 with RpcType

use of io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType in project grpc-java by grpc.

the class XdsTestClient method runQps.

private void runQps() throws InterruptedException, ExecutionException {
    final SettableFuture<Void> failure = SettableFuture.create();
    final class PeriodicRpc implements Runnable {

        @Override
        public void run() {
            List<RpcConfig> configs = rpcConfigs;
            for (RpcConfig cfg : configs) {
                makeRpc(cfg);
            }
        }

        private void makeRpc(final RpcConfig config) {
            final long requestId;
            final Set<XdsStatsWatcher> savedWatchers = new HashSet<>();
            synchronized (lock) {
                currentRequestId += 1;
                requestId = currentRequestId;
                savedWatchers.addAll(watchers);
            }
            ManagedChannel channel = channels.get((int) (requestId % channels.size()));
            TestServiceGrpc.TestServiceStub stub = TestServiceGrpc.newStub(channel);
            final AtomicReference<ClientCall<?, ?>> clientCallRef = new AtomicReference<>();
            final AtomicReference<String> hostnameRef = new AtomicReference<>();
            stub = stub.withDeadlineAfter(config.timeoutSec, TimeUnit.SECONDS).withInterceptors(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);
                    clientCallRef.set(call);
                    return new SimpleForwardingClientCall<ReqT, RespT>(call) {

                        @Override
                        public void start(Listener<RespT> responseListener, Metadata headers) {
                            headers.merge(config.metadata);
                            super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {

                                @Override
                                public void onHeaders(Metadata headers) {
                                    hostnameRef.set(headers.get(XdsTestServer.HOSTNAME_KEY));
                                    super.onHeaders(headers);
                                }
                            }, headers);
                        }
                    };
                }
            });
            if (config.rpcType == RpcType.EMPTY_CALL) {
                stub.emptyCall(EmptyProtos.Empty.getDefaultInstance(), new StreamObserver<EmptyProtos.Empty>() {

                    @Override
                    public void onCompleted() {
                        handleRpcCompleted(requestId, config.rpcType, hostnameRef.get(), savedWatchers);
                    }

                    @Override
                    public void onError(Throwable t) {
                        handleRpcError(requestId, config.rpcType, Status.fromThrowable(t), savedWatchers);
                    }

                    @Override
                    public void onNext(EmptyProtos.Empty response) {
                    }
                });
            } else if (config.rpcType == RpcType.UNARY_CALL) {
                SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build();
                stub.unaryCall(request, new StreamObserver<SimpleResponse>() {

                    @Override
                    public void onCompleted() {
                        handleRpcCompleted(requestId, config.rpcType, hostnameRef.get(), savedWatchers);
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (printResponse) {
                            logger.log(Level.WARNING, "Rpc failed", t);
                        }
                        handleRpcError(requestId, config.rpcType, Status.fromThrowable(t), savedWatchers);
                    }

                    @Override
                    public void onNext(SimpleResponse response) {
                        // service and rely on parsing stdout.
                        if (printResponse) {
                            System.out.println("Greeting: Hello world, this is " + response.getHostname() + ", from " + clientCallRef.get().getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
                        }
                        // TODO(ericgribkoff) Delete when server is deployed that sets metadata value.
                        if (hostnameRef.get() == null) {
                            hostnameRef.set(response.getHostname());
                        }
                    }
                });
            } else {
                throw new AssertionError("Unknown RPC type: " + config.rpcType);
            }
            statsAccumulator.recordRpcStarted(config.rpcType);
        }

        private void handleRpcCompleted(long requestId, RpcType rpcType, String hostname, Set<XdsStatsWatcher> watchers) {
            statsAccumulator.recordRpcFinished(rpcType, Status.OK);
            notifyWatchers(watchers, rpcType, requestId, hostname);
        }

        private void handleRpcError(long requestId, RpcType rpcType, Status status, Set<XdsStatsWatcher> watchers) {
            statsAccumulator.recordRpcFinished(rpcType, status);
            notifyWatchers(watchers, rpcType, requestId, null);
        }
    }
    long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps;
    ListenableScheduledFuture<?> future = exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS);
    Futures.addCallback(future, new FutureCallback<Object>() {

        @Override
        public void onFailure(Throwable t) {
            failure.setException(t);
        }

        @Override
        public void onSuccess(Object o) {
        }
    }, MoreExecutors.directExecutor());
    failure.get();
}
Also used : SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Set(java.util.Set) HashSet(java.util.HashSet) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) HashSet(java.util.HashSet) StreamObserver(io.grpc.stub.StreamObserver) Status(io.grpc.Status) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) RpcType(io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType) AtomicReference(java.util.concurrent.atomic.AtomicReference) MethodDescriptor(io.grpc.MethodDescriptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 3 with RpcType

use of io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType in project grpc-java by grpc.

the class XdsTestClient method parseArgs.

private void parseArgs(String[] args) {
    boolean usage = false;
    List<RpcType> rpcTypes = ImmutableList.of(RpcType.UNARY_CALL);
    EnumMap<RpcType, Metadata> metadata = new EnumMap<>(RpcType.class);
    for (String arg : args) {
        if (!arg.startsWith("--")) {
            System.err.println("All arguments must start with '--': " + arg);
            usage = true;
            break;
        }
        String[] parts = arg.substring(2).split("=", 2);
        String key = parts[0];
        if ("help".equals(key)) {
            usage = true;
            break;
        }
        if (parts.length != 2) {
            System.err.println("All arguments must be of the form --arg=value");
            usage = true;
            break;
        }
        String value = parts[1];
        if ("metadata".equals(key)) {
            metadata = parseMetadata(value);
        } else if ("num_channels".equals(key)) {
            numChannels = Integer.valueOf(value);
        } else if ("print_response".equals(key)) {
            printResponse = Boolean.valueOf(value);
        } else if ("qps".equals(key)) {
            qps = Integer.valueOf(value);
        } else if ("rpc".equals(key)) {
            rpcTypes = parseRpcs(value);
        } else if ("rpc_timeout_sec".equals(key)) {
            rpcTimeoutSec = Integer.valueOf(value);
        } else if ("server".equals(key)) {
            server = value;
        } else if ("stats_port".equals(key)) {
            statsPort = Integer.valueOf(value);
        } else if ("secure_mode".equals(key)) {
            secureMode = Boolean.valueOf(value);
        } else {
            System.err.println("Unknown argument: " + key);
            usage = true;
            break;
        }
    }
    List<RpcConfig> configs = new ArrayList<>();
    for (RpcType type : rpcTypes) {
        Metadata md = new Metadata();
        if (metadata.containsKey(type)) {
            md = metadata.get(type);
        }
        configs.add(new RpcConfig(type, md, rpcTimeoutSec));
    }
    rpcConfigs = Collections.unmodifiableList(configs);
    if (usage) {
        XdsTestClient c = new XdsTestClient();
        System.err.println("Usage: [ARGS...]" + "\n" + "\n  --num_channels=INT     Default: " + c.numChannels + "\n  --print_response=BOOL  Write RPC response to stdout. Default: " + c.printResponse + "\n  --qps=INT              Qps per channel, for each type of RPC. Default: " + c.qps + "\n  --rpc=STR              Types of RPCs to make, ',' separated string. RPCs can " + "be EmptyCall or UnaryCall. Default: UnaryCall" + "\n[deprecated] Use XdsUpdateClientConfigureService" + "\n  --metadata=STR         The metadata to send with each RPC, in the format " + "EmptyCall:key1:value1,UnaryCall:key2:value2." + "\n[deprecated] Use XdsUpdateClientConfigureService" + "\n  --rpc_timeout_sec=INT  Per RPC timeout seconds. Default: " + c.rpcTimeoutSec + "\n  --server=host:port     Address of server. Default: " + c.server + "\n  --secure_mode=BOOLEAN  Use true to enable XdsCredentials. Default: " + c.secureMode + "\n  --stats_port=INT       Port to expose peer distribution stats service. " + "Default: " + c.statsPort);
        System.exit(1);
    }
}
Also used : RpcType(io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType) Metadata(io.grpc.Metadata) ArrayList(java.util.ArrayList) EnumMap(java.util.EnumMap)

Aggregations

Metadata (io.grpc.Metadata)3 RpcType (io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType)3 EnumMap (java.util.EnumMap)2 CallOptions (io.grpc.CallOptions)1 Channel (io.grpc.Channel)1 ClientCall (io.grpc.ClientCall)1 ClientInterceptor (io.grpc.ClientInterceptor)1 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)1 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)1 ManagedChannel (io.grpc.ManagedChannel)1 MethodDescriptor (io.grpc.MethodDescriptor)1 Status (io.grpc.Status)1 StreamObserver (io.grpc.stub.StreamObserver)1 SimpleRequest (io.grpc.testing.integration.Messages.SimpleRequest)1 SimpleResponse (io.grpc.testing.integration.Messages.SimpleResponse)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1