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

package internal

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

Index

Package Files

adaptive_sampler.go analytics_events.go apdex.go attributes.go browser.go collector.go compress.go connect_reply.go context.go cross_process_http.go custom_event.go custom_events.go custom_metric.go distributed_tracing.go environment.go error_events.go errors.go expect.go harvest.go intrinsics.go json_object_writer.go labels.go limits.go metric_names.go metric_rules.go metrics.go obfuscate.go priority.go queuing.go rand.go rules_cache.go sampler.go security_policies.go segment_terms.go serverless.go slow_queries.go span_events.go stack_frame.go stacktrace.go trace_id_generator.go tracing.go txn_cross_process.go txn_events.go txn_trace.go url.go utilities.go

Constants

const (
    // HarvestTypesEvents includes all Event types
    HarvestTypesEvents = HarvestSpanEvents | HarvestCustomEvents | HarvestTxnEvents | HarvestErrorEvents
    // HarvestTypesAll includes all harvest types
    HarvestTypesAll = HarvestMetricsTraces | HarvestTypesEvents
)
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
)
const (

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

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

Variables

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 (
    // 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")
)
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)
)
var (
    // MatchAnything is for use when matching attributes.
    MatchAnything = uniquePointer()
)
var (
    // SampleEnvironment is useful for testing.
    SampleEnvironment = Environment{
        Compiler: "comp",
        GOARCH:   "arch",
        GOOS:     "goos",
        Version:  "vers",
        NumCPU:   8,
    }
)
var (
    // ThisHost is the system hostname.
    ThisHost = func() string {
        if h, err := sysinfo.Hostname(); nil == err {
            return h
        }
        return unknownDatastoreHost
    }()
)

func AddAgentSpanAttribute Uses

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

AddAgentSpanAttribute allows instrumentation packages to add span attributes.

func AddUserAttribute Uses

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

AddUserAttribute adds a user attribute.

func ApdexFailingThreshold Uses

func ApdexFailingThreshold(threshold time.Duration) time.Duration

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

func AppDataToHTTPHeader Uses

func AppDataToHTTPHeader(appData string) http.Header

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

func BrowserAttributes Uses

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 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 ConnectAttempt Uses

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

ConnectAttempt tries to connect an application.

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 CreateTxnMetrics Uses

func CreateTxnMetrics(args *TxnData, metrics *metricTable)

CreateTxnMetrics creates metrics for a transaction.

func Deobfuscate Uses

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

Deobfuscate deobfuscates a byte array.

func EndBasicSegment Uses

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

EndBasicSegment ends a basic segment.

func EndDatastoreSegment Uses

func EndDatastoreSegment(p EndDatastoreParams) error

EndDatastoreSegment ends a datastore segment.

func EndExternalSegment Uses

func EndExternalSegment(p EndExternalParams) error

EndExternalSegment ends an external segment.

func EndMessageSegment Uses

func EndMessageSegment(p EndMessageParams) error

EndMessageSegment ends an external segment.

func ExpectCustomEvents Uses

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

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

func ExpectErrorEvents Uses

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

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

func ExpectErrors Uses

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

ExpectErrors allows testing of errors.

func ExpectMetrics Uses

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

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

func ExpectMetricsPresent Uses

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

ExpectMetricsPresent allows testing of metrics without requiring an exact match

func ExpectSlowQueries Uses

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

ExpectSlowQueries allows testing of slow queries.

func ExpectSpanEvents Uses

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

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

func ExpectTxnEvents Uses

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

ExpectTxnEvents allows testing of txn events.

func ExpectTxnMetrics Uses

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

ExpectTxnMetrics tests that the app contains metrics for a transaction.

func ExpectTxnTraces Uses

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

ExpectTxnTraces allows testing of transaction traces.

func FloatSecondsToDuration Uses

func FloatSecondsToDuration(seconds float64) time.Duration

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

func GetContentLengthFromHeader Uses

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 Uses

func HTTPHeaderToAppData(header http.Header) string

HTTPHeaderToAppData gets the appData value from the correct HTTP header.

func HarvestTesting Uses

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

HarvestTesting allows integration packages to test instrumentation.

func HostFromURL Uses

func HostFromURL(u *url.URL) string

HostFromURL returns the URL's host.

func MergeBreakdownMetrics Uses

func MergeBreakdownMetrics(t *TxnData, metrics *metricTable)

MergeBreakdownMetrics creates segment metrics.

func MergeTxnErrors Uses

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

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

func MetadataToHTTPHeader Uses

