context.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import { _optionalChain } from '@sentry/utils';
  2. import { execFile } from 'child_process';
  3. import { readFile, readdir } from 'fs';
  4. import * as os from 'os';
  5. import { join } from 'path';
  6. import { promisify } from 'util';
  7. import { defineIntegration, convertIntegrationFnToClass } from '@sentry/core';
  8. /* eslint-disable max-lines */
  9. // TODO: Required until we drop support for Node v8
  10. const readFileAsync = promisify(readFile);
  11. const readDirAsync = promisify(readdir);
  12. const INTEGRATION_NAME = 'Context';
  13. const _nodeContextIntegration = ((options = {}) => {
  14. let cachedContext;
  15. const _options = {
  16. app: true,
  17. os: true,
  18. device: true,
  19. culture: true,
  20. cloudResource: true,
  21. ...options,
  22. };
  23. /** Add contexts to the event. Caches the context so we only look it up once. */
  24. async function addContext(event) {
  25. if (cachedContext === undefined) {
  26. cachedContext = _getContexts();
  27. }
  28. const updatedContext = _updateContext(await cachedContext);
  29. event.contexts = {
  30. ...event.contexts,
  31. app: { ...updatedContext.app, ..._optionalChain([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) },
  32. os: { ...updatedContext.os, ..._optionalChain([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) },
  33. device: { ...updatedContext.device, ..._optionalChain([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) },
  34. culture: { ...updatedContext.culture, ..._optionalChain([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) },
  35. cloud_resource: { ...updatedContext.cloud_resource, ..._optionalChain([event, 'access', _9 => _9.contexts, 'optionalAccess', _10 => _10.cloud_resource]) },
  36. };
  37. return event;
  38. }
  39. /** Get the contexts from node. */
  40. async function _getContexts() {
  41. const contexts = {};
  42. if (_options.os) {
  43. contexts.os = await getOsContext();
  44. }
  45. if (_options.app) {
  46. contexts.app = getAppContext();
  47. }
  48. if (_options.device) {
  49. contexts.device = getDeviceContext(_options.device);
  50. }
  51. if (_options.culture) {
  52. const culture = getCultureContext();
  53. if (culture) {
  54. contexts.culture = culture;
  55. }
  56. }
  57. if (_options.cloudResource) {
  58. contexts.cloud_resource = getCloudResourceContext();
  59. }
  60. return contexts;
  61. }
  62. return {
  63. name: INTEGRATION_NAME,
  64. // TODO v8: Remove this
  65. setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function
  66. processEvent(event) {
  67. return addContext(event);
  68. },
  69. };
  70. }) ;
  71. const nodeContextIntegration = defineIntegration(_nodeContextIntegration);
  72. /**
  73. * Add node modules / packages to the event.
  74. * @deprecated Use `nodeContextIntegration()` instead.
  75. */
  76. // eslint-disable-next-line deprecation/deprecation
  77. const Context = convertIntegrationFnToClass(INTEGRATION_NAME, nodeContextIntegration)
  78. ;
  79. // eslint-disable-next-line deprecation/deprecation
  80. /**
  81. * Updates the context with dynamic values that can change
  82. */
  83. function _updateContext(contexts) {
  84. // Only update properties if they exist
  85. if (_optionalChain([contexts, 'optionalAccess', _11 => _11.app, 'optionalAccess', _12 => _12.app_memory])) {
  86. contexts.app.app_memory = process.memoryUsage().rss;
  87. }
  88. if (_optionalChain([contexts, 'optionalAccess', _13 => _13.device, 'optionalAccess', _14 => _14.free_memory])) {
  89. contexts.device.free_memory = os.freemem();
  90. }
  91. return contexts;
  92. }
  93. /**
  94. * Returns the operating system context.
  95. *
  96. * Based on the current platform, this uses a different strategy to provide the
  97. * most accurate OS information. Since this might involve spawning subprocesses
  98. * or accessing the file system, this should only be executed lazily and cached.
  99. *
  100. * - On macOS (Darwin), this will execute the `sw_vers` utility. The context
  101. * has a `name`, `version`, `build` and `kernel_version` set.
  102. * - On Linux, this will try to load a distribution release from `/etc` and set
  103. * the `name`, `version` and `kernel_version` fields.
  104. * - On all other platforms, only a `name` and `version` will be returned. Note
  105. * that `version` might actually be the kernel version.
  106. */
  107. async function getOsContext() {
  108. const platformId = os.platform();
  109. switch (platformId) {
  110. case 'darwin':
  111. return getDarwinInfo();
  112. case 'linux':
  113. return getLinuxInfo();
  114. default:
  115. return {
  116. name: PLATFORM_NAMES[platformId] || platformId,
  117. version: os.release(),
  118. };
  119. }
  120. }
  121. function getCultureContext() {
  122. try {
  123. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
  124. if (typeof (process.versions ).icu !== 'string') {
  125. // Node was built without ICU support
  126. return;
  127. }
  128. // Check that node was built with full Intl support. Its possible it was built without support for non-English
  129. // locales which will make resolvedOptions inaccurate
  130. //
  131. // https://nodejs.org/api/intl.html#detecting-internationalization-support
  132. const january = new Date(9e8);
  133. const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
  134. if (spanish.format(january) === 'enero') {
  135. const options = Intl.DateTimeFormat().resolvedOptions();
  136. return {
  137. locale: options.locale,
  138. timezone: options.timeZone,
  139. };
  140. }
  141. } catch (err) {
  142. //
  143. }
  144. return;
  145. }
  146. function getAppContext() {
  147. const app_memory = process.memoryUsage().rss;
  148. const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();
  149. return { app_start_time, app_memory };
  150. }
  151. /**
  152. * Gets device information from os
  153. */
  154. function getDeviceContext(deviceOpt) {
  155. const device = {};
  156. // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202
  157. let uptime;
  158. try {
  159. uptime = os.uptime && os.uptime();
  160. } catch (e) {
  161. // noop
  162. }
  163. // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).
  164. // Hence, we only set boot time, if we get a valid uptime value.
  165. // @see https://github.com/getsentry/sentry-javascript/issues/5856
  166. if (typeof uptime === 'number') {
  167. device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();
  168. }
  169. device.arch = os.arch();
  170. if (deviceOpt === true || deviceOpt.memory) {
  171. device.memory_size = os.totalmem();
  172. device.free_memory = os.freemem();
  173. }
  174. if (deviceOpt === true || deviceOpt.cpu) {
  175. const cpuInfo = os.cpus();
  176. if (cpuInfo && cpuInfo.length) {
  177. const firstCpu = cpuInfo[0];
  178. device.processor_count = cpuInfo.length;
  179. device.cpu_description = firstCpu.model;
  180. device.processor_frequency = firstCpu.speed;
  181. }
  182. }
  183. return device;
  184. }
  185. /** Mapping of Node's platform names to actual OS names. */
  186. const PLATFORM_NAMES = {
  187. aix: 'IBM AIX',
  188. freebsd: 'FreeBSD',
  189. openbsd: 'OpenBSD',
  190. sunos: 'SunOS',
  191. win32: 'Windows',
  192. };
  193. /** Linux version file to check for a distribution. */
  194. /** Mapping of linux release files located in /etc to distributions. */
  195. const LINUX_DISTROS = [
  196. { name: 'fedora-release', distros: ['Fedora'] },
  197. { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },
  198. { name: 'redhat_version', distros: ['Red Hat Linux'] },
  199. { name: 'SuSE-release', distros: ['SUSE Linux'] },
  200. { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },
  201. { name: 'debian_version', distros: ['Debian'] },
  202. { name: 'debian_release', distros: ['Debian'] },
  203. { name: 'arch-release', distros: ['Arch Linux'] },
  204. { name: 'gentoo-release', distros: ['Gentoo Linux'] },
  205. { name: 'novell-release', distros: ['SUSE Linux'] },
  206. { name: 'alpine-release', distros: ['Alpine Linux'] },
  207. ];
  208. /** Functions to extract the OS version from Linux release files. */
  209. const LINUX_VERSIONS
  210. = {
  211. alpine: content => content,
  212. arch: content => matchFirst(/distrib_release=(.*)/, content),
  213. centos: content => matchFirst(/release ([^ ]+)/, content),
  214. debian: content => content,
  215. fedora: content => matchFirst(/release (..)/, content),
  216. mint: content => matchFirst(/distrib_release=(.*)/, content),
  217. red: content => matchFirst(/release ([^ ]+)/, content),
  218. suse: content => matchFirst(/VERSION = (.*)\n/, content),
  219. ubuntu: content => matchFirst(/distrib_release=(.*)/, content),
  220. };
  221. /**
  222. * Executes a regular expression with one capture group.
  223. *
  224. * @param regex A regular expression to execute.
  225. * @param text Content to execute the RegEx on.
  226. * @returns The captured string if matched; otherwise undefined.
  227. */
  228. function matchFirst(regex, text) {
  229. const match = regex.exec(text);
  230. return match ? match[1] : undefined;
  231. }
  232. /** Loads the macOS operating system context. */
  233. async function getDarwinInfo() {
  234. // Default values that will be used in case no operating system information
  235. // can be loaded. The default version is computed via heuristics from the
  236. // kernel version, but the build ID is missing.
  237. const darwinInfo = {
  238. kernel_version: os.release(),
  239. name: 'Mac OS X',
  240. version: `10.${Number(os.release().split('.')[0]) - 4}`,
  241. };
  242. try {
  243. // We try to load the actual macOS version by executing the `sw_vers` tool.
  244. // This tool should be available on every standard macOS installation. In
  245. // case this fails, we stick with the values computed above.
  246. const output = await new Promise((resolve, reject) => {
  247. execFile('/usr/bin/sw_vers', (error, stdout) => {
  248. if (error) {
  249. reject(error);
  250. return;
  251. }
  252. resolve(stdout);
  253. });
  254. });
  255. darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output);
  256. darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output);
  257. darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output);
  258. } catch (e) {
  259. // ignore
  260. }
  261. return darwinInfo;
  262. }
  263. /** Returns a distribution identifier to look up version callbacks. */
  264. function getLinuxDistroId(name) {
  265. return name.split(' ')[0].toLowerCase();
  266. }
  267. /** Loads the Linux operating system context. */
  268. async function getLinuxInfo() {
  269. // By default, we cannot assume anything about the distribution or Linux
  270. // version. `os.release()` returns the kernel version and we assume a generic
  271. // "Linux" name, which will be replaced down below.
  272. const linuxInfo = {
  273. kernel_version: os.release(),
  274. name: 'Linux',
  275. };
  276. try {
  277. // We start guessing the distribution by listing files in the /etc
  278. // directory. This is were most Linux distributions (except Knoppix) store
  279. // release files with certain distribution-dependent meta data. We search
  280. // for exactly one known file defined in `LINUX_DISTROS` and exit if none
  281. // are found. In case there are more than one file, we just stick with the
  282. // first one.
  283. const etcFiles = await readDirAsync('/etc');
  284. const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));
  285. if (!distroFile) {
  286. return linuxInfo;
  287. }
  288. // Once that file is known, load its contents. To make searching in those
  289. // files easier, we lowercase the file contents. Since these files are
  290. // usually quite small, this should not allocate too much memory and we only
  291. // hold on to it for a very short amount of time.
  292. const distroPath = join('/etc', distroFile.name);
  293. const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase();
  294. // Some Linux distributions store their release information in the same file
  295. // (e.g. RHEL and Centos). In those cases, we scan the file for an
  296. // identifier, that basically consists of the first word of the linux
  297. // distribution name (e.g. "red" for Red Hat). In case there is no match, we
  298. // just assume the first distribution in our list.
  299. const { distros } = distroFile;
  300. linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];
  301. // Based on the found distribution, we can now compute the actual version
  302. // number. This is different for every distribution, so several strategies
  303. // are computed in `LINUX_VERSIONS`.
  304. const id = getLinuxDistroId(linuxInfo.name);
  305. linuxInfo.version = LINUX_VERSIONS[id](contents);
  306. } catch (e) {
  307. // ignore
  308. }
  309. return linuxInfo;
  310. }
  311. /**
  312. * Grabs some information about hosting provider based on best effort.
  313. */
  314. function getCloudResourceContext() {
  315. if (process.env.VERCEL) {
  316. // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables
  317. return {
  318. 'cloud.provider': 'vercel',
  319. 'cloud.region': process.env.VERCEL_REGION,
  320. };
  321. } else if (process.env.AWS_REGION) {
  322. // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
  323. return {
  324. 'cloud.provider': 'aws',
  325. 'cloud.region': process.env.AWS_REGION,
  326. 'cloud.platform': process.env.AWS_EXECUTION_ENV,
  327. };
  328. } else if (process.env.GCP_PROJECT) {
  329. // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables
  330. return {
  331. 'cloud.provider': 'gcp',
  332. };
  333. } else if (process.env.ALIYUN_REGION_ID) {
  334. // TODO: find where I found these environment variables - at least gc.github.com returns something
  335. return {
  336. 'cloud.provider': 'alibaba_cloud',
  337. 'cloud.region': process.env.ALIYUN_REGION_ID,
  338. };
  339. } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {
  340. // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment
  341. return {
  342. 'cloud.provider': 'azure',
  343. 'cloud.region': process.env.REGION_NAME,
  344. };
  345. } else if (process.env.IBM_CLOUD_REGION) {
  346. // TODO: find where I found these environment variables - at least gc.github.com returns something
  347. return {
  348. 'cloud.provider': 'ibm_cloud',
  349. 'cloud.region': process.env.IBM_CLOUD_REGION,
  350. };
  351. } else if (process.env.TENCENTCLOUD_REGION) {
  352. // https://www.tencentcloud.com/document/product/583/32748
  353. return {
  354. 'cloud.provider': 'tencent_cloud',
  355. 'cloud.region': process.env.TENCENTCLOUD_REGION,
  356. 'cloud.account.id': process.env.TENCENTCLOUD_APPID,
  357. 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE,
  358. };
  359. } else if (process.env.NETLIFY) {
  360. // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables
  361. return {
  362. 'cloud.provider': 'netlify',
  363. };
  364. } else if (process.env.FLY_REGION) {
  365. // https://fly.io/docs/reference/runtime-environment/
  366. return {
  367. 'cloud.provider': 'fly.io',
  368. 'cloud.region': process.env.FLY_REGION,
  369. };
  370. } else if (process.env.DYNO) {
  371. // https://devcenter.heroku.com/articles/dynos#local-environment-variables
  372. return {
  373. 'cloud.provider': 'heroku',
  374. };
  375. } else {
  376. return undefined;
  377. }
  378. }
  379. export { Context, getDeviceContext, nodeContextIntegration, readDirAsync, readFileAsync };
  380. //# sourceMappingURL=context.js.map