internal

package
v3.12.0+incompatible Latest Latest
Warning

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

Go to latest
Published: May 3, 2021 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// HarvestTypesEvents includes all Event types
	HarvestTypesEvents = HarvestSpanEvents | HarvestCustomEvents | HarvestTxnEvents | HarvestErrorEvents
	// HarvestTypesAll includes all harvest types
	HarvestTypesAll = HarvestMetricsTraces | HarvestTypesEvents
)
View Source
const (

	// FixedHarvestPeriod is the period that fixed period data (metrics,
	// traces, and span events) is sent to New Relic.
	FixedHarvestPeriod = 60 * time.Second
	// DefaultConfigurableEventHarvestMs is the period for custom, error,
	// and transaction events if the connect response's
	// "event_harvest_config.report_period_ms" is missing or invalid.
	DefaultConfigurableEventHarvestMs = 60 * 1000
	// CollectorTimeout is the timeout used in the client for communication
	// with New Relic's servers.
	CollectorTimeout = 20 * time.Second
	// AppDataChanSize is the size of the channel that contains data sent
	// the app processor.
	AppDataChanSize = 200

	// MaxTxnErrors is the maximum number of errors captured per
	// transaction.
	MaxTxnErrors = 5

	// MaxCustomEvents is the maximum number of Transaction Events that can be captured
	// per 60-second harvest cycle
	MaxCustomEvents = 10 * 1000
	// MaxTxnEvents is the maximum number of Transaction Events that can be captured
	// per 60-second harvest cycle
	MaxTxnEvents = 10 * 1000

	// MaxErrorEvents is the maximum number of Error Events that can be captured
	// per 60-second harvest cycle
	MaxErrorEvents = 100

	// MaxSpanEvents is the maximum number of Span Events that can be captured
	// per 60-second harvest cycle
	MaxSpanEvents = 1000

	// AttributeErrorLimit limits the number of extra attributes that can be
	// provided when noticing an error.
	AttributeErrorLimit = 32

	// RuntimeSamplerPeriod is the period of the runtime sampler.  Runtime
	// metrics should not depend on the sampler period, but the period must
	// be the same across instances.  For that reason, this value should not
	// be changed without notifying customers that they must update all
	// instance simultaneously for valid runtime metrics.
	RuntimeSamplerPeriod = 60 * time.Second
)
View Source
const (

	// AgentLanguage is used in the connect JSON and the Lambda JSON.
	AgentLanguage = "go"
)
View Source
const (
	// CallerType is the Type field's value for outbound payloads.
	CallerType = "App"
)
View Source
const (

	// DestAll contains all destinations.
	DestAll destinationSet = destTxnEvent | destTxnTrace | destError | destBrowser | destSpan | destSegment
)
View Source
const (
	// PanicErrorKlass is the error klass used for errors generated by
	// recovering panics in txn.End.
	PanicErrorKlass = "panic"
)
View Source
const (
	// ProcotolVersion is the protocol version used to communicate with NR
	// backend.
	ProcotolVersion = 17
)

Variables

View Source
var (
	// TransactionContextKey is the key used for newrelic.FromContext and
	// newrelic.NewContext.
	TransactionContextKey = contextKeyType(struct{}{})

	// GinTransactionContextKey is used as the context key in
	// nrgin.Middleware and nrgin.Transaction.  Unfortunately, Gin requires
	// a string context key. We use two different context keys (and check
	// both in nrgin.Transaction and newrelic.FromContext) rather than use a
	// single string key because context.WithValue will fail golint if used
	// with a string key.
	GinTransactionContextKey = "newRelicTransaction"
)
View Source
var (
	// ErrAccountNotTrusted indicates that, while the inbound headers were valid,
	// the account ID within them is not trusted by the user's application.
	ErrAccountNotTrusted = errors.New("account not trusted")
)
View Source
var (

	// ErrEventTypeRegex will be returned to caller of app.RecordCustomEvent
	// if the event type is not valid.
	ErrEventTypeRegex = fmt.Errorf("event type must match %s", eventTypeRegexRaw)
)
View Source
var (
	// MatchAnything is for use when matching attributes.
	MatchAnything = uniquePointer()
)
View Source
var (
	// SampleEnvironment is useful for testing.
	SampleEnvironment = Environment{
		Compiler: "comp",
		GOARCH:   "arch",
		GOOS:     "goos",
		Version:  "vers",
		NumCPU:   8,
	}
)
View Source
var (
	// ThisHost is the system hostname.
	ThisHost = func() string {
		if h, err := sysinfo.Hostname(); nil == err {
			return h
		}
		return unknownDatastoreHost
	}()
)

Functions

func AddAgentSpanAttribute

func AddAgentSpanAttribute(txn interface{}, key SpanAttribute, val string)

AddAgentSpanAttribute allows instrumentation packages to add span attributes.

func AddUserAttribute

func AddUserAttribute(a *Attributes, key string, val interface{}, d destinationSet) error

AddUserAttribute adds a user attribute.

func ApdexFailingThreshold

func ApdexFailingThreshold(threshold time.Duration) time.Duration

ApdexFailingThreshold calculates the threshold at which the transaction is considered a failure.

func AppDataToHTTPHeader

func AppDataToHTTPHeader(appData string) http.Header

AppDataToHTTPHeader encapsulates the given appData value in the correct HTTP header.

func BrowserAttributes

func BrowserAttributes(a *Attributes) []byte

BrowserAttributes returns a string with the attributes that are attached to the browser destination encoded in the JSON format expected by the Browser agent.

func CalculateApdexThreshold

func CalculateApdexThreshold(c *ConnectReply, txnName string) time.Duration

CalculateApdexThreshold calculates the apdex threshold.

func CompactJSONString

func CompactJSONString(js string) string

CompactJSONString removes the whitespace from a JSON string. This function will panic if the string provided is not valid JSON. Thus is must only be used in testing code!

func ConnectAttempt

func ConnectAttempt(config ConnectJSONCreator, securityPoliciesToken string, highSecurity bool, cs RpmControls) (*ConnectReply, RPMResponse)

ConnectAttempt tries to connect an application.

func CreateFullTxnName

func CreateFullTxnName(input string, reply *ConnectReply, isWeb bool) string

CreateFullTxnName uses collector rules and the appropriate metric prefix to construct the full transaction metric name from the name given by the consumer.

func CreateTxnMetrics

func CreateTxnMetrics(args *TxnData, metrics *metricTable)

CreateTxnMetrics creates metrics for a transaction.

func Deobfuscate

func Deobfuscate(in string, key []byte) ([]byte, error)

Deobfuscate deobfuscates a byte array.

func EndBasicSegment

func EndBasicSegment(t *TxnData, thread *Thread, start SegmentStartTime, now time.Time, name string) error

EndBasicSegment ends a basic segment.

func EndDatastoreSegment

func EndDatastoreSegment(p EndDatastoreParams) error

EndDatastoreSegment ends a datastore segment.

func EndExternalSegment

func EndExternalSegment(p EndExternalParams) error

EndExternalSegment ends an external segment.

func EndMessageSegment

