Search in sources :

Example 1 with TagValue

use of io.opencensus.tags.TagValue in project instrumentation-java by census-instrumentation.

the class StatszZPageHandlerTest method assertContainsViewData.

private static void assertContainsViewData(OutputStream output, ViewData viewData) {
    View view = viewData.getView();
    assertThat(output.toString()).contains(view.getName().asString());
    assertThat(output.toString()).contains(view.getDescription());
    assertThat(output.toString()).contains(view.getMeasure().getName());
    for (TagKey tagKey : view.getColumns()) {
        assertThat(output.toString()).contains(tagKey.getName());
    }
    String aggregationType = view.getAggregation().match(Functions.returnConstant("Sum"), Functions.returnConstant("Count"), Functions.returnConstant("Distribution"), Functions.returnConstant("Last Value"), new Function<Aggregation, String>() {

        @Override
        public String apply(Aggregation arg) {
            if (arg instanceof Aggregation.Mean) {
                return "Mean";
            }
            throw new AssertionError();
        }
    });
    assertThat(output.toString()).contains(aggregationType);
    for (Map.Entry<List<TagValue>, AggregationData> /*@Nullable*/
    entry : viewData.getAggregationMap().entrySet()) {
        List<TagValue> tagValues = entry.getKey();
        for (TagValue tagValue : tagValues) {
            String tagValueStr = tagValue == null ? "" : tagValue.asString();
            assertThat(output.toString()).contains(tagValueStr);
        }
        entry.getValue().match(Functions.</*@Nullable*/
        Void>throwAssertionError(), Functions.</*@Nullable*/
        Void>throwAssertionError(), Functions.</*@Nullable*/
        Void>throwAssertionError(), new Function<AggregationData.DistributionData, Void>() {

            @Override
            public Void apply(AggregationData.DistributionData arg) {
                assertThat(output.toString()).contains(String.valueOf(arg.getCount()));
                assertThat(output.toString()).contains(String.valueOf(arg.getMax()));
                assertThat(output.toString()).contains(String.valueOf(arg.getMin()));
                assertThat(output.toString()).contains(String.valueOf(arg.getMean()));
                assertThat(output.toString()).contains(String.valueOf(arg.getSumOfSquaredDeviations()));
                return null;
            }
        }, Functions.</*@Nullable*/
        Void>throwAssertionError(), Functions.</*@Nullable*/
        Void>throwAssertionError(), new Function<AggregationData, Void>() {

            @Override
            public Void apply(AggregationData arg) {
                if (arg instanceof MeanData) {
                    MeanData meanData = (MeanData) arg;
                    assertThat(output.toString()).contains(String.valueOf(meanData.getCount()));
                    assertThat(output.toString()).contains(String.valueOf(meanData.getMean()));
                    return null;
                }
                throw new AssertionError();
            }
        });
    }
}
Also used : AggregationData(io.opencensus.stats.AggregationData) MeanData(io.opencensus.stats.AggregationData.MeanData) View(io.opencensus.stats.View) Aggregation(io.opencensus.stats.Aggregation) TagKey(io.opencensus.tags.TagKey) List(java.util.List) TagValue(io.opencensus.tags.TagValue) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 2 with TagValue

use of io.opencensus.tags.TagValue in project instrumentation-java by census-instrumentation.

the class StatsRecorderImplTest method record_CurrentContextNotSet.

@Test
public void record_CurrentContextNotSet() {
    View view = View.create(VIEW_NAME, "description", MEASURE_DOUBLE, Sum.create(), Arrays.asList(KEY), Cumulative.create());
    viewManager.registerView(view);
    statsRecorder.newMeasureMap().put(MEASURE_DOUBLE, 1.0).record();
    ViewData viewData = viewManager.getView(VIEW_NAME);
    // record() should have used the default TagContext, so the tag value should be null.
    assertThat(viewData.getAggregationMap().keySet()).containsExactly(Arrays.asList((TagValue) null));
}
Also used : StatsTestUtil.createEmptyViewData(io.opencensus.implcore.stats.StatsTestUtil.createEmptyViewData) ViewData(io.opencensus.stats.ViewData) TagValue(io.opencensus.tags.TagValue) View(io.opencensus.stats.View) Test(org.junit.Test)

