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
|
#!/usr/bin/env node
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'path';
import fs from 'fs';
import net from 'net';
import os from 'os';
import { spawn, execSync } from 'child_process';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT_DIR = path.resolve(__dirname, '..');
const GEMINI_DIR = path.join(ROOT_DIR, '.gemini');
const OTEL_DIR = path.join(GEMINI_DIR, 'otel');
const BIN_DIR = path.join(OTEL_DIR, 'bin');
const OTEL_CONFIG_FILE = path.join(OTEL_DIR, 'collector-local.yaml');
const OTEL_LOG_FILE = path.join(OTEL_DIR, 'collector.log');
const JAEGER_LOG_FILE = path.join(OTEL_DIR, 'jaeger.log');
const JAEGER_PORT = 16686;
const WORKSPACE_SETTINGS_FILE = path.join(GEMINI_DIR, 'settings.json');
// This configuration is for the primary otelcol-contrib instance.
// It receives from the CLI on 4317, exports traces to Jaeger on 14317,
// and sends metrics/logs to the debug log.
const OTEL_CONFIG_CONTENT = `
receivers:
otlp:
protocols:
grpc:
endpoint: "localhost:4317"
processors:
batch:
timeout: 1s
exporters:
otlp:
endpoint: "localhost:14317"
tls:
insecure: true
debug:
verbosity: detailed
service:
telemetry:
logs:
level: "debug"
metrics:
level: "none"
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [debug]
logs:
receivers: [otlp]
processors: [batch]
exporters: [debug]
`;
function getJson(url) {
const tmpFile = path.join(
os.tmpdir(),
`gemini-cli-releases-${Date.now()}.json`,
);
try {
execSync(
`curl -sL -H "User-Agent: gemini-cli-dev-script" -o "${tmpFile}" "${url}"`,
{ stdio: 'pipe' },
);
const content = fs.readFileSync(tmpFile, 'utf-8');
return JSON.parse(content);
} catch (e) {
console.error(`Failed to fetch or parse JSON from ${url}`);
throw e;
} finally {
if (fs.existsSync(tmpFile)) {
fs.unlinkSync(tmpFile);
}
}
}
function downloadFile(url, dest) {
try {
// Use -sS to hide progress but show errors.
execSync(`curl -fL -sS -o "${dest}" "${url}"`, {
stdio: 'pipe', // Suppress stdout/stderr from the command
});
return dest;
} catch (e) {
console.error(`Failed to download file from ${url}`);
throw e;
}
}
function findFile(startPath, filter) {
if (!fs.existsSync(startPath)) {
return null;
}
const files = fs.readdirSync(startPath);
for (const file of files) {
const filename = path.join(startPath, file);
const stat = fs.lstatSync(filename);
if (stat.isDirectory()) {
const result = findFile(filename, filter);
if (result) return result;
} else if (filter(file)) {
// Test the simple file name, not the full path.
return filename;
}
}
return null;
}
async function ensureBinary(
executableName,
repo,
assetNameCallback,
binaryNameInArchive,
) {
const executablePath = path.join(BIN_DIR, executableName);
if (fileExists(executablePath)) {
console.log(`โ
${executableName} already exists at ${executablePath}`);
return executablePath;
}
console.log(`๐ ${executableName} not found. Downloading from ${repo}...`);
const platform = process.platform === 'win32' ? 'windows' : process.platform;
const arch = process.arch === 'x64' ? 'amd64' : process.arch;
const ext = platform === 'windows' ? 'zip' : 'tar.gz';
if (platform === 'windows' && arch === 'arm64') {
if (repo === 'jaegertracing/jaeger') {
console.warn(
`โ ๏ธ Jaeger does not have a release for Windows on ARM64. Skipping.`,
);
return null;
}
}
let release;
let asset;
if (repo === 'jaegertracing/jaeger') {
console.log(`๐ Finding latest Jaeger v2+ asset...`);
const releases = getJson(`https://api.github.com/repos/${repo}/releases`);
const sortedReleases = releases
.filter((r) => !r.prerelease && r.tag_name.startsWith('v'))
.sort((a, b) => {
const aVersion = a.tag_name.substring(1).split('.').map(Number);
const bVersion = b.tag_name.substring(1).split('.').map(Number);
for (let i = 0; i < Math.max(aVersion.length, bVersion.length); i++) {
if ((aVersion[i] || 0) > (bVersion[i] || 0)) return -1;
if ((aVersion[i] || 0) < (bVersion[i] || 0)) return 1;
}
return 0;
});
for (const r of sortedReleases) {
// Jaeger v2 assets are named like 'jaeger-2.7.0-...' but can be in a v1.x release tag.
// We must search for the asset using simple string matching.
const expectedSuffix = `-${platform}-${arch}.tar.gz`;
const foundAsset = r.assets.find(
(a) =>
a.name.startsWith('jaeger-2.') && a.name.endsWith(expectedSuffix),
);
if (foundAsset) {
release = r;
asset = foundAsset;
console.log(
`โฌ๏ธ Found ${asset.name} in release ${r.tag_name}, downloading...`,
);
break;
}
}
if (!asset) {
throw new Error(
`Could not find a suitable Jaeger v2 asset for platform ${platform}/${arch}.`,
);
}
} else {
release = getJson(`https://api.github.com/repos/${repo}/releases/latest`);
const version = release.tag_name.startsWith('v')
? release.tag_name.substring(1)
: release.tag_name;
const assetName = assetNameCallback(version, platform, arch, ext);
asset = release.assets.find((a) => a.name === assetName);
}
if (!asset) {
throw new Error(
`Could not find a suitable asset for ${repo} on platform ${platform}/${arch}.`,
);
}
const downloadUrl = asset.browser_download_url;
const tmpDir = fs.mkdtempSync(
path.join(os.tmpdir(), 'gemini-cli-telemetry-'),
);
const archivePath = path.join(tmpDir, asset.name);
try {
downloadFile(downloadUrl, archivePath);
if (ext === 'zip') {
execSync(`unzip -o "${archivePath}" -d "${tmpDir}"`, { stdio: 'pipe' });
} else {
execSync(`tar -xzf "${archivePath}" -C "${tmpDir}"`, { stdio: 'pipe' });
}
const nameToFind = binaryNameInArchive || executableName;
const foundBinaryPath = findFile(tmpDir, (file) => {
if (platform === 'windows') {
return file === `${nameToFind}.exe`;
}
return file === nameToFind;
});
if (!foundBinaryPath) {
throw new Error(
`Could not find binary "${nameToFind}" in extracted archive.`,
);
}
fs.renameSync(foundBinaryPath, executablePath);
if (platform !== 'windows') {
fs.chmodSync(executablePath, '755');
}
console.log(`โ
${executableName} installed at ${executablePath}`);
return executablePath;
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
if (fs.existsSync(archivePath)) {
fs.unlinkSync(archivePath);
}
}
}
function fileExists(filePath) {
return fs.existsSync(filePath);
}
function readJsonFile(filePath) {
if (!fileExists(filePath)) {
return {};
}
const content = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(content);
}
function writeJsonFile(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}
function waitForPort(port, timeout = 5000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const tryConnect = () => {
const socket = new net.Socket();
socket.once('connect', () => {
socket.end();
resolve();
});
socket.once('error', (_) => {
if (Date.now() - startTime > timeout) {
reject(new Error(`Timeout waiting for port ${port} to open.`));
} else {
setTimeout(tryConnect, 500);
}
});
socket.connect(port, 'localhost');
};
tryConnect();
});
}
async function main() {
// 1. Ensure binaries are available, downloading if necessary.
// Binaries are stored in the project's .gemini/otel/bin directory
// to avoid modifying the user's system.
if (!fileExists(BIN_DIR)) fs.mkdirSync(BIN_DIR, { recursive: true });
const otelcolPath = await ensureBinary(
'otelcol-contrib',
'open-telemetry/opentelemetry-collector-releases',
(version, platform, arch, ext) =>
`otelcol-contrib_${version}_${platform}_${arch}.${ext}`,
'otelcol-contrib',
).catch((e) => {
console.error(`๐ Error getting otelcol-contrib: ${e.message}`);
return null;
});
if (!otelcolPath) process.exit(1);
const jaegerPath = await ensureBinary(
'jaeger',
'jaegertracing/jaeger',
(version, platform, arch, ext) =>
`jaeger-${version}-${platform}-${arch}.${ext}`,
'jaeger',
).catch((e) => {
console.error(`๐ Error getting jaeger: ${e.message}`);
return null;
});
if (!jaegerPath) process.exit(1);
// 2. Kill any existing processes to ensure a clean start.
console.log('๐งน Cleaning up old processes and logs...');
try {
execSync('pkill -f "otelcol-contrib"');
console.log('โ
Stopped existing otelcol-contrib process.');
} catch (_e) {} // eslint-disable-line no-empty
try {
execSync('pkill -f "jaeger"');
console.log('โ
Stopped existing jaeger process.');
} catch (_e) {} // eslint-disable-line no-empty
try {
fs.unlinkSync(OTEL_LOG_FILE);
console.log('โ
Deleted old collector log.');
} catch (e) {
if (e.code !== 'ENOENT') console.error(e);
}
try {
fs.unlinkSync(JAEGER_LOG_FILE);
console.log('โ
Deleted old jaeger log.');
} catch (e) {
if (e.code !== 'ENOENT') console.error(e);
}
let jaegerProcess, collectorProcess;
let jaegerLogFd, collectorLogFd;
const cleanup = () => {
console.log('\n๐ Shutting down...');
// Restore original settings
const finalSettings = readJsonFile(WORKSPACE_SETTINGS_FILE);
delete finalSettings.telemetry;
delete finalSettings.telemetryOtlpEndpoint;
finalSettings.sandbox = originalSandboxSetting;
writeJsonFile(WORKSPACE_SETTINGS_FILE, finalSettings);
console.log('โ
Restored original telemetry and sandbox settings.');
[jaegerProcess, collectorProcess].forEach((proc) => {
if (proc && proc.pid) {
const name = path.basename(proc.spawnfile);
try {
console.log(`๐ Stopping ${name} (PID: ${proc.pid})...`);
// Use SIGTERM for a graceful shutdown
process.kill(proc.pid, 'SIGTERM');
console.log(`โ
${name} stopped.`);
} catch (e) {
// It's okay if the process is already gone.
if (e.code !== 'ESRCH')
console.error(`Error stopping ${name}: ${e.message}`);
}
}
});
[jaegerLogFd, collectorLogFd].forEach((fd) => {
if (fd)
try {
fs.closeSync(fd);
} catch (_) {} // eslint-disable-line no-empty
});
};
process.on('exit', cleanup);
process.on('SIGINT', () => process.exit(0));
process.on('SIGTERM', () => process.exit(0));
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
if (!fileExists(OTEL_DIR)) fs.mkdirSync(OTEL_DIR, { recursive: true });
fs.writeFileSync(OTEL_CONFIG_FILE, OTEL_CONFIG_CONTENT);
console.log('๐ Wrote OTEL collector config.');
const workspaceSettings = readJsonFile(WORKSPACE_SETTINGS_FILE);
const originalSandboxSetting = workspaceSettings.sandbox;
let settingsModified = false;
if (workspaceSettings.telemetry !== true) {
workspaceSettings.telemetry = true;
settingsModified = true;
console.log('โ๏ธ Enabled telemetry in workspace settings.');
}
if (workspaceSettings.sandbox !== false) {
workspaceSettings.sandbox = false;
settingsModified = true;
console.log('โ
Disabled sandbox mode for local telemetry.');
}
if (workspaceSettings.telemetryOtlpEndpoint !== 'http://localhost:4317') {
workspaceSettings.telemetryOtlpEndpoint = 'http://localhost:4317';
settingsModified = true;
console.log('๐ง Set telemetry endpoint to http://localhost:4317.');
}
if (settingsModified) {
writeJsonFile(WORKSPACE_SETTINGS_FILE, workspaceSettings);
console.log('โ
Workspace settings updated.');
} else {
console.log('โ
Telemetry is already configured correctly.');
}
// Start Jaeger
console.log(`๐ Starting Jaeger service... Logs: ${JAEGER_LOG_FILE}`);
jaegerLogFd = fs.openSync(JAEGER_LOG_FILE, 'a');
// The collector is on 4317, so we move jaeger to 14317.
jaegerProcess = spawn(
jaegerPath,
['--set=receivers.otlp.protocols.grpc.endpoint=localhost:14317'],
{ stdio: ['ignore', jaegerLogFd, jaegerLogFd] },
);
console.log(`โณ Waiting for Jaeger to start (PID: ${jaegerProcess.pid})...`);
try {
await waitForPort(JAEGER_PORT);
console.log(`โ
Jaeger started successfully.`);
} catch (_) {
console.error(`๐ Error: Jaeger failed to start on port ${JAEGER_PORT}.`);
if (jaegerProcess && jaegerProcess.pid) {
process.kill(jaegerProcess.pid, 'SIGKILL');
}
if (fileExists(JAEGER_LOG_FILE)) {
console.error('๐ Jaeger Log Output:');
console.error(fs.readFileSync(JAEGER_LOG_FILE, 'utf-8'));
}
process.exit(1);
}
// Start the primary OTEL collector
console.log(`๐ Starting OTEL collector... Logs: ${OTEL_LOG_FILE}`);
collectorLogFd = fs.openSync(OTEL_LOG_FILE, 'a');
collectorProcess = spawn(otelcolPath, ['--config', OTEL_CONFIG_FILE], {
stdio: ['ignore', collectorLogFd, collectorLogFd],
});
console.log(
`โณ Waiting for OTEL collector to start (PID: ${collectorProcess.pid})...`,
);
try {
await waitForPort(4317);
console.log(`โ
OTEL collector started successfully.`);
} catch (_) {
console.error(`๐ Error: OTEL collector failed to start on port 4317.`);
if (collectorProcess && collectorProcess.pid) {
process.kill(collectorProcess.pid, 'SIGKILL');
}
if (fileExists(OTEL_LOG_FILE)) {
console.error('๐ OTEL Collector Log Output:');
console.error(fs.readFileSync(OTEL_LOG_FILE, 'utf-8'));
}
process.exit(1);
}
[jaegerProcess, collectorProcess].forEach((proc) => {
proc.on('error', (err) => {
console.error(`${proc.spawnargs[0]} process error:`, err);
process.exit(1);
});
});
console.log(`\nโจ Local telemetry environment is running.`);
console.log(
`\n๐ View traces in the Jaeger UI: http://localhost:${JAEGER_PORT}`,
);
console.log(`\nPress Ctrl+C to exit.`);
}
main();
|