xray

package
Version: v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2017 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ContextKey = new(ContextKeytype)

ContextKey returns a pointer to a newly allocated zero value of ContextKeytype.

View Source
var ErrRetrieveSegment = errors.New("unable to retrieve segment")

ErrRetrieveSegment happens when a segment cannot be retrieved

View Source
var Header = []byte(`{"format": "json", "version": 1}` + "\n")

Header is added before sending segments to daemon.

Functions

func AWS

func AWS(c *client.Client)

AWS adds X-Ray tracing to an AWS client.

func AWSWithWhitelist

func AWSWithWhitelist(c *client.Client, filename string)

AWSWithWhitelist allows a custom parameter whitelist JSON file to be defined.

func AddAnnotation

func AddAnnotation(ctx context.Context, key string, value interface{}) error

AddAnnotation adds an annotation to the provided segment or subsegment in ctx.

func AddError

func AddError(ctx context.Context, err error) error

AddError adds an error to the provided segment or subsegment in ctx.

func AddMetadata

func AddMetadata(ctx context.Context, key string, value interface{}) error

AddMetadata adds a metadata to the provided segment or subsegment in ctx.

func AddMetadataToNamespace

func AddMetadataToNamespace(ctx context.Context, namespace string, key string, value interface{}) error

AddMetadataToNamespace adds a namespace to the provided segment's or subsegment's metadata in ctx.

func Capture

func Capture(ctx context.Context, name string, fn func(context.Context) error) (err error)

Capture traces the provided synchronous function by beginning and closing a subsegment around its execution.

func CaptureAsync

func CaptureAsync(ctx context.Context, name string, fn func(context.Context) error)

CaptureAsync traces an arbitrary code segment within a goroutine. Use CaptureAsync instead of manually calling Capture within a goroutine to ensure the segment is flushed properly.

func Client

func Client(c *http.Client) *http.Client

Client creates a shallow copy of the provided http client, defaulting to http.DefaultClient, with roundtripper wrapped with xray.RoundTripper.

func Configure

func Configure(c Config) error

Configure overrides default configuration options with customer-defined values.

func DetachContext

func DetachContext(ctx context.Context) context.Context

DetachContext returns a new context with the existing segment. This is useful for creating background tasks which won't be cancelled when a request completes.

func Handler

func Handler(sn SegmentNamer, h http.Handler) http.Handler

Handler wraps the provided http handler with xray.Capture using the request's context, parsing the incoming headers, adding response headers if needed, and sets HTTP sepecific trace fields. Handler names the generated segments using the provided SegmentNamer.

func NewSegmentID

func NewSegmentID() string

NewSegmentID generates a string format of segment ID.

func NewTraceID

func NewTraceID() string

NewTraceID generates a string format of random trace ID.

func RequestWasTraced

func RequestWasTraced(ctx context.Context) bool

RequestWasTraced returns true if the context contains an X-Ray segment that was created from an HTTP request that contained a trace header. This is useful to ensure that a service is only called from X-Ray traced services.

func RoundTripper

func RoundTripper(rt http.RoundTripper) http.RoundTripper

RoundTripper wraps the provided http roundtripper with xray.Capture, sets HTTP-specific xray fields, and adds the trace header to the outbound request.

func TraceID

func TraceID(ctx context.Context) string

TraceID returns the canonical ID of the cross-service trace from the given segment in ctx. The value can be used in X-Ray's UI to uniquely identify the code paths executed. If no segment is provided in ctx, an empty string is returned.

Types

type CauseData

type CauseData struct {
	WorkingDirectory string                `json:"working_directory,omitempty"`
	Paths            []string              `json:"paths,omitempty"`
	Exceptions       []exception.Exception `json:"exceptions,omitempty"`
}

CauseData provides the shape for unmarshaling data that records exception.

type ClientTrace

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

func NewClientTrace

func NewClientTrace(opCtx context.Context) (ct *ClientTrace, err error)

