otlpgrpc

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2021 License: Apache-2.0 Imports: 22 Imported by: 47

Documentation

Overview

Package otlpgrpc provides an implementation of otlp.ProtocolDriver that connects to the collector and sends traces and metrics using gRPC.

This package is currently in a pre-GA phase. Backwards incompatible changes may be introduced in subsequent minor version releases as we work to track the evolving OpenTelemetry specification and user feedback.

Example (Insecure)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp"
	"go.opentelemetry.io/otel/exporters/otlp/otlpgrpc"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	ctx := context.Background()
	driver := otlpgrpc.NewDriver(otlpgrpc.WithInsecure())
	exp, err := otlp.NewExporter(ctx, driver)
	if err != nil {
		log.Fatalf("Failed to create the collector exporter: %v", err)
	}
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := exp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()

	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(
			exp,
			// add following two options to ensure flush
			sdktrace.WithBatchTimeout(5*time.Second),
			sdktrace.WithMaxExportBatchSize(10),
		),
	)
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := tp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()
	otel.SetTracerProvider(tp)

	tracer := otel.Tracer("test-tracer")

	// Then use the OpenTelemetry tracing library, like we normally would.
	ctx, span := tracer.Start(ctx, "CollectorExporter-Example")
	defer span.End()

	for i := 0; i < 10; i++ {
		_, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i))
		<-time.After(6 * time.Millisecond)
		iSpan.End()
	}
}
Output:

Example (WithDifferentSignalCollectors)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp"
	"go.opentelemetry.io/otel/exporters/otlp/otlpgrpc"
	"go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/metric/global"

	controller "go.opentelemetry.io/otel/sdk/metric/controller/basic"

	processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
	"go.opentelemetry.io/otel/sdk/metric/selector/simple"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {

	// Set different endpoints for the metrics and traces collectors
	metricsDriver := otlpgrpc.NewDriver(
		otlpgrpc.WithInsecure(),
		otlpgrpc.WithEndpoint("localhost:30080"),
	)
	tracesDriver := otlpgrpc.NewDriver(
		otlpgrpc.WithInsecure(),
		otlpgrpc.WithEndpoint("localhost:30082"),
	)
	splitCfg := otlp.SplitConfig{
		ForMetrics: metricsDriver,
		ForTraces:  tracesDriver,
	}
	driver := otlp.NewSplitDriver(splitCfg)
	ctx := context.Background()
	exp, err := otlp.NewExporter(ctx, driver)
	if err != nil {
		log.Fatalf("failed to create the collector exporter: %v", err)
	}

	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := exp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()

	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(
			exp,
			// add following two options to ensure flush
			sdktrace.WithBatchTimeout(5*time.Second),
			sdktrace.WithMaxExportBatchSize(10),
		),
	)
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := tp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()
	otel.SetTracerProvider(tp)

	pusher := controller.New(
		processor.New(
			simple.NewWithExactDistribution(),
			exp,
		),
		controller.WithExporter(exp),
		controller.WithCollectPeriod(2*time.Second),
	)
	global.SetMeterProvider(pusher.MeterProvider())

	if err := pusher.Start(ctx); err != nil {
		log.Fatalf("could not start metric controoler: %v", err)
	}
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		// pushes any last exports to the receiver
		if err := pusher.Stop(ctx); err != nil {
			otel.Handle(err)
		}
	}()

	tracer := otel.Tracer("test-tracer")
	meter := global.Meter("test-meter")

	// Recorder metric example
	counter := metric.Must(meter).
		NewFloat64Counter(
			"an_important_metric",
			metric.WithDescription("Measures the cumulative epicness of the app"),
		)

	// work begins
	ctx, span := tracer.Start(
		ctx,
		"DifferentCollectors-Example")
	defer span.End()
	for i := 0; i < 10; i++ {
		_, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i))
		log.Printf("Doing really hard work (%d / 10)\n", i+1)
		counter.Add(ctx, 1.0)

		<-time.After(time.Second)
		iSpan.End()
	}

	log.Printf("Done!")
}
Output:

Example (WithTLS)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"google.golang.org/grpc/credentials"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp"
	"go.opentelemetry.io/otel/exporters/otlp/otlpgrpc"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	// Please take at look at https://pkg.go.dev/google.golang.org/grpc/credentials#TransportCredentials
	// for ways on how to initialize gRPC TransportCredentials.
	creds, err := credentials.NewClientTLSFromFile("my-cert.pem", "")
	if err != nil {
		log.Fatalf("failed to create gRPC client TLS credentials: %v", err)
	}

	ctx := context.Background()
	driver := otlpgrpc.NewDriver(otlpgrpc.WithTLSCredentials(creds))
	exp, err := otlp.NewExporter(ctx, driver)
	if err != nil {
		log.Fatalf("failed to create the collector exporter: %v", err)
	}
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := exp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()

	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(
			exp,
			// add following two options to ensure flush
			sdktrace.WithBatchTimeout(5*time.Second),
			sdktrace.WithMaxExportBatchSize(10),
		),
	)
	defer func() {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		if err := tp.Shutdown(ctx); err != nil {
			otel.Handle(err)
		}
	}()
	otel.SetTracerProvider(tp)

	tracer := otel.Tracer("test-tracer")

	// Then use the OpenTelemetry tracing library, like we normally would.
	ctx, span := tracer.Start(ctx, "Securely-Talking-To-Collector-Span")
	defer span.End()

	for i := 0; i < 10; i++ {
		_, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i))
		<-time.After(6 * time.Millisecond)
		iSpan.End()
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDriver

func NewDriver(opts ...Option) otlp.ProtocolDriver

NewDriver creates a new gRPC protocol driver.

func WithReconnectionPeriod

