Search in sources :

Example 41 with ManagedChannel

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

the class OcAgentMetricsExporterWorker method connect.

private void connect() {
    ManagedChannelBuilder<?> channelBuilder;
    if (useInsecure) {
        channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext();
    } else {
        channelBuilder = NettyChannelBuilder.forTarget(endPoint).negotiationType(NegotiationType.TLS).sslContext(sslContext);
    }
    ManagedChannel channel = channelBuilder.build();
    MetricsServiceGrpc.MetricsServiceStub stub = MetricsServiceGrpc.newStub(channel);
    exportRpcHandler = OcAgentMetricsServiceExportRpcHandler.create(stub);
    ExportMetricsServiceRequest.Builder builder = ExportMetricsServiceRequest.newBuilder().setNode(OcAgentNodeUtils.getNodeInfo(serviceName));
    @Nullable Resource resourceProto = OcAgentNodeUtils.getAutoDetectedResourceProto();
    if (resourceProto != null) {
        builder.setResource(resourceProto);
    }
    exportRpcHandler.onExport(builder.build());
}
Also used : MetricsServiceGrpc(io.opencensus.proto.agent.metrics.v1.MetricsServiceGrpc) Resource(io.opencensus.proto.resource.v1.Resource) ManagedChannel(io.grpc.ManagedChannel) Nullable(javax.annotation.Nullable) ExportMetricsServiceRequest(io.opencensus.proto.agent.metrics.v1.ExportMetricsServiceRequest)

Example 42 with ManagedChannel

use of io.grpc.ManagedChannel in project alluxio by Alluxio.

the class GrpcConnectionPool method acquireConnection.

/**
 * Acquires and increases the ref-count for the {@link ManagedChannel}.
 *
 * @param channelKey the channel key
 * @param conf the Alluxio configuration
 * @return a {@link GrpcConnection}
 */
public GrpcConnection acquireConnection(GrpcChannelKey channelKey, AlluxioConfiguration conf) {
    // Get a connection key.
    GrpcConnectionKey connectionKey = getConnectionKey(channelKey, conf);
    // Acquire connection.
    CountingReference<ManagedChannel> connectionRef = mChannels.compute(connectionKey, (key, ref) -> {
        boolean shutdownExistingConnection = false;
        int existingRefCount = 0;
        if (ref != null) {
            // Connection exists, wait for health check.
            if (waitForConnectionReady(ref.get(), conf)) {
                LOG.debug("Acquiring an existing connection. ConnectionKey: {}. Ref-count: {}", key, ref.getRefCount());
                return ref.reference();
            } else {
                // Health check failed.
                shutdownExistingConnection = true;
            }
        }
        // Existing connection should shut-down.
        if (shutdownExistingConnection) {
            // TODO(ggezer): Implement GrpcConnectionListener for receiving notification.
            existingRefCount = ref.getRefCount();
            LOG.debug("Shutting down an existing unhealthy connection. " + "ConnectionKey: {}. Ref-count: {}", key, existingRefCount);
            // Shutdown the channel forcefully as it's already unhealthy.
            shutdownManagedChannel(ref.get(), conf);
        }
        // Create a new managed channel.
        LOG.debug("Creating a new managed channel. ConnectionKey: {}. Ref-count:{}", key, existingRefCount);
        ManagedChannel managedChannel = createManagedChannel(channelKey, conf);
        // Set map reference.
        return new CountingReference(managedChannel, existingRefCount).reference();
    });
    // Wrap connection reference and the connection.
    return new GrpcConnection(connectionKey, connectionRef.get(), conf);
}
Also used : ManagedChannel(io.grpc.ManagedChannel)

Example 43 with ManagedChannel

use of io.grpc.ManagedChannel in project beam by apache.

the class ServerFactoryTest method runTestUsing.

private Endpoints.ApiServiceDescriptor runTestUsing(ServerFactory serverFactory, ManagedChannelFactory channelFactory) throws Exception {
    Endpoints.ApiServiceDescriptor.Builder apiServiceDescriptorBuilder = Endpoints.ApiServiceDescriptor.newBuilder();
    final Collection<Elements> serverElements = new ArrayList<>();
    final CountDownLatch clientHangedUp = new CountDownLatch(1);
    CallStreamObserver<Elements> serverInboundObserver = TestStreams.withOnNext(serverElements::add).withOnCompleted(clientHangedUp::countDown).build();
    TestDataService service = new TestDataService(serverInboundObserver);
    Server server = serverFactory.allocateAddressAndCreate(ImmutableList.of(service), apiServiceDescriptorBuilder);
    assertFalse(server.isShutdown());
    ManagedChannel channel = channelFactory.forDescriptor(apiServiceDescriptorBuilder.build());
    BeamFnDataGrpc.BeamFnDataStub stub = BeamFnDataGrpc.newStub(channel);
    final Collection<BeamFnApi.Elements> clientElements = new ArrayList<>();
    final CountDownLatch serverHangedUp = new CountDownLatch(1);
    CallStreamObserver<BeamFnApi.Elements> clientInboundObserver = TestStreams.withOnNext(clientElements::add).withOnCompleted(serverHangedUp::countDown).build();
    StreamObserver<Elements> clientOutboundObserver = stub.data(clientInboundObserver);
    StreamObserver<BeamFnApi.Elements> serverOutboundObserver = service.outboundObservers.take();
    clientOutboundObserver.onNext(CLIENT_DATA);
    serverOutboundObserver.onNext(SERVER_DATA);
    clientOutboundObserver.onCompleted();
    clientHangedUp.await();
    serverOutboundObserver.onCompleted();
    serverHangedUp.await();
    assertThat(clientElements, contains(SERVER_DATA));
    assertThat(serverElements, contains(CLIENT_DATA));
    return apiServiceDescriptorBuilder.build();
}
Also used : ApiServiceDescriptor(org.apache.beam.model.pipeline.v1.Endpoints.ApiServiceDescriptor) Server(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Server) ArrayList(java.util.ArrayList) Elements(org.apache.beam.model.fnexecution.v1.BeamFnApi.Elements) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedChannel(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel) BeamFnDataGrpc(org.apache.beam.model.fnexecution.v1.BeamFnDataGrpc)

