1
0
Fork 0

Added support for Haystack tracing

This commit is contained in:
Alex Antonov 2019-05-08 17:14:04 -05:00 committed by Traefiker Bot
parent 681892148e
commit 9cf6827ccc
274 changed files with 38070 additions and 13436 deletions

View file

@ -0,0 +1,201 @@
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.

View file

@ -0,0 +1,356 @@
/*
* 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))
}
}

View file

@ -0,0 +1,37 @@
/*
* 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{}) {}

View file

@ -0,0 +1,193 @@
/*
* 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,
}
}

View file

@ -0,0 +1,165 @@
/*
* 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
}

View file

@ -0,0 +1,164 @@
/*
* 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
}

View file

@ -0,0 +1,433 @@
// 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, 0x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ff, 0x00, 0x00, 0x00, 0xff, 0xff,
0xdd, 0x60, 0xee, 0x6b, 0xc0, 0x02, 0x00, 0x00,
}

View file

@ -0,0 +1,197 @@
// 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,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 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",
}

View file

@ -0,0 +1,80 @@
/*
* 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)
}

View file

@ -0,0 +1,214 @@
/*
* 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
}

View file

@ -0,0 +1,59 @@
/*
* 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
}
}