func EndMessageSegment(p EndMessageParams) error

EndMessageSegment ends an external segment.

func ExpectCustomEvents

func ExpectCustomEvents(v Validator, cs *customEvents, expect []WantEvent)

ExpectCustomEvents allows testing of custom events. It passes if cs exactly matches expect.

func ExpectErrorEvents

func ExpectErrorEvents(v Validator, events *errorEvents, expect []WantEvent)

ExpectErrorEvents allows testing of error events. It passes if events exactly matches expect.

func ExpectErrors

func ExpectErrors(v Validator, errors harvestErrors, expect []WantError)

ExpectErrors allows testing of errors.

func ExpectMetrics

func ExpectMetrics(t Validator, mt *metricTable, expect []WantMetric)

ExpectMetrics allows testing of metrics. It passes if mt exactly matches expect.

func ExpectMetricsPresent

func ExpectMetricsPresent(t Validator, mt *metricTable, expect []WantMetric)

ExpectMetricsPresent allows testing of metrics without requiring an exact match

func ExpectSlowQueries

func ExpectSlowQueries(t Validator, slowQueries *slowQueries, want []WantSlowQuery)

ExpectSlowQueries allows testing of slow queries.

func ExpectSpanEvents

func ExpectSpanEvents(v Validator, events *spanEvents, expect []WantEvent)

ExpectSpanEvents allows testing of span events. It passes if events exactly matches expect.

func ExpectTxnEvents

func ExpectTxnEvents(v Validator, events *txnEvents, expect []WantEvent)

ExpectTxnEvents allows testing of txn events.

func ExpectTxnMetrics

func ExpectTxnMetrics(t Validator, mt *metricTable, want WantTxn)

ExpectTxnMetrics tests that the app contains metrics for a transaction.

func ExpectTxnTraces

func ExpectTxnTraces(v Validator, traces *harvestTraces, want []WantTxnTrace)

ExpectTxnTraces allows testing of transaction traces.

func FloatSecondsToDuration

func FloatSecondsToDuration(seconds float64) time.Duration

FloatSecondsToDuration turns a float64 in seconds into a time.Duration.

func GetContentLengthFromHeader

func GetContentLengthFromHeader(h http.Header) int64

GetContentLengthFromHeader gets the content length from a HTTP header, or -1 if no content length is available.

func HTTPHeaderToAppData

func HTTPHeaderToAppData(header http.Header) string

HTTPHeaderToAppData gets the appData value from the correct HTTP header.

func HarvestTesting

func HarvestTesting(app interface{}, replyfn func(*ConnectReply))

HarvestTesting allows integration packages to test instrumentation.

func HostFromURL

func HostFromURL(u *url.URL) string

HostFromURL returns the URL's host.

func MergeBreakdownMetrics

func MergeBreakdownMetrics(t *TxnData, metrics *metricTable)

MergeBreakdownMetrics creates segment metrics.

func MergeTxnErrors

func MergeTxnErrors(errors *harvestErrors, errs TxnErrors, txnEvent TxnEvent)

MergeTxnErrors merges a transaction's errors into the harvest's errors.

func MetadataToHTTPHeader

func MetadataToHTTPHeader(metadata CrossProcessMetadata) http.Header

MetadataToHTTPHeader creates a set of HTTP headers to represent the given cross process metadata.

func MinorVersion

func MinorVersion(v string) string

MinorVersion takes a given version string and returns only the major and minor portions of it. If the input is malformed, it returns the input untouched.

func Obfuscate

func Obfuscate(in, key []byte) (string, error)

Obfuscate obfuscates a byte array for transmission in CAT and RUM.

func ParseServerlessPayload

func ParseServerlessPayload(data []byte) (metadata, uncompressedData map[string]json.RawMessage, err error)

ParseServerlessPayload exists for testing.

func QueueDuration

func QueueDuration(hdr http.Header, txnStart time.Time) time.Duration

QueueDuration TODO

func RandFloat32

func RandFloat32() float32

RandFloat32 returns a random float32 between 0.0 and 1.0.

func RandUint32

func RandUint32() uint32

RandUint32 returns a random uint32.

func RandUint64

func RandUint64() uint64

RandUint64 returns a random uint64.

IMPORTANT! The default rand package functions are not used, since we want to minimize the chance that different Go processes duplicate the same transaction id. (Note that the rand top level functions "use a default shared Source that produces a deterministic sequence of values each time a program is run" (and we don't seed the shared Source to avoid changing customer apps' behavior)).

func RandUint64N

func RandUint64N(max uint64) uint64

RandUint64N returns a random int64 that's between 0 and the passed in max, non-inclusive

func RequestAgentAttributes

func RequestAgentAttributes(a *Attributes, method string, h http.Header, u *url.URL)

RequestAgentAttributes gathers agent attributes out of the request.

func ResponseCodeAttribute

func ResponseCodeAttribute(a *Attributes, code int)

ResponseCodeAttribute sets the response code agent attribute.

func ResponseHeaderAttributes

func ResponseHeaderAttributes(a *Attributes, h http.Header)

ResponseHeaderAttributes gather agent attributes from the response headers.

func SafeURL

func SafeURL(u *url.URL) string

SafeURL removes sensitive information from a URL.

func SafeURLFromString

func SafeURLFromString(rawurl string) string

SafeURLFromString removes sensitive information from a URL.

func ServerlessWrite

func ServerlessWrite(app interface{}, arn string, writer io.Writer)

ServerlessWrite exists to avoid type assertion in the nrlambda integration package.

func StringLengthByteLimit

func StringLengthByteLimit(str string, byteLimit int) string

StringLengthByteLimit truncates strings using a byte-limit boundary and avoids terminating in the middle of a multibyte character.

func TimeToUnixMilliseconds

func TimeToUnixMilliseconds(tm time.Time) uint64

TimeToUnixMilliseconds converts a time into a Unix timestamp in millisecond units.

func TrackUsage

func TrackUsage(s ...string)

TrackUsage helps track which integration packages are used.

func ValidateUserAttribute

func ValidateUserAttribute(key string, val interface{}) (interface{}, error)

ValidateUserAttribute validates a user attribute.

Types

type AdaptiveSampler

type AdaptiveSampler interface {
	ComputeSampled(priority float32, now time.Time) bool
}

AdaptiveSampler calculates which transactions should be sampled. An interface is used in the connect reply to facilitate testing.

func NewAdaptiveSampler

func NewAdaptiveSampler(period time.Duration, target uint64, now time.Time) AdaptiveSampler

NewAdaptiveSampler creates an AdaptiveSampler.

type AddAgentAttributer

type AddAgentAttributer interface {
	AddAgentAttribute(id AgentAttributeID, stringVal string, otherVal interface{})
}

AddAgentAttributer allows instrumentation to add agent attributes without exposing a Transaction method.

type AddAgentSpanAttributer

type AddAgentSpanAttributer interface {
	AddAgentSpanAttribute(key SpanAttribute, val string)
}

AddAgentSpanAttributer should be implemented by the Transaction.

type AgentAttributeID

type AgentAttributeID int

AgentAttributeID uniquely identifies each agent attribute.