Example 44 with ManagedChannel

use of io.grpc.ManagedChannel in project beam by apache.

the class BeamFnLoggingClientTest method testLogging.

@Test
public void testLogging() throws Exception {
    BeamFnLoggingMDC.setInstructionId("instruction-1");
    AtomicBoolean clientClosedStream = new AtomicBoolean();
    Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
    AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver = new AtomicReference<>();
    CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver = TestStreams.withOnNext((BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList())).withOnCompleted(() -> {
        // Remember that the client told us that this stream completed
        clientClosedStream.set(true);
        outboundServerObserver.get().onCompleted();
    }).build();
    Endpoints.ApiServiceDescriptor apiServiceDescriptor = Endpoints.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
    Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {

        @Override
        public StreamObserver<BeamFnApi.LogEntry.List> logging(StreamObserver<BeamFnApi.LogControl> outboundObserver) {
            outboundServerObserver.set(outboundObserver);
            return inboundServerObserver;
        }
    }).build();
    server.start();
    ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
    try {
        BeamFnLoggingClient client = new BeamFnLoggingClient(PipelineOptionsFactory.fromArgs(new String[] { "--defaultSdkHarnessLogLevel=OFF", "--sdkHarnessLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}" }).create(), apiServiceDescriptor, (Endpoints.ApiServiceDescriptor descriptor) -> channel);
        // Keep a strong reference to the loggers in this block. Otherwise the call to client.close()
        // removes the only reference and the logger may get GC'd before the assertions (BEAM-4136).
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        Logger configuredLogger = LogManager.getLogManager().getLogger("ConfiguredLogger");
        // Ensure that log levels were correctly set.
        assertEquals(Level.OFF, rootLogger.getLevel());
        assertEquals(Level.FINE, configuredLogger.getLevel());
        // Should be filtered because the default log level override is OFF
        rootLogger.log(FILTERED_RECORD);
        // Should not be filtered because the default log level override for ConfiguredLogger is DEBUG
        configuredLogger.log(TEST_RECORD);
        configuredLogger.log(TEST_RECORD_WITH_EXCEPTION);
        client.close();
        // Verify that after close, log levels are reset.
        assertEquals(Level.INFO, rootLogger.getLevel());
        assertNull(configuredLogger.getLevel());
        assertTrue(clientClosedStream.get());
        assertTrue(channel.isShutdown());
        assertThat(values, contains(TEST_ENTRY, TEST_ENTRY_WITH_EXCEPTION));
    } finally {
        server.shutdownNow();
    }
}
Also used : CallStreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.CallStreamObserver) StreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver) Server(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Server) BeamFnApi(org.apache.beam.model.fnexecution.v1.BeamFnApi) AtomicReference(java.util.concurrent.atomic.AtomicReference) Logger(java.util.logging.Logger) Endpoints(org.apache.beam.model.pipeline.v1.Endpoints) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedChannel(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.Test)

Example 45 with ManagedChannel

use of io.grpc.ManagedChannel in project beam by apache.

the class BeamFnLoggingClientTest method testWhenServerHangsUpEarlyThatClientIsAbleCleanup.

@Test
public void testWhenServerHangsUpEarlyThatClientIsAbleCleanup() throws Exception {
    BeamFnLoggingMDC.setInstructionId("instruction-1");
    Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
    AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver = new AtomicReference<>();
    CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver = TestStreams.withOnNext((BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList())).build();
    Endpoints.ApiServiceDescriptor apiServiceDescriptor = Endpoints.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
    Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {

        @Override
        public StreamObserver<BeamFnApi.LogEntry.List> logging(StreamObserver<BeamFnApi.LogControl> outboundObserver) {
            outboundServerObserver.set(outboundObserver);
            outboundObserver.onCompleted();
            return inboundServerObserver;
        }
    }).build();
    server.start();
    ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
    try {
        BeamFnLoggingClient client = new BeamFnLoggingClient(PipelineOptionsFactory.fromArgs(new String[] { "--defaultSdkHarnessLogLevel=OFF", "--sdkHarnessLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}" }).create(), apiServiceDescriptor, (Endpoints.ApiServiceDescriptor descriptor) -> channel);
        // Keep a strong reference to the loggers in this block. Otherwise the call to client.close()
        // removes the only reference and the logger may get GC'd before the assertions (BEAM-4136).
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        Logger configuredLogger = LogManager.getLogManager().getLogger("ConfiguredLogger");
        client.close();
        // Verify that after close, log levels are reset.
        assertEquals(Level.INFO, rootLogger.getLevel());
        assertNull(configuredLogger.getLevel());
    } finally {
        assertTrue(channel.isShutdown());
        server.shutdownNow();
    }
}
Also used : CallStreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.CallStreamObserver) StreamObserver(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver) Server(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.Server) BeamFnApi(org.apache.beam.model.fnexecution.v1.BeamFnApi) AtomicReference(java.util.concurrent.atomic.AtomicReference) Logger(java.util.logging.Logger) Endpoints(org.apache.beam.model.pipeline.v1.Endpoints) ManagedChannel(org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.Test)

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