-
Notifications
You must be signed in to change notification settings - Fork 22
/
hec.ts
500 lines (453 loc) · 17.3 KB
/
hec.ts
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
import AbortController from 'abort-controller';
import { default as HttpAgent, HttpOptions, HttpsAgent } from 'agentkeepalive';
import BufferList from 'bl';
import fetch from 'node-fetch';
import { createGzip } from 'zlib';
import { HecConfig } from './config';
import { sleep } from './utils/async';
import { createModuleDebug } from './utils/debug';
import { isHttps, isSuccessfulStatus } from './utils/httputils';
import { exponentialBackoff, resolveWaitTime, retry, linearBackoff } from './utils/retry';
import { AggregateMetric, httpClientStats as httpAgentStats } from './utils/stats';
import { deepMerge, removeEmtpyValues } from './utils/obj';
const { debug, info, warn, error, trace } = createModuleDebug('hec');
/** Number of milliseconds since epoch */
export type EpochMillis = number;
export interface Metadata {
host?: string;
source?: string;
sourcetype?: string;
index?: string;
}
export type Fields = { [k: string]: any };
type SerializedHecMsg = Buffer;
export interface Event {
time: Date | EpochMillis;
body: string | { [k: string]: any };
fields?: Fields;
metadata?: Metadata;
}
export interface Metric {
time: Date | EpochMillis;
name: string;
value: number;
fields?: Fields;
metadata?: Metadata;
}
export interface MultiMetrics {
time: Date | EpochMillis;
measurements: { [name: string]: number | undefined };
fields?: Fields;
metadata?: Metadata;
}
export function serializeTime(time: Date | EpochMillis): number {
if (time instanceof Date) {
return +(time.getTime() / 1000).toFixed(3);
}
return +(time / 1000);
}
export function serializeEvent(event: Event, defaultMetadata?: Metadata, defaultFields?: Fields): SerializedHecMsg {
return Buffer.from(
JSON.stringify({
time: serializeTime(event.time),
event: event.body,
fields: { ...defaultFields, ...event.fields },
...{ ...defaultMetadata, ...event.metadata },
}),
'utf-8'
);
}
export function serializeMetric(metric: Metric, defaultMetadata?: Metadata, defaultFields?: Fields): SerializedHecMsg {
return Buffer.from(
JSON.stringify({
time: serializeTime(metric.time),
fields: {
...defaultFields,
...metric.fields,
metric_name: metric.name,
_value: metric.value,
},
...{ ...defaultMetadata, ...metric.metadata },
}),
'utf-8'
);
}
export function serializeMetrics(
metrics: MultiMetrics,
defaultMetadata?: Metadata,
defaultFields?: Fields
): SerializedHecMsg {
const measurements = Object.fromEntries(
Object.entries(metrics.measurements).map(([key, value]) => [`metric_name:${key}`, value])
);
return Buffer.from(
JSON.stringify({
time: serializeTime(metrics.time),
fields: {
...defaultFields,
...metrics.fields,
...measurements,
},
...{ ...defaultMetadata, ...metrics.metadata },
}),
'utf-8'
);
}
const CONFIG_DEFAULTS = {
token: null,
defaultMetadata: {},
defaultFields: {},
maxQueueEntries: -1,
maxQueueSize: 512_000,
flushTime: 0,
gzip: true,
maxRetries: Infinity,
timeout: 30_000,
requestKeepAlive: true,
validateCertificate: true,
maxSockets: 256,
userAgent: 'ethlogger-hec-client/1.0',
retryWaitTime: exponentialBackoff({ min: 0, max: 180_000 }),
multipleMetricFormatEnabled: false,
};
type CookedHecConfig = Required<HecConfig>;
export function parseHecConfig(config: HecConfig): CookedHecConfig {
const url = new URL(config.url!);
if (url.pathname === '' || url.pathname === '/') {
url.pathname = '/services/collector/event/1.0';
}
return {
...CONFIG_DEFAULTS,
...config,
url: url.href,
token: config.token ?? '',
waitForAvailability: config.waitForAvailability ?? 0,
};
}
export function compressBody(source: BufferList): Promise<BufferList> {
return new Promise((resolve, reject) => {
const stream = createGzip();
const result = new BufferList();
const sourceSize = source.length;
stream.pipe(result);
stream.once('end', () => {
trace(`Compressed batch of HEC messages from ${sourceSize} bytes -> ${result.length} bytes`);
resolve(result);
});
stream.once('error', e => reject(e));
source.pipe(stream, { end: true });
});
}
class FlushHandle {
public promise: Promise<void> | null = null;
constructor(private abortController: AbortController) {}
public cancel() {
this.abortController.abort();
}
}
export function isMetric(msg: Event | Metric): msg is Metric {
return 'name' in msg && typeof msg.name !== 'undefined';
}
const initialCounters = {
errorCount: 0,
retryCount: 0,
queuedMessages: 0,
sentMessages: 0,
queuedBytes: 0,
sentBytes: 0,
transferredBytes: 0,
};
export class HecClient {
public readonly config: CookedHecConfig;
private active: boolean = true;
private queue: SerializedHecMsg[] = [];
private queueSizeBytes: number = 0;
private flushTimer: NodeJS.Timer | null = null;
private activeFlushing: Set<FlushHandle> = new Set();
private httpAgent: HttpAgent | HttpsAgent;
private counters = {
...initialCounters,
};
private aggregates = {
requestDuration: new AggregateMetric(),
batchSize: new AggregateMetric(),
batchSizeBytes: new AggregateMetric(),
batchSizeCompressed: new AggregateMetric(),
};
public constructor(config: HecConfig) {
this.config = parseHecConfig(config);
const agentOptions: HttpOptions = {
keepAlive: this.config.requestKeepAlive,
maxSockets: this.config.maxSockets,
timeout: this.config.timeout,
};
this.httpAgent = isHttps(this.config.url)
? new HttpsAgent({
...agentOptions,
rejectUnauthorized: this.config.validateCertificate,
})
: new HttpAgent(agentOptions);
}
public clone(configOverrides?: Partial<HecConfig>): HecClient {
debug('Cloning HEC client with overrides %O', configOverrides);
if (configOverrides == null || Object.keys(removeEmtpyValues(configOverrides)).length === 0) {
debug('Reusing HEC client for clone without any overrides');
return this;
}
if (configOverrides?.url && configOverrides.url !== this.config.url) {
debug('Creating new HEC client with different URL', configOverrides.url);
return new HecClient(deepMerge(this.config, configOverrides || {}));
}
debug('Creating new HEC client instance but reusing HTTP agent and socket pool');
const cloned = new HecClient(deepMerge(this.config, configOverrides || {}));
cloned.httpAgent = this.httpAgent;
return cloned;
}
public push(msg: Event | Metric) {
return isMetric(msg) ? this.pushMetric(msg) : this.pushEvent(msg);
}
public pushEvent(event: Event) {
const serialized = serializeEvent(event, this.config.defaultMetadata, this.config.defaultFields);
this.pushSerializedMsg(serialized);
}
public pushMetric(metric: Metric) {
const serialized = serializeMetric(metric, this.config.defaultMetadata, this.config.defaultFields);
this.pushSerializedMsg(serialized);
}
public pushMetrics(metrics: MultiMetrics) {
if (this.config.multipleMetricFormatEnabled) {
const serialized = serializeMetrics(metrics, this.config.defaultMetadata, this.config.defaultFields);
this.pushSerializedMsg(serialized);
} else {
const { measurements, ...rest } = metrics;
for (const [name, value] of Object.entries(measurements)) {
if (value != null) {
this.pushMetric({
...rest,
name,
value,
});
}
}
}
}
private pushSerializedMsg(serialized: SerializedHecMsg) {
if (!this.active) {
throw new Error('HEC client has been shut down');
}
this.counters.queuedMessages++;
this.counters.queuedBytes += serialized.length;
if (this.queueSizeBytes + serialized.length > this.config.maxQueueSize) {
debug(
'Flushing HEC queue as size limit would be exceeded by new message (queue size is %s bytes)',
this.queueSizeBytes
);
this.flushInternal();
}
this.queueSizeBytes += serialized.length;
this.queue.push(serialized);
this.scheduleFlush();
}
public async flush(): Promise<void> {
await Promise.all([...this.activeFlushing.values()].map(f => f.promise).concat(this.flushInternal()));
}
public get stats() {
return {
queueSize: this.queue.length,
queueSizeBytes: this.queueSizeBytes,
...this.counters,
httpClient: httpAgentStats(this.httpAgent.getCurrentStatus()),
};
}
public flushStats() {
const stats = {
...this.counters,
...this.aggregates.requestDuration.flush('requestDuration'),
...this.aggregates.batchSize.flush('batchSize'),
...this.aggregates.batchSizeBytes.flush('batchSizeBytes'),
...this.aggregates.batchSizeCompressed.flush('batchSizeCompressed'),
activeFlushingCount: this.activeFlushing.size,
};
this.counters = { ...initialCounters };
return stats;
}
public async shutdown(maxTime?: number) {
info('Shutting down HEC client');
this.active = false;
if (maxTime != null && (this.activeFlushing.size > 0 || this.queue.length > 0)) {
debug(`Waiting for ${this.activeFlushing.size} flush tasks to complete`);
await Promise.race([sleep(maxTime), this.flush()]);
}
if (this.activeFlushing.size > 0) {
debug(`Cancelling ${this.activeFlushing.size} flush tasks`);
this.activeFlushing.forEach(f => f.cancel());
}
}
public async checkAvailable(): Promise<void> {
const url = new URL(this.config.url);
url.pathname = '/services/collector/health';
debug('Checking if HEC is available at %s', url.href);
try {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), this.config.timeout);
const res = await fetch(url.href, {
method: 'GET',
headers: {
'User-Agent': this.config.userAgent,
},
agent: this.httpAgent,
signal: controller.signal,
});
clearTimeout(id);
debug('HEC responded to availability check with HTTP status %d', res.status);
if (!isSuccessfulStatus(res.status)) {
throw new Error(`HTTP Status ${res.status}`);
}
const data = await res.json();
debug('Received availability check response: %o', data);
} catch (e) {
debug('HEC availability check failed', e);
throw e;
}
}
public async waitUntilAvailable(maxTime: number = 20_000) {
const startTime = Date.now();
debug('Checking HEC service %s availability (timeout %d ms)', this.config.url, maxTime);
let checkFailedOnce = false;
await retry(
() =>
this.checkAvailable().catch(e =>
Promise.reject(`HEC service ${this.config.url} not available: ${e.toString()}`)
),
{
taskName: 'HEC availablility',
waitBetween: linearBackoff({ min: 500, step: 250, max: 2500 }),
timeout: maxTime,
onError: e => {
if (!checkFailedOnce) {
warn('HEC service not (yet) available:', e);
info(
'Waiting for HEC service %s to become available (timeout %d ms)',
this.config.url,
maxTime
);
checkFailedOnce = true;
}
},
}
);
if (checkFailedOnce) {
info('HEC service is now available after %d ms', Date.now() - startTime);
}
}
private flushInternal = (): Promise<void> => {
if (this.flushTimer != null) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
if (this.queue.length === 0) {
return Promise.resolve();
}
const queue = this.queue;
this.queue = [];
this.queueSizeBytes = 0;
const abortController = new AbortController();
const flushHandle = new FlushHandle(abortController);
const flushCompletePromise = this.sendToHec(queue, abortController);
flushHandle.promise = flushCompletePromise;
this.activeFlushing.add(flushHandle);
const removeFromActive = () => this.activeFlushing.delete(flushHandle);
flushCompletePromise.then(removeFromActive, removeFromActive);
return flushCompletePromise;
};
private async sendToHec(msgs: SerializedHecMsg[], abortController: AbortController): Promise<void> {
const startTime = Date.now();
debug('Flushing HEC queue with %s messages', msgs.length);
const rawBody = new BufferList(msgs);
const rawBodySize = rawBody.length;
const body = this.config.gzip ? await compressBody(rawBody) : rawBody;
const bodySize = body.length;
this.aggregates.batchSize.push(msgs.length);
this.aggregates.batchSizeBytes.push(rawBodySize);
if (this.config.gzip) {
this.aggregates.batchSizeCompressed.push(bodySize);
}
const headers: { [k: string]: string } = {
'Content-Length': String(bodySize),
'User-Agent': this.config.userAgent,
};
if (this.config.token !== null) {
headers['Authorization'] = `Splunk ${this.config.token}`;
}
if (this.config.gzip) {
headers['Content-Encoding'] = 'gzip';
}
let attempt = 0;
while (true) {
attempt++;
try {
const requestStart = Date.now();
const id = setTimeout(() => abortController.abort(), this.config.timeout);
const response = await fetch(this.config.url, {
method: 'POST',
headers,
body: body.duplicate(),
agent: this.httpAgent,
signal: abortController.signal,
});
clearTimeout(id);
this.aggregates.requestDuration.push(Date.now() - requestStart);
if (!isSuccessfulStatus(response.status)) {
if (debug.enabled) {
try {
const text = await response.text();
debug(`Response from HEC: %s`, text);
} catch (e) {
debug('Failed to retrieve text from HEC response', e);
}
}
throw new Error(`HEC responded with status ${response.status}`);
}
debug(
'Successfully flushed %s HEC messages in %s attempts and %s ms',
msgs.length,
attempt,
Date.now() - startTime
);
this.counters.sentMessages += msgs.length;
this.counters.sentBytes += rawBodySize;
this.counters.transferredBytes += bodySize;
break;
} catch (e) {
this.counters.errorCount++;
debug('Failed to send batch to HEC (attempt %s)', attempt, e);
error('Failed to send batch to HEC (attempt %s): %s', attempt, e.toString());
if (abortController.signal.aborted) {
throw new Error('Aborted');
}
if (attempt <= this.config.maxRetries) {
const retryDelay = resolveWaitTime(this.config.retryWaitTime, attempt);
debug(`Retrying to send batch to HEC in %d ms`, retryDelay);
await sleep(retryDelay);
if (abortController.signal.aborted) {
throw new Error('Aborted');
}
this.counters.retryCount++;
}
}
}
}
private scheduleFlush() {
if (this.config.maxQueueEntries !== -1 && this.queue.length > this.config.maxQueueEntries) {
debug('Flushing HEC queue for entries limit being reached (%s entries)', this.queue.length);
this.flushInternal();
return;
}
if (this.flushTimer == null) {
this.flushTimer = setTimeout(() => {
debug('Flushing HEC queue for time limit being reached');
this.flushInternal();
}, this.config.flushTime ?? 0);
}
}
}