NewClientTrace returns an instance of xray.ClientTrace, a wrapper around httptrace.ClientTrace. The ClientTrace implementation will generate subsegments for connection time, DNS lookup time, TLS handshake time, and provides additional information about the HTTP round trip

type Config

type Config struct {
	DaemonAddr                  string
	ServiceVersion              string
	SamplingStrategy            sampling.Strategy
	StreamingStrategy           StreamingStrategy
	ExceptionFormattingStrategy exception.FormattingStrategy
	ContextMissingStrategy      ctxmissing.Strategy
	LogLevel                    string
	LogFormat                   string
}

Config is a set of X-Ray configurations.

type ContextKeytype

type ContextKeytype int

ContextKeytype defines integer to be type of ContextKey.

type DB

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

DB copies the interface of sql.DB but adds X-Ray tracing. It must be created with xray.SQL.

func SQL

func SQL(driver, dsn string) (*DB, error)

SQL opens a normalized and traced wrapper around an *sql.DB connection. It uses `sql.Open` internally and shares the same function signature. To ensure passwords are filtered, it is HIGHLY RECOMMENDED that your DSN follows the format: `<schema>://<user>:<password>@<host>:<port>/<database>`

func (*DB) Begin

func (db *DB) Begin(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

Begin starts a transaction.

func (*DB) Close

func (db *DB) Close() error

Close closes a database and returns error if any.

func (*DB) Driver

func (db *DB) Driver() driver.Driver

Driver returns database's underlying driver.

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec captures executing a query without returning any rows and adds corresponding information into subsegment.

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping traces verifying a connection to the database is still alive, establishing a connection if necessary and adds corresponding information into subsegment.

func (*DB) Prepare

func (db *DB) Prepare(ctx context.Context, query string) (*Stmt, error)

Prepare creates a prepared statement for later queries or executions.

func (*DB) Query

func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query captures executing a query that returns rows and adds corresponding information into subsegment.

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow captures executing a query that is expected to return at most one row and adds corresponding information into subsegment.

func (*DB) SetConnMaxLifetime

func (db *DB) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

func (*DB) SetMaxIdleConns

func (db *DB) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection pool.

func (*DB) SetMaxOpenConns

func (db *DB) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database.

func (*DB) Stats

func (db *DB) Stats() sql.DBStats

Stats returns database statistics.

type DefaultStreamingStrategy

type DefaultStreamingStrategy struct {
	MaxSubsegmentCount int
}

DefaultStreamingStrategy provides a default value of 20 for the maximum number of subsegments that can be emitted in a single UDP packet.

func NewDefaultStreamingStrategy

func NewDefaultStreamingStrategy() (*DefaultStreamingStrategy, error)

NewDefaultStreamingStrategy initializes and returns a pointer to an instance of DefaultStreamingStrategy.

func NewDefaultStreamingStrategyWithMaxSubsegmentCount

func NewDefaultStreamingStrategyWithMaxSubsegmentCount(maxSubsegmentCount int) (*DefaultStreamingStrategy, error)

NewDefaultStreamingStrategyWithMaxSubsegmentCount initializes and returns a pointer to an instance of DefaultStreamingStrategy with a custom maximum number of subsegments per UDP packet.

func (*DefaultStreamingStrategy) RequiresStreaming

func (dSS *DefaultStreamingStrategy) RequiresStreaming(seg *Segment) bool

RequiresStreaming returns true when the number of subsegment children for a given segment is larger than MaxSubsegmentCount.

func (*DefaultStreamingStrategy) StreamCompletedSubsegments

func (dSS *DefaultStreamingStrategy) StreamCompletedSubsegments(seg *Segment) [][]byte

StreamCompletedSubsegments separates subsegments from the provided segment tree and sends them to daemon as streamed subsegment UDP packets.

type DynamicSegmentNamer

type DynamicSegmentNamer struct {
	FallbackName    string
	RecognizedHosts string
}

DynamicSegmentNamer chooses names for segments generated for incoming requests by parsing the HOST header of the incoming request. If the host header matches a given recognized pattern (using the included pattern package), it is used as the segment name. Otherwise, the fallback name is used.

func NewDynamicSegmentNamer

func NewDynamicSegmentNamer(fallback string, recognized string) *DynamicSegmentNamer

NewDynamicSegmentNamer creates a new dynamic segment namer.

func (*DynamicSegmentNamer) Name

func (dSN *DynamicSegmentNamer) Name(host string) string

Name returns the segment name for the given host header value.

type FixedSegmentNamer

type FixedSegmentNamer struct {
	FixedName string
}

FixedSegmentNamer records the fixed name of service node.

func NewFixedSegmentNamer

func NewFixedSegmentNamer(name string) *FixedSegmentNamer

NewFixedSegmentNamer initializes a FixedSegmentNamer which will provide a fixed segment name for every generated segment. If the AWS_XRAY_TRACING_NAME environment variable is set, its value will override the provided name argument.

func (*FixedSegmentNamer) Name

func (fSN *FixedSegmentNamer) Name(host string) string

Name returns the segment name for the given host header value. In this case, FixedName is always returned.

type HTTPData

type HTTPData struct {
	Request  *RequestData  `json:"request,omitempty"`
	Response *ResponseData `json:"response,omitempty"`
}

HTTPData provides the shape for unmarshaling request and response data.

func (*HTTPData) GetRequest

func (d *HTTPData) GetRequest() *RequestData

GetRequest returns value of RequestData.

func (*HTTPData) GetResponse

func (d *HTTPData) GetResponse() *ResponseData

GetResponse returns value of ResponseData.

type HTTPSubsegments added in v0.9.4

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

func (*HTTPSubsegments) ConnectDone added in v0.9.4

func (xt *HTTPSubsegments) ConnectDone(network, addr string, err error)

ConnectDone closes the dial subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the network over which the dial was made is added as metadata to the subsegment.

func (*HTTPSubsegments) ConnectStart added in v0.9.4

func (xt *HTTPSubsegments) ConnectStart(network, addr string)

ConnectStart begins a dial subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) DNSDone added in v0.9.4

