internal

package
v3.3.9 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2022 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// 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
	// MaxPayloadSizeInBytes specifies the maximum payload size in bytes that
	// should be sent to any endpoint
	MaxPayloadSizeInBytes = 1000 * 1000

	// 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
)
View Source
const (

	// TraceIDHexStringLen is the length of the trace ID when represented
	// as a hex string.
	TraceIDHexStringLen = 32
)

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 (
	// MatchAnything is for use when matching attributes.
	MatchAnything = uniquePointer()
	// MatchAnyString is a placeholder for matching any string
	MatchAnyString = "xxANY-STRINGxx"
)

Functions

func AddAgentSpanAttribute

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

AddAgentSpanAttribute allows instrumentation packages to add span attributes.

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 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 FloatSecondsToDuration

func FloatSecondsToDuration(seconds float64) time.Duration

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

func GetUsageSupportabilityMetrics

func GetUsageSupportabilityMetrics() []string

GetUsageSupportabilityMetrics returns supportability metric names.

func HarvestTesting

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

HarvestTesting allows integration packages to test instrumentation.

func IsDisconnectSecurityPolicyError

func IsDisconnectSecurityPolicyError(e error) bool

IsDisconnectSecurityPolicyError indicates if the error is disconnect worthy.

func ServerlessWrite

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

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

func TrackUsage

func TrackUsage(s ...string)

TrackUsage helps track which integration packages are used.

Types

type AddAgentAttributer

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

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

type AddAgentSpanAttributer

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

AddAgentSpanAttributer should be implemented by the Transaction.

type AgentRunID

type AgentRunID string

AgentRunID identifies the current connection with the collector.

func (AgentRunID) String

func (id AgentRunID) String() string

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"`

	// 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:"-"`
	// DistributedTraceTimestampGenerator allows tests to fix the outbound
	// DT header timestamp.
	DistributedTraceTimestampGenerator func() time.Time `json:"-"`
	// TraceObsDialer allows tests to connect to a local TraceObserver directly
	TraceObsDialer DialerFunc

	// 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"`
}

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 UnmarshalConnectReply

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

UnmarshalConnectReply 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.

func (*ConnectReply) SetSampleEverything

func (r *ConnectReply) SetSampleEverything()

SetSampleEverything is used for testing to ensure span events get saved.

func (*ConnectReply) SetSampleNothing

func (r *ConnectReply) SetSampleNothing()

SetSampleNothing is used for testing to ensure no span events get saved.

type DialerFunc

type DialerFunc func(context.Context, string) (net.Conn, error)

DialerFunc is a shorthand that is used in tests for connecting directly to a local gRPC server

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(maxTxnEvents int) 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 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 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 MetricRules

type MetricRules []*metricRule

MetricRules is a collection of metric rules.

func (MetricRules) Apply

func (rules MetricRules) Apply(input string) string

Apply applies the rules.

func (MetricRules) Len

func (rules MetricRules) Len() int

Len returns the number of rules.

func (MetricRules) Less

func (rules MetricRules) Less(i, j int) bool

Rules should be applied in increasing order

func (MetricRules) Swap

func (rules MetricRules) Swap(i, j int)

Swap is used for sorting.

func (*MetricRules) UnmarshalJSON

func (rules *MetricRules) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON unmarshals rules from connect reply JSON.

type PreconnectReply

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

PreconnectReply contains settings from the preconnect endpoint.

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 ServerlessWriter

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

ServerlessWriter is implemented by newrelic.Application.

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) Float32

func (tg *TraceIDGenerator) Float32() float32

Float32 returns a random float32 from its random source.

func (*TraceIDGenerator) GenerateSpanID

func (tg *TraceIDGenerator) GenerateSpanID() string

GenerateSpanID creates a new span identifier, which is a 16 character hex string.

func (*TraceIDGenerator) GenerateTraceID

func (tg *TraceIDGenerator) GenerateTraceID() string

GenerateTraceID creates a new trace identifier, which is a 32 character hex string.

type TrustedAccountSet

type TrustedAccountSet map[int]struct{}

TrustedAccountSet is used for CAT.

func (*TrustedAccountSet) IsTrusted

func (t *TrustedAccountSet) IsTrusted(account int) bool

IsTrusted reveals whether the account can be trusted.

func (*TrustedAccountSet) UnmarshalJSON

func (t *TrustedAccountSet) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the trusted set from the connect reply JSON.

type Validator

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

Validator is used for testing.

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 {
	// DurationMillis is compared if non-nil.
	DurationMillis  *float64
	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