Example 3 with TagValue

use of io.opencensus.tags.TagValue in project instrumentation-java by census-instrumentation.

the class RpczZPageHandler method getStatsSnapshots.

private void getStatsSnapshots(Map<String, StatsSnapshot> map, List<View> views) {
    for (View view : views) {
        ViewData viewData = viewManager.getView(view.getName());
        if (viewData == null) {
            continue;
        }
        for (Entry<List<TagValue>, AggregationData> /*@Nullable*/
        entry : viewData.getAggregationMap().entrySet()) {
            TagValue tagValue;
            List<TagValue> /*@Nullable*/
            tagValues = entry.getKey();
            if (tagValues.size() == 1) {
                tagValue = tagValues.get(0);
            } else {
                // Error count views have two tag key: status and method.
                tagValue = tagValues.get(1);
            }
            String method = tagValue == null ? "" : tagValue.asString();
            StatsSnapshot snapshot = map.get(method);
            if (snapshot == null) {
                snapshot = new StatsSnapshot();
                map.put(method, snapshot);
            }
            getStats(snapshot, entry.getValue(), view, viewData.getWindowData());
        }
    }
}
Also used : ViewData(io.opencensus.stats.ViewData) AggregationData(io.opencensus.stats.AggregationData) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) TagValue(io.opencensus.tags.TagValue) View(io.opencensus.stats.View)

Example 4 with TagValue

use of io.opencensus.tags.TagValue in project grpc-java by grpc.

the class CensusModulesTest method subtestClientBasicStatsDefaultContext.

