Repository navigation
Expand file tree
/
Copy pathcontext.ts
More file actions
588 lines (522 loc) · 19.1 KB
/
Copy pathcontext.ts
File metadata and controls
588 lines (522 loc) · 19.1 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
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
/* eslint-disable max-lines */
import { execFile } from 'node:child_process';
import { readdir, readFile } from 'node:fs';
import * as os from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import type {
AppContext,
CloudResourceContext,
Contexts,
CultureContext,
DeviceContext,
Event,
IntegrationFn,
OsContext,
} from '@sentry/core';
import { defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core';
export const readFileAsync = promisify(readFile);
export const readDirAsync = promisify(readdir);
// Process enhanced with methods from Node 18, 20, 22 as @types/node
// is on `14.18.0` to match minimum version requirements of the SDK
interface ProcessWithCurrentValues extends NodeJS.Process {
availableMemory?(): number;
}
const INTEGRATION_NAME = 'Context' as const;
interface DeviceContextOptions {
cpu?: boolean;
memory?: boolean;
}
interface ContextOptions {
app?: boolean;
os?: boolean;
device?: DeviceContextOptions | boolean;
culture?: boolean;
cloudResource?: boolean;
}
const _nodeContextIntegration = ((options: ContextOptions = {}) => {
const _options = {
app: true,
os: true,
device: true,
culture: true,
cloudResource: true,
...options,
};
// Compute contexts eagerly (shared between tx and span paths)
const appContext = _options.app ? getAppContext() : undefined;
const deviceContext = _options.device ? getDeviceContext(_options.device) : undefined;
const cultureContext = _options.culture ? getCultureContext() : undefined;
const cloudResourceContext = _options.cloudResource ? getCloudResourceContext() : undefined;
const osContextPromise = _options.os ? getOsContext() : undefined;
// Map static context data to span attributes
const cachedSpanAttributes: Record<string, unknown> = {
'process.runtime.engine.name': 'v8',
'process.runtime.engine.version': process.versions.v8,
...contextsToSpanAttributes({
app: appContext,
device: deviceContext,
culture: cultureContext,
cloud_resource: cloudResourceContext,
}),
};
if (osContextPromise) {
osContextPromise
.then(osCtx => Object.assign(cachedSpanAttributes, contextsToSpanAttributes({ os: osCtx })))
.catch(() => {
// Ignore - os attributes will be undefined
});
}
// Build contexts for event processing (reuses same data, awaits async OS context)
const contextsPromise: Promise<Contexts> = (async () => {
const contexts: Contexts = {};
if (osContextPromise) {
contexts.os = await osContextPromise;
}
if (appContext) {
contexts.app = appContext;
}
if (deviceContext) {
contexts.device = deviceContext;
}
if (cultureContext) {
contexts.culture = cultureContext;
}
if (cloudResourceContext) {
contexts.cloud_resource = cloudResourceContext;
}
return contexts;
})();
async function addContext(event: Event): Promise<Event> {
const updatedContext = _updateContext(await contextsPromise);
event.contexts = {
...event.contexts,
app: { ...updatedContext.app, ...event.contexts?.app },
os: { ...updatedContext.os, ...event.contexts?.os },
device: { ...updatedContext.device, ...event.contexts?.device },
culture: { ...updatedContext.culture, ...event.contexts?.culture },
cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource },
};
return event;
}
return {
name: INTEGRATION_NAME,
processEvent(event) {
return addContext(event);
},
processSegmentSpan(span) {
safeSetSpanJSONAttributes(span, cachedSpanAttributes);
safeSetSpanJSONAttributes(span, getDynamicSpanAttributes(appContext, deviceContext));
},
};
}) satisfies IntegrationFn;
/**
* Capture context about the environment and the device that the client is running on, to events.
*/
export const nodeContextIntegration = defineIntegration(_nodeContextIntegration);
/**
* Updates the context with dynamic values that can change
*/
function _updateContext(contexts: Contexts): Contexts {
// Only update properties if they exist
if (contexts.app?.app_memory) {
contexts.app.app_memory = process.memoryUsage().rss;
}
if (contexts.app?.free_memory && typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {
const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();
if (freeMemory != null) {
contexts.app.free_memory = freeMemory;
}
}
if (contexts.device?.free_memory) {
contexts.device.free_memory = os.freemem();
}
return contexts;
}
export function contextsToSpanAttributes(contexts: Contexts): Record<string, unknown> {
const attrs: Record<string, unknown> = {};
const { app, device, os: osCtx, culture, cloud_resource } = contexts;
if (app) {
if (app.app_start_time) {
attrs['app.start_time'] = app.app_start_time;
}
}
if (device) {
if (device.arch) {
attrs['device.archs'] = [device.arch];
}
if (device.boot_time) {
attrs['device.boot_time'] = device.boot_time;
}
if (device.memory_size != null) {
attrs['device.memory_size'] = device.memory_size;
}
if (device.processor_count != null) {
attrs['device.processor_count'] = device.processor_count;
}
if (device.cpu_description) {
attrs['device.cpu_description'] = device.cpu_description;
}
if (device.processor_frequency != null) {
attrs['device.processor_frequency'] = device.processor_frequency;
}
}
if (osCtx) {
if (osCtx.name) {
attrs['os.name'] = osCtx.name;
}
if (osCtx.version) {
attrs['os.version'] = osCtx.version;
}
if (osCtx.kernel_version) {
attrs['os.kernel_version'] = osCtx.kernel_version;
}
if (osCtx.build) {
attrs['os.build'] = osCtx.build;
}
}
if (culture) {
if (culture.locale) {
attrs['culture.locale'] = culture.locale;
}
if (culture.timezone) {
attrs['culture.timezone'] = culture.timezone;
}
}
// CloudResourceContext already uses dot-notation keys matching span attribute conventions
if (cloud_resource) {
for (const [key, value] of Object.entries(cloud_resource)) {
if (value != null) {
attrs[key] = value;
}
}
}
return attrs;
}
export function getDynamicSpanAttributes(
appContext: AppContext | undefined,
deviceContext: DeviceContext | undefined,
): Record<string, unknown> {
const attrs: Record<string, unknown> = {};
if (appContext) {
attrs['app.memory'] = process.memoryUsage().rss;
if (typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {
const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();
if (freeMemory != null) {
attrs['app.free_memory'] = freeMemory;
}
}
}
// Only include if memory tracking was initially enabled (indicated by free_memory being set)
if (deviceContext?.free_memory != null) {
attrs['device.free_memory'] = os.freemem();
}
return attrs;
}
/**
* Returns the operating system context.
*
* Based on the current platform, this uses a different strategy to provide the
* most accurate OS information. Since this might involve spawning subprocesses
* or accessing the file system, this should only be executed lazily and cached.
*
* - On macOS (Darwin), this will execute the `sw_vers` utility. The context
* has a `name`, `version`, `build` and `kernel_version` set.
* - On Linux, this will try to load a distribution release from `/etc` and set
* the `name`, `version` and `kernel_version` fields.
* - On all other platforms, only a `name` and `version` will be returned. Note
* that `version` might actually be the kernel version.
*/
async function getOsContext(): Promise<OsContext> {
const platformId = os.platform();
switch (platformId) {
case 'darwin':
return getDarwinInfo();
case 'linux':
return getLinuxInfo();
default:
return {
name: PLATFORM_NAMES[platformId] || platformId,
version: os.release(),
};
}
}
function getCultureContext(): CultureContext | undefined {
try {
if (typeof process.versions.icu !== 'string') {
// Node was built without ICU support
return;
}
// Check that node was built with full Intl support. Its possible it was built without support for non-English
// locales which will make resolvedOptions inaccurate
//
// https://nodejs.org/api/intl.html#detecting-internationalization-support
const january = new Date(9e8);
const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
if (spanish.format(january) === 'enero') {
const options = Intl.DateTimeFormat().resolvedOptions();
return {
locale: options.locale,
timezone: options.timeZone,
};
}
} catch {
//
}
return;
}
/**
* Get app context information from process
*/
export function getAppContext(): AppContext {
const app_memory = process.memoryUsage().rss;
// oxlint-disable-next-line sdk/no-unsafe-random-apis
const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();
// https://nodejs.org/api/process.html#processavailablememory
const appContext: AppContext = { app_start_time, app_memory };
if (typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {
const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();
if (freeMemory != null) {
appContext.free_memory = freeMemory;
}
}
return appContext;
}
/**
* Gets device information from os
*/
export function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext {
const device: DeviceContext = {};
// Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202
let uptime;
try {
uptime = os.uptime();
} catch {
// noop
}
// os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).
// Hence, we only set boot time, if we get a valid uptime value.
// @see https://github.com/getsentry/sentry-javascript/issues/5856
if (typeof uptime === 'number') {
// oxlint-disable-next-line sdk/no-unsafe-random-apis
device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();
}
device.arch = os.arch();
if (deviceOpt === true || deviceOpt.memory) {
device.memory_size = os.totalmem();
device.free_memory = os.freemem();
}
if (deviceOpt === true || deviceOpt.cpu) {
const cpuInfo = os.cpus() as os.CpuInfo[] | undefined;
const firstCpu = cpuInfo?.[0];
if (firstCpu) {
device.processor_count = cpuInfo.length;
device.cpu_description = firstCpu.model;
device.processor_frequency = firstCpu.speed;
}
}
return device;
}
/** Mapping of Node's platform names to actual OS names. */
const PLATFORM_NAMES: { [platform: string]: string } = {
aix: 'IBM AIX',
freebsd: 'FreeBSD',
openbsd: 'OpenBSD',
sunos: 'SunOS',
win32: 'Windows',
ohos: 'OpenHarmony',
android: 'Android',
};
/** Linux version file to check for a distribution. */
interface DistroFile {
/** The file name, located in `/etc`. */
name: string;
/** Potential distributions to check. */
distros: [string, ...string[]];
}
/** Mapping of linux release files located in /etc to distributions. */
const LINUX_DISTROS: DistroFile[] = [
{ name: 'fedora-release', distros: ['Fedora'] },
{ name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },
{ name: 'redhat_version', distros: ['Red Hat Linux'] },
{ name: 'SuSE-release', distros: ['SUSE Linux'] },
{ name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },
{ name: 'debian_version', distros: ['Debian'] },
{ name: 'debian_release', distros: ['Debian'] },
{ name: 'arch-release', distros: ['Arch Linux'] },
{ name: 'gentoo-release', distros: ['Gentoo Linux'] },
{ name: 'novell-release', distros: ['SUSE Linux'] },
{ name: 'alpine-release', distros: ['Alpine Linux'] },
];
/** Functions to extract the OS version from Linux release files. */
const LINUX_VERSIONS: {
[identifier: string]: (content: string) => string | undefined;
} = {
alpine: content => content,
arch: content => matchFirst(/distrib_release=(.*)/, content),
centos: content => matchFirst(/release ([^ ]+)/, content),
debian: content => content,
fedora: content => matchFirst(/release (..)/, content),
mint: content => matchFirst(/distrib_release=(.*)/, content),
red: content => matchFirst(/release ([^ ]+)/, content),
suse: content => matchFirst(/VERSION = (.*)\n/, content),
ubuntu: content => matchFirst(/distrib_release=(.*)/, content),
};
/**
* Executes a regular expression with one capture group.
*
* @param regex A regular expression to execute.
* @param text Content to execute the RegEx on.
* @returns The captured string if matched; otherwise undefined.
*/
function matchFirst(regex: RegExp, text: string): string | undefined {
const match = regex.exec(text);
return match ? match[1] : undefined;
}
/** Loads the macOS operating system context. */
async function getDarwinInfo(): Promise<OsContext> {
// Default values that will be used in case no operating system information
// can be loaded. The default version is computed via heuristics from the
// kernel version, but the build ID is missing.
const darwinInfo: OsContext = {
kernel_version: os.release(),
name: 'Mac OS X',
version: `10.${Number(os.release().split('.')[0]) - 4}`,
};
try {
// We try to load the actual macOS version by executing the `sw_vers` tool.
// This tool should be available on every standard macOS installation. In
// case this fails, we stick with the values computed above.
const output = await new Promise<string>((resolve, reject) => {
execFile('/usr/bin/sw_vers', (error: Error | null, stdout: string) => {
if (error) {
reject(error);
return;
}
resolve(stdout);
});
});
darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output);
darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output);
darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output);
} catch {
// ignore
}
return darwinInfo;
}
/** Returns a distribution identifier to look up version callbacks. */
function getLinuxDistroId(name: string): string {
return (name.split(' ') as [string])[0].toLowerCase();
}
/** Loads the Linux operating system context. */
async function getLinuxInfo(): Promise<OsContext> {
// By default, we cannot assume anything about the distribution or Linux
// version. `os.release()` returns the kernel version and we assume a generic
// "Linux" name, which will be replaced down below.
const linuxInfo: OsContext = {
kernel_version: os.release(),
name: 'Linux',
};
try {
// We start guessing the distribution by listing files in the /etc
// directory. This is were most Linux distributions (except Knoppix) store
// release files with certain distribution-dependent meta data. We search
// for exactly one known file defined in `LINUX_DISTROS` and exit if none
// are found. In case there are more than one file, we just stick with the
// first one.
const etcFiles = await readDirAsync('/etc');
const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));
if (!distroFile) {
return linuxInfo;
}
// Once that file is known, load its contents. To make searching in those
// files easier, we lowercase the file contents. Since these files are
// usually quite small, this should not allocate too much memory and we only
// hold on to it for a very short amount of time.
const distroPath = join('/etc', distroFile.name);
const contents = (await readFileAsync(distroPath, { encoding: 'utf-8' })).toLowerCase();
// Some Linux distributions store their release information in the same file
// (e.g. RHEL and Centos). In those cases, we scan the file for an
// identifier, that basically consists of the first word of the linux
// distribution name (e.g. "red" for Red Hat). In case there is no match, we
// just assume the first distribution in our list.
const { distros } = distroFile;
linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];
// Based on the found distribution, we can now compute the actual version
// number. This is different for every distribution, so several strategies
// are computed in `LINUX_VERSIONS`.
const id = getLinuxDistroId(linuxInfo.name);
linuxInfo.version = LINUX_VERSIONS[id]?.(contents);
} catch {
// ignore
}
return linuxInfo;
}
/**
* Grabs some information about hosting provider based on best effort.
*/
function getCloudResourceContext(): CloudResourceContext | undefined {
if (process.env.VERCEL) {
// https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables
return {
'cloud.provider': 'vercel',
'cloud.region': process.env.VERCEL_REGION,
};
} else if (process.env.AWS_REGION) {
// https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
return {
'cloud.provider': 'aws',
'cloud.region': process.env.AWS_REGION,
'cloud.platform': process.env.AWS_EXECUTION_ENV,
};
} else if (process.env.GCP_PROJECT) {
// https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables
return {
'cloud.provider': 'gcp',
};
} else if (process.env.ALIYUN_REGION_ID) {
// TODO: find where I found these environment variables - at least gc.github.com returns something
return {
'cloud.provider': 'alibaba_cloud',
'cloud.region': process.env.ALIYUN_REGION_ID,
};
} else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {
// https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment
return {
'cloud.provider': 'azure',
'cloud.region': process.env.REGION_NAME,
};
} else if (process.env.IBM_CLOUD_REGION) {
// TODO: find where I found these environment variables - at least gc.github.com returns something
return {
'cloud.provider': 'ibm_cloud',
'cloud.region': process.env.IBM_CLOUD_REGION,
};
} else if (process.env.TENCENTCLOUD_REGION) {
// https://www.tencentcloud.com/document/product/583/32748
return {
'cloud.provider': 'tencent_cloud',
'cloud.region': process.env.TENCENTCLOUD_REGION,
'cloud.account.id': process.env.TENCENTCLOUD_APPID,
'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE,
};
} else if (process.env.NETLIFY) {
// https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables
return {
'cloud.provider': 'netlify',
};
} else if (process.env.FLY_REGION) {
// https://fly.io/docs/reference/runtime-environment/
return {
'cloud.provider': 'fly.io',
'cloud.region': process.env.FLY_REGION,
};
} else if (process.env.DYNO) {
// https://devcenter.heroku.com/articles/dynos#local-environment-variables
return {
'cloud.provider': 'heroku',
};
} else {
return undefined;
}
}