pinpoint

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2024 License: Apache-2.0 Imports: 50 Imported by: 73

README

ci PkgGoDev

Pinpoint Go Agent

This is the official Go agent for Pinpoint.

Pinpoint Go Agent enables you to monitor Go applications using Pinpoint. Go applications must be instrumented manually at the source code level, because Go is a compiled language and does not have a virtual machine like Java. Developers can instrument Go applications using the APIs provided in this package.

Installation

go get github.com/pinpoint-apm/pinpoint-go-agent

Requirements

  • Go 1.15+
  • Pinpoint 2.1.1+
  • Linux, OS X, and Windows are supported.

Getting Started

Refer Quick Start for simple test run of Pinpoint Go Agent.

Plug-ins

Pinpoint Go Agent provides support for instrumenting Go’s built-in http package, database/sql drivers and plug-ins for popular frameworks and toolkits. These packages help you to make instruments with simple source code modifications. Refer the Plugin User Guide for more information.

Documents

Contributing

We are looking forward to your contributions via pull requests. For tips on contributing code fixes or enhancements, please see the contributing guide. To report bugs, please create an Issue on the GitHub repository.

License

Pinpoint is licensed under the Apache License, Version 2.0. See LICENSE for full license text.

Documentation

Overview

Package pinpoint provides the APIs to instrument Go applications for Pinpoint (https://github.com/pinpoint-apm/pinpoint).

This package enables you to monitor Go applications using Pinpoint. Go applications must be instrumented manually at the source code level, because Go is a compiled language and does not have a virtual machine like Java. Developers can instrument Go applications using the APIs provided in this package. It has support for instrumenting Go’s built-in http package, database/sql drivers and plug-ins for popular frameworks and toolkits (like Gin and gRPC, ...).

In Pinpoint, a transaction consists of a group of Spans. Each span represents a trace of a single logical node where the transaction has gone through. A span records important function invocations and their related data(arguments, return value, etc.) before encapsulating them as SpanEvents in a call stack like representation. The span itself and each of its SpanEvents represents a function invocation. Find out more about the concept of Pinpoint at the links below:

Index

Constants

View Source
const (
	CfgAppName                    = "ApplicationName"
	CfgAppType                    = "ApplicationType"
	CfgAgentID                    = "AgentID"
	CfgAgentName                  = "AgentName"
	CfgCollectorHost              = "Collector.Host"
	CfgCollectorAgentPort         = "Collector.AgentPort"
	CfgCollectorSpanPort          = "Collector.SpanPort"
	CfgCollectorStatPort          = "Collector.StatPort"
	CfgLogLevelOld                = "LogLevel"
	CfgLogLevel                   = "Log.Level"
	CfgLogOutput                  = "Log.Output"
	CfgLogMaxSize                 = "Log.MaxSize"
	CfgSamplingType               = "Sampling.Type"
	CfgSamplingCounterRate        = "Sampling.CounterRate"
	CfgSamplingPercentRate        = "Sampling.PercentRate"
	CfgSamplingNewThroughput      = "Sampling.NewThroughput"
	CfgSamplingContinueThroughput = "Sampling.ContinueThroughput"
	CfgSpanQueueSize              = "Span.QueueSize"
	CfgSpanMaxCallStackDepth      = "Span.MaxCallStackDepth"
	CfgSpanMaxCallStackSequence   = "Span.MaxCallStackSequence"
	CfgStatCollectInterval        = "Stat.CollectInterval"
	CfgStatBatchCount             = "Stat.BatchCount"
	CfgIsContainerEnv             = "IsContainerEnv"
	CfgConfigFile                 = "ConfigFile"
	CfgActiveProfile              = "ActiveProfile"
	CfgSQLTraceBindValue          = "SQL.TraceBindValue"
	CfgSQLMaxBindValueSize        = "SQL.MaxBindValueSize"
	CfgSQLTraceCommit             = "SQL.TraceCommit"
	CfgSQLTraceRollback           = "SQL.TraceRollback"
	CfgSQLTraceQueryStat          = "SQL.TraceQueryStat"
	CfgEnable                     = "Enable"
	CfgHttpUrlStatEnable          = "Http.UrlStat.Enable"
	CfgHttpUrlStatLimitSize       = "Http.UrlStat.LimitSize"
	CfgHttpUrlStatWithMethod      = "Http.UrlStat.WithMethod"
	CfgErrorTraceCallStack        = "Error.TraceCallStack"
	CfgErrorCallStackDepth        = "Error.CallStackDepth"
)

Config option keys

View Source
const (
	CfgInt int = iota
	CfgFloat
	CfgBool
	CfgString
	CfgStringSlice
)

Config value type

View Source
const (
	HeaderTraceId                    = "Pinpoint-TraceID"
	HeaderSpanId                     = "Pinpoint-SpanID"
	HeaderParentSpanId               = "Pinpoint-pSpanID"
	HeaderSampled                    = "Pinpoint-Sampled"
	HeaderFlags                      = "Pinpoint-Flags"
	HeaderParentApplicationName      = "Pinpoint-pAppName"
	HeaderParentApplicationType      = "Pinpoint-pAppType"
	HeaderParentApplicationNamespace = "Pinpoint-pAppNamespace"
	HeaderHost                       = "Pinpoint-Host"
)

keys of distributed tracing headers

View Source
const (
	ServiceTypeGoApp                 = 1800
	ServiceTypeGoFunction            = 1801
	ServiceTypeGoHttpClient          = 9401
	ServiceTypeAsync                 = 100
	ServiceTypeMysql                 = 2100
	ServiceTypeMysqlExecuteQuery     = 2101
	ServiceTypeMssql                 = 2200
	ServiceTypeMssqlExecuteQuery     = 2201
	ServiceTypeOracle                = 2300
	ServiceTypeOracleExecuteQuery    = 2301
	ServiceTypePgSql                 = 2500
	ServiceTypePgSqlExecuteQuery     = 2501
	ServiceTypeCassandraExecuteQuery = 2601
	ServiceTypeMongo                 = 2650
	ServiceTypeMongoExecuteQuery     = 2651
	ServiceTypeGrpc                  = 9160
	ServiceTypeGrpcServer            = 1130
	ServiceTypeMemcached             = 8050
	ServiceTypeRedis                 = 8203
	ServiceTypeKafkaClient           = 8660
	ServiceTypeHbaseClient           = 8800
	ServiceTypeGoElastic             = 9204
)

service types pre-defined

View Source
const (
	AnnotationArgs0               = -1
	AnnotationApi                 = 12
	AnnotationSqlId               = 20
	AnnotationSqlUid              = 25
	AnnotationHttpUrl             = 40
	AnnotationHttpParam           = 41
	AnnotationHttpCookie          = 45
	AnnotationHttpStatusCode      = 46
	AnnotationHttpRequestHeader   = 47
	AnnotationHttpResponseHeader  = 55
	AnnotationHttpProxyHeader     = 300
	AnnotationKafkaTopic          = 140
	AnnotationKafkaPartition      = 141
	AnnotationKafkaOffset         = 142
	AnnotationMongoJasonData      = 150
	AnnotationMongoCollectionInfo = 151
	AnnotationEsDsl               = 173
	AnnotationHbaseClientParams   = 320
	AnnotationExceptionChainId    = -52
)

annotation keys pre-defined

View Source
const (
	LogTransactionIdKey = "PtxId"
	LogSpanIdKey        = "PspanId"
	Logged              = 1
	NotLogged           = 0
	MetricURLStat       = "URLStat"
)
View Source
const (
	Version = "1.4.0"
)

Variables

This section is empty.

Functions

func AddConfig added in v1.0.0

func AddConfig(cfgName string, valueType int, defaultValue interface{}, dynamic bool)

AddConfig adds a configuration item.

func IsLogLevelEnabled added in v1.3.3

func IsLogLevelEnabled(level logrus.Level) bool

func Log added in v1.0.0

func Log(src string) *logEntry

func NewContext

func NewContext(ctx context.Context, tracer Tracer) context.Context

NewContext returns a new Context that contains the given Tracer.

func RequestWithTracerContext

func RequestWithTracerContext(req *http.Request, tracer Tracer) *http.Request

RequestWithTracerContext returns the request that has a Context carrying the given Tracer.

func SetExtraLogger added in v1.2.0

func SetExtraLogger(lgr *logrus.Logger)

func WrapSQLDriver added in v1.0.0

func WrapSQLDriver(drv driver.Driver, info DBInfo) driver.Driver

WrapSQLDriver wraps a driver.Driver and instruments SQL query calls.

Types

type Agent

type Agent interface {
	// NewSpanTracer returns a span Tracer indicating the start of a transaction.
	// A span is generated according to a given sampling policy, and trace data is not collected if not sampled.
	NewSpanTracer(operation string, rpcName string) Tracer

	// NewSpanTracerWithReader returns a span Tracer that continues a transaction passed from the previous node.
	// A span is generated according to a given sampling policy, and trace data is not collected if not sampled.
	// Distributed tracing headers are extracted from the reader. If it is empty, new transaction is started.
	NewSpanTracerWithReader(operation string, rpcName string, reader DistributedTracingContextReader) Tracer

	// Enable returns whether the agent is in an operational state.
	Enable() bool

	// Config returns the configuration associated with the agent.
	Config() *Config

	// Shutdown stops all related goroutines managing this agent.
	// After Shutdown is called, the agent will never collect tracing data again.
	Shutdown()
}

Agent instruments an application and makes spans and manages it.

func GetAgent added in v1.0.0

func GetAgent() Agent

GetAgent returns a global Agent created by NewAgent.

func NewAgent

func NewAgent(config *Config) (Agent, error)

NewAgent creates an Agent and spawns goroutines that manage spans and statistical data. The generated Agent is maintained globally and only one instance is retained. The provided config is generated by NewConfig and an error is returned if it is nil.

example:

opts := []pinpoint.ConfigOption{
  pinpoint.WithAppName("GoTestApp"),
  pinpoint.WithConfigFile(os.Getenv("HOME") + "/tmp/pinpoint-config.yaml"),
}
cfg, err := pinpoint.NewConfig(opts...)
agent, err := pinpoint.NewAgent(cfg)

func NewTestAgent added in v1.3.1

func NewTestAgent(config *Config, t *testing.T) (Agent, error)

func NoopAgent added in v1.0.0

func NoopAgent() Agent

NoopAgent returns a Agent that doesn't collect tracing data.

type Annotation

type Annotation interface {
	// AppendInt records an integer value to annotation.
	AppendInt(key int32, i int32)

	// AppendLong records a long value to annotation.
	AppendLong(key int32, l int64)

	// AppendString records a string value to annotation.
	AppendString(key int32, s string)

	// AppendStringString records two string values to annotation.
	AppendStringString(key int32, s1 string, s2 string)

	// AppendIntStringString records an integer value and two string values to annotation.
	AppendIntStringString(key int32, i int32, s1 string, s2 string)

	// AppendBytesStringString records an array of byte and two string values to annotation.
	AppendBytesStringString(key int32, b []byte, s1 string, s2 string)

	// AppendLongIntIntByteByteString records a long integer value, two integer value, two byte value and a string value to annotation.
	AppendLongIntIntByteByteString(key int32, l int64, i1 int32, i2 int32, b1 int32, b2 int32, s string)
}

Annotation is a key-value pair and used to annotate Span and SpanEvent with more information.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds agent configuration, for passing to NewAgent.

func GetConfig added in v1.0.0

func GetConfig() *Config

GetConfig returns a global Config created by NewConfig.

func NewConfig

func NewConfig(opts ...ConfigOption) (*Config, error)

NewConfig creates a Config populated with default settings, command line arguments, environment variables and the given config options. Config uses the following precedence order. Each item takes precedence over the item below it:

  1. command line flag
  2. environment variable
  3. configuration file
  4. ConfigOption
  5. default

configuration keys used in config files are case-insensitive. The generated Config is maintained globally.

example:

opts := []pinpoint.ConfigOption{
  pinpoint.WithAppName("GoTestApp"),
  pinpoint.WithConfigFile(os.Getenv("HOME") + "/tmp/pinpoint-config.yaml"),
}
cfg, err := pinpoint.NewConfig(opts...)

func (*Config) AddReloadCallback added in v1.3.0

func (config *Config) AddReloadCallback(optNames []string, callback func())

AddReloadCallback adds a callback function will be called after reloading config file.

func (*Config) Bool added in v1.0.0

func (config *Config) Bool(cfgName string) bool

Bool returns a boolean value for the specified configuration item.

func (*Config) Float added in v1.0.0

func (config *Config) Float(cfgName string) float64

Float returns a float value for the specified configuration item.

func (*Config) Int added in v1.0.0

func (config *Config) Int(cfgName string) int

Int returns an integer value for the specified configuration item.

func (*Config) Set added in v1.0.0

func (config *Config) Set(cfgName string, value interface{})

Set stores the specified configuration item value.

func (*Config) String

func (config *Config) String(cfgName string) string

String returns a string value for the specified configuration item.

func (*Config) StringSlice added in v1.0.0

func (config *Config) StringSlice(cfgName string) []string

StringSlice returns a string slice value for the specified configuration item.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption represents an option that can be passed to NewConfig.

func WithActiveProfile added in v1.0.0

func WithActiveProfile(profile string) ConfigOption

WithActiveProfile sets the configuration profile.

func WithAgentId

func WithAgentId(id string) ConfigOption

WithAgentId sets the agent ID.

func WithAgentName added in v1.0.0

func WithAgentName(name string) ConfigOption

WithAgentName sets the agent name.

func WithAppName

func WithAppName(name string) ConfigOption

WithAppName sets the application name.

func WithAppType

func WithAppType(typ int32) ConfigOption

WithAppType sets the application type.

func WithCollectorAgentPort

func WithCollectorAgentPort(port int) ConfigOption

WithCollectorAgentPort sets the agent port of pinpoint collector.

func WithCollectorHost

func WithCollectorHost(host string) ConfigOption

WithCollectorHost sets the host address of pinpoint collector.

func WithCollectorSpanPort

func WithCollectorSpanPort(port int) ConfigOption

WithCollectorSpanPort sets the span port of pinpoint collector.

func WithCollectorStatPort

func WithCollectorStatPort(port int) ConfigOption

WithCollectorStatPort sets the agent stat of pinpoint collector.

func WithConfigFile

func WithConfigFile(filePath string) ConfigOption

WithConfigFile sets the configuration file.

func WithEnable added in v1.0.0

func WithEnable(enable bool) ConfigOption

WithEnable enables the agent is operational state.

func WithErrorCallStackDepth added in v1.4.0

func WithErrorCallStackDepth(depth int) ConfigOption

WithErrorCallStackDepth sets the maximum depth of call stack that can be dumped.

func WithErrorTraceCallStack added in v1.4.0

func WithErrorTraceCallStack(trace bool) ConfigOption

WithErrorTraceCallStack enables the agent collects a call stack when error occurs.

func WithHttpUrlStatEnable added in v1.3.0

func WithHttpUrlStatEnable(enable bool) ConfigOption

WithHttpUrlStatEnable enables the agent collects the HTTP URL statistics.

func WithHttpUrlStatLimitSize added in v1.3.0

func WithHttpUrlStatLimitSize(size int) ConfigOption

WithHttpUrlStatLimitSize sets the maximum number of URLs that can be stored in one snapshot.

func WithHttpUrlStatWithMethod added in v1.4.0

func WithHttpUrlStatWithMethod(withMethod bool) ConfigOption

WithHttpUrlStatWithMethod adds http method as prefix to uri string key.

func WithIsContainerEnv added in v1.0.0

func WithIsContainerEnv(isContainer bool) ConfigOption

WithIsContainerEnv sets whether the application is running in a container environment or not. If this is not set, the agent automatically checks it.

func WithLogLevel

func WithLogLevel(level string) ConfigOption

WithLogLevel sets the logging level for agent logger.

func WithLogMaxSize added in v1.2.0

func WithLogMaxSize(size int) ConfigOption

WithLogMaxSize sets the max size of output file for agent logger.

func WithLogOutput added in v1.2.0

func WithLogOutput(output string) ConfigOption

WithLogOutput sets the output for agent logger.

func WithSQLMaxBindValueSize added in v1.0.0

func WithSQLMaxBindValueSize(size int) ConfigOption

WithSQLMaxBindValueSize sets the max length of traced bind value for SQL Driver.

func WithSQLTraceBindValue added in v1.0.0

func WithSQLTraceBindValue(trace bool) ConfigOption

WithSQLTraceBindValue enables bind value tracing for SQL Driver.

func WithSQLTraceCommit added in v1.0.0

func WithSQLTraceCommit(trace bool) ConfigOption

WithSQLTraceCommit enables commit tracing for SQL Driver.

func WithSQLTraceQueryStat added in v1.4.0

func WithSQLTraceQueryStat(collect bool) ConfigOption

WithSQLTraceQueryStat enables to trace SQL query statistics for SQL Driver.

func WithSQLTraceRollback added in v1.0.0

func WithSQLTraceRollback(trace bool) ConfigOption

WithSQLTraceRollback enables rollback tracing for SQL Driver.

func WithSamplingContinueThroughput

func WithSamplingContinueThroughput(tps int) ConfigOption

WithSamplingContinueThroughput sets the cont tps for a 'throughput sampler'.

func WithSamplingCounterRate added in v1.0.0

func WithSamplingCounterRate(rate int) ConfigOption

WithSamplingCounterRate sets the sampling rate for a 'counter sampler'.

func WithSamplingNewThroughput

func WithSamplingNewThroughput(tps int) ConfigOption

WithSamplingNewThroughput sets the new tps for a 'throughput sampler'.

func WithSamplingPercentRate added in v1.0.0

func WithSamplingPercentRate(rate float32) ConfigOption

WithSamplingPercentRate sets the sampling rate for a 'percent sampler'.

func WithSamplingRate

func WithSamplingRate(rate int) ConfigOption

WithSamplingRate DEPRECATED: Use WithSamplingCounterRate()

func WithSamplingType added in v1.0.0

func WithSamplingType(samplingType string) ConfigOption

WithSamplingType sets the type of agent sampler. Either "COUNTER" or "PERCENT" must be specified.

func WithSpanMaxCallStackDepth added in v1.2.0

func WithSpanMaxCallStackDepth(depth int) ConfigOption

WithSpanMaxCallStackDepth sets the max callstack depth of a span.

func WithSpanMaxCallStackSequence added in v1.2.0

func WithSpanMaxCallStackSequence(seq int) ConfigOption

WithSpanMaxCallStackSequence sets the max callstack sequence of a span.

func WithSpanQueueSize added in v1.2.0

func WithSpanQueueSize(size int) ConfigOption

WithSpanQueueSize sets the size of the span queue for gRPC.

func WithStatBatchCount

func WithStatBatchCount(count int) ConfigOption

WithStatBatchCount sets batch delivery units for collected statistics.

func WithStatCollectInterval

func WithStatCollectInterval(interval int) ConfigOption

WithStatCollectInterval sets the statistics collection cycle for the agent.

type DBInfo added in v1.0.0

type DBInfo struct {
	DBType    int
	QueryType int
	DBName    string
	DBHost    string

	ParseDSN func(info *DBInfo, dsn string)
}

type DistributedTracingContextReader

type DistributedTracingContextReader interface {
	// Get returns the value of a given key from carrier.
	Get(key string) string
}

DistributedTracingContextReader reads distributed tracing headers from carrier.

type DistributedTracingContextWriter

type DistributedTracingContextWriter interface {
	// Set sets a given key-value pair to carrier.
	Set(key string, value string)
}

DistributedTracingContextWriter writes distributed tracing headers to carrier.

type SpanEventRecorder

type SpanEventRecorder interface {
	// SetServiceType sets the type of service.
	SetServiceType(typ int32)

	// SetDestination sets the destination of operation.
	SetDestination(id string)

	// SetEndPoint sets the end point of operation.
	SetEndPoint(endPoint string)

	// SetError Record an error and indicate that operation has failed.
	SetError(e error, errorName ...string)

	// SetSQL records the SQL string and bind variables.
	SetSQL(sql string, args string)

	// Annotations returns annotations that the SpanEvent holds.
	Annotations() Annotation

	// FixDuration fixes the elapsed time of operation.
	FixDuration(start time.Time, end time.Time)
}

SpanEventRecorder records the collected data in the fields of SpanEvent.

type SpanRecorder

type SpanRecorder interface {
	// SetServiceType sets the type of service.
	SetServiceType(typ int32)

	// SetError Record an error and indicate that operation has failed.
	SetError(e error)

	// SetFailure indicate that operation has failed.
	SetFailure()

	// SetRpcName sets the name of RPC.
	// This value is displayed as the path of the span on the pinpoint web screen.
	SetRpcName(rpc string)

	// SetRemoteAddress sets the remote address.
	SetRemoteAddress(remoteAddress string)

	// SetEndPoint sets the end point of RPC.
	SetEndPoint(endPoint string)

	// SetAcceptorHost sets the host of acceptor.
	SetAcceptorHost(host string)

	// SetLogging sets whether the Span has been logged.
	SetLogging(logInfo int32)

	// Annotations returns annotations that the Span holds.
	Annotations() Annotation
}

SpanRecorder records the collected data in the fields of Span.

type Tracer

type Tracer interface {
	// NewSpanEvent returns a span event.
	NewSpanEvent(operationName string) Tracer

	// NewAsyncSpan is deprecated. Use NewGoroutineTracer.
	NewAsyncSpan() Tracer

	// NewGoroutineTracer returns a tracer that tracks the call stack of a goroutine.
	NewGoroutineTracer() Tracer

	// WrapGoroutine generates a tracer that tracks a given goroutine and passes it in context.
	WrapGoroutine(goroutineName string, goroutine func(context.Context), ctx context.Context) func()

	// EndSpan completes the span and transmits it to the collector.
	// Sending a span is handled by a separate goroutine.
	EndSpan()

	// EndSpanEvent completes the span event.
	EndSpanEvent()

	// Inject injects distributed tracing headers to the writer.
	Inject(writer DistributedTracingContextWriter)

	// Extract extracts distributed tracing headers from the reader.
	Extract(reader DistributedTracingContextReader)

	// TransactionId returns the ID of the transaction containing the span.
	TransactionId() TransactionId

	// SpanId returns the ID of the span.
	SpanId() int64

	Span() SpanRecorder
	SpanEvent() SpanEventRecorder

	// IsSampled returns whether the span has been sampled.
	IsSampled() bool

	// AddMetric adds a custom metric.
	AddMetric(metric string, value interface{})

	JsonString() []byte
}

Tracer instruments a single call stack of application and makes the result a single span.

func FromContext

func FromContext(ctx context.Context) Tracer

FromContext returns the Tracer from the context. If not present, NoopTracer is returned.

func NewDatabaseTracer

func NewDatabaseTracer(ctx context.Context, funcName string, info *DBInfo) Tracer

NewDatabaseTracer returns a Tracer for database operation.

func NoopTracer added in v1.0.0

func NoopTracer() Tracer

NoopTracer returns a Tracer that doesn't collect tracing data.

func TracerFromRequestContext

func TracerFromRequestContext(req *http.Request) Tracer

TracerFromRequestContext returns the Tracer from the request's context. If not present, NoopTracer is returned.

type TransactionId

type TransactionId struct {
	AgentId   string
	StartTime int64
	Sequence  int64
}

TransactionId represents that different RPCs are associated with each other as a single transaction.

func (TransactionId) String

func (tid TransactionId) String() string

String returns transaction id string.

type UrlStatEntry added in v1.3.0

type UrlStatEntry struct {
	Url    string
	Method string
	Status int
}

Directories

Path Synopsis
example module
plugin
beego Module
chi Module
echo Module
echov4 Module
fasthttp Module
fiber Module
gin Module
gocql Module
goelastic Module
gohbase Module
gomemcache Module
goredis Module
goredisv7 Module
goredisv8 Module
goredisv9 Module
gorilla Module
gorm Module
grpc Module
http Module
httprouter Module
kratos Module
logrus Module
mongodriver Module
mssql Module
mysql Module
oracle Module
pgsql Module
pgxv5 Module
redigo Module
rueidis Module
sarama Module
sarama-IBM Module
mock
Package mock_v1 is a generated GoMock package.
Package mock_v1 is a generated GoMock package.

Jump to

Keyboard shortcuts

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