const (
	AttributeHostDisplayName AgentAttributeID = iota

	AttributeAWSRequestID
	AttributeAWSLambdaARN
	AttributeAWSLambdaColdStart
	AttributeAWSLambdaEventSourceARN
	AttributeMessageRoutingKey
	AttributeMessageQueueName
	AttributeMessageExchangeType
	AttributeMessageReplyTo
	AttributeMessageCorrelationID
)

New agent attributes must be added in the following places: * Constants here. * Top level attributes.go file. * agentAttributeInfo

type AgentRunID

type AgentRunID string

AgentRunID identifies the current connection with the collector.

func (AgentRunID) String

func (id AgentRunID) String() string

type ApdexZone

type ApdexZone int

ApdexZone is a transaction classification.

const (
	ApdexNone ApdexZone = iota
	ApdexSatisfying
	ApdexTolerating
	ApdexFailing
)

https://en.wikipedia.org/wiki/Apdex

func CalculateApdexZone

func CalculateApdexZone(threshold, duration time.Duration) ApdexZone

CalculateApdexZone calculates the apdex based on the transaction duration and threshold.

Note that this does not take into account whether or not the transaction had an error. That is expected to be done by the caller.

type AttributeConfig

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

AttributeConfig is created at connect and shared between all transactions.

func CreateAttributeConfig

func CreateAttributeConfig(input AttributeConfigInput, includeEnabled bool) *AttributeConfig

CreateAttributeConfig creates a new AttributeConfig.

type AttributeConfigInput

type AttributeConfigInput struct {
	Attributes        AttributeDestinationConfig
	ErrorCollector    AttributeDestinationConfig
	TransactionEvents AttributeDestinationConfig
	BrowserMonitoring AttributeDestinationConfig
	TransactionTracer AttributeDestinationConfig
	SpanEvents        AttributeDestinationConfig
	TraceSegments     AttributeDestinationConfig
}

AttributeConfigInput is used as the input to CreateAttributeConfig: it transforms newrelic.Config settings into an AttributeConfig.

type AttributeDestinationConfig

type AttributeDestinationConfig struct {
	Enabled bool
	Include []string
	Exclude []string
}

AttributeDestinationConfig matches newrelic.AttributeDestinationConfig to avoid circular dependency issues.

type Attributes

type Attributes struct {
	Agent agentAttributes
	// contains filtered or unexported fields
}

Attributes are key value pairs attached to the various collected data types.

func NewAttributes

func NewAttributes(config *AttributeConfig) *Attributes

NewAttributes creates a new Attributes.

func (*Attributes) GetAgentValue

func (a *Attributes) GetAgentValue(id AgentAttributeID, d destinationSet) (string, interface{})

GetAgentValue is used to access agent attributes. This function returns ("", nil) if the attribute doesn't exist or it doesn't match the destinations provided.

type BetterCAT

type BetterCAT struct {
	Enabled  bool
	Priority Priority
	Sampled  bool
	Inbound  *Payload
	ID       string
}

BetterCAT stores the transaction's priority and all fields related to a DistributedTracer's Cross-Application Trace.

func (BetterCAT) TraceID

func (e BetterCAT) TraceID() string

TraceID returns the trace id.

type ConnectJSONCreator

type ConnectJSONCreator interface {
	CreateConnectJSON(*SecurityPolicies) ([]byte, error)
}

ConnectJSONCreator allows the creation of the connect payload JSON to be deferred until the SecurityPolicies are acquired and vetted.

type ConnectReply

type ConnectReply struct {
	RunID                 AgentRunID        `json:"agent_run_id"`
	RequestHeadersMap     map[string]string `json:"request_headers_map"`
	MaxPayloadSizeInBytes int               `json:"max_payload_size_in_bytes"`
	EntityGUID            string            `json:"entity_guid"`

	// Transaction Name Modifiers
	SegmentTerms segmentRules `json:"transaction_segment_terms"`
	TxnNameRules metricRules  `json:"transaction_name_rules"`
	URLRules     metricRules  `json:"url_rules"`
	MetricRules  metricRules  `json:"metric_name_rules"`

	// Cross Process
	EncodingKey     string            `json:"encoding_key"`
	CrossProcessID  string            `json:"cross_process_id"`
	TrustedAccounts trustedAccountSet `json:"trusted_account_ids"`

	// Settings
	KeyTxnApdex            map[string]float64 `json:"web_transactions_apdex"`
	ApdexThresholdSeconds  float64            `json:"apdex_t"`
	CollectAnalyticsEvents bool               `json:"collect_analytics_events"`
	CollectCustomEvents    bool               `json:"collect_custom_events"`
	CollectTraces          bool               `json:"collect_traces"`
	CollectErrors          bool               `json:"collect_errors"`
	CollectErrorEvents     bool               `json:"collect_error_events"`
	CollectSpanEvents      bool               `json:"collect_span_events"`

	// RUM
	AgentLoader string `json:"js_agent_loader"`
	Beacon      string `json:"beacon"`
	BrowserKey  string `json:"browser_key"`
	AppID       string `json:"application_id"`
	ErrorBeacon string `json:"error_beacon"`
	JSAgentFile string `json:"js_agent_file"`

	// PreconnectReply fields are not in the connect reply, this embedding
	// is done to simplify code.
	PreconnectReply `json:"-"`

	Messages []struct {
		Message string `json:"message"`
		Level   string `json:"level"`
	} `json:"messages"`

	AdaptiveSampler AdaptiveSampler
	// TraceIDGenerator creates random IDs for distributed tracing.  It
	// exists here in the connect reply so it can be modified to create
	// deterministic identifiers in tests.
	TraceIDGenerator *TraceIDGenerator `json:"-"`

	// BetterCAT/Distributed Tracing
	AccountID                     string `json:"account_id"`
	TrustedAccountKey             string `json:"trusted_account_key"`
	PrimaryAppID                  string `json:"primary_application_id"`
	SamplingTarget                uint64 `json:"sampling_target"`
	SamplingTargetPeriodInSeconds int    `json:"sampling_target_period_in_seconds"`

	ServerSideConfig struct {
		TransactionTracerEnabled *bool `json:"transaction_tracer.enabled"`
		// TransactionTracerThreshold should contain either a number or
		// "apdex_f" if it is non-nil.
		TransactionTracerThreshold           interface{} `json:"transaction_tracer.transaction_threshold"`
		TransactionTracerStackTraceThreshold *float64    `json:"transaction_tracer.stack_trace_threshold"`
		ErrorCollectorEnabled                *bool       `json:"error_collector.enabled"`
		ErrorCollectorIgnoreStatusCodes      []int       `json:"error_collector.ignore_status_codes"`
		CrossApplicationTracerEnabled        *bool       `json:"cross_application_tracer.enabled"`
	} `json:"agent_config"`

	// Faster Event Harvest
	EventData EventHarvestConfig `json:"event_harvest_config"`
	// contains filtered or unexported fields
}

ConnectReply contains all of the settings and state send down from the collector. It should not be modified after creation.

func ConnectReplyDefaults

func ConnectReplyDefaults() *ConnectReply

