-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
qryn_node.js
executable file
·491 lines (432 loc) · 18.1 KB
/
qryn_node.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
#!/usr/bin/env node
/*
* qryn: polyglot observability API
* (C) 2018-2024 QXIP BV
*/
const { boolEnv, readerMode, writerMode } = require('./common')
const { Duplex } = require('stream')
this.readonly = boolEnv('READONLY')
this.http_user = process.env.QRYN_LOGIN || process.env.CLOKI_LOGIN || undefined
this.http_password = process.env.QRYN_PASSWORD || process.env.CLOKI_PASSWORD || undefined
this.maxListeners = process.env.MAXLISTENERS || 0;
process.setMaxListeners(this.maxListeners)
require('./plugins/engine')
const DATABASE = require('./lib/db/clickhouse')
const UTILS = require('./lib/utils')
/* ProtoBuf Helpers */
const fs = require('fs')
const path = require('path')
const logger = require('./lib/logger')
/* Alerting */
const { startAlerting, stop } = require('./lib/db/alerting')
/* Fingerprinting */
this.fingerPrint = UTILS.fingerPrint
this.toJSON = UTILS.toJSON
/* Database this.bulk Helpers */
this.bulk = DATABASE.cache.bulk // samples
this.bulk_labels = DATABASE.cache.bulk_labels // labels
this.labels = DATABASE.cache.labels // in-memory labels
/* Function Helpers */
this.labelParser = UTILS.labelParser
const init = DATABASE.init
this.reloadFingerprints = DATABASE.reloadFingerprints
this.scanFingerprints = DATABASE.scanFingerprints
this.scanTempo = DATABASE.scanTempo
this.instantQueryScan = DATABASE.instantQueryScan
this.tempoQueryScan = DATABASE.tempoQueryScan
this.scanMetricFingerprints = DATABASE.scanMetricFingerprints
this.tempoQueryScan = DATABASE.tempoQueryScan
this.scanClickhouse = DATABASE.scanClickhouse
this.pushZipkin = DATABASE.pushZipkin
this.pushOTLP = DATABASE.pushOTLP
this.queryTempoTags = DATABASE.queryTempoTags
this.queryTempoValues = DATABASE.queryTempoValues
let profiler = null
const pako = require('pako')
const {
shaper,
parsers,
lokiPushJSONParser, lokiPushProtoParser, jsonParser, rawStringParser, tempoPushParser, tempoPushNDJSONParser,
yamlParser, prometheusPushProtoParser, combinedParser, otlpPushProtoParser, wwwFormParser, otlpLogsDataParser
} = require('./parsers')
const fastifyPlugin = require('fastify-plugin')
let fastify = require('fastify')({
logger,
bodyLimit: parseInt(process.env.FASTIFY_BODYLIMIT) || 5242880,
requestTimeout: parseInt(process.env.FASTIFY_REQUESTTIMEOUT) || 0,
maxRequestsPerSocket: parseInt(process.env.FASTIFY_MAXREQUESTS) || 0
});
(async () => {
try {
await init(process.env.CLICKHOUSE_DB || 'cloki')
if (process.env.MODE === 'init_only') {
process.exit(0)
}
} catch (err) {
logger.error(err, 'Error starting qryn')
process.exit(1)
}
try {
if (!this.readonly) {
await startAlerting()
}
await DATABASE.checkDB()
if (!this.readonly && process.env.PROFILE) {
const tag = JSON.stringify({ profiler_id: process.env.PROFILE, label: 'RAM usage' })
const fp = this.fingerPrint(tag)
profiler = setInterval(() => {
this.bulk_labels.add([[new Date().toISOString().split('T')[0], fp, tag, '']])
this.bulk.add([[fp,
[['label', 'RAM usage'], ['profiler_id', process.env.PROFILE]],
BigInt(Date.now()) * BigInt(1000000),
process.memoryUsage().rss / 1024 / 1024, ''
]])
}, 1000)
}
} catch (err) {
logger.error(err, 'Error starting qryn')
process.exit(1)
}
await fastify.register(fastifyPlugin((fastify, opts, done) => {
const snappyPaths = [
'/api/v1/prom/remote/write',
'/api/prom/remote/write',
'/prom/remote/write',
'/loki/api/v1/push',
'/api/v1/write',
'/api/prom/push'
]
fastify.addHook('preParsing', (request, reply, payload, done) => {
if (snappyPaths.indexOf(request.routeOptions.url) !== -1) {
if (request.headers['content-encoding'] === 'snappy') {
delete request.headers['content-encoding']
}
}
done(null, payload)
})
done()
}))
await fastify.register(require('@fastify/compress'), {
encodings: ['gzip']
})
await fastify.register(require('@fastify/url-data'))
await fastify.register(require('@fastify/websocket'))
/* Fastify local metrics exporter */
if (boolEnv('FASTIFY_METRICS')) {
const metricsPlugin = require('fastify-metrics')
fastify.register(metricsPlugin, { endpoint: '/metrics' })
} else {
fastify.get('/metrics', () => 'not supported')
}
fastify.get('/config', () => 'not supported')
fastify.get('/influx/api/v2/write/health', () => 'ok')
/* CORS Helper */
const CORS = process.env.CORS_ALLOW_ORIGIN || '*'
fastify.register(require('@fastify/cors'), {
origin: CORS
})
fastify.after((err) => {
if (err) {
logger.error({ err }, 'Error creating http response')
throw err
}
})
fastify.__post = fastify.post
fastify.post = (route, handler, _parsers) => {
if (_parsers) {
for (const t of Object.keys(_parsers)) {
parsers.register('post', route, t, _parsers[t])
}
}
return fastify.__post(route, handler)
}
fastify.__put = fastify.put
fastify.put = (route, handler, _parsers) => {
const __parsers = handler.parsers || _parsers
if (__parsers) {
for (const t of Object.keys(__parsers)) {
parsers.register('put', route, t, __parsers[t])
}
}
return fastify.__put(route, handler)
}
fastify.__all = fastify.all
fastify.all = (route, handler, _parsers) => {
const __parsers = handler.parsers || _parsers
if (__parsers) {
for (const t of Object.keys(__parsers)) {
parsers.register('post', route, t, __parsers[t])
parsers.register('put', route, t, __parsers[t])
}
}
return fastify.__all(route, handler)
}
/* Enable Simple Authentication */
if (this.http_user && this.http_password) {
function checkAuth (username, password, req, reply, done) {
if (username === this.http_user && password === this.http_password) {
done()
} else {
done(new (require('http-errors').Unauthorized)('Unauthorized!: Wrong username/password.'))
}
}
const validate = checkAuth.bind(this)
fastify.register(require('@fastify/basic-auth'), {
validate,
authenticate: true
})
fastify.after(() => {
fastify.addHook('preHandler', fastify.basicAuth)
})
}
/* 404 Handler */
const handler404 = require('./lib/handlers/404.js').bind(this)
fastify.setNotFoundHandler(handler404)
fastify.setErrorHandler(require('./lib/handlers/errors').handler.bind(this))
/* Hello qryn test API */
const handlerHello = require('./lib/handlers/ready').bind(this)
fastify.get('/hello', handlerHello)
fastify.get('/ready', handlerHello)
/* Write Handler */
const handlerPush = require('./lib/handlers/push.js').bind(this)
writerMode && fastify.post('/loki/api/v1/push', handlerPush, {
'application/json': lokiPushJSONParser,
'application/x-protobuf': lokiPushProtoParser,
'*': lokiPushJSONParser
})
/* Elastic Write Handler */
const handlerElasticPush = require('./lib/handlers/elastic_index.js').bind(this)
writerMode && fastify.post('/:target/_doc', handlerElasticPush, {
'application/json': jsonParser,
'*': rawStringParser
})
writerMode && fastify.post('/:target/_create/:id', handlerElasticPush, {
'application/json': jsonParser,
'*': rawStringParser
})
writerMode && fastify.put('/:target/_doc/:id', handlerElasticPush, {
'application/json': jsonParser,
'*': rawStringParser
})
writerMode && fastify.put('/:target/_create/:id', handlerElasticPush, {
'application/json': jsonParser,
'*': rawStringParser
})
const handlerElasticBulk = require('./lib/handlers/elastic_bulk.js').bind(this)
writerMode && fastify.post('/_bulk', handlerElasticBulk, {
'application/json': jsonParser,
'*': rawStringParser
})
writerMode && fastify.post('/:target/_bulk', handlerElasticBulk, {
'application/json': jsonParser,
'*': rawStringParser
})
/* Tempo Write Handler */
this.tempo_tagtrace = boolEnv('TEMPO_TAGTRACE')
const handlerTempoPush = require('./lib/handlers/tempo_push.js').bind(this)
writerMode && fastify.post('/tempo/api/push', handlerTempoPush, {
'application/json': tempoPushParser,
'application/x-ndjson': tempoPushNDJSONParser,
'*': tempoPushParser
})
writerMode && fastify.post('/tempo/spans', handlerTempoPush, {
'application/json': tempoPushParser,
'application/x-ndjson': tempoPushNDJSONParser,
'*': tempoPushParser
})
writerMode && fastify.post('/api/v2/spans', handlerTempoPush, {
'application/json': tempoPushParser,
'application/x-ndjson': tempoPushNDJSONParser,
'*': tempoPushParser
})
/* Tempo Traces Query Handler */
this.tempo_span = process.env.TEMPO_SPAN || 24
const handlerTempoTraces = require('./lib/handlers/tempo_traces.js').bind(this)
readerMode && fastify.get('/api/traces/:traceId', handlerTempoTraces)
readerMode && fastify.get('/api/traces/:traceId/:json', handlerTempoTraces)
readerMode && fastify.get('/tempo/api/traces/:traceId', handlerTempoTraces)
readerMode && fastify.get('/tempo/api/traces/:traceId/:json', handlerTempoTraces)
/* Tempo Tag Handlers */
const handlerTempoLabel = require('./lib/handlers/tempo_tags').bind(this)
readerMode && fastify.get('/api/search/tags', handlerTempoLabel)
readerMode && fastify.get('/tempo/api/search/tags', handlerTempoLabel)
const handlerTempoLabelV2 = require('./lib/handlers/tempo_v2_tags').bind(this)
readerMode && fastify.get('/api/v2/search/tags', handlerTempoLabelV2)
readerMode && fastify.get('/tempo/api/v2/search/tags', handlerTempoLabelV2)
/* Tempo Tag Value Handler */
const handlerTempoLabelValues = require('./lib/handlers/tempo_values').bind(this)
readerMode && fastify.get('/api/search/tag/:name/values', handlerTempoLabelValues)
readerMode && fastify.get('/tempo/api/search/tag/:name/values', handlerTempoLabelValues)
const handlerTempoLabelV2Values = require('./lib/handlers/tempo_v2_values').bind(this)
readerMode && fastify.get('/api/v2/search/tag/:name/values', handlerTempoLabelV2Values)
readerMode && fastify.get('/tempo/api/v2/search/tag/:name/values', handlerTempoLabelV2Values)
/* Tempo Traces Query Handler */
const handlerTempoSearch = require('./lib/handlers/tempo_search.js').bind(this)
readerMode && fastify.get('/api/search', handlerTempoSearch)
readerMode && fastify.get('/tempo/api/search', handlerTempoSearch)
/* Tempo Echo Handler */
const handlerTempoEcho = require('./lib/handlers/echo.js').bind(this)
fastify.get('/api/echo', handlerTempoEcho)
fastify.get('/tempo/api/echo', handlerTempoEcho)
/* Telegraf HTTP Bulk handler */
const handlerTelegraf = require('./lib/handlers/telegraf.js').bind(this)
writerMode && fastify.post('/telegraf', handlerTelegraf, {
'*': jsonParser
})
/* Datadog Log Push Handler */
const handlerDatadogLogPush = require('./lib/handlers/datadog_log_push.js').bind(this)
writerMode && fastify.post('/api/v2/logs', handlerDatadogLogPush, {
'application/json': jsonParser,
'*': rawStringParser
})
/* Datadog Series Push Handler */
const handlerDatadogSeriesPush = require('./lib/handlers/datadog_series_push.js').bind(this)
writerMode && fastify.post('/api/v2/series', handlerDatadogSeriesPush, {
'application/json': jsonParser,
'*': rawStringParser
})
/* Query Handler */
const handlerQueryRange = require('./lib/handlers/query_range.js').bind(this)
readerMode && fastify.get('/loki/api/v1/query_range', handlerQueryRange)
/* Label Handlers */
/* Label Value Handler via query (test) */
const handlerQuery = require('./lib/handlers/query.js').bind(this)
readerMode && fastify.get('/loki/api/v1/query', handlerQuery)
/* Label Handlers */
const handlerLabel = require('./lib/handlers/label.js').bind(this)
readerMode && fastify.get('/loki/api/v1/label', handlerLabel)
readerMode && fastify.get('/loki/api/v1/labels', handlerLabel)
/* Label Value Handler */
const handlerLabelValues = require('./lib/handlers/label_values.js').bind(this)
readerMode && fastify.get('/loki/api/v1/label/:name/values', handlerLabelValues)
/* Series Handler - experimental support for both Loki and Prometheus */
const handlerSeries = require('./lib/handlers/series.js').bind(this)
readerMode && fastify.get('/loki/api/v1/series', handlerSeries)
const handlerPromSeries = require('./lib/handlers/prom_series.js').bind(this)
readerMode && fastify.get('/api/v1/series', handlerPromSeries)
readerMode && fastify.post('/api/v1/series', handlerPromSeries, {
'application/x-www-form-urlencoded': wwwFormParser
})
readerMode && fastify.register(async (fastify) => {
fastify.get('/loki/api/v1/tail', { websocket: true }, require('./lib/handlers/tail').bind(this))
})
/* ALERT MANAGER Handlers */
readerMode && fastify.get('/api/prom/rules', require('./lib/handlers/alerts/get_rules').bind(this))
readerMode && fastify.get('/api/prom/rules/:ns/:group', require('./lib/handlers/alerts/get_group').bind(this))
readerMode && fastify.post('/api/prom/rules/:ns', require('./lib/handlers/alerts/post_group').bind(this), {
'*': yamlParser
})
readerMode && fastify.delete('/api/prom/rules/:ns/:group', require('./lib/handlers/alerts/del_group').bind(this))
readerMode && fastify.delete('/api/prom/rules/:ns', require('./lib/handlers/alerts/del_ns').bind(this))
readerMode && fastify.get('/prometheus/api/v1/rules', require('./lib/handlers/alerts/prom_get_rules').bind(this))
/* PROMETHEUS REMOTE WRITE Handlers */
const promWriteHandler = require('./lib/handlers/prom_push.js').bind(this)
const remoteWritePaths = [
'/api/v1/prom/remote/write',
'/api/prom/remote/write',
'/prom/remote/write',
'/api/v1/write'
]
for (const path of remoteWritePaths) {
writerMode && fastify.post(path, promWriteHandler, {
'application/x-protobuf': prometheusPushProtoParser,
'application/json': jsonParser,
'*': combinedParser(prometheusPushProtoParser, jsonParser)
})
writerMode && fastify.get(path, handlerTempoEcho)
}
/* PROMQETHEUS API EMULATION */
const handlerPromQueryRange = require('./lib/handlers/prom_query_range.js').bind(this)
readerMode && fastify.post('/api/v1/query_range', handlerPromQueryRange, {
'application/x-www-form-urlencoded': wwwFormParser
})
readerMode && fastify.get('/api/v1/query_range', handlerPromQueryRange)
const handlerPromQuery = require('./lib/handlers/prom_query.js').bind(this)
readerMode && fastify.post('/api/v1/query', handlerPromQuery, {
'application/x-www-form-urlencoded': wwwFormParser
})
readerMode && fastify.get('/api/v1/query', handlerPromQuery)
const handlerPromLabel = require('./lib/handlers/promlabel.js').bind(this)
const handlerPromLabelValues = require('./lib/handlers/promlabel_values.js').bind(this)
readerMode && fastify.get('/api/v1/labels', handlerPromLabel) // piggyback on qryn labels
readerMode && fastify.get('/api/v1/label/:name/values', handlerPromLabelValues) // piggyback on qryn values
readerMode && fastify.post('/api/v1/labels', handlerPromLabel, {
'*': rawStringParser
}) // piggyback on qryn labels
readerMode && fastify.post('/api/v1/label/:name/values', handlerPromLabelValues, {
'*': rawStringParser
}) // piggyback on qryn values
const handlerPromDefault = require('./lib/handlers/prom_default.js')
readerMode && fastify.get('/api/v1/metadata', handlerPromDefault.misc.bind(this)) // default handler TBD
readerMode && fastify.get('/api/v1/rules', handlerPromDefault.rules.bind(this)) // default handler TBD
readerMode && fastify.get('/api/v1/query_exemplars', handlerPromDefault.misc.bind(this)) // default handler TBD
readerMode && fastify.post('/api/v1/query_exemplars', handlerPromDefault.misc.bind(this), {
'application/x-www-form-urlencoded': wwwFormParser
}) // default handler TBD
readerMode && fastify.get('/api/v1/format_query', handlerPromDefault.misc.bind(this)) // default handler TBD
readerMode && fastify.post('/api/v1/format_query', handlerPromDefault.misc.bind(this), {
'application/x-www-form-urlencoded': wwwFormParser
}) // default handler TBD
fastify.get('/api/v1/status/buildinfo', handlerPromDefault.buildinfo.bind(this)) // default handler TBD
/* NewRelic Log Handler */
const handlerNewrelicLogPush = require('./lib/handlers/newrelic_log_push.js').bind(this)
writerMode && fastify.post('/log/v1', handlerNewrelicLogPush, {
'text/plain': jsonParser,
'*': jsonParser
})
/* INFLUX WRITE Handlers */
const handlerInfluxWrite = require('./lib/handlers/influx_write.js').bind(this)
writerMode && fastify.post('/write', handlerInfluxWrite, {
'*': rawStringParser
})
writerMode && fastify.post('/influx/api/v2/write', handlerInfluxWrite, {
'*': rawStringParser
})
/* INFLUX HEALTH Handlers */
const handlerInfluxHealth = require('./lib/handlers/influx_health.js').bind(this)
fastify.get('/health', handlerInfluxHealth)
fastify.get('/influx/health', handlerInfluxHealth)
const handlerOTLPPush = require('./lib/handlers/otlp_push').bind(this)
writerMode && fastify.post('/v1/traces', handlerOTLPPush, {
'*': otlpPushProtoParser
})
fastify = parsers.init(fastify)
/* QRYN-VIEW Optional Handler */
if (fs.existsSync(path.join(__dirname, 'view/index.html'))) {
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'view'),
prefix: '/'
})
const idx = fs.readFileSync(path.join(__dirname, 'view/index.html'), 'utf8')
for (const fakePath of ['/plugins', '/users', '/datasources', '/datasources/:ds']) {
fastify.get(fakePath,
(req, reply) =>
reply.code(200).header('Content-Type', 'text/html').send(idx))
}
}
readerMode && require('./pyroscope/pyroscope').init(fastify)
const handleOTLPLogs = require('./lib/handlers/otlp_log_push').bind(this)
writerMode && fastify.post('/v1/logs', handleOTLPLogs, {
'*': otlpLogsDataParser
})
// Run API Service
fastify.listen(
{
port: process.env.PORT || 3100,
host: process.env.HOST || '0.0.0.0'
},
(err, address) => {
if (err) throw err
logger.info('Qryn API up')
fastify.log.info(`Qryn API listening on ${address}`)
}
)
})()
module.exports.stop = () => {
shaper.stop()
profiler && clearInterval(profiler)
fastify.close()
DATABASE.stop()
require('./parser/transpiler').stop()
stop()
}