func MetadataToHTTPHeader(metadata CrossProcessMetadata) http.Header

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

func MinorVersion Uses

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 Uses

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

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

func ParseServerlessPayload Uses

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

ParseServerlessPayload exists for testing.

func QueueDuration Uses

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

QueueDuration TODO

func RandFloat32 Uses

func RandFloat32() float32

RandFloat32 returns a random float32 between 0.0 and 1.0.

func RandUint32 Uses

func RandUint32() uint32

RandUint32 returns a random uint32.

func RandUint64 Uses

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 Uses

func RandUint64N(max uint64) uint64

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

func RequestAgentAttributes Uses

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

RequestAgentAttributes gathers agent attributes out of the request.

func ResponseCodeAttribute Uses

func ResponseCodeAttribute(a *Attributes, code int)

ResponseCodeAttribute sets the response code agent attribute.

func ResponseHeaderAttributes Uses

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

ResponseHeaderAttributes gather agent attributes from the response headers.

func SafeURL Uses

func SafeURL(u *url.URL) string

SafeURL removes sensitive information from a URL.

func SafeURLFromString Uses

func SafeURLFromString(rawurl string) string

SafeURLFromString removes sensitive information from a URL.

func ServerlessWrite Uses

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

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

func StringLengthByteLimit Uses

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 Uses

func TimeToUnixMilliseconds(tm time.Time) uint64

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

func TrackUsage Uses

func TrackUsage(s ...string)

TrackUsage helps track which integration packages are used.

func ValidateUserAttribute Uses

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

ValidateUserAttribute validates a user attribute.

type AdaptiveSampler Uses

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 Uses

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

NewAdaptiveSampler creates an AdaptiveSampler.

type AddAgentAttributer Uses

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

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

type AddAgentSpanAttributer Uses

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

AddAgentSpanAttributer should be implemented by the Transaction.

type AgentAttributeID Uses

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 Uses

type AgentRunID string

AgentRunID identifies the current connection with the collector.

func (AgentRunID) String Uses

func (id AgentRunID) String() string

type ApdexZone Uses

type ApdexZone int

ApdexZone is a transaction classification.

const (
    ApdexNone ApdexZone = iota
    ApdexSatisfying
    ApdexTolerating
    ApdexFailing
)

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

func CalculateApdexZone Uses

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 Uses

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

AttributeConfig is created at connect and shared between all transactions.

func CreateAttributeConfig Uses

func CreateAttributeConfig(input AttributeConfigInput, includeEnabled bool) *AttributeConfig

CreateAttributeConfig creates a new AttributeConfig.

type AttributeConfigInput Uses

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 Uses

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

AttributeDestinationConfig matches newrelic.AttributeDestinationConfig to avoid circular dependency issues.

type Attributes Uses

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

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

func NewAttributes Uses

func NewAttributes(config *AttributeConfig) *Attributes

NewAttributes creates a new Attributes.

func (*Attributes) GetAgentValue Uses

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 Uses

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 Uses

func (e BetterCAT) TraceID() string

TraceID returns the trace id.

type ConnectJSONCreator Uses

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

    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 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 ConstructConnectReply Uses

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

type CrossProcessMetadata Uses

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 Uses

func HTTPHeaderToMetadata(header http.Header) CrossProcessMetadata

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

type CustomEvent Uses

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

CustomEvent is a custom event.

func CreateCustomEvent Uses

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

CreateCustomEvent creates a custom event.

func (*CustomEvent) MarshalJSON Uses

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

MarshalJSON is used for testing.

func (*CustomEvent) MergeIntoHarvest Uses

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

MergeIntoHarvest implements Harvestable.

func (*CustomEvent) WriteJSON Uses

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

WriteJSON prepares JSON in the format expected by the collector.

type CustomMetric Uses

type CustomMetric struct {
    RawInputName string
    Value        float64
}

CustomMetric is a custom metric.

func (CustomMetric) MergeIntoHarvest Uses

func (m CustomMetric) MergeIntoHarvest(h *Harvest)

MergeIntoHarvest implements Harvestable.

type DatastoreExternalTotals Uses

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

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

type DatastoreMetricKey Uses

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 Uses

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 Uses

func (d *DfltHarvestCfgr) MaxCustomEvents() int

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

func (*DfltHarvestCfgr) MaxErrorEvents Uses

func (d *DfltHarvestCfgr) MaxErrorEvents() int

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

func (*DfltHarvestCfgr) MaxSpanEvents Uses

func (d *DfltHarvestCfgr) MaxSpanEvents() int

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

