pax_global_header00006660000000000000000000000064134427561710014524gustar00rootroot0000000000000052 comment=e7edbdf53a61a82ed143809088ed582312ff7e36 haystack-client-go-0.2.3/000077500000000000000000000000001344275617100152145ustar00rootroot00000000000000haystack-client-go-0.2.3/.gitignore000066400000000000000000000003421344275617100172030ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out vendor/ .idea/ examples/examples haystack-client-go-0.2.3/.gitmodules000066400000000000000000000001451344275617100173710ustar00rootroot00000000000000[submodule "haystack-idl"] path = haystack-idl url = https://github.com/ExpediaDotCom/haystack-idl haystack-client-go-0.2.3/.travis.yml000066400000000000000000000011571344275617100173310ustar00rootroot00000000000000sudo: required language: go go_import_path: github.com/ExpdiaDotCom/haystack-client-go dist: trusty matrix: include: - go: 1.9 services: - docker addons: hosts: - kafkasvc - haystack_agent - haystack_collector before_script: - curl -OL https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip - sudo unzip -o protoc-3.3.0-linux-x86_64.zip -d /usr/local bin/protoc - rm -f protoc-3.3.0-linux-x86_64.zip - curl https://glide.sh/get | sh script: - make glide test validate integration_test notifications: email: - haystack-notifications@expedia.com haystack-client-go-0.2.3/LICENSE000066400000000000000000000261221344275617100162240ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2018] Expedia Group. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. haystack-client-go-0.2.3/Makefile000066400000000000000000000014711344275617100166570ustar00rootroot00000000000000.PHONY: codegen codegen: idl-submodule go get -u github.com/golang/protobuf/protoc-gen-go cp haystack-idl/proto/agent/spanAgent.proto haystack-idl/proto/. protoc -I haystack-idl/proto/ --go_out=plugins=grpc:. haystack-idl/proto/span.proto protoc -I haystack-idl/proto/ --go_out=plugins=grpc:. haystack-idl/proto/spanAgent.proto rm haystack-idl/proto/spanAgent.proto idl-submodule: git submodule init git submodule update .PHONY: test test: codegen go test -run TestUnit* .PHONY: integration_test integration_test: docker-compose -f docker-compose.yaml -p sandbox up -d sleep 30 go test -run TestIntegration* docker-compose -f docker-compose.yaml -p sandbox stop .PHONY: glide glide: glide --version || go get github.com/Masterminds/glide glide update .PHONY: validate validate: ./scripts/validate-go haystack-client-go-0.2.3/README.md000066400000000000000000000016651344275617100165030ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/ExpediaDotCom/haystack-client-go.svg?branch=master)](https://travis-ci.org/ExpediaDotCom/haystack-client-go) [![License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/ExpediaDotCom/haystack/blob/master/LICENSE) # Haystack bindings for Go OpenTracing API. This is Haystack's client library for Golang that implements [OpenTracing API 1.0](https://github.com/opentracing/opentracing-go/). ## How to use the library? Check our detailed [example](examples/example.go) on how to initialize tracer, start a span and send it to one of the dispatchers. This example is actually an integration test uses haystack-agent container ## How to build this library? `git clone --recursive https://github.com/ExpediaDotCom/haystack-client-go` - clone the repo `make glide` - if you are running for the very first time `make test validate` - go test and validate the code haystack-client-go-0.2.3/dispatcher.go000066400000000000000000000177431344275617100177050ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "fmt" "os" "os/signal" "time" "github.com/opentracing/opentracing-go/ext" "github.com/opentracing/opentracing-go/log" ) /*Dispatcher dispatches the span object*/ type Dispatcher interface { Name() string Dispatch(span *_Span) DispatchProtoSpan(span *Span) Close() SetLogger(logger Logger) } /*InMemoryDispatcher implements the Dispatcher interface*/ type InMemoryDispatcher struct { spans []*_Span logger Logger } /*NewInMemoryDispatcher creates a new in memory dispatcher*/ func NewInMemoryDispatcher() Dispatcher { return &InMemoryDispatcher{} } /*Name gives the Dispatcher name*/ func (d *InMemoryDispatcher) Name() string { return "InMemoryDispatcher" } /*SetLogger sets the logger to use*/ func (d *InMemoryDispatcher) SetLogger(logger Logger) { d.logger = logger } /*Dispatch dispatches the span object*/ func (d *InMemoryDispatcher) Dispatch(span *_Span) { d.spans = append(d.spans, span) } /*DispatchProtoSpan dispatches proto span object*/ func (d *InMemoryDispatcher) DispatchProtoSpan(span *Span) { /* not implemented */ } /*Close down the inMemory dispatcher*/ func (d *InMemoryDispatcher) Close() { d.spans = nil } /*FileDispatcher file dispatcher*/ type FileDispatcher struct { fileHandle *os.File logger Logger } /*NewFileDispatcher creates a new file dispatcher*/ func NewFileDispatcher(filename string) Dispatcher { fd, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if err != nil { panic(err) } return &FileDispatcher{ fileHandle: fd, } } /*Name gives the Dispatcher name*/ func (d *FileDispatcher) Name() string { return "FileDispatcher" } /*SetLogger sets the logger to use*/ func (d *FileDispatcher) SetLogger(logger Logger) { d.logger = logger } /*Dispatch dispatches the span object*/ func (d *FileDispatcher) Dispatch(span *_Span) { _, err := d.fileHandle.WriteString(span.String() + "\n") if err != nil { panic(err) } } /*DispatchProtoSpan dispatches proto span object*/ func (d *FileDispatcher) DispatchProtoSpan(span *Span) { /* not implemented */ } /*Close down the file dispatcher*/ func (d *FileDispatcher) Close() { err := d.fileHandle.Close() if err != nil { panic(err) } } /*RemoteDispatcher dispatcher, client can be grpc or http*/ type RemoteDispatcher struct { client RemoteClient timeout time.Duration logger Logger spanChannel chan *Span } /*NewHTTPDispatcher creates a new haystack-agent dispatcher*/ func NewHTTPDispatcher(url string, timeout time.Duration, headers map[string]string, maxQueueLength int) Dispatcher { dispatcher := &RemoteDispatcher{ client: NewHTTPClient(url, headers, timeout), timeout: timeout, spanChannel: make(chan *Span, maxQueueLength), } go startListener(dispatcher) return dispatcher } /*NewDefaultHTTPDispatcher creates a new http dispatcher*/ func NewDefaultHTTPDispatcher() Dispatcher { return NewHTTPDispatcher("http://haystack-collector/span", 3*time.Second, make(map[string](string)), 1000) } /*NewAgentDispatcher creates a new haystack-agent dispatcher*/ func NewAgentDispatcher(host string, port int, timeout time.Duration, maxQueueLength int) Dispatcher { dispatcher := &RemoteDispatcher{ client: NewGrpcClient(host, port, timeout), timeout: timeout, spanChannel: make(chan *Span, maxQueueLength), } go startListener(dispatcher) return dispatcher } /*NewDefaultAgentDispatcher creates a new haystack-agent dispatcher*/ func NewDefaultAgentDispatcher() Dispatcher { return NewAgentDispatcher("haystack-agent", 35000, 3*time.Second, 1000) } func startListener(dispatcher *RemoteDispatcher) { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, os.Kill) for { select { case sp := <-dispatcher.spanChannel: dispatcher.client.Send(sp) case <-signals: break } } } /*Name gives the Dispatcher name*/ func (d *RemoteDispatcher) Name() string { return "RemoteDispatcher" } /*SetLogger sets the logger to use*/ func (d *RemoteDispatcher) SetLogger(logger Logger) { d.logger = logger d.client.SetLogger(logger) } /*Dispatch dispatches the span object*/ func (d *RemoteDispatcher) Dispatch(span *_Span) { s := &Span{ TraceId: span.context.TraceID, SpanId: span.context.SpanID, ParentSpanId: span.context.ParentID, ServiceName: span.ServiceName(), OperationName: span.OperationName(), StartTime: span.startTime.UnixNano() / int64(time.Microsecond), Duration: span.duration.Nanoseconds() / int64(time.Microsecond), Tags: d.tags(span), Logs: d.logs(span), } d.spanChannel <- s } /*DispatchProtoSpan dispatches the proto span object*/ func (d *RemoteDispatcher) DispatchProtoSpan(s *Span) { d.spanChannel <- s } func (d *RemoteDispatcher) logs(span *_Span) []*Log { var spanLogs []*Log for _, lg := range span.logs { spanLogs = append(spanLogs, &Log{ Timestamp: lg.Timestamp.UnixNano() / int64(time.Microsecond), Fields: d.logFieldsToTags(lg.Fields), }) } return spanLogs } func (d *RemoteDispatcher) logFieldsToTags(fields []log.Field) []*Tag { var spanTags []*Tag for _, field := range fields { spanTags = append(spanTags, ConvertToProtoTag(field.Key(), field.Value())) } return spanTags } func (d *RemoteDispatcher) tags(span *_Span) []*Tag { var spanTags []*Tag for _, tag := range span.tags { spanTags = append(spanTags, ConvertToProtoTag(tag.Key, tag.Value)) } return spanTags } /*Close down the file dispatcher*/ func (d *RemoteDispatcher) Close() { err := d.client.Close() if err != nil { d.logger.Error("Fail to close the haystack-agent dispatcher %v", err) } } /*ConvertToProtoTag converts to proto tag*/ func ConvertToProtoTag(key string, value interface{}) *Tag { switch v := value.(type) { case string: return &Tag{ Key: key, Myvalue: &Tag_VStr{ VStr: value.(string), }, Type: Tag_STRING, } case int: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(int)), }, Type: Tag_LONG, } case int32: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(int32)), }, Type: Tag_LONG, } case int16: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(int16)), }, Type: Tag_LONG, } case int64: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: value.(int64), }, Type: Tag_LONG, } case uint16: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(uint16)), }, Type: Tag_LONG, } case uint32: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(uint32)), }, Type: Tag_LONG, } case uint64: return &Tag{ Key: key, Myvalue: &Tag_VLong{ VLong: int64(value.(uint64)), }, Type: Tag_LONG, } case float32: return &Tag{ Key: key, Myvalue: &Tag_VDouble{ VDouble: float64(value.(float32)), }, Type: Tag_DOUBLE, } case float64: return &Tag{ Key: key, Myvalue: &Tag_VDouble{ VDouble: value.(float64), }, Type: Tag_DOUBLE, } case bool: return &Tag{ Key: key, Myvalue: &Tag_VBool{ VBool: value.(bool), }, Type: Tag_BOOL, } case []byte: return &Tag{ Key: key, Myvalue: &Tag_VBytes{ VBytes: value.([]byte), }, Type: Tag_BINARY, } case ext.SpanKindEnum: return &Tag{ Key: key, Myvalue: &Tag_VStr{ VStr: string(value.(ext.SpanKindEnum)), }, Type: Tag_STRING, } default: panic(fmt.Errorf("unknown format %v", v)) } } haystack-client-go-0.2.3/docker-compose.yaml000066400000000000000000000020741344275617100210150ustar00rootroot00000000000000version: '3' services: haystack_agent: image: expediadotcom/haystack-agent:0.1.3 depends_on: - zookeeper - kafkasvc environment: haystack_env_agents_spans_port: 35000 haystack_env_agents_spans_dispatchers_kafka_bootstrap_servers: "kafkasvc:9092" ports: - "35000:35000" entrypoint: - /bin/sh - -c - 'sleep 10 && java -jar /app/bin/haystack-agent.jar --config-provider file --file-path /app/bin/dev.conf' haystack_collector: image: expediadotcom/haystack-http-span-collector:1.1 depends_on: - zookeeper - kafkasvc environment: HAYSTACK_PROP_KAFKA_PRODUCER_PROPS_BOOTSTRAP_SERVERS: "kafkasvc:9092" ports: - "8080:8080" zookeeper: image: wurstmeister/zookeeper ports: - "2181:2181" kafkasvc: image: wurstmeister/kafka:2.11-1.1.1 depends_on: - zookeeper environment: KAFKA_ADVERTISED_HOST_NAME: "kafkasvc" KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 volumes: - /var/run/docker.sock:/var/run/docker.sock ports: - "9092:9092" haystack-client-go-0.2.3/examples/000077500000000000000000000000001344275617100170325ustar00rootroot00000000000000haystack-client-go-0.2.3/examples/example.go000066400000000000000000000056361344275617100210260ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package main import ( "fmt" "net/http" "time" haystack "github.com/ExpediaDotCom/haystack-client-go" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) type consoleLogger struct{} /*Error prints the error message*/ func (logger *consoleLogger) Error(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } /*Info prints the info message*/ func (logger *consoleLogger) Info(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } /*Debug prints the info message*/ func (logger *consoleLogger) Debug(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } func main() { /*Use haystack.NewDefaultAgentDispatcher() for non-dev environment*/ tracer, closer := haystack.NewTracer("dummy-service", haystack.NewDefaultAgentDispatcher(), haystack.TracerOptionsFactory.Tag("appVer", "v1.1"), haystack.TracerOptionsFactory.Logger(&consoleLogger{})) defer func() { err := closer.Close() if err != nil { panic(err) } }() carrier := opentracing.HTTPHeadersCarrier(http.Header(map[string][]string{ "Trace-Id": {"409dec0e-473e-11e9-81cc-186590cf29af"}, "Span-Id": {"509df8d3-473e-11e9-81cc-186590cf29af"}, "Parent-Id": {"609df88c-473e-11e9-81cc-186590cf29af"}, })) clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier) if err != nil { panic(err) } span1 := tracer.StartSpan("operation1", opentracing.ChildOf(clientContext), opentracing.Tag{Key: "my-tag", Value: "something"}) span1.SetTag(string(ext.SpanKind), ext.SpanKindRPCServerEnum) span1.SetTag(string(ext.Error), false) span1.SetTag(string(ext.HTTPStatusCode), 200) span1.SetTag(string(ext.HTTPMethod), "POST") span1.LogEventWithPayload("code", 1001) span2 := tracer.StartSpan("operation2", opentracing.ChildOf(span1.Context())) // a slightly different way to set the tags on a span ext.Error.Set(span2, true) ext.HTTPStatusCode.Set(span1, 404) // inject the span context in http header using tracer.Inject(...) req, _ := http.NewRequest(http.MethodGet, "https://expediadotcom.github.io/haystack/", nil) tracer.Inject(span2.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)) // //log.Println(req.Header) span2.Finish() span1.Finish() time.Sleep(5 * time.Second) } haystack-client-go-0.2.3/glide.lock000066400000000000000000000057751344275617100171700ustar00rootroot00000000000000hash: b6963927c0443115cdeb1fcbea1352a139652ba323520f2c1bd15985bc9e38c5 updated: 2018-12-04T16:02:58.279853731+05:30 imports: - name: github.com/codeskyblue/go-uuid version: 952abbca900b023c1a80bc522ff4795db50d9d6c - name: github.com/DataDog/zstd version: c7161f8c63c045cbc7ca051dcc969dd0e4054de2 - name: github.com/davecgh/go-spew version: 782f4967f2dc4564575ca782fe2d04090b5faca8 subpackages: - spew - name: github.com/eapache/go-resiliency version: ea41b0fad31007accc7f806884dcdf3da98b79ce subpackages: - breaker - name: github.com/eapache/go-xerial-snappy version: 776d5712da21bc4762676d614db1d8a64f4238b0 - name: github.com/eapache/queue version: 093482f3f8ce946c05bcba64badd2c82369e084d - name: github.com/golang/protobuf version: 1d3f30b51784bec5aad268e59fd3c2fc1c2fe73f subpackages: - proto - ptypes - ptypes/any - ptypes/duration - ptypes/timestamp - name: github.com/golang/snappy version: 2e65f85255dbc3072edf28d6b5b8efc472979f5a - name: github.com/google/uuid version: 9b3b1e0f5f99ae461456d768e7d301a7acdaa2d8 - name: github.com/opentracing/opentracing-go version: 1949ddbfd147afd4d964a9f00b24eb291e0e7c38 subpackages: - ext - log - name: github.com/pierrec/lz4 version: 623b5a2f4d2a41e411730dcdfbfdaeb5c0c4564e subpackages: - internal/xxh32 - name: github.com/pkg/errors version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/rcrowley/go-metrics version: 3113b8401b8a98917cde58f8bbd42a1b1c03b1fd - name: github.com/Shopify/sarama version: 96e43a884d5ef985c98dc02e5ec6904a2b8b1d1c - name: golang.org/x/net version: 1c05540f6879653db88113bc4a2b70aec4bd491f subpackages: - context - http2 - http2/hpack - idna - internal/timeseries - lex/httplex - trace - name: golang.org/x/sys version: 95c6576299259db960f6c5b9b69ea52422860fce subpackages: - unix - name: golang.org/x/text version: b19bf474d317b857955b12035d2c5acb57ce8b01 subpackages: - secure/bidirule - transform - unicode/bidi - unicode/norm - name: google.golang.org/genproto version: bd91e49a0898e27abb88c339b432fa53d7497ac0 subpackages: - googleapis/rpc/status - name: google.golang.org/grpc version: ca62c6b92c334f52c7e48b7cbf624f3b877fb092 subpackages: - balancer - balancer/base - balancer/roundrobin - codes - connectivity - credentials - credentials/internal - encoding - encoding/proto - grpclog - internal - internal/backoff - internal/channelz - internal/envconfig - internal/grpcrand - internal/syscall - internal/transport - keepalive - metadata - naming - peer - resolver - resolver/dns - resolver/passthrough - stats - status - tap testImports: - name: github.com/magiconair/properties version: 7c38529aac7222391b7a2661365177a97e21b998 subpackages: - assert - name: github.com/pmezard/go-difflib version: 792786c7400a136282c1664665ae0a8db921c6c2 subpackages: - difflib - name: github.com/stretchr/testify version: 8019298d9fa5a04fc2ad10ae03349df3483096a6 subpackages: - assert - require - suite haystack-client-go-0.2.3/glide.yaml000066400000000000000000000006061344275617100171660ustar00rootroot00000000000000package: github.com/ExpediaDotCom/haystack-client-go import: - package: github.com/opentracing/opentracing-go version: ^1 subpackages: - ext - log - package: github.com/google/uuid version: ^1 - package: github.com/pkg/errors version: ~0.8.0 testImport: - package: github.com/Shopify/sarama - package: github.com/stretchr/testify subpackages: - assert - require - suite haystack-client-go-0.2.3/haystack-idl/000077500000000000000000000000001344275617100175715ustar00rootroot00000000000000haystack-client-go-0.2.3/integration_test.go000066400000000000000000000130541344275617100211300ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "fmt" "strconv" "testing" "time" "github.com/Shopify/sarama" "github.com/magiconair/properties/assert" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) type consoleLogger struct{} /*Error prints the error message*/ func (logger *consoleLogger) Error(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } /*Info prints the info message*/ func (logger *consoleLogger) Info(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } /*Debug prints the info message*/ func (logger *consoleLogger) Debug(format string, v ...interface{}) { fmt.Printf(format, v...) fmt.Print("\n") } func createKafkaConsumer() sarama.PartitionConsumer { consumer, err := sarama.NewConsumer([]string{"kafkasvc:9092"}, nil) if err != nil { panic(err) } partitionConsumer, err := consumer.ConsumePartition("proto-spans", 0, sarama.OffsetOldest) if err != nil { panic(err) } return partitionConsumer } func executeTest(tracer opentracing.Tracer, partitionConsumer sarama.PartitionConsumer, t *testing.T) { serverTime := time.Now() serverSpan := tracer.StartSpan("serverOp", opentracing.Tag{Key: "server-tag-key", Value: "something"}, opentracing.StartTime(serverTime)) ext.SpanKind.Set(serverSpan, ext.SpanKindRPCServerEnum) ext.Error.Set(serverSpan, false) ext.HTTPStatusCode.Set(serverSpan, 200) ext.HTTPMethod.Set(serverSpan, "POST") serverSpan.LogEventWithPayload("code", 1001) clientTime := time.Now() clientSpan := tracer.StartSpan("clientOp", opentracing.ChildOf(serverSpan.Context()), opentracing.StartTime(clientTime)) ext.SpanKind.Set(clientSpan, ext.SpanKindRPCClientEnum) ext.Error.Set(clientSpan, true) ext.HTTPStatusCode.Set(clientSpan, 404) // finish the two spans clientSpan.Finish() serverSpan.Finish() clientSpanReceived := 0 serverSpanReceived := 0 clientParentSpanID := "" clientTraceID := "" serverSpanID := "" serverTraceID := "" ConsumerLoop: for { select { case msg := <-partitionConsumer.Messages(): span := &Span{} unmarshalErr := span.XXX_Unmarshal(msg.Value) if unmarshalErr != nil { panic(unmarshalErr) } verifyCommonAttr(t, span) for _, tag := range span.GetTags() { if tag.GetKey() == "span.kind" { switch tag.GetVStr() { case "client": clientSpanReceived = clientSpanReceived + 1 assert.Equal(t, span.GetOperationName(), "clientOp") assert.Equal(t, span.StartTime, int64(clientTime.UnixNano()/int64(time.Microsecond))) assert.Equal(t, tagVal(span, "server-tag-key"), "") assert.Equal(t, tagVal(span, "error"), "true") assert.Equal(t, tagVal(span, string(ext.HTTPStatusCode)), "404") clientParentSpanID = span.GetParentSpanId() clientTraceID = span.GetTraceId() case "server": serverSpanReceived = serverSpanReceived + 1 assert.Equal(t, span.GetOperationName(), "serverOp") assert.Equal(t, span.StartTime, int64(serverTime.UnixNano()/int64(time.Microsecond))) assert.Equal(t, tagVal(span, "server-tag-key"), "something") assert.Equal(t, tagVal(span, "error"), "false") assert.Equal(t, tagVal(span, string(ext.HTTPStatusCode)), "200") serverSpanID = span.GetSpanId() serverTraceID = span.GetTraceId() } } } // expect only two spans and compare the ID relationship if msg.Offset == 1 { assert.Equal(t, clientSpanReceived, 1) assert.Equal(t, serverSpanReceived, 1) assert.Equal(t, serverSpanID, clientParentSpanID) assert.Equal(t, serverTraceID, clientTraceID) break ConsumerLoop } } } } func TestIntegration(t *testing.T) { consumer := createKafkaConsumer() agentTracer, agentCloser := NewTracer("dummy-service", NewAgentDispatcher("haystack_agent", 35000, 3*time.Second, 1000), TracerOptionsFactory.Tag("appVer", "v1.1"), TracerOptionsFactory.Logger(&consoleLogger{})) defer func() { err := agentCloser.Close() if err != nil { panic(err) } }() executeTest(agentTracer, consumer, t) httpDispatcher := NewHTTPDispatcher("http://haystack_collector:8080/span", 3*time.Second, make(map[string]string), 1000) _, httpCloser := NewTracer("dummy-service", httpDispatcher, TracerOptionsFactory.Tag("appVer", "v1.1"), TracerOptionsFactory.Logger(&consoleLogger{})) defer func() { err := httpCloser.Close() if err != nil { panic(err) } }() //executeTest(httpTracer, consumer, t) } func verifyCommonAttr(t *testing.T, span *Span) { assert.Equal(t, span.GetServiceName(), "dummy-service") assert.Equal(t, tagVal(span, "appVer"), "v1.1") } func tagVal(span *Span, tagKey string) string { for _, tag := range span.GetTags() { if tag.GetKey() == tagKey { switch tag.GetType() { case Tag_STRING: return tag.GetVStr() case Tag_BOOL: return strconv.FormatBool(tag.GetVBool()) case Tag_LONG: return fmt.Sprintf("%d", tag.GetVLong()) case Tag_DOUBLE: return fmt.Sprintf("%f", tag.GetVDouble()) } } } return "" } haystack-client-go-0.2.3/logger.go000066400000000000000000000022631344275617100170250ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack /*Logger defines a new logger interface*/ type Logger interface { Info(format string, v ...interface{}) Error(format string, v ...interface{}) Debug(format string, v ...interface{}) } /*NullLogger does nothing*/ type NullLogger struct{} /*Error prints the error message*/ func (logger NullLogger) Error(format string, v ...interface{}) {} /*Info prints the info message*/ func (logger NullLogger) Info(format string, v ...interface{}) {} /*Debug prints the info message*/ func (logger NullLogger) Debug(format string, v ...interface{}) {} haystack-client-go-0.2.3/propagator.go000066400000000000000000000123451344275617100177260ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "fmt" "net/url" "strings" "github.com/opentracing/opentracing-go" ) /*Propagator defines the interface for injecting and extracing the SpanContext from the carrier*/ type Propagator interface { // Inject takes `SpanContext` and injects it into `carrier` Inject(ctx *SpanContext, carrier interface{}) error // Extract `SpanContext` from the `carrier` Extract(carrier interface{}) (*SpanContext, error) } /*Codex defines the interface for encoding and decoding the propagated data*/ type Codex interface { Encode(value string) string Decode(value string) string } /*DefaultCodex is a no op*/ type DefaultCodex struct{} /*Encode a no-op for encoding the value*/ func (c DefaultCodex) Encode(value string) string { return value } /*Decode a no-op for decoding the value*/ func (c DefaultCodex) Decode(value string) string { return value } /*URLCodex encodes decodes a url*/ type URLCodex struct{} /*Encode a no-op for encoding the value*/ func (c URLCodex) Encode(value string) string { return url.QueryEscape(value) } /*Decode a no-op for decoding the value*/ func (c URLCodex) Decode(value string) string { decoded, err := url.QueryUnescape(value) if err == nil { return decoded } return "" } /*PropagatorOpts defines the options need by a propagator*/ type PropagatorOpts struct { TraceIDKEYName string SpanIDKEYName string ParentSpanIDKEYName string BaggagePrefixKEYName string } var defaultPropagatorOpts = PropagatorOpts{} var defaultCodex = DefaultCodex{} /*TraceIDKEY returns the trace id key in the propagator*/ func (p *PropagatorOpts) TraceIDKEY() string { if p.TraceIDKEYName != "" { return p.TraceIDKEYName } return "Trace-ID" } /*SpanIDKEY returns the span id key in the propagator*/ func (p *PropagatorOpts) SpanIDKEY() string { if p.SpanIDKEYName != "" { return p.SpanIDKEYName } return "Span-ID" } /*ParentSpanIDKEY returns the parent span id key in the propagator*/ func (p *PropagatorOpts) ParentSpanIDKEY() string { if p.ParentSpanIDKEYName != "" { return p.ParentSpanIDKEYName } return "Parent-ID" } /*BaggageKeyPrefix returns the baggage key prefix*/ func (p *PropagatorOpts) BaggageKeyPrefix() string { if p.BaggagePrefixKEYName != "" { return p.BaggagePrefixKEYName } return "Baggage-" } /*TextMapPropagator implements Propagator interface*/ type TextMapPropagator struct { opts PropagatorOpts codex Codex } /*Inject injects the span context in the carrier*/ func (p *TextMapPropagator) Inject(ctx *SpanContext, carrier interface{}) error { textMapWriter, ok := carrier.(opentracing.TextMapWriter) if !ok { return opentracing.ErrInvalidCarrier } textMapWriter.Set(p.opts.TraceIDKEY(), ctx.TraceID) textMapWriter.Set(p.opts.SpanIDKEY(), ctx.SpanID) textMapWriter.Set(p.opts.ParentSpanIDKEY(), ctx.ParentID) ctx.ForeachBaggageItem(func(key, value string) bool { textMapWriter.Set(fmt.Sprintf("%s%s", p.opts.BaggageKeyPrefix(), key), p.codex.Encode(ctx.Baggage[key])) return true }) return nil } /*Extract the span context from the carrier*/ func (p *TextMapPropagator) Extract(carrier interface{}) (*SpanContext, error) { textMapReader, ok := carrier.(opentracing.TextMapReader) if !ok { return nil, opentracing.ErrInvalidCarrier } baggageKeyLowerCasePrefix := strings.ToLower(p.opts.BaggageKeyPrefix()) traceIDKeyLowerCase := strings.ToLower(p.opts.TraceIDKEY()) spanIDKeyLowerCase := strings.ToLower(p.opts.SpanIDKEY()) parentSpanIDKeyLowerCase := strings.ToLower(p.opts.ParentSpanIDKEY()) traceID := "" spanID := "" parentSpanID := "" baggage := make(map[string]string) err := textMapReader.ForeachKey(func(k, v string) error { lcKey := strings.ToLower(k) if strings.HasPrefix(lcKey, baggageKeyLowerCasePrefix) { keySansPrefix := lcKey[len(p.opts.BaggageKeyPrefix()):] baggage[keySansPrefix] = p.codex.Decode(v) } else if lcKey == traceIDKeyLowerCase { traceID = v } else if lcKey == spanIDKeyLowerCase { spanID = v } else if lcKey == parentSpanIDKeyLowerCase { parentSpanID = v } return nil }) if err != nil { return nil, err } return &SpanContext{ TraceID: traceID, SpanID: spanID, ParentID: parentSpanID, Baggage: baggage, IsExtractedContext: true, }, nil } /*NewDefaultTextMapPropagator returns a default text map propagator*/ func NewDefaultTextMapPropagator() *TextMapPropagator { return NewTextMapPropagator(defaultPropagatorOpts, defaultCodex) } /*NewTextMapPropagator returns a text map propagator*/ func NewTextMapPropagator(opts PropagatorOpts, codex Codex) *TextMapPropagator { return &TextMapPropagator{ opts: opts, codex: codex, } } haystack-client-go-0.2.3/remote_client.go000066400000000000000000000102131344275617100203710ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "bytes" "fmt" "io/ioutil" "net/http" "time" "github.com/golang/protobuf/proto" context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) /*RemoteClient remote client*/ type RemoteClient interface { Send(span *Span) Close() error SetLogger(logger Logger) } /*GrpcClient grpc client*/ type GrpcClient struct { conn *grpc.ClientConn client SpanAgentClient timeout time.Duration logger Logger } /*NewGrpcClient returns a new grpc client*/ func NewGrpcClient(host string, port int, timeout time.Duration) *GrpcClient { targetHost := fmt.Sprintf("%s:%d", host, port) conn, err := grpc.Dial(targetHost, grpc.WithInsecure()) if err != nil { panic(fmt.Sprintf("fail to connect to agent with error: %v", err)) } return &GrpcClient{ conn: conn, client: NewSpanAgentClient(conn), timeout: timeout, } } /*Send a proto span to grpc server*/ func (c *GrpcClient) Send(span *Span) { ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() result, err := c.client.Dispatch(ctx, span) if err != nil { c.logger.Error("Fail to dispatch to haystack-agent with error %v", err) } else if result.GetCode() != DispatchResult_SUCCESS { c.logger.Error(fmt.Sprintf("Fail to dispatch to haystack-agent with error code: %d, message :%s", result.GetCode(), result.GetErrorMessage())) } else { c.logger.Debug(fmt.Sprintf("span [%v] has been successfully dispatched to haystack", span)) } } /*Close the grpc client*/ func (c *GrpcClient) Close() error { return c.conn.Close() } /*SetLogger sets the logger*/ func (c *GrpcClient) SetLogger(logger Logger) { c.logger = logger } /*HTTPClient a http client*/ type HTTPClient struct { url string headers map[string]string client *http.Client logger Logger } /*NewHTTPClient returns a new http client*/ func NewHTTPClient(url string, headers map[string]string, timeout time.Duration) *HTTPClient { httpClient := &http.Client{ Timeout: timeout, } return &HTTPClient{ url: url, headers: headers, client: httpClient, } } /*Send a proto span to http server*/ func (c *HTTPClient) Send(span *Span) { serializedBytes, marshalErr := proto.Marshal(span) if marshalErr != nil { c.logger.Error("Fail to serialize the span to proto bytes, error=%v", marshalErr) return } postRequest, requestErr := http.NewRequest(http.MethodPost, c.url, bytes.NewReader(serializedBytes)) if requestErr != nil { c.logger.Error("Fail to create request for posting span to haystack server, error=%v", requestErr) return } if c.headers != nil { for k, v := range c.headers { postRequest.Header.Add(k, v) } } resp, err := c.client.Do(postRequest) if err != nil { c.logger.Error("Fail to dispatch to haystack http server, error=%v", err) } defer func() { closeErr := resp.Body.Close() if closeErr != nil { /* do nothing */ } }() respBytes, respErr := ioutil.ReadAll(resp.Body) if respErr != nil { c.logger.Error("Fail to read the http response from haystack server, error=%v", respErr) return } if resp.StatusCode < 200 || resp.StatusCode >= 300 { c.logger.Error("Fail to dispatch the span to haystack http server with statusCode=%d , payload=%s", resp.StatusCode, string(respBytes)) } else { c.logger.Debug(fmt.Sprintf("span [%v] has been successfully dispatched to haystack, response=%s", span, string(respBytes))) } } /*Close the http client*/ func (c *HTTPClient) Close() error { return nil } /*SetLogger sets the logger*/ func (c *HTTPClient) SetLogger(logger Logger) { c.logger = logger } haystack-client-go-0.2.3/scripts/000077500000000000000000000000001344275617100167035ustar00rootroot00000000000000haystack-client-go-0.2.3/scripts/validate-errcheck000077500000000000000000000010431344275617100222040ustar00rootroot00000000000000#!/usr/bin/env bash go get github.com/kisielk/errcheck export PATH=$PATH:$GOBIN errors=() failedErrcheck=$(errcheck -ignorepkg github.com/golang/protobuf/proto .) if [ "$failedErrcheck" ]; then errors+=( "$failedErrcheck" ) fi if [ ${#errors[@]} -eq 0 ]; then echo 'Congratulations! All Go source files have been errchecked.' else { echo "Errors from errcheck:" for err in "${errors[@]}"; do echo "$err" done echo echo 'Please fix the above errors. You can test via "errcheck" and commit the result.' echo } >&2 false fihaystack-client-go-0.2.3/scripts/validate-go000077500000000000000000000010331344275617100210220ustar00rootroot00000000000000#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" RESP=0 function checkResult { if [[ $RESP -eq 1 ]]; then exit 1 fi } echo --------------- validate fmt --------------- $DIR/validate-gofmt RESP=$? checkResult echo --------------- validate vet --------------- $DIR/validate-govet RESP=$? checkResult echo --------------- validate lint --------------- $DIR/validate-golint RESP=$? checkResult echo --------------- validate errcheck--------------- $DIR/validate-errcheck RESP=$? checkResult haystack-client-go-0.2.3/scripts/validate-gofmt000077500000000000000000000011711344275617100215340ustar00rootroot00000000000000#!/usr/bin/env bash IFS=$'\n' files=( $(find . -iname "*.go" | grep -v "vendor*" | grep -v "haystack-idl*") ) unset IFS badFiles=() for f in "${files[@]}"; do # we use "git show" here to validate that what's committed is formatted if [ "$(gofmt -s -l $f)" ]; then badFiles+=( "$f" ) fi done if [ ${#badFiles[@]} -eq 0 ]; then echo 'Congratulations! All Go source files are properly formatted.' else { echo "These files are not properly gofmt'd:" for f in "${badFiles[@]}"; do echo " - $f" done echo echo 'Please reformat the above files using "gofmt -s -w" and commit the result.' echo } >&2 false fi haystack-client-go-0.2.3/scripts/validate-golint000077500000000000000000000011571344275617100217200ustar00rootroot00000000000000#!/usr/bin/env bash go get github.com/golang/lint/golint export PATH=$PATH:$GOBIN IFS=$'\n' files=( $(find . -iname "*.go" | grep -v "vendor*" | grep -v "haystack-idl*") ) unset IFS errors=() for f in "${files[@]}"; do failedLint=$(golint "$f") if [ "$failedLint" ]; then errors+=( "$failedLint" ) fi done if [ ${#errors[@]} -eq 0 ]; then echo 'Congratulations! All Go source files have been linted.' else { echo "Errors from golint:" for err in "${errors[@]}"; do echo "$err" done echo echo 'Please fix the above errors. You can test via "golint" and commit the result.' echo } >&2 false fi haystack-client-go-0.2.3/scripts/validate-govet000077500000000000000000000010501344275617100215400ustar00rootroot00000000000000#!/usr/bin/env bash IFS=$'\n' files=( $(find . -iname "*.go" | grep -v "vendor*") ) unset IFS errors=() for f in "${files[@]}"; do failedVet=$(go tool vet -printf=false "$f") if [ "$failedVet" ]; then errors+=( "$failedVet" ) fi done if [ ${#errors[@]} -eq 0 ]; then echo 'Congratulations! All Go source files have been vetted.' else { echo "Errors from govet:" for err in "${errors[@]}"; do echo "$err" done echo echo 'Please fix the above errors. You can test via "go vet" and commit the result.' echo } >&2 false fi haystack-client-go-0.2.3/span.go000066400000000000000000000110171344275617100165040ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "encoding/json" "time" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/log" ) /*_Span implements opentracing.Span*/ type _Span struct { tracer *Tracer context *SpanContext operationName string // startTime is the timestamp indicating when the span began, with microseconds precision. startTime time.Time // duration returns duration of the span with microseconds precision. duration time.Duration tags []opentracing.Tag logs []opentracing.LogRecord } // SetOperationName sets or changes the operation name. func (span *_Span) SetOperationName(operationName string) opentracing.Span { span.operationName = operationName return span } // SetTag implements SetTag() of opentracing.Span func (span *_Span) SetTag(key string, value interface{}) opentracing.Span { span.tags = append(span.tags, opentracing.Tag{ Key: key, Value: value, }) return span } // LogFields implements opentracing.Span API func (span *_Span) LogFields(fields ...log.Field) { log := opentracing.LogRecord{ Fields: fields, Timestamp: time.Now(), } span.logs = append(span.logs, log) } // LogKV implements opentracing.Span API func (span *_Span) LogKV(alternatingKeyValues ...interface{}) { fields, err := log.InterleavedKVToFields(alternatingKeyValues...) if err != nil { span.LogFields(log.Error(err), log.String("function", "LogKV")) return } span.LogFields(fields...) } // LogEvent implements opentracing.Span API func (span *_Span) LogEvent(event string) { span.Log(opentracing.LogData{Event: event}) } // LogEventWithPayload implements opentracing.Span API func (span *_Span) LogEventWithPayload(event string, payload interface{}) { span.Log(opentracing.LogData{Event: event, Payload: payload}) } // Log implements opentracing.Span API func (span *_Span) Log(ld opentracing.LogData) { span.logs = append(span.logs, ld.ToLogRecord()) } // SetBaggageItem implements SetBaggageItem() of opentracing.SpanContext func (span *_Span) SetBaggageItem(key, value string) opentracing.Span { span.context = span.context.WithBaggageItem(key, value) span.LogFields(log.String("event", "baggage"), log.String("payload", key), log.String("payload", value)) return span } // BaggageItem implements BaggageItem() of opentracing.SpanContext func (span *_Span) BaggageItem(key string) string { return span.context.Baggage[key] } // Finish implements opentracing.Span API func (span *_Span) Finish() { span.FinishWithOptions(opentracing.FinishOptions{}) } // FinishWithOptions implements opentracing.Span API func (span *_Span) FinishWithOptions(options opentracing.FinishOptions) { if options.FinishTime.IsZero() { options.FinishTime = span.tracer.timeNow() } span.duration = options.FinishTime.Sub(span.startTime) if options.LogRecords != nil { span.logs = append(span.logs, options.LogRecords...) } for _, ld := range options.BulkLogData { span.logs = append(span.logs, ld.ToLogRecord()) } span.tracer.DispatchSpan(span) } // Context implements opentracing.Span API func (span *_Span) Context() opentracing.SpanContext { return span.context } /*Tracer returns the tracer*/ func (span *_Span) Tracer() opentracing.Tracer { return span.tracer } /*OperationName allows retrieving current operation name*/ func (span *_Span) OperationName() string { return span.operationName } /*ServiceName returns the name of the service*/ func (span *_Span) ServiceName() string { return span.tracer.serviceName } func (span *_Span) String() string { data, err := json.Marshal(map[string]interface{}{ "traceId": span.context.TraceID, "spanId": span.context.SpanID, "parentSpanId": span.context.ParentID, "operationName": span.OperationName(), "serviceName": span.ServiceName(), "tags": span.Tags(), "logs": span.logs, }) if err != nil { panic(err) } return string(data) } func (span *_Span) Tags() []opentracing.Tag { return span.tags } haystack-client-go-0.2.3/span.pb.go000066400000000000000000000311771344275617100171150ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: span.proto package haystack import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // TagType denotes the type of a Tag's value. type Tag_TagType int32 const ( Tag_STRING Tag_TagType = 0 Tag_DOUBLE Tag_TagType = 1 Tag_BOOL Tag_TagType = 2 Tag_LONG Tag_TagType = 3 Tag_BINARY Tag_TagType = 4 ) var Tag_TagType_name = map[int32]string{ 0: "STRING", 1: "DOUBLE", 2: "BOOL", 3: "LONG", 4: "BINARY", } var Tag_TagType_value = map[string]int32{ "STRING": 0, "DOUBLE": 1, "BOOL": 2, "LONG": 3, "BINARY": 4, } func (x Tag_TagType) String() string { return proto.EnumName(Tag_TagType_name, int32(x)) } func (Tag_TagType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_fc5f2b88b579999f, []int{2, 0} } // Span represents a unit of work performed by a service. type Span struct { TraceId string `protobuf:"bytes,1,opt,name=traceId,proto3" json:"traceId,omitempty"` SpanId string `protobuf:"bytes,2,opt,name=spanId,proto3" json:"spanId,omitempty"` ParentSpanId string `protobuf:"bytes,3,opt,name=parentSpanId,proto3" json:"parentSpanId,omitempty"` ServiceName string `protobuf:"bytes,4,opt,name=serviceName,proto3" json:"serviceName,omitempty"` OperationName string `protobuf:"bytes,5,opt,name=operationName,proto3" json:"operationName,omitempty"` StartTime int64 `protobuf:"varint,6,opt,name=startTime,proto3" json:"startTime,omitempty"` Duration int64 `protobuf:"varint,7,opt,name=duration,proto3" json:"duration,omitempty"` Logs []*Log `protobuf:"bytes,8,rep,name=logs,proto3" json:"logs,omitempty"` Tags []*Tag `protobuf:"bytes,9,rep,name=tags,proto3" json:"tags,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Span) Reset() { *m = Span{} } func (m *Span) String() string { return proto.CompactTextString(m) } func (*Span) ProtoMessage() {} func (*Span) Descriptor() ([]byte, []int) { return fileDescriptor_fc5f2b88b579999f, []int{0} } func (m *Span) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Span.Unmarshal(m, b) } func (m *Span) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Span.Marshal(b, m, deterministic) } func (m *Span) XXX_Merge(src proto.Message) { xxx_messageInfo_Span.Merge(m, src) } func (m *Span) XXX_Size() int { return xxx_messageInfo_Span.Size(m) } func (m *Span) XXX_DiscardUnknown() { xxx_messageInfo_Span.DiscardUnknown(m) } var xxx_messageInfo_Span proto.InternalMessageInfo func (m *Span) GetTraceId() string { if m != nil { return m.TraceId } return "" } func (m *Span) GetSpanId() string { if m != nil { return m.SpanId } return "" } func (m *Span) GetParentSpanId() string { if m != nil { return m.ParentSpanId } return "" } func (m *Span) GetServiceName() string { if m != nil { return m.ServiceName } return "" } func (m *Span) GetOperationName() string { if m != nil { return m.OperationName } return "" } func (m *Span) GetStartTime() int64 { if m != nil { return m.StartTime } return 0 } func (m *Span) GetDuration() int64 { if m != nil { return m.Duration } return 0 } func (m *Span) GetLogs() []*Log { if m != nil { return m.Logs } return nil } func (m *Span) GetTags() []*Tag { if m != nil { return m.Tags } return nil } // Log is a timestamped event with a set of tags. type Log struct { Timestamp int64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` Fields []*Tag `protobuf:"bytes,2,rep,name=fields,proto3" json:"fields,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Log) Reset() { *m = Log{} } func (m *Log) String() string { return proto.CompactTextString(m) } func (*Log) ProtoMessage() {} func (*Log) Descriptor() ([]byte, []int) { return fileDescriptor_fc5f2b88b579999f, []int{1} } func (m *Log) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Log.Unmarshal(m, b) } func (m *Log) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Log.Marshal(b, m, deterministic) } func (m *Log) XXX_Merge(src proto.Message) { xxx_messageInfo_Log.Merge(m, src) } func (m *Log) XXX_Size() int { return xxx_messageInfo_Log.Size(m) } func (m *Log) XXX_DiscardUnknown() { xxx_messageInfo_Log.DiscardUnknown(m) } var xxx_messageInfo_Log proto.InternalMessageInfo func (m *Log) GetTimestamp() int64 { if m != nil { return m.Timestamp } return 0 } func (m *Log) GetFields() []*Tag { if m != nil { return m.Fields } return nil } // Tag is a strongly typed key/value pair. We use 'oneof' protobuf attribute to represent the possible tagTypes type Tag struct { Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Type Tag_TagType `protobuf:"varint,2,opt,name=type,proto3,enum=Tag_TagType" json:"type,omitempty"` // Types that are valid to be assigned to Myvalue: // *Tag_VStr // *Tag_VLong // *Tag_VDouble // *Tag_VBool // *Tag_VBytes Myvalue isTag_Myvalue `protobuf_oneof:"myvalue"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Tag) Reset() { *m = Tag{} } func (m *Tag) String() string { return proto.CompactTextString(m) } func (*Tag) ProtoMessage() {} func (*Tag) Descriptor() ([]byte, []int) { return fileDescriptor_fc5f2b88b579999f, []int{2} } func (m *Tag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Tag.Unmarshal(m, b) } func (m *Tag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Tag.Marshal(b, m, deterministic) } func (m *Tag) XXX_Merge(src proto.Message) { xxx_messageInfo_Tag.Merge(m, src) } func (m *Tag) XXX_Size() int { return xxx_messageInfo_Tag.Size(m) } func (m *Tag) XXX_DiscardUnknown() { xxx_messageInfo_Tag.DiscardUnknown(m) } var xxx_messageInfo_Tag proto.InternalMessageInfo func (m *Tag) GetKey() string { if m != nil { return m.Key } return "" } func (m *Tag) GetType() Tag_TagType { if m != nil { return m.Type } return Tag_STRING } type isTag_Myvalue interface { isTag_Myvalue() } type Tag_VStr struct { VStr string `protobuf:"bytes,3,opt,name=vStr,proto3,oneof"` } type Tag_VLong struct { VLong int64 `protobuf:"varint,4,opt,name=vLong,proto3,oneof"` } type Tag_VDouble struct { VDouble float64 `protobuf:"fixed64,5,opt,name=vDouble,proto3,oneof"` } type Tag_VBool struct { VBool bool `protobuf:"varint,6,opt,name=vBool,proto3,oneof"` } type Tag_VBytes struct { VBytes []byte `protobuf:"bytes,7,opt,name=vBytes,proto3,oneof"` } func (*Tag_VStr) isTag_Myvalue() {} func (*Tag_VLong) isTag_Myvalue() {} func (*Tag_VDouble) isTag_Myvalue() {} func (*Tag_VBool) isTag_Myvalue() {} func (*Tag_VBytes) isTag_Myvalue() {} func (m *Tag) GetMyvalue() isTag_Myvalue { if m != nil { return m.Myvalue } return nil } func (m *Tag) GetVStr() string { if x, ok := m.GetMyvalue().(*Tag_VStr); ok { return x.VStr } return "" } func (m *Tag) GetVLong() int64 { if x, ok := m.GetMyvalue().(*Tag_VLong); ok { return x.VLong } return 0 } func (m *Tag) GetVDouble() float64 { if x, ok := m.GetMyvalue().(*Tag_VDouble); ok { return x.VDouble } return 0 } func (m *Tag) GetVBool() bool { if x, ok := m.GetMyvalue().(*Tag_VBool); ok { return x.VBool } return false } func (m *Tag) GetVBytes() []byte { if x, ok := m.GetMyvalue().(*Tag_VBytes); ok { return x.VBytes } return nil } // XXX_OneofWrappers is for the internal use of the proto package. func (*Tag) XXX_OneofWrappers() []interface{} { return []interface{}{ (*Tag_VStr)(nil), (*Tag_VLong)(nil), (*Tag_VDouble)(nil), (*Tag_VBool)(nil), (*Tag_VBytes)(nil), } } // You can optionally use Batch to send a collection of spans. Spans may not necessarily belong to one traceId. type Batch struct { Spans []*Span `protobuf:"bytes,1,rep,name=spans,proto3" json:"spans,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Batch) Reset() { *m = Batch{} } func (m *Batch) String() string { return proto.CompactTextString(m) } func (*Batch) ProtoMessage() {} func (*Batch) Descriptor() ([]byte, []int) { return fileDescriptor_fc5f2b88b579999f, []int{3} } func (m *Batch) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Batch.Unmarshal(m, b) } func (m *Batch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Batch.Marshal(b, m, deterministic) } func (m *Batch) XXX_Merge(src proto.Message) { xxx_messageInfo_Batch.Merge(m, src) } func (m *Batch) XXX_Size() int { return xxx_messageInfo_Batch.Size(m) } func (m *Batch) XXX_DiscardUnknown() { xxx_messageInfo_Batch.DiscardUnknown(m) } var xxx_messageInfo_Batch proto.InternalMessageInfo func (m *Batch) GetSpans() []*Span { if m != nil { return m.Spans } return nil } func init() { proto.RegisterEnum("Tag_TagType", Tag_TagType_name, Tag_TagType_value) proto.RegisterType((*Span)(nil), "Span") proto.RegisterType((*Log)(nil), "Log") proto.RegisterType((*Tag)(nil), "Tag") proto.RegisterType((*Batch)(nil), "Batch") } func init() { proto.RegisterFile("span.proto", fileDescriptor_fc5f2b88b579999f) } var fileDescriptor_fc5f2b88b579999f = []byte{ // 456 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x92, 0xcd, 0x8a, 0x9c, 0x40, 0x14, 0x85, 0xdb, 0xf6, 0xb7, 0xef, 0x74, 0x82, 0x14, 0x61, 0x28, 0x26, 0xb3, 0x10, 0x19, 0x42, 0xaf, 0x5c, 0x4c, 0x9e, 0xa0, 0x65, 0xc2, 0x74, 0x83, 0x74, 0x87, 0x6a, 0xb3, 0x48, 0x76, 0x35, 0x5a, 0x71, 0x64, 0xd4, 0x2a, 0xac, 0x6a, 0x89, 0xeb, 0xbc, 0x41, 0x9e, 0x38, 0x54, 0xe9, 0xfc, 0x2d, 0x84, 0x7b, 0xbe, 0x73, 0xaf, 0xca, 0xe1, 0x00, 0x48, 0x41, 0xbb, 0x44, 0xf4, 0x5c, 0xf1, 0xf8, 0xdf, 0x12, 0x9c, 0x93, 0xa0, 0x1d, 0xc2, 0xe0, 0xab, 0x9e, 0x16, 0x6c, 0x5f, 0x62, 0x2b, 0xb2, 0x36, 0x2b, 0xf2, 0x2c, 0xd1, 0x25, 0x78, 0xfa, 0x60, 0x5f, 0xe2, 0xa5, 0x31, 0x66, 0x85, 0x62, 0x58, 0x0b, 0xda, 0xb3, 0x4e, 0x9d, 0x26, 0xd7, 0x36, 0xee, 0x3b, 0x86, 0x22, 0xb8, 0x90, 0xac, 0x1f, 0xea, 0x82, 0x1d, 0x68, 0xcb, 0xb0, 0x63, 0x56, 0xde, 0x22, 0x74, 0x03, 0x1f, 0xb8, 0x60, 0x3d, 0x55, 0x35, 0xef, 0xcc, 0x8e, 0x6b, 0x76, 0xde, 0x43, 0x74, 0x0d, 0x2b, 0xa9, 0x68, 0xaf, 0xf2, 0xba, 0x65, 0xd8, 0x8b, 0xac, 0x8d, 0x4d, 0x5e, 0x01, 0xba, 0x82, 0xa0, 0x3c, 0x4f, 0xdb, 0xd8, 0x37, 0xe6, 0x8b, 0x46, 0x18, 0x9c, 0x86, 0x57, 0x12, 0x07, 0x91, 0xbd, 0xb9, 0xb8, 0x75, 0x92, 0x8c, 0x57, 0xc4, 0x10, 0xed, 0x28, 0x5a, 0x49, 0xbc, 0x9a, 0x9d, 0x9c, 0x56, 0xc4, 0x90, 0x78, 0x0b, 0x76, 0xc6, 0x2b, 0xfd, 0x51, 0x55, 0xb7, 0x4c, 0x2a, 0xda, 0x0a, 0x13, 0x8a, 0x4d, 0x5e, 0x01, 0xba, 0x06, 0xef, 0x77, 0xcd, 0x9a, 0x52, 0xe2, 0xe5, 0x9b, 0x17, 0xcc, 0x2c, 0xfe, 0xbb, 0x04, 0x3b, 0xa7, 0x15, 0x0a, 0xc1, 0x7e, 0x62, 0xe3, 0x1c, 0xa9, 0x1e, 0x51, 0x04, 0x8e, 0x1a, 0x05, 0x33, 0x61, 0x7e, 0xbc, 0x5d, 0xeb, 0x2b, 0xfd, 0xe4, 0xa3, 0x60, 0xc4, 0x38, 0xe8, 0x13, 0x38, 0xc3, 0x49, 0xf5, 0x53, 0xa0, 0xbb, 0x05, 0x31, 0x0a, 0x5d, 0x82, 0x3b, 0x64, 0xbc, 0xab, 0x4c, 0x88, 0xf6, 0x6e, 0x41, 0x26, 0x89, 0xae, 0xc0, 0x1f, 0xee, 0xf8, 0xf9, 0xa1, 0x99, 0xa2, 0xb3, 0x76, 0x0b, 0xf2, 0x0c, 0xcc, 0x4d, 0xca, 0x79, 0x63, 0x22, 0x0b, 0xcc, 0x8d, 0x96, 0x08, 0x83, 0x37, 0xa4, 0xa3, 0x62, 0xd2, 0xc4, 0xb5, 0xde, 0x2d, 0xc8, 0xac, 0xe3, 0x2d, 0xf8, 0xf3, 0xcf, 0x20, 0x00, 0xef, 0x94, 0x93, 0xfd, 0xe1, 0x3e, 0x5c, 0xe8, 0xf9, 0xee, 0xf8, 0x23, 0xcd, 0xbe, 0x85, 0x16, 0x0a, 0xc0, 0x49, 0x8f, 0xc7, 0x2c, 0x5c, 0xea, 0x29, 0x3b, 0x1e, 0xee, 0x43, 0x5b, 0xfb, 0xe9, 0xfe, 0xb0, 0x25, 0x3f, 0x43, 0x27, 0x5d, 0x81, 0xdf, 0x8e, 0x03, 0x6d, 0xce, 0x2c, 0xbe, 0x01, 0x37, 0xa5, 0xaa, 0x78, 0x44, 0x9f, 0xc1, 0xd5, 0xad, 0x91, 0xd8, 0x32, 0x59, 0xb9, 0x89, 0xee, 0x07, 0x99, 0x58, 0xfa, 0x05, 0x70, 0xc1, 0xdb, 0x84, 0xfd, 0x11, 0xac, 0xac, 0x69, 0xc2, 0x05, 0xeb, 0x12, 0x5d, 0xbe, 0xba, 0xab, 0xbe, 0x5b, 0xbf, 0x82, 0x47, 0x3a, 0x4a, 0x45, 0x8b, 0xa7, 0x07, 0xcf, 0x54, 0xf6, 0xeb, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdd, 0x60, 0xee, 0x6b, 0xc0, 0x02, 0x00, 0x00, } haystack-client-go-0.2.3/spanAgent.pb.go000066400000000000000000000160331344275617100200660ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: spanAgent.proto package haystack import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" grpc "google.golang.org/grpc" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type DispatchResult_ResultCode int32 const ( DispatchResult_SUCCESS DispatchResult_ResultCode = 0 DispatchResult_UNKNOWN_ERROR DispatchResult_ResultCode = 1 DispatchResult_RATE_LIMIT_ERROR DispatchResult_ResultCode = 2 ) var DispatchResult_ResultCode_name = map[int32]string{ 0: "SUCCESS", 1: "UNKNOWN_ERROR", 2: "RATE_LIMIT_ERROR", } var DispatchResult_ResultCode_value = map[string]int32{ "SUCCESS": 0, "UNKNOWN_ERROR": 1, "RATE_LIMIT_ERROR": 2, } func (x DispatchResult_ResultCode) String() string { return proto.EnumName(DispatchResult_ResultCode_name, int32(x)) } func (DispatchResult_ResultCode) EnumDescriptor() ([]byte, []int) { return fileDescriptor_5a4cb81dd7dcc459, []int{0, 0} } type DispatchResult struct { Code DispatchResult_ResultCode `protobuf:"varint,1,opt,name=code,proto3,enum=DispatchResult_ResultCode" json:"code,omitempty"` ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *DispatchResult) Reset() { *m = DispatchResult{} } func (m *DispatchResult) String() string { return proto.CompactTextString(m) } func (*DispatchResult) ProtoMessage() {} func (*DispatchResult) Descriptor() ([]byte, []int) { return fileDescriptor_5a4cb81dd7dcc459, []int{0} } func (m *DispatchResult) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_DispatchResult.Unmarshal(m, b) } func (m *DispatchResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_DispatchResult.Marshal(b, m, deterministic) } func (m *DispatchResult) XXX_Merge(src proto.Message) { xxx_messageInfo_DispatchResult.Merge(m, src) } func (m *DispatchResult) XXX_Size() int { return xxx_messageInfo_DispatchResult.Size(m) } func (m *DispatchResult) XXX_DiscardUnknown() { xxx_messageInfo_DispatchResult.DiscardUnknown(m) } var xxx_messageInfo_DispatchResult proto.InternalMessageInfo func (m *DispatchResult) GetCode() DispatchResult_ResultCode { if m != nil { return m.Code } return DispatchResult_SUCCESS } func (m *DispatchResult) GetErrorMessage() string { if m != nil { return m.ErrorMessage } return "" } func init() { proto.RegisterEnum("DispatchResult_ResultCode", DispatchResult_ResultCode_name, DispatchResult_ResultCode_value) proto.RegisterType((*DispatchResult)(nil), "DispatchResult") } func init() { proto.RegisterFile("spanAgent.proto", fileDescriptor_5a4cb81dd7dcc459) } var fileDescriptor_5a4cb81dd7dcc459 = []byte{ // 254 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0xc1, 0x4a, 0xf3, 0x40, 0x10, 0xc7, 0xbf, 0x2d, 0x9f, 0xda, 0x8e, 0xb6, 0x8d, 0x8b, 0x87, 0x92, 0x53, 0x89, 0x97, 0x9e, 0x56, 0xa9, 0x4f, 0xd0, 0xc6, 0x1c, 0x8a, 0x36, 0x95, 0x4d, 0x8b, 0xe0, 0x25, 0x8c, 0x9b, 0x21, 0x0d, 0xda, 0xec, 0xb2, 0xbb, 0x82, 0x3e, 0x92, 0x6f, 0x29, 0x4d, 0x2a, 0xa2, 0xa7, 0x19, 0x7e, 0x33, 0x03, 0xff, 0xf9, 0xc1, 0xd0, 0x19, 0xac, 0x67, 0x25, 0xd5, 0x5e, 0x18, 0xab, 0xbd, 0x0e, 0x61, 0x0f, 0xda, 0x3e, 0xfa, 0x64, 0x30, 0xb8, 0xad, 0x9c, 0x41, 0xaf, 0xb6, 0x92, 0xdc, 0xdb, 0xab, 0xe7, 0x02, 0xfe, 0x2b, 0x5d, 0xd0, 0x88, 0x8d, 0xd9, 0x64, 0x30, 0x0d, 0xc5, 0xef, 0xb1, 0x68, 0x4b, 0xac, 0x0b, 0x92, 0xcd, 0x1e, 0xbf, 0x84, 0x3e, 0x59, 0xab, 0x6d, 0xbe, 0x23, 0xe7, 0xb0, 0xa4, 0x51, 0x67, 0xcc, 0x26, 0x3d, 0x79, 0xd6, 0xc0, 0x65, 0xcb, 0xa2, 0x39, 0xc0, 0xcf, 0x21, 0x3f, 0x85, 0x93, 0x6c, 0x13, 0xc7, 0x49, 0x96, 0x05, 0xff, 0xf8, 0x39, 0xf4, 0x37, 0xe9, 0x5d, 0xba, 0x7a, 0x4c, 0xf3, 0x44, 0xca, 0x95, 0x0c, 0x18, 0xbf, 0x80, 0x40, 0xce, 0xd6, 0x49, 0x7e, 0xbf, 0x58, 0x2e, 0xd6, 0x07, 0xda, 0x99, 0x5e, 0x41, 0x2f, 0xfb, 0x7e, 0x85, 0x47, 0xd0, 0x2d, 0x0e, 0xc1, 0xf8, 0x91, 0xd8, 0xf3, 0x70, 0xf8, 0x27, 0xea, 0xfc, 0x1a, 0x22, 0xa5, 0x77, 0x82, 0xde, 0x0d, 0x15, 0x15, 0x0a, 0x6d, 0xa8, 0x16, 0xde, 0xa2, 0xaa, 0xea, 0x52, 0x60, 0x23, 0x04, 0x4d, 0xf5, 0xc0, 0x9e, 0xba, 0x5b, 0xfc, 0x70, 0x1e, 0xd5, 0xcb, 0xf3, 0x71, 0x63, 0xe5, 0xe6, 0x2b, 0x00, 0x00, 0xff, 0xff, 0x30, 0xb9, 0x7d, 0x07, 0x34, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // SpanAgentClient is the client API for SpanAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type SpanAgentClient interface { Dispatch(ctx context.Context, in *Span, opts ...grpc.CallOption) (*DispatchResult, error) } type spanAgentClient struct { cc *grpc.ClientConn } func NewSpanAgentClient(cc *grpc.ClientConn) SpanAgentClient { return &spanAgentClient{cc} } func (c *spanAgentClient) Dispatch(ctx context.Context, in *Span, opts ...grpc.CallOption) (*DispatchResult, error) { out := new(DispatchResult) err := c.cc.Invoke(ctx, "/SpanAgent/dispatch", in, out, opts...) if err != nil { return nil, err } return out, nil } // SpanAgentServer is the server API for SpanAgent service. type SpanAgentServer interface { Dispatch(context.Context, *Span) (*DispatchResult, error) } func RegisterSpanAgentServer(s *grpc.Server, srv SpanAgentServer) { s.RegisterService(&_SpanAgent_serviceDesc, srv) } func _SpanAgent_Dispatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Span) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SpanAgentServer).Dispatch(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/SpanAgent/Dispatch", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SpanAgentServer).Dispatch(ctx, req.(*Span)) } return interceptor(ctx, in, info, handler) } var _SpanAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "SpanAgent", HandlerType: (*SpanAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "dispatch", Handler: _SpanAgent_Dispatch_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "spanAgent.proto", } haystack-client-go-0.2.3/span_context.go000066400000000000000000000043311344275617100202510ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "fmt" ) /*SpanContext implements opentracing.spanContext*/ type SpanContext struct { // traceID represents globally unique ID of the trace. TraceID string // spanID represents span ID that must be unique within its trace SpanID string // parentID refers to the ID of the parent span. // Should be empty if the current span is a root span. ParentID string //Context baggage. The is a snapshot in time. Baggage map[string]string // set to true if extracted using a extractor in tracer IsExtractedContext bool } // IsValid indicates whether this context actually represents a valid trace. func (context SpanContext) IsValid() bool { return context.TraceID != "" && context.SpanID != "" } /*ForeachBaggageItem implements opentracing.spancontext*/ func (context SpanContext) ForeachBaggageItem(handler func(k, v string) bool) { for k, v := range context.Baggage { if !handler(k, v) { break } } } // WithBaggageItem creates a new context with an extra baggage item. func (context SpanContext) WithBaggageItem(key, value string) *SpanContext { var newBaggage map[string]string if context.Baggage == nil { newBaggage = map[string]string{key: value} } else { newBaggage = make(map[string]string, len(context.Baggage)+1) for k, v := range context.Baggage { newBaggage[k] = v } newBaggage[key] = value } return &SpanContext{ TraceID: context.TraceID, SpanID: context.SpanID, ParentID: context.ParentID, Baggage: newBaggage, } } /*ToString represents the string*/ func (context SpanContext) ToString() string { return fmt.Sprintf("%+v", context) } haystack-client-go-0.2.3/span_test.go000066400000000000000000000054231344275617100175470ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "io" "testing" opentracing "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/suite" ) type SpanTestSuite struct { suite.Suite tracer opentracing.Tracer closer io.Closer dispatcher Dispatcher } func (suite *SpanTestSuite) SetupTest() { suite.dispatcher = NewInMemoryDispatcher() tracer, closer := NewTracer("my-service", suite.dispatcher, TracerOptionsFactory.Tag("t1", "v1")) suite.tracer = tracer suite.closer = closer } func (suite *SpanTestSuite) TearDownTest() { if suite.tracer != nil { err := suite.closer.Close() if err != nil { panic(err) } } } func (suite *SpanTestSuite) TestSpanProperties() { sp1 := suite.tracer.StartSpan("op1").(*_Span) suite.Equal(sp1.ServiceName(), "my-service") suite.Len(sp1.Tags(), 1) suite.Equal(sp1.Tags()[0].Key, "t1") suite.Equal(sp1.Tags()[0].Value.(string), "v1") suite.Equal("op1", sp1.OperationName()) suite.Equal(suite.tracer, sp1.Tracer()) suite.NotNil(sp1.Context()) } func (suite *SpanTestSuite) TestBaggageIterator() { span1 := suite.tracer.StartSpan("sp1").(*_Span) span1.SetBaggageItem("bk1", "something") span1.SetBaggageItem("bk2", "100") expectedBaggage := map[string]string{"bk1": "something", "bk2": "100"} suite.Equal(expectedBaggage, extractBaggage(span1)) assertBaggageRecords(suite, span1, expectedBaggage) span2 := suite.tracer.StartSpan("sp2", opentracing.ChildOf(span1.Context())).(*_Span) suite.Equal(expectedBaggage, extractBaggage(span2)) } func extractBaggage(sp opentracing.Span) map[string]string { b := make(map[string]string) sp.Context().ForeachBaggageItem(func(k, v string) bool { b[k] = v return true }) return b } func assertBaggageRecords(suite *SpanTestSuite, sp *_Span, expected map[string]string) { suite.Len(sp.logs, len(expected)) for _, logRecord := range sp.logs { suite.Len(logRecord.Fields, 3) suite.Equal("event:baggage", logRecord.Fields[0].String()) key := logRecord.Fields[1].Value().(string) value := logRecord.Fields[2].Value().(string) suite.Contains(expected, key) suite.Equal(expected[key], value) } } func TestUnitSpanSuite(t *testing.T) { suite.Run(t, new(SpanTestSuite)) } haystack-client-go-0.2.3/tracer.go000066400000000000000000000131601344275617100170240ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "io" "time" "github.com/google/uuid" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) /*Tracer implements the opentracing.tracer*/ type Tracer struct { serviceName string logger Logger dispatcher Dispatcher commonTags []opentracing.Tag timeNow func() time.Time idGenerator func() string propagators map[interface{}]Propagator useDualSpanMode bool } /*NewTracer creates a new tracer*/ func NewTracer( serviceName string, dispatcher Dispatcher, options ...TracerOption, ) (opentracing.Tracer, io.Closer) { tracer := &Tracer{ serviceName: serviceName, dispatcher: dispatcher, useDualSpanMode: false, } tracer.propagators = make(map[interface{}]Propagator) tracer.propagators[opentracing.TextMap] = NewDefaultTextMapPropagator() tracer.propagators[opentracing.HTTPHeaders] = NewTextMapPropagator(PropagatorOpts{}, URLCodex{}) for _, option := range options { option(tracer) } if tracer.timeNow == nil { tracer.timeNow = time.Now } if tracer.logger == nil { tracer.logger = NullLogger{} } if tracer.idGenerator == nil { tracer.idGenerator = func() string { _uuid, err := uuid.NewUUID() if err != nil { panic(err) } return _uuid.String() } } dispatcher.SetLogger(tracer.logger) return tracer, tracer } /*StartSpan starts a new span*/ func (tracer *Tracer) StartSpan( operationName string, options ...opentracing.StartSpanOption, ) opentracing.Span { sso := opentracing.StartSpanOptions{} for _, o := range options { o.Apply(&sso) } if sso.StartTime.IsZero() { sso.StartTime = tracer.timeNow() } var followsFromIsParent = false var parent *SpanContext for _, ref := range sso.References { if ref.Type == opentracing.ChildOfRef { if parent == nil || followsFromIsParent { parent = ref.ReferencedContext.(*SpanContext) } } else if ref.Type == opentracing.FollowsFromRef { if parent == nil { parent = ref.ReferencedContext.(*SpanContext) followsFromIsParent = true } } } spanContext := tracer.createSpanContext(parent, tracer.isServerSpan(sso.Tags)) span := &_Span{ tracer: tracer, context: spanContext, operationName: operationName, startTime: sso.StartTime, duration: 0, } for _, tag := range tracer.Tags() { span.SetTag(tag.Key, tag.Value) } for k, v := range sso.Tags { span.SetTag(k, v) } return span } func (tracer *Tracer) isServerSpan(spanTags map[string]interface{}) bool { if spanKind, ok := spanTags[string(ext.SpanKind)]; ok && spanKind == "server" { return true } return false } func (tracer *Tracer) createSpanContext(parent *SpanContext, isServerSpan bool) *SpanContext { if parent == nil || !parent.IsValid() { return &SpanContext{ TraceID: tracer.idGenerator(), SpanID: tracer.idGenerator(), } } // This is a check to see if the tracer is configured to support single // single span type (Zipkin style shared span id) or // dual span type (client and server having their own span ids ). // a. If tracer is not of dualSpanType and if it is a server span then we // just return the parent context with the same shared span ids // b. If tracer is not of dualSpanType and if the parent context is an extracted one from the wire // then we assume this is the first span in the server and so just return the parent context // with the same shared span ids if !tracer.useDualSpanMode && (isServerSpan || parent.IsExtractedContext) { return &SpanContext{ TraceID: parent.TraceID, SpanID: parent.SpanID, ParentID: parent.ParentID, Baggage: parent.Baggage, IsExtractedContext: false, } } return &SpanContext{ TraceID: parent.TraceID, SpanID: tracer.idGenerator(), ParentID: parent.SpanID, Baggage: parent.Baggage, IsExtractedContext: false, } } /*Inject implements Inject() method of opentracing.Tracer*/ func (tracer *Tracer) Inject(ctx opentracing.SpanContext, format interface{}, carrier interface{}) error { c, ok := ctx.(*SpanContext) if !ok { return opentracing.ErrInvalidSpanContext } if injector, ok := tracer.propagators[format]; ok { return injector.Inject(c, carrier) } return opentracing.ErrUnsupportedFormat } /*Extract implements Extract() method of opentracing.Tracer*/ func (tracer *Tracer) Extract( format interface{}, carrier interface{}, ) (opentracing.SpanContext, error) { if extractor, ok := tracer.propagators[format]; ok { return extractor.Extract(carrier) } return nil, opentracing.ErrUnsupportedFormat } /*Tags return all common tags */ func (tracer *Tracer) Tags() []opentracing.Tag { return tracer.commonTags } /*DispatchSpan dispatches the span to a dispatcher*/ func (tracer *Tracer) DispatchSpan(span *_Span) { if tracer.dispatcher != nil { tracer.dispatcher.Dispatch(span) } } /*Close closes the tracer*/ func (tracer *Tracer) Close() error { if tracer.dispatcher != nil { tracer.dispatcher.Close() } return nil } haystack-client-go-0.2.3/tracer_options.go000066400000000000000000000033621344275617100206020ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "github.com/opentracing/opentracing-go" ) // TracerOption is a function that sets some option on the tracer type TracerOption func(tracer *Tracer) /*TracerOptions a list of tracer options*/ type TracerOptions struct{} /*TracerOptionsFactory factory to create multiple tracer options*/ var TracerOptionsFactory TracerOptions /*Propagator registers a new Propagator*/ func (t TracerOptions) Propagator(format interface{}, propagator Propagator) TracerOption { return func(tracer *Tracer) { tracer.propagators[format] = propagator } } /*Tag adds a common tag in every span*/ func (t TracerOptions) Tag(key string, value interface{}) TracerOption { return func(tracer *Tracer) { tracer.commonTags = append(tracer.commonTags, opentracing.Tag{Key: key, Value: value}) } } /*Logger set the logger type*/ func (t TracerOptions) Logger(logger Logger) TracerOption { return func(tracer *Tracer) { tracer.logger = logger } } /*UseDualSpanMode sets the tracer in dual span mode*/ func (t TracerOptions) UseDualSpanMode() TracerOption { return func(tracer *Tracer) { tracer.useDualSpanMode = true } } haystack-client-go-0.2.3/tracer_test.go000066400000000000000000000240571344275617100200720ustar00rootroot00000000000000/* * Copyright 2018 Expedia Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package haystack import ( "io" "strings" "testing" opentracing "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/suite" ) type TracerTestSuite struct { suite.Suite tracer opentracing.Tracer closer io.Closer dualSpanModeTracer opentracing.Tracer dualSpanTracerCloser io.Closer dispatcher Dispatcher } func (suite *TracerTestSuite) SetupTest() { suite.dispatcher = NewInMemoryDispatcher() tracer, closer := NewTracer("my-service", suite.dispatcher, TracerOptionsFactory.Tag("t1", "v1")) dualSpanModeTracer, dualSpanTracerCloser := NewTracer("my-service", suite.dispatcher, TracerOptionsFactory.Tag("t1", "v1"), TracerOptionsFactory.UseDualSpanMode()) suite.tracer = tracer suite.closer = closer suite.dualSpanModeTracer = dualSpanModeTracer suite.dualSpanTracerCloser = dualSpanTracerCloser } func (suite *TracerTestSuite) TearDownTest() { if suite.tracer != nil { err := suite.closer.Close() if err != nil { panic(err) } } if suite.dualSpanTracerCloser != nil { err := suite.dualSpanTracerCloser.Close() if err != nil { panic(err) } } } func (suite *TracerTestSuite) TestTracerProperties() { tag := opentracing.Tag{Key: "user_agent", Value: "ua"} span1 := suite.tracer.StartSpan("op1", tag) span2 := suite.tracer.StartSpan("op2", opentracing.ChildOf(span1.Context()), tag) span2.Finish() span1.Finish() dispatcher := suite.dispatcher.(*InMemoryDispatcher) suite.Len(dispatcher.spans, 2, "2 spans should be dispatched") childSpan := dispatcher.spans[0] childSpanContext := childSpan.Context().(*SpanContext) parentSpan := dispatcher.spans[1] parentSpanContext := parentSpan.Context().(*SpanContext) suite.Equal(parentSpanContext.TraceID, childSpanContext.TraceID, "trace id should match for both parent and child span") suite.Equal(parentSpanContext.SpanID, childSpanContext.ParentID, "parent id should match for parent and child span") suite.NotEqual(parentSpanContext.SpanID, childSpanContext.SpanID, "span id should be unique for parent and child span") for _, span := range dispatcher.spans { suite.Len(span.Tags(), 2, "1 tag should be present on the span") suite.Equal(span.Tags()[0], opentracing.Tag{Key: "t1", Value: "v1"}, "tag key should be t1") suite.Equal(span.Tags()[1], tag, "tag key should be user_agent") } } func (suite *TracerTestSuite) TestTracerWithDualSpanMode_1() { serverTag := opentracing.Tag{Key: "span.kind", Value: "server"} clientTag := opentracing.Tag{Key: "span.kind", Value: "client"} headerMap := map[string]string{ "trace-id": "T1", "Span-ID": "S1", "Parent-ID": "P1", "Baggage-myKey": "myVal", "baggage-mykey-1": "myval", } upstreamSpanContext, _ := suite.dualSpanModeTracer.Extract(opentracing.HTTPHeaders, buildHTTPHeaderCarrier(headerMap)) serverSpan := suite.dualSpanModeTracer.StartSpan("op1", serverTag, opentracing.ChildOf(upstreamSpanContext)) clientSpan := suite.dualSpanModeTracer.StartSpan("op2", clientTag, opentracing.ChildOf(serverSpan.Context())) clientSpan.Finish() serverSpan.Finish() dispatcher := suite.dispatcher.(*InMemoryDispatcher) suite.Len(dispatcher.spans, 2, "2 spans should be dispatched") receivedClientSpan := dispatcher.spans[0] receivedClientSpanCtx := receivedClientSpan.Context().(*SpanContext) receivedServerSpan := dispatcher.spans[1] receivedServerSpanCtx := receivedServerSpan.Context().(*SpanContext) suite.Equal(receivedServerSpanCtx.TraceID, "T1", "Trace Ids should match") suite.Equal(receivedServerSpanCtx.Baggage[strings.ToLower("myKey")], "myVal", "baggage key should match") suite.Equal(receivedServerSpanCtx.Baggage[strings.ToLower("mykey-1")], "myval", "baggage lowercase key should match") suite.NotEqual(receivedServerSpanCtx.SpanID, "S1", "SpanId should be newly created") suite.NotEqual(receivedServerSpanCtx.SpanID, "P1", "SpanId should be newly created") suite.NotEqual(receivedServerSpanCtx.SpanID, "T1", "SpanId should be newly created") suite.Equal(receivedServerSpanCtx.ParentID, "S1", "Parent Ids should match") suite.Equal(receivedServerSpan.Tags()[1], serverTag, "span.kind tag should be present and equal to server") suite.Equal(receivedClientSpanCtx.TraceID, "T1", "Parent Ids should match") suite.NotEqual(receivedClientSpanCtx.SpanID, receivedServerSpanCtx.SpanID, "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, receivedServerSpanCtx.SpanID, "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, receivedServerSpanCtx.SpanID, "SpanId should be newly created") suite.Equal(receivedClientSpanCtx.ParentID, receivedServerSpanCtx.SpanID, "Parent Ids should match") suite.Equal(receivedClientSpan.Tags()[1], clientTag, "span.kind tag should be present and equal to client") } func (suite *TracerTestSuite) TestTracerWithSingleSpanMode_1() { serverTag := opentracing.Tag{Key: "span.kind", Value: "server"} clientTag := opentracing.Tag{Key: "span.kind", Value: "client"} headerMap := map[string]string{ "Trace-ID": "T1", "Span-ID": "S1", "Parent-ID": "P1", } upstreamSpanContext, _ := suite.tracer.Extract(opentracing.HTTPHeaders, buildHTTPHeaderCarrier(headerMap)) serverSpan := suite.tracer.StartSpan("op1", serverTag, opentracing.ChildOf(upstreamSpanContext)) clientSpan := suite.tracer.StartSpan("op2", clientTag, opentracing.ChildOf(serverSpan.Context())) clientSpan.Finish() serverSpan.Finish() dispatcher := suite.dispatcher.(*InMemoryDispatcher) suite.Len(dispatcher.spans, 2, "2 spans should be dispatched") receivedClientSpan := dispatcher.spans[0] receivedClientSpanCtx := receivedClientSpan.Context().(*SpanContext) receivedServerSpan := dispatcher.spans[1] receivedServerSpanCtx := receivedServerSpan.Context().(*SpanContext) suite.Equal(receivedServerSpanCtx.TraceID, "T1", "Trace Ids should match") suite.Equal(receivedServerSpanCtx.SpanID, "S1", "Span Ids should match") suite.Equal(receivedServerSpanCtx.ParentID, "P1", "Parent Ids should match") suite.Equal(receivedServerSpan.Tags()[1], serverTag, "span.kind tag should be present and equal to server") suite.Equal(receivedClientSpanCtx.TraceID, "T1", "Parent Ids should match") suite.NotEqual(receivedClientSpanCtx.SpanID, "S1", "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, "P1", "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, "T1", "SpanId should be newly created") suite.Equal(receivedClientSpanCtx.ParentID, "S1", "Parent Ids should match") suite.Equal(receivedClientSpan.Tags()[1], clientTag, "span.kind tag should be present and equal to client") } func (suite *TracerTestSuite) TestTracerWithSingleSpanMode_2() { serverTag := opentracing.Tag{Key: "error", Value: true} clientTag := opentracing.Tag{Key: "error", Value: false} headerMap := map[string]string{ "Trace-ID": "T1", "Span-ID": "S1", "Parent-ID": "P1", } upstreamSpanContext, _ := suite.tracer.Extract(opentracing.HTTPHeaders, buildHTTPHeaderCarrier(headerMap)) serverSpan := suite.tracer.StartSpan("op1", serverTag, opentracing.ChildOf(upstreamSpanContext)) clientSpan := suite.tracer.StartSpan("op2", clientTag, opentracing.ChildOf(serverSpan.Context())) clientSpan.Finish() serverSpan.Finish() dispatcher := suite.dispatcher.(*InMemoryDispatcher) suite.Len(dispatcher.spans, 2, "2 spans should be dispatched") receivedClientSpan := dispatcher.spans[0] receivedClientSpanCtx := receivedClientSpan.Context().(*SpanContext) receivedServerSpan := dispatcher.spans[1] receivedServerSpanCtx := receivedServerSpan.Context().(*SpanContext) suite.Equal(receivedServerSpanCtx.TraceID, "T1", "Trace Ids should match") suite.Equal(receivedServerSpanCtx.SpanID, "S1", "Span Ids should match") suite.Equal(receivedServerSpanCtx.ParentID, "P1", "Parent Ids should match") suite.Equal(receivedServerSpan.Tags()[1].Key, "error", "error tag should be present") suite.Equal(receivedServerSpan.Tags()[1].Value, true, "error tag should be true") suite.Equal(receivedClientSpanCtx.TraceID, "T1", "Parent Ids should match") suite.NotEqual(receivedClientSpanCtx.SpanID, "S1", "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, "P1", "SpanId should be newly created") suite.NotEqual(receivedClientSpanCtx.SpanID, "T1", "SpanId should be newly created") suite.Equal(receivedClientSpanCtx.ParentID, "S1", "Parent Ids should match") suite.Equal(receivedClientSpan.Tags()[1].Key, "error", "error tag should be present") suite.Equal(receivedClientSpan.Tags()[1].Value, false, "error tag should be false") } func (suite *TracerTestSuite) TestTracerInject() { carrier := opentracing.HTTPHeadersCarrier(make(map[string][]string)) span1 := suite.tracer.StartSpan("op1") err := suite.tracer.Inject(span1.Context(), opentracing.HTTPHeaders, carrier) if err != nil { panic(err) } suite.Len(carrier, 3, "trace-id, span-id, parent-id should be injected in the http headers") ctx, err := suite.tracer.Extract(opentracing.HTTPHeaders, carrier) if err != nil { panic(err) } suite.NotEqual("", ctx.(*SpanContext).TraceID) suite.NotEqual("", ctx.(*SpanContext).SpanID) suite.Equal("", ctx.(*SpanContext).ParentID) suite.Equal(true, ctx.(*SpanContext).IsExtractedContext) } func buildHTTPHeaderCarrier(headerMap map[string]string) *opentracing.HTTPHeadersCarrier { httpHeaderCarrier := opentracing.HTTPHeadersCarrier(make(map[string][]string)) for k, v := range headerMap { httpHeaderCarrier.Set(k, v) } return &httpHeaderCarrier } func TestUnitTracerSuite(t *testing.T) { suite.Run(t, new(TracerTestSuite)) }