@sentry/node
Version:
Sentry Node SDK using OpenTelemetry for performance instrumentation
390 lines (389 loc) • 13.1 kB
JavaScript
import { APP_START_TIME, CLOUD_ACCOUNT_ID, CLOUD_AVAILABILITY_ZONE, CLOUD_PLATFORM, CLOUD_PROVIDER, CLOUD_REGION, CULTURE_LOCALE, CULTURE_TIMEZONE, DEVICE_ARCHS, DEVICE_BOOT_TIME, DEVICE_CPU_DESCRIPTION, DEVICE_FREE_MEMORY, DEVICE_MEMORY_SIZE, DEVICE_PROCESSOR_COUNT, DEVICE_PROCESSOR_FREQUENCY, OS_BUILD, OS_KERNEL_VERSION, OS_NAME, OS_VERSION, PROCESS_RUNTIME_ENGINE_NAME, PROCESS_RUNTIME_ENGINE_VERSION } from "@sentry/conventions/attributes";
import { defineIntegration, safeSetSpanJSONAttributes } from "@sentry/core";
import { execFile } from "node:child_process";
import { readFile, readdir } from "node:fs";
import * as os from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
// src/integrations/context.ts
const readFileAsync = promisify(readFile);
const readDirAsync = promisify(readdir);
const INTEGRATION_NAME = "Context";
const _nodeContextIntegration = ((options = {}) => {
const _options = {
app: true,
os: true,
device: true,
culture: true,
cloudResource: true,
...options
};
const appContext = _options.app ? getAppContext() : void 0;
const deviceContext = _options.device ? getDeviceContext(_options.device) : void 0;
const cultureContext = _options.culture ? getCultureContext() : void 0;
const cloudResourceContext = _options.cloudResource ? getCloudResourceContext() : void 0;
const osContextPromise = _options.os ? getOsContext() : void 0;
const cachedSpanAttributes = {
[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(() => {});
const contextsPromise = (async () => {
const 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) {
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));
}
};
});
/**
* Capture context about the environment and the device that the client is running on, to events.
*/
const nodeContextIntegration = defineIntegration(_nodeContextIntegration);
/**
* Updates the context with dynamic values that can change
*/
function _updateContext(contexts) {
if (contexts.app?.app_memory) contexts.app.app_memory = process.memoryUsage().rss;
if (contexts.app?.free_memory && typeof process.availableMemory === "function") {
const freeMemory = process.availableMemory();
if (freeMemory != null) contexts.app.free_memory = freeMemory;
}
if (contexts.device?.free_memory) contexts.device.free_memory = os.freemem();
return contexts;
}
function contextsToSpanAttributes(contexts) {
const attrs = {};
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;
}
if (cloud_resource) {
for (const [key, value] of Object.entries(cloud_resource)) if (value != null) attrs[key] = value;
}
return attrs;
}
function getDynamicSpanAttributes(appContext, deviceContext) {
const attrs = {};
if (appContext) {
attrs["app.memory"] = process.memoryUsage().rss;
if (typeof process.availableMemory === "function") {
const freeMemory = process.availableMemory();
if (freeMemory != null) attrs["app.free_memory"] = freeMemory;
}
}
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() {
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() {
try {
if (typeof process.versions.icu !== "string") return;
const january = /* @__PURE__ */ new Date(9e8);
if (new Intl.DateTimeFormat("es", { month: "long" }).format(january) === "enero") {
const options = Intl.DateTimeFormat().resolvedOptions();
return {
locale: options.locale,
timezone: options.timeZone
};
}
} catch {}
}
/**
* Get app context information from process
*/
function getAppContext() {
const app_memory = process.memoryUsage().rss;
const appContext = {
app_start_time: (/* @__PURE__ */ new Date(Date.now() - process.uptime() * 1e3)).toISOString(),
app_memory
};
if (typeof process.availableMemory === "function") {
const freeMemory = process.availableMemory();
if (freeMemory != null) appContext.free_memory = freeMemory;
}
return appContext;
}
/**
* Gets device information from os
*/
function getDeviceContext(deviceOpt) {
const device = {};
let uptime;
try {
uptime = os.uptime();
} catch {}
if (typeof uptime === "number") device.boot_time = (/* @__PURE__ */ new Date(Date.now() - uptime * 1e3)).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();
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 = {
aix: "IBM AIX",
freebsd: "FreeBSD",
openbsd: "OpenBSD",
sunos: "SunOS",
win32: "Windows",
ohos: "OpenHarmony",
android: "Android"
};
/** Mapping of linux release files located in /etc to distributions. */
const LINUX_DISTROS = [
{
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 = {
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, text) {
const match = regex.exec(text);
return match ? match[1] : void 0;
}
/** Loads the macOS operating system context. */
async function getDarwinInfo() {
const darwinInfo = {
kernel_version: os.release(),
name: "Mac OS X",
version: `10.${Number(os.release().split(".")[0]) - 4}`
};
try {
const output = await new Promise((resolve, reject) => {
execFile("/usr/bin/sw_vers", (error, stdout) => {
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 {}
return darwinInfo;
}
/** Returns a distribution identifier to look up version callbacks. */
function getLinuxDistroId(name) {
return name.split(" ")[0].toLowerCase();
}
/** Loads the Linux operating system context. */
async function getLinuxInfo() {
const linuxInfo = {
kernel_version: os.release(),
name: "Linux"
};
try {
const etcFiles = await readDirAsync("/etc");
const distroFile = LINUX_DISTROS.find((file) => etcFiles.includes(file.name));
if (!distroFile) return linuxInfo;
const distroPath = join("/etc", distroFile.name);
const contents = (await readFileAsync(distroPath, { encoding: "utf-8" })).toLowerCase();
const { distros } = distroFile;
linuxInfo.name = distros.find((d) => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];
const id = getLinuxDistroId(linuxInfo.name);
linuxInfo.version = LINUX_VERSIONS[id]?.(contents);
} catch {}
return linuxInfo;
}
/**
* Grabs some information about hosting provider based on best effort.
*/
function getCloudResourceContext() {
if (process.env.VERCEL) return {
[CLOUD_PROVIDER]: "vercel",
[CLOUD_REGION]: process.env.VERCEL_REGION
};
else if (process.env.AWS_REGION) {
const executionEnv = process.env.AWS_EXECUTION_ENV;
return {
[CLOUD_PROVIDER]: "aws",
[CLOUD_REGION]: process.env.AWS_REGION,
[CLOUD_PLATFORM]: executionEnv?.startsWith("AWS_Lambda") ? "aws_lambda" : executionEnv
};
} else if (process.env.GCP_PROJECT) return { [CLOUD_PROVIDER]: "gcp" };
else if (process.env.ALIYUN_REGION_ID) return {
[CLOUD_PROVIDER]: "alibaba_cloud",
[CLOUD_REGION]: process.env.ALIYUN_REGION_ID
};
else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) return {
[CLOUD_PROVIDER]: "azure",
[CLOUD_REGION]: process.env.REGION_NAME
};
else if (process.env.IBM_CLOUD_REGION) return {
[CLOUD_PROVIDER]: "ibm_cloud",
[CLOUD_REGION]: process.env.IBM_CLOUD_REGION
};
else if (process.env.TENCENTCLOUD_REGION) 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) return { [CLOUD_PROVIDER]: "netlify" };
else if (process.env.FLY_REGION) return {
[CLOUD_PROVIDER]: "fly.io",
[CLOUD_REGION]: process.env.FLY_REGION
};
else if (process.env.DYNO) return { [CLOUD_PROVIDER]: "heroku" };
else return;
}
export { contextsToSpanAttributes, getAppContext, getDeviceContext, getDynamicSpanAttributes, nodeContextIntegration, readDirAsync, readFileAsync };
//# sourceMappingURL=context.js.map