func (*DfltHarvestCfgr) MaxTxnEvents Uses

func (d *DfltHarvestCfgr) MaxTxnEvents() int

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

func (*DfltHarvestCfgr) ReportPeriods Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func NewEnvironment() Environment

NewEnvironment returns a new Environment.

func (Environment) MarshalJSON Uses

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

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

type ErrInvalidAttributeType Uses

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

ErrInvalidAttributeType is returned when the value is not valid.

func (ErrInvalidAttributeType) Error Uses

func (e ErrInvalidAttributeType) Error() string

type ErrPayloadMissingField Uses

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

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

func (ErrPayloadMissingField) Error Uses

func (e ErrPayloadMissingField) Error() string

type ErrPayloadParse Uses

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

ErrPayloadParse indicates that the payload was malformed.

func (ErrPayloadParse) Error Uses

func (e ErrPayloadParse) Error() string

type ErrUnsupportedPayloadVersion Uses

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

ErrUnsupportedPayloadVersion indicates that the major version number is unknown.

func (ErrUnsupportedPayloadVersion) Error Uses

func (e ErrUnsupportedPayloadVersion) Error() string

type ErrorData Uses

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 Uses

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

TxnErrorFromPanic creates a new TxnError from a panic.

func TxnErrorFromResponseCode Uses

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

TxnErrorFromResponseCode creates a new TxnError from an http response code.

type ErrorEvent Uses

type ErrorEvent TxnError

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

func (*ErrorEvent) MarshalJSON Uses

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

MarshalJSON is used for testing.

func (*ErrorEvent) WriteJSON Uses

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 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(eventer MaxTxnEventer) 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 Harvest Uses

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 Uses

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

NewHarvest returns a new Harvest.

func (*Harvest) CreateFinalMetrics Uses

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

CreateFinalMetrics creates extra metrics at harvest time.

func (*Harvest) Payloads Uses

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

Payloads returns a slice of payload creators.

func (*Harvest) Ready Uses

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 Uses

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 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 HarvestTrace Uses

type HarvestTrace struct {
    TxnEvent
    Trace TxnTrace
}

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

func (*HarvestTrace) MarshalJSON Uses

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

MarshalJSON is used for testing.

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

type HarvestTypes Uses

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 Uses

type Harvestable interface {
    MergeIntoHarvest(h *Harvest)
}

Harvestable is something that can be merged into a Harvest.

type JSONString Uses

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 Uses

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

MarshalJSON returns the JSONString unmodified without any escaping.

type Labels Uses

type Labels map[string]string

Labels is used for connect JSON formatting.

func (Labels) MarshalJSON Uses

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

MarshalJSON requires a comment for golint?

type MaxTxnEventer Uses

type MaxTxnEventer interface {
    MaxTxnEvents() int
}

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

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 Payload Uses

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 Uses

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

AcceptPayload parses the inbound distributed tracing payload.

func (Payload) HTTPSafe Uses

func (p Payload) HTTPSafe() string

HTTPSafe implements newrelic.DistributedTracePayload.

func (Payload) IsValid Uses

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 Uses

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 Uses

func (p Payload) Text() string

Text implements newrelic.DistributedTracePayload.

type PayloadCreator Uses

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 Uses

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

PreconnectReply contains settings from the preconnect endpoint.

type Priority Uses

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 Uses

func NewPriority() Priority

NewPriority returns a new priority.

func (Priority) Float32 Uses

func (p Priority) Float32() float32

Float32 returns the priority as a float32.

func (*Priority) MarshalJSON Uses

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

MarshalJSON limits the number of decimals.

func (Priority) WriteJSON Uses

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

WriteJSON limits the number of decimals.

type RPMResponse Uses

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 Uses

func CollectorRequest(cmd RpmCmd, cs RpmControls) RPMResponse

CollectorRequest makes a request to New Relic.

func (RPMResponse) IsDisconnect Uses

func (resp RPMResponse) IsDisconnect() bool

IsDisconnect indicates that the agent should disconnect.

func (RPMResponse) IsRestartException Uses

func (resp RPMResponse) IsRestartException() bool

IsRestartException indicates that the agent should restart.

func (RPMResponse) ShouldSaveHarvestData Uses

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 Uses

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 Uses

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 Uses

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

Sample is a system/runtime snapshot.

func GetSample Uses

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

GetSample gathers a new Sample.

type SampleEverything Uses

type SampleEverything struct{}

SampleEverything is used for testing.

func (SampleEverything) ComputeSampled Uses

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

