Repository navigation
Expand file tree
/
Copy pathsqlite_exporter.go
More file actions
295 lines (262 loc) · 8.81 KB
/
Copy pathsqlite_exporter.go
File metadata and controls
295 lines (262 loc) · 8.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright 2024 William Perron. All rights reserved. MIT License.
package sqliteexporter
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
_ "github.com/mattn/go-sqlite3"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.wperron.io/sqliteexporter/internal/transform"
)
// The goal is to have the sqliteexporter usable both in a collector deployment
// but also embedded in an app. As such, it must satisfy the component.Component
// interface and the sdktrace.SpanExporter interface.
var _ sdktrace.SpanExporter = &sqliteExporter{}
var _ component.Component = &sqliteExporter{}
type sqliteExporter struct {
db *sql.DB
}
// DO NOT CHANGE: any modification will not be backwards compatible and
// must never be done outside of a new major release.
// ExportSpans exports a batch of spans.
//
// This function is called synchronously, so there is no concurrency
// safety requirement. However, due to the synchronous calling pattern,
// it is critical that all timeouts and cancellations contained in the
// passed context must be honored.
//
// Any retry logic must be contained in this function. The SDK that
// calls this function will not implement any retry logic. All errors
// returned by this function are considered unrecoverable and will be
// reported to a configured error Handler.
// DO NOT CHANGE: any modification will not be backwards compatible and
// must never be done outside of a new major release.
func (e *sqliteExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
ss := transform.Spans(spans)
return e.ConsumeTraces(ctx, ss)
}
// Start tells the component to start. Host parameter can be used for communicating
// with the host after Start() has already returned. If an error is returned by
// Start() then the collector startup will be aborted.
// If this is an exporter component it may prepare for exporting
// by connecting to the endpoint.
//
// If the component needs to perform a long-running starting operation then it is recommended
// that Start() returns quickly and the long-running operation is performed in background.
// In that case make sure that the long-running operation does not use the context passed
// to Start() function since that context will be cancelled soon and can abort the long-running
// operation. Create a new context from the context.Background() for long-running operations.
func (e *sqliteExporter) Start(ctx context.Context, host component.Host) error {
return nil
}
// Shutdown is invoked during service shutdown. After Shutdown() is called, if the component
// accepted data in any way, it should not accept it anymore.
//
// This method must be safe to call:
// - without Start() having been called
// - if the component is in a shutdown state already
//
// If there are any background operations running by the component they must be aborted before
// this function returns. Remember that if you started any long-running background operations from
// the Start() method, those operations must be also cancelled. If there are any buffers in the
// component, they should be cleared and the data sent immediately to the next component.
//
// The component's lifecycle is completed once the Shutdown() method returns. No other
// methods of the component are called after that. If necessary a new component with
// the same or different configuration may be created and started (this may happen
// for example if we want to restart the component).
func (e *sqliteExporter) Shutdown(ctx context.Context) error {
return e.db.Close()
}
// TODO(wperron) add instrumentation library (scope) name and version
const insertSpanQ string = `INSERT INTO spans
(
span_id,
trace_id,
parent_span_id,
tracestate,
__service_name,
__duration,
name,
kind,
start_time,
end_time,
status_code,
status_description,
attributes,
dropped_attributes_count,
dropped_events_count,
dropped_links_count,
resource_attributes,
resource_dropped_attributes_count,
instrumentation_library_name,
instrumentation_library_version,
instrumentation_library_attributes
)
VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, json(?), ?, ?, ?, json(?), ?, ?, ?, json(?)
);
`
const insertEventQ string = `INSERT INTO events
(
span_id,
timestamp,
name,
attributes,
dropped_attributes_count
)
VALUES (
?, ?, ?, json(?), ?
);
`
const insertLinkQ string = `INSERT INTO links
(
parent_span_id,
span_id,
trace_id,
tracestate,
attributes,
dropped_attributes_count
)
VALUES (
?, ?, ?, ?, json(?), ?
)`
func (e *sqliteExporter) ConsumeTraces(ctx context.Context, traces ptrace.Traces) error {
tx, err := e.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer tx.Commit()
for i := 0; i < traces.ResourceSpans().Len(); i++ {
resource := traces.ResourceSpans().At(i)
svc := "unknown"
resource.Resource().Attributes().Range(func(k string, v pcommon.Value) bool {
if k == "service.name" {
svc = v.Str()
if svc == "" { // protect against service name being another type for some reason
svc = "unknown"
}
return false
}
return true
})
rattrs, err := pcommonMapAsJSON(resource.Resource().Attributes())
if err != nil {
return fmt.Errorf("failed to marshal resource attributes as json: %w", err)
}
for j := 0; j < resource.ScopeSpans().Len(); j++ {
scope := resource.ScopeSpans().At(j)
sattrs, err := pcommonMapAsJSON(scope.Scope().Attributes())
if err != nil {
return fmt.Errorf("failed to marshal instrumentation scope attributes as json: %w", err)
}
for k := 0; k < scope.Spans().Len(); k++ {
span := scope.Spans().At(k)
dur := span.EndTimestamp().AsTime().Sub(span.StartTimestamp().AsTime())
stmt, err := tx.PrepareContext(ctx, insertSpanQ)
if err != nil {
return fmt.Errorf("failed to prepare span insert stmt: %w", err)
}
attrs, err := pcommonMapAsJSON(span.Attributes())
if err != nil {
return fmt.Errorf("failed to marshal attributes as json: %w", err)
}
spanidraw := [8]byte(span.SpanID())
spanidbs := spanidraw[:]
traceidraw := [16]byte(span.TraceID())
traceidbs := traceidraw[:]
parentidraw := [8]byte(span.ParentSpanID())
parentidbs := parentidraw[:]
if span.ParentSpanID().IsEmpty() {
parentidbs = nil
}
_, err = stmt.ExecContext(ctx,
spanidbs,
traceidbs,
parentidbs,
span.TraceState().AsRaw(),
svc,
dur.Microseconds(),
span.Name(),
span.Kind().String(),
// Use microsecond precision for start and timestamps
unixMicro(span.StartTimestamp().AsTime()),
unixMicro(span.EndTimestamp().AsTime()),
span.Status().Code(),
span.Status().Message(),
attrs,
span.DroppedAttributesCount(),
span.DroppedEventsCount(),
span.DroppedLinksCount(),
rattrs,
resource.Resource().DroppedAttributesCount(),
scope.Scope().Name(),
scope.Scope().Version(),
sattrs,
)
if err != nil {
return fmt.Errorf("error occured while inserting span: %w", err)
}
for l := 0; l < span.Events().Len(); l++ {
event := span.Events().At(l)
attrs, err := pcommonMapAsJSON(event.Attributes())
if err != nil {
return fmt.Errorf("failed to marshal event attributes as json: %w", err)
}
stmt, err := tx.PrepareContext(ctx, insertEventQ)
if err != nil {
return fmt.Errorf("failed to prepare event insert query: %w", err)
}
_, err = stmt.ExecContext(ctx,
spanidbs,
unixMicro(event.Timestamp().AsTime()),
event.Name(),
attrs,
event.DroppedAttributesCount(),
)
if err != nil {
return fmt.Errorf("error occured while inserting event: %w", err)
}
}
for l := 0; l < span.Links().Len(); l++ {
link := span.Links().At(l)
attrs, err := pcommonMapAsJSON(link.Attributes())
if err != nil {
return fmt.Errorf("failed to marshal link attributes as json: %w", err)
}
stmt, err := tx.PrepareContext(ctx, insertLinkQ)
if err != nil {
return fmt.Errorf("failed to prepare link insert query: %w", err)
}
linkidraw := [8]byte(link.SpanID())
linkidbs := linkidraw[:]
linktraceraw := [16]byte(link.TraceID())
linetracebs := linktraceraw[:]
_, err = stmt.ExecContext(ctx,
spanidbs,
linkidbs,
linetracebs,
link.TraceState().AsRaw(),
attrs,
link.DroppedAttributesCount(),
)
if err != nil {
return fmt.Errorf("error occured while inserting link: %w", err)
}
}
}
}
}
return nil
}
func pcommonMapAsJSON(m pcommon.Map) ([]byte, error) {
return json.Marshal(m.AsRaw())
}
func unixMicro(t time.Time) int64 {
return t.UnixNano() / 1000
}