func (xt *HTTPSubsegments) DNSDone(info httptrace.DNSDoneInfo)

DNSDone closes the dns subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the address values looked up, and whether or not the call was coalesced is added as metadata to the dns subsegment.

func (*HTTPSubsegments) DNSStart added in v0.9.4

func (xt *HTTPSubsegments) DNSStart(info httptrace.DNSStartInfo)

DNSStart begins a dns subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) GetConn added in v0.9.4

func (xt *HTTPSubsegments) GetConn(hostPort string)

GetConn begins a connect subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) GotConn added in v0.9.4

func (xt *HTTPSubsegments) GotConn(info *httptrace.GotConnInfo, err error)

GotConn closes the connect subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). Information about the connection is added as metadata to the subsegment. If the connection is marked as reused, the connect subsegment is deleted.

func (*HTTPSubsegments) GotFirstResponseByte added in v0.9.4

func (xt *HTTPSubsegments) GotFirstResponseByte()

GotFirstResponseByte closes the response subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) TLSHandshakeDone added in v0.9.4

func (xt *HTTPSubsegments) TLSHandshakeDone(connState tls.ConnectionState, err error)

TLSHandshakeDone closes the tls subsegment if the HTTP operation subsegment is still in progress, passing the error value(if any). Information about the tls connection is added as metadata to the subsegment.

func (*HTTPSubsegments) TLSHandshakeStart added in v0.9.4

func (xt *HTTPSubsegments) TLSHandshakeStart()

TLSHandshakeStart begins a tls subsegment if the HTTP operation subsegment is still in progress.

func (*HTTPSubsegments) WroteRequest added in v0.9.4

func (xt *HTTPSubsegments) WroteRequest(info httptrace.WroteRequestInfo)

WroteRequest closes the request subsegment if the HTTP operation subsegment is still in progress, passing the error value (if any). The response subsegment is then begun.

type RequestData

type RequestData struct {
	Method        string `json:"method,omitempty"`
	URL           string `json:"url,omitempty"` // http(s)://host/path
	ClientIP      string `json:"client_ip,omitempty"`
	UserAgent     string `json:"user_agent,omitempty"`
	XForwardedFor bool   `json:"x_forwarded_for,omitempty"`
	Traced        bool   `json:"traced,omitempty"`
}

RequestData provides the shape for unmarshaling request data.

type ResponseData

type ResponseData struct {
	Status        int `json:"status,omitempty"`
	ContentLength int `json:"content_length,omitempty"`
}

ResponseData provides the shape for unmarshaling response data.

type SQLData

type SQLData struct {
	ConnectionString string `json:"connection_string,omitempty"`
	URL              string `json:"url,omitempty"` // host:port/database
	DatabaseType     string `json:"database_type,omitempty"`
	DatabaseVersion  string `json:"database_version,omitempty"`
	DriverVersion    string `json:"driver_version,omitempty"`
	User             string `json:"user,omitempty"`
	Preparation      string `json:"preparation,omitempty"` // "statement" / "call"
	SanitizedQuery   string `json:"sanitized_query,omitempty"`
}

SQLData provides the shape for unmarshaling sql data.

type Segment

type Segment struct {
	sync.Mutex

	Sampled          bool           `json:"-"`
	RequestWasTraced bool           `json:"-"` // Used by xray.RequestWasTraced
	ContextDone      bool           `json:"-"`
	Emitted          bool           `json:"-"`
	IncomingHeader   *header.Header `json:"-"`
	ParentSegment    *Segment       `json:"-"` // The root of the Segment tree, the parent Segment (not Subsegment).

	// Required
	TraceID   string  `json:"trace_id,omitempty"`
	ID        string  `json:"id"`
	Name      string  `json:"name"`
	StartTime float64 `json:"start_time"`
	EndTime   float64 `json:"end_time,omitempty"`

	// Optional
	InProgress  bool       `json:"in_progress,omitempty"`
	ParentID    string     `json:"parent_id,omitempty"`
	Fault       bool       `json:"fault,omitempty"`
	Error       bool       `json:"error,omitempty"`
	Throttle    bool       `json:"throttle,omitempty"`
	Cause       *CauseData `json:"cause,omitempty"`
	ResourceARN string     `json:"resource_arn,omitempty"`
	Origin      string     `json:"origin,omitempty"`

	Type         string   `json:"type,omitempty"`
	Namespace    string   `json:"namespace,omitempty"`
	User         string   `json:"user,omitempty"`
	PrecursorIDs []string `json:"precursor_ids,omitempty"`

	HTTP *HTTPData              `json:"http,omitempty"`
	AWS  map[string]interface{} `json:"aws,omitempty"`

	Service *ServiceData `json:"service,omitempty"`

	// SQL
	SQL *SQLData `json:"sql,omitempty"`

	// Metadata
	Annotations map[string]interface{}            `json:"annotations,omitempty"`
	Metadata    map[string]map[string]interface{} `json:"metadata,omitempty"`

	// Children
	Subsegments []json.RawMessage `json:"subsegments,omitempty"`
	// contains filtered or unexported fields
}

Segment provides the resource's name, details about the request, and details about the work done.

func BeginSegment

func BeginSegment(ctx context.Context, name string) (context.Context, *Segment)

BeginSegment creates a Segment for a given name and context.

func BeginSubsegment

func BeginSubsegment(ctx context.Context, name string) (context.Context, *Segment)

BeginSubsegment creates a subsegment for a given name and context.

func GetSegment

func GetSegment(ctx context.Context) *Segment

GetSegment returns a pointer to the segment or subsegment provided in ctx, or nil if no segment or subsegment is found.

func NewSegmentFromHeader

func NewSegmentFromHeader(ctx context.Context, name string, h *header.Header) (context.Context, *Segment)

NewSegmentFromHeader creates a segment for downstream call and add information to the segment that gets from HTTP header.

func (*Segment) AddAnnotation added in v0.9.4

func (seg *Segment) AddAnnotation(key string, value interface{}) error

AddAnnotation allows adding an annotation to the segment.

func (*Segment) AddError added in v0.9.4

func (seg *Segment) AddError(err error) error

AddError allows adding an error to the segment.

func (*Segment) AddMetadata added in v0.9.4

func (seg *Segment) AddMetadata(key string, value interface{}) error

AddMetadata allows adding metadata to the segment.

func (*Segment) AddMetadataToNamespace added in v0.9.4

func (seg *Segment) AddMetadataToNamespace(namespace string, key string, value interface{}) error

AddMetadataToNamespace allows adding a namespace into metadata for the segment.

func (*Segment) Close

func (seg *Segment) Close(err error)

Close a segment.

func (*Segment) DownstreamHeader

func (s *Segment) DownstreamHeader() *header.Header

DownstreamHeader returns a header for passing to downstream calls.

func (*Segment) GetAWS

func (s *Segment) GetAWS() map[string]interface{}

GetAWS returns value of AWS.

func (*Segment) GetCause

func (s *Segment) GetCause() *CauseData

GetCause returns value of Cause.

func (*Segment) GetHTTP

func (s *Segment) GetHTTP() *HTTPData

GetHTTP returns value of HTTP.

func (*Segment) GetSQL

func (s *Segment) GetSQL() *SQLData

GetSQL returns value of SQL.

func (*Segment) GetService

func (s *Segment) GetService() *ServiceData

GetService returns value of Service.

func (*Segment) RemoveSubsegment

func (seg *Segment) RemoveSubsegment(remove *Segment) bool

RemoveSubsegment removes a subsegment child from a segment or subsegment.

type SegmentNamer

type SegmentNamer interface {
	Name(host string) string
}

SegmentNamer is the interface for naming service node.

type ServiceData

type ServiceData struct {
	Version string `json:"version,omitempty"`
}

ServiceData provides the shape for unmarshaling service version.

type Stmt

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

Stmt copies the interface of sql.Stmt but adds X-Ray tracing. It must be created with xray.DB.Prepare or xray.Tx.Stmt.

func (*Stmt) Close

func (stmt *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

func (stmt *Stmt) Exec(ctx context.Context, args ...interface{}) (sql.Result, error)

Exec captures executing a prepared statement with the given arguments and returning a Result summarizing the effect of the statement and adds corresponding information into subsegment.

func (*Stmt) Query

func (stmt *Stmt) Query(ctx context.Context, args ...interface{}) (*sql.Rows, error)

Query captures executing a prepared query statement with the given arguments and returning the query results as a *Rows and adds corresponding information into subsegment.

func (*Stmt) QueryRow

func (stmt *Stmt) QueryRow(ctx context.Context, args ...interface{}) *sql.Row

QueryRow captures executing a prepared query statement with the given arguments and adds corresponding information into subsegment.

type StreamingStrategy

type StreamingStrategy interface {
	RequiresStreaming(seg *Segment) bool
	StreamCompletedSubsegments(seg *Segment) [][]byte
}

StreamingStrategy provides an interface for implementing streaming strategies.

type Tx

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

Tx copies the interface of sql.Tx but adds X-Ray tracing. It must be created with xray.DB.Begin.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Exec

func (tx *Tx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec captures executing a query that doesn't return rows and adds corresponding information into subsegment.

func (*Tx) Query

func (tx *Tx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query captures executing a query that returns rows and adds corresponding information into subsegment.

func (*Tx) QueryRow

func (tx *Tx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow captures executing a query that is expected to return at most one row and adds corresponding information into subsegment.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback aborts the transaction.

func (*Tx) Stmt

func (tx *Tx) Stmt(ctx context.Context, stmt *Stmt) *Stmt

Stmt returns a transaction-specific prepared statement from an existing statement.

Jump to

Keyboard shortcuts

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