-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathimport-telemetry.ts
More file actions
430 lines (378 loc) · 12.4 KB
/
import-telemetry.ts
File metadata and controls
430 lines (378 loc) · 12.4 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
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
#!/usr/bin/env bun
/**
* Import Telemetry Script
*
* Imports CodeMachine trace and log JSON files into the Grafana/Tempo/Loki stack.
* Useful for viewing user bug reports with full visualization.
*
* Usage:
* bun scripts/import-telemetry.ts <path-to-traces-dir>
* bun scripts/import-telemetry.ts ~/.codemachine/traces
* bun scripts/import-telemetry.ts ./bug-report/traces
*
* Options:
* --loki-url Loki push URL (default: http://localhost:3100)
* --tempo-url Tempo OTLP URL (default: http://localhost:4318)
* --logs-only Only import logs
* --traces-only Only import traces
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join, basename } from 'node:path';
// Configuration
interface Config {
lokiUrl: string;
tempoUrl: string;
logsOnly: boolean;
tracesOnly: boolean;
sourcePath: string;
}
// Our serialized formats (from the exporters)
interface SerializedSpan {
name: string;
traceId: string;
spanId: string;
parentSpanId?: string;
startTime: number; // ms
endTime: number; // ms
duration: number; // ms
status: {
code: number;
message?: string;
};
attributes: Record<string, unknown>;
events: Array<{
name: string;
time: number;
attributes?: Record<string, unknown>;
}>;
}
interface TraceFile {
version: number;
service: string;
exportedAt: string;
spanCount: number;
spans: SerializedSpan[];
}
interface SerializedLog {
timestamp: [number, number]; // [seconds, nanoseconds]
severityNumber: number;
severityText?: string;
body: unknown;
attributes: Record<string, unknown>;
resource?: Record<string, unknown>;
}
interface LogFile {
version: number;
service: string;
exportedAt: string;
logCount: number;
logs: SerializedLog[];
}
// Parse command line arguments
function parseArgs(): Config {
const args = process.argv.slice(2);
const config: Config = {
lokiUrl: 'http://localhost:3100',
tempoUrl: 'http://localhost:4318',
logsOnly: false,
tracesOnly: false,
sourcePath: '',
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--loki-url' && args[i + 1]) {
config.lokiUrl = args[++i];
} else if (arg === '--tempo-url' && args[i + 1]) {
config.tempoUrl = args[++i];
} else if (arg === '--logs-only') {
config.logsOnly = true;
} else if (arg === '--traces-only') {
config.tracesOnly = true;
} else if (!arg.startsWith('-')) {
config.sourcePath = arg;
}
}
return config;
}
// Find trace and log files in a directory
function findFiles(dir: string): { traceFiles: string[]; logFiles: string[] } {
const traceFiles: string[] = [];
const logFiles: string[] = [];
function scan(path: string) {
const stat = statSync(path);
if (stat.isDirectory()) {
for (const entry of readdirSync(path)) {
scan(join(path, entry));
}
} else if (stat.isFile() && path.endsWith('.json')) {
const name = basename(path);
if (name.includes('-logs') || name === 'latest-logs.json') {
logFiles.push(path);
} else if (!name.includes('-logs')) {
traceFiles.push(path);
}
}
}
scan(dir);
return { traceFiles, logFiles };
}
// Convert our span format to OTLP JSON format
function spansToOTLP(spans: SerializedSpan[], serviceName: string): object {
// Group spans by trace ID
const spansByTrace = new Map<string, SerializedSpan[]>();
for (const span of spans) {
const existing = spansByTrace.get(span.traceId) || [];
existing.push(span);
spansByTrace.set(span.traceId, existing);
}
// Convert to OTLP format
const resourceSpans = [
{
resource: {
attributes: [
{ key: 'service.name', value: { stringValue: serviceName } },
{ key: 'telemetry.sdk.name', value: { stringValue: 'codemachine-import' } },
],
},
scopeSpans: [
{
scope: { name: 'codemachine.import' },
spans: spans.map((span) => ({
traceId: hexToBytes(span.traceId),
spanId: hexToBytes(span.spanId),
parentSpanId: span.parentSpanId ? hexToBytes(span.parentSpanId) : undefined,
name: span.name,
kind: 1, // INTERNAL
startTimeUnixNano: String(Math.floor(span.startTime * 1_000_000)),
endTimeUnixNano: String(Math.floor(span.endTime * 1_000_000)),
attributes: Object.entries(span.attributes || {}).map(([key, value]) => ({
key,
value: attributeValue(value),
})),
status: {
code: span.status.code === 2 ? 2 : span.status.code === 1 ? 1 : 0,
message: span.status.message,
},
events: (span.events || []).map((event) => ({
name: event.name,
timeUnixNano: String(Math.floor(event.time * 1_000_000)),
attributes: Object.entries(event.attributes || {}).map(([key, value]) => ({
key,
value: attributeValue(value),
})),
})),
})),
},
],
},
];
return { resourceSpans };
}
// Convert hex string to byte array for OTLP JSON
// OTLP JSON expects byte arrays as base64-encoded strings
function hexToBytes(hex: string): string {
// For OTLP JSON format, we need to provide hex string directly
// The receiver expects lowercase hex
return hex.toLowerCase();
}
// Convert a value to OTLP attribute value format
function attributeValue(value: unknown): object {
if (typeof value === 'string') {
return { stringValue: value };
} else if (typeof value === 'number') {
if (Number.isInteger(value)) {
return { intValue: String(value) };
}
return { doubleValue: value };
} else if (typeof value === 'boolean') {
return { boolValue: value };
} else if (Array.isArray(value)) {
return { arrayValue: { values: value.map(attributeValue) } };
}
return { stringValue: String(value) };
}
// Convert our log format to Loki push format
function logsToLokiFormat(logs: SerializedLog[], serviceName: string): object {
// Group logs by their label set
const streams = new Map<string, Array<[string, string]>>();
for (const log of logs) {
// Build labels
const labels: Record<string, string> = {
service_name: serviceName,
severity_text: log.severityText || 'UNSPECIFIED',
imported: 'true',
};
// Add trace correlation if present
if (log.attributes['trace.id']) {
labels.trace_id = String(log.attributes['trace.id']);
}
if (log.attributes['span.id']) {
labels.span_id = String(log.attributes['span.id']);
}
// Create label key for grouping
const labelKey = Object.entries(labels)
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => `${k}="${v}"`)
.join(',');
// Convert timestamp
const [seconds, nanos] = log.timestamp;
const timestampNs = String(BigInt(seconds) * BigInt(1_000_000_000) + BigInt(nanos));
// Format log line
const logLine = typeof log.body === 'string' ? log.body : JSON.stringify(log.body);
// Add to stream
const existing = streams.get(labelKey) || [];
existing.push([timestampNs, logLine]);
streams.set(labelKey, existing);
}
// Convert to Loki format
const lokiStreams = Array.from(streams.entries()).map(([labelKey, values]) => ({
stream: Object.fromEntries(
labelKey.split(',').map((pair) => {
const [key, value] = pair.split('=');
return [key, value.replace(/^"|"$/g, '')];
})
),
values: values.sort((a, b) => a[0].localeCompare(b[0])),
}));
return { streams: lokiStreams };
}
// Send traces to Tempo via OTLP
async function sendTracesToTempo(spans: SerializedSpan[], serviceName: string, tempoUrl: string): Promise<void> {
const otlpData = spansToOTLP(spans, serviceName);
const url = `${tempoUrl}/v1/traces`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(otlpData),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Failed to send traces to Tempo: ${response.status} ${text}`);
}
}
// Send logs to Loki
async function sendLogsToLoki(logs: SerializedLog[], serviceName: string, lokiUrl: string): Promise<void> {
const lokiData = logsToLokiFormat(logs, serviceName);
const url = `${lokiUrl}/loki/api/v1/push`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(lokiData),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Failed to send logs to Loki: ${response.status} ${text}`);
}
}
// Read and parse a JSON file
function readJsonFile<T>(path: string): T | null {
try {
const content = readFileSync(path, 'utf-8');
return JSON.parse(content) as T;
} catch (error) {
console.error(`Failed to read ${path}:`, error);
return null;
}
}
// Main function
async function main() {
const config = parseArgs();
if (!config.sourcePath) {
console.log(`
Usage: bun scripts/import-telemetry.ts <path-to-traces-dir>
Examples:
bun scripts/import-telemetry.ts .codemachine/traces
bun scripts/import-telemetry.ts ~/Downloads/bug-report-traces
bun scripts/import-telemetry.ts ./traces --loki-url http://localhost:3100
Options:
--loki-url <url> Loki URL (default: http://localhost:3100)
--tempo-url <url> Tempo OTLP URL (default: http://localhost:4318)
--logs-only Only import logs
--traces-only Only import traces
`);
process.exit(1);
}
if (!existsSync(config.sourcePath)) {
console.error(`Path not found: ${config.sourcePath}`);
process.exit(1);
}
console.log(`Importing telemetry from: ${config.sourcePath}`);
console.log(`Loki URL: ${config.lokiUrl}`);
console.log(`Tempo URL: ${config.tempoUrl}`);
console.log('');
// Find files
const stat = statSync(config.sourcePath);
let traceFiles: string[] = [];
let logFiles: string[] = [];
if (stat.isDirectory()) {
const found = findFiles(config.sourcePath);
traceFiles = found.traceFiles;
logFiles = found.logFiles;
} else {
// Single file
const name = basename(config.sourcePath);
if (name.includes('-logs') || name === 'latest-logs.json') {
logFiles = [config.sourcePath];
} else {
traceFiles = [config.sourcePath];
}
}
console.log(`Found ${traceFiles.length} trace file(s) and ${logFiles.length} log file(s)`);
console.log('');
// Import traces
if (!config.logsOnly && traceFiles.length > 0) {
console.log('Importing traces...');
let totalSpans = 0;
for (const file of traceFiles) {
const data = readJsonFile<TraceFile>(file);
if (!data || !data.spans || data.spans.length === 0) {
console.log(` Skipping ${basename(file)} (no spans)`);
continue;
}
try {
await sendTracesToTempo(data.spans, data.service || 'codemachine', config.tempoUrl);
totalSpans += data.spans.length;
console.log(` Imported ${data.spans.length} spans from ${basename(file)}`);
} catch (error) {
console.error(` Failed to import ${basename(file)}:`, error);
}
}
console.log(`Total: ${totalSpans} spans imported`);
console.log('');
}
// Import logs
if (!config.tracesOnly && logFiles.length > 0) {
console.log('Importing logs...');
let totalLogs = 0;
for (const file of logFiles) {
const data = readJsonFile<LogFile>(file);
if (!data || !data.logs || data.logs.length === 0) {
console.log(` Skipping ${basename(file)} (no logs)`);
continue;
}
try {
await sendLogsToLoki(data.logs, data.service || 'codemachine', config.lokiUrl);
totalLogs += data.logs.length;
console.log(` Imported ${data.logs.length} logs from ${basename(file)}`);
} catch (error) {
console.error(` Failed to import ${basename(file)}:`, error);
}
}
console.log(`Total: ${totalLogs} logs imported`);
console.log('');
}
console.log('Done! View in Grafana at http://localhost:3000');
console.log('');
console.log('Tips:');
console.log(' - Imported logs have label: imported="true"');
console.log(' - Query imported logs: {service_name="codemachine", imported="true"}');
console.log(' - Traces appear in Tempo under service "codemachine"');
}
main().catch((error) => {
console.error('Error:', error);
process.exit(1);
});