ConnectReplyDefaults returns a newly allocated ConnectReply with the proper default settings. A pointer to a global is not used to prevent consumers from changing the default settings.

func ConstructConnectReply

func ConstructConnectReply(body []byte, preconnect PreconnectReply) (*ConnectReply, error)

ConstructConnectReply takes the body of a Connect reply, in the form of bytes, and a PreconnectReply, and converts it into a *ConnectReply

func (*ConnectReply) ConfigurablePeriod

func (r *ConnectReply) ConfigurablePeriod() time.Duration

ConfigurablePeriod returns the Faster Event Harvest configurable reporting period if it is set, or the default report period otherwise.

type CrossProcessMetadata

type CrossProcessMetadata struct {
	ID         string
	TxnData    string
	Synthetics string
}

CrossProcessMetadata represents the metadata that must be transmitted with an external request for CAT to work.

func HTTPHeaderToMetadata

func HTTPHeaderToMetadata(header http.Header) CrossProcessMetadata

HTTPHeaderToMetadata gets the cross process metadata from the relevant HTTP headers.

type CustomEvent

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

CustomEvent is a custom event.

func CreateCustomEvent

func CreateCustomEvent(eventType string, params map[string]interface{}, now time.Time) (*CustomEvent, error)

CreateCustomEvent creates a custom event.

func (*CustomEvent) MarshalJSON

func (e *CustomEvent) MarshalJSON() ([]byte, error)

MarshalJSON is used for testing.

func (*CustomEvent) MergeIntoHarvest

func (e *CustomEvent) MergeIntoHarvest(h *Harvest)

MergeIntoHarvest implements Harvestable.

func (*CustomEvent) WriteJSON

func (e *CustomEvent) WriteJSON(buf *bytes.Buffer)

WriteJSON prepares JSON in the format expected by the collector.

type CustomMetric

type CustomMetric struct {
	RawInputName string
	Value        float64
}

CustomMetric is a custom metric.

func (CustomMetric) MergeIntoHarvest

func (m CustomMetric) MergeIntoHarvest(h *Harvest)

MergeIntoHarvest implements Harvestable.

type DatastoreExternalTotals

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

DatastoreExternalTotals contains overview of external and datastore calls made during a transaction.

type DatastoreMetricKey

type DatastoreMetricKey struct {
	Product      string
	Collection   string
	Operation    string
	Host         string
	PortPathOrID string
}

DatastoreMetricKey contains the fields by which datastore metrics are aggregated.

type DfltHarvestCfgr

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

DfltHarvestCfgr implements HarvestConfigurer for internal test cases, and for situations where we don't have a ConnectReply, such as for serverless harvests

func (*DfltHarvestCfgr) MaxCustomEvents

func (d *DfltHarvestCfgr) MaxCustomEvents() int

MaxCustomEvents returns the maximum number of Custom Events that should be reported per period

func (*DfltHarvestCfgr) MaxErrorEvents

func (d *DfltHarvestCfgr) MaxErrorEvents() int

MaxErrorEvents returns the maximum number of Error Events that should be reported per period

func (*DfltHarvestCfgr) MaxSpanEvents

func (d *DfltHarvestCfgr) MaxSpanEvents() int

MaxSpanEvents returns the maximum number of Span Events that should be reported per period

func (*DfltHarvestCfgr) MaxTxnEvents

func (d *DfltHarvestCfgr) MaxTxnEvents() int

MaxTxnEvents returns the maximum number of Transaction Events that should be reported per period

func (*DfltHarvestCfgr) ReportPeriods

func (d *DfltHarvestCfgr) ReportPeriods() map[HarvestTypes]time.Duration

ReportPeriods returns a map from the bitset of harvest types to the period that those types should be reported

type DistributedTracingSupport

type DistributedTracingSupport struct {
	AcceptPayloadSuccess            bool // AcceptPayload was called successfully
	AcceptPayloadException          bool // AcceptPayload had a generic exception
	AcceptPayloadParseException     bool // AcceptPayload had a parsing exception
	AcceptPayloadCreateBeforeAccept bool // AcceptPayload was ignored because CreatePayload had already been called
	AcceptPayloadIgnoredMultiple    bool // AcceptPayload was ignored because AcceptPayload had already been called
	AcceptPayloadIgnoredVersion     bool // AcceptPayload was ignored because the payload's major version was greater than the agent's
	AcceptPayloadUntrustedAccount   bool // AcceptPayload was ignored because the payload was untrusted
	AcceptPayloadNullPayload        bool // AcceptPayload was ignored because the payload was nil
	CreatePayloadSuccess            bool // CreatePayload was called successfully
	CreatePayloadException          bool // CreatePayload had a generic exception
}

DistributedTracingSupport is used to track distributed tracing activity for supportability.

type EndDatastoreParams

type EndDatastoreParams struct {
	TxnData            *TxnData
	Thread             *Thread
	Start              SegmentStartTime
	Now                time.Time
	Product            string
	Collection         string
	Operation          string
	ParameterizedQuery string
	QueryParameters    map[string]interface{}
	Host               string
	PortPathOrID       string
	Database           string
}

EndDatastoreParams contains the parameters for EndDatastoreSegment.

type EndExternalParams

type EndExternalParams struct {
	TxnData  *TxnData
	Thread   *Thread
	Start    SegmentStartTime
	Now      time.Time
	Logger   logger.Logger
	Response *http.Response
	URL      *url.URL
	Host     string
	Library  string
	Method   string
}

EndExternalParams contains the parameters for EndExternalSegment.

type EndMessageParams

type EndMessageParams struct {
	TxnData         *TxnData
	Thread          *Thread
	Start           SegmentStartTime
	Now             time.Time
	Logger          logger.Logger
	DestinationName string
	Library         string
	DestinationType string
	DestinationTemp bool
}

EndMessageParams contains the parameters for EndMessageSegment.

type Environment

type Environment struct {
	Compiler string `env:"runtime.Compiler"`
	GOARCH   string `env:"runtime.GOARCH"`
	GOOS     string `env:"runtime.GOOS"`
	Version  string `env:"runtime.Version"`
	NumCPU   int    `env:"runtime.NumCPU"`
}

Environment describes the application's environment.

func NewEnvironment

func NewEnvironment() Environment

NewEnvironment returns a new Environment.

func (Environment) MarshalJSON

func (e Environment) MarshalJSON() ([]byte, error)

MarshalJSON prepares Environment JSON in the format expected by the collector during the connect command.

type ErrInvalidAttributeType

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

ErrInvalidAttributeType is returned when the value is not valid.

func (ErrInvalidAttributeType) Error

func (e ErrInvalidAttributeType) Error() string

type ErrPayloadMissingField

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

ErrPayloadMissingField indicates there's a required field that's missing

func (ErrPayloadMissingField) Error

func (e ErrPayloadMissingField) Error() string

type ErrPayloadParse

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

ErrPayloadParse indicates that the payload was malformed.

func (ErrPayloadParse) Error

func (e ErrPayloadParse) Error() string

type ErrUnsupportedPayloadVersion

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

ErrUnsupportedPayloadVersion indicates that the major version number is unknown.

