├── .circleci └── config.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-3rdparty.csv ├── NOTICE ├── README.md ├── datadog.go ├── datadog_test.go ├── doc.go ├── errors.go ├── errors_test.go ├── examples ├── stats │ └── main.go └── trace │ └── main.go ├── go.mod ├── go.sum ├── msgpack.go ├── msgpack_gen.go ├── msgpack_test.go ├── sampler.go ├── sampler_test.go ├── span.go ├── span_test.go ├── stats.go ├── stats_test.go ├── trace.go ├── trace_test.go ├── transport.go └── transport_test.go /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | working_directory: /go/src/github.com/DataDog/opencensus-go-exporter-datadog 5 | docker: 6 | - image: circleci/golang:1.14 7 | - image: datadog/docker-dd-agent 8 | environment: 9 | - DD_APM_ENABLED=true 10 | - DD_BIND_HOST=0.0.0.0 11 | - DD_API_KEY=invalid_key_but_this_is_fine 12 | steps: 13 | - checkout 14 | - run: 15 | name: Fetching dependencies 16 | command: | 17 | go get -t ./... 18 | go get golang.org/x/lint/golint 19 | - run: 20 | name: Testing 21 | command: | 22 | go vet ./... 23 | golint $(go list ./... | grep -v /vendor/) 24 | INTEGRATION=1 go test -v -race ./... 25 | 26 | workflows: 27 | version: 2 28 | commit-workflow: 29 | jobs: 30 | - build 31 | scheduled-workflow: 32 | triggers: 33 | - schedule: 34 | # Everyday at 1am UTC 35 | cron: "0 1 * * *" 36 | filters: 37 | branches: 38 | only: 39 | - master 40 | jobs: 41 | - build 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .idea 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ### Contributing 2 | 3 | Pull requests for bug fixes are welcome, but before submitting new features or changes to current functionalities [open an issue](https://github.com/DataDog/opencensus-go-exporter-datadog/issues/new) 4 | and discuss your ideas or propose the changes you wish to make. After a resolution is reached a PR can be submitted for review. 5 | 6 | Commit messages should be prefixed with "trace" if they are related to APM or with "stats" if they are related to metrics. For example: 7 | ``` 8 | trace: add support for float64 9 | 10 | Adds support for `float64`, added in census-instrumentation/opencensus-go#1033 11 | 12 | Closes #37 13 | ``` 14 | Please apply the same logic for Pull Requests, start with "trace" or "stats", followed by a colon and a description of the change, similar to 15 | the official [Go language](https://github.com/golang/go/pulls). 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Datadog, Inc. 190 | Licensed under the Apache License, Version 2.0 (the "License"); 191 | you may not use this file except in compliance with the License. 192 | You may obtain a copy of the License at 193 | 194 | http://www.apache.org/licenses/LICENSE-2.0 195 | 196 | Unless required by applicable law or agreed to in writing, software 197 | distributed under the License is distributed on an "AS IS" BASIS, 198 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 199 | See the License for the specific language governing permissions and 200 | limitations under the License. 201 | -------------------------------------------------------------------------------- /LICENSE-3rdparty.csv: -------------------------------------------------------------------------------- 1 | Component,Origin,License 2 | core,go.opencensus.io,Apache-2.0 3 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Datadog OpenCensus Go Exporter 2 | Copyright 2018 Datadog, Inc. 3 | 4 | This product includes software developed at Datadog (https://www.datadoghq.com/). 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenCensus Go Datadog 2 | 3 | [![CircleCI](https://circleci.com/gh/DataDog/opencensus-go-exporter-datadog.svg?style=svg)](https://circleci.com/gh/DataDog/opencensus-go-exporter-datadog) [![GoDoc][godoc-image]][godoc-url] 4 | 5 | Provides OpenCensus stats and trace exporter support for Datadog Metrics and Datadog APM. The [examples folder](https://github.com/DataDog/opencensus-go-exporter-datadog/tree/master/examples) 6 | provides some simple usage examples. 7 | 8 | **Note**: **This repository is deprecated and is in maintenance mode. Bugs are being addressed, but new features are not being implemented.** OpenCensus and OpenTracing have merged into OpenTelemetry. It is recommended that OpenTelemetry alongside the 9 | [Datadog OpenTelemetry Exporter](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/datadogexporter) 10 | be used instead. 11 | 12 | 13 | ### Requirements: 14 | 15 | - [Go 1.10+](https://golang.org/doc/install) 16 | - [Datadog Agent 6](https://docs.datadoghq.com/agent/) 17 | 18 | [godoc-image]: https://godoc.org/github.com/DataDog/opencensus-go-exporter-datadog?status.svg 19 | [godoc-url]: https://godoc.org/github.com/DataDog/opencensus-go-exporter-datadog 20 | 21 | ### Contributing 22 | 23 | Please make sure to read through our [contribution guidelines](https://github.com/DataDog/opencensus-go-exporter-datadog/tree/master/CONTRIBUTING.md) before opening an issue or a Pull Request. 24 | 25 | ### Disclaimer 26 | 27 | In order to get accurate Datadog APM statistics and full distributed tracing, trace sampling must be done by the Datadog stack. For this to be possible, OpenCensus must be notified to forward all traces to our exporter: 28 | 29 | ```go 30 | trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()}) 31 | ``` 32 | 33 | This change simply means that Datadog will handle sampling. It does not mean that all traces will be sampled. 34 | -------------------------------------------------------------------------------- /datadog.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "log" 10 | "regexp" 11 | "strings" 12 | 13 | "github.com/DataDog/datadog-go/statsd" 14 | "go.opencensus.io/stats/view" 15 | "go.opencensus.io/tag" 16 | "go.opencensus.io/trace" 17 | ) 18 | 19 | var ( 20 | _ view.Exporter = (*Exporter)(nil) 21 | _ trace.Exporter = (*Exporter)(nil) 22 | ) 23 | 24 | // Exporter exports stats to Datadog. 25 | type Exporter struct { 26 | *statsExporter 27 | *traceExporter 28 | } 29 | 30 | // ExportView implements view.Exporter. 31 | func (e *Exporter) ExportView(vd *view.Data) { 32 | if len(vd.Rows) == 0 { 33 | return 34 | } 35 | e.statsExporter.addViewData(vd) 36 | } 37 | 38 | // ExportSpan implements trace.Exporter. 39 | func (e *Exporter) ExportSpan(s *trace.SpanData) { 40 | e.traceExporter.exportSpan(s) 41 | } 42 | 43 | // Stop cleanly stops the exporter, flushing any remaining spans and stats to the transport and 44 | // reporting any errors. Make sure to always call Stop at the end of your program in 45 | // order to not lose any tracing data. Only call Stop once per exporter. Repeated calls 46 | // will cause panic. 47 | func (e *Exporter) Stop() { 48 | e.statsExporter.stop() 49 | e.traceExporter.stop() 50 | } 51 | 52 | // Options contains options for configuring the exporter. 53 | type Options struct { 54 | // Namespace specifies the namespaces to which metric keys are appended. 55 | Namespace string 56 | 57 | // Service specifies the service name used for tracing. 58 | Service string 59 | 60 | // TraceAddr specifies the host[:port] address of the Datadog Trace Agent. 61 | // It defaults to localhost:8126. 62 | TraceAddr string 63 | 64 | // StatsAddr specifies the host[:port] address for DogStatsD. It defaults 65 | // to localhost:8125. 66 | StatsAddr string 67 | 68 | // OnError specifies a function that will be called if an error occurs during 69 | // processing stats or metrics. 70 | OnError func(err error) 71 | 72 | // Tags specifies a set of global tags to attach to each metric. 73 | Tags []string 74 | 75 | // GlobalTags holds a set of tags that will automatically be applied to all 76 | // exported spans. 77 | GlobalTags map[string]interface{} 78 | 79 | // DisableCountPerBuckets specifies whether to emit count_per_bucket metrics 80 | DisableCountPerBuckets bool 81 | 82 | // TagMetricNames specifies whether to include tags to metric names. 83 | TagMetricNames bool 84 | 85 | // StatsdOptions defines a set of options to be passed to the statsd client. 86 | StatsdOptions []statsd.Option 87 | } 88 | 89 | func (o *Options) onError(err error) { 90 | if o.OnError != nil { 91 | o.OnError(err) 92 | } else { 93 | log.Printf("Failed to export to Datadog: %v\n", err) 94 | } 95 | } 96 | 97 | // NewExporter returns an exporter that exports stats and traces to Datadog. 98 | // When using trace, it is important to call Stop at the end of your program 99 | // for a clean exit and to flush any remaining tracing data to the Datadog agent. 100 | // If an error occurs initializing the stats exporter, the error will be returned 101 | // and the exporter will be nil. 102 | func NewExporter(o Options) (exporter *Exporter, err error) { 103 | statsExporter, err := newStatsExporter(o) 104 | if err != nil { 105 | return nil, err 106 | } 107 | return &Exporter{ 108 | statsExporter: statsExporter, 109 | traceExporter: newTraceExporter(o), 110 | }, nil 111 | } 112 | 113 | // regex pattern 114 | var reg = regexp.MustCompile("[^a-zA-Z0-9]+") 115 | 116 | // sanitizeString replaces all non-alphanumerical characters to underscore 117 | func sanitizeString(str string) string { 118 | return reg.ReplaceAllString(str, "_") 119 | } 120 | 121 | // sanitizeMetricName formats the custom namespace and view name to 122 | // Datadog's metric naming convention 123 | func sanitizeMetricName(namespace string, v *view.View) string { 124 | if namespace != "" { 125 | namespace = strings.Replace(namespace, " ", "", -1) 126 | return sanitizeString(namespace) + "." + sanitizeString(v.Name) 127 | } 128 | return sanitizeString(v.Name) 129 | } 130 | 131 | // viewSignature creates the view signature with custom namespace 132 | func viewSignature(namespace string, tagMetricNames bool, v *view.View) string { 133 | if tagMetricNames { 134 | var buf strings.Builder 135 | buf.WriteString(sanitizeMetricName(namespace, v)) 136 | for _, k := range v.TagKeys { 137 | buf.WriteString("_" + k.Name()) 138 | } 139 | return buf.String() 140 | } 141 | 142 | return sanitizeMetricName(namespace, v) 143 | } 144 | 145 | // tagMetrics concatenates user input custom tags with row tags 146 | func (o *Options) tagMetrics(rowTags []tag.Tag, addlTags []string) []string { 147 | finalTags := make([]string, len(o.Tags), len(o.Tags)+len(rowTags)+len(addlTags)) 148 | copy(finalTags, o.Tags) 149 | for key := range rowTags { 150 | finalTags = append(finalTags, 151 | rowTags[key].Key.Name()+":"+rowTags[key].Value) 152 | } 153 | finalTags = append(finalTags, addlTags...) 154 | return finalTags 155 | } 156 | -------------------------------------------------------------------------------- /datadog_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "bytes" 10 | "context" 11 | "errors" 12 | "fmt" 13 | "log" 14 | "os" 15 | "reflect" 16 | "strings" 17 | "testing" 18 | "time" 19 | 20 | "go.opencensus.io/stats" 21 | "go.opencensus.io/stats/view" 22 | "go.opencensus.io/tag" 23 | ) 24 | 25 | var ( 26 | measureCount = stats.Int64("fooCount", "testing count metrics", stats.UnitBytes) 27 | measureSum = stats.Int64("fooSum", "testing sum metrics", stats.UnitBytes) 28 | measureLast = stats.Int64("fooLast", "testing LastValueData metrics", stats.UnitBytes) 29 | measureDist = stats.Int64("fooHisto", "testing histogram metrics", stats.UnitDimensionless) 30 | testTags []tag.Key 31 | ) 32 | 33 | func newView(agg *view.Aggregation) *view.View { 34 | return &view.View{ 35 | Name: "fooCount", 36 | Description: "fooDesc", 37 | Measure: measureCount, 38 | Aggregation: agg, 39 | } 40 | } 41 | 42 | func newCustomView(measureName string, agg *view.Aggregation, tags []tag.Key, measure *stats.Int64Measure) *view.View { 43 | return &view.View{ 44 | Name: measureName, 45 | Description: "fooDesc", 46 | Measure: measureCount, 47 | TagKeys: tags, 48 | Aggregation: agg, 49 | } 50 | } 51 | 52 | func TestExportView(t *testing.T) { 53 | reportPeriod := time.Millisecond 54 | exporter, err := testExporter(Options{}) 55 | if err != nil { 56 | t.Error(err) 57 | } 58 | 59 | vd := newCustomView("fooCount", view.Count(), testTags, measureCount) 60 | if err := view.Register(vd); err != nil { 61 | t.Fatalf("Register error occurred: %v\n", err) 62 | } 63 | defer view.Unregister(vd) 64 | // Wait for exporter to process metrics 65 | <-time.After(10 * reportPeriod) 66 | 67 | ctx := context.Background() 68 | stats.Record(ctx, measureCount.M(1)) 69 | <-time.After(10 * time.Millisecond) 70 | 71 | actual := exporter.view("fooCount") 72 | if actual != vd { 73 | t.Errorf("Expected: %v, Got: %v\n", vd, actual) 74 | } 75 | } 76 | 77 | func TestSanitizeString(t *testing.T) { 78 | testCases := []struct { 79 | input string 80 | want string 81 | }{ 82 | {"data-234_123!doge", "data_234_123_doge"}, 83 | {"hello!good@morn#ing$test%", "hello_good_morn_ing_test_"}, 84 | } 85 | for _, tc := range testCases { 86 | t.Run(tc.input, func(t *testing.T) { 87 | got := sanitizeString(tc.input) 88 | if got != tc.want { 89 | t.Errorf("Expected: %v, Got: %v\n", tc.want, got) 90 | } 91 | }) 92 | } 93 | } 94 | 95 | func TestSanitizeMetricName(t *testing.T) { 96 | vd1 := newCustomView("fooGauge", view.Count(), testTags, measureCount) 97 | vd2 := newCustomView("bar-Sum", view.Sum(), testTags, measureSum) 98 | 99 | testCases := []struct { 100 | namespace string 101 | view *view.View 102 | want string 103 | }{ 104 | {"opencensus", vd1, "opencensus.fooGauge"}, 105 | {"data!doge", vd2, "data_doge.bar_Sum"}, 106 | } 107 | for _, tc := range testCases { 108 | t.Run("Testing sanitizeMetricName", func(t *testing.T) { 109 | got := sanitizeMetricName(tc.namespace, tc.view) 110 | if got != tc.want { 111 | t.Errorf("Expected: %v, Got: %v\n", tc.want, got) 112 | } 113 | }) 114 | } 115 | } 116 | 117 | func TestSignatureNoTag(t *testing.T) { 118 | key, _ := tag.NewKey("signature") 119 | namespace := "opencensus" 120 | tags := append(testTags, key) 121 | vd := newCustomView("fooGauge", view.Count(), tags, measureCount) 122 | 123 | res := viewSignature(namespace, false, vd) 124 | exp := "opencensus.fooGauge" 125 | if res != exp { 126 | t.Errorf("Expected: %v, Got: %v\n", exp, res) 127 | } 128 | } 129 | 130 | func TestSignatureTag(t *testing.T) { 131 | key, _ := tag.NewKey("tag1") 132 | namespace := "datadog" 133 | tags := append(testTags, key) 134 | vd := newCustomView("fooCount", view.Count(), tags, measureCount) 135 | 136 | res := viewSignature(namespace, true, vd) 137 | exp := "datadog.fooCount_tag1" 138 | if res != exp { 139 | t.Errorf("Expected: %v, Got: %v\n", exp, res) 140 | } 141 | } 142 | 143 | func TestTagMetrics(t *testing.T) { 144 | o := Options{} 145 | key, _ := tag.NewKey("testTags") 146 | key2, _ := tag.NewKey("testTags2") 147 | 148 | tags := []tag.Tag{tag.Tag{Key: key, Value: "Metrics"}, tag.Tag{Key: key2, Value: "Metrics"}} 149 | customTag := []string{"program_name:main"} 150 | result := o.tagMetrics(tags, customTag) 151 | expected := []string{"testTags:Metrics", "testTags2:Metrics", "program_name:main"} 152 | 153 | if n := len(expected); n == 0 { 154 | t.Fatal("got 0") 155 | } 156 | 157 | if !reflect.DeepEqual(expected, result) { 158 | t.Fatalf("Expected: %v, Got: %v\n", expected, result) 159 | } 160 | } 161 | 162 | func TestOnErrorNil(t *testing.T) { 163 | var buf bytes.Buffer 164 | opt := &Options{} 165 | testError := errors.New("Testing error") 166 | 167 | testCases := []struct { 168 | input error 169 | want string 170 | }{ 171 | {nil, fmt.Sprintf("Failed to export to Datadog: %v", nil)}, 172 | {testError, "Testing error"}, 173 | } 174 | for _, tc := range testCases { 175 | t.Run(fmt.Sprintf("Testing error: %v\n", tc.input), func(t *testing.T) { 176 | log.SetOutput(&buf) 177 | defer func() { 178 | log.SetOutput(os.Stderr) 179 | }() 180 | opt.onError(tc.input) 181 | got := buf.String() 182 | if !strings.Contains(got, tc.want) { 183 | t.Errorf("expected: %v, got: %v\n", tc.want, got) 184 | } 185 | }) 186 | } 187 | } 188 | 189 | func TestCountData(t *testing.T) { 190 | reportPeriod := time.Millisecond 191 | exporter, err := testExporter(Options{}) 192 | if err != nil { 193 | t.Error(err) 194 | } 195 | 196 | vd := newCustomView("fooCount", view.Count(), testTags, measureCount) 197 | if err := view.Register(vd); err != nil { 198 | t.Fatalf("Register error occurred: %v\n", err) 199 | } 200 | defer view.Unregister(vd) 201 | // Wait for exporter to process metrics 202 | <-time.After(10 * reportPeriod) 203 | 204 | ctx := context.Background() 205 | stats.Record(ctx, measureCount.M(1)) 206 | <-time.After(10 * time.Millisecond) 207 | 208 | actual := exporter.view("fooCount") 209 | if !reflect.DeepEqual(*actual, *vd) { 210 | t.Errorf("Expected: %v, Got: %v\n", vd, actual) 211 | } 212 | } 213 | 214 | func TestSumData(t *testing.T) { 215 | reportPeriod := time.Millisecond 216 | exporter, err := testExporter(Options{}) 217 | if err != nil { 218 | t.Error(err) 219 | } 220 | 221 | vd := newCustomView("fooSum", view.Sum(), testTags, measureSum) 222 | if err := view.Register(vd); err != nil { 223 | t.Fatalf("Register error occurred: %v\n", err) 224 | } 225 | defer view.Unregister(vd) 226 | // Wait for exporter to process metrics 227 | <-time.After(10 * reportPeriod) 228 | 229 | ctx := context.Background() 230 | stats.Record(ctx, measureCount.M(1)) 231 | <-time.After(10 * time.Millisecond) 232 | 233 | actual := exporter.view("fooSum") 234 | if actual != vd { 235 | t.Errorf("Expected: %v, Got: %v\n", vd, actual) 236 | } 237 | } 238 | 239 | func TestLastValueData(t *testing.T) { 240 | reportPeriod := time.Millisecond 241 | exporter, err := testExporter(Options{}) 242 | if err != nil { 243 | t.Error(err) 244 | } 245 | 246 | vd := newCustomView("fooLast", view.LastValue(), testTags, measureLast) 247 | if err := view.Register(vd); err != nil { 248 | t.Fatalf("Register error occurred: %v\n", err) 249 | } 250 | defer view.Unregister(vd) 251 | // Wait for exporter to process metrics 252 | <-time.After(10 * reportPeriod) 253 | 254 | ctx := context.Background() 255 | stats.Record(ctx, measureCount.M(1)) 256 | <-time.After(10 * time.Millisecond) 257 | 258 | actual := exporter.view("fooLast") 259 | if actual != vd { 260 | t.Errorf("Expected: %v, Got: %v\n", vd, actual) 261 | } 262 | } 263 | 264 | func TestHistogram(t *testing.T) { 265 | reportPeriod := time.Millisecond 266 | exporter, err := testExporter(Options{}) 267 | if err != nil { 268 | t.Error(err) 269 | } 270 | 271 | vd := newCustomView("fooHisto", view.Distribution(), testTags, measureDist) 272 | if err := view.Register(vd); err != nil { 273 | t.Fatalf("Register error occurred: %v\n", err) 274 | } 275 | defer view.Unregister(vd) 276 | // Wait for exporter to process metrics 277 | <-time.After(10 * reportPeriod) 278 | 279 | ctx := context.Background() 280 | stats.Record(ctx, measureCount.M(1)) 281 | <-time.After(10 * time.Millisecond) 282 | 283 | actual := exporter.view("fooHisto") 284 | if actual != vd { 285 | t.Errorf("Expected: %v, Got: %v\n", vd, actual) 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package datadog contains a Datadog exporter for OpenCensus. 2 | package datadog 3 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "errors" 10 | "fmt" 11 | "log" 12 | "strings" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | const ( 18 | // defaultErrorLimit specifies the maximum number of occurrences that will 19 | // be recorded for an error of a certain type. 20 | defaultErrorLimit = 50 21 | 22 | // defaultErrorFreq specifies the default frequency at which errors will 23 | // be reported. 24 | defaultErrorFreq = 5 * time.Second 25 | ) 26 | 27 | // errorType specifies the error type. 28 | type errorType int 29 | 30 | const ( 31 | // errorTypeEncoding specifies that an encoding error has occurred. 32 | errorTypeEncoding errorType = iota 33 | 34 | // errorTypeOverflow specifies that the in channel capacity has been reached. 35 | errorTypeOverflow 36 | 37 | // errorTypeTransport specifies that an error occurred while trying 38 | // to upload spans to the agent. 39 | errorTypeTransport 40 | 41 | // errorTypeUnknown specifies that an unknown error type was reported. 42 | errorTypeUnknown 43 | ) 44 | 45 | // errorTypeStrings maps error types to their human-readable description. 46 | var errorTypeStrings = map[errorType]string{ 47 | errorTypeEncoding: "encoding error", 48 | errorTypeOverflow: "span buffer overflow", 49 | errorTypeTransport: "transport error", 50 | errorTypeUnknown: "error", 51 | } 52 | 53 | // String implements fmt.Stringer. 54 | func (et errorType) String() string { return errorTypeStrings[et] } 55 | 56 | // errorAmortizer amortizes high frequency errors and condenses them into 57 | // periodical reports to avoid flooding. 58 | type errorAmortizer struct { 59 | interval time.Duration // frequency of report 60 | callback func(error) // error handler; defaults to log.Println 61 | 62 | mu sync.RWMutex // guards below fields 63 | pausing bool 64 | errs map[errorType]*aggregateError 65 | } 66 | 67 | // newErrorAmortizer creates a new errorAmortizer which calls the provided function 68 | // at the given interval, passing it a detailed error report if one has occurred. 69 | func newErrorAmortizer(interval time.Duration, cb func(error)) *errorAmortizer { 70 | if cb == nil { 71 | cb = func(err error) { 72 | log.Println(err) 73 | } 74 | } 75 | return &errorAmortizer{ 76 | interval: interval, 77 | callback: cb, 78 | errs: make(map[errorType]*aggregateError), 79 | } 80 | } 81 | 82 | // flush flushes any aggregated errors and resets the amortizer. 83 | func (e *errorAmortizer) flush() { 84 | e.mu.Lock() 85 | defer e.mu.Unlock() 86 | n := len(e.errs) 87 | if n == 0 { 88 | return 89 | } 90 | var str strings.Builder 91 | str.WriteString("Datadog Exporter error: ") 92 | for _, err := range e.errs { 93 | if n > 1 { 94 | str.WriteString("\n\t") 95 | } 96 | str.WriteString(err.Error()) 97 | } 98 | e.callback(errors.New(str.String())) 99 | e.errs = make(map[errorType]*aggregateError) 100 | e.pausing = false 101 | } 102 | 103 | // limitReached returns true if the defaultErrorLimit has been reached 104 | // for the given error type. 105 | func (e *errorAmortizer) limitReached(typ errorType) bool { 106 | e.mu.RLock() 107 | defer e.mu.RUnlock() 108 | return e.errs[typ] != nil && e.errs[typ].num > defaultErrorLimit-1 109 | } 110 | 111 | // log logs an error of the given type, having the given message. err 112 | // is optional and can be nil. 113 | func (e *errorAmortizer) log(typ errorType, err error) { 114 | if e.limitReached(typ) { 115 | // avoid too much lock contention 116 | return 117 | } 118 | e.mu.Lock() 119 | defer e.mu.Unlock() 120 | if _, ok := e.errs[typ]; !ok { 121 | e.errs[typ] = newError(typ, err) 122 | } else { 123 | e.errs[typ].num++ 124 | } 125 | if !e.pausing { 126 | e.pausing = true 127 | time.AfterFunc(e.interval, e.flush) 128 | } 129 | } 130 | 131 | var _ error = (*aggregateError)(nil) 132 | 133 | // aggregateError is an error consisting of a type and an optional context 134 | // error. It is used to aggregate errors inside the errorAmortizer. 135 | type aggregateError struct { 136 | typ errorType // error type 137 | err error // error message (optional) 138 | num int // number of occurrences 139 | } 140 | 141 | // newError creates a new aggregateError. 142 | func newError(t errorType, err error) *aggregateError { 143 | return &aggregateError{t, err, 1} 144 | } 145 | 146 | // Error implements the error interface. If the error occurred more than 147 | // once, it appends the number of occurrences to the error message. 148 | func (e *aggregateError) Error() string { 149 | var str strings.Builder 150 | if e.err == nil { 151 | str.WriteString(e.typ.String()) 152 | } else { 153 | // no need to include the type into the message, it will be evident 154 | // from the message itself. 155 | str.WriteString(e.err.Error()) 156 | } 157 | if e.num >= defaultErrorLimit { 158 | str.WriteString(fmt.Sprintf(" (x%d+)", defaultErrorLimit)) 159 | } else if e.num > 1 { 160 | str.WriteString(fmt.Sprintf(" (x%d)", e.num)) 161 | } 162 | return str.String() 163 | } 164 | -------------------------------------------------------------------------------- /errors_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "errors" 10 | "fmt" 11 | "strings" 12 | "sync" 13 | "testing" 14 | "time" 15 | ) 16 | 17 | const waitTime = 10 * time.Millisecond 18 | 19 | func containsFunc(t *testing.T) func(a error, b string) { 20 | return func(a error, b string) { 21 | if !strings.Contains(a.Error(), b) { 22 | t.Fatalf("%q did not contain %q", a.Error(), b) 23 | } 24 | } 25 | } 26 | 27 | func TestErrorAmortizer(t *testing.T) { 28 | if testing.Short() { 29 | t.SkipNow() 30 | } 31 | 32 | t.Run("same", func(t *testing.T) { 33 | ma := newTestErrorAmortizer() 34 | for i := 0; i < 10; i++ { 35 | ma.log(errorTypeOverflow, errors.New("buffer full")) 36 | } 37 | time.Sleep(waitTime + 10*time.Millisecond) 38 | out := ma.lastError() 39 | if out == nil { 40 | t.Fatal("no error") 41 | } 42 | contains := containsFunc(t) 43 | contains(out, "Datadog Exporter error:") 44 | contains(out, "(x10)") 45 | contains(out, "buffer full") 46 | }) 47 | 48 | t.Run("contention", func(t *testing.T) { 49 | ma := newTestErrorAmortizer() 50 | for i := 0; i < defaultErrorLimit+10; i++ { 51 | ma.log(errorTypeOverflow, nil) 52 | } 53 | time.Sleep(waitTime + 10*time.Millisecond) 54 | out := ma.lastError() 55 | if out == nil { 56 | t.Fatal("no error") 57 | } 58 | containsFunc(t)(out, fmt.Sprintf("Datadog Exporter error: span buffer overflow (x%d+)", defaultErrorLimit)) 59 | }) 60 | 61 | t.Run("various", func(t *testing.T) { 62 | ma := newTestErrorAmortizer() 63 | for j := 0; j < 2; j++ { 64 | ma.reset() 65 | for i := 0; i < 2; i++ { 66 | ma.log(errorTypeOverflow, nil) 67 | } 68 | for i := 0; i < 5; i++ { 69 | ma.log(errorTypeTransport, errors.New("transport failed")) 70 | } 71 | for i := 0; i < 3; i++ { 72 | ma.log(errorTypeEncoding, errors.New("encoding error")) 73 | } 74 | ma.log(errorTypeUnknown, errors.New("unknown error")) 75 | time.Sleep(waitTime + 10*time.Millisecond) 76 | out := ma.lastError() 77 | if out == nil { 78 | t.Fatal("no error") 79 | } 80 | contains := containsFunc(t) 81 | contains(out, "Datadog Exporter error:") 82 | contains(out, "span buffer overflow (x2)") 83 | contains(out, "transport failed (x5)") 84 | contains(out, "encoding error (x3)") 85 | contains(out, "unknown error") 86 | } 87 | }) 88 | 89 | t.Run("one", func(t *testing.T) { 90 | ma := newTestErrorAmortizer() 91 | ma.log(errorTypeUnknown, errors.New("some error")) 92 | time.Sleep(waitTime + 10*time.Millisecond) 93 | out := ma.lastError() 94 | if out == nil { 95 | t.Fatal("no error") 96 | } 97 | contains := containsFunc(t) 98 | contains(out, "Datadog Exporter error:") 99 | contains(out, "some error") 100 | }) 101 | } 102 | 103 | type testErrorAmortizer struct { 104 | *errorAmortizer 105 | 106 | mu sync.RWMutex // guards lastErr 107 | lastErr error 108 | } 109 | 110 | func (ma *testErrorAmortizer) lastError() error { 111 | ma.mu.RLock() 112 | defer ma.mu.RUnlock() 113 | return ma.lastErr 114 | } 115 | 116 | func (ma *testErrorAmortizer) reset() { 117 | ma.mu.RLock() 118 | defer ma.mu.RUnlock() 119 | ma.lastErr = nil 120 | } 121 | 122 | func (ma *testErrorAmortizer) captureError(err error) { 123 | ma.mu.Lock() 124 | defer ma.mu.Unlock() 125 | ma.lastErr = err 126 | } 127 | 128 | func newTestErrorAmortizer() *testErrorAmortizer { 129 | ea := newErrorAmortizer(waitTime, nil) 130 | ma := &testErrorAmortizer{errorAmortizer: ea} 131 | ma.errorAmortizer.callback = ma.captureError 132 | return ma 133 | } 134 | -------------------------------------------------------------------------------- /examples/stats/main.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package main 7 | 8 | import ( 9 | "context" 10 | "log" 11 | "math/rand" 12 | "time" 13 | 14 | datadog "github.com/DataDog/opencensus-go-exporter-datadog" 15 | "go.opencensus.io/stats" 16 | "go.opencensus.io/stats/view" 17 | ) 18 | 19 | // Create measures. The program will record measures for the size of 20 | // processed videos and the number of videos marked as spam. 21 | var ( 22 | videoCount = stats.Int64("my.org/measures/video_count", "number of processed videos", stats.UnitDimensionless) 23 | videoSize = stats.Int64("my.org/measures/video_size", "size of processed video", stats.UnitBytes) 24 | ) 25 | 26 | func main() { 27 | exporter, err := datadog.NewExporter(datadog.Options{}) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | defer exporter.Stop() 32 | 33 | view.RegisterExporter(exporter) 34 | 35 | // Create view to see the number of processed videos cumulatively. 36 | // Create view to see the amount of video processed 37 | view.Register( 38 | &view.View{ 39 | Name: "video_count", 40 | Description: "number of videos processed over time", 41 | Measure: videoCount, 42 | Aggregation: view.Count(), 43 | }, 44 | &view.View{ 45 | Name: "video_size", 46 | Description: "processed video size over time", 47 | Measure: videoSize, 48 | Aggregation: view.Distribution(0, 1<<16, 1<<32), 49 | }, 50 | ) 51 | 52 | // Set reporting period to report data at every second. 53 | view.SetReportingPeriod(1 * time.Second) 54 | 55 | // Record some measures... 56 | for { 57 | log.Printf("recording...\n") 58 | stats.Record(context.Background(), videoCount.M(1), videoSize.M(rand.Int63())) 59 | <-time.After(time.Millisecond * time.Duration(1+rand.Intn(400))) 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /examples/trace/main.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package main 7 | 8 | import ( 9 | "context" 10 | "log" 11 | 12 | datadog "github.com/DataDog/opencensus-go-exporter-datadog" 13 | "go.opencensus.io/trace" 14 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 15 | ) 16 | 17 | func main() { 18 | exporter, err := datadog.NewExporter(datadog.Options{Service: "my-app"}) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | defer exporter.Stop() 23 | 24 | trace.RegisterExporter(exporter) 25 | 26 | // For demoing purposes, always sample. 27 | trace.ApplyConfig(trace.Config{ 28 | DefaultSampler: trace.AlwaysSample(), 29 | }) 30 | 31 | ctx, span := trace.StartSpan(context.Background(), "/foo") 32 | bar(ctx) 33 | span.End() 34 | } 35 | 36 | func bar(ctx context.Context) { 37 | ctx, span := trace.StartSpan(ctx, "/bar") 38 | defer span.End() 39 | 40 | // Do bar... 41 | 42 | // Set Datadog APM Trace Metadata 43 | span.AddAttributes( 44 | trace.StringAttribute(ext.ResourceName, "/foo/bar"), 45 | trace.StringAttribute(ext.SpanType, ext.SpanTypeWeb), 46 | ) 47 | } 48 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/DataDog/opencensus-go-exporter-datadog 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/DataDog/datadog-go v3.5.0+incompatible 7 | github.com/philhofer/fwd v1.0.0 // indirect 8 | github.com/stretchr/testify v1.4.0 9 | github.com/tinylib/msgp v1.1.2 10 | go.opencensus.io v0.22.3 11 | gopkg.in/DataDog/dd-trace-go.v1 v1.22.0 12 | ) 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/DataDog/datadog-go v3.5.0+incompatible h1:AShr9cqkF+taHjyQgcBcQUt/ZNK+iPq4ROaZwSX5c/U= 4 | github.com/DataDog/datadog-go v3.5.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= 5 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 6 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 7 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 9 | github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= 10 | github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= 11 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 12 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 13 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 14 | github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= 15 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 16 | github.com/philhofer/fwd v1.0.0 h1:UbZqGr5Y38ApvM/V/jEljVxwocdweyH+vmYvRPBnbqQ= 17 | github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= 18 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 19 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 20 | github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= 21 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 22 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 23 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 24 | github.com/tinylib/msgp v1.1.2 h1:gWmO7n0Ys2RBEb7GPYB9Ujq8Mk5p2U08lRnmMcGy6BQ= 25 | github.com/tinylib/msgp v1.1.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= 26 | go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= 27 | go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= 28 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 29 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 30 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 31 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 32 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 33 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 34 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 35 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 36 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 37 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 38 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 39 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 40 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 41 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 42 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 43 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 44 | golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 45 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 46 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 47 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 48 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 49 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 50 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 51 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 52 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 53 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 54 | google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 55 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 56 | google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= 57 | gopkg.in/DataDog/dd-trace-go.v1 v1.22.0 h1:gpWsqqkwUldNZXGJqT69NU9MdEDhLboK1C4nMgR0MWw= 58 | gopkg.in/DataDog/dd-trace-go.v1 v1.22.0/go.mod h1:DVp8HmDh8PuTu2Z0fVVlBsyWaC++fzwVCaGWylTe3tg= 59 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 60 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 61 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 62 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 63 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 64 | -------------------------------------------------------------------------------- /msgpack.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | //go:generate msgp -unexported -marshal=false -o=msgpack_gen.go -tests=false 7 | //msgp:ignore payload packedSpans 8 | 9 | package datadog 10 | 11 | import ( 12 | "bytes" 13 | "encoding/binary" 14 | "fmt" 15 | "math" 16 | 17 | "github.com/tinylib/msgp/msgp" 18 | ) 19 | 20 | type ( 21 | ddPayload []ddTrace // used in tests 22 | ddTrace []ddSpan // used in tests 23 | ) 24 | 25 | // ddSpan represents the Datadog span definition. 26 | type ddSpan struct { 27 | SpanID uint64 `msg:"span_id"` 28 | TraceID uint64 `msg:"trace_id"` 29 | ParentID uint64 `msg:"parent_id"` 30 | Name string `msg:"name"` 31 | Service string `msg:"service"` 32 | Resource string `msg:"resource"` 33 | Type string `msg:"type"` 34 | Start int64 `msg:"start"` 35 | Duration int64 `msg:"duration"` 36 | Meta map[string]string `msg:"meta,omitempty"` 37 | Metrics map[string]float64 `msg:"metrics,omitempty"` 38 | Error int32 `msg:"error"` 39 | } 40 | 41 | // maxLength indicates the maximum number of items supported in a msgpack-encoded array. 42 | // See: https://github.com/msgpack/msgpack/blob/master/spec.md#array-format-family 43 | const maxLength = uint(math.MaxUint32) 44 | 45 | // errOverflow is returned when maxLength is exceeded. 46 | var errOverflow = fmt.Errorf("maximum msgpack array length (%d) exceeded", maxLength) 47 | 48 | // payload represents a Datadog-compatible, msgpack-encoded payload consisting of traces. 49 | // It allows adding spans sequentially while keeping track of the size of the resulting payload. 50 | type payload struct { 51 | // traces maps trace IDs to their specific set of msgpack-encoded spans. 52 | traces map[uint64]*packedSpans 53 | 54 | // headerlessSize specifies the size of the payload in bytes, excluding the header 55 | // which can range between 1 to 5 bytes, depending on len(traces). 56 | headerlessSize int 57 | } 58 | 59 | func newPayload() *payload { 60 | return &payload{traces: make(map[uint64]*packedSpans)} 61 | } 62 | 63 | // reset resets the payload, making it ready to use for a new buffer. 64 | func (p *payload) reset() { 65 | p.traces = make(map[uint64]*packedSpans) 66 | p.headerlessSize = 0 67 | } 68 | 69 | // size returns the number of bytes that the resulting payload would occupy given 70 | // the current state. 71 | func (p *payload) size() int { 72 | return p.headerlessSize + arrayHeaderSize(uint64(len(p.traces))) 73 | } 74 | 75 | // add adds the given span to the payload. 76 | func (p *payload) add(span *ddSpan) error { 77 | if uint(len(p.traces)) >= maxLength { 78 | return errOverflow 79 | } 80 | id := span.TraceID 81 | if _, ok := p.traces[id]; !ok { 82 | p.traces[id] = new(packedSpans) 83 | } 84 | oldsize := p.traces[id].size() 85 | if err := p.traces[id].add(span); err != nil { 86 | return err 87 | } 88 | newsize := p.traces[id].size() 89 | p.headerlessSize += newsize - oldsize 90 | return nil 91 | } 92 | 93 | // buffer creates a copy of the msgpack-encoded payload and returns it. 94 | func (p *payload) buffer() *bytes.Buffer { 95 | var ( 96 | buf bytes.Buffer 97 | header [8]byte 98 | ) 99 | off := arrayHeader(&header, uint64(len(p.traces))) 100 | buf.Write(header[off:]) 101 | for _, ss := range p.traces { 102 | buf.Write(ss.bytes()) 103 | } 104 | return &buf 105 | } 106 | 107 | // packedSpans represents a slice of spans encoded in msgpack format. It allows adding spans 108 | // sequentially while keeping track of their count. 109 | type packedSpans struct { 110 | count uint64 // number of items in slice 111 | buf bytes.Buffer // msgpack encoded items (without header) 112 | } 113 | 114 | // add adds the given span to the trace. 115 | func (s *packedSpans) add(span *ddSpan) error { 116 | if uint(s.count) >= maxLength { 117 | return errOverflow 118 | } 119 | if err := msgp.Encode(&s.buf, span); err != nil { 120 | return err 121 | } 122 | s.count++ 123 | return nil 124 | } 125 | 126 | // size returns the number of bytes that would be returned by a call to bytes(). 127 | func (s *packedSpans) size() int { 128 | return s.buf.Len() + arrayHeaderSize(s.count) 129 | } 130 | 131 | // reset resets the packedSpans. 132 | func (s *packedSpans) reset() { 133 | s.count = 0 134 | s.buf.Reset() 135 | } 136 | 137 | // bytes returns the msgpack encoded set of bytes that represents the entire slice. 138 | func (s *packedSpans) bytes() []byte { 139 | var header [8]byte 140 | off := arrayHeader(&header, s.count) 141 | var buf bytes.Buffer 142 | buf.Write(header[off:]) 143 | buf.Write(s.buf.Bytes()) 144 | return buf.Bytes() 145 | } 146 | 147 | // arrayHeader writes the msgpack array header for a slice of length n into out. 148 | // It returns the offset at which to begin reading from out. For more information, 149 | // see the msgpack spec: 150 | // https://github.com/msgpack/msgpack/blob/master/spec.md#array-format-family 151 | func arrayHeader(out *[8]byte, n uint64) (off int) { 152 | const ( 153 | msgpackArrayFix byte = 144 // up to 15 items 154 | msgpackArray16 = 0xdc // up to 2^16-1 items, followed by size in 2 bytes 155 | msgpackArray32 = 0xdd // up to 2^32-1 items, followed by size in 4 bytes 156 | ) 157 | off = 8 - arrayHeaderSize(n) 158 | switch { 159 | case n <= 15: 160 | out[off] = msgpackArrayFix + byte(n) 161 | case n <= math.MaxUint16: 162 | binary.BigEndian.PutUint64(out[:], n) // writes 2 bytes 163 | out[off] = msgpackArray16 164 | case n <= math.MaxUint32: 165 | fallthrough 166 | default: 167 | binary.BigEndian.PutUint64(out[:], n) // writes 4 bytes 168 | out[off] = msgpackArray32 169 | } 170 | return off 171 | } 172 | 173 | // arrayHeaderSize returns the size in bytes of a header for a msgpack array of length n. 174 | func arrayHeaderSize(n uint64) int { 175 | switch { 176 | case n == 0: 177 | return 0 178 | case n <= 15: 179 | return 1 180 | case n <= math.MaxUint16: 181 | return 3 182 | case n <= math.MaxUint32: 183 | fallthrough 184 | default: 185 | return 5 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /msgpack_gen.go: -------------------------------------------------------------------------------- 1 | package datadog 2 | 3 | // NOTE: THIS FILE WAS PRODUCED BY THE 4 | // MSGP CODE GENERATION TOOL (github.com/tinylib/msgp) 5 | // DO NOT EDIT 6 | 7 | import ( 8 | "github.com/tinylib/msgp/msgp" 9 | ) 10 | 11 | // DecodeMsg implements msgp.Decodable 12 | func (z *ddPayload) DecodeMsg(dc *msgp.Reader) (err error) { 13 | var zb0003 uint32 14 | zb0003, err = dc.ReadArrayHeader() 15 | if err != nil { 16 | return 17 | } 18 | if cap((*z)) >= int(zb0003) { 19 | (*z) = (*z)[:zb0003] 20 | } else { 21 | (*z) = make(ddPayload, zb0003) 22 | } 23 | for zb0001 := range *z { 24 | var zb0004 uint32 25 | zb0004, err = dc.ReadArrayHeader() 26 | if err != nil { 27 | return 28 | } 29 | if cap((*z)[zb0001]) >= int(zb0004) { 30 | (*z)[zb0001] = ((*z)[zb0001])[:zb0004] 31 | } else { 32 | (*z)[zb0001] = make(ddTrace, zb0004) 33 | } 34 | for zb0002 := range (*z)[zb0001] { 35 | err = (*z)[zb0001][zb0002].DecodeMsg(dc) 36 | if err != nil { 37 | return 38 | } 39 | } 40 | } 41 | return 42 | } 43 | 44 | // EncodeMsg implements msgp.Encodable 45 | func (z ddPayload) EncodeMsg(en *msgp.Writer) (err error) { 46 | err = en.WriteArrayHeader(uint32(len(z))) 47 | if err != nil { 48 | return 49 | } 50 | for zb0005 := range z { 51 | err = en.WriteArrayHeader(uint32(len(z[zb0005]))) 52 | if err != nil { 53 | return 54 | } 55 | for zb0006 := range z[zb0005] { 56 | err = z[zb0005][zb0006].EncodeMsg(en) 57 | if err != nil { 58 | return 59 | } 60 | } 61 | } 62 | return 63 | } 64 | 65 | // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message 66 | func (z ddPayload) Msgsize() (s int) { 67 | s = msgp.ArrayHeaderSize 68 | for zb0005 := range z { 69 | s += msgp.ArrayHeaderSize 70 | for zb0006 := range z[zb0005] { 71 | s += z[zb0005][zb0006].Msgsize() 72 | } 73 | } 74 | return 75 | } 76 | 77 | // DecodeMsg implements msgp.Decodable 78 | func (z *ddSpan) DecodeMsg(dc *msgp.Reader) (err error) { 79 | var field []byte 80 | _ = field 81 | var zb0001 uint32 82 | zb0001, err = dc.ReadMapHeader() 83 | if err != nil { 84 | return 85 | } 86 | for zb0001 > 0 { 87 | zb0001-- 88 | field, err = dc.ReadMapKeyPtr() 89 | if err != nil { 90 | return 91 | } 92 | switch msgp.UnsafeString(field) { 93 | case "span_id": 94 | z.SpanID, err = dc.ReadUint64() 95 | if err != nil { 96 | return 97 | } 98 | case "trace_id": 99 | z.TraceID, err = dc.ReadUint64() 100 | if err != nil { 101 | return 102 | } 103 | case "parent_id": 104 | z.ParentID, err = dc.ReadUint64() 105 | if err != nil { 106 | return 107 | } 108 | case "name": 109 | z.Name, err = dc.ReadString() 110 | if err != nil { 111 | return 112 | } 113 | case "service": 114 | z.Service, err = dc.ReadString() 115 | if err != nil { 116 | return 117 | } 118 | case "resource": 119 | z.Resource, err = dc.ReadString() 120 | if err != nil { 121 | return 122 | } 123 | case "type": 124 | z.Type, err = dc.ReadString() 125 | if err != nil { 126 | return 127 | } 128 | case "start": 129 | z.Start, err = dc.ReadInt64() 130 | if err != nil { 131 | return 132 | } 133 | case "duration": 134 | z.Duration, err = dc.ReadInt64() 135 | if err != nil { 136 | return 137 | } 138 | case "meta": 139 | var zb0002 uint32 140 | zb0002, err = dc.ReadMapHeader() 141 | if err != nil { 142 | return 143 | } 144 | if z.Meta == nil && zb0002 > 0 { 145 | z.Meta = make(map[string]string, zb0002) 146 | } else if len(z.Meta) > 0 { 147 | for key := range z.Meta { 148 | delete(z.Meta, key) 149 | } 150 | } 151 | for zb0002 > 0 { 152 | zb0002-- 153 | var za0001 string 154 | var za0002 string 155 | za0001, err = dc.ReadString() 156 | if err != nil { 157 | return 158 | } 159 | za0002, err = dc.ReadString() 160 | if err != nil { 161 | return 162 | } 163 | z.Meta[za0001] = za0002 164 | } 165 | case "metrics": 166 | var zb0003 uint32 167 | zb0003, err = dc.ReadMapHeader() 168 | if err != nil { 169 | return 170 | } 171 | if z.Metrics == nil && zb0003 > 0 { 172 | z.Metrics = make(map[string]float64, zb0003) 173 | } else if len(z.Metrics) > 0 { 174 | for key := range z.Metrics { 175 | delete(z.Metrics, key) 176 | } 177 | } 178 | for zb0003 > 0 { 179 | zb0003-- 180 | var za0003 string 181 | var za0004 float64 182 | za0003, err = dc.ReadString() 183 | if err != nil { 184 | return 185 | } 186 | za0004, err = dc.ReadFloat64() 187 | if err != nil { 188 | return 189 | } 190 | z.Metrics[za0003] = za0004 191 | } 192 | case "error": 193 | z.Error, err = dc.ReadInt32() 194 | if err != nil { 195 | return 196 | } 197 | default: 198 | err = dc.Skip() 199 | if err != nil { 200 | return 201 | } 202 | } 203 | } 204 | return 205 | } 206 | 207 | // EncodeMsg implements msgp.Encodable 208 | func (z *ddSpan) EncodeMsg(en *msgp.Writer) (err error) { 209 | // map header, size 12 210 | // write "span_id" 211 | err = en.Append(0x8c, 0xa7, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64) 212 | if err != nil { 213 | return 214 | } 215 | err = en.WriteUint64(z.SpanID) 216 | if err != nil { 217 | return 218 | } 219 | // write "trace_id" 220 | err = en.Append(0xa8, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64) 221 | if err != nil { 222 | return 223 | } 224 | err = en.WriteUint64(z.TraceID) 225 | if err != nil { 226 | return 227 | } 228 | // write "parent_id" 229 | err = en.Append(0xa9, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64) 230 | if err != nil { 231 | return 232 | } 233 | err = en.WriteUint64(z.ParentID) 234 | if err != nil { 235 | return 236 | } 237 | // write "name" 238 | err = en.Append(0xa4, 0x6e, 0x61, 0x6d, 0x65) 239 | if err != nil { 240 | return 241 | } 242 | err = en.WriteString(z.Name) 243 | if err != nil { 244 | return 245 | } 246 | // write "service" 247 | err = en.Append(0xa7, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65) 248 | if err != nil { 249 | return 250 | } 251 | err = en.WriteString(z.Service) 252 | if err != nil { 253 | return 254 | } 255 | // write "resource" 256 | err = en.Append(0xa8, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65) 257 | if err != nil { 258 | return 259 | } 260 | err = en.WriteString(z.Resource) 261 | if err != nil { 262 | return 263 | } 264 | // write "type" 265 | err = en.Append(0xa4, 0x74, 0x79, 0x70, 0x65) 266 | if err != nil { 267 | return 268 | } 269 | err = en.WriteString(z.Type) 270 | if err != nil { 271 | return 272 | } 273 | // write "start" 274 | err = en.Append(0xa5, 0x73, 0x74, 0x61, 0x72, 0x74) 275 | if err != nil { 276 | return 277 | } 278 | err = en.WriteInt64(z.Start) 279 | if err != nil { 280 | return 281 | } 282 | // write "duration" 283 | err = en.Append(0xa8, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e) 284 | if err != nil { 285 | return 286 | } 287 | err = en.WriteInt64(z.Duration) 288 | if err != nil { 289 | return 290 | } 291 | // write "meta" 292 | err = en.Append(0xa4, 0x6d, 0x65, 0x74, 0x61) 293 | if err != nil { 294 | return 295 | } 296 | err = en.WriteMapHeader(uint32(len(z.Meta))) 297 | if err != nil { 298 | return 299 | } 300 | for za0001, za0002 := range z.Meta { 301 | err = en.WriteString(za0001) 302 | if err != nil { 303 | return 304 | } 305 | err = en.WriteString(za0002) 306 | if err != nil { 307 | return 308 | } 309 | } 310 | // write "metrics" 311 | err = en.Append(0xa7, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73) 312 | if err != nil { 313 | return 314 | } 315 | err = en.WriteMapHeader(uint32(len(z.Metrics))) 316 | if err != nil { 317 | return 318 | } 319 | for za0003, za0004 := range z.Metrics { 320 | err = en.WriteString(za0003) 321 | if err != nil { 322 | return 323 | } 324 | err = en.WriteFloat64(za0004) 325 | if err != nil { 326 | return 327 | } 328 | } 329 | // write "error" 330 | err = en.Append(0xa5, 0x65, 0x72, 0x72, 0x6f, 0x72) 331 | if err != nil { 332 | return 333 | } 334 | err = en.WriteInt32(z.Error) 335 | if err != nil { 336 | return 337 | } 338 | return 339 | } 340 | 341 | // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message 342 | func (z *ddSpan) Msgsize() (s int) { 343 | s = 1 + 8 + msgp.Uint64Size + 9 + msgp.Uint64Size + 10 + msgp.Uint64Size + 5 + msgp.StringPrefixSize + len(z.Name) + 8 + msgp.StringPrefixSize + len(z.Service) + 9 + msgp.StringPrefixSize + len(z.Resource) + 5 + msgp.StringPrefixSize + len(z.Type) + 6 + msgp.Int64Size + 9 + msgp.Int64Size + 5 + msgp.MapHeaderSize 344 | if z.Meta != nil { 345 | for za0001, za0002 := range z.Meta { 346 | _ = za0002 347 | s += msgp.StringPrefixSize + len(za0001) + msgp.StringPrefixSize + len(za0002) 348 | } 349 | } 350 | s += 8 + msgp.MapHeaderSize 351 | if z.Metrics != nil { 352 | for za0003, za0004 := range z.Metrics { 353 | _ = za0004 354 | s += msgp.StringPrefixSize + len(za0003) + msgp.Float64Size 355 | } 356 | } 357 | s += 6 + msgp.Int32Size 358 | return 359 | } 360 | 361 | // DecodeMsg implements msgp.Decodable 362 | func (z *ddTrace) DecodeMsg(dc *msgp.Reader) (err error) { 363 | var zb0002 uint32 364 | zb0002, err = dc.ReadArrayHeader() 365 | if err != nil { 366 | return 367 | } 368 | if cap((*z)) >= int(zb0002) { 369 | (*z) = (*z)[:zb0002] 370 | } else { 371 | (*z) = make(ddTrace, zb0002) 372 | } 373 | for zb0001 := range *z { 374 | err = (*z)[zb0001].DecodeMsg(dc) 375 | if err != nil { 376 | return 377 | } 378 | } 379 | return 380 | } 381 | 382 | // EncodeMsg implements msgp.Encodable 383 | func (z ddTrace) EncodeMsg(en *msgp.Writer) (err error) { 384 | err = en.WriteArrayHeader(uint32(len(z))) 385 | if err != nil { 386 | return 387 | } 388 | for zb0003 := range z { 389 | err = z[zb0003].EncodeMsg(en) 390 | if err != nil { 391 | return 392 | } 393 | } 394 | return 395 | } 396 | 397 | // Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message 398 | func (z ddTrace) Msgsize() (s int) { 399 | s = msgp.ArrayHeaderSize 400 | for zb0003 := range z { 401 | s += z[zb0003].Msgsize() 402 | } 403 | return 404 | } 405 | -------------------------------------------------------------------------------- /msgpack_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "bytes" 10 | "reflect" 11 | "strconv" 12 | "sync/atomic" 13 | "testing" 14 | 15 | "github.com/tinylib/msgp/msgp" 16 | ) 17 | 18 | func TestPayload(t *testing.T) { 19 | t.Run("partitioning", func(t *testing.T) { 20 | p := newPayload() 21 | prevSize := 0 22 | for i, tt := range []struct { 23 | span *ddSpan // span to add 24 | traceLengths map[uint64]uint64 // maps traces to their expected length 25 | }{ 26 | { 27 | span: makeSpan(100), 28 | traceLengths: map[uint64]uint64{100: 1}, 29 | }, 30 | { 31 | span: makeSpan(100), 32 | traceLengths: map[uint64]uint64{100: 2}, 33 | }, 34 | { 35 | span: makeSpan(100), 36 | traceLengths: map[uint64]uint64{100: 3}, 37 | }, 38 | { 39 | span: makeSpan(250), 40 | traceLengths: map[uint64]uint64{100: 3, 250: 1}, 41 | }, 42 | { 43 | span: makeSpan(325), 44 | traceLengths: map[uint64]uint64{100: 3, 250: 1, 325: 1}, 45 | }, 46 | { 47 | span: makeSpan(250), 48 | traceLengths: map[uint64]uint64{100: 3, 250: 2, 325: 1}, 49 | }, 50 | } { 51 | err := p.add(tt.span) 52 | if err != nil { 53 | t.Fatalf("%d: %v", i, err) 54 | } 55 | for id, total := range tt.traceLengths { 56 | if got := p.traces[id].count; got != total { 57 | t.Fatalf("%d: count mismatch at trace ID %d, expected %d, got %d", i, id, total, got) 58 | } 59 | } 60 | if p.size() <= prevSize { 61 | t.Fatalf("%d: expected a size above %d, got %d", i, prevSize, p.size()) 62 | } 63 | prevSize = p.size() 64 | } 65 | }) 66 | 67 | t.Run("size", func(t *testing.T) { 68 | p := newPayload() 69 | if p.size() != 0 { 70 | t.Fatal("wanted 0") 71 | } 72 | fillPayload(t, p) 73 | total := arrayHeaderSize(uint64(len(testPayload))) 74 | for _, tr := range p.traces { 75 | total += tr.size() 76 | } 77 | if total != p.size() { 78 | t.Fatal("size is off") 79 | } 80 | }) 81 | 82 | t.Run("decode", func(t *testing.T) { 83 | p := newPayload() 84 | // run the test twice to test reset 85 | for i := 0; i < 1; i++ { 86 | p.reset() 87 | fillPayload(t, p) 88 | buf := p.buffer() 89 | var got ddPayload 90 | err := msgp.Decode(buf, &got) 91 | if err != nil { 92 | t.Fatal(err) 93 | } 94 | // use two loops to compare because the element order might differ 95 | for _, trc := range testPayload { 96 | var found bool 97 | for _, trc2 := range got { 98 | if reflect.DeepEqual(trc, trc2) { 99 | found = true 100 | break 101 | } 102 | } 103 | if !found { 104 | t.Fatal("integrity error") 105 | } 106 | } 107 | } 108 | }) 109 | } 110 | 111 | func TestPackedSpans(t *testing.T) { 112 | t.Run("integrity", func(t *testing.T) { 113 | // whatever we push into the packedSpans should allow us to read the same content 114 | // as would have been encoded by the encoder. 115 | ss := new(packedSpans) 116 | buf := new(bytes.Buffer) 117 | for _, n := range []int{10, 1 << 10, 1 << 17} { 118 | t.Run(strconv.Itoa(n), func(t *testing.T) { 119 | ss.reset() 120 | spanList := makeTrace(n) 121 | for _, span := range spanList { 122 | if err := ss.add(&span); err != nil { 123 | t.Fatal(err) 124 | } 125 | } 126 | buf.Reset() 127 | err := msgp.Encode(buf, spanList) 128 | if err != nil { 129 | t.Fatal(err) 130 | } 131 | if ss.count != uint64(n) { 132 | t.Fatalf("count mismatch: expected %d, got %d", ss.count, n) 133 | } 134 | got := ss.bytes() 135 | if len(got) == 0 { 136 | t.Fatal("0 bytes") 137 | } 138 | if !bytes.Equal(buf.Bytes(), got) { 139 | t.Fatalf("content mismatch") 140 | } 141 | }) 142 | } 143 | }) 144 | 145 | t.Run("size", func(t *testing.T) { 146 | ss := new(packedSpans) 147 | if ss.size() != 0 { 148 | t.Fatalf("expected 0, got %d", ss.size()) 149 | } 150 | if err := ss.add(&ddSpan{SpanID: 1}); err != nil { 151 | t.Fatal(err) 152 | } 153 | if ss.size() <= 0 { 154 | t.Fatal("got 0") 155 | } 156 | }) 157 | 158 | t.Run("decode", func(t *testing.T) { 159 | // ensure that whatever we push into the span slice can be decoded by the decoder. 160 | ss := new(packedSpans) 161 | for _, n := range []int{10, 1 << 10} { 162 | t.Run(strconv.Itoa(n), func(t *testing.T) { 163 | ss.reset() 164 | for i := 0; i < n; i++ { 165 | if err := ss.add(&ddSpan{SpanID: uint64(i)}); err != nil { 166 | t.Fatal(err) 167 | } 168 | } 169 | var got ddTrace 170 | err := msgp.Decode(bytes.NewReader(ss.bytes()), &got) 171 | if err != nil { 172 | t.Fatal(err) 173 | } 174 | }) 175 | } 176 | }) 177 | } 178 | 179 | // makeTrace returns a ddTrace of size n. 180 | func makeTrace(n int) ddTrace { 181 | ddt := make(ddTrace, n) 182 | for i := 0; i < n; i++ { 183 | span := ddSpan{SpanID: uint64(i)} 184 | ddt[i] = span 185 | } 186 | return ddt 187 | } 188 | 189 | // idSeed is the starting number from which the generated span IDs are incremented. 190 | var idSeed uint64 = 123 191 | 192 | // makeSpan returns a new span having id as the trace ID. 193 | func makeSpan(id uint64) *ddSpan { 194 | atomic.AddUint64(&idSeed, 1) 195 | return &ddSpan{TraceID: id, SpanID: idSeed} 196 | } 197 | 198 | // testPayload returns a payload used for testing. 199 | var testPayload = ddPayload{ 200 | ddTrace{*makeSpan(1), *makeSpan(1), *makeSpan(1)}, 201 | ddTrace{*makeSpan(2), *makeSpan(2)}, 202 | ddTrace{*makeSpan(3), *makeSpan(3), *makeSpan(3), *makeSpan(3)}, 203 | } 204 | 205 | // fillPayload adds the traces from testPayload to payload. 206 | func fillPayload(t *testing.T, p *payload) { 207 | for _, spans := range testPayload { 208 | for _, span := range spans { 209 | if err := p.add(&span); err != nil { 210 | t.Fatal(err) 211 | } 212 | } 213 | } 214 | } 215 | 216 | func BenchmarkThroughput(b *testing.B) { 217 | p := newPayload() 218 | b.SetBytes(int64(flushThreshold)) 219 | b.ReportAllocs() 220 | b.ResetTimer() 221 | for i := 0; i < b.N; i++ { 222 | p.reset() 223 | for p.size() < flushThreshold { 224 | if err := p.add(spanPairs["tags"].dd); err != nil { 225 | b.Fatal(err) 226 | } 227 | } 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /sampler.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "encoding/json" 10 | "io" 11 | "math" 12 | "sync" 13 | 14 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 15 | ) 16 | 17 | // constants used for the Knuth hashing, same as agent. 18 | const knuthFactor = uint64(1111111111111111111) 19 | 20 | // sampledByRate verifies if the number n should be sampled at the specified 21 | // rate. 22 | func sampledByRate(n uint64, rate float64) bool { 23 | if rate < 1 { 24 | return n*knuthFactor < uint64(rate*math.MaxUint64) 25 | } 26 | return true 27 | } 28 | 29 | // prioritySampler holds a set of per-service sampling rates and applies 30 | // them to spans. 31 | type prioritySampler struct { 32 | mu sync.RWMutex 33 | rates map[string]float64 34 | defaultRate float64 35 | } 36 | 37 | func newPrioritySampler() *prioritySampler { 38 | return &prioritySampler{ 39 | rates: make(map[string]float64), 40 | defaultRate: 1., 41 | } 42 | } 43 | 44 | // readRatesJSON will try to read the rates as JSON from the given io.ReadCloser. 45 | func (ps *prioritySampler) readRatesJSON(rc io.ReadCloser) error { 46 | var payload struct { 47 | Rates map[string]float64 `json:"rate_by_service"` 48 | } 49 | if err := json.NewDecoder(rc).Decode(&payload); err != nil { 50 | return err 51 | } 52 | rc.Close() 53 | const defaultRateKey = "service:,env:" 54 | ps.mu.Lock() 55 | defer ps.mu.Unlock() 56 | ps.rates = payload.Rates 57 | if v, ok := ps.rates[defaultRateKey]; ok { 58 | ps.defaultRate = v 59 | delete(ps.rates, defaultRateKey) 60 | } 61 | return nil 62 | } 63 | 64 | // getRate returns the sampling rate to be used for the given span. 65 | func (ps *prioritySampler) getRate(spn *ddSpan) float64 { 66 | key := "service:" + spn.Service + ",env:" + spn.Meta[ext.Environment] 67 | ps.mu.RLock() 68 | defer ps.mu.RUnlock() 69 | if rate, ok := ps.rates[key]; ok { 70 | return rate 71 | } 72 | return ps.defaultRate 73 | } 74 | 75 | // applyPriority applies sampling priority to the given ddSpan. 76 | func (ps *prioritySampler) applyPriority(spn *ddSpan) { 77 | rate := ps.getRate(spn) 78 | if sampledByRate(spn.TraceID, rate) { 79 | spn.Metrics[keySamplingPriority] = ext.PriorityAutoKeep 80 | } else { 81 | spn.Metrics[keySamplingPriority] = ext.PriorityAutoReject 82 | } 83 | spn.Metrics[keySamplingPriorityRate] = rate 84 | } 85 | -------------------------------------------------------------------------------- /sampler_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "io/ioutil" 10 | "math" 11 | "strings" 12 | "sync" 13 | "testing" 14 | 15 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 16 | 17 | "github.com/stretchr/testify/assert" 18 | ) 19 | 20 | func TestPrioritySampler(t *testing.T) { 21 | // create a new span with given service/env 22 | mkSpan := func(svc, env string) *ddSpan { 23 | s := &ddSpan{Service: svc, Meta: map[string]string{}} 24 | if env != "" { 25 | s.Meta["env"] = env 26 | } 27 | return s 28 | } 29 | 30 | t.Run("mkspan", func(t *testing.T) { 31 | assert := assert.New(t) 32 | s := mkSpan("my-service", "my-env") 33 | assert.Equal("my-service", s.Service) 34 | assert.Equal("my-env", s.Meta[ext.Environment]) 35 | 36 | s = mkSpan("my-service2", "") 37 | assert.Equal("my-service2", s.Service) 38 | _, ok := s.Meta[ext.Environment] 39 | assert.False(ok) 40 | }) 41 | 42 | t.Run("ops", func(t *testing.T) { 43 | ps := newPrioritySampler() 44 | assert := assert.New(t) 45 | 46 | type key struct{ service, env string } 47 | for _, tt := range []struct { 48 | in string 49 | out map[key]float64 50 | }{ 51 | { 52 | in: `{}`, 53 | out: map[key]float64{ 54 | key{"some-service", ""}: 1, 55 | key{"obfuscate.http", "none"}: 1, 56 | }, 57 | }, 58 | { 59 | in: `{ 60 | "rate_by_service":{ 61 | "service:,env:":0.8, 62 | "service:obfuscate.http,env:":0.9, 63 | "service:obfuscate.http,env:none":0.9 64 | } 65 | }`, 66 | out: map[key]float64{ 67 | key{"obfuscate.http", ""}: 0.9, 68 | key{"obfuscate.http", "none"}: 0.9, 69 | key{"obfuscate.http", "other"}: 0.8, 70 | key{"some-service", ""}: 0.8, 71 | }, 72 | }, 73 | { 74 | in: `{ 75 | "rate_by_service":{ 76 | "service:my-service,env:":0.2, 77 | "service:my-service,env:none":0.2 78 | } 79 | }`, 80 | out: map[key]float64{ 81 | key{"my-service", ""}: 0.2, 82 | key{"my-service", "none"}: 0.2, 83 | key{"obfuscate.http", ""}: 0.8, 84 | key{"obfuscate.http", "none"}: 0.8, 85 | key{"obfuscate.http", "other"}: 0.8, 86 | key{"some-service", ""}: 0.8, 87 | }, 88 | }, 89 | } { 90 | assert.NoError(ps.readRatesJSON(ioutil.NopCloser(strings.NewReader(tt.in)))) 91 | for k, v := range tt.out { 92 | assert.Equal(v, ps.getRate(mkSpan(k.service, k.env)), k) 93 | } 94 | } 95 | }) 96 | 97 | t.Run("race", func(t *testing.T) { 98 | ps := newPrioritySampler() 99 | assert := assert.New(t) 100 | 101 | var wg sync.WaitGroup 102 | 103 | wg.Add(1) 104 | go func() { 105 | defer wg.Done() 106 | for i := 0; i < 500; i++ { 107 | assert.NoError(ps.readRatesJSON( 108 | ioutil.NopCloser(strings.NewReader( 109 | `{ 110 | "rate_by_service":{ 111 | "service:,env:":0.8, 112 | "service:obfuscate.http,env:none":0.9 113 | } 114 | }`, 115 | )), 116 | )) 117 | } 118 | }() 119 | 120 | wg.Add(1) 121 | go func() { 122 | defer wg.Done() 123 | for i := 0; i < 500; i++ { 124 | ps.getRate(mkSpan("obfuscate.http", "none")) 125 | ps.getRate(mkSpan("other.service", "none")) 126 | } 127 | }() 128 | 129 | wg.Wait() 130 | }) 131 | 132 | t.Run("apply", func(t *testing.T) { 133 | ps := newPrioritySampler() 134 | assert := assert.New(t) 135 | assert.NoError(ps.readRatesJSON( 136 | ioutil.NopCloser(strings.NewReader( 137 | `{ 138 | "rate_by_service":{ 139 | "service:obfuscate.http,env:":0.5, 140 | "service:obfuscate.http,env:none":0.5 141 | } 142 | }`, 143 | )), 144 | )) 145 | 146 | testSpan1 := &ddSpan{ 147 | Name: "http.request", 148 | Metrics: map[string]float64{}, 149 | } 150 | testSpan1.Service = "obfuscate.http" 151 | testSpan1.TraceID = math.MaxUint64 - (math.MaxUint64 / 4) 152 | 153 | ps.applyPriority(testSpan1) 154 | assert.EqualValues(ext.PriorityAutoKeep, testSpan1.Metrics[keySamplingPriority]) 155 | assert.EqualValues(0.5, testSpan1.Metrics[keySamplingPriorityRate]) 156 | 157 | testSpan1.TraceID = math.MaxUint64 - (math.MaxUint64 / 3) 158 | ps.applyPriority(testSpan1) 159 | assert.EqualValues(ext.PriorityAutoReject, testSpan1.Metrics[keySamplingPriority]) 160 | assert.EqualValues(0.5, testSpan1.Metrics[keySamplingPriorityRate]) 161 | 162 | testSpan1.Service = "other-service" 163 | testSpan1.TraceID = 1 164 | assert.EqualValues(ext.PriorityAutoReject, testSpan1.Metrics[keySamplingPriority]) 165 | assert.EqualValues(0.5, testSpan1.Metrics[keySamplingPriorityRate]) 166 | }) 167 | } 168 | -------------------------------------------------------------------------------- /span.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "encoding/binary" 10 | "fmt" 11 | "net/http" 12 | "strconv" 13 | 14 | "go.opencensus.io/trace" 15 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 16 | ) 17 | 18 | // statusCodes maps (*trace.SpanData).Status.Code to their message and http status code. See: 19 | // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto. 20 | var statusCodes = map[int32]codeDetails{ 21 | trace.StatusCodeOK: {message: "OK", status: http.StatusOK}, 22 | trace.StatusCodeCancelled: {message: "CANCELLED", status: 499}, 23 | trace.StatusCodeUnknown: {message: "UNKNOWN", status: http.StatusInternalServerError}, 24 | trace.StatusCodeInvalidArgument: {message: "INVALID_ARGUMENT", status: http.StatusBadRequest}, 25 | trace.StatusCodeDeadlineExceeded: {message: "DEADLINE_EXCEEDED", status: http.StatusGatewayTimeout}, 26 | trace.StatusCodeNotFound: {message: "NOT_FOUND", status: http.StatusNotFound}, 27 | trace.StatusCodeAlreadyExists: {message: "ALREADY_EXISTS", status: http.StatusConflict}, 28 | trace.StatusCodePermissionDenied: {message: "PERMISSION_DENIED", status: http.StatusForbidden}, 29 | trace.StatusCodeResourceExhausted: {message: "RESOURCE_EXHAUSTED", status: http.StatusTooManyRequests}, 30 | trace.StatusCodeFailedPrecondition: {message: "FAILED_PRECONDITION", status: http.StatusBadRequest}, 31 | trace.StatusCodeAborted: {message: "ABORTED", status: http.StatusConflict}, 32 | trace.StatusCodeOutOfRange: {message: "OUT_OF_RANGE", status: http.StatusBadRequest}, 33 | trace.StatusCodeUnimplemented: {message: "UNIMPLEMENTED", status: http.StatusNotImplemented}, 34 | trace.StatusCodeInternal: {message: "INTERNAL", status: http.StatusInternalServerError}, 35 | trace.StatusCodeUnavailable: {message: "UNAVAILABLE", status: http.StatusServiceUnavailable}, 36 | trace.StatusCodeDataLoss: {message: "DATA_LOSS", status: http.StatusNotImplemented}, 37 | trace.StatusCodeUnauthenticated: {message: "UNAUTHENTICATED", status: http.StatusUnauthorized}, 38 | } 39 | 40 | // codeDetails specifies information about a trace status code. 41 | type codeDetails struct { 42 | message string // status message 43 | status int // corresponding HTTP status code 44 | } 45 | 46 | // convertSpan takes an OpenCensus span and returns a Datadog span. 47 | func (e *traceExporter) convertSpan(s *trace.SpanData) *ddSpan { 48 | startNano := s.StartTime.UnixNano() 49 | span := &ddSpan{ 50 | TraceID: binary.BigEndian.Uint64(s.SpanContext.TraceID[8:]), 51 | SpanID: binary.BigEndian.Uint64(s.SpanContext.SpanID[:]), 52 | Name: "opencensus", 53 | Resource: s.Name, 54 | Service: e.opts.Service, 55 | Start: startNano, 56 | Duration: s.EndTime.UnixNano() - startNano, 57 | Metrics: map[string]float64{}, 58 | Meta: map[string]string{}, 59 | } 60 | if s.ParentSpanID != (trace.SpanID{}) { 61 | span.ParentID = binary.BigEndian.Uint64(s.ParentSpanID[:]) 62 | } 63 | 64 | code, ok := statusCodes[s.Status.Code] 65 | if !ok { 66 | code = codeDetails{ 67 | message: "ERR_CODE_" + strconv.FormatInt(int64(s.Status.Code), 10), 68 | status: http.StatusInternalServerError, 69 | } 70 | } 71 | 72 | switch s.SpanKind { 73 | case trace.SpanKindClient: 74 | span.Type = "client" 75 | if code.status/100 == 4 { 76 | span.Error = 1 77 | } 78 | case trace.SpanKindServer: 79 | span.Type = "server" 80 | if code.status/100 == 5 { 81 | span.Error = 1 82 | } 83 | default: 84 | if code.status/100 == 4 || code.status/100 == 5 { 85 | span.Error = 1 86 | } 87 | } 88 | 89 | if span.Error == 1 { 90 | span.Meta[ext.ErrorType] = code.message 91 | if msg := s.Status.Message; msg != "" { 92 | span.Meta[ext.ErrorMsg] = msg 93 | } 94 | } 95 | 96 | span.Meta[keyStatusCode] = strconv.Itoa(int(s.Status.Code)) 97 | span.Meta[keyStatus] = code.message 98 | if msg := s.Status.Message; msg != "" { 99 | span.Meta[keyStatusDescription] = msg 100 | } 101 | 102 | for key, val := range e.opts.GlobalTags { 103 | setTag(span, key, val) 104 | } 105 | for key, val := range s.Attributes { 106 | setTag(span, key, val) 107 | } 108 | return span 109 | } 110 | 111 | const ( 112 | keySamplingPriority = "_sampling_priority_v1" 113 | keyStatusDescription = "opencensus.status_description" 114 | keyStatusCode = "opencensus.status_code" 115 | keyStatus = "opencensus.status" 116 | keySpanName = "span.name" 117 | keySamplingPriorityRate = "_sampling_priority_rate_v1" 118 | ) 119 | 120 | func setTag(s *ddSpan, key string, val interface{}) { 121 | if key == ext.Error { 122 | setError(s, val) 123 | return 124 | } 125 | switch v := val.(type) { 126 | case string: 127 | setStringTag(s, key, v) 128 | case bool: 129 | if v { 130 | setStringTag(s, key, "true") 131 | } else { 132 | setStringTag(s, key, "false") 133 | } 134 | case float64: 135 | setMetric(s, key, v) 136 | case int64: 137 | setMetric(s, key, float64(v)) 138 | default: 139 | // should never happen according to docs, nevertheless 140 | // we should account for this to avoid exceptions 141 | setStringTag(s, key, fmt.Sprintf("%v", v)) 142 | } 143 | } 144 | 145 | func setMetric(s *ddSpan, key string, v float64) { 146 | switch key { 147 | case ext.SamplingPriority: 148 | s.Metrics[keySamplingPriority] = v 149 | default: 150 | s.Metrics[key] = v 151 | } 152 | } 153 | 154 | func setStringTag(s *ddSpan, key, v string) { 155 | switch key { 156 | case ext.ServiceName: 157 | s.Service = v 158 | case ext.ResourceName: 159 | s.Resource = v 160 | case ext.SpanType: 161 | s.Type = v 162 | case ext.AnalyticsEvent: 163 | if v != "false" { 164 | setMetric(s, ext.EventSampleRate, 1) 165 | } else { 166 | setMetric(s, ext.EventSampleRate, 0) 167 | } 168 | case keySpanName: 169 | s.Name = v 170 | default: 171 | s.Meta[key] = v 172 | } 173 | } 174 | 175 | func setError(s *ddSpan, val interface{}) { 176 | switch v := val.(type) { 177 | case string: 178 | s.Error = 1 179 | s.Meta[ext.ErrorMsg] = v 180 | case bool: 181 | if v { 182 | s.Error = 1 183 | } else { 184 | s.Error = 0 185 | } 186 | case int64: 187 | if v > 0 { 188 | s.Error = 1 189 | } else { 190 | s.Error = 0 191 | } 192 | case nil: 193 | s.Error = 0 194 | default: 195 | s.Error = 1 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /span_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "reflect" 10 | "testing" 11 | "time" 12 | 13 | "go.opencensus.io/trace" 14 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 15 | ) 16 | 17 | var ( 18 | testStartTime = time.Now() 19 | testEndTime = testStartTime.Add(10 * time.Second) 20 | ) 21 | 22 | // spanPairs holds a set of trace.SpanData and its corresponding conversion to a ddSpan. 23 | var spanPairs = map[string]struct { 24 | oc *trace.SpanData 25 | dd *ddSpan 26 | }{ 27 | "root": { 28 | oc: &trace.SpanData{ 29 | SpanContext: trace.SpanContext{ 30 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 31 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 32 | TraceOptions: 1, 33 | }, 34 | SpanKind: trace.SpanKindClient, 35 | Name: "/a/b", 36 | StartTime: testStartTime, 37 | EndTime: testEndTime, 38 | Attributes: map[string]interface{}{ 39 | "str": "abc", 40 | "bool": true, 41 | "int64": int64(1), 42 | }, 43 | Status: trace.Status{ 44 | Code: 0, 45 | Message: "status-msg", 46 | }, 47 | }, 48 | dd: &ddSpan{ 49 | TraceID: 651345242494996240, 50 | SpanID: 72623859790382856, 51 | Type: "client", 52 | Name: "opencensus", 53 | Resource: "/a/b", 54 | Start: testStartTime.UnixNano(), 55 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 56 | Metrics: map[string]float64{"int64": 1}, 57 | Service: "my-service", 58 | Meta: map[string]string{ 59 | "bool": "true", 60 | "str": "abc", 61 | keyStatus: "OK", 62 | keyStatusCode: "0", 63 | keyStatusDescription: "status-msg", 64 | }, 65 | }, 66 | }, 67 | "child": { 68 | oc: &trace.SpanData{ 69 | SpanContext: trace.SpanContext{ 70 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 71 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 72 | TraceOptions: 1, 73 | }, 74 | ParentSpanID: trace.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}), 75 | SpanKind: trace.SpanKindClient, 76 | Name: "/a/b", 77 | StartTime: testStartTime, 78 | EndTime: testEndTime, 79 | Attributes: map[string]interface{}{}, 80 | Status: trace.Status{}, 81 | }, 82 | dd: &ddSpan{ 83 | TraceID: 651345242494996240, 84 | SpanID: 72623859790382856, 85 | ParentID: 578437695752307201, 86 | Type: "client", 87 | Name: "opencensus", 88 | Resource: "/a/b", 89 | Start: testStartTime.UnixNano(), 90 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 91 | Metrics: map[string]float64{}, 92 | Service: "my-service", 93 | Meta: map[string]string{ 94 | keyStatus: "OK", 95 | keyStatusCode: "0", 96 | }, 97 | }, 98 | }, 99 | "server_error_4xx": { 100 | oc: &trace.SpanData{ 101 | SpanContext: trace.SpanContext{ 102 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 103 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 104 | TraceOptions: 1, 105 | }, 106 | SpanKind: trace.SpanKindServer, 107 | Name: "/a/b", 108 | StartTime: testStartTime, 109 | EndTime: testEndTime, 110 | Attributes: map[string]interface{}{}, 111 | Status: trace.Status{ 112 | Code: trace.StatusCodeCancelled, 113 | Message: "status-msg", 114 | }, 115 | }, 116 | dd: &ddSpan{ 117 | TraceID: 651345242494996240, 118 | SpanID: 72623859790382856, 119 | Type: "server", 120 | Name: "opencensus", 121 | Resource: "/a/b", 122 | Start: testStartTime.UnixNano(), 123 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 124 | Metrics: map[string]float64{}, 125 | Error: 0, 126 | Service: "my-service", 127 | Meta: map[string]string{ 128 | keyStatus: "CANCELLED", 129 | keyStatusCode: "1", 130 | keyStatusDescription: "status-msg", 131 | }, 132 | }, 133 | }, 134 | "server_error_5xx": { 135 | oc: &trace.SpanData{ 136 | SpanContext: trace.SpanContext{ 137 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 138 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 139 | TraceOptions: 1, 140 | }, 141 | SpanKind: trace.SpanKindServer, 142 | Name: "/a/b", 143 | StartTime: testStartTime, 144 | EndTime: testEndTime, 145 | Attributes: map[string]interface{}{}, 146 | Status: trace.Status{ 147 | Code: trace.StatusCodeInternal, 148 | Message: "status-msg", 149 | }, 150 | }, 151 | dd: &ddSpan{ 152 | TraceID: 651345242494996240, 153 | SpanID: 72623859790382856, 154 | Type: "server", 155 | Name: "opencensus", 156 | Resource: "/a/b", 157 | Start: testStartTime.UnixNano(), 158 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 159 | Metrics: map[string]float64{}, 160 | Error: 1, 161 | Service: "my-service", 162 | Meta: map[string]string{ 163 | ext.ErrorMsg: "status-msg", 164 | ext.ErrorType: "INTERNAL", 165 | keyStatus: "INTERNAL", 166 | keyStatusCode: "13", 167 | keyStatusDescription: "status-msg", 168 | }, 169 | }, 170 | }, 171 | "client_error_4xx": { 172 | oc: &trace.SpanData{ 173 | SpanContext: trace.SpanContext{ 174 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 175 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 176 | TraceOptions: 1, 177 | }, 178 | SpanKind: trace.SpanKindClient, 179 | Name: "/a/b", 180 | StartTime: testStartTime, 181 | EndTime: testEndTime, 182 | Attributes: map[string]interface{}{}, 183 | Status: trace.Status{ 184 | Code: trace.StatusCodeCancelled, 185 | Message: "status-msg", 186 | }, 187 | }, 188 | dd: &ddSpan{ 189 | TraceID: 651345242494996240, 190 | SpanID: 72623859790382856, 191 | Type: "client", 192 | Name: "opencensus", 193 | Resource: "/a/b", 194 | Start: testStartTime.UnixNano(), 195 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 196 | Metrics: map[string]float64{}, 197 | Error: 1, 198 | Service: "my-service", 199 | Meta: map[string]string{ 200 | ext.ErrorMsg: "status-msg", 201 | ext.ErrorType: "CANCELLED", 202 | keyStatus: "CANCELLED", 203 | keyStatusCode: "1", 204 | keyStatusDescription: "status-msg", 205 | }, 206 | }, 207 | }, 208 | "client_error_5xx": { 209 | oc: &trace.SpanData{ 210 | SpanContext: trace.SpanContext{ 211 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 212 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 213 | TraceOptions: 1, 214 | }, 215 | SpanKind: trace.SpanKindClient, 216 | Name: "/a/b", 217 | StartTime: testStartTime, 218 | EndTime: testEndTime, 219 | Attributes: map[string]interface{}{}, 220 | Status: trace.Status{ 221 | Code: trace.StatusCodeInternal, 222 | Message: "status-msg", 223 | }, 224 | }, 225 | dd: &ddSpan{ 226 | TraceID: 651345242494996240, 227 | SpanID: 72623859790382856, 228 | Type: "client", 229 | Name: "opencensus", 230 | Resource: "/a/b", 231 | Start: testStartTime.UnixNano(), 232 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 233 | Metrics: map[string]float64{}, 234 | Error: 0, 235 | Service: "my-service", 236 | Meta: map[string]string{ 237 | keyStatus: "INTERNAL", 238 | keyStatusCode: "13", 239 | keyStatusDescription: "status-msg", 240 | }, 241 | }, 242 | }, 243 | "default_error_4xx": { 244 | oc: &trace.SpanData{ 245 | SpanContext: trace.SpanContext{ 246 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 247 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 248 | TraceOptions: 1, 249 | }, 250 | SpanKind: trace.SpanKindUnspecified, 251 | Name: "/a/b", 252 | StartTime: testStartTime, 253 | EndTime: testEndTime, 254 | Attributes: map[string]interface{}{}, 255 | Status: trace.Status{ 256 | Code: trace.StatusCodeCancelled, 257 | Message: "status-msg", 258 | }, 259 | }, 260 | dd: &ddSpan{ 261 | TraceID: 651345242494996240, 262 | SpanID: 72623859790382856, 263 | Type: "", 264 | Name: "opencensus", 265 | Resource: "/a/b", 266 | Start: testStartTime.UnixNano(), 267 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 268 | Metrics: map[string]float64{}, 269 | Error: 1, 270 | Service: "my-service", 271 | Meta: map[string]string{ 272 | ext.ErrorMsg: "status-msg", 273 | ext.ErrorType: "CANCELLED", 274 | keyStatus: "CANCELLED", 275 | keyStatusCode: "1", 276 | keyStatusDescription: "status-msg", 277 | }, 278 | }, 279 | }, 280 | "tags": { 281 | oc: &trace.SpanData{ 282 | SpanContext: trace.SpanContext{ 283 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 284 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 285 | TraceOptions: 1, 286 | }, 287 | SpanKind: trace.SpanKindServer, 288 | Name: "/a/b", 289 | StartTime: testStartTime, 290 | EndTime: testEndTime, 291 | Attributes: map[string]interface{}{ 292 | ext.Error: true, 293 | ext.ServiceName: "other-service", 294 | ext.ResourceName: "other-resource", 295 | ext.SpanType: "other-type", 296 | ext.SamplingPriority: int64(ext.PriorityUserReject), 297 | }, 298 | Status: trace.Status{}, 299 | }, 300 | dd: &ddSpan{ 301 | TraceID: 651345242494996240, 302 | SpanID: 72623859790382856, 303 | Type: "other-type", 304 | Name: "opencensus", 305 | Resource: "other-resource", 306 | Start: testStartTime.UnixNano(), 307 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 308 | Metrics: map[string]float64{ 309 | keySamplingPriority: ext.PriorityUserReject, 310 | }, 311 | Service: "other-service", 312 | Error: 1, 313 | Meta: map[string]string{ 314 | keyStatus: "OK", 315 | keyStatusCode: "0", 316 | }, 317 | }, 318 | }, 319 | "slash": { 320 | oc: &trace.SpanData{ 321 | SpanContext: trace.SpanContext{ 322 | TraceID: trace.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), 323 | SpanID: trace.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), 324 | TraceOptions: 1, 325 | }, 326 | SpanKind: trace.SpanKindClient, 327 | Name: "/", 328 | StartTime: testStartTime, 329 | EndTime: testEndTime, 330 | }, 331 | dd: &ddSpan{ 332 | TraceID: 651345242494996240, 333 | SpanID: 72623859790382856, 334 | Type: "client", 335 | Name: "opencensus", 336 | Resource: "/", 337 | Start: testStartTime.UnixNano(), 338 | Duration: testEndTime.UnixNano() - testStartTime.UnixNano(), 339 | Service: "my-service", 340 | Meta: map[string]string{ 341 | keyStatus: "OK", 342 | keyStatusCode: "0", 343 | }, 344 | Metrics: map[string]float64{}, 345 | }, 346 | }, 347 | } 348 | 349 | func TestConvertSpan(t *testing.T) { 350 | service := "my-service" 351 | e := newTraceExporter(Options{Service: service}) 352 | defer e.stop() 353 | 354 | for name, tt := range spanPairs { 355 | t.Run(name, func(t *testing.T) { 356 | if got := e.convertSpan(tt.oc); !reflect.DeepEqual(got, tt.dd) { 357 | t.Fatalf("\nGot:\n%#v\n\nWant:\n%#v\n", got, tt.dd) 358 | } 359 | }) 360 | } 361 | } 362 | 363 | func TestGlobalTags(t *testing.T) { 364 | e := newTraceExporter(Options{ 365 | Service: "my-service", 366 | GlobalTags: map[string]interface{}{"key1": "value1"}, 367 | }) 368 | defer e.stop() 369 | 370 | got := e.convertSpan(spanPairs["tags"].oc) 371 | if got.Meta["key1"] != "value1" { 372 | t.Fatal("global tag not set") 373 | } 374 | } 375 | 376 | func TestSetError(t *testing.T) { 377 | for i, tt := range [...]struct { 378 | val interface{} // error value 379 | err int32 // expected error field value 380 | msg string // expected error message tag value 381 | }{ 382 | {val: "error", err: 1, msg: "error"}, 383 | {val: true, err: 1}, 384 | {val: false}, 385 | {val: int64(12), err: 1}, 386 | {val: int64(-1)}, 387 | {val: int64(0)}, 388 | {val: nil}, 389 | {val: float32(0), err: 1}, 390 | } { 391 | span := &ddSpan{Meta: map[string]string{}} 392 | setError(span, tt.val) 393 | if span.Error != tt.err { 394 | t.Fatalf("%d: span.Error mismatch, wanted %d, got %d", i, tt.err, span.Error) 395 | } 396 | if tt.msg != "" { 397 | if got, ok := span.Meta[ext.ErrorMsg]; !ok || got != tt.msg { 398 | t.Fatalf("%d: span.Meta[ext.ErrorMsg] mismatch, wanted %q, got %q", i, tt.msg, got) 399 | } 400 | } 401 | } 402 | } 403 | 404 | func TestSetStringTag(t *testing.T) { 405 | span := &ddSpan{Meta: map[string]string{}} 406 | eq := equalFunc(t) 407 | 408 | setStringTag(span, ext.ServiceName, "service") 409 | eq(span.Service, "service") 410 | 411 | setStringTag(span, ext.ResourceName, "resource") 412 | eq(span.Resource, "resource") 413 | 414 | setStringTag(span, ext.SpanType, "type") 415 | eq(span.Type, "type") 416 | 417 | setStringTag(span, "key", "val") 418 | eq(span.Meta["key"], "val") 419 | } 420 | 421 | func TestSetTag(t *testing.T) { 422 | testSpan := func() *ddSpan { 423 | return &ddSpan{ 424 | Meta: map[string]string{}, 425 | Metrics: map[string]float64{}, 426 | } 427 | } 428 | 429 | t.Run("error", func(t *testing.T) { 430 | span := testSpan() 431 | setTag(span, ext.Error, true) 432 | equalFunc(t)(span.Error, int32(1)) 433 | }) 434 | 435 | t.Run("string", func(t *testing.T) { 436 | eq := equalFunc(t) 437 | span := testSpan() 438 | setTag(span, ext.ResourceName, "resource") 439 | eq(span.Resource, "resource") 440 | setTag(span, "key", "value") 441 | eq(span.Meta["key"], "value") 442 | }) 443 | 444 | t.Run("bool", func(t *testing.T) { 445 | eq := equalFunc(t) 446 | span := testSpan() 447 | setTag(span, "key", true) 448 | eq(span.Meta["key"], "true") 449 | setTag(span, "key2", false) 450 | eq(span.Meta["key2"], "false") 451 | setTag(span, ext.AnalyticsEvent, true) 452 | eq(span.Metrics[ext.EventSampleRate], 1.) 453 | setTag(span, ext.AnalyticsEvent, false) 454 | eq(span.Metrics[ext.EventSampleRate], 0.) 455 | }) 456 | 457 | t.Run("int64", func(t *testing.T) { 458 | eq := equalFunc(t) 459 | span := testSpan() 460 | setTag(span, "key", int64(12)) 461 | eq(span.Metrics["key"], float64(12)) 462 | setTag(span, ext.SamplingPriority, int64(1)) 463 | eq(span.Metrics[keySamplingPriority], float64(1)) 464 | }) 465 | 466 | t.Run("float64", func(t *testing.T) { 467 | eq := equalFunc(t) 468 | span := testSpan() 469 | setTag(span, "key", float64(12)) 470 | eq(span.Metrics["key"], float64(12)) 471 | setTag(span, ext.SamplingPriority, float64(1)) 472 | eq(span.Metrics[keySamplingPriority], float64(1)) 473 | setTag(span, ext.EventSampleRate, float64(0.4)) 474 | eq(span.Metrics[ext.EventSampleRate], float64(0.4)) 475 | }) 476 | 477 | t.Run("default", func(t *testing.T) { 478 | span := testSpan() 479 | setTag(span, "key", 1) 480 | equalFunc(t)(span.Meta["key"], "1") 481 | }) 482 | } 483 | 484 | // equalFunc returns a function that tests the equality of two values. It fails 485 | // if there is a type mismatch. 486 | func equalFunc(t *testing.T) func(got, want interface{}) { 487 | return func(a, b interface{}) { 488 | t.Helper() 489 | if !reflect.DeepEqual(a, b) { 490 | t.Fatalf("mismatch: got %v, wanted %v", a, b) 491 | } 492 | } 493 | } 494 | -------------------------------------------------------------------------------- /stats.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "fmt" 10 | "github.com/DataDog/datadog-go/statsd" 11 | "go.opencensus.io/stats/view" 12 | "sync" 13 | ) 14 | 15 | const ( 16 | // DefaultStatsAddrUDP specifies the default protocol (UDP) and address 17 | // for the DogStatsD service. 18 | DefaultStatsAddrUDP = "localhost:8125" 19 | 20 | // DefaultStatsAddrUDS specifies the default socket address for the 21 | // DogStatsD service over UDS. Only useful for platforms supporting unix 22 | // sockets. 23 | DefaultStatsAddrUDS = "unix:///var/run/datadog/dsd.socket" 24 | ) 25 | 26 | // collector implements statsd.Client 27 | type statsExporter struct { 28 | opts Options 29 | client *statsd.Client 30 | mu sync.Mutex // mu guards viewData 31 | viewData map[string]*view.Data 32 | countData map[string]int64 33 | } 34 | 35 | func newStatsExporter(o Options) (*statsExporter, error) { 36 | endpoint := o.StatsAddr 37 | if endpoint == "" { 38 | endpoint = DefaultStatsAddrUDP 39 | } 40 | 41 | client, err := statsd.New(endpoint, o.StatsdOptions...) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | return &statsExporter{ 47 | opts: o, 48 | viewData: make(map[string]*view.Data), 49 | countData: make(map[string]int64), 50 | client: client, 51 | }, nil 52 | } 53 | 54 | func (s *statsExporter) addViewData(vd *view.Data) { 55 | sig := viewSignature(s.opts.Namespace, s.opts.TagMetricNames, vd.View) 56 | s.mu.Lock() 57 | s.viewData[sig] = vd 58 | s.mu.Unlock() 59 | 60 | var lastErr error 61 | for _, row := range vd.Rows { 62 | if err := s.submitMetric(vd.View, row, sig); err != nil { 63 | lastErr = err 64 | } 65 | } 66 | if lastErr != nil { 67 | s.opts.onError(lastErr) // Only report last error. 68 | } 69 | } 70 | 71 | func (s *statsExporter) submitMetric(v *view.View, row *view.Row, metricName string) error { 72 | var err error 73 | const rate = float64(1) 74 | client := s.client 75 | opt := s.opts 76 | tags := []string{} 77 | 78 | switch data := row.Data.(type) { 79 | case *view.CountData: 80 | // get a unique string for metric and associated tags 81 | metricID := metricRowID(row, metricName) 82 | // compute the difference of now and last collected period 83 | submitData := data.Value - s.countData[metricID] 84 | // update map with current value 85 | s.countData[metricID] = data.Value 86 | return client.Count(metricName, submitData, opt.tagMetrics(row.Tags, tags), rate) 87 | 88 | case *view.SumData: 89 | return client.Gauge(metricName, float64(data.Value), opt.tagMetrics(row.Tags, tags), rate) 90 | 91 | case *view.LastValueData: 92 | return client.Gauge(metricName, float64(data.Value), opt.tagMetrics(row.Tags, tags), rate) 93 | 94 | case *view.DistributionData: 95 | var metrics = map[string]float64{ 96 | "min": data.Min, 97 | "max": data.Max, 98 | "count": float64(data.Count), 99 | "avg": data.Mean, 100 | "squared_dev_sum": data.SumOfSquaredDev, 101 | } 102 | 103 | for name, value := range metrics { 104 | err = client.Gauge(metricName+"."+name, value, opt.tagMetrics(row.Tags, tags), rate) 105 | } 106 | if !s.opts.DisableCountPerBuckets { 107 | for x := range data.CountPerBucket { 108 | addlTags := []string{"bucket_idx:" + fmt.Sprint(x)} 109 | err = client.Gauge(metricName+".count_per_bucket", float64(data.CountPerBucket[x]), opt.tagMetrics(row.Tags, addlTags), rate) 110 | } 111 | } 112 | return err 113 | default: 114 | return fmt.Errorf("aggregation %T is not supported", v.Aggregation) 115 | } 116 | } 117 | 118 | func (s *statsExporter) stop() { 119 | if err := s.client.Close(); err != nil { 120 | s.opts.onError(err) 121 | } 122 | } 123 | 124 | func metricRowID(row *view.Row, metricName string) string{ 125 | tgs := "" 126 | for _,tag := range row.Tags{ 127 | tgs += tag.Key.Name() + ":" + tag.Value 128 | } 129 | if tgs != ""{ 130 | metricName += "|" + tgs 131 | } 132 | return metricName 133 | } 134 | -------------------------------------------------------------------------------- /stats_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadoghq.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "context" 10 | "fmt" 11 | "go.opencensus.io/stats" 12 | "io" 13 | "net" 14 | "sort" 15 | "strings" 16 | "testing" 17 | "time" 18 | 19 | "github.com/DataDog/datadog-go/statsd" 20 | 21 | "go.opencensus.io/stats/view" 22 | "go.opencensus.io/tag" 23 | ) 24 | 25 | type testStatsExporter struct{ *Exporter } 26 | 27 | func (e *testStatsExporter) view(name string) *view.View { 28 | e.statsExporter.mu.Lock() 29 | defer e.statsExporter.mu.Unlock() 30 | return e.Exporter.statsExporter.viewData[name].View 31 | } 32 | 33 | func testExporter(opts Options) (*testStatsExporter, error) { 34 | if opts.OnError == nil { 35 | opts.OnError = func(_ error) {} 36 | } 37 | e, err := NewExporter(opts) 38 | if err != nil { 39 | return nil, err 40 | } 41 | defer e.statsExporter.stop() 42 | view.RegisterExporter(e) 43 | view.SetReportingPeriod(time.Millisecond) 44 | return &testStatsExporter{e}, nil 45 | } 46 | 47 | func listenUDP(addr string) (*net.UDPConn, error) { 48 | udpAddr, err := net.ResolveUDPAddr("udp", addr) 49 | if err != nil { 50 | return nil, err 51 | } 52 | return net.ListenUDP("udp", udpAddr) 53 | } 54 | 55 | func TestAddViewData(t *testing.T) { 56 | exporter, err := testExporter(Options{Namespace: "hello", Tags: []string{"test:optionalTag"}}) 57 | if err != nil { 58 | t.Error(err) 59 | } 60 | expected := &view.Data{ 61 | View: newView(view.Count()), 62 | } 63 | exporter.statsExporter.addViewData(expected) 64 | actual := exporter.statsExporter.viewData["hello.fooCount"] 65 | if actual != expected { 66 | t.Errorf("Expected: %v, Got: %v", expected, actual) 67 | } 68 | } 69 | 70 | func TestUDPExportError(t *testing.T) { 71 | _, err := testExporter(Options{ 72 | StatsAddr: "invalid_address", 73 | }) 74 | if err == nil { 75 | t.Errorf("Expected an error") 76 | } 77 | } 78 | 79 | func TestSubmitMetricError(t *testing.T) { 80 | var expected error 81 | 82 | exporter, err := testExporter(Options{ 83 | StatsAddr: "unix:///dummy.socket", 84 | OnError: func(err error) { 85 | expected = err 86 | }, 87 | }) 88 | if err != nil { 89 | t.Error(err) 90 | } 91 | 92 | data := &view.Data{ 93 | View: newView(view.Count()), 94 | Rows: []*view.Row{ 95 | { 96 | Tags: []tag.Tag{}, 97 | Data: nil, 98 | }, 99 | }, 100 | } 101 | exporter.statsExporter.addViewData(data) 102 | 103 | if expected == nil { 104 | t.Errorf("Expected an error") 105 | } 106 | } 107 | 108 | func TestSubmitCount(t *testing.T) { 109 | conn, err := listenUDP("localhost:0") 110 | if err != nil { 111 | t.Fatal(err) 112 | } 113 | defer conn.Close() 114 | 115 | addr := conn.LocalAddr().String() 116 | 117 | client, err := statsd.NewBuffered(addr, 100) 118 | if err != nil { 119 | t.Fatal(err) 120 | } 121 | 122 | fooCount := stats.Int64("fooCount", "fooDesc", stats.UnitDimensionless) 123 | 124 | options := Options{ 125 | StatsAddr: addr, 126 | } 127 | 128 | exporter, err := testExporter(options) 129 | if err != nil { 130 | t.Fatal(err) 131 | } 132 | exporter.client = client 133 | 134 | fooCountView := &view.View{ 135 | Name: "fooCount", 136 | Description: "fooDesc", 137 | Measure: fooCount, 138 | Aggregation: view.Count(), 139 | } 140 | view.Register(fooCountView) 141 | stats.Record(context.Background(), fooCount.M(1)) 142 | 143 | buffer := make([]byte, 4096) 144 | n, err := io.ReadAtLeast(conn, buffer, 1) 145 | if err != nil { 146 | t.Fatal(err) 147 | } 148 | expectedResults := []string{ 149 | `fooCount:1|c`, 150 | `fooCount:0|c`, 151 | } 152 | result := string(buffer[:n]) 153 | 154 | results := strings.Split(result, "\n") 155 | results = results[:len(expectedResults)] 156 | for i, res := range results { 157 | if res != expectedResults[i] { 158 | t.Errorf("Got `%s`, expected `%s`", res, expectedResults[i]) 159 | } 160 | } 161 | view.Unregister(fooCountView) 162 | } 163 | 164 | func TestDistributionData(t *testing.T) { 165 | conn, err := listenUDP("localhost:0") 166 | if err != nil { 167 | t.Fatal(err) 168 | } 169 | defer conn.Close() 170 | 171 | addr := conn.LocalAddr().String() 172 | 173 | client, err := statsd.NewBuffered(addr, 100) 174 | if err != nil { 175 | t.Fatal(err) 176 | } 177 | 178 | data := &view.Data{ 179 | View: newView(view.Count()), 180 | Rows: []*view.Row{ 181 | { 182 | Tags: []tag.Tag{}, 183 | Data: &view.DistributionData{ 184 | CountPerBucket: []int64{0, 2, 3}, 185 | Min: 1, 186 | Max: 5, 187 | Mean: 3, 188 | SumOfSquaredDev: 10, 189 | Count: 15, 190 | }, 191 | }, 192 | }, 193 | } 194 | 195 | testCases := map[string]struct { 196 | Options Options 197 | ExpectedResults []string 198 | }{ 199 | "ok": { 200 | Options{ 201 | StatsAddr: addr, 202 | }, 203 | []string{ 204 | `fooCount.avg:3|g`, 205 | `fooCount.count:15|g`, 206 | `fooCount.count_per_bucket:0|g|#bucket_idx:0`, 207 | `fooCount.count_per_bucket:2|g|#bucket_idx:1`, 208 | `fooCount.count_per_bucket:3|g|#bucket_idx:2`, 209 | `fooCount.max:5|g`, 210 | `fooCount.min:1|g`, 211 | `fooCount.squared_dev_sum:10|g`, 212 | }, 213 | }, 214 | "disabled": { 215 | Options{ 216 | StatsAddr: addr, 217 | DisableCountPerBuckets: true, 218 | }, 219 | []string{ 220 | `fooCount.avg:3|g`, 221 | `fooCount.count:15|g`, 222 | `fooCount.max:5|g`, 223 | `fooCount.min:1|g`, 224 | `fooCount.squared_dev_sum:10|g`, 225 | }, 226 | }, 227 | } 228 | 229 | for name, tc := range testCases { 230 | t.Run(name, func(t *testing.T) { 231 | exporter, err := testExporter(tc.Options) 232 | if err != nil { 233 | t.Fatal(err) 234 | } 235 | exporter.client = client 236 | exporter.statsExporter.addViewData(data) 237 | 238 | buffer := make([]byte, 4096) 239 | n, err := io.ReadAtLeast(conn, buffer, 1) 240 | if err != nil { 241 | t.Fatal(err) 242 | } 243 | result := string(buffer[:n]) 244 | 245 | results := strings.Split(result, "\n") 246 | sort.Strings(results) 247 | for i, res := range results { 248 | if res != tc.ExpectedResults[i] { 249 | t.Errorf("Got `%s`, expected `%s`", res, tc.ExpectedResults[i]) 250 | } 251 | } 252 | }) 253 | } 254 | } 255 | 256 | func TestNilAggregation(t *testing.T) { 257 | exporter, err := testExporter(Options{}) 258 | if err != nil { 259 | t.Error(err) 260 | } 261 | noneAgg := &view.Aggregation{ 262 | Type: view.AggTypeNone, 263 | Buckets: []float64{1}, 264 | } 265 | v := newCustomView("fooNone", noneAgg, testTags, measureCount) 266 | row := &view.Row{ 267 | Tags: []tag.Tag{}, 268 | } 269 | actual := exporter.statsExporter.submitMetric(v, row, "fooNone") 270 | if actual == nil { 271 | t.Errorf("Expected: %v, Got: %v", fmt.Errorf("aggregation *view.Aggregation is not supported"), actual) 272 | } 273 | } 274 | 275 | func TestOnError(t *testing.T) { 276 | var expected error 277 | 278 | exporter, err := testExporter(Options{ 279 | StatsAddr: "unix:///invalid.socket", 280 | OnError: func(err error) { 281 | expected = err 282 | }, 283 | }) 284 | if err != nil { 285 | t.Error(err) 286 | } 287 | 288 | exporter.statsExporter.client = nil 289 | exporter.statsExporter.stop() 290 | 291 | if expected == nil { 292 | t.Errorf("Expected an error") 293 | } 294 | } 295 | 296 | func TestStatsdOptions(t *testing.T) { 297 | expected := "customnamespace.fooCount:1|c" 298 | payloadMaxSize := len(expected) + 3 299 | conn, err := listenUDP("localhost:0") 300 | if err != nil { 301 | t.Fatal(err) 302 | } 303 | defer conn.Close() 304 | 305 | addr := conn.LocalAddr().String() 306 | 307 | exporter, err := NewExporter(Options{ 308 | StatsAddr: addr, 309 | StatsdOptions: []statsd.Option{ 310 | // Payload size is enough for one metric only 311 | statsd.WithMaxBytesPerPayload(payloadMaxSize), 312 | statsd.WithNamespace("customnamespace."), 313 | }, 314 | }) 315 | if err != nil { 316 | t.Error(err) 317 | } 318 | defer exporter.statsExporter.stop() 319 | view.RegisterExporter(exporter) 320 | view.SetReportingPeriod(100 * time.Millisecond) 321 | 322 | if exporter.client.Namespace != "customnamespace." { 323 | t.Errorf("Namespace expected: customnamespace, Got: %s", exporter.client.Namespace) 324 | } 325 | 326 | fooCount := stats.Int64("fooCount", "fooInc", stats.UnitDimensionless) 327 | fooCountView := &view.View{ 328 | Name: "fooCount", 329 | Description: "fooInc", 330 | Measure: fooCount, 331 | Aggregation: view.Count(), 332 | } 333 | barCount := stats.Int64("barCount", "barInc", stats.UnitDimensionless) 334 | barCountView := &view.View{ 335 | Name: "barCount", 336 | Description: "barInc", 337 | Measure: barCount, 338 | Aggregation: view.Count(), 339 | } 340 | view.Register(fooCountView, barCountView) 341 | 342 | stats.Record(context.Background(), fooCount.M(1)) 343 | stats.Record(context.Background(), barCount.M(1)) 344 | 345 | buffer := make([]byte, 4096) 346 | n, err := io.ReadAtLeast(conn, buffer, 1) 347 | if err != nil { 348 | t.Fatal(err) 349 | } 350 | 351 | if len(expected) != n { 352 | t.Errorf("Expected: %s, Got: %s", expected, buffer) 353 | } 354 | } 355 | -------------------------------------------------------------------------------- /trace.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "bytes" 10 | "io" 11 | "sync" 12 | "time" 13 | 14 | "go.opencensus.io/trace" 15 | ) 16 | 17 | const ( 18 | // payloadLimit specifies the maximum payload size that the Datadog 19 | // agent will accept. Request bodies larger than this will be rejected. 20 | payloadLimit = int(1e7) // 10MB 21 | 22 | // defaultService specifies the default service name that will be used 23 | // with the registered traces. Users should normally specify a different 24 | // service name. 25 | defaultService = "opencensus-app" 26 | ) 27 | 28 | // allows tests to override 29 | var ( 30 | // inChannelSize specifies the size of the buffered channel which 31 | // takes spans and adds them to the payload. 32 | inChannelSize = int(5e5) // 500K (approx 61MB memory if full) 33 | 34 | // flushThreshold specifies the payload's size threshold in bytes. If it 35 | // is exceeded, a flush will be triggered. 36 | flushThreshold = payloadLimit / 2 37 | 38 | // flushInterval specifies the interval at which the payload will 39 | // automatically be flushed. 40 | flushInterval = 2 * time.Second 41 | ) 42 | 43 | type traceExporter struct { 44 | opts Options 45 | payload *payload 46 | errors *errorAmortizer 47 | sampler *prioritySampler 48 | 49 | // uploadFn specifies the function used for uploading. 50 | // Defaults to (*transport).upload; replaced in tests. 51 | uploadFn func(pkg *bytes.Buffer, count int) (io.ReadCloser, error) 52 | 53 | wg sync.WaitGroup // counts active uploads 54 | in chan *ddSpan 55 | exit chan struct{} 56 | } 57 | 58 | func newTraceExporter(o Options) *traceExporter { 59 | if o.Service == "" { 60 | o.Service = defaultService 61 | } 62 | sampler := newPrioritySampler() 63 | e := &traceExporter{ 64 | opts: o, 65 | payload: newPayload(), 66 | errors: newErrorAmortizer(defaultErrorFreq, o.OnError), 67 | sampler: sampler, 68 | uploadFn: newTransport(o.TraceAddr).upload, 69 | in: make(chan *ddSpan, inChannelSize), 70 | exit: make(chan struct{}), 71 | } 72 | 73 | go e.loop() 74 | 75 | return e 76 | } 77 | 78 | func (e *traceExporter) exportSpan(s *trace.SpanData) { 79 | select { 80 | case e.in <- e.convertSpan(s): 81 | // ok 82 | default: 83 | e.errors.log(errorTypeOverflow, nil) 84 | } 85 | } 86 | 87 | // loop consumes the input channel and also listens on exit channel 88 | // to cleanly stop the exporter, flushing any remaining spans to the transport 89 | // and reporting any errors. 90 | func (e *traceExporter) loop() { 91 | defer close(e.exit) 92 | tick := time.NewTicker(flushInterval) 93 | defer tick.Stop() 94 | 95 | loop: 96 | for { 97 | select { 98 | case span := <-e.in: 99 | e.receiveSpan(span) 100 | 101 | case <-tick.C: 102 | e.flush() 103 | 104 | case <-e.exit: 105 | break loop 106 | } 107 | } 108 | 109 | // drain the input channel to catch anything the loop might not process 110 | drained := false 111 | for !drained { 112 | select { 113 | case span := <-e.in: 114 | e.receiveSpan(span) 115 | default: 116 | drained = true 117 | } 118 | } 119 | e.flush() 120 | e.wg.Wait() // wait for uploads to finish 121 | e.errors.flush() 122 | } 123 | 124 | func (e *traceExporter) receiveSpan(span *ddSpan) { 125 | if _, ok := span.Metrics[keySamplingPriority]; !ok { 126 | e.sampler.applyPriority(span) 127 | } 128 | if err := e.payload.add(span); err != nil { 129 | e.errors.log(errorTypeEncoding, err) 130 | } 131 | if e.payload.size() > flushThreshold { 132 | e.flush() 133 | } 134 | } 135 | 136 | func (e *traceExporter) flush() { 137 | n := len(e.payload.traces) 138 | if n == 0 { 139 | return 140 | } 141 | buf := e.payload.buffer() 142 | e.wg.Add(1) 143 | go func() { 144 | body, err := e.uploadFn(buf, n) 145 | if err != nil { 146 | e.errors.log(errorTypeTransport, err) 147 | } else { 148 | e.sampler.readRatesJSON(body) // do we care about errors? 149 | } 150 | e.wg.Done() 151 | }() 152 | e.payload.reset() 153 | } 154 | 155 | // stop signals the loop goroutine to finish. 156 | // This blocks until the loop goroutine closes the exit channel. 157 | func (e *traceExporter) stop() { 158 | e.exit <- struct{}{} 159 | <-e.exit 160 | } 161 | -------------------------------------------------------------------------------- /trace_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "bytes" 10 | "io" 11 | "io/ioutil" 12 | "os" 13 | "strings" 14 | "sync" 15 | "testing" 16 | "time" 17 | 18 | "github.com/tinylib/msgp/msgp" 19 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 20 | ) 21 | 22 | const ( 23 | // testFlushInterval is the flush interval that will be used for the 24 | // duration of the tests. 25 | testFlushInterval = 24 * time.Hour 26 | 27 | // testFlushThreshold is the flush threshold that will be used for the 28 | // duration of the tests. 29 | testFlushThreshold = 1e3 30 | 31 | // testInChannelSize is the input channel's buffer size that will be used 32 | // for the duration of the tests. 33 | testInChannelSize = 1000 34 | ) 35 | 36 | func TestMain(m *testing.M) { 37 | o1, o2, o3 := flushInterval, flushThreshold, inChannelSize 38 | flushInterval = testFlushInterval 39 | flushThreshold = testFlushThreshold 40 | inChannelSize = testInChannelSize 41 | 42 | defer func() { 43 | flushInterval, flushThreshold, inChannelSize = o1, o2, o3 44 | }() 45 | 46 | os.Exit(m.Run()) 47 | } 48 | 49 | func TestTraceExporter(t *testing.T) { 50 | if testing.Short() { 51 | t.SkipNow() 52 | } 53 | 54 | t.Run("service", func(t *testing.T) { 55 | me := newTraceExporter(Options{}) 56 | defer me.stop() 57 | if me.opts.Service == "" { 58 | t.Fatal("service should never be empty") 59 | } 60 | }) 61 | 62 | t.Run("threshold", func(t *testing.T) { 63 | me := newTestTraceExporter(t) 64 | defer me.stop() 65 | span := spanPairs["tags"].oc 66 | count := 4 // 4 spans should take us overboard 67 | for i := 0; i < count; i++ { 68 | me.exportSpan(span) 69 | } 70 | time.Sleep(time.Millisecond) // wait for recv 71 | me.wg.Wait() // wait for flush 72 | flushed := me.payloads() 73 | eq := equalFunc(t) 74 | eq(len(flushed), 1) 75 | eq(len(flushed[0][0]), count) 76 | }) 77 | 78 | t.Run("stop", func(t *testing.T) { 79 | me := newTestTraceExporter(t) 80 | me.exportSpan(spanPairs["root"].oc) 81 | me.stop() 82 | 83 | if len(me.payloads()) != 1 { 84 | t.Fatalf("expected to flush 1, got %d", len(me.payloads())) 85 | } 86 | }) 87 | 88 | t.Run("sampler", func(t *testing.T) { 89 | eq := equalFunc(t) 90 | me := newTestTraceExporter(t) 91 | me.exportSpan(spanPairs["server_error_5xx"].oc) 92 | me.stop() 93 | 94 | // sampler is updated after flush 95 | eq(me.sampler.rates["service:db.users,env:"], 0.9) 96 | eq(me.sampler.defaultRate, 0.8) 97 | 98 | // got the sent span 99 | payload := me.payloads() 100 | eq(len(payload), 1) 101 | eq(len(payload[0]), 1) 102 | eq(len(payload[0][0]), 1) 103 | 104 | // span has sampling priority and rate applied 105 | span1 := payload[0][0][0] 106 | p, ok := span1.Metrics[keySamplingPriority] 107 | if !ok || !(p == ext.PriorityAutoKeep || p == ext.PriorityAutoReject) { 108 | t.Fatal(p, ok) 109 | } 110 | if v := span1.Metrics[keySamplingPriorityRate]; v != 1 { 111 | t.Fatalf("got %f", v) 112 | } 113 | }) 114 | } 115 | 116 | // testTraceExporter wraps a traceExporter, recording all flushed payloads. 117 | type testTraceExporter struct { 118 | *traceExporter 119 | t *testing.T 120 | 121 | mu sync.RWMutex 122 | flushed []ddPayload 123 | } 124 | 125 | func newTestTraceExporter(t *testing.T) *testTraceExporter { 126 | te := newTraceExporter(Options{Service: "mock.exporter"}) 127 | me := &testTraceExporter{traceExporter: te, flushed: make([]ddPayload, 0)} 128 | me.traceExporter.uploadFn = me.uploadFn 129 | return me 130 | } 131 | 132 | // payloads returns all payloads that were uploaded by this exporter. 133 | func (me *testTraceExporter) payloads() []ddPayload { 134 | me.mu.RLock() 135 | defer me.mu.RUnlock() 136 | return me.flushed 137 | } 138 | 139 | func (me *testTraceExporter) uploadFn(buf *bytes.Buffer, _ int) (io.ReadCloser, error) { 140 | var ddp ddPayload 141 | if err := msgp.Decode(buf, &ddp); err != nil { 142 | me.t.Fatal(err) 143 | } 144 | me.mu.Lock() 145 | me.flushed = append(me.flushed, ddp) 146 | me.mu.Unlock() 147 | return ioutil.NopCloser(strings.NewReader(`{"rate_by_service":{"service:,env:":0.8,"service:db.users,env:":0.9}}`)), nil 148 | } 149 | -------------------------------------------------------------------------------- /transport.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "bytes" 10 | "fmt" 11 | "io" 12 | "net" 13 | "net/http" 14 | "runtime" 15 | "strconv" 16 | "strings" 17 | "time" 18 | ) 19 | 20 | const ( 21 | // defaultTraceAddr specifies the default address of the Datadog trace agent. 22 | defaultTraceAddr = "localhost:8126" 23 | 24 | // version specifies the version identifier that will be attached to the 25 | // HTTP headers. In this case it is prefixed OC for Opencensus. 26 | version = "OC/0.1.0" 27 | ) 28 | 29 | // transport holds an HTTP client used to connect to the Datadog agent at the specified URL. 30 | type transport struct { 31 | client *http.Client 32 | url string 33 | } 34 | 35 | // newTransport creates a new transport that will connect to the Datadog agent at the given address. If 36 | // addr is empty, it will use the default address, which is "localhost:8126". 37 | func newTransport(addr string) *transport { 38 | if addr == "" { 39 | addr = defaultTraceAddr 40 | } 41 | httpclient := &http.Client{ 42 | Transport: &http.Transport{ 43 | Proxy: http.ProxyFromEnvironment, 44 | DialContext: (&net.Dialer{ 45 | Timeout: 30 * time.Second, 46 | KeepAlive: 30 * time.Second, 47 | DualStack: true, 48 | }).DialContext, 49 | MaxIdleConns: 100, 50 | IdleConnTimeout: 90 * time.Second, 51 | TLSHandshakeTimeout: 10 * time.Second, 52 | ExpectContinueTimeout: 1 * time.Second, 53 | }, 54 | Timeout: 1 * time.Second, 55 | } 56 | return &transport{ 57 | url: fmt.Sprintf("http://%s/v0.4/traces", addr), 58 | client: httpclient, 59 | } 60 | } 61 | 62 | // httpHeaders specifies the set of HTTP headers that will be attached to all HTTP calls 63 | // to the Datadog agent. 64 | var httpHeaders = map[string]string{ 65 | "Datadog-Meta-Lang": "go", 66 | "Datadog-Meta-Lang-Version": strings.TrimPrefix(runtime.Version(), "go"), 67 | "Datadog-Meta-Lang-Interpreter": runtime.Compiler + "-" + runtime.GOARCH + "-" + runtime.GOOS, 68 | "Datadog-Meta-Tracer-Version": version, 69 | "Content-Type": "application/msgpack", 70 | } 71 | 72 | // upload sents the given request body to the Datadog agent and assigns the traceCount 73 | // as an HTTP header. It returns a non-nil body if it was successful. 74 | func (t *transport) upload(data *bytes.Buffer, traceCount int) (body io.ReadCloser, err error) { 75 | req, err := http.NewRequest("POST", t.url, data) 76 | if err != nil { 77 | return nil, fmt.Errorf("cannot create http request: %v", err) 78 | } 79 | for header, value := range httpHeaders { 80 | req.Header.Set(header, value) 81 | } 82 | req.Header.Set("X-Datadog-Trace-Count", strconv.Itoa(traceCount)) 83 | req.Header.Set("Content-Length", strconv.Itoa(data.Len())) 84 | response, err := t.client.Do(req) 85 | if err != nil { 86 | return nil, err 87 | } 88 | if code := response.StatusCode; code >= 400 { 89 | // error, check the body for context information and 90 | // return a user friendly error 91 | msg := make([]byte, 1000) 92 | n, _ := response.Body.Read(msg) 93 | response.Body.Close() 94 | txt := http.StatusText(code) 95 | if n > 0 { 96 | return nil, fmt.Errorf("%s (Status: %s)", msg[:n], txt) 97 | } 98 | return nil, fmt.Errorf("%s", txt) 99 | } 100 | return response.Body, nil 101 | } 102 | -------------------------------------------------------------------------------- /transport_test.go: -------------------------------------------------------------------------------- 1 | // Unless explicitly stated otherwise all files in this repository are licensed 2 | // under the Apache License Version 2.0. 3 | // This product includes software developed at Datadog (https://www.datadog.com/). 4 | // Copyright 2018 Datadog, Inc. 5 | 6 | package datadog 7 | 8 | import ( 9 | "os" 10 | "sync/atomic" 11 | "testing" 12 | "time" 13 | 14 | "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" 15 | ) 16 | 17 | func TestTransport(t *testing.T) { 18 | _, ok := os.LookupEnv("INTEGRATION") 19 | if !ok { 20 | t.Skip("to run: set the INTEGRATION environment variable and have the agent running") 21 | } 22 | p := newPayload() 23 | for _, span := range []*ddSpan{ 24 | testSpan(1234, "abc", "qwe"), 25 | testSpan(1234, "abc1", "qwe"), 26 | testSpan(4567, "abc2", "qwe"), 27 | testSpan(4567, "abc2", "qwe"), 28 | } { 29 | p.add(span) 30 | } 31 | trans := newTransport("") 32 | body, err := trans.upload(p.buffer(), len(p.traces)) 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | err = newPrioritySampler().readRatesJSON(body) 37 | if err != nil { 38 | t.Fatal(err) 39 | } 40 | } 41 | 42 | // testSpan returns a minimally valid span that the agent will accept 43 | // through its normalization process. 44 | func testSpan(traceID uint64, name, service string) *ddSpan { 45 | now := time.Now() 46 | start := now.UnixNano() 47 | duration := now.Add(time.Minute).UnixNano() - start 48 | return &ddSpan{ 49 | TraceID: traceID, 50 | SpanID: atomic.AddUint64(&idSeed, 1), 51 | Name: name, 52 | Resource: name, 53 | Service: service, 54 | Start: start, 55 | Duration: duration, 56 | Metrics: map[string]float64{keySamplingPriority: ext.PriorityAutoKeep}, 57 | } 58 | } 59 | --------------------------------------------------------------------------------