func WithReconnectionPeriod(rp time.Duration) otlpconfig.GRPCOption

WithReconnectionPeriod allows one to set the delay between next connection attempt after failing to connect with the collector.

Types

type Option

type Option interface {
	otlpconfig.GRPCOption
}

Option applies an option to the gRPC driver.

func WithCompressor

func WithCompressor(compressor string) Option

WithCompressor will set the compressor for the gRPC client to use when sending requests. It is the responsibility of the caller to ensure that the compressor set has been registered with google.golang.org/grpc/encoding. This can be done by encoding.RegisterCompressor. Some compressors auto-register on import, such as gzip, which can be registered by calling `import _ "google.golang.org/grpc/encoding/gzip"`.

func WithDialOption

func WithDialOption(opts ...grpc.DialOption) Option

WithDialOption opens support to any grpc.DialOption to be used. If it conflicts with some other configuration the GRPC specified via the collector the ones here will take preference since they are set last.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint allows one to set the endpoint that the exporter will connect to the collector on. If unset, it will instead try to use connect to DefaultCollectorHost:DefaultCollectorPort.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders will send the provided headers with gRPC requests.

func WithInsecure

func WithInsecure() Option

WithInsecure disables client transport security for the exporter's gRPC connection just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure does. Note, by default, client security is required unless WithInsecure is used.

func WithInsecureMetrics added in v0.20.0

func WithInsecureMetrics() Option

WithInsecureMetrics disables client transport security for the metrics exporter's gRPC connection just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure does. Note, by default, client security is required unless WithInsecure is used.

func WithMetricsCompression added in v0.20.0

func WithMetricsCompression(compressor string) Option

WithMetricsCompression will set the compressor for the gRPC client to use when sending metrics requests. It is the responsibility of the caller to ensure that the compressor set has been registered with google.golang.org/grpc/encoding. This can be done by encoding.RegisterCompressor. Some compressors auto-register on import, such as gzip, which can be registered by calling `import _ "google.golang.org/grpc/encoding/gzip"`.

func WithMetricsEndpoint added in v0.20.0

func WithMetricsEndpoint(endpoint string) Option

WithMetricsEndpoint allows one to set the metrics endpoint that the exporter will connect to the collector on. If unset, it will instead try to use connect to DefaultCollectorHost:DefaultCollectorPort.

func WithMetricsHeaders added in v0.20.0

func WithMetricsHeaders(headers map[string]string) Option

WithMetricsHeaders will send the provided headers with gRPC metrics requests.

func WithMetricsTLSCredentials added in v0.20.0

func WithMetricsTLSCredentials(creds credentials.TransportCredentials) Option

WithMetricsTLSCredentials allows the connection to use TLS credentials when talking to the metrics server. It takes in grpc.TransportCredentials instead of say a Certificate file or a tls.Certificate, because the retrieving of these credentials can be done in many ways e.g. plain file, in code tls.Config or by certificate rotation, so it is up to the caller to decide what to use.

func WithMetricsTimeout added in v0.20.0

func WithMetricsTimeout(duration time.Duration) Option

WithMetricsTimeout tells the driver the max waiting time for the backend to process each metrics batch. If unset, the default will be 10 seconds.

func WithServiceConfig

func WithServiceConfig(serviceConfig string) Option

WithServiceConfig defines the default gRPC service config used.

func WithTLSCredentials

func WithTLSCredentials(creds credentials.TransportCredentials) Option

WithTLSCredentials allows the connection to use TLS credentials when talking to the server. It takes in grpc.TransportCredentials instead of say a Certificate file or a tls.Certificate, because the retrieving of these credentials can be done in many ways e.g. plain file, in code tls.Config or by certificate rotation, so it is up to the caller to decide what to use.

func WithTimeout added in v0.20.0

func WithTimeout(duration time.Duration) Option

WithTimeout tells the driver the max waiting time for the backend to process each spans or metrics batch. If unset, the default will be 10 seconds.

func WithTracesCompression added in v0.20.0

func WithTracesCompression(compressor string) Option

WithTracesCompression will set the compressor for the gRPC client to use when sending traces requests. It is the responsibility of the caller to ensure that the compressor set has been registered with google.golang.org/grpc/encoding. This can be done by encoding.RegisterCompressor. Some compressors auto-register on import, such as gzip, which can be registered by calling `import _ "google.golang.org/grpc/encoding/gzip"`.

func WithTracesEndpoint added in v0.20.0

func WithTracesEndpoint(endpoint string) Option

WithTracesEndpoint allows one to set the traces endpoint that the exporter will connect to the collector on. If unset, it will instead try to use connect to DefaultCollectorHost:DefaultCollectorPort.

func WithTracesHeaders added in v0.20.0

func WithTracesHeaders(headers map[string]string) Option

WithTracesHeaders will send the provided headers with gRPC traces requests.

func WithTracesInsecure added in v0.20.0

func WithTracesInsecure() Option

WithTracesInsecure disables client transport security for the traces exporter's gRPC connection just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure does. Note, by default, client security is required unless WithInsecure is used.

func WithTracesTLSCredentials added in v0.20.0

func WithTracesTLSCredentials(creds credentials.TransportCredentials) Option

WithTracesTLSCredentials allows the connection to use TLS credentials when talking to the traces server. It takes in grpc.TransportCredentials instead of say a Certificate file or a tls.Certificate, because the retrieving of these credentials can be done in many ways e.g. plain file, in code tls.Config or by certificate rotation, so it is up to the caller to decide what to use.

func WithTracesTimeout added in v0.20.0

func WithTracesTimeout(duration time.Duration) Option

WithTracesTimeout tells the driver the max waiting time for the backend to process each spans batch. If unset, the default will be 10 seconds.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL