diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e553f372..eada1a590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,26 @@ # ChangeLog ## Unreleased +## 3.14.0 + +## Fixed +* Integration tags and `go.mod` files for integrations were updated so that [pkg.go.dev]() displays the documentation for each integration correctly. +* The `nrgrpc` server integration was reporting all non-`OK` grpc statuses as errors. This has now been changed so that only selected grpc status codes will be reported as errors. Others are shown (via transaction attributes) as "warnings" or "informational" messages. There is a built-in set of defaults as to which status codes are reported at which severity levels, but this may be overridden by the caller as desired. Also supports custom grpc error handling functions supplied by the user. + * This is implemented by adding `WithStatusHandler()` options to the end of the `UnaryServerInterceptor()` and `StreamServerInterceptor()` calls, thus extending the capability of those functions while retaining the existing functionality and usage syntax for backward compatibility. +* Added advice on the recommended usage of the `app.WaitForConnection()` method. Fixes [https://github.com/newrelic/go-agent/issues/296](Issue #296) + +## Added +* Added a convenience function to build distributed trace header set from a JSON string for use with the `AcceptDistributedTraceHeaders()` method. Normally, you must create a valid set of HTTP headers representing the trace identification information from the other trace so the new trace will be associated with it. This needs to be in a Go `http.Header` type value. + * If working only in Go, this may be just fine as it is. However, if the other trace information came from another source, possibly in a different language or environment, it is often the case that the trace data is already presented to you in the form of a JSON string. + * This new function, `DistributedTraceHeadersFromJSON()`, creates the required `http.Header` value from the JSON string without requiring manual effort on your part. + * We also provide a new all-in-one method `AcceptDistributedTraceHeadersFromJSON()` to be used in place of `AcceptDistributedTraceHeaders()`. It accepts a JSON string rather than an `http.Header`, adding its trace info to the new transaction in one step. + * Fixes [https://github.com/newrelic/go-agent/issues/331](Issue #331) + +### Changed +* Improved the NR AWS SDK V2 integration to use the current transaction rather than the one passed in during middleware creation, if `nil` is passed into nrawssdk-v2.AppendMiddlewares. Thanks to @HenriBeck for noticing and suggesting improvement, and thanks to @nc-wittj for the fantastic PR! [#328](https://github.com/newrelic/go-agent/pull/328) + +## Support Statement +New Relic recommends that you upgrade the agent regularly to ensure that you're getting the latest features and performance benefits. Additionally, older releases will no longer be supported when they reach end-of-life. ## 3.13.0 diff --git a/v3/integrations/nrawssdk-v2/example/main.go b/v3/integrations/nrawssdk-v2/example/main.go index d73f48708..d6c77e313 100644 --- a/v3/integrations/nrawssdk-v2/example/main.go +++ b/v3/integrations/nrawssdk-v2/example/main.go @@ -45,7 +45,7 @@ func main() { } // Instrument all new AWS clients with New Relic - nraws.AppendMiddlewares(&awsConfig.APIOptions, txn) + nraws.AppendMiddlewares(&awsConfig.APIOptions, nil) s3Client := s3.NewFromConfig(awsConfig) output, err := s3Client.ListBuckets(ctx, nil) diff --git a/v3/integrations/nrawssdk-v2/nrawssdk.go b/v3/integrations/nrawssdk-v2/nrawssdk.go index 2a844bcf5..8ff3a8ab6 100644 --- a/v3/integrations/nrawssdk-v2/nrawssdk.go +++ b/v3/integrations/nrawssdk-v2/nrawssdk.go @@ -50,6 +50,11 @@ func (m nrMiddleware) deserializeMiddleware(stack *smithymiddle.Stack) error { ctx context.Context, in smithymiddle.DeserializeInput, next smithymiddle.DeserializeHandler) ( out smithymiddle.DeserializeOutput, metadata smithymiddle.Metadata, err error) { + txn := m.txn + if txn == nil { + txn = newrelic.FromContext(ctx) + } + smithyRequest := in.Request.(*smithyhttp.Request) // The actual http.Request is inside the smithyhttp.Request @@ -70,10 +75,10 @@ func (m nrMiddleware) deserializeMiddleware(stack *smithymiddle.Stack) error { Host: httpRequest.URL.Host, PortPathOrID: httpRequest.URL.Port(), DatabaseName: "", - StartTime: m.txn.StartSegmentNow(), + StartTime: txn.StartSegmentNow(), } } else { - segment = newrelic.StartExternalSegment(m.txn, httpRequest) + segment = newrelic.StartExternalSegment(txn, httpRequest) } // Hand off execution to other middlewares and then perform the request @@ -84,15 +89,15 @@ func (m nrMiddleware) deserializeMiddleware(stack *smithymiddle.Stack) error { if ok { // Set additional span attributes - integrationsupport.AddAgentSpanAttribute(m.txn, + integrationsupport.AddAgentSpanAttribute(txn, newrelic.AttributeResponseCode, strconv.Itoa(response.StatusCode)) - integrationsupport.AddAgentSpanAttribute(m.txn, + integrationsupport.AddAgentSpanAttribute(txn, newrelic.SpanAttributeAWSOperation, operation) - integrationsupport.AddAgentSpanAttribute(m.txn, + integrationsupport.AddAgentSpanAttribute(txn, newrelic.SpanAttributeAWSRegion, region) requestID, ok := awsmiddle.GetRequestIDMetadata(metadata) if ok { - integrationsupport.AddAgentSpanAttribute(m.txn, + integrationsupport.AddAgentSpanAttribute(txn, newrelic.AttributeAWSRequestID, requestID) } } @@ -105,19 +110,34 @@ func (m nrMiddleware) deserializeMiddleware(stack *smithymiddle.Stack) error { // AppendMiddlewares inserts New Relic middleware in the given `apiOptions` for // the AWS SDK V2 for Go. It must be called only once per AWS configuration. // +// If `txn` is provided as nil, the New Relic transaction will be retrieved +// using `newrelic.FromContext`. +// // Additional attributes will be added to transaction trace segments and span // events: aws.region, aws.requestId, and aws.operation. In addition, // http.statusCode will be added to span events. // -// To see segments and spans for each AWS invocation, call AppendMiddlewares -// with the AWS Config `apiOptions` and pass in your current New Relic -// transaction. For example: +// To see segments and spans for all AWS invocations, call AppendMiddlewares +// with the AWS Config `apiOptions` and provide nil for `txn`. For example: +// +// awsConfig, err := config.LoadDefaultConfig(ctx) +// if err != nil { +// log.Fatal(err) +// } +// nraws.AppendMiddlewares(&awsConfig.APIOptions, nil) +// +// If do not want the transaction to be retrived from the context, you can +// explicitly set `txn`. For example: +// +// awsConfig, err := config.LoadDefaultConfig(ctx) +// if err != nil { +// log.Fatal(err) +// } +// +// ... // -// awsConfig, err := config.LoadDefaultConfig(ctx) -// if err != nil { -// log.Fatal(err) -// } -// nraws.AppendMiddlewares(ctx, &awsConfig.APIOptions, txn) +// txn := loadNewRelicTransaction() +// nraws.AppendMiddlewares(&awsConfig.APIOptions, txn) func AppendMiddlewares(apiOptions *[]func(*smithymiddle.Stack) error, txn *newrelic.Transaction) { m := nrMiddleware{txn: txn} *apiOptions = append(*apiOptions, m.deserializeMiddleware) diff --git a/v3/integrations/nrawssdk-v2/nrawssdk_test.go b/v3/integrations/nrawssdk-v2/nrawssdk_test.go index 521d8c741..c57bba514 100644 --- a/v3/integrations/nrawssdk-v2/nrawssdk_test.go +++ b/v3/integrations/nrawssdk-v2/nrawssdk_test.go @@ -188,54 +188,121 @@ var ( }...) ) -func TestInstrumentRequestExternal(t *testing.T) { - app := testApp() - txn := app.StartTransaction(txnName) - ctx := context.TODO() - - client := lambda.NewFromConfig(newConfig(ctx, txn)) - - input := &lambda.InvokeInput{ - ClientContext: aws.String("MyApp"), - FunctionName: aws.String("non-existent-function"), - InvocationType: types.InvocationTypeRequestResponse, - LogType: types.LogTypeTail, - Payload: []byte("{}"), - } +type testTableEntry struct { + Name string + + BuildContext func(txn *newrelic.Transaction) context.Context + BuildConfig func(ctx context.Context, txn *newrelic.Transaction) aws.Config +} - _, err := client.Invoke(ctx, input) - if err != nil { - t.Error(err) +func runTestTable(t *testing.T, table []*testTableEntry, executeEntry func(t *testing.T, entry *testTableEntry)) { + for _, entry := range table { + entry := entry // Pin range variable + + t.Run(entry.Name, func(t *testing.T) { + executeEntry(t, entry) + }) } +} + +func TestInstrumentRequestExternal(t *testing.T) { + runTestTable(t, + []*testTableEntry{ + { + Name: "with manually set transaction", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return context.Background() + }, + BuildConfig: newConfig, + }, + { + Name: "with transaction set in context", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return newrelic.NewContext(context.Background(), txn) + }, + BuildConfig: func(ctx context.Context, txn *newrelic.Transaction) aws.Config { + return newConfig(ctx, nil) // Set txn to nil to ensure transaction is retrieved from the context + }, + }, + }, + + func(t *testing.T, entry *testTableEntry) { + app := testApp() + txn := app.StartTransaction(txnName) + ctx := entry.BuildContext(txn) - txn.End() + client := lambda.NewFromConfig(entry.BuildConfig(ctx, txn)) - app.ExpectMetrics(t, externalMetrics) - app.ExpectSpanEvents(t, []internal.WantEvent{ - externalSpan, genericSpan}) + input := &lambda.InvokeInput{ + ClientContext: aws.String("MyApp"), + FunctionName: aws.String("non-existent-function"), + InvocationType: types.InvocationTypeRequestResponse, + LogType: types.LogTypeTail, + Payload: []byte("{}"), + } + + _, err := client.Invoke(ctx, input) + if err != nil { + t.Error(err) + } + + txn.End() + + app.ExpectMetrics(t, externalMetrics) + app.ExpectSpanEvents(t, []internal.WantEvent{ + externalSpan, genericSpan}) + }, + ) } func TestInstrumentRequestDatastore(t *testing.T) { - app := testApp() - txn := app.StartTransaction(txnName) - ctx := context.TODO() + runTestTable(t, + []*testTableEntry{ + { + Name: "with manually set transaction", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return context.Background() + }, + BuildConfig: newConfig, + }, + { + Name: "with transaction set in context", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return newrelic.NewContext(context.Background(), txn) + }, + BuildConfig: func(ctx context.Context, txn *newrelic.Transaction) aws.Config { + return newConfig(ctx, nil) // Set txn to nil to ensure transaction is retrieved from the context + }, + }, + }, - client := dynamodb.NewFromConfig(newConfig(ctx, txn)) + func(t *testing.T, entry *testTableEntry) { + app := testApp() + txn := app.StartTransaction(txnName) + ctx := entry.BuildContext(txn) - input := &dynamodb.DescribeTableInput{ - TableName: aws.String("thebesttable"), - } + client := dynamodb.NewFromConfig(entry.BuildConfig(ctx, txn)) - _, err := client.DescribeTable(ctx, input) - if err != nil { - t.Error(err) - } + input := &dynamodb.DescribeTableInput{ + TableName: aws.String("thebesttable"), + } + + _, err := client.DescribeTable(ctx, input) + if err != nil { + t.Error(err) + } - txn.End() + txn.End() - app.ExpectMetrics(t, datastoreMetrics) - app.ExpectSpanEvents(t, []internal.WantEvent{ - datastoreSpan, genericSpan}) + app.ExpectMetrics(t, datastoreMetrics) + app.ExpectSpanEvents(t, []internal.WantEvent{ + datastoreSpan, genericSpan}) + }, + ) } type firstFailingTransport struct { @@ -259,142 +326,192 @@ func (t *firstFailingTransport) RoundTrip(r *http.Request) (*http.Response, erro } func TestRetrySend(t *testing.T) { - app := testApp() - txn := app.StartTransaction(txnName) - ctx := context.TODO() - - cfg := newConfig(ctx, txn) - - cfg.HTTPClient = &http.Client{ - Transport: &firstFailingTransport{failing: true}, - } - - customRetry := retry.NewStandard(func(o *retry.StandardOptions) { - o.MaxAttempts = 2 - }) - client := lambda.NewFromConfig(cfg, func(o *lambda.Options) { - o.Retryer = customRetry - }) - - input := &lambda.InvokeInput{ - ClientContext: aws.String("MyApp"), - FunctionName: aws.String("non-existent-function"), - InvocationType: types.InvocationTypeRequestResponse, - LogType: types.LogTypeTail, - Payload: []byte("{}"), - } - - _, err := client.Invoke(ctx, input) - if err != nil { - t.Error(err) - } - - txn.End() - - app.ExpectMetrics(t, externalMetrics) - - app.ExpectSpanEvents(t, []internal.WantEvent{ - { - Intrinsics: map[string]interface{}{ - "name": "External/lambda.us-west-2.amazonaws.com/http/POST", - "sampled": true, - "category": "http", - "priority": internal.MatchAnything, - "guid": internal.MatchAnything, - "transactionId": internal.MatchAnything, - "traceId": internal.MatchAnything, - "parentId": internal.MatchAnything, - "component": "http", - "span.kind": "client", + runTestTable(t, + []*testTableEntry{ + { + Name: "with manually set transaction", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return context.Background() + }, + BuildConfig: newConfig, }, - UserAttributes: map[string]interface{}{}, - AgentAttributes: map[string]interface{}{ - "aws.operation": "Invoke", - "aws.region": awsRegion, - "http.method": "POST", - "http.url": "https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/non-existent-function/invocations", - "http.statusCode": "0", + { + Name: "with transaction set in context", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return newrelic.NewContext(context.Background(), txn) + }, + BuildConfig: func(ctx context.Context, txn *newrelic.Transaction) aws.Config { + return newConfig(ctx, nil) // Set txn to nil to ensure transaction is retrieved from the context + }, }, - }, { - Intrinsics: map[string]interface{}{ - "name": "External/lambda.us-west-2.amazonaws.com/http/POST", - "sampled": true, - "category": "http", - "priority": internal.MatchAnything, - "guid": internal.MatchAnything, - "transactionId": internal.MatchAnything, - "traceId": internal.MatchAnything, - "parentId": internal.MatchAnything, - "component": "http", - "span.kind": "client", - }, - UserAttributes: map[string]interface{}{}, - AgentAttributes: map[string]interface{}{ - "aws.operation": "Invoke", - "aws.region": awsRegion, - "aws.requestId": requestID, - "http.method": "POST", - "http.url": "https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/non-existent-function/invocations", - "http.statusCode": "200", - }, - }, { - Intrinsics: map[string]interface{}{ - "name": "OtherTransaction/Go/" + txnName, - "transaction.name": "OtherTransaction/Go/" + txnName, - "sampled": true, - "category": "generic", - "priority": internal.MatchAnything, - "guid": internal.MatchAnything, - "transactionId": internal.MatchAnything, - "nr.entryPoint": true, - "traceId": internal.MatchAnything, - }, - UserAttributes: map[string]interface{}{}, - AgentAttributes: map[string]interface{}{}, - }}) + }, + + func(t *testing.T, entry *testTableEntry) { + app := testApp() + txn := app.StartTransaction(txnName) + ctx := entry.BuildContext(txn) + + cfg := entry.BuildConfig(ctx, txn) + + cfg.HTTPClient = &http.Client{ + Transport: &firstFailingTransport{failing: true}, + } + + customRetry := retry.NewStandard(func(o *retry.StandardOptions) { + o.MaxAttempts = 2 + }) + client := lambda.NewFromConfig(cfg, func(o *lambda.Options) { + o.Retryer = customRetry + }) + + input := &lambda.InvokeInput{ + ClientContext: aws.String("MyApp"), + FunctionName: aws.String("non-existent-function"), + InvocationType: types.InvocationTypeRequestResponse, + LogType: types.LogTypeTail, + Payload: []byte("{}"), + } + + _, err := client.Invoke(ctx, input) + if err != nil { + t.Error(err) + } + + txn.End() + + app.ExpectMetrics(t, externalMetrics) + + app.ExpectSpanEvents(t, []internal.WantEvent{ + { + Intrinsics: map[string]interface{}{ + "name": "External/lambda.us-west-2.amazonaws.com/http/POST", + "sampled": true, + "category": "http", + "priority": internal.MatchAnything, + "guid": internal.MatchAnything, + "transactionId": internal.MatchAnything, + "traceId": internal.MatchAnything, + "parentId": internal.MatchAnything, + "component": "http", + "span.kind": "client", + }, + UserAttributes: map[string]interface{}{}, + AgentAttributes: map[string]interface{}{ + "aws.operation": "Invoke", + "aws.region": awsRegion, + "http.method": "POST", + "http.url": "https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/non-existent-function/invocations", + "http.statusCode": "0", + }, + }, { + Intrinsics: map[string]interface{}{ + "name": "External/lambda.us-west-2.amazonaws.com/http/POST", + "sampled": true, + "category": "http", + "priority": internal.MatchAnything, + "guid": internal.MatchAnything, + "transactionId": internal.MatchAnything, + "traceId": internal.MatchAnything, + "parentId": internal.MatchAnything, + "component": "http", + "span.kind": "client", + }, + UserAttributes: map[string]interface{}{}, + AgentAttributes: map[string]interface{}{ + "aws.operation": "Invoke", + "aws.region": awsRegion, + "aws.requestId": requestID, + "http.method": "POST", + "http.url": "https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/non-existent-function/invocations", + "http.statusCode": "200", + }, + }, { + Intrinsics: map[string]interface{}{ + "name": "OtherTransaction/Go/" + txnName, + "transaction.name": "OtherTransaction/Go/" + txnName, + "sampled": true, + "category": "generic", + "priority": internal.MatchAnything, + "guid": internal.MatchAnything, + "transactionId": internal.MatchAnything, + "nr.entryPoint": true, + "traceId": internal.MatchAnything, + }, + UserAttributes: map[string]interface{}{}, + AgentAttributes: map[string]interface{}{}, + }}) + }, + ) } func TestRequestSentTwice(t *testing.T) { - app := testApp() - txn := app.StartTransaction(txnName) - ctx := context.TODO() - - client := lambda.NewFromConfig(newConfig(ctx, txn)) - - input := &lambda.InvokeInput{ - ClientContext: aws.String("MyApp"), - FunctionName: aws.String("non-existent-function"), - InvocationType: types.InvocationTypeRequestResponse, - LogType: types.LogTypeTail, - Payload: []byte("{}"), - } - - _, firstErr := client.Invoke(ctx, input) - if firstErr != nil { - t.Error(firstErr) - } - - _, secondErr := client.Invoke(ctx, input) - if secondErr != nil { - t.Error(secondErr) - } - - txn.End() + runTestTable(t, + []*testTableEntry{ + { + Name: "with manually set transaction", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return context.Background() + }, + BuildConfig: newConfig, + }, + { + Name: "with transaction set in context", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return newrelic.NewContext(context.Background(), txn) + }, + BuildConfig: func(ctx context.Context, txn *newrelic.Transaction) aws.Config { + return newConfig(ctx, nil) // Set txn to nil to ensure transaction is retrieved from the context + }, + }, + }, - app.ExpectMetrics(t, []internal.WantMetric{ - {Name: "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", Scope: "", Forced: false, Data: nil}, - {Name: "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther", Scope: "", Forced: false, Data: nil}, - {Name: "External/all", Scope: "", Forced: true, Data: []float64{2}}, - {Name: "External/allOther", Scope: "", Forced: true, Data: []float64{2}}, - {Name: "External/lambda.us-west-2.amazonaws.com/all", Scope: "", Forced: false, Data: []float64{2}}, - {Name: "External/lambda.us-west-2.amazonaws.com/http/POST", Scope: "OtherTransaction/Go/" + txnName, Forced: false, Data: []float64{2}}, - {Name: "OtherTransaction/Go/" + txnName, Scope: "", Forced: true, Data: nil}, - {Name: "OtherTransaction/all", Scope: "", Forced: true, Data: nil}, - {Name: "OtherTransactionTotalTime/Go/" + txnName, Scope: "", Forced: false, Data: nil}, - {Name: "OtherTransactionTotalTime", Scope: "", Forced: true, Data: nil}, - }) - app.ExpectSpanEvents(t, []internal.WantEvent{ - externalSpan, externalSpan, genericSpan}) + func(t *testing.T, entry *testTableEntry) { + app := testApp() + txn := app.StartTransaction(txnName) + ctx := entry.BuildContext(txn) + + client := lambda.NewFromConfig(entry.BuildConfig(ctx, txn)) + + input := &lambda.InvokeInput{ + ClientContext: aws.String("MyApp"), + FunctionName: aws.String("non-existent-function"), + InvocationType: types.InvocationTypeRequestResponse, + LogType: types.LogTypeTail, + Payload: []byte("{}"), + } + + _, firstErr := client.Invoke(ctx, input) + if firstErr != nil { + t.Error(firstErr) + } + + _, secondErr := client.Invoke(ctx, input) + if secondErr != nil { + t.Error(secondErr) + } + + txn.End() + + app.ExpectMetrics(t, []internal.WantMetric{ + {Name: "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", Scope: "", Forced: false, Data: nil}, + {Name: "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther", Scope: "", Forced: false, Data: nil}, + {Name: "External/all", Scope: "", Forced: true, Data: []float64{2}}, + {Name: "External/allOther", Scope: "", Forced: true, Data: []float64{2}}, + {Name: "External/lambda.us-west-2.amazonaws.com/all", Scope: "", Forced: false, Data: []float64{2}}, + {Name: "External/lambda.us-west-2.amazonaws.com/http/POST", Scope: "OtherTransaction/Go/" + txnName, Forced: false, Data: []float64{2}}, + {Name: "OtherTransaction/Go/" + txnName, Scope: "", Forced: true, Data: nil}, + {Name: "OtherTransaction/all", Scope: "", Forced: true, Data: nil}, + {Name: "OtherTransactionTotalTime/Go/" + txnName, Scope: "", Forced: false, Data: nil}, + {Name: "OtherTransactionTotalTime", Scope: "", Forced: true, Data: nil}, + }) + app.ExpectSpanEvents(t, []internal.WantEvent{ + externalSpan, externalSpan, genericSpan}) + }, + ) } type noRequestIDTransport struct{} @@ -408,31 +525,56 @@ func (t *noRequestIDTransport) RoundTrip(r *http.Request) (*http.Response, error } func TestNoRequestIDFound(t *testing.T) { - app := testApp() - txn := app.StartTransaction(txnName) - ctx := context.TODO() - - cfg := newConfig(ctx, txn) - cfg.HTTPClient = &http.Client{ - Transport: &noRequestIDTransport{}, - } - client := lambda.NewFromConfig(cfg) - - input := &lambda.InvokeInput{ - ClientContext: aws.String("MyApp"), - FunctionName: aws.String("non-existent-function"), - InvocationType: types.InvocationTypeRequestResponse, - LogType: types.LogTypeTail, - Payload: []byte("{}"), - } - _, err := client.Invoke(ctx, input) - if err != nil { - t.Error(err) - } - - txn.End() + runTestTable(t, + []*testTableEntry{ + { + Name: "with manually set transaction", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return context.Background() + }, + BuildConfig: newConfig, + }, + { + Name: "with transaction set in context", + + BuildContext: func(txn *newrelic.Transaction) context.Context { + return newrelic.NewContext(context.Background(), txn) + }, + BuildConfig: func(ctx context.Context, txn *newrelic.Transaction) aws.Config { + return newConfig(ctx, nil) // Set txn to nil to ensure transaction is retrieved from the context + }, + }, + }, - app.ExpectMetrics(t, externalMetrics) - app.ExpectSpanEvents(t, []internal.WantEvent{ - externalSpanNoRequestID, genericSpan}) + func(t *testing.T, entry *testTableEntry) { + app := testApp() + txn := app.StartTransaction(txnName) + ctx := entry.BuildContext(txn) + + cfg := entry.BuildConfig(ctx, txn) + cfg.HTTPClient = &http.Client{ + Transport: &noRequestIDTransport{}, + } + client := lambda.NewFromConfig(cfg) + + input := &lambda.InvokeInput{ + ClientContext: aws.String("MyApp"), + FunctionName: aws.String("non-existent-function"), + InvocationType: types.InvocationTypeRequestResponse, + LogType: types.LogTypeTail, + Payload: []byte("{}"), + } + _, err := client.Invoke(ctx, input) + if err != nil { + t.Error(err) + } + + txn.End() + + app.ExpectMetrics(t, externalMetrics) + app.ExpectSpanEvents(t, []internal.WantEvent{ + externalSpanNoRequestID, genericSpan}) + }, + ) } diff --git a/v3/integrations/nrb3/LICENSE.txt b/v3/integrations/nrb3/LICENSE.txt new file mode 100644 index 000000000..cee548c2d --- /dev/null +++ b/v3/integrations/nrb3/LICENSE.txt @@ -0,0 +1,206 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Versions 3.8.0 and above for this project are licensed under Apache 2.0. For +prior versions of this project, please see the LICENCE.txt file in the root +directory of that version for more information. diff --git a/v3/integrations/nrb3/go.mod b/v3/integrations/nrb3/go.mod new file mode 100644 index 000000000..d3d2447d1 --- /dev/null +++ b/v3/integrations/nrb3/go.mod @@ -0,0 +1 @@ +module github.com/newrelic/go-agent/v3/integrations/nrb3 diff --git a/v3/integrations/nrgrpc/nrgrpc_client_test.go b/v3/integrations/nrgrpc/nrgrpc_client_test.go index 902e28a1a..f91d568d4 100644 --- a/v3/integrations/nrgrpc/nrgrpc_client_test.go +++ b/v3/integrations/nrgrpc/nrgrpc_client_test.go @@ -95,15 +95,15 @@ func TestUnaryClientInterceptor(t *testing.T) { client := testapp.NewTestApplicationClient(conn) resp, err := client.DoUnaryUnary(ctx, &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryUnary failed", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(resp.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } - if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || "" == hdr[0] { + if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || hdr[0] == "" { t.Error("distributed trace header not sent", hdrs) } txn.End() @@ -175,7 +175,7 @@ func TestUnaryStreamClientInterceptor(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoUnaryStream(ctx, &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryStream failed", err) } var recved int @@ -184,15 +184,15 @@ func TestUnaryStreamClientInterceptor(t *testing.T) { if err == io.EOF { break } - if nil != err { + if err != nil { t.Fatal("error receiving message", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(msg.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } - if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || "" == hdr[0] { + if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || hdr[0] == "" { t.Error("distributed trace header not sent", hdrs) } recved++ @@ -269,11 +269,11 @@ func TestStreamUnaryClientInterceptor(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoStreamUnary(ctx) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamUnary failed", err) } for i := 0; i < 3; i++ { - if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); nil != err { + if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); err != nil { if err == io.EOF { break } @@ -281,15 +281,15 @@ func TestStreamUnaryClientInterceptor(t *testing.T) { } } msg, err := stream.CloseAndRecv() - if nil != err { + if err != nil { t.Fatal("failure to CloseAndRecv", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(msg.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } - if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || "" == hdr[0] { + if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || hdr[0] == "" { t.Error("distributed trace header not sent", hdrs) } txn.End() @@ -361,7 +361,7 @@ func TestStreamStreamClientInterceptor(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoStreamStream(ctx) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamStream failed", err) } waitc := make(chan struct{}) @@ -378,10 +378,10 @@ func TestStreamStreamClientInterceptor(t *testing.T) { } var hdrs map[string][]string err = json.Unmarshal([]byte(msg.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } - if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || "" == hdr[0] { + if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || hdr[0] == "" { t.Error("distributed trace header not sent", hdrs) } recved++ @@ -473,18 +473,18 @@ func TestClientUnaryMetadata(t *testing.T) { client := testapp.NewTestApplicationClient(conn) resp, err := client.DoUnaryUnary(ctx, &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryUnary failed", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(resp.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } - if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || "" == hdr[0] || "payload" == hdr[0] { + if hdr, ok := hdrs["newrelic"]; !ok || len(hdr) != 1 || hdr[0] == "" || hdr[0] == "payload" { t.Error("distributed trace header not sent", hdrs) } - if hdr, ok := hdrs["testing"]; !ok || len(hdr) != 1 || "hello world" != hdr[0] { + if hdr, ok := hdrs["testing"]; !ok || len(hdr) != 1 || hdr[0] != "hello world" { t.Error("testing header not sent", hdrs) } } @@ -496,12 +496,12 @@ func TestNilTxnClientUnary(t *testing.T) { client := testapp.NewTestApplicationClient(conn) resp, err := client.DoUnaryUnary(context.Background(), &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryUnary failed", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(resp.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } if _, ok := hdrs["newrelic"]; ok { @@ -516,11 +516,11 @@ func TestNilTxnClientStreaming(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoStreamUnary(context.Background()) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamUnary failed", err) } for i := 0; i < 3; i++ { - if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); nil != err { + if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); err != nil { if err == io.EOF { break } @@ -528,12 +528,12 @@ func TestNilTxnClientStreaming(t *testing.T) { } } msg, err := stream.CloseAndRecv() - if nil != err { + if err != nil { t.Fatal("failure to CloseAndRecv", err) } var hdrs map[string][]string err = json.Unmarshal([]byte(msg.Text), &hdrs) - if nil != err { + if err != nil { t.Fatal("cannot unmarshall client response", err) } if _, ok := hdrs["newrelic"]; ok { @@ -557,7 +557,7 @@ func TestClientStreamingError(t *testing.T) { defer cancel() ctx = newrelic.NewContext(ctx, txn) _, err := client.DoUnaryStream(ctx, &testapp.Message{}) - if nil == err { + if err == nil { t.Fatal("client call to DoUnaryStream did not return error") } txn.End() diff --git a/v3/integrations/nrgrpc/nrgrpc_doc.go b/v3/integrations/nrgrpc/nrgrpc_doc.go index 075b4f610..c059d13fe 100644 --- a/v3/integrations/nrgrpc/nrgrpc_doc.go +++ b/v3/integrations/nrgrpc/nrgrpc_doc.go @@ -1,6 +1,7 @@ // Copyright 2020 New Relic Corporation. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +// // Package nrgrpc instruments https://github.com/grpc/grpc-go. // // This package can be used to instrument gRPC servers and gRPC clients. @@ -9,18 +10,58 @@ // // To instrument a gRPC server, use UnaryServerInterceptor and // StreamServerInterceptor with your newrelic.Application to create server -// interceptors to pass to grpc.NewServer. Example: +// interceptors to pass to grpc.NewServer. // +// The results of these calls are reported as errors or as informational +// messages (of levels OK, Info, Warning, or Error) based on the gRPC status +// code they return. // -// app, _ := newrelic.NewApplication( -// newrelic.ConfigAppName("gRPC Server"), -// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), -// newrelic.ConfigDebugLogger(os.Stdout), -// ) -// server := grpc.NewServer( -// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)), -// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), -// ) +// In the simplest case, simply add interceptors as in the following example: +// +// app, _ := newrelic.NewApplication( +// newrelic.ConfigAppName("gRPC Server"), +// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), +// newrelic.ConfigDebugLogger(os.Stdout), +// ) +// server := grpc.NewServer( +// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)), +// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), +// ) +// +// The disposition of each, in terms of how to report each of the various +// gRPC status codes, is determined by a built-in set of defaults: +// OK OK +// Info AlreadyExists, Canceled, InvalidArgument, NotFound, +// Unauthenticated +// Warning Aborted, DeadlineExceeded, FailedPrecondition, OutOfRange, +// PermissionDenied, ResourceExhausted, Unavailable +// Error DataLoss, Internal, Unknown, Unimplemented +// +// These +// may be overridden on a case-by-case basis using `WithStatusHandler()` +// options to each `UnaryServerInterceptor()` or `StreamServerInterceptor()` +// call, or globally via the `Configure()` function. +// +// For example, to report DeadlineExceeded as an error and NotFound +// as a warning, for the UnaryInterceptor only: +// server := grpc.NewServer( +// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app, +// nrgrpc.WithStatusHandler(codes.DeadlineExceeded, nrgrpc.ErrorInterceptorStatusHandler), +// nrgrpc.WithStatusHandler(codes.NotFound, nrgrpc.WarningInterceptorStatusHandler)), +// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), +// ) +// +// If you wanted to make those two changes to the overall default behavior, so they +// apply to all subsequently declared interceptors: +// nrgrpc.Configure( +// nrgrpc.WithStatusHandler(codes.DeadlineExceeded, nrgrpc.ErrorInterceptorStatusHandler), +// nrgrpc.WithStatusHandler(codes.NotFound, nrgrpc.WarningInterceptorStatusHandler), +// ) +// server := grpc.NewServer( +// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)), +// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), +// ) +// In this case the new behavior for those two status codes applies to both interceptors. // // These interceptors create transactions for inbound calls. The transaction is // added to the call context and can be accessed in your method handlers diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index e8119c66e..afca8033b 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -1,6 +1,36 @@ // Copyright 2020 New Relic Corporation. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +// +// This integration instruments grpc service calls via +// UnaryServerInterceptor() and StreamServerInterceptor() functions. +// +// The results of these calls are reported as errors or as informational +// messages (of levels OK, Info, Warning, or Error) based on the gRPC status +// code they return. +// +// In the simplest case, simply add interceptors as in the following example: +// +// app, _ := newrelic.NewApplication( +// newrelic.ConfigAppName("gRPC Server"), +// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), +// newrelic.ConfigDebugLogger(os.Stdout), +// ) +// server := grpc.NewServer( +// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)), +// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), +// ) +// +// The disposition of each, in terms of how to report each of the various +// gRPC status codes, is determined by a built-in set of defaults. These +// may be overridden on a case-by-case basis using WithStatusHandler() +// options to each UnaryServerInterceptor() or StreamServerInterceptor() +// call, or globally via the Configure() function. +// +// Full example: +// https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrgrpc/example/server/server.go +// + package nrgrpc import ( @@ -10,6 +40,7 @@ import ( "github.com/newrelic/go-agent/v3/newrelic" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -42,6 +73,173 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod return txn } +// +// ErrorHandler is the type of a gRPC status handler function. +// Normally the supplied set of ErrorHandler functions will suffice, but +// a custom handler may be crafted by the user and installed as a handler +// if needed. +// +type ErrorHandler func(context.Context, *newrelic.Transaction, *status.Status) + +// +// Internal registry of handlers associated with various +// status codes. +// +type statusHandlerMap map[codes.Code]ErrorHandler + +// +// interceptorStatusHandlerRegistry is the current default set of handlers +// used by each interceptor. +// +var interceptorStatusHandlerRegistry = statusHandlerMap{ + codes.OK: OKInterceptorStatusHandler, + codes.Canceled: InfoInterceptorStatusHandler, + codes.Unknown: ErrorInterceptorStatusHandler, + codes.InvalidArgument: InfoInterceptorStatusHandler, + codes.DeadlineExceeded: WarningInterceptorStatusHandler, + codes.NotFound: InfoInterceptorStatusHandler, + codes.AlreadyExists: InfoInterceptorStatusHandler, + codes.PermissionDenied: WarningInterceptorStatusHandler, + codes.ResourceExhausted: WarningInterceptorStatusHandler, + codes.FailedPrecondition: WarningInterceptorStatusHandler, + codes.Aborted: WarningInterceptorStatusHandler, + codes.OutOfRange: WarningInterceptorStatusHandler, + codes.Unimplemented: ErrorInterceptorStatusHandler, + codes.Internal: ErrorInterceptorStatusHandler, + codes.Unavailable: WarningInterceptorStatusHandler, + codes.DataLoss: ErrorInterceptorStatusHandler, + codes.Unauthenticated: InfoInterceptorStatusHandler, +} + +type handlerOption func(statusHandlerMap) + +// +// WithStatusHandler() indicates a handler function to be used to +// report the indicated gRPC status. Zero or more of these may be +// given to the Configure(), StreamServiceInterceptor(), or +// UnaryServiceInterceptor() functions. +// +// The ErrorHandler parameter is generally one of the provided standard +// reporting functions: +// OKInterceptorStatusHandler // report the operation as successful +// ErrorInterceptorStatusHandler // report the operation as an error +// WarningInterceptorStatusHandler // report the operation as a warning +// InfoInterceptorStatusHandler // report the operation as an informational message +// +// The following reporting function should only be used if you know for sure +// you want this. It does not report the error in any way at all, but completely +// ignores it. +// IgnoreInterceptorStatusHandler // report the operation as successful +// +// Finally, if you have a custom reporting need that isn't covered by the standard +// handler functions, you can create your own handler function as +// func myHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { +// ... +// } +// Within the function, do whatever you need to do with the txn parameter to report the +// gRPC status passed as s. If needed, the context is also passed to your function. +// +// If you wish to use your custom handler for a code such as codes.NotFound, you would +// include the parameter +// WithStatusHandler(codes.NotFound, myHandler) +// to your Configure(), StreamServiceInterceptor(), or UnaryServiceInterceptor() function. +// +func WithStatusHandler(c codes.Code, h ErrorHandler) handlerOption { + return func(m statusHandlerMap) { + m[c] = h + } +} + +// +// Configure() takes a list of WithStatusHandler() options and sets them +// as the new default handlers for the specified gRPC status codes, in the same +// way as if WithStatusHandler() were given to the StreamServiceInterceptor() +// or UnaryServiceInterceptor() functions (q.v.); however, in this case the new handlers +// become the default for any subsequent interceptors created by the above functions. +// +func Configure(options ...handlerOption) { + for _, option := range options { + option(interceptorStatusHandlerRegistry) + } +} + +// +// Standard handler: IGNORE +// This does not report anything at all in the context. +// +func IgnoreInterceptorStatusHandler(_ context.Context, _ *newrelic.Transaction, _ *status.Status) {} + +// +// Standard handler: OK +// Reports only that the RPC call was successful by setting the web response header +// value. +// +func OKInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) +} + +// +// Standard handler: ERROR +// Reports the transaction as an error, with the relevant error messages and +// contextual information gleaned from the error value received from the RPC call. +// +func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) + txn.NoticeError(&newrelic.Error{ + Message: s.Message(), + Class: "gRPC Status: " + s.Code().String(), + }) + txn.AddAttribute("GrpcStatusLevel", "error") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) +} + +// examples +// Class "LoginError", Attr: "username": username + +// +// Standard handler: WARNING +// Reports the transaction's status with attributes containing information gleaned +// from the error value returned, but does not count this as an error. +// +func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) + txn.AddAttribute("GrpcStatusLevel", "warning") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) +} + +// +// Standard handler: INFO +// Reports the transaction's status with attributes containing information gleaned +// from the error value returned, but does not count this as an error. +// +func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) + txn.AddAttribute("GrpcStatusLevel", "info") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) +} + +// +// Standard handler: DEFAULT +// The DefaultInterceptorStatusHander is used for any status code which is not +// explicitly assigned a handler. +// +var DefaultInterceptorStatusHandler = InfoInterceptorStatusHandler + +// +// Common routine for reporting any kind of interceptor. +// +func reportInterceptorStatus(ctx context.Context, txn *newrelic.Transaction, handlers statusHandlerMap, err error) { + grpcStatus := status.Convert(err) + handler, ok := handlers[grpcStatus.Code()] + if !ok { + handler = DefaultInterceptorStatusHandler + } + handler(ctx, txn, grpcStatus) +} + // UnaryServerInterceptor instruments server unary RPCs. // // Use this function with grpc.UnaryInterceptor and a newrelic.Application to @@ -65,26 +263,46 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod // These interceptors add the transaction to the call context so it may be // accessed in your method handlers using newrelic.FromContext. // -// Full example: -// https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrgrpc/example/server/server.go +// The nrgrpc integration has a built-in set of handlers for each gRPC status +// code encountered. Serious errors are reported as error traces à la the +// newrelic.NoticeError() function, while the others are reported but not +// counted as errors. +// +// If you wish to change this behavior, you may do so at a global level for +// all intercepted functions by calling the Configure() function, passing +// any number of WithStatusHandler(code, handler) functions as parameters. +// +// You can specify a custom set of handlers with each interceptor creation by adding +// WithStatusHandler() calls at the end of the StreamInterceptor() call's parameter list, +// like so: +// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app, +// nrgrpc.WithStatusHandler(codes.OutOfRange, nrgrpc.WarningInterceptorStatusHandler), +// nrgrpc.WithStatusHandler(codes.Unimplemented, nrgrpc.InfoInterceptorStatusHandler))) +// In this case, those two handlers are used (along with the current defaults for the other status +// codes) only for that interceptor. // -func UnaryServerInterceptor(app *newrelic.Application) grpc.UnaryServerInterceptor { +func UnaryServerInterceptor(app *newrelic.Application, options ...handlerOption) grpc.UnaryServerInterceptor { if app == nil { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { return handler(ctx, req) } } + localHandlerMap := make(statusHandlerMap) + for code, handler := range interceptorStatusHandlerRegistry { + localHandlerMap[code] = handler + } + for _, option := range options { + option(localHandlerMap) + } + return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { txn := startTransaction(ctx, app, info.FullMethod) defer txn.End() ctx = newrelic.NewContext(ctx, txn) resp, err = handler(ctx, req) - txn.SetWebResponse(nil).WriteHeader(int(status.Code(err))) - if err != nil { - txn.NoticeError(err) - } + reportInterceptorStatus(ctx, txn, localHandlerMap, err) return } } @@ -114,40 +332,29 @@ func newWrappedServerStream(stream grpc.ServerStream, txn *newrelic.Transaction) // UnaryServerInterceptor and StreamServerInterceptor to instrument unary and // streaming calls. // -// Example: +// See the notes and examples for the UnaryServerInterceptor() function. // -// app, _ := newrelic.NewApplication( -// newrelic.ConfigAppName("gRPC Server"), -// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), -// newrelic.ConfigDebugLogger(os.Stdout), -// ) -// server := grpc.NewServer( -// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)), -// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), -// ) -// -// These interceptors add the transaction to the call context so it may be -// accessed in your method handlers using newrelic.FromContext. -// -// Full example: -// https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrgrpc/example/server/server.go -// -func StreamServerInterceptor(app *newrelic.Application) grpc.StreamServerInterceptor { +func StreamServerInterceptor(app *newrelic.Application, options ...handlerOption) grpc.StreamServerInterceptor { if app == nil { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { return handler(srv, ss) } } + localHandlerMap := make(statusHandlerMap) + for code, handler := range interceptorStatusHandlerRegistry { + localHandlerMap[code] = handler + } + for _, option := range options { + option(localHandlerMap) + } + return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { txn := startTransaction(ss.Context(), app, info.FullMethod) defer txn.End() err := handler(srv, newWrappedServerStream(ss, txn)) - txn.SetWebResponse(nil).WriteHeader(int(status.Code(err))) - if err != nil { - txn.NoticeError(err) - } + reportInterceptorStatus(ss.Context(), txn, localHandlerMap, err) return err } } diff --git a/v3/integrations/nrgrpc/nrgrpc_server_test.go b/v3/integrations/nrgrpc/nrgrpc_server_test.go index 4dce85bdf..d77004c0d 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server_test.go +++ b/v3/integrations/nrgrpc/nrgrpc_server_test.go @@ -62,7 +62,7 @@ func TestUnaryServerInterceptor(t *testing.T) { txn := app.StartTransaction("client") ctx := newrelic.NewContext(context.Background(), txn) _, err := client.DoUnaryUnary(ctx, &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("unable to call client DoUnaryUnary", err) } @@ -152,7 +152,7 @@ func TestUnaryServerInterceptorError(t *testing.T) { client := testapp.NewTestApplicationClient(conn) _, err := client.DoUnaryUnaryError(context.Background(), &testapp.Message{}) - if nil == err { + if err == nil { t.Fatal("DoUnaryUnaryError should have returned an error") } @@ -181,10 +181,14 @@ func TestUnaryServerInterceptorError(t *testing.T) { "sampled": internal.MatchAnything, "traceId": internal.MatchAnything, }, - UserAttributes: map[string]interface{}{}, + UserAttributes: map[string]interface{}{ + "GrpcStatusMessage": "oooooops!", + "GrpcStatusCode": "DataLoss", + "GrpcStatusLevel": "error", + }, AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, + "httpResponseCode": 0, + "http.statusCode": 0, "request.headers.contentType": "application/grpc", "request.method": "TestApplication/DoUnaryUnaryError", "request.uri": "grpc://bufnet/TestApplication/DoUnaryUnaryError", @@ -192,8 +196,8 @@ func TestUnaryServerInterceptorError(t *testing.T) { }}) app.ExpectErrorEvents(t, []internal.WantEvent{{ Intrinsics: map[string]interface{}{ - "error.class": "15", - "error.message": "response code 15", + "error.class": "gRPC Error: DataLoss", + "error.message": "oooooops!", "guid": internal.MatchAnything, "priority": internal.MatchAnything, "sampled": internal.MatchAnything, @@ -202,36 +206,19 @@ func TestUnaryServerInterceptorError(t *testing.T) { "transactionName": "WebTransaction/Go/TestApplication/DoUnaryUnaryError", }, AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, + "httpResponseCode": 0, + "http.statusCode": 0, "request.headers.User-Agent": internal.MatchAnything, "request.headers.userAgent": internal.MatchAnything, "request.headers.contentType": "application/grpc", "request.method": "TestApplication/DoUnaryUnaryError", "request.uri": "grpc://bufnet/TestApplication/DoUnaryUnaryError", }, - UserAttributes: map[string]interface{}{}, - }, { - Intrinsics: map[string]interface{}{ - "error.class": internal.MatchAnything, - "error.message": "rpc error: code = DataLoss desc = oooooops!", - "guid": internal.MatchAnything, - "priority": internal.MatchAnything, - "sampled": internal.MatchAnything, - "spanId": internal.MatchAnything, - "traceId": internal.MatchAnything, - "transactionName": "WebTransaction/Go/TestApplication/DoUnaryUnaryError", + UserAttributes: map[string]interface{}{ + "GrpcStatusMessage": "oooooops!", + "GrpcStatusCode": "DataLoss", + "GrpcStatusLevel": "error", }, - AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, - "request.headers.User-Agent": internal.MatchAnything, - "request.headers.userAgent": internal.MatchAnything, - "request.headers.contentType": "application/grpc", - "request.method": "TestApplication/DoUnaryUnaryError", - "request.uri": "grpc://bufnet/TestApplication/DoUnaryUnaryError", - }, - UserAttributes: map[string]interface{}{}, }}) } @@ -246,7 +233,7 @@ func TestUnaryStreamServerInterceptor(t *testing.T) { txn := app.StartTransaction("client") ctx := newrelic.NewContext(context.Background(), txn) stream, err := client.DoUnaryStream(ctx, &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryStream failed", err) } var recved int @@ -255,7 +242,7 @@ func TestUnaryStreamServerInterceptor(t *testing.T) { if err == io.EOF { break } - if nil != err { + if err != nil { t.Fatal("error receiving message", err) } recved++ @@ -352,11 +339,11 @@ func TestStreamUnaryServerInterceptor(t *testing.T) { txn := app.StartTransaction("client") ctx := newrelic.NewContext(context.Background(), txn) stream, err := client.DoStreamUnary(ctx) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamUnary failed", err) } for i := 0; i < 3; i++ { - if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); nil != err { + if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); err != nil { if err == io.EOF { break } @@ -364,7 +351,7 @@ func TestStreamUnaryServerInterceptor(t *testing.T) { } } _, err = stream.CloseAndRecv() - if nil != err { + if err != nil { t.Fatal("failure to CloseAndRecv", err) } @@ -456,7 +443,7 @@ func TestStreamStreamServerInterceptor(t *testing.T) { txn := app.StartTransaction("client") ctx := newrelic.NewContext(context.Background(), txn) stream, err := client.DoStreamStream(ctx) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamStream failed", err) } waitc := make(chan struct{}) @@ -571,11 +558,11 @@ func TestStreamServerInterceptorError(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoUnaryStreamError(context.Background(), &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("client call to DoUnaryStream failed", err) } _, err = stream.Recv() - if nil == err { + if err == nil { t.Fatal("DoUnaryStreamError should have returned an error") } @@ -604,10 +591,14 @@ func TestStreamServerInterceptorError(t *testing.T) { "sampled": internal.MatchAnything, "traceId": internal.MatchAnything, }, - UserAttributes: map[string]interface{}{}, + UserAttributes: map[string]interface{}{ + "GrpcStatusLevel": "error", + "GrpcStatusMessage": "oooooops!", + "GrpcStatusCode": "DataLoss", + }, AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, + "httpResponseCode": 0, + "http.statusCode": 0, "request.headers.contentType": "application/grpc", "request.method": "TestApplication/DoUnaryStreamError", "request.uri": "grpc://bufnet/TestApplication/DoUnaryStreamError", @@ -615,8 +606,8 @@ func TestStreamServerInterceptorError(t *testing.T) { }}) app.ExpectErrorEvents(t, []internal.WantEvent{{ Intrinsics: map[string]interface{}{ - "error.class": "15", - "error.message": "response code 15", + "error.class": "gRPC Error: DataLoss", + "error.message": "oooooops!", "guid": internal.MatchAnything, "priority": internal.MatchAnything, "sampled": internal.MatchAnything, @@ -625,36 +616,19 @@ func TestStreamServerInterceptorError(t *testing.T) { "transactionName": "WebTransaction/Go/TestApplication/DoUnaryStreamError", }, AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, + "httpResponseCode": 0, + "http.statusCode": 0, "request.headers.User-Agent": internal.MatchAnything, "request.headers.userAgent": internal.MatchAnything, "request.headers.contentType": "application/grpc", "request.method": "TestApplication/DoUnaryStreamError", "request.uri": "grpc://bufnet/TestApplication/DoUnaryStreamError", }, - UserAttributes: map[string]interface{}{}, - }, { - Intrinsics: map[string]interface{}{ - "error.class": internal.MatchAnything, - "error.message": "rpc error: code = DataLoss desc = oooooops!", - "guid": internal.MatchAnything, - "priority": internal.MatchAnything, - "sampled": internal.MatchAnything, - "spanId": internal.MatchAnything, - "traceId": internal.MatchAnything, - "transactionName": "WebTransaction/Go/TestApplication/DoUnaryStreamError", - }, - AgentAttributes: map[string]interface{}{ - "httpResponseCode": 15, - "http.statusCode": 15, - "request.headers.User-Agent": internal.MatchAnything, - "request.headers.userAgent": internal.MatchAnything, - "request.headers.contentType": "application/grpc", - "request.method": "TestApplication/DoUnaryStreamError", - "request.uri": "grpc://bufnet/TestApplication/DoUnaryStreamError", + UserAttributes: map[string]interface{}{ + "GrpcStatusLevel": "error", + "GrpcStatusMessage": "oooooops!", + "GrpcStatusCode": "DataLoss", }, - UserAttributes: map[string]interface{}{}, }}) } @@ -665,7 +639,7 @@ func TestUnaryServerInterceptorNilApp(t *testing.T) { client := testapp.NewTestApplicationClient(conn) msg, err := client.DoUnaryUnary(context.Background(), &testapp.Message{}) - if nil != err { + if err != nil { t.Fatal("unable to call client DoUnaryUnary", err) } if !strings.Contains(msg.Text, "content-type") { @@ -680,11 +654,11 @@ func TestStreamServerInterceptorNilApp(t *testing.T) { client := testapp.NewTestApplicationClient(conn) stream, err := client.DoStreamUnary(context.Background()) - if nil != err { + if err != nil { t.Fatal("client call to DoStreamUnary failed", err) } for i := 0; i < 3; i++ { - if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); nil != err { + if err := stream.Send(&testapp.Message{Text: "Hello DoStreamUnary"}); err != nil { if err == io.EOF { break } @@ -692,7 +666,7 @@ func TestStreamServerInterceptorNilApp(t *testing.T) { } } msg, err := stream.CloseAndRecv() - if nil != err { + if err != nil { t.Fatal("failure to CloseAndRecv", err) } if !strings.Contains(msg.Text, "content-type") { diff --git a/v3/newrelic/application.go b/v3/newrelic/application.go index fb81eb793..7a8db268f 100644 --- a/v3/newrelic/application.go +++ b/v3/newrelic/application.go @@ -83,6 +83,15 @@ func (app *Application) RecordCustomMetric(name string, value float64) { // If Infinite Tracing is enabled, WaitForConnection will block until a // connection to the Trace Observer is made, a fatal error is reached, or the // timeout is hit. +// +// Note that in most cases, it is not necesary nor recommended to call +// WaitForConnection() at all, particularly for any but the most trivial, short-lived +// processes. It is better to simply start the application and allow the +// instrumentation code to handle its connections on its own, which it will do +// as needed in the background (and will continue attempting to connect +// if it wasn't immediately successful, all while allowing your application +// to proceed with its primary function). +// func (app *Application) WaitForConnection(timeout time.Duration) error { if nil == app { return nil diff --git a/v3/newrelic/trace_context_test.go b/v3/newrelic/trace_context_test.go index 3aeccc10a..e054219b1 100644 --- a/v3/newrelic/trace_context_test.go +++ b/v3/newrelic/trace_context_test.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net/http" + "reflect" "strings" "testing" @@ -46,6 +47,47 @@ type TraceContextTestCase struct { } `json:"intrinsics"` } +func TestJSONDTHeaders(t *testing.T) { + type testcase struct { + in string + out http.Header + err bool + } + + for i, test := range []testcase{ + {"", http.Header{}, false}, + {"{}", http.Header{}, false}, + {" invalid ", http.Header{}, true}, + {`"foo"`, http.Header{}, true}, + {`{"foo": "bar"}`, http.Header{ + "Foo": {"bar"}, + }, false}, + {`{ + "foo": "bar", + "baz": "quux", + "multiple": [ + "alpha", + "beta", + "gamma" + ] + }`, http.Header{ + "Foo": {"bar"}, + "Baz": {"quux"}, + "Multiple": {"alpha", "beta", "gamma"}, + }, false}, + } { + h, err := DistributedTraceHeadersFromJSON(test.in) + + if err != nil { + if !test.err { + t.Errorf("case %d: %v: error expected but not generated", i, test.in) + } + } else if !reflect.DeepEqual(test.out, h) { + t.Errorf("case %d, %v -> %v but expected %v", i, test.in, h, test.out) + } + } +} + func TestCrossAgentW3CTraceContext(t *testing.T) { var tcs []TraceContextTestCase diff --git a/v3/newrelic/transaction.go b/v3/newrelic/transaction.go index 60c3e9cee..82e738ed1 100644 --- a/v3/newrelic/transaction.go +++ b/v3/newrelic/transaction.go @@ -4,6 +4,8 @@ package newrelic import ( + "encoding/json" + "fmt" "net/http" "net/url" "strings" @@ -269,6 +271,93 @@ func (txn *Transaction) AcceptDistributedTraceHeaders(t TransportType, hdrs http txn.thread.logAPIError(txn.thread.AcceptDistributedTraceHeaders(t, hdrs), "accept trace payload", nil) } +// +// AcceptDistributedTraceHeadersFromJSON works just like AcceptDistributedTraceHeaders(), except +// that it takes the header data as a JSON string à la DistributedTraceHeadersFromJSON(). Additionally +// (unlike AcceptDistributedTraceHeaders()) it returns an error if it was unable to successfully +// convert the JSON string to http headers. There is no guarantee that the header data found in JSON +// is correct beyond conforming to the expected types and syntax. +// +func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, jsondata string) error { + hdrs, err := DistributedTraceHeadersFromJSON(jsondata) + if err != nil { + return err + } + txn.AcceptDistributedTraceHeaders(t, hdrs) + return nil +} + +// +// DistributedTraceHeadersFromJSON takes a set of distributed trace headers as a JSON-encoded string +// and emits a http.Header value suitable for passing on to the +// txn.AcceptDistributedTraceHeaders() function. +// +// This is a convenience function provided for cases where you receive the trace header data +// already as a JSON string and want to avoid manually converting that to an http.Header. +// It helps facilitate handling of headers passed to your Go application from components written in other +// languages which may natively handle these header values as JSON strings. +// +// For example, given the input string +// `{"traceparent": "frob", "tracestate": "blorfl", "newrelic": "xyzzy"}` +// This will emit an http.Header value with headers "traceparent", "tracestate", and "newrelic". +// Specifically: +// http.Header{ +// "Traceparent": {"frob"}, +// "Tracestate": {"blorfl"}, +// "Newrelic": {"xyzzy"}, +// } +// +// The JSON string must be a single object whose values may be strings or arrays of strings. +// These are translated directly to http headers with singleton or multiple values. +// In the case of multiple string values, these are translated to a multi-value HTTP +// header. For example: +// `{"traceparent": "12345", "colors": ["red", "green", "blue"]}` +// which produces +// http.Header{ +// "Traceparent": {"12345"}, +// "Colors": {"red", "green", "blue"}, +// } +// (Note that the HTTP headers are capitalized.) +// +func DistributedTraceHeadersFromJSON(jsondata string) (hdrs http.Header, err error) { + var raw interface{} + hdrs = http.Header{} + if jsondata == "" { + return + } + err = json.Unmarshal([]byte(jsondata), &raw) + if err != nil { + return + } + + switch d := raw.(type) { + case map[string]interface{}: + for k, v := range d { + switch hval := v.(type) { + case string: + hdrs.Set(k, hval) + case []interface{}: + for _, subval := range hval { + switch sval := subval.(type) { + case string: + hdrs.Add(k, sval) + default: + err = fmt.Errorf("the JSON object must have only strings or arrays of strings") + return + } + } + default: + err = fmt.Errorf("the JSON object must have only strings or arrays of strings") + return + } + } + default: + err = fmt.Errorf("the JSON string must consist of only a single object") + return + } + return +} + // Application returns the Application which started the transaction. func (txn *Transaction) Application() *Application { if nil == txn { diff --git a/v3/newrelic/version.go b/v3/newrelic/version.go index 4df810937..daf8e5f57 100644 --- a/v3/newrelic/version.go +++ b/v3/newrelic/version.go @@ -11,7 +11,7 @@ import ( const ( // Version is the full string version of this Go Agent. - Version = "3.13.0" + Version = "3.14.0" ) var (