1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package ocagent adds the ability to export all telemetry to an ocagent.
6 // This keeps the compile time dependencies to zero and allows the agent to
7 // have the exporters needed for telemetry aggregation and viewing systems.
21 "golang.org/x/tools/internal/event"
22 "golang.org/x/tools/internal/event/core"
23 "golang.org/x/tools/internal/event/export"
24 "golang.org/x/tools/internal/event/export/metric"
25 "golang.org/x/tools/internal/event/export/ocagent/wire"
26 "golang.org/x/tools/internal/event/keys"
27 "golang.org/x/tools/internal/event/label"
42 exporters = make(map[Config]*Exporter)
45 // Discover finds the local agent to export to, it will return nil if there
46 // is not one running.
47 // TODO: Actually implement a discovery protocol rather than a hard coded address
48 func Discover() *Config {
50 Address: "http://localhost:55678",
54 type Exporter struct {
61 // Connect creates a process specific exporter with the specified
62 // serviceName and the address of the ocagent to which it will upload
64 func Connect(config *Config) *Exporter {
65 if config == nil || config.Address == "off" {
69 if resolved.Host == "" {
70 hostname, _ := os.Hostname()
71 resolved.Host = hostname
73 if resolved.Process == 0 {
74 resolved.Process = uint32(os.Getpid())
76 if resolved.Client == nil {
77 resolved.Client = http.DefaultClient
79 if resolved.Service == "" {
80 resolved.Service = filepath.Base(os.Args[0])
82 if resolved.Rate == 0 {
83 resolved.Rate = 2 * time.Second
87 defer connectMu.Unlock()
88 if exporter, found := exporters[resolved]; found {
91 exporter := &Exporter{config: resolved}
92 exporters[resolved] = exporter
93 if exporter.config.Start.IsZero() {
94 exporter.config.Start = time.Now()
97 for range time.Tick(exporter.config.Rate) {
104 func (e *Exporter) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) context.Context {
106 case event.IsEnd(ev):
109 span := export.GetSpan(ctx)
111 e.spans = append(e.spans, span)
113 case event.IsMetric(ev):
116 data := metric.Entries.Get(lm).([]metric.Data)
117 e.metrics = append(e.metrics, data...)
122 func (e *Exporter) Flush() {
125 spans := make([]*wire.Span, len(e.spans))
126 for i, s := range e.spans {
127 spans[i] = convertSpan(s)
130 metrics := make([]*wire.Metric, len(e.metrics))
131 for i, m := range e.metrics {
132 metrics[i] = convertMetric(m, e.config.Start)
137 e.send("/v1/trace", &wire.ExportTraceServiceRequest{
138 Node: e.config.buildNode(),
143 if len(metrics) > 0 {
144 e.send("/v1/metrics", &wire.ExportMetricsServiceRequest{
145 Node: e.config.buildNode(),
152 func (cfg *Config) buildNode() *wire.Node {
154 Identifier: &wire.ProcessIdentifier{
157 StartTimestamp: convertTimestamp(cfg.Start),
159 LibraryInfo: &wire.LibraryInfo{
160 Language: wire.LanguageGo,
161 ExporterVersion: "0.0.1",
162 CoreLibraryVersion: "x/tools",
164 ServiceInfo: &wire.ServiceInfo{
170 func (e *Exporter) send(endpoint string, message interface{}) {
171 blob, err := json.Marshal(message)
173 errorInExport("ocagent failed to marshal message for %v: %v", endpoint, err)
176 uri := e.config.Address + endpoint
177 req, err := http.NewRequest("POST", uri, bytes.NewReader(blob))
179 errorInExport("ocagent failed to build request for %v: %v", uri, err)
182 req.Header.Set("Content-Type", "application/json")
183 res, err := e.config.Client.Do(req)
185 errorInExport("ocagent failed to send message: %v \n", err)
193 func errorInExport(message string, args ...interface{}) {
194 // This function is useful when debugging the exporter, but in general we
195 // want to just drop any export
198 func convertTimestamp(t time.Time) wire.Timestamp {
199 return t.Format(time.RFC3339Nano)
202 func toTruncatableString(s string) *wire.TruncatableString {
206 return &wire.TruncatableString{Value: s}
209 func convertSpan(span *export.Span) *wire.Span {
210 result := &wire.Span{
211 TraceID: span.ID.TraceID[:],
212 SpanID: span.ID.SpanID[:],
213 TraceState: nil, //TODO?
214 ParentSpanID: span.ParentID[:],
215 Name: toTruncatableString(span.Name),
216 Kind: wire.UnspecifiedSpanKind,
217 StartTime: convertTimestamp(span.Start().At()),
218 EndTime: convertTimestamp(span.Finish().At()),
219 Attributes: convertAttributes(span.Start(), 1),
220 TimeEvents: convertEvents(span.Events()),
221 SameProcessAsParentSpan: true,
230 func convertMetric(data metric.Data, start time.Time) *wire.Metric {
231 descriptor := dataToMetricDescriptor(data)
232 timeseries := dataToTimeseries(data, start)
234 if descriptor == nil && timeseries == nil {
238 // TODO: handle Histogram metrics
240 MetricDescriptor: descriptor,
241 Timeseries: timeseries,
242 // TODO: attach Resource?
246 func skipToValidLabel(list label.List, index int) (int, label.Label) {
247 // skip to the first valid label
248 for ; list.Valid(index); index++ {
249 l := list.Label(index)
250 if !l.Valid() || l.Key() == keys.Label {
255 return -1, label.Label{}
258 func convertAttributes(list label.List, index int) *wire.Attributes {
259 index, l := skipToValidLabel(list, index)
263 attributes := make(map[string]wire.Attribute)
266 attributes[l.Key().Name()] = convertAttribute(l)
269 if !list.Valid(index) {
270 return &wire.Attributes{AttributeMap: attributes}
272 l = list.Label(index)
276 func convertAttribute(l label.Label) wire.Attribute {
277 switch key := l.Key().(type) {
279 return wire.IntAttribute{IntValue: int64(key.From(l))}
281 return wire.IntAttribute{IntValue: int64(key.From(l))}
283 return wire.IntAttribute{IntValue: int64(key.From(l))}
285 return wire.IntAttribute{IntValue: int64(key.From(l))}
287 return wire.IntAttribute{IntValue: int64(key.From(l))}
289 return wire.IntAttribute{IntValue: int64(key.From(l))}
291 return wire.IntAttribute{IntValue: int64(key.From(l))}
293 return wire.IntAttribute{IntValue: int64(key.From(l))}
295 return wire.IntAttribute{IntValue: int64(key.From(l))}
297 return wire.IntAttribute{IntValue: int64(key.From(l))}
299 return wire.DoubleAttribute{DoubleValue: float64(key.From(l))}
301 return wire.DoubleAttribute{DoubleValue: key.From(l)}
303 return wire.BoolAttribute{BoolValue: key.From(l)}
305 return wire.StringAttribute{StringValue: toTruncatableString(key.From(l))}
307 return wire.StringAttribute{StringValue: toTruncatableString(key.From(l).Error())}
309 return wire.StringAttribute{StringValue: toTruncatableString(fmt.Sprint(key.From(l)))}
311 return wire.StringAttribute{StringValue: toTruncatableString(fmt.Sprintf("%T", key))}
315 func convertEvents(events []core.Event) *wire.TimeEvents {
316 //TODO: MessageEvents?
317 result := make([]wire.TimeEvent, len(events))
318 for i, event := range events {
319 result[i] = convertEvent(event)
321 return &wire.TimeEvents{TimeEvent: result}
324 func convertEvent(ev core.Event) wire.TimeEvent {
325 return wire.TimeEvent{
326 Time: convertTimestamp(ev.At()),
327 Annotation: convertAnnotation(ev),
331 func getAnnotationDescription(ev core.Event) (string, int) {
333 if l.Key() != keys.Msg {
336 if msg := keys.Msg.From(l); msg != "" {
340 if l.Key() != keys.Err {
343 if err := keys.Err.From(l); err != nil {
344 return err.Error(), 2
349 func convertAnnotation(ev core.Event) *wire.Annotation {
350 description, index := getAnnotationDescription(ev)
351 if _, l := skipToValidLabel(ev, index); !l.Valid() && description == "" {
354 return &wire.Annotation{
355 Description: toTruncatableString(description),
356 Attributes: convertAttributes(ev, index),