func (ErrUnsupportedPayloadVersion) Error

type ErrorData

type ErrorData struct {
	When            time.Time
	Stack           StackTrace
	ExtraAttributes map[string]interface{}
	Msg             string
	Klass           string
}

ErrorData contains the information about a recorded error.

func TxnErrorFromPanic

func TxnErrorFromPanic(now time.Time, v interface{}) ErrorData

TxnErrorFromPanic creates a new TxnError from a panic.

func TxnErrorFromResponseCode

func TxnErrorFromResponseCode(now time.Time, code int) ErrorData

TxnErrorFromResponseCode creates a new TxnError from an http response code.

type ErrorEvent

type ErrorEvent TxnError

ErrorEvent and tracedError are separate types so that error events and traced errors can have different WriteJSON methods.

func (*ErrorEvent) MarshalJSON

func (e *ErrorEvent) MarshalJSON() ([]byte, error)

MarshalJSON is used for testing.

func (*ErrorEvent) WriteJSON

func (e *ErrorEvent) WriteJSON(buf *bytes.Buffer)

WriteJSON prepares JSON in the format expected by the collector. https://source.datanerd.us/agents/agent-specs/blob/master/Error-Events.md

type EventHarvestConfig

type EventHarvestConfig struct {
	ReportPeriodMs int `json:"report_period_ms,omitempty"`
	Limits         struct {
		TxnEvents    *uint `json:"analytic_event_data,omitempty"`
		CustomEvents *uint `json:"custom_event_data,omitempty"`
		ErrorEvents  *uint `json:"error_event_data,omitempty"`
		SpanEvents   *uint `json:"span_event_data,omitempty"`
	} `json:"harvest_limits"`
}

EventHarvestConfig contains fields relating to faster event harvest. This structure is used in the connect request (to send up defaults) and in the connect response (to get the server values).

https://source.datanerd.us/agents/agent-specs/blob/master/Connect-LEGACY.md#event_harvest_config-hash https://source.datanerd.us/agents/agent-specs/blob/master/Connect-LEGACY.md#event-harvest-config

func DefaultEventHarvestConfig

func DefaultEventHarvestConfig(eventer MaxTxnEventer) EventHarvestConfig

DefaultEventHarvestConfig provides faster event harvest defaults.

type Expect

type Expect interface {
	ExpectCustomEvents(t Validator, want []WantEvent)
	ExpectErrors(t Validator, want []WantError)
	ExpectErrorEvents(t Validator, want []WantEvent)

	ExpectTxnEvents(t Validator, want []WantEvent)

	ExpectMetrics(t Validator, want []WantMetric)
	ExpectMetricsPresent(t Validator, want []WantMetric)
	ExpectTxnMetrics(t Validator, want WantTxn)

	ExpectTxnTraces(t Validator, want []WantTxnTrace)
	ExpectSlowQueries(t Validator, want []WantSlowQuery)

	ExpectSpanEvents(t Validator, want []WantEvent)
}

Expect exposes methods that allow for testing whether the correct data was captured.

type Harvest

type Harvest struct {
	Metrics      *metricTable
	ErrorTraces  harvestErrors
	TxnTraces    *harvestTraces
	SlowSQLs     *slowQueries
	SpanEvents   *spanEvents
	CustomEvents *customEvents
	TxnEvents    *txnEvents
	ErrorEvents  *errorEvents
	// contains filtered or unexported fields
}

Harvest contains collected data.

func NewHarvest

func NewHarvest(now time.Time, configurer HarvestConfigurer) *Harvest

NewHarvest returns a new Harvest.

func (*Harvest) CreateFinalMetrics

func (h *Harvest) CreateFinalMetrics(reply *ConnectReply, hc HarvestConfigurer)

CreateFinalMetrics creates extra metrics at harvest time.

func (*Harvest) Payloads

func (h *Harvest) Payloads(splitLargeTxnEvents bool) (ps []PayloadCreator)

Payloads returns a slice of payload creators.

func (*Harvest) Ready

func (h *Harvest) Ready(now time.Time) *Harvest

Ready returns a new Harvest which contains the data types ready for harvest, or nil if no data is ready for harvest.

type HarvestConfigurer

type HarvestConfigurer interface {
	// ReportPeriods returns a map from the bitset of harvest types to the period that those types should be reported
	ReportPeriods() map[HarvestTypes]time.Duration
	// MaxSpanEvents returns the maximum number of Span Events that should be reported per period
	MaxSpanEvents() int
	// MaxCustomEvents returns the maximum number of Custom Events that should be reported per period
	MaxCustomEvents() int
	// MaxErrorEvents returns the maximum number of Error Events that should be reported per period
	MaxErrorEvents() int
	MaxTxnEventer
}

HarvestConfigurer contains information about the configured number of various types of events as well as the Faster Event Harvest report period. It is implemented by AppRun and DfltHarvestCfgr.

type HarvestTestinger

type HarvestTestinger interface {
	HarvestTesting(replyfn func(*ConnectReply))
}

HarvestTestinger is implemented by the app. It sets an empty test harvest and modifies the connect reply if a callback is provided.

type HarvestTrace

type HarvestTrace struct {
	TxnEvent
	Trace TxnTrace
}

HarvestTrace contains a finished transaction trace ready for serialization to the collector.

func (*HarvestTrace) MarshalJSON

func (trace *HarvestTrace) MarshalJSON() ([]byte, error)

MarshalJSON is used for testing.

TODO: Eliminate this entirely by using harvestTraces.Data().

type HarvestTypes

type HarvestTypes uint

HarvestTypes is a bit set used to indicate which data types are ready to be reported.

const (
	// HarvestMetricsTraces is the Metrics Traces type
	HarvestMetricsTraces HarvestTypes = 1 << iota
	// HarvestSpanEvents is the Span Event type
	HarvestSpanEvents
	// HarvestCustomEvents is the Custom Event type
	HarvestCustomEvents
	// HarvestTxnEvents is the Transaction Event type
	HarvestTxnEvents
	// HarvestErrorEvents is the Error Event type
	HarvestErrorEvents
)

type Harvestable

type Harvestable interface {
	MergeIntoHarvest(h *Harvest)
}

Harvestable is something that can be merged into a Harvest.

type JSONString

type JSONString string

JSONString assists in logging JSON: Based on the formatter used to log Context contents, the contents could be marshalled as JSON or just printed directly.

func (JSONString) MarshalJSON

func (js JSONString) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSONString unmodified without any escaping.

type Labels

type Labels map[string]string

Labels is used for connect JSON formatting.

func (Labels) MarshalJSON

func (l Labels) MarshalJSON() ([]byte, error)

MarshalJSON requires a comment for golint?

type MaxTxnEventer

type MaxTxnEventer interface {
	MaxTxnEvents() int
}

MaxTxnEventer returns the maximum number of Transaction Events that should be reported per period

type MessageMetricKey

type MessageMetricKey struct {
	Library         string
	DestinationType string
	Consumer        bool
	DestinationName string
	DestinationTemp bool
}

MessageMetricKey is the key to use for message segments.

