From 43662fc9c9830adb24e98b43768f77be6b8f8620 Mon Sep 17 00:00:00 2001 From: Josiah Witt Date: Mon, 7 Jun 2021 09:50:56 -0400 Subject: [PATCH 01/20] Grab the NR txn from the ctx when txn is not set --- v3/integrations/nrawssdk-v2/nrawssdk.go | 48 +- v3/integrations/nrawssdk-v2/nrawssdk_test.go | 526 ++++++++++++------- 2 files changed, 368 insertions(+), 206 deletions(-) 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}) + }, + ) } From 273fd3f4d27cddda36bc5c5c8f970ffcf53c1417 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Mon, 7 Jun 2021 15:23:40 -0700 Subject: [PATCH 02/20] update integration tags, add go.mod and license for nrb3 --- v3/integrations/nrb3/LICENSE.txt | 206 +++++++++++++++++++++++++++++++ v3/integrations/nrb3/go.mod | 1 + 2 files changed, 207 insertions(+) create mode 100644 v3/integrations/nrb3/LICENSE.txt create mode 100644 v3/integrations/nrb3/go.mod 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 From 907d0bc40bd4a80934987587133278ad7a4e9dd7 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Sun, 27 Jun 2021 20:19:14 -0700 Subject: [PATCH 03/20] initial cut at structure of configurable status handler architecture --- v3/integrations/nrgrpc/nrgrpc_client_test.go | 52 +++--- v3/integrations/nrgrpc/nrgrpc_server.go | 157 +++++++++++++++++-- v3/integrations/nrgrpc/nrgrpc_server_test.go | 28 ++-- 3 files changed, 186 insertions(+), 51 deletions(-) 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_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index e8119c66e..ab96a0d5d 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -10,6 +10,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" ) @@ -45,7 +46,7 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod // UnaryServerInterceptor instruments server unary RPCs. // // Use this function with grpc.UnaryInterceptor and a newrelic.Application to -// create a grpc.ServerOption to pass to grpc.NewServer. This interceptor +// sreate a grpc.ServerOption to pass to grpc.NewServer. This interceptor // records each unary call with a transaction. You must use both // UnaryServerInterceptor and StreamServerInterceptor to instrument unary and // streaming calls. @@ -62,29 +63,158 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod // grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)), // ) // +// The nrgrpc integration has a built-in set of handlers for each gRPC status +// code encountered. Serious errors are reported as error traces ala 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. +// In each of these, `code` represents a gRPC code such as `codes.Unknown`, +// and `handler` is a function with the calling signature +// func myHandler(c context.Context, t *newrelic.Transaction, s *status.Status) +// If the given gRPC code is produced by the intercepted function, then `myHandler()` +// will be called to report that out in the current transaction, in whatever way +// is appropriate. To assist with this, `myHandler()` is provided with the corresponding +// context and transaction along with the actual gRPC `Status` value captured. +// +// We provide a set of standard handlers which should suffice in most cases to report +// non-error, info-level, warning-level, and error-level statuses: +// ErrorInterceptorStatusHandler // report as error +// IgnoreInterceptorStatusHandler // no report AT ALL +// InfoInterceptorStatusHandler // report as informational message +// OKInterceptorStatusHandler // report as successful +// WarningInterceptorStatusHandler // report as warning +// +// Thus, to specify that all codes with status `OutOfRange` should be logged as warnings +// and all `Unimplemented` ones should be informational, then make this call: +// Config( +// WithStatusHandler(codes.OutOfRange, WarningInterceptorStatusHandler), +// WithStatusHandler(codes.Unimplemented, InfoInterceptorStatusHandler)) +// +// This will affect the behavior of calls to `UnaryInterceptor()` and `StreamInterceptor()` +// which occur after this. You may call `Config()` again to change the handling of errors +// from that point forward (but note that once an interceptor is created, it will use whatever +// handlers were defined at that point, even if the intercepted service call happens later. +// +// You can also 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. +// +// // 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 UnaryServerInterceptor(app *newrelic.Application) grpc.UnaryServerInterceptor { + +type ErrorHandler func(context.Context, *newrelic.Transaction, *status.Status) +type StatusHandlerMap map[codes.Code]ErrorHandler + +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) + +func WithStatusHandler(c codes.Code, h ErrorHandler) handlerOption { + return func(m StatusHandlerMap) { + m[c] = h + } +} + +func Configure(options ...handlerOption) { + for _, option := range options { + option(interceptorStatusHandlerRegistry) + } +} + +func IgnoreInterceptorStatusHandler(_ context.Context, _ *newrelic.Transaction, _ *status.Status) {} + +func OKInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) +} + +func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(s.Code())) + // + // TODO: Figure out specifically how we want to set up the custom attributes for this + // (it was txn.NoticeError(s.Err())) + txn.NoticeError(&newrelic.Error{ + Message: s.Err().Error(), + Class: "...", + Attributes: map[string]interface{}{ + "...": "...", + }, + }) +} + +func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(s.Code())) + // TODO: just add some attributes about this (treat as WARN, not NoticeError()) +} + +func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { + txn.SetWebResponse(nil).WriteHeader(int(s.Code())) + // TODO: just add some attributes about this (treat as INFO, not NoticeError()) +} + +var DefaultInterceptorStatusHandler = InfoInterceptorStatusHandler + +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) +} + +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 } } @@ -132,22 +262,27 @@ func newWrappedServerStream(stream grpc.ServerStream, txn *newrelic.Transaction) // 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..d06e77b06 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") } @@ -246,7 +246,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 +255,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 +352,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 +364,7 @@ func TestStreamUnaryServerInterceptor(t *testing.T) { } } _, err = stream.CloseAndRecv() - if nil != err { + if err != nil { t.Fatal("failure to CloseAndRecv", err) } @@ -456,7 +456,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 +571,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") } @@ -665,7 +665,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 +680,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 +692,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") { From 26708ed0fffd3537b468d8d435527e9f314281c0 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Mon, 28 Jun 2021 11:23:14 -0700 Subject: [PATCH 04/20] documentation/comment cleanup --- v3/integrations/nrgrpc/nrgrpc_server.go | 251 +++++++++++++++--------- 1 file changed, 159 insertions(+), 92 deletions(-) diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index ab96a0d5d..9e92103d0 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -1,6 +1,35 @@ // 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 ( @@ -43,82 +72,25 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod return txn } -// UnaryServerInterceptor instruments server unary RPCs. -// -// Use this function with grpc.UnaryInterceptor and a newrelic.Application to -// sreate a grpc.ServerOption to pass to grpc.NewServer. This interceptor -// records each unary call with a transaction. You must use both -// UnaryServerInterceptor and StreamServerInterceptor to instrument unary and -// streaming calls. -// -// 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 nrgrpc integration has a built-in set of handlers for each gRPC status -// code encountered. Serious errors are reported as error traces ala the -// `newrelic.NoticeError()` function, while the others are reported but not -// counted as errors. +// `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. // -// 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. -// In each of these, `code` represents a gRPC code such as `codes.Unknown`, -// and `handler` is a function with the calling signature -// func myHandler(c context.Context, t *newrelic.Transaction, s *status.Status) -// If the given gRPC code is produced by the intercepted function, then `myHandler()` -// will be called to report that out in the current transaction, in whatever way -// is appropriate. To assist with this, `myHandler()` is provided with the corresponding -// context and transaction along with the actual gRPC `Status` value captured. -// -// We provide a set of standard handlers which should suffice in most cases to report -// non-error, info-level, warning-level, and error-level statuses: -// ErrorInterceptorStatusHandler // report as error -// IgnoreInterceptorStatusHandler // no report AT ALL -// InfoInterceptorStatusHandler // report as informational message -// OKInterceptorStatusHandler // report as successful -// WarningInterceptorStatusHandler // report as warning -// -// Thus, to specify that all codes with status `OutOfRange` should be logged as warnings -// and all `Unimplemented` ones should be informational, then make this call: -// Config( -// WithStatusHandler(codes.OutOfRange, WarningInterceptorStatusHandler), -// WithStatusHandler(codes.Unimplemented, InfoInterceptorStatusHandler)) -// -// This will affect the behavior of calls to `UnaryInterceptor()` and `StreamInterceptor()` -// which occur after this. You may call `Config()` again to change the handling of errors -// from that point forward (but note that once an interceptor is created, it will use whatever -// handlers were defined at that point, even if the intercepted service call happens later. -// -// You can also 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. +type ErrorHandler func(context.Context, *newrelic.Transaction, *status.Status) + // +// Internal registry of handlers associated with various +// status codes. // -// These interceptors add the transaction to the call context so it may be -// accessed in your method handlers using newrelic.FromContext. +type statusHandlerMap map[codes.Code]ErrorHandler + // -// Full example: -// https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrgrpc/example/server/server.go +// interceptorStatusHandlerRegistry is the current default set of handlers +// used by each interceptor. // - -type ErrorHandler func(context.Context, *newrelic.Transaction, *status.Status) -type StatusHandlerMap map[codes.Code]ErrorHandler - -var interceptorStatusHandlerRegistry = StatusHandlerMap{ +var interceptorStatusHandlerRegistry = statusHandlerMap{ codes.OK: OKInterceptorStatusHandler, codes.Canceled: InfoInterceptorStatusHandler, codes.Unknown: ErrorInterceptorStatusHandler, @@ -138,26 +110,78 @@ var interceptorStatusHandlerRegistry = StatusHandlerMap{ codes.Unauthenticated: InfoInterceptorStatusHandler, } -type handlerOption func(StatusHandlerMap) +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) { + 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(s.Code())) // @@ -172,19 +196,37 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio }) } +// +// 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(s.Code())) // TODO: just add some attributes about this (treat as WARN, not NoticeError()) } +// +// 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(s.Code())) // TODO: just add some attributes about this (treat as INFO, not NoticeError()) } +// +// Standard handler: DEFAULT +// The `DefaultInterceptorStatusHander` is used for any status code which is not +// explicitly assigned a handler. +// var DefaultInterceptorStatusHandler = InfoInterceptorStatusHandler -func reportInterceptorStatus(ctx context.Context, txn *newrelic.Transaction, handlers StatusHandlerMap, err error) { +// +// 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 { @@ -193,6 +235,47 @@ func reportInterceptorStatus(ctx context.Context, txn *newrelic.Transaction, han handler(ctx, txn, grpcStatus) } +// UnaryServerInterceptor instruments server unary RPCs. +// +// Use this function with grpc.UnaryInterceptor and a newrelic.Application to +// create a grpc.ServerOption to pass to grpc.NewServer. This interceptor +// records each unary call with a transaction. You must use both +// UnaryServerInterceptor and StreamServerInterceptor to instrument unary and +// streaming calls. +// +// 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)), +// ) +// +// These interceptors add the transaction to the call context so it may be +// accessed in your method handlers using newrelic.FromContext. +// +// 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, options ...handlerOption) grpc.UnaryServerInterceptor { if app == nil { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { @@ -200,7 +283,7 @@ func UnaryServerInterceptor(app *newrelic.Application, options ...handlerOption) } } - localHandlerMap := make(StatusHandlerMap) + localHandlerMap := make(statusHandlerMap) for code, handler := range interceptorStatusHandlerRegistry { localHandlerMap[code] = handler } @@ -244,23 +327,7 @@ func newWrappedServerStream(stream grpc.ServerStream, txn *newrelic.Transaction) // UnaryServerInterceptor and StreamServerInterceptor to instrument unary and // streaming calls. // -// 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)), -// ) -// -// 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 +// See the notes and examples for the `UnaryServerInterceptor()` function. // func StreamServerInterceptor(app *newrelic.Application, options ...handlerOption) grpc.StreamServerInterceptor { if app == nil { @@ -269,7 +336,7 @@ func StreamServerInterceptor(app *newrelic.Application, options ...handlerOption } } - localHandlerMap := make(StatusHandlerMap) + localHandlerMap := make(statusHandlerMap) for code, handler := range interceptorStatusHandlerRegistry { localHandlerMap[code] = handler } From b77ebd9c751fe467cf98538717db6dffc6231b01 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Mon, 28 Jun 2021 12:09:29 -0700 Subject: [PATCH 05/20] first test with some actual attributes --- v3/integrations/nrgrpc/nrgrpc_server.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index 9e92103d0..48c665c8a 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -189,13 +189,18 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio // (it was txn.NoticeError(s.Err())) txn.NoticeError(&newrelic.Error{ Message: s.Err().Error(), - Class: "...", + Class: "GrpcStatus", Attributes: map[string]interface{}{ - "...": "...", + "GrpcStatusLevel": "error", + "GrpcStatusMessage": s.Message(), + "GrpcStatusCode": s.Code(), }, }) } +// examples +// Class "LoginError", Attr: "username": username + // // Standard handler: WARNING // Reports the transaction's status with attributes containing information gleaned @@ -203,6 +208,9 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio // func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { txn.SetWebResponse(nil).WriteHeader(int(s.Code())) + txn.AddAttribute("GrpcStatusLevel", "warning") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code()) // TODO: just add some attributes about this (treat as WARN, not NoticeError()) } @@ -213,6 +221,9 @@ func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transact // func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { txn.SetWebResponse(nil).WriteHeader(int(s.Code())) + txn.AddAttribute("GrpcStatusLevel", "info") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code()) // TODO: just add some attributes about this (treat as INFO, not NoticeError()) } From ecc3ec722c4fc865ba52f5c4cd8b1165bc20c34c Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 13:13:05 -0700 Subject: [PATCH 06/20] more testing and refinement --- v3/integrations/nrgrpc/nrgrpc_server.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index 48c665c8a..d753787b1 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -34,6 +34,7 @@ package nrgrpc import ( "context" + "fmt" "net/http" "strings" @@ -187,6 +188,7 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio // // TODO: Figure out specifically how we want to set up the custom attributes for this // (it was txn.NoticeError(s.Err())) + fmt.Printf("**NoticeError %v %v %v**\n", s.Err().Error(), s.Message(), s.Code()) txn.NoticeError(&newrelic.Error{ Message: s.Err().Error(), Class: "GrpcStatus", From bb7fe4f155cf1e769209c8ca8b020233f7a0b384 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 14:22:35 -0700 Subject: [PATCH 07/20] implemented JSON distributed trace converter --- v3/go.mod | 4 +- v3/newrelic/trace_context_test.go | 42 ++++++++++++++++++ v3/newrelic/transaction.go | 72 +++++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 2 deletions(-) diff --git a/v3/go.mod b/v3/go.mod index 2ada3801e..92bc2eef5 100644 --- a/v3/go.mod +++ b/v3/go.mod @@ -3,6 +3,6 @@ module github.com/newrelic/go-agent/v3 go 1.7 require ( - github.com/golang/protobuf v1.3.3 - google.golang.org/grpc v1.27.0 + github.com/golang/protobuf v1.4.3 + google.golang.org/grpc v1.39.0 ) diff --git a/v3/newrelic/trace_context_test.go b/v3/newrelic/trace_context_test.go index 3aeccc10a..7dc6dd9cb 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"}`, map[string][]string{ + "Foo": {"bar"}, + }, false}, + {`{ + "foo": "bar", + "baz": "quux", + "multiple": [ + "alpha", + "beta", + "gamma" + ] + }`, map[string][]string{ + "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..bbc5b9a49 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,76 @@ 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. +// +// 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". +// +// 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. +// +// 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. +// +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("JSON object must have only strings or arrays of strings.") + return + } + } + default: + err = fmt.Errorf("JSON object must have only strings or arrays of strings.") + return + } + } + default: + err = fmt.Errorf("JSON string must be a single object.") + return + } + return +} + // Application returns the Application which started the transaction. func (txn *Transaction) Application() *Application { if nil == txn { From 98f82a3f51bc28009b7e243feb2ef72271c006bc Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 15:17:33 -0700 Subject: [PATCH 08/20] errors working --- v3/integrations/nrgrpc/nrgrpc_server.go | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index d753787b1..c9b72baaf 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -34,7 +34,6 @@ package nrgrpc import ( "context" - "fmt" "net/http" "strings" @@ -185,19 +184,7 @@ func OKInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, // func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) { txn.SetWebResponse(nil).WriteHeader(int(s.Code())) - // - // TODO: Figure out specifically how we want to set up the custom attributes for this - // (it was txn.NoticeError(s.Err())) - fmt.Printf("**NoticeError %v %v %v**\n", s.Err().Error(), s.Message(), s.Code()) - txn.NoticeError(&newrelic.Error{ - Message: s.Err().Error(), - Class: "GrpcStatus", - Attributes: map[string]interface{}{ - "GrpcStatusLevel": "error", - "GrpcStatusMessage": s.Message(), - "GrpcStatusCode": s.Code(), - }, - }) + txn.NoticeError(s.Err()) } // examples @@ -213,7 +200,6 @@ func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transact txn.AddAttribute("GrpcStatusLevel", "warning") txn.AddAttribute("GrpcStatusMessage", s.Message()) txn.AddAttribute("GrpcStatusCode", s.Code()) - // TODO: just add some attributes about this (treat as WARN, not NoticeError()) } // @@ -226,7 +212,6 @@ func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction txn.AddAttribute("GrpcStatusLevel", "info") txn.AddAttribute("GrpcStatusMessage", s.Message()) txn.AddAttribute("GrpcStatusCode", s.Code()) - // TODO: just add some attributes about this (treat as INFO, not NoticeError()) } // From bae9df32ead6b36e9afae4072d5dcfe3980030b5 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 15:39:50 -0700 Subject: [PATCH 09/20] added advice on usage of WaitForConnection() call --- v3/newrelic/application.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/v3/newrelic/application.go b/v3/newrelic/application.go index fb81eb793..865668d30 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 short-lived +// processes. It is better to simply start the application and allow the +// instrumentation code handle 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 From b89a93e07c4e2866870822da712deac17d042cad Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 16:05:01 -0700 Subject: [PATCH 10/20] style cleanup, corrected go.mod versions --- v3/go.mod | 4 ++-- v3/newrelic/trace_context_test.go | 8 ++++---- v3/newrelic/transaction.go | 18 +++++++++--------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/v3/go.mod b/v3/go.mod index 92bc2eef5..2ada3801e 100644 --- a/v3/go.mod +++ b/v3/go.mod @@ -3,6 +3,6 @@ module github.com/newrelic/go-agent/v3 go 1.7 require ( - github.com/golang/protobuf v1.4.3 - google.golang.org/grpc v1.39.0 + github.com/golang/protobuf v1.3.3 + google.golang.org/grpc v1.27.0 ) diff --git a/v3/newrelic/trace_context_test.go b/v3/newrelic/trace_context_test.go index 7dc6dd9cb..e054219b1 100644 --- a/v3/newrelic/trace_context_test.go +++ b/v3/newrelic/trace_context_test.go @@ -47,7 +47,7 @@ type TraceContextTestCase struct { } `json:"intrinsics"` } -func TestJsonDTHeaders(t *testing.T) { +func TestJSONDTHeaders(t *testing.T) { type testcase struct { in string out http.Header @@ -59,7 +59,7 @@ func TestJsonDTHeaders(t *testing.T) { {"{}", http.Header{}, false}, {" invalid ", http.Header{}, true}, {`"foo"`, http.Header{}, true}, - {`{"foo": "bar"}`, map[string][]string{ + {`{"foo": "bar"}`, http.Header{ "Foo": {"bar"}, }, false}, {`{ @@ -70,13 +70,13 @@ func TestJsonDTHeaders(t *testing.T) { "beta", "gamma" ] - }`, map[string][]string{ + }`, http.Header{ "Foo": {"bar"}, "Baz": {"quux"}, "Multiple": {"alpha", "beta", "gamma"}, }, false}, } { - h, err := DistributedTraceHeadersFromJson(test.in) + h, err := DistributedTraceHeadersFromJSON(test.in) if err != nil { if !test.err { diff --git a/v3/newrelic/transaction.go b/v3/newrelic/transaction.go index bbc5b9a49..306a3de12 100644 --- a/v3/newrelic/transaction.go +++ b/v3/newrelic/transaction.go @@ -272,14 +272,14 @@ func (txn *Transaction) AcceptDistributedTraceHeaders(t TransportType, hdrs http } // -// AcceptDistributedTraceHeadersFromJson() works just like AcceptDistributedTraceHeaders(), except -// that it takes the header data as a JSON string à la DistributedTraceHeadersFromJson(). Additionally +// 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) +func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, jsondata string) error { + hdrs, err := DistributedTraceHeadersFromJSON(jsondata) if err != nil { return err } @@ -288,7 +288,7 @@ func (txn *Transaction) AcceptDistributedTraceHeadersFromJson(t TransportType, j } // -// DistributedTraceHeadersFromJson() takes a set of distributed trace headers as a JSON-encoded string +// 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. // @@ -302,7 +302,7 @@ func (txn *Transaction) AcceptDistributedTraceHeadersFromJson(t TransportType, j // 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. // -func DistributedTraceHeadersFromJson(jsondata string) (hdrs http.Header, err error) { +func DistributedTraceHeadersFromJSON(jsondata string) (hdrs http.Header, err error) { var raw interface{} hdrs = http.Header{} if jsondata == "" { @@ -325,17 +325,17 @@ func DistributedTraceHeadersFromJson(jsondata string) (hdrs http.Header, err err case string: hdrs.Add(k, sval) default: - err = fmt.Errorf("JSON object must have only strings or arrays of strings.") + err = fmt.Errorf("the JSON object must have only strings or arrays of strings") return } } default: - err = fmt.Errorf("JSON object must have only strings or arrays of strings.") + err = fmt.Errorf("the JSON object must have only strings or arrays of strings") return } } default: - err = fmt.Errorf("JSON string must be a single object.") + err = fmt.Errorf("the JSON string must consist of only a single object") return } return From 2c20aed6f46cb52cd53db7597933b0015d64e033 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 16:31:12 -0700 Subject: [PATCH 11/20] updated documentation --- v3/newrelic/transaction.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/v3/newrelic/transaction.go b/v3/newrelic/transaction.go index 306a3de12..34ea3932f 100644 --- a/v3/newrelic/transaction.go +++ b/v3/newrelic/transaction.go @@ -292,15 +292,33 @@ func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, j // and emits a http.Header value suitable for passing on to the // txn.AcceptDistributedTraceHeaders() function. // +// This helps facilitate 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"}, +// } // // 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. // // 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{} From f6642c602fd406fe3f276ed789a93c88ae1a62fb Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 16:33:48 -0700 Subject: [PATCH 12/20] updated documentation --- v3/newrelic/transaction.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/v3/newrelic/transaction.go b/v3/newrelic/transaction.go index 34ea3932f..82e738ed1 100644 --- a/v3/newrelic/transaction.go +++ b/v3/newrelic/transaction.go @@ -292,7 +292,9 @@ func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, j // and emits a http.Header value suitable for passing on to the // txn.AcceptDistributedTraceHeaders() function. // -// This helps facilitate headers passed to your Go application from components written in other +// 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 @@ -305,9 +307,6 @@ func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, j // "Newrelic": {"xyzzy"}, // } // -// 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. -// // 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 From 8400fc0b105542607a55a2104f08d53168379d0f Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Wed, 30 Jun 2021 17:05:21 -0700 Subject: [PATCH 13/20] typo corrections --- v3/newrelic/application.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v3/newrelic/application.go b/v3/newrelic/application.go index 865668d30..7a8db268f 100644 --- a/v3/newrelic/application.go +++ b/v3/newrelic/application.go @@ -85,9 +85,9 @@ func (app *Application) RecordCustomMetric(name string, value float64) { // 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 short-lived +// 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 handle connections on its own, which it will do +// 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). From 852ae31ca73e1d28243809eabdf0ee15b2232537 Mon Sep 17 00:00:00 2001 From: Rich Vanderwal Date: Thu, 1 Jul 2021 17:32:41 -0700 Subject: [PATCH 14/20] example change to support PR #328, plus CHANGELOG.md --- CHANGELOG.md | 3 +++ v3/integrations/nrawssdk-v2/example/main.go | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e553f372..92c61ba3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +### 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) + ## 3.13.0 ### Fixed 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) From 094273df318536d9441d3e546475ce10207e4844 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Sat, 3 Jul 2021 14:02:50 -0700 Subject: [PATCH 15/20] changed non-error handlers to report OK web responses --- v3/integrations/nrgrpc/nrgrpc_server.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index c9b72baaf..6db33d2bd 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -196,7 +196,7 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio // 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(s.Code())) + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) txn.AddAttribute("GrpcStatusLevel", "warning") txn.AddAttribute("GrpcStatusMessage", s.Message()) txn.AddAttribute("GrpcStatusCode", s.Code()) @@ -208,7 +208,7 @@ func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transact // 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(s.Code())) + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) txn.AddAttribute("GrpcStatusLevel", "info") txn.AddAttribute("GrpcStatusMessage", s.Message()) txn.AddAttribute("GrpcStatusCode", s.Code()) From 1ccdb9d0968b2d85baf121a9d10091f4dc448014 Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Thu, 8 Jul 2021 09:20:30 -0700 Subject: [PATCH 16/20] modified error reporting to avoid double reporting --- .../nrgrpc/example/server/server.go | 5 +- v3/integrations/nrgrpc/nrgrpc_server.go | 14 ++- v3/integrations/nrgrpc/nrgrpc_server_test.go | 86 +++++++------------ 3 files changed, 44 insertions(+), 61 deletions(-) diff --git a/v3/integrations/nrgrpc/example/server/server.go b/v3/integrations/nrgrpc/example/server/server.go index 469f3c80d..4a37dfcff 100644 --- a/v3/integrations/nrgrpc/example/server/server.go +++ b/v3/integrations/nrgrpc/example/server/server.go @@ -14,6 +14,8 @@ import ( sampleapp "github.com/newrelic/go-agent/v3/integrations/nrgrpc/example/sampleapp" newrelic "github.com/newrelic/go-agent/v3/newrelic" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // Server is a gRPC server. @@ -28,7 +30,8 @@ func processMessage(ctx context.Context, msg *sampleapp.Message) { // DoUnaryUnary is a unary request, unary response method. func (s *Server) DoUnaryUnary(ctx context.Context, msg *sampleapp.Message) (*sampleapp.Message, error) { processMessage(ctx, msg) - return &sampleapp.Message{Text: "Hello from DoUnaryUnary"}, nil + // return &sampleapp.Message{Text: "Hello from DoUnaryUnary"}, nil + return &sampleapp.Message{}, status.New(codes.DataLoss, "oooooops!").Err() } // DoUnaryStream is a unary request, stream response method. diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index 6db33d2bd..e77168060 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -183,8 +183,14 @@ func OKInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, // 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(s.Code())) - txn.NoticeError(s.Err()) + txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) + txn.NoticeError(&newrelic.Error{ + Message: s.Message(), + Class: "gRPC Error: " + s.Code().String(), + }) + txn.AddAttribute("GrpcStatusLevel", "error") + txn.AddAttribute("GrpcStatusMessage", s.Message()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) } // examples @@ -199,7 +205,7 @@ func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transact txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) txn.AddAttribute("GrpcStatusLevel", "warning") txn.AddAttribute("GrpcStatusMessage", s.Message()) - txn.AddAttribute("GrpcStatusCode", s.Code()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) } // @@ -211,7 +217,7 @@ func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) txn.AddAttribute("GrpcStatusLevel", "info") txn.AddAttribute("GrpcStatusMessage", s.Message()) - txn.AddAttribute("GrpcStatusCode", s.Code()) + txn.AddAttribute("GrpcStatusCode", s.Code().String()) } // diff --git a/v3/integrations/nrgrpc/nrgrpc_server_test.go b/v3/integrations/nrgrpc/nrgrpc_server_test.go index d06e77b06..d77004c0d 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server_test.go +++ b/v3/integrations/nrgrpc/nrgrpc_server_test.go @@ -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", - }, - 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{}{ + "GrpcStatusMessage": "oooooops!", + "GrpcStatusCode": "DataLoss", + "GrpcStatusLevel": "error", }, - UserAttributes: map[string]interface{}{}, }}) } @@ -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{}{}, }}) } From 0efa74cda8ec9900188cabe0b122b0d08b6fd09b Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Thu, 8 Jul 2021 15:07:22 -0700 Subject: [PATCH 17/20] updated documentation --- v3/integrations/nrgrpc/nrgrpc_doc.go | 61 +++++++++++++++++++++---- v3/integrations/nrgrpc/nrgrpc_server.go | 57 +++++++++++------------ 2 files changed, 80 insertions(+), 38 deletions(-) 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 e77168060..a9b1f6e0a 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -3,7 +3,7 @@ // // This integration instruments grpc service calls via -// `UnaryServerInterceptor()` and `StreamServerInterceptor()` functions. +// 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 @@ -23,13 +23,14 @@ // // 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. +// 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 ( @@ -73,8 +74,8 @@ func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod } // -// `ErrorHandler` is the type of a gRPC status handler function. -// Normally the supplied set of `ErrorHandler` functions will suffice, but +// 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. // @@ -113,35 +114,35 @@ var interceptorStatusHandlerRegistry = statusHandlerMap{ type handlerOption func(statusHandlerMap) // -// `WithStatusHandler()` indicates a handler function to be used to +// 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. +// given to the Configure(), StreamServiceInterceptor(), or +// UnaryServiceInterceptor() functions. // -// The `ErrorHandler` parameter is generally one of the provided standard +// 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 +// 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 +// 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. +// 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 +// 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. +// to your Configure(), StreamServiceInterceptor(), or UnaryServiceInterceptor() function. // func WithStatusHandler(c codes.Code, h ErrorHandler) handlerOption { return func(m statusHandlerMap) { @@ -150,10 +151,10 @@ func WithStatusHandler(c codes.Code, h ErrorHandler) handlerOption { } // -// `Configure()` takes a list of `WithStatusHandler()` options and sets them +// 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 +// 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) { @@ -222,7 +223,7 @@ func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction // // Standard handler: DEFAULT -// The `DefaultInterceptorStatusHander` is used for any status code which is not +// The DefaultInterceptorStatusHander is used for any status code which is not // explicitly assigned a handler. // var DefaultInterceptorStatusHandler = InfoInterceptorStatusHandler @@ -264,15 +265,15 @@ func reportInterceptorStatus(ctx context.Context, txn *newrelic.Transaction, han // // 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 +// 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. +// 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, +// 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), @@ -331,7 +332,7 @@ func newWrappedServerStream(stream grpc.ServerStream, txn *newrelic.Transaction) // UnaryServerInterceptor and StreamServerInterceptor to instrument unary and // streaming calls. // -// See the notes and examples for the `UnaryServerInterceptor()` function. +// See the notes and examples for the UnaryServerInterceptor() function. // func StreamServerInterceptor(app *newrelic.Application, options ...handlerOption) grpc.StreamServerInterceptor { if app == nil { From b5d08f3536f7d07ee4c4e654e8fad68e6fa0f70a Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Thu, 8 Jul 2021 16:24:19 -0700 Subject: [PATCH 18/20] removed test code --- v3/integrations/nrgrpc/example/server/server.go | 5 +---- v3/integrations/nrgrpc/nrgrpc_server.go | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/v3/integrations/nrgrpc/example/server/server.go b/v3/integrations/nrgrpc/example/server/server.go index 4a37dfcff..469f3c80d 100644 --- a/v3/integrations/nrgrpc/example/server/server.go +++ b/v3/integrations/nrgrpc/example/server/server.go @@ -14,8 +14,6 @@ import ( sampleapp "github.com/newrelic/go-agent/v3/integrations/nrgrpc/example/sampleapp" newrelic "github.com/newrelic/go-agent/v3/newrelic" "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) // Server is a gRPC server. @@ -30,8 +28,7 @@ func processMessage(ctx context.Context, msg *sampleapp.Message) { // DoUnaryUnary is a unary request, unary response method. func (s *Server) DoUnaryUnary(ctx context.Context, msg *sampleapp.Message) (*sampleapp.Message, error) { processMessage(ctx, msg) - // return &sampleapp.Message{Text: "Hello from DoUnaryUnary"}, nil - return &sampleapp.Message{}, status.New(codes.DataLoss, "oooooops!").Err() + return &sampleapp.Message{Text: "Hello from DoUnaryUnary"}, nil } // DoUnaryStream is a unary request, stream response method. diff --git a/v3/integrations/nrgrpc/nrgrpc_server.go b/v3/integrations/nrgrpc/nrgrpc_server.go index a9b1f6e0a..afca8033b 100644 --- a/v3/integrations/nrgrpc/nrgrpc_server.go +++ b/v3/integrations/nrgrpc/nrgrpc_server.go @@ -187,7 +187,7 @@ func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transactio txn.SetWebResponse(nil).WriteHeader(int(codes.OK)) txn.NoticeError(&newrelic.Error{ Message: s.Message(), - Class: "gRPC Error: " + s.Code().String(), + Class: "gRPC Status: " + s.Code().String(), }) txn.AddAttribute("GrpcStatusLevel", "error") txn.AddAttribute("GrpcStatusMessage", s.Message()) From 4708861f6d92086a32c83b07cce420fe5b9e25eb Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Thu, 8 Jul 2021 16:40:34 -0700 Subject: [PATCH 19/20] updated CHANGELOG for 3.14.0 release --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c61ba3d..eada1a590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,27 @@ # 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 ### Fixed From 8cc1b281f2435e4e18a5767eba1a58a402b26c6e Mon Sep 17 00:00:00 2001 From: Steve Willoughby Date: Mon, 12 Jul 2021 10:12:41 -0700 Subject: [PATCH 20/20] increased version number --- v3/newrelic/version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 (