go-agent: github.com/newrelic/go-agent/v3/internal Index | Files | Directories

package internal

import "github.com/newrelic/go-agent/v3/internal"


Package Files

connect_reply.go context.go expect.go hidden_methods.go limits.go message_metric_key.go metric_rules.go security_policies.go segment_terms.go trace_id_generator.go usage.go utilities.go


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
const (

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


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

func AddAgentSpanAttribute Uses

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

AddAgentSpanAttribute allows instrumentation packages to add span attributes.

func CalculateApdexThreshold Uses

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

CalculateApdexThreshold calculates the apdex threshold.

func CompactJSONString Uses

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 Uses

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 Uses

func FloatSecondsToDuration(seconds float64) time.Duration

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

func GetUsageSupportabilityMetrics Uses

func GetUsageSupportabilityMetrics() []string

GetUsageSupportabilityMetrics returns supportability metric names.

func HarvestTesting Uses

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

HarvestTesting allows integration packages to test instrumentation.

func IsDisconnectSecurityPolicyError Uses

func IsDisconnectSecurityPolicyError(e error) bool

IsDisconnectSecurityPolicyError indicates if the error is disconnect worthy.

func ServerlessWrite Uses

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

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

func TrackUsage Uses

func TrackUsage(s ...string)

TrackUsage helps track which integration packages are used.

type AddAgentAttributer Uses

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

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

type AddAgentSpanAttributer Uses

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

AddAgentSpanAttributer should be implemented by the Transaction.

type AgentRunID Uses

type AgentRunID string

AgentRunID identifies the current connection with the collector.

func (AgentRunID) String Uses

func (id AgentRunID) String() string

type ConnectReply Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (r *ConnectReply) SetSampleEverything()

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

func (*ConnectReply) SetSampleNothing Uses

func (r *ConnectReply) SetSampleNothing()

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

type DialerFunc Uses

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 Uses

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 Uses

func DefaultEventHarvestConfig(maxTxnEvents int) EventHarvestConfig

DefaultEventHarvestConfig provides faster event harvest defaults.

type Expect Uses

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 Uses

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 Uses

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 Uses

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 Uses

type MetricRules []*metricRule

MetricRules is a collection of metric rules.

func (MetricRules) Apply Uses

func (rules MetricRules) Apply(input string) string

Apply applies the rules.

func (MetricRules) Len Uses

func (rules MetricRules) Len() int

Len returns the number of rules.

func (MetricRules) Less Uses

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

Rules should be applied in increasing order

func (MetricRules) Swap Uses

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

Swap is used for sorting.

func (*MetricRules) UnmarshalJSON Uses

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

UnmarshalJSON unmarshals rules from connect reply JSON.

type PreconnectReply Uses

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

PreconnectReply contains settings from the preconnect endpoint.

type SecurityPolicies Uses

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 Uses

func (sp *SecurityPolicies) PointerIfPopulated() *SecurityPolicies

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

func (*SecurityPolicies) UnmarshalJSON Uses

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

UnmarshalJSON decodes security policies sent from the preconnect endpoint.

type ServerlessWriter Uses

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

ServerlessWriter is implemented by newrelic.Application.

type TraceIDGenerator Uses

type TraceIDGenerator struct {
    // contains filtered or unexported fields

TraceIDGenerator creates identifiers for distributed tracing.

func NewTraceIDGenerator Uses

func NewTraceIDGenerator(seed int64) *TraceIDGenerator

NewTraceIDGenerator creates a new trace identifier generator.

func (*TraceIDGenerator) Float32 Uses

func (tg *TraceIDGenerator) Float32() float32

Float32 returns a random float32 from its random source.

func (*TraceIDGenerator) GenerateSpanID Uses

func (tg *TraceIDGenerator) GenerateSpanID() string

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

func (*TraceIDGenerator) GenerateTraceID Uses

func (tg *TraceIDGenerator) GenerateTraceID() string

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

type TrustedAccountSet Uses

type TrustedAccountSet map[int]struct{}

TrustedAccountSet is used for CAT.

func (*TrustedAccountSet) IsTrusted Uses

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

IsTrusted reveals whether the account can be trusted.

func (*TrustedAccountSet) UnmarshalJSON Uses

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

UnmarshalJSON unmarshals the trusted set from the connect reply JSON.

type Validator Uses

type Validator interface {

Validator is used for testing.

type WantError Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

type WantTxn struct {
    Name      string
    IsWeb     bool
    NumErrors int

WantTxn provides the expectation parameters to ExpectTxnMetrics.

type WantTxnTrace Uses

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.


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

Package internal imports 14 packages (graph) and is imported by 31 packages. Updated 2021-01-12. Refresh now. Tools for package owners.