func (MessageMetricKey) Name

func (key MessageMetricKey) Name() string

Name returns the metric name value for this MessageMetricKey to be used for scoped and unscoped metrics.

Producers MessageBroker/{Library}/{Destination Type}/{Action}/Named/{Destination Name} MessageBroker/{Library}/{Destination Type}/{Action}/Temp

Consumers OtherTransaction/Message/{Library}/{DestinationType}/Named/{Destination Name} OtherTransaction/Message/{Library}/{DestinationType}/Temp

type Payload

type Payload struct {
	TransactionID     string          `json:"tx,omitempty"`
	ID                string          `json:"id,omitempty"`
	TracedID          string          `json:"tr"`
	Priority          Priority        `json:"pr"`
	Sampled           *bool           `json:"sa"`
	Timestamp         timestampMillis `json:"ti"`
	TransportDuration time.Duration   `json:"-"`
	// contains filtered or unexported fields
}

Payload is the distributed tracing payload.

func AcceptPayload

func AcceptPayload(p interface{}) (*Payload, error)

AcceptPayload parses the inbound distributed tracing payload.

func (Payload) HTTPSafe

func (p Payload) HTTPSafe() string

HTTPSafe implements newrelic.DistributedTracePayload.

func (Payload) IsValid

func (p Payload) IsValid() error

IsValid validates the payload data by looking for missing fields. Returns an error if there's a problem, nil if everything's fine

func (*Payload) SetSampled

func (p *Payload) SetSampled(sampled bool)

SetSampled lets us set a value for our *bool, which we can't do directly since a pointer needs something to point at.

func (Payload) Text

func (p Payload) Text() string

Text implements newrelic.DistributedTracePayload.

type PayloadCreator

type PayloadCreator interface {
	// In the event of a rpm request failure (hopefully simply an
	// intermittent collector issue) the payload may be merged into the next
	// time period's harvest.
	Harvestable
	// Data prepares JSON in the format expected by the collector endpoint.
	// This method should return (nil, nil) if the payload is empty and no
	// rpm request is necessary.
	Data(agentRunID string, harvestStart time.Time) ([]byte, error)
	// EndpointMethod is used for the "method" query parameter when posting
	// the data.
	EndpointMethod() string
}

PayloadCreator is a data type in the harvest.

type PreconnectReply

type PreconnectReply struct {
	Collector        string           `json:"redirect_host"`
	SecurityPolicies SecurityPolicies `json:"security_policies"`
}

PreconnectReply contains settings from the preconnect endpoint.

type Priority

type Priority float32

Priority allows for a priority sampling of events. When an event is created it is given a Priority. Whenever an event pool is full and events need to be dropped, the events with the lowest priority are dropped.

func NewPriority

func NewPriority() Priority

NewPriority returns a new priority.

func (Priority) Float32

func (p Priority) Float32() float32

Float32 returns the priority as a float32.

func (*Priority) MarshalJSON

func (p *Priority) MarshalJSON() ([]byte, error)

MarshalJSON limits the number of decimals.

func (Priority) WriteJSON

func (p Priority) WriteJSON(buf *bytes.Buffer)

WriteJSON limits the number of decimals.

type RPMResponse

type RPMResponse struct {

	// Err indicates whether or not the call was successful: newRPMResponse
	// should be used to avoid mismatch between statusCode and Err.
	Err error
	// contains filtered or unexported fields
}

RPMResponse contains a NR endpoint response.

Agent Behavior Summary:

on connect/preconnect:

410 means shutdown
200, 202 mean success (start run)
all other response codes and errors mean try after backoff

on harvest:

410 means shutdown
401, 409 mean restart run
408, 429, 500, 503 mean save data for next harvest
all other response codes and errors discard the data and continue the current harvest

func CollectorRequest

func CollectorRequest(cmd RpmCmd, cs RpmControls) RPMResponse

CollectorRequest makes a request to New Relic.

func (RPMResponse) IsDisconnect

func (resp RPMResponse) IsDisconnect() bool

IsDisconnect indicates that the agent should disconnect.

func (RPMResponse) IsRestartException

func (resp RPMResponse) IsRestartException() bool

IsRestartException indicates that the agent should restart.

func (RPMResponse) ShouldSaveHarvestData

func (resp RPMResponse) ShouldSaveHarvestData() bool

ShouldSaveHarvestData indicates that the agent should save the data and try to send it in the next harvest.

type RpmCmd

type RpmCmd struct {
	Name              string
	Collector         string
	RunID             string
	Data              []byte
	RequestHeadersMap map[string]string
	MaxPayloadSize    int
}

RpmCmd contains fields specific to an individual call made to RPM.

type RpmControls

type RpmControls struct {
	License      string
	Client       *http.Client
	Logger       logger.Logger
	AgentVersion string
}

RpmControls contains fields which will be the same for all calls made by the same application.

type Sample

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

Sample is a system/runtime snapshot.

func GetSample

func GetSample(now time.Time, lg logger.Logger) *Sample

GetSample gathers a new Sample.

type SampleEverything

type SampleEverything struct{}

SampleEverything is used for testing.

func (SampleEverything) ComputeSampled

func (s SampleEverything) ComputeSampled(priority float32, now time.Time) bool

ComputeSampled implements AdaptiveSampler.

type SampleNothing

type SampleNothing struct{}

SampleNothing is used when the application is not yet connected.

func (SampleNothing) ComputeSampled

func (s SampleNothing) ComputeSampled(priority float32, now time.Time) bool

ComputeSampled implements AdaptiveSampler.

type Samples

type Samples struct {
	Previous *Sample
	Current  *Sample
}

Samples is used as the parameter to GetStats to avoid mixing up the previous and current sample.

type SecurityPolicies

type SecurityPolicies struct {
	RecordSQL                 securityPolicy `json:"record_sql"`
	AttributesInclude         securityPolicy `json:"attributes_include"`
	AllowRawExceptionMessages securityPolicy `json:"allow_raw_exception_messages"`
	CustomEvents              securityPolicy `json:"custom_events"`
	CustomParameters          securityPolicy `json:"custom_parameters"`
}

SecurityPolicies contains the security policies.

func (*SecurityPolicies) PointerIfPopulated

func (sp *SecurityPolicies) PointerIfPopulated() *SecurityPolicies

PointerIfPopulated returns a reference to the security policies if they have been populated from JSON.

func (*SecurityPolicies) UnmarshalJSON

func (sp *SecurityPolicies) UnmarshalJSON(data []byte) (er error)

UnmarshalJSON decodes security policies sent from the preconnect endpoint.

type SegmentStartTime

type SegmentStartTime struct {
	Stamp segmentStamp
	Depth int
}

SegmentStartTime is embedded into the top level segments (rather than segmentTime) to minimize the structure sizes to minimize allocations.

func StartSegment

func StartSegment(t *TxnData, thread *Thread, now time.Time) SegmentStartTime

StartSegment begins a segment.

type ServerlessHarvest

type ServerlessHarvest struct {

	// The Lambda handler could be using multiple goroutines so we use a
	// mutex to prevent race conditions.
	sync.Mutex
	// contains filtered or unexported fields
}

