/
clickhouse.js
1470 lines (1396 loc) · 44.3 KB
/
clickhouse.js
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Qryn DB Adapter for Clickhouse
* (C) 2018-2022 QXIP BV
*/
const UTILS = require('../utils')
const toJSON = UTILS.toJSON
const logger = require('../logger')
const { formatISO9075 } = require('date-fns')
const { Blob } = require('buffer')
const Zipkin = require('./zipkin')
const Otlp = require('./otlp')
const logfmt = require('logfmt')
const csql = require('@cloki/clickhouse-sql')
const clusterName = require('../../common').clusterName
const dist = clusterName ? '_dist' : ''
/* DB Helper */
const ClickHouse = require('@apla/clickhouse')
const transpiler = require('../../parser/transpiler')
const rotationLabels = process.env.LABELS_DAYS || 7
const rotationSamples = process.env.SAMPLES_DAYS || 7
const axios = require('axios')
const { samplesTableName, samplesReadTableName } = UTILS
const path = require('path')
const { Transform } = require('stream')
const { CORS, bun, readonly, boolEnv } = require('../../common')
const clickhouseOptions = require('./clickhouse_options').databaseOptions
const { getClickhouseUrl } = require('./clickhouse_options')
// External Storage Policy for Tables (S3, MINIO)
const storagePolicy = process.env.STORAGE_POLICY || false
const { StringStream, DataStream } = require('scramjet')
const { parseLabels, hashLabels, isCustomSamplesOrderingRule, isOmitTablesCreation } = require('../../common')
const { Worker, isMainThread } = require('worker_threads')
const jsonSerializer = (k, val) => typeof val === 'bigint'
? val.toString()
: typeof val === 'number' && isNaN(val)
? 'NaN'
: val
const createCsvArrayWriter = require('csv-writer').createArrayCsvStringifier
const capabilities = {}
let state = 'INITIALIZING'
const clickhouse = new ClickHouse(clickhouseOptions)
let ch
const conveyor = {
labels: 0,
lastUpdate: 0,
count: async () => {
if (conveyor.lastUpdate < Date.now() - 30000) {
return conveyor.labels
}
try {
const resp = await rawRequest(`SELECT COUNT(1) as c FROM ${UTILS.DATABASE_NAME()}.time_series FORMAT JSON`)
conveyor.labels = resp.data.data[0].c
return conveyor.labels
} catch (e) {
logger.error(e)
}
}
}
let throttler = null
const resolvers = {}
const rejectors = {}
let first = false
if (isMainThread && !bun()) {
throttler = new Worker(path.join(__dirname, 'throttler.js'))
throttler.on('message', (msg) => {
switch (msg.status) {
case 'ok':
resolvers[msg.id]()
break
case 'err':
rejectors[msg.id](new Error('Database push error'))
break
}
delete resolvers[msg.id]
delete rejectors[msg.id]
})
} else if (isMainThread && !first) {
first = true
setTimeout(() => {
const _throttler = require('./throttler')
throttler = {
on: _throttler.on,
postMessage: _throttler.postMessage,
removeAllListeners: _throttler.removeAllListeners,
terminate: _throttler.terminate
}
_throttler.init()
throttler.on('message', (msg) => {
switch (msg.status) {
case 'ok':
resolvers[msg.id]()
break
case 'err':
rejectors[msg.id](new Error('Database push error'))
break
}
delete resolvers[msg.id]
delete rejectors[msg.id]
})
})
}
// timeSeriesv2Throttler.start();
/* Cache Helper */
const recordCache = require('record-cache')
const { parseMs, DATABASE_NAME } = require('../utils')
let id = 0
function getThrottlerId () {
id = (id + 1) % 1e6
return id
}
// Flushing to Clickhouse
const bulk = {
add: (values) => {
const id = getThrottlerId()
return new Promise((resolve, reject) => {
throttler.postMessage({
type: 'values',
data: values.map(r => JSON.stringify({
fingerprint: r[0],
timestamp_ns: r[1],
value: r[2],
string: r[3],
type: r[4]
}, jsonSerializer)).join('\n'),
id: id
})
resolvers[id] = resolve
rejectors[id] = reject
})
}
}
const bulkLabels = {
add: (values) => {
return new Promise((resolve, reject) => {
const id = getThrottlerId()
throttler.postMessage({
type: 'labels',
data: values.map(r => JSON.stringify({
date: r[0],
fingerprint: r[1],
labels: r[2],
name: r[3],
type: r[4]
}, jsonSerializer)).join('\n'),
id: id
})
resolvers[id] = resolve
rejectors[id] = reject
})
}
}
// In-Memory LRU for quick lookups
const labels = recordCache({
maxSize: process.env.BULK_MAXCACHE || 50000,
maxAge: 0,
onStale: false
})
const checkDB = async function() {
await checkCapabilities()
await samplesReadTable.check()
}
/* Initialize */
const initialize = async function (dbName) {
logger.info('Initializing DB... ' + dbName)
const tmp = { ...clickhouseOptions, queryOptions: { database: '' } }
ch = new ClickHouse(tmp)
if (readonly) {
state = 'READY'
return
}
if (!isOmitTablesCreation()) {
const maintain = require('./maintain/index')
await maintain.upgrade({ name: dbName, storage_policy: storagePolicy })
await maintain.rotate([{
db: dbName,
samples_days: rotationSamples,
time_series_days: rotationLabels,
storage_policy: storagePolicy
}])
} else {
logger.info('Omitting tables creation')
}
state = 'READY'
reloadFingerprints()
}
const checkCapabilities = async () => {
logger.info('Checking clickhouse capabilities')
// qryn doesn't use LIVE VIEW after ClickHouse dropped WITH TIMEOUT clause support
capabilities.liveView = false
}
const reloadFingerprints = function () {
return;
logger.info('Reloading Fingerprints...')
const selectQuery = `SELECT DISTINCT fingerprint, labels FROM ${clickhouseOptions.queryOptions.database}.time_series`
const stream = ch.query(selectQuery)
// or collect records yourself
const rows = []
stream.on('metadata', function (columns) {
// do something with column list
})
stream.on('data', function (row) {
rows.push(row)
})
stream.on('error', function (err) {
logger.error(err, 'Error reloading fingerprints')
})
stream.on('end', function () {
rows.forEach(function (row) {
try {
const JSONLabels = toJSON(row[1]/*.replace(/\!?=/g, ':')*/)
labels.add(row[0], JSON.stringify(JSONLabels))
for (const key in JSONLabels) {
// logger.debug('Adding key',row);
labels.add('_LABELS_', key)
labels.add(key, JSONLabels[key])
}
} catch (err) { logger.error(err, 'error reloading fingerprints') }
})
})
}
const fakeStats = { summary: { bytesProcessedPerSecond: 0, linesProcessedPerSecond: 0, totalBytesProcessed: 0, totalLinesProcessed: 0, execTime: 0.001301608 }, store: { totalChunksRef: 0, totalChunksDownloaded: 0, chunksDownloadTime: 0, headChunkBytes: 0, headChunkLines: 0, decompressedBytes: 0, decompressedLines: 0, compressedBytes: 0, totalDuplicates: 0 }, ingester: { totalReached: 1, totalChunksMatched: 0, totalBatches: 0, totalLinesSent: 0, headChunkBytes: 0, headChunkLines: 0, decompressedBytes: 0, decompressedLines: 0, compressedBytes: 0, totalDuplicates: 0 } }
const scanFingerprints = async function (query) {
logger.debug('Scanning Fingerprints...')
const _query = transpiler.transpile(query)
_query.step = UTILS.parseDurationSecOrDefault(query.step, 5) * 1000
_query.csv = query.csv
return queryFingerprintsScan(_query)
}
const scanTempo = async function (query) {
return queryTempoScan(query)
}
const instantQueryScan = async function (query) {
logger.debug('Scanning Fingerprints...')
const time = parseMs(query.time, Date.now())
query.start = (time - 10 * 60 * 1000) * 1000000
query.end = Date.now() * 1000000
const _query = transpiler.transpile(query)
_query.step = UTILS.parseDurationSecOrDefault(query.step, 5) * 1000
const _stream = await axios.post(getClickhouseUrl() + '/',
_query.query + ' FORMAT JSONEachRow',
{
responseType: 'stream'
}
)
const dataStream = preprocessStream(_stream, _query.stream || [])
const res = new Transform({
transform (chunk, encoding, callback) {
callback(null, chunk)
}
})
setTimeout(() => {
try {
_query.matrix ? outputQueryVector(dataStream, res) : outputQueryStreams(dataStream, res)
} catch (e) { logger.error(e) }
}, 0)
return res
}
const tempoQueryScan = async function (query, res, traceId) {
const response = {
v2: [],
v1: []
}
response.v2 = await tempoQueryScanV2(query, res, traceId)
return response
}
const tempoQueryScanV2 = async function (query, res, traceId) {
logger.debug(`Scanning Tempo Fingerprints... ${traceId}`)
const _stream = await axios.post(getClickhouseUrl() + '/',
`SELECT payload_type, payload FROM ${DATABASE_NAME()}.tempo_traces${dist} WHERE oid='0' AND trace_id=unhex('${traceId}') ORDER BY timestamp_ns ASC LIMIT 2000 FORMAT JSONEachRow`,
{
responseType: 'stream'
}
)
return await StringStream.from(_stream.data).lines().map((e) => {
try {
const _e = JSON.parse(e)
return { ..._e, payload: JSON.parse(_e.payload) }
} catch (e) {
return null
}
}, DataStream).filter(e => e).toArray()
}
const tempoSearchScan = async function (query, res) {
logger.debug(`Scanning Tempo traces... ${query.tags}`)
const time = parseMs(query.time, Date.now())
/* Tempo does not seem to pass start/stop parameters. Use ENV or default 24h */
const hours = this.tempo_span || 24
if (!query.start) query.start = (time - (hours * 60 * 60 * 1000)) * 1000000
if (!query.end) query.end = Date.now() * 1000000
const _query = transpiler.transpile(query)
_query.step = UTILS.parseDurationSecOrDefault(query.step, 5) * 1000
const _stream = await axios.post(getClickhouseUrl() + '/',
_query.query + ' FORMAT JSONEachRow',
{
responseType: 'stream'
}
)
const dataStream = preprocessStream(_stream, _query.stream || [])
logger.info('debug tempo search', query)
return await (outputTempoSearch(dataStream, res))
}
/**
*
* @param traces {Object[]} openzipkin traces array see https://zipkin.io/zipkin-api/#/default/post_spans
* @returns {Promise<unknown>}
*/
function pushZipkin (traces) {
return new Promise((resolve, reject) => {
const id = getThrottlerId()
throttler.postMessage({
type: 'traces',
data: traces.map(obj => (new Zipkin(obj)).toJson()).join('\n'),
id: id
})
resolvers[id] = resolve
rejectors[id] = reject
})
}
/**
*
* @param traces {Object[]} openzipkin traces array see https://zipkin.io/zipkin-api/#/default/post_spans
* @returns {Promise<unknown>}
*/
function pushOTLP (traces) {
return new Promise((resolve, reject) => {
const id = getThrottlerId()
throttler.postMessage({
type: 'traces',
data: traces.map(obj => (new Otlp(obj)).toJson()).join('\n'),
id: id
})
resolvers[id] = resolve
rejectors[id] = reject
})
}
/**
* @param query {{
* query: string,
* duration: number,
* matrix: boolean,
* stream: (function(DataStream): DataStream)[],
* step: number,
* csv?: boolean
* }}
* @returns {Promise<Readable>}
*/
const queryFingerprintsScan = async function (query) {
logger.debug('Scanning Fingerprints...')
// logger.info(_query.query);
const _stream = await getClickhouseStream(query)
const dataStream = preprocessStream(_stream, query.stream || [])
const res = new Transform({
transform (chunk, encoding, callback) {
callback(null, chunk)
}
})
if (query.csv) {
setTimeout(async () => {
try {
await (query.matrix
? outputQueryMatrixCSV(dataStream, res, query.step, query.duration)
: outputQueryStreamsCSV(dataStream, res))
} catch (e) { logger.error(e) }
}, 0)
return res
}
setTimeout(async () => {
try {
await (query.matrix
? outputQueryMatrix(dataStream, res, query.step, query.duration)
: outputQueryStreams(dataStream, res))
} catch (e) { logger.error(e) }
}, 0)
return res
}
/**
* @param query {{
* query: string,
* duration: number,
* matrix: boolean,
* stream: (function(DataStream): DataStream)[],
* step: number,
* start: number,
* end: number,
* minDurationNs: number,
* maxDurationNs: number,
* tags: Object<string, string>
* }}
* @returns {Promise<{v1: Object[], v2: Object[]}>}
*/
const queryTempoScan = async function (query) {
const resp = {
v1: [],
v2: []
}
resp.v2 = await queryTempoScanV2({ ...query })
return resp
}
const queryTempoScanV2 = async function (query) {
const select = `SELECT hex(trace_id) as traceID, service_name as rootServiceName,
name as rootTraceName, timestamp_ns as startTimeUnixNano,
intDiv(duration_ns, 1000000) as durationMs`
const from = `FROM ${DATABASE_NAME()}.tempo_traces${dist}`
const where = [
'oid = \'0\'',
`timestamp_ns >= ${parseInt(query.start)} AND timestamp_ns <= ${parseInt(query.end)}`,
(query.minDurationNs ? `duration_ns >= ${parseInt(query.minDurationNs)}` : null),
(query.maxDurationNs ? `duration_ns <= ${parseInt(query.maxDurationNs)}` : null)
].filter(e => e)
let idxSubsel = null
if (query.tags) {
idxSubsel = Object.entries(query.tags)
.map(e => {
const timestampNs = query.limit ? ', timestamp_ns' : ''
let subQ = `SELECT trace_id, span_id ${timestampNs} FROM ${DATABASE_NAME()}.tempo_traces_attrs_gin WHERE oid='0'` +
` AND date >= '${formatISO9075(query.start / 1000000).substring(0, 10)}' ` +
` AND date <= '${formatISO9075(query.end / 1000000).substring(0, 10)}'` +
` AND key = ${csql.quoteVal(e[0].toString())} AND val = ${csql.quoteVal(e[1].toString())}` +
` AND timestamp_ns >= ${parseInt(query.start)} AND timestamp_ns <= ${parseInt(query.end)}`
if (query.minDurationNs) {
subQ += ` AND duration >= ${query.minDurationNs}`
}
if (query.maxDurationNs) {
subQ += ` AND duration <= ${query.maxDurationNs}`
}
return subQ
}).join(' INTERSECT ')
if (query.limit) {
idxSubsel = `SELECT trace_id, span_id FROM (${idxSubsel}) as rawsubsel ` +
`ORDER BY timestamp_ns DESC LIMIT ${parseInt(query.limit)}`
}
where.push(`(trace_id, span_id) IN (${idxSubsel})`)
}
const limit = query.limit ? `LIMIT ${parseInt(query.limit)}` : ''
const sql = `${select} ${from} WHERE ${where.join(' AND ')} ORDER BY timestamp_ns DESC ${limit} FORMAT JSON`
console.log(sql)
const resp = await rawRequest(sql, null, process.env.CLICKHOUSE_DB || 'cloki')
return resp.data.data ? resp.data.data : JSON.parse(resp.data).data
}
async function queryTempoTags () {
const q = `SELECT distinct key
FROM ${DATABASE_NAME()}.tempo_traces_kv${dist}
WHERE oid='0' AND date >= toDate(NOW()) - interval '1 day'
FORMAT JSON`
const resp = await axios.post(getClickhouseUrl() + '/',q)
return resp.data.data ? resp.data.data : JSON.parse(resp.data).data
}
/**
*
* @param tag {string}
* @returns {Promise<{val: string}[]>}
*/
async function queryTempoValues (tag) {
const q = `SELECT distinct val
FROM ${DATABASE_NAME()}.tempo_traces_kv${dist}
WHERE oid='0' AND date >= toDate(NOW()) - interval '1 day' AND key = ${csql.quoteVal(tag)}
FORMAT JSON`
const resp = await axios.post(getClickhouseUrl() + '/', q)
return resp.data.data ? resp.data.data : JSON.parse(resp.data).data
}
/**
*
* @param query {{query: string}}
* @returns {Promise<Stream>}
*/
const getClickhouseStream = (query) => {
return axios.post(getClickhouseUrl() + '/',
query.query + ' FORMAT JSONEachRow',
{
responseType: 'stream'
}
)
}
/**
*
* @param dataStream {DataStream}
* @param res {{res: {
* write: (function(string)),
* onBegin: (function(string)),
* onEnd: (function(string))
* }}}
* @param i {number}
* @returns {Promise<void>}
*/
const outputQueryStreams = async (dataStream, res, i) => {
//res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': CORS })
const gen = dataStream.toGenerator()
i = i || 0
let lastLabels = null
let lastStream = []
res.onBegin
? res.onBegin('{"status":"success", "data":{ "resultType": "streams", "result": [')
: res.write('{"status":"success", "data":{ "resultType": "streams", "result": [')
for await (const item of gen()) {
if (!item) {
continue
}
if (!item.labels) {
if (!lastLabels || !lastStream.length) {
continue
}
res.write(i ? ',' : '')
res.write(JSON.stringify({
stream: parseLabels(lastLabels),
values: lastStream
}))
lastLabels = null
lastStream = []
++i
continue
}
const hash = hashLabels(item.labels)
const ts = item.timestamp_ns || null
if (hash === lastLabels) {
ts && lastStream.push([ts, item.string])
continue
}
if (lastLabels) {
res.write(i ? ',' : '')
res.write(JSON.stringify({
stream: parseLabels(lastLabels),
values: lastStream
}))
++i
}
lastLabels = hash
lastStream = ts ? [[ts, item.string]] : []
}
res.onEnd ? res.onEnd(']}}') : res.write(']}}')
res.end()
}
/**
*
* @param dataStream {DataStream}
* @param res {{res: {
* write: (function(string)),
* onBegin: (function(string)),
* onEnd: (function(string))
* }}}
* @param i {number}
* @returns {Promise<void>}
*/
const outputQueryStreamsCSV = async (dataStream, res, i) => {
//res.writeHead(200, { 'Content-Type': 'text/csv', 'Access-Control-Allow-Origin': CORS })
const gen = dataStream.toGenerator()
const writer = createCsvArrayWriter({
header: ['timestamp_ns', 'labels', 'string']
})
res.onBegin
? res.onBegin(writer.getHeaderString())
: res.write(writer.getHeaderString())
for await (const item of gen()) {
if (!item) {
continue
}
const record = [
item.timestamp_ns,
JSON.stringify(item.labels),
item.string
]
res.write(writer.stringifyRecords([record]))
}
res.onEnd ? res.onEnd('') : res.write('')
res.end()
}
/**
*
* @param dataStream {DataStream}
* @param res {{write: (function(string))}}
* @param stepMs {number}
* @param durationMs {number}
* @returns {Promise<void>}
*/
const outputQueryMatrix = async (dataStream, res,
stepMs, durationMs) => {
//res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': CORS })
const addPoints = Math.ceil(durationMs / stepMs)
const gen = dataStream.toGenerator()
let i = 0
let lastLabels = null
let lastStream = []
let lastTsMs = 0
res.write('{"status":"success", "data":{ "resultType": "matrix", "result": [')
for await (const item of gen()) {
if (!item) {
continue
}
if (!item.labels) {
if (!lastLabels || !lastStream.length) {
continue
}
res.write(i ? ',' : '')
res.write(JSON.stringify({
metric: parseLabels(lastLabels),
values: lastStream
}))
lastLabels = null
lastStream = []
lastTsMs = 0
++i
continue
}
const hash = hashLabels(item.labels)
const ts = item.timestamp_ns ? parseInt(item.timestamp_ns) : null
if (hash === lastLabels) {
if (ts < (lastTsMs + stepMs)) {
continue
}
for (let j = 0; j < addPoints; ++j) {
ts && lastStream.push([(ts + stepMs * j) / 1000, item.value.toString()])
}
lastTsMs = ts
continue
}
if (lastLabels) {
res.write(i ? ',' : '')
res.write(JSON.stringify({
metric: parseLabels(lastLabels),
values: lastStream
}))
++i
}
lastLabels = hash
lastStream = []
for (let j = 0; j < addPoints; ++j) {
ts && lastStream.push([(ts + stepMs * j) / 1000, item.value.toString()])
}
lastTsMs = ts
}
res.write(']}}')
res.end()
}
/**
*
* @param dataStream {DataStream}
* @param res {{write: (function(string))}}
* @param stepMs {number}
* @param durationMs {number}
* @returns {Promise<void>}
*/
const outputQueryMatrixCSV = async (dataStream, res,
stepMs, durationMs) => {
//res.writeHead(200, { 'Content-Type': 'text/csv', 'Access-Control-Allow-Origin': CORS })
const addPoints = Math.ceil(durationMs / stepMs)
const gen = dataStream.toGenerator()
let lastTsMs = 0
let hash = ''
const writer = createCsvArrayWriter({
header: ['timestamp_ns', 'labels', 'value']
})
res.onBegin
? res.onBegin(writer.getHeaderString())
: res.write(writer.getHeaderString())
for await (const item of gen()) {
if (!item || !item.labels) {
continue
}
if (hashLabels(item.labels) !== hash) {
hash = hashLabels(item.labels)
lastTsMs = 0
}
const ts = item.timestamp_ns ? parseInt(item.timestamp_ns) : null
if (ts < (lastTsMs + stepMs)) {
continue
}
for (let j = 0; j < addPoints; ++j) {
const record = [
(ts + stepMs * j) * 1000000,
JSON.stringify(item.labels),
item.value.toString()
]
ts && res.write(writer.stringifyRecords([record]))
lastTsMs = (ts + stepMs * j)
}
}
res.onEnd ? res.onEnd('') : res.write('')
res.end()
}
/**
*
* @param dataStream {DataStream}
* @param res {Writable}
* @returns {Promise<void>}
*/
const outputQueryVector = async (dataStream, res) => {
//res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': CORS })
const gen = dataStream.toGenerator()
let i = 0
let lastLabels = null
let lastTsMs = 0
let lastValue = 0
res.write('{"status":"success", "data":{ "resultType": "vector", "result": [')
for await (const item of gen()) {
if (!item) {
continue
}
if (!item.labels) {
if (!lastLabels || !lastTsMs) {
continue
}
res.write(i ? ',' : '')
res.write(JSON.stringify({
metric: parseLabels(lastLabels),
value: [lastTsMs / 1000, lastValue.toString()]
}))
lastLabels = null
lastTsMs = 0
++i
continue
}
const hash = hashLabels(item.labels)
const ts = item.timestamp_ns ? parseInt(item.timestamp_ns) : null
if (hash === lastLabels) {
lastTsMs = ts
lastValue = item.value
continue
}
if (lastLabels) {
res.write(i ? ',' : '')
res.write(JSON.stringify({
metric: parseLabels(lastLabels),
value: [lastTsMs / 1000, lastValue.toString()]
}))
++i
}
lastLabels = hash
lastTsMs = ts
lastValue = item.value
}
res.write(']}}')
res.end()
}
/**
*
* @param dataStream {DataStream}
* @param res {{res: {write: (function(string)), writeHead: (function(number, {}))}}}
* @param traceId {String}
* @returns {Promise<any>}
*/
const outputTempoSpans = async (dataStream, res, traceId) => {
// res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': CORS })
return dataStream.filter(e => e && e.string).map(e => {
try {
return JSON.parse(e.string)
} catch (e) {
return null
}
}, DataStream).filter(e => e).toArray()
}
/**
*
* @param dataStream {DataStream}
* @param res {{res: {write: (function(string)), writeHead: (function(number, {}))}}}
* @returns {Promise<any>}
*
* {"traces": [{"traceID":"AC62F5E32AFE5C28D4F8DCA4C159627E","rootServiceName":"dummy-server","rootTraceName":"request_response","startTimeUnixNano":1661290946168377000,"durationMs":10}]}
*
*/
const outputTempoSearch = async (dataStream, res) => {
const gen = dataStream.toGenerator()
let i = 0
let response = '{"traces": ['
for await (const item of gen()) {
if (!item || !item.string) {
continue
}
let duration = parseInt((item.Span.end_time_unix_nano - item.Span.start_time_unix_nano) / 1000000) || 0;
let trace = `{"traceID": ${item.Span.trace_id}, "rootServiceName": ${item.ServiceName}, "rootTraceName": ${item.Span.name}, "startTimeUnixNano": ${item.Span.start_time_unix_nano}, "durationMs": ${duration}}`
response += (i ? ',' : '')
response += trace
i++
}
response += (']}')
return response
}
/**
*
* @param rawStream {any} Stream from axios response
* @param processors {(function(DataStream): DataStream)[] | undefined}
* @returns {DataStream}
*/
const preprocessStream = (rawStream, processors) => {
let dStream = StringStream.from(rawStream.data).lines().endWith(JSON.stringify({ EOF: true }))
.map(chunk => {
try {
return chunk ? JSON.parse(chunk) : ({})
} catch (e) {
return {}
}
}, DataStream)
.map(chunk => {
try {
if (!chunk || !chunk.labels) {
return chunk
}
const labels = chunk.extra_labels
? { ...parseLabels(chunk.labels), ...parseLabels(chunk.extra_labels) }
: parseLabels(chunk.labels)
return { ...chunk, labels: labels }
} catch (e) {
logger.info(chunk)
return chunk
}
}, DataStream)
if (processors && processors.length) {
processors.forEach(f => {
dStream = f(dStream)
})
}
return dStream
}
/**
*
* @param rawStream {any} Stream from axios response
* @param processors {(function(DataStream): DataStream)[] | undefined}
* @returns {DataStream}
*/
const preprocessLiveStream = (rawStream, processors) => {
let dStream = StringStream.from(rawStream.data).lines().endWith(JSON.stringify({ EOF: true }))
.map(chunk => chunk ? JSON.parse(chunk) : ({}), DataStream)
.filter(chunk => {
return chunk && (chunk.row || chunk.EOF)
}).map(chunk => ({
...(chunk.row || {}),
EOF: chunk.EOF
}))
.map(chunk => {
try {
if (!chunk || !chunk.labels) {
return chunk
}
const labels = chunk.extra_labels
? { ...parseLabels(chunk.labels), ...parseLabels(chunk.extra_labels) }
: parseLabels(chunk.labels)
return { ...chunk, labels: labels }
} catch (e) {
logger.info(chunk)
return chunk
}
}, DataStream)
if (processors && processors.length) {
processors.forEach(f => {
dStream = f(dStream)
})
}
return dStream
}
/* Qryn Metrics Column */
const scanMetricFingerprints = function (settings, client, params) {
logger.debug({ settings }, 'Scanning Clickhouse...')
// populate matrix structure
const resp = {
status: 'success',
data: {
resultType: 'matrix',
result: []
}
}
// Check for required fields or return nothing!
if (!settings || !settings.table || !settings.db || !settings.tag || !settings.metric) { client.send(resp); return }
settings.interval = settings.interval ? parseInt(settings.interval) : 60
if (!settings.timefield) settings.timefield = process.env.CLICKHOUSE_TIMEFIELD || 'record_datetime'
const tags = settings.tag.split(',')
let template = 'SELECT ' + tags.join(', ') + ', groupArray((toUnixTimestamp(timestamp_ns)*1000, toString(value))) AS groupArr FROM (SELECT '
if (tags) {
tags.forEach(function (tag) {
tag = tag.trim()
template += " visitParamExtractString(labels, '" + tag + "') as " + tag + ','
})
}
// if(settings.interval > 0){
template += ' toStartOfInterval(toDateTime(timestamp_ns/1000), INTERVAL ' + settings.interval + ' second) as timestamp_ns, value' +
// } else {
// template += " timestampMs, value"
// }
// template += " timestampMs, value"
' FROM ' + settings.db + '.samples RIGHT JOIN ' + settings.db + '.time_series ON samples.fingerprint = time_series.fingerprint'
if (params.start && params.end) {
template += ' WHERE ' + settings.timefield + ' BETWEEN ' + parseInt(params.start / 1000000000) + ' AND ' + parseInt(params.end / 1000000000)
// template += " WHERE "+settings.timefield+" BETWEEN "+parseInt(params.start/1000000) +" AND "+parseInt(params.end/1000000)
}
if (tags) {
tags.forEach(function (tag) {
tag = tag.trim()
template += " AND (visitParamExtractString(labels, '" + tag + "') != '')"
})
}
if (settings.where) {
template += ' AND ' + settings.where
}
template += ' AND value > 0 ORDER BY timestamp_ns) GROUP BY ' + tags.join(', ')
const stream = ch.query(template)
// or collect records yourself
const rows = []
stream.on('metadata', function (columns) {
// do something with column list
})
stream.on('data', function (row) {
rows.push(row)
})
stream.on('error', function (err) {
// TODO: handler error
client.code(400).send(err)
})
stream.on('end', function () {
logger.debug({ rows }, 'CLICKHOUSE RESPONSE')
if (!rows || rows.length < 1) {
resp.data.result = []
resp.data.stats = fakeStats
} else {
try {
rows.forEach(function (row) {
const metrics = { metric: {}, values: [] }
const tags = settings.tag.split(',')
// bypass empty blocks
if (row[row.length - 1].length < 1) return
// iterate tags
for (let i = 0; i < row.length - 1; i++) {
metrics.metric[tags[i]] = row[i]
}
// iterate values
row[row.length - 1].forEach(function (row) {
if (row[1] === 0) return
metrics.values.push([parseInt(row[0] / 1000), row[1].toString()])
})
resp.data.result.push(metrics)
})
} catch (err) { logger.error(err, 'Error scanning fingerprints') }
}
logger.debug({ resp }, 'QRYN RESPONSE')
client.send(resp)
})
}
/**
* Clickhouse Metrics Column Query
* @param settings {{
* db: string,
* table: string,
* interval: string | number,
* tag: string,
* metric: string
* }}
* @param client {{
* code: function(number): any,