-
Notifications
You must be signed in to change notification settings - Fork 35
/
writer.go
444 lines (399 loc) · 12.6 KB
/
writer.go
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Copyright The OpenTelemetry Authors
//
// 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 clickhousetracesexporter
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
"github.com/SigNoz/signoz-otel-collector/usage"
"github.com/google/uuid"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"go.opentelemetry.io/collector/component"
"go.uber.org/zap"
)
type Encoding string
const (
// EncodingJSON is used for spans encoded as JSON.
EncodingJSON Encoding = "json"
// EncodingProto is used for spans encoded as Protobuf.
EncodingProto Encoding = "protobuf"
)
// SpanWriter for writing spans to ClickHouse
type SpanWriter struct {
logger *zap.Logger
db clickhouse.Conn
traceDatabase string
indexTable string
errorTable string
spansTable string
attributeTable string
attributeKeyTable string
encoding Encoding
exporterId uuid.UUID
}
type WriterOptions struct {
logger *zap.Logger
db clickhouse.Conn
traceDatabase string
spansTable string
indexTable string
errorTable string
attributeTable string
attributeKeyTable string
encoding Encoding
exporterId uuid.UUID
}
// NewSpanWriter returns a SpanWriter for the database
func NewSpanWriter(options WriterOptions) *SpanWriter {
if err := view.Register(SpansCountView, SpansCountBytesView); err != nil {
return nil
}
writer := &SpanWriter{
logger: options.logger,
db: options.db,
traceDatabase: options.traceDatabase,
indexTable: options.indexTable,
errorTable: options.errorTable,
spansTable: options.spansTable,
attributeTable: options.attributeTable,
attributeKeyTable: options.attributeKeyTable,
encoding: options.encoding,
exporterId: options.exporterId,
}
return writer
}
func (w *SpanWriter) writeIndexBatch(ctx context.Context, batchSpans []*Span) error {
var statement driver.Batch
var err error
defer func() {
if statement != nil {
_ = statement.Abort()
}
}()
statement, err = w.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s", w.traceDatabase, w.indexTable), driver.WithReleaseConnection())
if err != nil {
w.logger.Error("Could not prepare batch for index table: ", zap.Error(err))
return err
}
for _, span := range batchSpans {
err = statement.Append(
time.Unix(0, int64(span.StartTimeUnixNano)),
span.TraceId,
span.SpanId,
span.ParentSpanId,
span.ServiceName,
span.Name,
span.Kind,
span.DurationNano,
span.StatusCode,
span.ExternalHttpMethod,
span.ExternalHttpUrl,
span.Component,
span.DBSystem,
span.DBName,
span.DBOperation,
span.PeerService,
span.Events,
span.HttpMethod,
span.HttpUrl,
span.HttpCode,
span.HttpRoute,
span.HttpHost,
span.MsgSystem,
span.MsgOperation,
span.HasError,
span.TagMap,
span.GRPCMethod,
span.GRPCCode,
span.RPCSystem,
span.RPCService,
span.RPCMethod,
span.ResponseStatusCode,
span.StringTagMap,
span.NumberTagMap,
span.BoolTagMap,
span.ResourceTagsMap,
span.IsRemote,
)
if err != nil {
w.logger.Error("Could not append span to batch: ", zap.Object("span", span), zap.Error(err))
return err
}
}
start := time.Now()
err = statement.Send()
ctx, _ = tag.New(ctx,
tag.Upsert(exporterKey, string(component.DataTypeTraces)),
tag.Upsert(tableKey, w.indexTable),
)
stats.Record(ctx, writeLatencyMillis.M(int64(time.Since(start).Milliseconds())))
return err
}
func (w *SpanWriter) writeTagBatch(ctx context.Context, batchSpans []*Span) error {
var tagKeyStatement driver.Batch
var tagStatement driver.Batch
var err error
defer func() {
if tagKeyStatement != nil {
_ = tagKeyStatement.Abort()
}
if tagStatement != nil {
_ = tagStatement.Abort()
}
}()
tagStatement, err = w.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s", w.traceDatabase, w.attributeTable), driver.WithReleaseConnection())
if err != nil {
w.logger.Error("Could not prepare batch for span attributes table due to error: ", zap.Error(err))
return err
}
tagKeyStatement, err = w.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s", w.traceDatabase, w.attributeKeyTable), driver.WithReleaseConnection())
if err != nil {
w.logger.Error("Could not prepare batch for span attributes key table due to error: ", zap.Error(err))
return err
}
// create map of span attributes of key, tagType, dataType and isColumn to avoid duplicates in batch
mapOfSpanAttributeKeys := make(map[string]struct{})
// create map of span attributes of key, tagType, dataType, isColumn and value to avoid duplicates in batch
mapOfSpanAttributeValues := make(map[string]struct{})
for _, span := range batchSpans {
for _, spanAttribute := range span.SpanAttributes {
// form a map key of span attribute key, tagType, dataType, isColumn and value
mapOfSpanAttributeValueKey := spanAttribute.Key + spanAttribute.TagType + spanAttribute.DataType + strconv.FormatBool(spanAttribute.IsColumn) + spanAttribute.StringValue + strconv.FormatFloat(spanAttribute.NumberValue, 'f', -1, 64)
// check if mapOfSpanAttributeValueKey already exists in map
_, ok := mapOfSpanAttributeValues[mapOfSpanAttributeValueKey]
if ok {
continue
}
// add mapOfSpanAttributeValueKey to map
mapOfSpanAttributeValues[mapOfSpanAttributeValueKey] = struct{}{}
// form a map key of span attribute key, tagType, dataType and isColumn
mapOfSpanAttributeKey := spanAttribute.Key + spanAttribute.TagType + spanAttribute.DataType + strconv.FormatBool(spanAttribute.IsColumn)
// check if mapOfSpanAttributeKey already exists in map
_, ok = mapOfSpanAttributeKeys[mapOfSpanAttributeKey]
if !ok {
err = tagKeyStatement.Append(
spanAttribute.Key,
spanAttribute.TagType,
spanAttribute.DataType,
spanAttribute.IsColumn,
)
if err != nil {
w.logger.Error("Could not append span to tagKey Statement to batch due to error: ", zap.Error(err), zap.Object("span", span))
return err
}
}
// add mapOfSpanAttributeKey to map
mapOfSpanAttributeKeys[mapOfSpanAttributeKey] = struct{}{}
if spanAttribute.DataType == "string" {
err = tagStatement.Append(
time.Unix(0, int64(span.StartTimeUnixNano)),
spanAttribute.Key,
spanAttribute.TagType,
spanAttribute.DataType,
spanAttribute.StringValue,
nil,
spanAttribute.IsColumn,
)
} else if spanAttribute.DataType == "float64" {
err = tagStatement.Append(
time.Unix(0, int64(span.StartTimeUnixNano)),
spanAttribute.Key,
spanAttribute.TagType,
spanAttribute.DataType,
nil,
spanAttribute.NumberValue,
spanAttribute.IsColumn,
)
} else if spanAttribute.DataType == "bool" {
err = tagStatement.Append(
time.Unix(0, int64(span.StartTimeUnixNano)),
spanAttribute.Key,
spanAttribute.TagType,
spanAttribute.DataType,
nil,
nil,
spanAttribute.IsColumn,
)
}
if err != nil {
w.logger.Error("Could not append span to tag Statement batch due to error: ", zap.Error(err), zap.Object("span", span))
return err
}
}
}
tagStart := time.Now()
err = tagStatement.Send()
stats.RecordWithTags(ctx,
[]tag.Mutator{
tag.Upsert(exporterKey, string(component.DataTypeTraces)),
tag.Upsert(tableKey, w.attributeTable),
},
writeLatencyMillis.M(int64(time.Since(tagStart).Milliseconds())),
)
if err != nil {
w.logger.Error("Could not write to span attributes table due to error: ", zap.Error(err))
return err
}
tagKeyStart := time.Now()
err = tagKeyStatement.Send()
stats.RecordWithTags(ctx,
[]tag.Mutator{
tag.Upsert(exporterKey, string(component.DataTypeTraces)),
tag.Upsert(tableKey, w.attributeKeyTable),
},
writeLatencyMillis.M(int64(time.Since(tagKeyStart).Milliseconds())),
)
if err != nil {
w.logger.Error("Could not write to span attributes key table due to error: ", zap.Error(err))
return err
}
return err
}
func (w *SpanWriter) writeErrorBatch(ctx context.Context, batchSpans []*Span) error {
var statement driver.Batch
var err error
defer func() {
if statement != nil {
_ = statement.Abort()
}
}()
statement, err = w.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s", w.traceDatabase, w.errorTable), driver.WithReleaseConnection())
if err != nil {
w.logger.Error("Could not prepare batch for error table: ", zap.Error(err))
return err
}
for _, span := range batchSpans {
if span.ErrorEvent.Name == "" {
continue
}
err = statement.Append(
time.Unix(0, int64(span.ErrorEvent.TimeUnixNano)),
span.ErrorID,
span.ErrorGroupID,
span.TraceId,
span.SpanId,
span.ServiceName,
span.ErrorEvent.AttributeMap["exception.type"],
span.ErrorEvent.AttributeMap["exception.message"],
span.ErrorEvent.AttributeMap["exception.stacktrace"],
stringToBool(span.ErrorEvent.AttributeMap["exception.escaped"]),
span.ResourceTagsMap,
)
if err != nil {
w.logger.Error("Could not append span to batch: ", zap.Object("span", span), zap.Error(err))
return err
}
}
start := time.Now()
err = statement.Send()
ctx, _ = tag.New(ctx,
tag.Upsert(exporterKey, string(component.DataTypeTraces)),
tag.Upsert(tableKey, w.errorTable),
)
stats.Record(ctx, writeLatencyMillis.M(int64(time.Since(start).Milliseconds())))
return err
}
func stringToBool(s string) bool {
return strings.ToLower(s) == "true"
}
func (w *SpanWriter) writeModelBatch(ctx context.Context, batchSpans []*Span) error {
var statement driver.Batch
var err error
defer func() {
if statement != nil {
_ = statement.Abort()
}
}()
statement, err = w.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s", w.traceDatabase, w.spansTable), driver.WithReleaseConnection())
if err != nil {
w.logger.Error("Could not prepare batch for model table: ", zap.Error(err))
return err
}
metrics := map[string]usage.Metric{}
for _, span := range batchSpans {
var serialized []byte
usageMap := span.TraceModel
usageMap.TagMap = map[string]string{}
serialized, err = json.Marshal(span.TraceModel)
if err != nil {
return err
}
serializedUsage, err := json.Marshal(usageMap)
if err != nil {
return err
}
err = statement.Append(time.Unix(0, int64(span.StartTimeUnixNano)), span.TraceId, string(serialized))
if err != nil {
w.logger.Error("Could not append span to batch: ", zap.Object("span", span), zap.Error(err))
return err
}
usage.AddMetric(metrics, *span.Tenant, 1, int64(len(serializedUsage)))
}
start := time.Now()
err = statement.Send()
ctx, _ = tag.New(ctx,
tag.Upsert(exporterKey, string(component.DataTypeTraces)),
tag.Upsert(tableKey, w.spansTable),
)
stats.Record(ctx, writeLatencyMillis.M(int64(time.Since(start).Milliseconds())))
if err != nil {
return err
}
for k, v := range metrics {
stats.RecordWithTags(ctx, []tag.Mutator{tag.Upsert(usage.TagTenantKey, k), tag.Upsert(usage.TagExporterIdKey, w.exporterId.String())}, ExporterSigNozSentSpans.M(int64(v.Count)), ExporterSigNozSentSpansBytes.M(int64(v.Size)))
}
return nil
}
// WriteBatchOfSpans writes the encoded batch of spans
func (w *SpanWriter) WriteBatchOfSpans(ctx context.Context, batch []*Span) error {
if w.spansTable != "" {
if err := w.writeModelBatch(ctx, batch); err != nil {
w.logger.Error("Could not write a batch of spans to model table: ", zap.Error(err))
return err
}
}
if w.indexTable != "" {
if err := w.writeIndexBatch(ctx, batch); err != nil {
w.logger.Error("Could not write a batch of spans to index table: ", zap.Error(err))
return err
}
}
if w.errorTable != "" {
if err := w.writeErrorBatch(ctx, batch); err != nil {
w.logger.Error("Could not write a batch of spans to error table: ", zap.Error(err))
return err
}
}
if w.attributeTable != "" && w.attributeKeyTable != "" {
if err := w.writeTagBatch(ctx, batch); err != nil {
w.logger.Error("Could not write a batch of spans to tag/tagKey tables: ", zap.Error(err))
return err
}
}
return nil
}
// Close closes the writer
func (w *SpanWriter) Close() error {
if w.db != nil {
return w.db.Close()
}
return nil
}