ServerlessHarvest is used to store and log data when the agent is running in serverless mode.

func NewServerlessHarvest

func NewServerlessHarvest(logger logger.Logger, version string, getEnv func(string) string) *ServerlessHarvest

NewServerlessHarvest creates a new ServerlessHarvest.

func (*ServerlessHarvest) Consume

func (sh *ServerlessHarvest) Consume(data Harvestable)

Consume adds data to the harvest.

func (*ServerlessHarvest) Write

func (sh *ServerlessHarvest) Write(arn string, writer io.Writer)

Write logs the data in the format described by: https://source.datanerd.us/agents/agent-specs/blob/master/Lambda.md

type ServerlessWriter

type ServerlessWriter interface {
	ServerlessWrite(arn string, writer io.Writer)
}

ServerlessWriter is implemented by newrelic.Application.

type SpanAttribute

type SpanAttribute string

SpanAttribute is an attribute put in span events.

const (

	// These span attributes are added by aws sdk instrumentation.
	// https://source.datanerd.us/agents/agent-specs/blob/master/implementation_guides/aws-sdk.md#span-and-segment-attributes
	SpanAttributeAWSOperation SpanAttribute = "aws.operation"
	SpanAttributeAWSRequestID SpanAttribute = "aws.requestId"
	SpanAttributeAWSRegion    SpanAttribute = "aws.region"
)

These span event string constants must match the contents of the top level attributes.go file.

func (SpanAttribute) String

func (sa SpanAttribute) String() string

type SpanEvent

type SpanEvent struct {
	TraceID       string
	GUID          string
	ParentID      string
	TransactionID string
	Sampled       bool
	Priority      Priority
	Timestamp     time.Time
	Duration      time.Duration
	Name          string
	Category      spanCategory
	Component     string
	Kind          string
	IsEntrypoint  bool
	Attributes    spanAttributeMap
}

SpanEvent represents a span event, necessary to support Distributed Tracing.

func (*SpanEvent) MarshalJSON

func (e *SpanEvent) MarshalJSON() ([]byte, error)

MarshalJSON is used for testing.

func (*SpanEvent) WriteJSON

func (e *SpanEvent) WriteJSON(buf *bytes.Buffer)

WriteJSON prepares JSON in the format expected by the collector.

type StackTrace

type StackTrace []uintptr

StackTrace is a stack trace.

func GetStackTrace

func GetStackTrace() StackTrace

GetStackTrace returns a new StackTrace.

func (StackTrace) MarshalJSON

func (st StackTrace) MarshalJSON() ([]byte, error)

MarshalJSON prepares JSON in the format expected by the collector.

func (StackTrace) WriteJSON

func (st StackTrace) WriteJSON(buf *bytes.Buffer)

WriteJSON adds the stack trace to the buffer in the JSON form expected by the collector.

type Stats

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

Stats contains system information for a period of time.

func GetStats

func GetStats(ss Samples) Stats

GetStats combines two Samples into a Stats.

func (Stats) MergeIntoHarvest

func (s Stats) MergeIntoHarvest(h *Harvest)

MergeIntoHarvest implements Harvestable.

type Thread

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

Thread contains a segment stack that is used to track segment parenting time within a single goroutine.

func NewThread

func NewThread(txndata *TxnData) *Thread

NewThread returns a new Thread to track segments in a new goroutine.

func (*Thread) AddAgentSpanAttribute

func (thread *Thread) AddAgentSpanAttribute(key SpanAttribute, val string)

AddAgentSpanAttribute allows attributes to be added to spans.

func (*Thread) RecordActivity

func (thread *Thread) RecordActivity(now time.Time)

RecordActivity indicates that activity happened at this time on this goroutine which helps track total time.

func (*Thread) TotalTime

func (thread *Thread) TotalTime() time.Duration

TotalTime returns the amount to time that this thread contributes to the total time.

type TraceIDGenerator

type TraceIDGenerator struct {
	sync.Mutex
	// contains filtered or unexported fields
}

TraceIDGenerator creates identifiers for distributed tracing.

func NewTraceIDGenerator

func NewTraceIDGenerator(seed int64) *TraceIDGenerator

NewTraceIDGenerator creates a new trace identifier generator.

func (*TraceIDGenerator) GenerateTraceID

func (tg *TraceIDGenerator) GenerateTraceID() string

GenerateTraceID creates a new trace identifier.

type TxnCrossProcess

type TxnCrossProcess struct {
	// The user side switch controlling whether CAT is enabled or not.
	Enabled bool

	// The user side switch controlling whether Distributed Tracing is enabled or not
	// This is required by synthetics support.  If Distributed Tracing is enabled,
	// any synthetics functionality that is triggered should not set nr.guid.
	DistributedTracingEnabled bool

	// Rather than copying in the entire ConnectReply, here are the fields that
	// we need to support CAT.
	CrossProcessID  []byte
	EncodingKey     []byte
	TrustedAccounts trustedAccountSet

	// CAT state for a given transaction.
	Type                uint8
	ClientID            string
	GUID                string
	TripID              string
	PathHash            string
	AlternatePathHashes map[string]bool
	ReferringPathHash   string
	ReferringTxnGUID    string
	Synthetics          *cat.SyntheticsHeader

	// The encoded synthetics header received as part of the request headers, if
	// any. By storing this here, we avoid needing to marshal the invariant
	// Synthetics struct above each time an external segment is created.
	SyntheticsHeader string
}

TxnCrossProcess contains the metadata required for CAT and Synthetics headers, transaction events, and traces.

func (*TxnCrossProcess) CreateAppData

func (txp *TxnCrossProcess) CreateAppData(name string, queueTime, responseTime time.Duration, contentLength int64) (string, error)

CreateAppData creates the appData value that should be sent with a response to ensure CAT operates as expected.

func (*TxnCrossProcess) CreateCrossProcessMetadata

func (txp *TxnCrossProcess) CreateCrossProcessMetadata(txnName, appName string) (CrossProcessMetadata, error)

CreateCrossProcessMetadata generates request metadata that enable CAT and Synthetics support for an external segment.

func (*TxnCrossProcess) Finalise

func (txp *TxnCrossProcess) Finalise(txnName, appName string) error

Finalise handles any end-of-transaction tasks. In practice, this simply means ensuring the path hash is set if it hasn't already been.

func (*TxnCrossProcess) InboundHTTPRequest

func (txp *TxnCrossProcess) InboundHTTPRequest(hdr http.Header) error

InboundHTTPRequest adds the inbound request metadata to the TxnCrossProcess.

func (*TxnCrossProcess) Init

func (txp *TxnCrossProcess) Init(enabled bool, dt bool, reply *ConnectReply)

Init initialises a TxnCrossProcess based on the given application connect reply.

func (*TxnCrossProcess) IsInbound

func (txp *TxnCrossProcess) IsInbound() bool

IsInbound returns true if the transaction had inbound CAT headers.

func (*TxnCrossProcess) IsOutbound

func (txp *TxnCrossProcess) IsOutbound() bool

IsOutbound returns true if the transaction has generated outbound CAT headers.

