Search in sources :

Example 56 with ManagedChannel

use of io.grpc.ManagedChannel in project grpc-java by grpc.

the class AndroidChannelBuilderTest method nullContextDoesNotThrow_api24.

@Test
@Config(sdk = 24)
public void nullContextDoesNotThrow_api24() {
    shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED);
    TestChannel delegateChannel = new TestChannel();
    ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, null);
    // Network change and shutdown should be no-op for the channel without an Android Context
    shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);
    androidChannel.shutdown();
    assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Test(org.junit.Test) Config(org.robolectric.annotation.Config)

Example 57 with ManagedChannel

use of io.grpc.ManagedChannel in project grpc-java by grpc.

the class AndroidChannelBuilderTest method shutdownNowUnregistersBroadcastReceiver_api23.

@Test
@Config(sdk = 23)
public void shutdownNowUnregistersBroadcastReceiver_api23() {
    TestChannel delegateChannel = new TestChannel();
    ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, ApplicationProvider.getApplicationContext());
    shadowOf(connectivityManager).setActiveNetworkInfo(null);
    ApplicationProvider.getApplicationContext().sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
    androidChannel.shutdownNow();
    shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);
    ApplicationProvider.getApplicationContext().sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
    assertThat(delegateChannel.enterIdleCount).isEqualTo(0);
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Intent(android.content.Intent) Test(org.junit.Test) Config(org.robolectric.annotation.Config)

Example 58 with ManagedChannel

use of io.grpc.ManagedChannel in project grpc-java by grpc.

the class TesterActivity method startTest.

private void startTest(String testCase) {
    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(hostEdit.getWindowToken(), 0);
    enableButtons(false);
    resultText.setText("Testing...");
    String host = hostEdit.getText().toString();
    String portStr = portEdit.getText().toString();
    int port = TextUtils.isEmpty(portStr) ? 8080 : Integer.valueOf(portStr);
    String serverHostOverride;
    InputStream testCert;
    if (testCertCheckBox.isChecked()) {
        serverHostOverride = "foo.test.google.fr";
        testCert = getResources().openRawResource(R.raw.ca);
    } else {
        serverHostOverride = null;
        testCert = null;
    }
    ManagedChannel channel = TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, true, testCert);
    new InteropTask(this, channel, testCase).execute();
}
Also used : InputStream(java.io.InputStream) ManagedChannel(io.grpc.ManagedChannel) InputMethodManager(android.view.inputmethod.InputMethodManager)

Example 59 with ManagedChannel

use of io.grpc.ManagedChannel in project grpc-java by grpc.

the class AbstractManagedChannelImplBuilderTest method buildReturnsDelegateBuildByDefault.

@Test
public void buildReturnsDelegateBuildByDefault() {
    ManagedChannel mockChannel = mock(ManagedChannel.class);
    doReturn(mockChannel).when(mockDelegate).build();
    assertThat(testChannelBuilder.build()).isSameInstanceAs(mockChannel);
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Test(org.junit.Test)

Example 60 with ManagedChannel

use of io.grpc.ManagedChannel 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)

Aggregations

ManagedChannel (io.grpc.ManagedChannel)164 Test (org.junit.Test)92 CountDownLatch (java.util.concurrent.CountDownLatch)26 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)26 ArrayList (java.util.ArrayList)20 Metadata (io.grpc.Metadata)18 EquivalentAddressGroup (io.grpc.EquivalentAddressGroup)15 ExecutorService (java.util.concurrent.ExecutorService)13 ByteString (com.google.protobuf.ByteString)12 Status (io.grpc.Status)12 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)11 StreamObserver (io.grpc.stub.StreamObserver)10 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)10 CallOptions (io.grpc.CallOptions)9 Subchannel (io.grpc.LoadBalancer.Subchannel)9 SubchannelPicker (io.grpc.LoadBalancer.SubchannelPicker)9 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)9 Endpoints (org.apache.beam.model.pipeline.v1.Endpoints)9