ComputeSampled implements AdaptiveSampler.

type SampleNothing Uses

type SampleNothing struct{}

SampleNothing is used when the application is not yet connected.

func (SampleNothing) ComputeSampled Uses

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

ComputeSampled implements AdaptiveSampler.

type Samples Uses

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 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 SegmentStartTime Uses

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 Uses

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

StartSegment begins a segment.

type ServerlessHarvest Uses

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 Uses

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

NewServerlessHarvest creates a new ServerlessHarvest.

func (*ServerlessHarvest) Consume Uses

func (sh *ServerlessHarvest) Consume(data Harvestable)

Consume adds data to the harvest.

func (*ServerlessHarvest) Write Uses

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 Uses

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

ServerlessWriter is implemented by newrelic.Application.

type SpanAttribute Uses

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 Uses

func (sa SpanAttribute) String() string

type SpanEvent Uses

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 Uses

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

MarshalJSON is used for testing.

func (*SpanEvent) WriteJSON Uses

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

WriteJSON prepares JSON in the format expected by the collector.

type StackTrace Uses

type StackTrace []uintptr

StackTrace is a stack trace.

func GetStackTrace Uses

func GetStackTrace() StackTrace

GetStackTrace returns a new StackTrace.

func (StackTrace) MarshalJSON Uses

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

MarshalJSON prepares JSON in the format expected by the collector.

func (StackTrace) WriteJSON Uses

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 Uses

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

Stats contains system information for a period of time.

func GetStats Uses

func GetStats(ss Samples) Stats

GetStats combines two Samples into a Stats.

func (Stats) MergeIntoHarvest Uses

func (s Stats) MergeIntoHarvest(h *Harvest)

MergeIntoHarvest implements Harvestable.

type Thread Uses

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 Uses

func NewThread(txndata *TxnData) *Thread

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

func (*Thread) AddAgentSpanAttribute Uses

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

AddAgentSpanAttribute allows attributes to be added to spans.

func (*Thread) RecordActivity Uses

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 Uses

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

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

type TraceIDGenerator Uses

type TraceIDGenerator struct {
    sync.Mutex
    // 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) GenerateTraceID Uses

func (tg *TraceIDGenerator) GenerateTraceID() string

GenerateTraceID creates a new trace identifier.

type TxnCrossProcess Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

InboundHTTPRequest adds the inbound request metadata to the TxnCrossProcess.

func (*TxnCrossProcess) Init Uses

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

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

func (*TxnCrossProcess) IsInbound Uses

func (txp *TxnCrossProcess) IsInbound() bool

IsInbound returns true if the transaction had inbound CAT headers.

func (*TxnCrossProcess) IsOutbound Uses

func (txp *TxnCrossProcess) IsOutbound() bool

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

func (*TxnCrossProcess) IsSynthetics Uses

func (txp *TxnCrossProcess) IsSynthetics() bool

IsSynthetics returns true if the transaction had inbound Synthetics headers.

func (*TxnCrossProcess) ParseAppData Uses

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

ParseAppData decodes the given appData value.

func (*TxnCrossProcess) SetInbound Uses

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 Uses

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 Uses

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 Uses

func (txp *TxnCrossProcess) Used() bool

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

type TxnData Uses

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 Uses

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

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

func (*TxnData) HasErrors Uses

func (t *TxnData) HasErrors() bool

HasErrors indicates whether the transaction had errors.

type TxnError Uses

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 Uses

type TxnErrors []*ErrorData

TxnErrors is a set of errors captured in a Transaction.

func NewTxnErrors Uses

func NewTxnErrors(max int) TxnErrors

NewTxnErrors returns a new empty TxnErrors.

func (*TxnErrors) Add Uses

func (errors *TxnErrors) Add(e ErrorData)

Add adds a TxnError.

type TxnEvent Uses

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 Uses

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

MarshalJSON is used for testing.

func (*TxnEvent) WriteJSON Uses

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

WriteJSON prepares JSON in the format expected by the collector.

type TxnTrace Uses

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 Uses

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

Validator is used for testing.

func ExtendValidator Uses

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

ExtendValidator is used to add more context to a validator.

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

PathSynopsis
catPackage cat provides functionality related to the wire format of CAT headers.
crossagent
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.
logger
sqlparse
stacktracetestPackage stacktracetest helps test stack trace behavior.
sysinfo
utilizationPackage utilization implements the Utilization spec, available at https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md

Package internal imports 28 packages (graph) and is imported by 29 packages. Updated 2019-12-07. Refresh now. Tools for package owners.