func (*TxnCrossProcess) IsSynthetics

func (txp *TxnCrossProcess) IsSynthetics() bool

IsSynthetics returns true if the transaction had inbound Synthetics headers.

func (*TxnCrossProcess) ParseAppData

func (txp *TxnCrossProcess) ParseAppData(encodedAppData string) (*cat.AppDataHeader, error)

ParseAppData decodes the given appData value.

func (*TxnCrossProcess) SetInbound

func (txp *TxnCrossProcess) SetInbound(inbound bool)

SetInbound sets the inbound CAT flag. This function is provided only for internal and unit testing purposes, and should not be used outside of this package normally.

func (*TxnCrossProcess) SetOutbound

func (txp *TxnCrossProcess) SetOutbound(outbound bool)

SetOutbound sets the outbound CAT flag. This function is provided only for internal and unit testing purposes, and should not be used outside of this package normally.

func (*TxnCrossProcess) SetSynthetics

func (txp *TxnCrossProcess) SetSynthetics(synthetics bool)

SetSynthetics sets the Synthetics CAT flag. This function is provided only for internal and unit testing purposes, and should not be used outside of this package normally.

func (*TxnCrossProcess) Used

func (txp *TxnCrossProcess) Used() bool

Used returns true if any CAT or Synthetics related functionality has been triggered on the transaction.

type TxnData

type TxnData struct {
	TxnEvent
	IsWeb          bool
	Name           string    // Work in progress name.
	Errors         TxnErrors // Lazily initialized.
	Stop           time.Time
	ApdexThreshold time.Duration

	TraceIDGenerator       *TraceIDGenerator
	LazilyCalculateSampled func() bool
	SpanEventsEnabled      bool

	TxnTrace

	SlowQueriesEnabled bool
	SlowQueryThreshold time.Duration
	SlowQueries        *slowQueries

	// These better CAT supportability fields are left outside of
	// TxnEvent.BetterCAT to minimize the size of transaction event memory.
	DistributedTracingSupport
	// contains filtered or unexported fields
}

TxnData contains the recorded data of a transaction.

func (*TxnData) CurrentSpanIdentifier

func (t *TxnData) CurrentSpanIdentifier(thread *Thread) string

CurrentSpanIdentifier returns the identifier of the span at the top of the segment stack.

func (*TxnData) HasErrors

func (t *TxnData) HasErrors() bool

HasErrors indicates whether the transaction had errors.

type TxnError

type TxnError struct {
	ErrorData
	TxnEvent
}

TxnError combines error data with information about a transaction. TxnError is used for both error events and traced errors.

type TxnErrors

type TxnErrors []*ErrorData

TxnErrors is a set of errors captured in a Transaction.

func NewTxnErrors

func NewTxnErrors(max int) TxnErrors

NewTxnErrors returns a new empty TxnErrors.

func (*TxnErrors) Add

func (errors *TxnErrors) Add(e ErrorData)

Add adds a TxnError.

type TxnEvent

type TxnEvent struct {
	FinalName string
	Start     time.Time
	Duration  time.Duration
	TotalTime time.Duration
	Queuing   time.Duration
	Zone      ApdexZone
	Attrs     *Attributes
	DatastoreExternalTotals
	CrossProcess TxnCrossProcess
	BetterCAT    BetterCAT
	HasError     bool
}

TxnEvent represents a transaction. https://source.datanerd.us/agents/agent-specs/blob/master/Transaction-Events-PORTED.md https://newrelic.atlassian.net/wiki/display/eng/Agent+Support+for+Synthetics%3A+Forced+Transaction+Traces+and+Analytic+Events

func (*TxnEvent) MarshalJSON

func (e *TxnEvent) MarshalJSON() ([]byte, error)

MarshalJSON is used for testing.

func (*TxnEvent) WriteJSON

func (e *TxnEvent) WriteJSON(buf *bytes.Buffer)

WriteJSON prepares JSON in the format expected by the collector.

type TxnTrace

type TxnTrace struct {
	Enabled             bool
	SegmentThreshold    time.Duration
	StackTraceThreshold time.Duration
	// contains filtered or unexported fields
}

TxnTrace contains the work in progress transaction trace.

type Validator

type Validator interface {
	Error(...interface{})
}

Validator is used for testing.

func ExtendValidator

func ExtendValidator(v Validator, field interface{}) Validator

ExtendValidator is used to add more context to a validator.

type WantError

type WantError struct {
	TxnName         string
	Msg             string
	Klass           string
	UserAttributes  map[string]interface{}
	AgentAttributes map[string]interface{}
}

WantError is a traced error expectation.

type WantEvent

type WantEvent struct {
	Intrinsics      map[string]interface{}
	UserAttributes  map[string]interface{}
	AgentAttributes map[string]interface{}
}

WantEvent is a transaction or error event expectation.

type WantMetric

type WantMetric struct {
	Name   string
	Scope  string
	Forced interface{} // true, false, or nil
	Data   []float64
}

WantMetric is a metric expectation. If Data is nil, then any data values are acceptable. If Data has len 1, then only the metric count is validated.

type WantSlowQuery

type WantSlowQuery struct {
	Count        int32
	MetricName   string
	Query        string
	TxnName      string
	TxnURL       string
	DatabaseName string
	Host         string
	PortPathOrID string
	Params       map[string]interface{}
}

WantSlowQuery is a slowQuery expectation.

type WantTraceSegment

type WantTraceSegment struct {
	SegmentName string
	// RelativeStartMillis and RelativeStopMillis will be tested if they are
	// provided:  This makes it easy for top level tests which cannot
	// control duration.
	RelativeStartMillis interface{}
	RelativeStopMillis  interface{}
	Attributes          map[string]interface{}
	Children            []WantTraceSegment
}

WantTraceSegment is a transaction trace segment expectation.

type WantTxn

type WantTxn struct {
	Name      string
	IsWeb     bool
	NumErrors int
}

WantTxn provides the expectation parameters to ExpectTxnMetrics.

type WantTxnTrace

type WantTxnTrace struct {
	MetricName      string
	NumSegments     int
	UserAttributes  map[string]interface{}
	AgentAttributes map[string]interface{}
	Intrinsics      map[string]interface{}
	// If the Root's SegmentName is populated then the segments will be
	// tested, otherwise NumSegments will be tested.
	Root WantTraceSegment
}

WantTxnTrace is a transaction trace expectation.

Directories

Path Synopsis
Package cat provides functionality related to the wire format of CAT headers.
Package cat provides functionality related to the wire format of CAT headers.
Package integrationsupport exists to expose functionality to integration packages without adding noise to the public API.
Package integrationsupport exists to expose functionality to integration packages without adding noise to the public API.
Package jsonx extends the encoding/json package to encode JSON incrementally and without requiring reflection.
Package jsonx extends the encoding/json package to encode JSON incrementally and without requiring reflection.
Package stacktracetest helps test stack trace behavior.
Package stacktracetest helps test stack trace behavior.
tools
Package utilization implements the Utilization spec, available at https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md
Package utilization implements the Utilization spec, available at https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md

Jump to

Keyboard shortcuts

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