private void subtestClientBasicStatsDefaultContext(boolean recordStarts, boolean recordFinishes, boolean recordRealTime) {
    CensusStatsModule localCensusStats = new CensusStatsModule(tagger, tagCtxSerializer, statsRecorder, fakeClock.getStopwatchSupplier(), true, recordStarts, recordFinishes, recordRealTime, true);
    CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory = new CensusStatsModule.CallAttemptsTracerFactory(localCensusStats, tagger.empty(), method.getFullMethodName());
    Metadata headers = new Metadata();
    ClientStreamTracer tracer = callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, headers);
    if (recordStarts) {
        StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
        assertNotNull(record);
        assertNoServerContent(record);
        assertEquals(1, record.tags.size());
        TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
        assertEquals(method.getFullMethodName(), methodTag.asString());
        assertEquals(1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
    } else {
        assertNull(statsRecorder.pollRecord());
    }
    fakeClock.forwardTime(30, MILLISECONDS);
    tracer.outboundHeaders();
    fakeClock.forwardTime(100, MILLISECONDS);
    tracer.outboundMessage(0);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, true);
    tracer.outboundWireSize(1028);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 1028, recordRealTime, true);
    tracer.outboundUncompressedSize(1128);
    fakeClock.forwardTime(16, MILLISECONDS);
    tracer.inboundMessage(0);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, true);
    tracer.inboundWireSize(33);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, 33, recordRealTime, true);
    tracer.inboundUncompressedSize(67);
    tracer.outboundMessage(1);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, true);
    tracer.outboundWireSize(99);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 99, recordRealTime, true);
    tracer.outboundUncompressedSize(865);
    fakeClock.forwardTime(24, MILLISECONDS);
    tracer.inboundMessage(1);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, true);
    tracer.inboundWireSize(154);
    assertRealTimeMetric(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, 154, recordRealTime, true);
    tracer.inboundUncompressedSize(552);
    tracer.streamClosed(Status.OK);
    callAttemptsTracerFactory.callEnded(Status.OK);
    if (recordFinishes) {
        StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
        assertNotNull(record);
        assertNoServerContent(record);
        TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
        assertEquals(method.getFullMethodName(), methodTag.asString());
        TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
        assertEquals(Status.Code.OK.toString(), statusTag.asString());
        assertEquals(1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
        assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
        assertEquals(2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
        assertEquals(1028 + 99, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
        assertEquals(1128 + 865, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
        assertEquals(2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
        assertEquals(33 + 154, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
        assertEquals(67 + 552, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
        assertEquals(30 + 100 + 16 + 24, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
        assertZeroRetryRecorded();
    } else {
        assertNull(statsRecorder.pollRecord());
    }
}
Also used : ClientStreamTracer(io.grpc.ClientStreamTracer) StatsTestUtils(io.grpc.internal.testing.StatsTestUtils) Metadata(io.grpc.Metadata) TagValue(io.opencensus.tags.TagValue) CallAttemptsTracerFactory(io.grpc.census.CensusTracingModule.CallAttemptsTracerFactory)

Example 5 with TagValue

use of io.opencensus.tags.TagValue in project grpc-java by grpc.

the class CensusModulesTest method testClientInterceptors.

// Test that Census ClientInterceptors uses the TagContext and Span out of the current Context
// to create the ClientCallTracer, and that it intercepts ClientCall.Listener.onClose() to call
// ClientCallTracer.callEnded().
private void testClientInterceptors(boolean nonDefaultContext) {
    grpcServerRule.getServiceRegistry().addService(ServerServiceDefinition.builder("package1.service2").addMethod(method, new ServerCallHandler<String, String>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, String> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.sendMessage("Hello");
            call.close(Status.PERMISSION_DENIED.withDescription("No you don't"), new Metadata());
            return mockServerCallListener;
        }
    }).build());
    final AtomicReference<CallOptions> capturedCallOptions = new AtomicReference<>();
    ClientInterceptor callOptionsCaptureInterceptor = new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            capturedCallOptions.set(callOptions);
            return next.newCall(method, callOptions);
        }
    };
    Channel interceptedChannel = ClientInterceptors.intercept(grpcServerRule.getChannel(), callOptionsCaptureInterceptor, censusStats.getClientInterceptor(), censusTracing.getClientInterceptor());
    ClientCall<String, String> call;
    if (nonDefaultContext) {
        Context ctx = io.opencensus.tags.unsafe.ContextUtils.withValue(Context.ROOT, tagger.emptyBuilder().putLocal(StatsTestUtils.EXTRA_TAG, TagValue.create("extra value")).build());
        ctx = ContextUtils.withValue(ctx, fakeClientParentSpan);
        Context origCtx = ctx.attach();
        try {
            call = interceptedChannel.newCall(method, CALL_OPTIONS);
        } finally {
            ctx.detach(origCtx);
        }
    } else {
        assertEquals(io.opencensus.tags.unsafe.ContextUtils.getValue(Context.ROOT), io.opencensus.tags.unsafe.ContextUtils.getValue(Context.current()));
        assertEquals(ContextUtils.getValue(Context.current()), BlankSpan.INSTANCE);
        call = interceptedChannel.newCall(method, CALL_OPTIONS);
    }
    // The interceptor adds tracer factory to CallOptions
    assertEquals("customvalue", capturedCallOptions.get().getOption(CUSTOM_OPTION));
    assertEquals(2, capturedCallOptions.get().getStreamTracerFactories().size());
    assertTrue(capturedCallOptions.get().getStreamTracerFactories().get(0) instanceof CallAttemptsTracerFactory);
    assertTrue(capturedCallOptions.get().getStreamTracerFactories().get(1) instanceof CensusStatsModule.CallAttemptsTracerFactory);
    // Make the call
    Metadata headers = new Metadata();
    call.start(mockClientCallListener, headers);
    StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
    assertNotNull(record);
    TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
    assertEquals(method.getFullMethodName(), methodTag.asString());
    if (nonDefaultContext) {
        TagValue extraTag = record.tags.get(StatsTestUtils.EXTRA_TAG);
        assertEquals("extra value", extraTag.asString());
        assertEquals(2, record.tags.size());
    } else {
        assertNull(record.tags.get(StatsTestUtils.EXTRA_TAG));
        assertEquals(1, record.tags.size());
    }
    if (nonDefaultContext) {
        verify(tracer).spanBuilderWithExplicitParent(eq("Sent.package1.service2.method3"), same(fakeClientParentSpan));
        verify(spyClientSpanBuilder).setRecordEvents(eq(true));
    } else {
        verify(tracer).spanBuilderWithExplicitParent(eq("Sent.package1.service2.method3"), ArgumentMatchers.<Span>isNotNull());
        verify(spyClientSpanBuilder).setRecordEvents(eq(true));
    }
    verify(spyClientSpan, never()).end(any(EndSpanOptions.class));
    // End the call
    call.halfClose();
    call.request(1);
    verify(mockClientCallListener).onClose(statusCaptor.capture(), any(Metadata.class));
    Status status = statusCaptor.getValue();
    assertEquals(Status.Code.PERMISSION_DENIED, status.getCode());
    assertEquals("No you don't", status.getDescription());
    // The intercepting listener calls callEnded() on ClientCallTracer, which records to Census.
    record = statsRecorder.pollRecord();
    assertNotNull(record);
    methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
    assertEquals(method.getFullMethodName(), methodTag.asString());
    TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
    assertEquals(Status.Code.PERMISSION_DENIED.toString(), statusTag.asString());
    if (nonDefaultContext) {
        TagValue extraTag = record.tags.get(StatsTestUtils.EXTRA_TAG);
        assertEquals("extra value", extraTag.asString());
    } else {
        assertNull(record.tags.get(StatsTestUtils.EXTRA_TAG));
    }
    verify(spyClientSpan).end(EndSpanOptions.builder().setStatus(io.opencensus.trace.Status.PERMISSION_DENIED.withDescription("No you don't")).setSampleToLocalSpanStore(false).build());
    verify(spyClientSpan, never()).end();
    assertZeroRetryRecorded();
}
Also used : SpanContext(io.opencensus.trace.SpanContext) Context(io.grpc.Context) TagContext(io.opencensus.tags.TagContext) Status(io.grpc.Status) StatsTestUtils(io.grpc.internal.testing.StatsTestUtils) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) EndSpanOptions(io.opencensus.trace.EndSpanOptions) ClientInterceptor(io.grpc.ClientInterceptor) TagValue(io.opencensus.tags.TagValue) CallAttemptsTracerFactory(io.grpc.census.CensusTracingModule.CallAttemptsTracerFactory)

Aggregations

TagValue (io.opencensus.tags.TagValue)22 StatsTestUtils (io.grpc.internal.testing.StatsTestUtils)8 Metadata (io.grpc.Metadata)7 TagKey (io.opencensus.tags.TagKey)7 Test (org.junit.Test)7 ClientStreamTracer (io.grpc.ClientStreamTracer)5 CallAttemptsTracerFactory (io.grpc.census.CensusTracingModule.CallAttemptsTracerFactory)5 Context (io.grpc.Context)4 SpanContext (io.opencensus.trace.SpanContext)4 Status (io.grpc.Status)3 AggregationData (io.opencensus.stats.AggregationData)3 View (io.opencensus.stats.View)3 TagContext (io.opencensus.tags.TagContext)3 CallOptions (io.grpc.CallOptions)2 ServerStreamTracer (io.grpc.ServerStreamTracer)2 MetricsRecord (io.grpc.internal.testing.StatsTestUtils.MetricsRecord)2 TagValueWithMetadata (io.opencensus.implcore.tags.TagValueWithMetadata)2 ViewData (io.opencensus.stats.ViewData)2 List (java.util.List)2 Map (java.util.Map)2