2020-01-18 13:20:46 +03:00
|
|
|
package trace
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/micro/go-micro/util/ring"
|
|
|
|
)
|
|
|
|
|
|
|
|
type trace struct {
|
|
|
|
opts Options
|
|
|
|
|
|
|
|
// ring buffer of traces
|
|
|
|
buffer *ring.Buffer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *trace) Read(opts ...ReadOption) ([]*Span, error) {
|
2020-01-25 00:24:51 +03:00
|
|
|
var options ReadOptions
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
|
|
|
sp := t.buffer.Get(t.buffer.Size())
|
|
|
|
|
|
|
|
var spans []*Span
|
|
|
|
|
|
|
|
for _, span := range sp {
|
|
|
|
val := span.Value.(*Span)
|
|
|
|
// skip if trace id is specified and doesn't match
|
|
|
|
if len(options.Trace) > 0 && val.Trace != options.Trace {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
spans = append(spans, val)
|
|
|
|
}
|
|
|
|
|
|
|
|
return spans, nil
|
2020-01-18 13:20:46 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *trace) Start(ctx context.Context, name string) *Span {
|
|
|
|
span := &Span{
|
|
|
|
Name: name,
|
|
|
|
Trace: uuid.New().String(),
|
|
|
|
Id: uuid.New().String(),
|
|
|
|
Started: time.Now(),
|
|
|
|
Metadata: make(map[string]string),
|
|
|
|
}
|
|
|
|
|
|
|
|
// return span if no context
|
|
|
|
if ctx == nil {
|
|
|
|
return span
|
|
|
|
}
|
|
|
|
|
|
|
|
s, ok := FromContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return span
|
|
|
|
}
|
|
|
|
|
|
|
|
// set trace id
|
|
|
|
span.Trace = s.Trace
|
|
|
|
// set parent
|
|
|
|
span.Parent = s.Id
|
|
|
|
|
|
|
|
// return the sapn
|
|
|
|
return span
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *trace) Finish(s *Span) error {
|
|
|
|
// set finished time
|
2020-01-25 00:24:51 +03:00
|
|
|
s.Duration = time.Since(s.Started)
|
2020-01-18 13:20:46 +03:00
|
|
|
|
|
|
|
// save the span
|
|
|
|
t.buffer.Put(s)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTrace(opts ...Option) Trace {
|
|
|
|
var options Options
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &trace{
|
|
|
|
opts: options,
|
|
|
|
// the last 64 requests
|
|
|
|
buffer: ring.New(64),
|
|
|
|
}
|
|
|
|
}
|