From df1b109ba814871a93317e20a875b1f22e4762be Mon Sep 17 00:00:00 2001 From: James Sumners Date: Mon, 23 Nov 2026 10:24:01 -0500 Subject: [PATCH] perf_hooks: add node:perf_hooks/pprof time profiler Add an experimental node:perf_hooks/pprof module that collects wall time profiles of the current thread and encodes them in the pprof format, so that they can be consumed by the pprof command-line tool and continuous profiling services without a native addon. The wall time profiler is ported from @datadog/pprof (Apache-2.0): the native profiler now lives in src/node_pprof.cc and src/pprof/ on top of Node.js internals instead of nan, and the JavaScript in lib/internal/perf/pprof/. The pprof protobuf encoder is ported from the pprof-format package (MIT). Both licenses are added to LICENSE. Profiles can optionally attribute thread CPU time to samples on POSIX systems, by intercepting the SIGPROF signals of V8's sampler, which is also used to work around a V8 bug that can leave the profiler stuck when it is restarted. The heap profiler, sampling contexts and source map support of @datadog/pprof are not included. The module emits an ExperimentalWarning when loaded. Assisted-by: Claude Code Signed-off-by: James Sumners --- LICENSE | 221 +++++ doc/api/perf_hooks.md | 300 +++++++ doc/type-map.json | 1 + lib/internal/perf/pprof/encoder.js | 96 ++ lib/internal/perf/pprof/normalizer.js | 381 ++++++++ lib/internal/perf/pprof/profile.js | 716 +++++++++++++++ lib/internal/perf/pprof/protobuf.js | 451 ++++++++++ lib/internal/perf/pprof/serializer.js | 193 +++++ lib/internal/perf/pprof/string_table.js | 104 +++ lib/internal/perf/pprof/time_profiler.js | 343 ++++++++ lib/perf_hooks/pprof.js | 39 + node.gyp | 8 + src/node_binding.cc | 1 + src/node_external_reference.h | 1 + src/node_pprof.cc | 818 ++++++++++++++++++ src/node_pprof.h | 141 +++ src/pprof/cpu_clock.cc | 181 ++++ src/pprof/cpu_clock.h | 104 +++ src/pprof/sigprof_handler.cc | 144 +++ src/pprof/sigprof_handler.h | 98 +++ src/pprof/time_profile.cc | 92 ++ src/pprof/time_profile.h | 82 ++ test/cctest/test_pprof.cc | 219 +++++ test/common/README.md | 36 + test/common/pprof.js | 269 ++++++ test/fixtures/snapshot/perf-hooks-pprof.js | 6 + .../parallel/test-perf-hooks-pprof-coexist.js | 82 ++ test/parallel/test-perf-hooks-pprof-encode.js | 42 + test/parallel/test-perf-hooks-pprof-exit.js | 32 + test/parallel/test-perf-hooks-pprof-module.js | 48 + .../test-perf-hooks-pprof-protobuf.js | 167 ++++ .../test-perf-hooks-pprof-serializer.js | 210 +++++ .../test-perf-hooks-pprof-time-cpu.js | 100 +++ ...test-perf-hooks-pprof-time-line-numbers.js | 56 ++ .../test-perf-hooks-pprof-time-profile.js | 81 ++ .../test-perf-hooks-pprof-time-recovery.js | 60 ++ .../test-perf-hooks-pprof-time-restart.js | 39 + .../test-perf-hooks-pprof-time-validation.js | 73 ++ test/parallel/test-perf-hooks-pprof-worker.js | 84 ++ .../test-snapshot-perf-hooks-pprof.js | 30 + tools/license-builder.sh | 9 + typings/globals.d.ts | 2 + typings/internalBinding/pprof.d.ts | 44 + 43 files changed, 6204 insertions(+) create mode 100644 lib/internal/perf/pprof/encoder.js create mode 100644 lib/internal/perf/pprof/normalizer.js create mode 100644 lib/internal/perf/pprof/profile.js create mode 100644 lib/internal/perf/pprof/protobuf.js create mode 100644 lib/internal/perf/pprof/serializer.js create mode 100644 lib/internal/perf/pprof/string_table.js create mode 100644 lib/internal/perf/pprof/time_profiler.js create mode 100644 lib/perf_hooks/pprof.js create mode 100644 src/node_pprof.cc create mode 100644 src/node_pprof.h create mode 100644 src/pprof/cpu_clock.cc create mode 100644 src/pprof/cpu_clock.h create mode 100644 src/pprof/sigprof_handler.cc create mode 100644 src/pprof/sigprof_handler.h create mode 100644 src/pprof/time_profile.cc create mode 100644 src/pprof/time_profile.h create mode 100644 test/cctest/test_pprof.cc create mode 100644 test/common/pprof.js create mode 100644 test/fixtures/snapshot/perf-hooks-pprof.js create mode 100644 test/parallel/test-perf-hooks-pprof-coexist.js create mode 100644 test/parallel/test-perf-hooks-pprof-encode.js create mode 100644 test/parallel/test-perf-hooks-pprof-exit.js create mode 100644 test/parallel/test-perf-hooks-pprof-module.js create mode 100644 test/parallel/test-perf-hooks-pprof-protobuf.js create mode 100644 test/parallel/test-perf-hooks-pprof-serializer.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-cpu.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-line-numbers.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-profile.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-recovery.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-restart.js create mode 100644 test/parallel/test-perf-hooks-pprof-time-validation.js create mode 100644 test/parallel/test-perf-hooks-pprof-worker.js create mode 100644 test/parallel/test-snapshot-perf-hooks-pprof.js create mode 100644 typings/internalBinding/pprof.d.ts diff --git a/LICENSE b/LICENSE index ec72f56e16fb..120053a01dba 100644 --- a/LICENSE +++ b/LICENSE @@ -2862,3 +2862,224 @@ The externally maintained libraries used by Node.js are: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + +- pprof-nodejs, located at src/node_pprof.cc, src/node_pprof.h, src/pprof, lib/internal/perf/pprof, is licensed as follows: + """ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + """ + +- pprof-format, located at lib/internal/perf/pprof/profile.js, lib/internal/perf/pprof/protobuf.js, lib/internal/perf/pprof/string_table.js, is licensed as follows: + """ + Copyright 2022 DataDog Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + Datadog pprof-format + Copyright 2022-Present Datadog, Inc. + + This product includes software developed at Datadog, Inc. (https://www.datadoghq.com/). + """ diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index a1c87b0143b3..fc41ee0bea2e 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -17,6 +17,8 @@ Node.js supports the following [Web Performance APIs][]: * [User Timing][] * [Resource Timing][] +The [`node:perf_hooks/pprof`][] module collects profiles in the pprof format. + ```mjs import { performance, PerformanceObserver } from 'node:perf_hooks'; @@ -3051,6 +3053,292 @@ recorded or expired after this method returns do not change the returned histogram. Materialization allocates one histogram and merges every retained chunk. +## pprof API + + + +> Stability: 1.1 - Active development + +The `node:perf_hooks/pprof` module collects wall time profiles of the +JavaScript code running on the current thread, and encodes them in the +[pprof][] format, a common format for profiling data. + +```mjs +import { time, encodeSync } from 'node:perf_hooks/pprof'; +import { writeFileSync } from 'node:fs'; + +function fibonacci(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +} + +time.start(); +fibonacci(35); +const profile = time.stop(); +writeFileSync('wall.pb.gz', encodeSync(profile)); +``` + +```cjs +const { time, encodeSync } = require('node:perf_hooks/pprof'); +const { writeFileSync } = require('node:fs'); + +function fibonacci(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +} + +time.start(); +fibonacci(35); +const profile = time.stop(); +writeFileSync('wall.pb.gz', encodeSync(profile)); +``` + +The profile can then be viewed with the [`pprof`][pprof] command-line tool +(see [installation instructions][pprof installation]): + +```bash +pprof -http=: wall.pb.gz +``` + +The profiler samples the stack of the thread at a regular interval, using V8's +CPU profiler. Each sample accounts for the wall time elapsed since the previous +one. Time spent idle in the event loop is not reported as wall time, and time +spent in garbage collection is reported under a `Node.js` frame, as +[`pprof.time.constants.GARBAGE_COLLECTION_FUNCTION_NAME`][]. When +`collectCpuTime` is enabled, the CPU time that the thread uses while idle is +reported under an `(idle)` frame, whose samples have no wall time. + +Each thread has its own profiler: a profiler started in a [`Worker`][] profiles +that worker. At most one profiler runs at a time on each thread. + +External modules that provide the same functionality, like `@datadog/pprof`, +should not be used in conjunction with this API. + +### `pprof.time.start([options])` + + + +* `options` {Object} + * `intervalMicros` {integer} The average time between samples, in + microseconds. **Default:** `1000`. + * `durationMillis` {integer} The expected time between calls to + [`pprof.time.stop()`][], in milliseconds. It is used to size buffers upfront and + must not be shorter than `intervalMicros`. **Default:** `60000`. + * `lineNumbers` {boolean} When `true`, samples are aggregated by line rather + than by function: the line of a leaf frame is the line that was running, + and the line of other frames is the line of the call they made. + **Default:** `false`. + * `collectCpuTime` {boolean} When `true`, profiles also report the CPU time + of the thread, as a `cpu` sample type. Profiles collected on the main + thread additionally report the CPU time of the threads that do not run + JavaScript, as [`pprof.time.constants.NON_JS_THREADS_FUNCTION_NAME`][]. Not + supported on Windows, nor with `lineNumbers`. **Default:** `false`. + * `workaroundV8Bug` {boolean} When `true`, works around a V8 bug that can + make the profiler stop collecting samples when it is restarted. Has no + effect on Windows. **Default:** `true`. + +Starts profiling the current thread. + +Throws an `ERR_INVALID_STATE` error if the profiler is already started. + +### `pprof.time.stop([restart])` + + + +* `restart` {boolean} When `true`, a new profile starts immediately, with the + same options, so that no sample is lost between consecutive profiles. + **Default:** `false`. +* Returns: {pprof.Profile} + +Stops the current profile, and returns it. + +The profile is processed after the next profile starts, so that the cost of +processing it is accounted for in the next profile. + +If the next profile cannot be started, the current profile is still returned, +and the profiler is stopped: [`pprof.time.isStarted()`][] returns `false`. + +Throws an `ERR_INVALID_STATE` error if the profiler is not started. + +### `pprof.time.profile([options])` + + + +* `options` {Object} The options of [`pprof.time.start()`][], and: + * `signal` {AbortSignal} Stops profiling, without returning a profile. +* Returns: {Promise} Fulfills with a {pprof.Profile}. + +Profiles the current thread for `options.durationMillis` milliseconds. + +The profile only contains the work that the thread does while the returned +promise is pending, such as handling requests, since time spent idle in the +event loop is not reported. + +```mjs +import { createServer } from 'node:http'; +import { writeFileSync } from 'node:fs'; +import { time, encodeSync } from 'node:perf_hooks/pprof'; + +function fibonacci(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +} + +createServer((req, res) => { + res.end(`${fibonacci(25)}\n`); +}).listen(8080); + +// Profile the requests that the server handles in the next 10 seconds. +const profile = await time.profile({ durationMillis: 10_000 }); +writeFileSync('wall.pb.gz', encodeSync(profile)); +``` + +```cjs +const { createServer } = require('node:http'); +const { writeFileSync } = require('node:fs'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +function fibonacci(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +} + +createServer((req, res) => { + res.end(`${fibonacci(25)}\n`); +}).listen(8080); + +// Profile the requests that the server handles in the next 10 seconds. +time.profile({ durationMillis: 10_000 }).then((profile) => { + writeFileSync('wall.pb.gz', encodeSync(profile)); +}); +``` + +### `pprof.time.isStarted()` + + + +* Returns: {boolean} + +Returns whether the profiler is started on the current thread. + +### `pprof.time.v8ProfilerStuckEventLoopDetected()` + + + +* Returns: {integer} + +Returns whether V8's CPU profiler was found to be stuck, and no longer +collecting samples, the last time that [`pprof.time.stop(true)`][] restarted +the profiler: `0` if it was not, `1` if it possibly was, or `2` if it certainly +was. + +When V8's CPU profiler is found to be stuck, possibly or certainly, the +profiler recovers on its own: it discards V8's CPU profiler and creates a new +one before starting the next profile. + +Always returns `0` after the profiler is stopped without being restarted. + +### `pprof.time.constants` + + + +* {Object} + * `GARBAGE_COLLECTION_FUNCTION_NAME` {string} The name of the frame under + which garbage collection is reported: `'Garbage Collection'`. + * `NON_JS_THREADS_FUNCTION_NAME` {string} The name of the frame under which + the CPU time of the threads that do not run JavaScript is reported: + `'Non JS threads activity'`. + +Both frames are children of a `Node.js` frame. + +### `pprof.encode(profile)` + + + +* `profile` {pprof.Profile} +* Returns: {Promise} Fulfills with a {Buffer}. + +Encodes a profile as a gzip-compressed pprof protobuf message, yielding to the +event loop while encoding. The profile must not be modified until the returned +promise settles. + +### `pprof.encodeSync(profile)` + + + +* `profile` {pprof.Profile} +* Returns: {Buffer} + +Encodes a profile as a gzip-compressed pprof protobuf message. + +### Class: `pprof.Profile` + + + +A profile returned by [`pprof.time.stop()`][] and [`pprof.time.profile()`][]. + +Its structure follows the `Profile` message defined in pprof's +[`profile.proto`][]: each field of the message is a property of the object, +named in camel case, such as `sampleType`, `sample`, `location`, `function`, +`stringTable`, `timeNanos`, `durationNanos`, `periodType` and `period`. + +`timeNanos` is the time at which the profile started, in nanoseconds since the +Unix epoch. + +#### `profile.encode()` + + + +* Returns: {Buffer} + +Encodes the profile as an uncompressed pprof protobuf message. + +#### `profile.encodeAsync()` + + + +* Returns: {Promise} Fulfills with a {Buffer}. + +Encodes the profile as an uncompressed pprof protobuf message, yielding to the +event loop while encoding. The profile must not be modified until the returned +promise settles. + +### Caveats + +On POSIX systems, when `workaroundV8Bug` or `collectCpuTime` is enabled, the +profiler installs its own `SIGPROF` signal handler, which runs before V8's +sampler handles the signal. Using other `SIGPROF` handlers at the same time, +such as a `process.on('SIGPROF')` listener, is not supported. + +V8 only records the source positions that attribute samples to inlined +functions for code compiled while a CPU profiler exists. Samples of functions +that were inlined into code optimized before the profiler started are +attributed to the function they were inlined into. + +When `collectCpuTime` is enabled, CPU time is attributed to samples using a +buffer sized after `durationMillis`. Samples taken after the buffer fills up, +because [`pprof.time.stop()`][] was called later than expected, are dropped. + ## Histogram analysis examples The `Histogram` class provides statistical analysis methods useful for @@ -3479,10 +3767,12 @@ dns.promises.resolve('localhost'); [Welch's t-test]: https://en.wikipedia.org/wiki/Welch%27s_t-test [Worker threads]: worker_threads.md#worker-threads [`'exit'`]: process.md#event-exit +[`Worker`]: worker_threads.md#class-worker [`child_process.spawnSync()`]: child_process.md#child_processspawnsynccommand-args-options [`histogram.diff()`]: #histogramdiffother [`histogram.exceeds`]: #histogramexceeds [`histogram.export()`]: #histogramexport +[`node:perf_hooks/pprof`]: #pprof-api [`perf_hooks.createHistogram()`]: #perf_hookscreatehistogramoptions [`perf_hooks.createSlidingWindowHistogram()`]: #perf_hookscreateslidingwindowhistogramoptions [`perf_hooks.eventLoopUtilization()`]: #perf_hookseventlooputilizationutilization1-utilization2 @@ -3491,8 +3781,18 @@ dns.promises.resolve('localhost'); [`perf_hooks.timerify()`]: #perf_hookstimerifyfn-options [`performanceNodeTiming.uvMetricsInfoBigInt`]: #performancenodetiminguvmetricsinfobigint [`performanceNodeTiming.uvMetricsInfo`]: #performancenodetiminguvmetricsinfo +[`pprof.time.constants.GARBAGE_COLLECTION_FUNCTION_NAME`]: #pproftimeconstants +[`pprof.time.constants.NON_JS_THREADS_FUNCTION_NAME`]: #pproftimeconstants +[`pprof.time.isStarted()`]: #pproftimeisstarted +[`pprof.time.profile()`]: #pproftimeprofileoptions +[`pprof.time.start()`]: #pproftimestartoptions +[`pprof.time.stop()`]: #pproftimestoprestart +[`pprof.time.stop(true)`]: #pproftimestoprestart [`process.hrtime()`]: process.md#processhrtimetime +[`profile.proto`]: https://github.com/google/pprof/blob/084b33a85f63291f0513dc6a6284e5dfa66c8e3a/proto/profile.proto [`timeOrigin`]: https://w3c.github.io/hr-time/#dom-performance-timeorigin [`window.performance.toJSON`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON [`window.performance`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/performance [histogram export format compatibility]: #histogram-export-format-compatibility +[pprof]: https://github.com/google/pprof/tree/084b33a85f63291f0513dc6a6284e5dfa66c8e3a +[pprof installation]: https://github.com/google/pprof/blob/084b33a85f63291f0513dc6a6284e5dfa66c8e3a/README.md#building-pprof diff --git a/doc/type-map.json b/doc/type-map.json index c603e059a7ee..40871630460a 100644 --- a/doc/type-map.json +++ b/doc/type-map.json @@ -101,6 +101,7 @@ "PerformanceNodeTiming": "perf_hooks.html#class-performancenodetiming", "PerformanceObserver": "perf_hooks.html#class-performanceobserver", "PerformanceObserverEntryList": "perf_hooks.html#class-performanceobserverentrylist", + "pprof.Profile": "perf_hooks.html#class-pprofprofile", "Readable": "stream.html#class-streamreadable", "ReadableByteStreamController": "webstreams.html#class-readablebytestreamcontroller", "ReadableStream": "webstreams.html#class-readablestream", diff --git a/lib/internal/perf/pprof/encoder.js b/lib/internal/perf/pprof/encoder.js new file mode 100644 index 000000000000..cc2b5bd7979f --- /dev/null +++ b/lib/internal/perf/pprof/encoder.js @@ -0,0 +1,96 @@ +// Copyright 2019 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/ts/src/profile-encoder.ts +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const { + Promise, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + }, +} = require('internal/errors'); +const { Profile } = require('internal/perf/pprof/profile'); + +// The zlib module is only loaded when a profile is encoded, so that loading +// node:perf_hooks/pprof to profile does not load it. +let zlib; +/** + * Loads the zlib module the first time it is needed. + * @returns {object} The zlib module. + */ +function lazyZlib() { + zlib ??= require('zlib'); + return zlib; +} + +/** + * Validates the argument of `encode()` and `encodeSync()`, so that they only + * encode profiles that the time profiler returned, or that were built from + * the same `Profile` class. + * @param {any} profile The value to validate. + * @throws {TypeError} An `ERR_INVALID_ARG_TYPE` error if `profile` is not a + * `pprof.Profile`. + */ +function validateProfile(profile) { + if (!(profile instanceof Profile)) { + throw new ERR_INVALID_ARG_TYPE('profile', 'pprof.Profile', profile); + } +} + +/** + * Encodes a profile as a gzip-compressed pprof protobuf message, yielding to + * the event loop while encoding. + * @param {Profile} profile The profile to encode. + * @returns {Promise} The gzip-compressed encoding of the profile. + * @throws {TypeError} Rejects with an `ERR_INVALID_ARG_TYPE` error if + * `profile` is not a `pprof.Profile`. + * @throws {Error} Rejects with the error of zlib if compressing fails. + */ +async function encode(profile) { + validateProfile(profile); + const { gzip } = lazyZlib(); + const encoded = await profile.encodeAsync(); + return new Promise((resolve, reject) => { + gzip(encoded, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); +} + +/** + * Encodes a profile as a gzip-compressed pprof protobuf message. + * @param {Profile} profile The profile to encode. + * @returns {Buffer} The gzip-compressed encoding of the profile. + * @throws {TypeError} An `ERR_INVALID_ARG_TYPE` error if `profile` is not a + * `pprof.Profile`. + * @throws {Error} The error of zlib if compressing fails. + */ +function encodeSync(profile) { + validateProfile(profile); + return lazyZlib().gzipSync(profile.encode()); +} + +module.exports = { + encode, + encodeSync, +}; diff --git a/lib/internal/perf/pprof/normalizer.js b/lib/internal/perf/pprof/normalizer.js new file mode 100644 index 000000000000..06039d24a803 --- /dev/null +++ b/lib/internal/perf/pprof/normalizer.js @@ -0,0 +1,381 @@ +// Copyright 2026 Datadog. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from the time profile parts +// of +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/ts/src/profile-normalizer.ts +// without source maps and labels, and walking the flat node tables that the +// pprof binding produces rather than trees of nodes. +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +// Format-neutral normalization of time profiles: turns the profiles that the +// pprof binding produces into a stream of frames, stacks and samples, applying +// everything that is a matter of profile semantics rather than of the output +// format: synthetic runtime frames, CPU time attribution and sample values. +// Output formats are implemented as visitors on top of it, as described by +// the TimeProfileVisitor type. + +/** + * Receives a normalized time profile. `metadata()` is called once, then + * `frame()`, `stack()` and `sample()` are called interleaved. Each distinct + * frame and stack is delivered once, before the first stack or sample that + * refers to it, and only stacks that have samples are delivered. + * @typedef {object} TimeProfileVisitor + * @property {(metadata: object) => void} metadata Receives the + * `sampleTypes`, `startTimeNanos`, `durationNanos`, `periodType` and + * `period` of the profile. + * @property {(frame: object) => any} frame Receives a frame, as + * `{ name, file, line, column, scriptId }`, and returns the ID by which + * stacks refer to it. + * @property {(frameIds: any[]) => any} stack Receives the frame IDs of a + * stack, leaf first, and returns the ID by which samples refer to it. + * @property {(sample: { stackId: any, values: number[] }) => void} sample + * Receives a sample: the ID of its stack, and one value per sample type. + */ + +const { + ArrayPrototypePush, + BigInt, + DateNow, + Int32Array, + MathFloor, + MathMax, + MathMin, + MathRound, + SafeMap, + StringPrototypeSlice, + StringPrototypeStartsWith, +} = primordials; + +/** + * The name of the synthetic frame that holds the CPU time of the threads that + * do not run JavaScript, such as the threads of the libuv thread pool and of + * V8. Exposed as `pprof.time.constants.NON_JS_THREADS_FUNCTION_NAME`. + * @type {string} + */ +const NON_JS_THREADS_FUNCTION_NAME = 'Non JS threads activity'; +/** + * The name of the synthetic frame that the samples taken during garbage + * collection are reported under, instead of V8's `(garbage collector)`. + * Exposed as `pprof.time.constants.GARBAGE_COLLECTION_FUNCTION_NAME`. + * @type {string} + */ +const GARBAGE_COLLECTION_FUNCTION_NAME = 'Garbage Collection'; +/** + * The name of the synthetic top level frame that the + * `GARBAGE_COLLECTION_FUNCTION_NAME` and `NON_JS_THREADS_FUNCTION_NAME` frames + * are under. + * @type {string} + */ +const RUNTIME_FUNCTION_NAME = 'Node.js'; + +/** + * Returns the name of the function that generated the frame, or, for an + * anonymous function, a name made from its position, so that anonymous + * functions can be told apart. + * @param {{ name: string, line: number, column: number }} frame The frame, + * with the name of its function, which is empty for anonymous functions, + * and its position. + * @returns {string} The name of the function, or + * `(anonymous:L#:C#)`, `(anonymous:L#)` or + * `(anonymous)`, depending on which parts of the position are known. + */ +function frameFunctionName(frame) { + if (frame.name) { + return frame.name; + } + if (frame.line) { + if (frame.column) { + return `(anonymous:L#${frame.line}:C#${frame.column})`; + } + return `(anonymous:L#${frame.line})`; + } + return '(anonymous)'; +} + +/** + * Delivers a time profile to a visitor. + * + * The profile's nodes are modified as follows: + * - `(program)` nodes are removed. + * - `(idle)` nodes are only kept when CPU time is attributed to them. Their + * samples keep their sample count, but get no wall time. + * - `(garbage collector)` nodes are renamed `Garbage Collection`, and moved + * under a top level `Node.js` node. + * - When CPU time was collected, a `Non JS threads activity` node, holding the + * CPU time of the threads that do not run JavaScript, is added under the + * `Node.js` node. + * + * Sample values are [sample count, wall nanoseconds], plus CPU nanoseconds if + * the profile has CPU time. + * @param {object} profile The flat node table that the pprof binding's + * `stop()` returns. + * @param {TimeProfileVisitor} visitor The visitor that receives the + * normalized profile. + * @param {object} options The sampling interval to report, and whether to + * recompute it from the profile. + * @param {number} options.intervalMicros The requested sampling interval. + * @param {boolean} options.recomputeSamplingInterval Whether to replace the + * requested interval with the average interval between samples. + */ +function visitTimeProfile(profile, visitor, options) { + const { + parent, + name, + scriptName, + scriptId, + lineNumber, + columnNumber, + hitCount, + cpuTime, + hasCpuTime, + } = profile; + const nodeCount = parent.length; + + let intervalMicros = options.intervalMicros; + if (options.recomputeSamplingInterval && profile.totalHitCount > 0) { + // The profile duration should be the number of hits times the interval. + // In practice, intervals between samples are larger than requested (e.g. + // 12.5ms vs 10ms), so an average is more accurate. For very short + // profiles the average is meaningless (e.g. with a single hit), so it is + // bounded to [intervalMicros, 2 * intervalMicros]. + intervalMicros = MathMin( + MathMax( + MathFloor((profile.endTime - profile.startTime) / profile.totalHitCount), + intervalMicros, + ), + 2 * intervalMicros, + ); + } + const intervalNanos = intervalMicros * 1000; + + const timeType = { type: 'wall', unit: 'nanoseconds' }; + const sampleTypes = [ + { type: 'sample', unit: 'count' }, + timeType, + ]; + if (hasCpuTime) { + ArrayPrototypePush(sampleTypes, { type: 'cpu', unit: 'nanoseconds' }); + } + const durationNanos = (profile.endTime - profile.startTime) * 1000; + // Exact with the binding's epoch offset. Without one, estimate it on the + // assumption that the profile was just stopped. + const startTimeNanos = profile.epochOffset !== undefined ? + BigInt(MathRound(profile.startTime + profile.epochOffset)) * 1000n : + BigInt(DateNow()) * 1000000n - BigInt(MathRound(durationNanos)); + visitor.metadata({ + sampleTypes, + startTimeNanos, + durationNanos, + periodType: timeType, + period: intervalNanos, + }); + + // The visitor's ID of each frame that was delivered, keyed by script ID, + // position and name, as made by getFrameId(). V8 creates a node for each + // call path, so a function called from several callers has several nodes: + // the map delivers their frame to the visitor once, and gives them the same + // frame ID, so that the visitor can share one location between them. + const frameIds = new SafeMap(); + + // Interned stacks, by internal stack index: the parent stack index (-1 for + // none), the visitor's frame ID, the visitor's stack ID (undefined until + // delivered), and the child stacks by frame ID. Stacks are interned by + // prefix, so stacks with equal frames get the same ID without comparing + // whole arrays. + const stackParents = []; + const stackFrames = []; + const stackIds = []; + const stackChildren = []; + const rootStacks = new SafeMap(); + + /** + * Returns the index of the interned stack made of `frameId` on top of + * `parentStack`, interning it if needed. + * @param {number} parentStack The index of the interned stack of the + * caller, or -1 for a stack of one frame. + * @param {any} frameId The ID that the visitor's `frame()` returned for the + * top frame. + * @returns {number} The index of the interned stack. + */ + function internStack(parentStack, frameId) { + let children; + if (parentStack < 0) { + children = rootStacks; + } else { + children = stackChildren[parentStack]; + if (children === undefined) { + children = new SafeMap(); + stackChildren[parentStack] = children; + } + } + let stack = children.get(frameId); + if (stack === undefined) { + stack = ArrayPrototypePush(stackParents, parentStack) - 1; + ArrayPrototypePush(stackFrames, frameId); + ArrayPrototypePush(stackIds, undefined); + ArrayPrototypePush(stackChildren, undefined); + children.set(frameId, stack); + } + return stack; + } + + /** + * Returns the visitor's ID of an interned stack, delivering the stack to + * the visitor the first time. + * @param {number} stack The index of the interned stack. + * @returns {any} The ID that the visitor's `stack()` returned for the stack. + */ + function getStackId(stack) { + let id = stackIds[stack]; + if (id === undefined) { + const stackFrameIds = []; + for (let s = stack; s !== -1; s = stackParents[s]) { + ArrayPrototypePush(stackFrameIds, stackFrames[s]); + } + id = visitor.stack(stackFrameIds); + stackIds[stack] = id; + } + return id; + } + + /** + * Returns the visitor's ID of a frame, delivering the frame to the visitor + * the first time. + * @param {string} frameName The name of the function of the frame, which + * is empty for anonymous functions. + * @param {string} file The path or URL of the script of the frame, or an + * empty string for frames without one. + * @param {number} frameScriptId The V8 ID of the script of the frame, or 0 + * for frames without one. + * @param {number} line The line of the frame: the first line of the + * function, or, with line numbers, the line that was executing. + * @param {number} column The column of the frame, or 0 if unknown. + * @returns {any} The ID that the visitor's `frame()` returned for the + * frame. Its type is up to the visitor; the serializer returns numbers. + */ + function getFrameId(frameName, file, frameScriptId, line, column) { + // The name comes last, so that the key is unambiguous. + const key = `${frameScriptId}:${line}:${column}:${frameName}`; + let id = frameIds.get(key); + if (id === undefined) { + id = visitor.frame({ + name: frameName, + file, + line, + column, + scriptId: frameScriptId, + }); + frameIds.set(key, id); + } + return id; + } + + let runtimeStack; + /** + * Returns the index of the stack of the synthetic top level `Node.js` + * frame, interning it the first time. + * @returns {number} The index of the interned stack. + */ + function getRuntimeStack() { + runtimeStack ??= internStack(-1, + getFrameId(RUNTIME_FUNCTION_NAME, '', 0, 0, 0)); + return runtimeStack; + } + + /** + * Delivers a sample of an interned stack to the visitor. + * @param {number} stack The index of the interned stack. + * @param {number[]} values One value per sample type. + */ + function emitSample(stack, values) { + visitor.sample({ stackId: getStackId(stack), values }); + } + + // The stack of each node, or -1 for nodes that are removed along with their + // descendants. Node 0 is the root, which has no frame. + const nodeStacks = new Int32Array(nodeCount); + nodeStacks[0] = -1; + for (let i = 1; i < nodeCount; i++) { + let nodeName = name[i]; + let parentStack; + if (parent[i] === 0) { + if (nodeName === '(program)') { + nodeStacks[i] = -1; + continue; + } + if (nodeName === '(garbage collector)') { + nodeName = GARBAGE_COLLECTION_FUNCTION_NAME; + parentStack = getRuntimeStack(); + } else { + parentStack = -1; + } + } else { + parentStack = nodeStacks[parent[i]]; + if (parentStack === -1) { + nodeStacks[i] = -1; + continue; + } + } + + // .mjs files have a `file://` prefix in the script name. + let file = scriptName[i]; + if (StringPrototypeStartsWith(file, 'file://')) { + file = StringPrototypeSlice(file, 7); + } + const stack = internStack( + parentStack, + getFrameId(nodeName, file, scriptId[i], lineNumber[i], columnNumber[i]), + ); + nodeStacks[i] = stack; + + const hits = hitCount[i]; + const cpu = hasCpuTime ? cpuTime[i] : 0; + // `(idle)` nodes only matter for the CPU time attributed to them, if any: + // their samples keep their sample count, but get no wall time. + const isIdle = nodeName === '(idle)'; + if ((!isIdle && hits > 0) || cpu > 0) { + const values = hits > 0 ? + [hits, isIdle ? 0 : hits * intervalNanos] : + [0, 0]; + if (hasCpuTime) { + ArrayPrototypePush(values, cpu); + } + emitSample(stack, values); + } + } + + if (hasCpuTime && profile.nonJSThreadsCpuTime) { + // No hits, since this is not wall time of the profiled thread. + const stack = internStack( + getRuntimeStack(), + getFrameId(NON_JS_THREADS_FUNCTION_NAME, '', 0, 0, 0), + ); + emitSample(stack, [ + 0, + 0, + profile.nonJSThreadsCpuTime, + ]); + } +} + +module.exports = { + GARBAGE_COLLECTION_FUNCTION_NAME, + NON_JS_THREADS_FUNCTION_NAME, + frameFunctionName, + visitTimeProfile, +}; diff --git a/lib/internal/perf/pprof/profile.js b/lib/internal/perf/pprof/profile.js new file mode 100644 index 000000000000..c25d27f9862c --- /dev/null +++ b/lib/internal/perf/pprof/profile.js @@ -0,0 +1,716 @@ +// Copyright 2022 Datadog, Inc. +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). +// +// Modified for inclusion in Node.js core: ported from the encoding half of +// https://github.com/DataDog/pprof-format/blob/53548398f38b16eb096cc04a75927316a68a9b54/src/index.ts +// +// SPDX-License-Identifier: MIT + +'use strict'; + +// The messages of pprof's profile.proto: +// https://github.com/google/pprof/blob/084b33a85f63291f0513dc6a6284e5dfa66c8e3a/proto/profile.proto + +const { + ArrayPrototypeMap, +} = primordials; + +const { FastBuffer } = require('internal/buffer'); +const { + Message, + encodeBoolField, + encodeMessageArrayField, + encodeMessageField, + encodeNumberField, + encodePackedNumbersField, + kEncodeToBuffer, + kMeasure, + measureBoolField, + measureMessageArrayField, + measureMessageField, + measureNumberField, + measurePackedNumbersField, + newEncodeContext, + verifyEncodedLength, + yieldToEventLoop, +} = require('internal/perf/pprof/protobuf'); +const { StringTable } = require('internal/perf/pprof/string_table'); + +// Field numbers, as declared in profile.proto. +const kValueTypeType = 1; +const kValueTypeUnit = 2; + +const kLabelKey = 1; +const kLabelStr = 2; +const kLabelNum = 3; +const kLabelNumUnit = 4; + +const kSampleLocationId = 1; +const kSampleValue = 2; +const kSampleLabel = 3; + +const kMappingId = 1; +const kMappingMemoryStart = 2; +const kMappingMemoryLimit = 3; +const kMappingFileOffset = 4; +const kMappingFilename = 5; +const kMappingBuildId = 6; +const kMappingHasFunctions = 7; +const kMappingHasFilenames = 8; +const kMappingHasLineNumbers = 9; +const kMappingHasInlineFrames = 10; + +const kLineFunctionId = 1; +const kLineLine = 2; +const kLineColumn = 3; + +const kLocationId = 1; +const kLocationMappingId = 2; +const kLocationAddress = 3; +const kLocationLine = 4; +const kLocationIsFolded = 5; + +const kFunctionId = 1; +const kFunctionName = 2; +const kFunctionSystemName = 3; +const kFunctionFilename = 4; +const kFunctionStartLine = 5; + +const kProfileSampleType = 1; +const kProfileSample = 2; +const kProfileMapping = 3; +const kProfileLocation = 4; +const kProfileFunction = 5; +const kProfileStringTable = 6; +const kProfileDropFrames = 7; +const kProfileKeepFrames = 8; +const kProfileTimeNanos = 9; +const kProfileDurationNanos = 10; +const kProfilePeriodType = 11; +const kProfilePeriod = 12; +const kProfileComment = 13; +const kProfileDefaultSampleType = 14; +const kProfileDocUrl = 15; + +/** + * The name and unit of a number in a profile. Each sample of a profile holds + * a list of numbers, and the profile's `sampleType` holds one `ValueType` per + * number, in the same order, which says what that number is. For example, a + * time profile has the sample types `sample` in `count`, `wall` in + * `nanoseconds` and, with CPU time, `cpu` in `nanoseconds`: a sample with + * the values `[3, 3000000, 2500000]` was seen 3 times, which accounts for + * 3 ms of wall time and 2.5 ms of CPU time. The profile's `periodType` is + * also a `ValueType`, which gives the name and unit of its `period`. + * `type` and `unit` are indices in the profile's string table. + */ +class ValueType extends Message { + /** + * Returns `data` if it is a `ValueType`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {ValueType|object} data A `ValueType`, or an object with the fields of one. + * @returns {ValueType} `data`, or a new `ValueType` with the fields of `data`. + */ + static create(data) { + return data instanceof ValueType ? data : new ValueType(data); + } + + /** + * Creates a `ValueType` message: the type and unit of a value. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.type = data.type || 0; + this.unit = data.unit || 0; + } + + /** + * Measures the message, without its tag and length. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure]() { + return measureNumberField(kValueTypeType, this.type) + + measureNumberField(kValueTypeUnit, this.unit); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset) { + offset = encodeNumberField(buffer, offset, kValueTypeType, this.type); + return encodeNumberField(buffer, offset, kValueTypeUnit, this.unit); + } +} + +/** + * A key-value pair that annotates a sample with information that is not part + * of its stack, such as the ID of the thread or of the request that was being + * handled when the sample was taken. Tools use labels to filter and group + * samples. `key` is the index of the key in the profile's string table, and + * the value is either a string, as the index `str` in the string table, or a + * number, `num`, whose unit is named by the index `numUnit`. The time + * profiler does not create labels. + */ +class Label extends Message { + /** + * Returns `data` if it is a `Label`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {Label|object} data A `Label`, or an object with the fields of one. + * @returns {Label} `data`, or a new `Label` with the fields of `data`. + */ + static create(data) { + return data instanceof Label ? data : new Label(data); + } + + /** + * Creates a `Label` message: a key and a string or numeric value attached to + * a sample. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.key = data.key || 0; + this.str = data.str || 0; + this.num = data.num || 0; + this.numUnit = data.numUnit || 0; + } + + /** + * Measures the message, without its tag and length. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure]() { + return measureNumberField(kLabelKey, this.key) + + measureNumberField(kLabelStr, this.str) + + measureNumberField(kLabelNum, this.num) + + measureNumberField(kLabelNumUnit, this.numUnit); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset) { + offset = encodeNumberField(buffer, offset, kLabelKey, this.key); + offset = encodeNumberField(buffer, offset, kLabelStr, this.str); + offset = encodeNumberField(buffer, offset, kLabelNum, this.num); + return encodeNumberField(buffer, offset, kLabelNumUnit, this.numUnit); + } +} + +/** + * One measurement of a profile: a stack trace, and the values recorded while + * the program was executing it. For the time profiler, a sample aggregates + * all the times that the sampler found the thread in the same stack, and its + * values are the number of times, the wall time that they account for and, + * optionally, the CPU time. `locationId` lists the IDs of the `Location`s of + * the stack, leaf (the function that was executing) first. `value` holds one + * value per `ValueType` of the profile's `sampleType`, in the same order. + * `label` holds the `Label`s that annotate the sample. + */ +class Sample extends Message { + /** + * Returns `data` if it is a `Sample`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {Sample|object} data A `Sample`, or an object with the fields of one. + * @returns {Sample} `data`, or a new `Sample` with the fields of `data`. + */ + static create(data) { + return data instanceof Sample ? data : new Sample(data); + } + + /** + * Creates a `Sample` message: a stack and the values recorded for it. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.locationId = data.locationId || []; + this.value = data.value || []; + this.label = ArrayPrototypeMap(data.label || [], Label.create); + } + + /** + * Measures the message, without its tag and length. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are recorded in. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure](context) { + return measurePackedNumbersField(kSampleLocationId, this.locationId, + context) + + measurePackedNumbersField(kSampleValue, this.value, context) + + measureMessageArrayField(kSampleLabel, this.label, context); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are read from. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset, context) { + offset = encodePackedNumbersField(buffer, offset, kSampleLocationId, + this.locationId, context); + offset = encodePackedNumbersField(buffer, offset, kSampleValue, + this.value, context); + return encodeMessageArrayField(buffer, offset, kSampleLabel, this.label, + context); + } +} + +/** + * Describes a binary, such as an executable or a shared library, that is + * loaded in the address space of the profiled process, so that tools can + * find the symbols of the native code addresses in a profile: the address + * range it is loaded at, its file, its build ID, and which symbol information + * is available. Profiles of JavaScript do not refer to code by address, so + * the time profiler creates no mappings. + */ +class Mapping extends Message { + /** + * Returns `data` if it is a `Mapping`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {Mapping|object} data A `Mapping`, or an object with the fields of one. + * @returns {Mapping} `data`, or a new `Mapping` with the fields of `data`. + */ + static create(data) { + return data instanceof Mapping ? data : new Mapping(data); + } + + /** + * Creates a `Mapping` message: a binary mapped into the address space. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.id = data.id || 0; + this.memoryStart = data.memoryStart || 0; + this.memoryLimit = data.memoryLimit || 0; + this.fileOffset = data.fileOffset || 0; + this.filename = data.filename || 0; + this.buildId = data.buildId || 0; + this.hasFunctions = !!data.hasFunctions; + this.hasFilenames = !!data.hasFilenames; + this.hasLineNumbers = !!data.hasLineNumbers; + this.hasInlineFrames = !!data.hasInlineFrames; + } + + /** + * Measures the message, without its tag and length. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure]() { + return measureNumberField(kMappingId, this.id) + + measureNumberField(kMappingMemoryStart, this.memoryStart) + + measureNumberField(kMappingMemoryLimit, this.memoryLimit) + + measureNumberField(kMappingFileOffset, this.fileOffset) + + measureNumberField(kMappingFilename, this.filename) + + measureNumberField(kMappingBuildId, this.buildId) + + measureBoolField(kMappingHasFunctions, this.hasFunctions) + + measureBoolField(kMappingHasFilenames, this.hasFilenames) + + measureBoolField(kMappingHasLineNumbers, this.hasLineNumbers) + + measureBoolField(kMappingHasInlineFrames, this.hasInlineFrames); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset) { + offset = encodeNumberField(buffer, offset, kMappingId, this.id); + offset = encodeNumberField(buffer, offset, kMappingMemoryStart, + this.memoryStart); + offset = encodeNumberField(buffer, offset, kMappingMemoryLimit, + this.memoryLimit); + offset = encodeNumberField(buffer, offset, kMappingFileOffset, + this.fileOffset); + offset = encodeNumberField(buffer, offset, kMappingFilename, + this.filename); + offset = encodeNumberField(buffer, offset, kMappingBuildId, this.buildId); + offset = encodeBoolField(buffer, offset, kMappingHasFunctions, + this.hasFunctions); + offset = encodeBoolField(buffer, offset, kMappingHasFilenames, + this.hasFilenames); + offset = encodeBoolField(buffer, offset, kMappingHasLineNumbers, + this.hasLineNumbers); + return encodeBoolField(buffer, offset, kMappingHasInlineFrames, + this.hasInlineFrames); + } +} + +/** + * A position in the source code: the ID of the `ProfileFunction` that it is + * in, and its `line` and `column`. A `Location` is made of one or more + * `Line`s. + */ +class Line extends Message { + /** + * Returns `data` if it is a `Line`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {Line|object} data A `Line`, or an object with the fields of one. + * @returns {Line} `data`, or a new `Line` with the fields of `data`. + */ + static create(data) { + return data instanceof Line ? data : new Line(data); + } + + /** + * Creates a `Line` message: a function and a position in its source. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.functionId = data.functionId || 0; + this.line = data.line || 0; + this.column = data.column || 0; + } + + /** + * Measures the message, without its tag and length. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure]() { + return measureNumberField(kLineFunctionId, this.functionId) + + measureNumberField(kLineLine, this.line) + + measureNumberField(kLineColumn, this.column); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset) { + offset = encodeNumberField(buffer, offset, kLineFunctionId, + this.functionId); + offset = encodeNumberField(buffer, offset, kLineLine, this.line); + return encodeNumberField(buffer, offset, kLineColumn, this.column); + } +} + +/** + * A frame of the stacks of a profile, which samples refer to by `id`. Its + * `line` lists the source positions that the frame is made of: one, unless + * functions were inlined into each other, in which case the inlined functions + * come first and the function they were inlined into comes last. Native code + * frames can also have an `address`, in the binary of the `Mapping` that + * `mappingId` refers to. The time profiler creates one location per distinct + * function, or per distinct line with the `lineNumbers` option. + */ +class Location extends Message { + /** + * Returns `data` if it is a `Location`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {Location|object} data A `Location`, or an object with the fields of one. + * @returns {Location} `data`, or a new `Location` with the fields of `data`. + */ + static create(data) { + return data instanceof Location ? data : new Location(data); + } + + /** + * Creates a `Location` message: a stack frame and its lines. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.id = data.id || 0; + this.mappingId = data.mappingId || 0; + this.address = data.address || 0; + this.line = ArrayPrototypeMap(data.line || [], Line.create); + this.isFolded = !!data.isFolded; + } + + /** + * Measures the message, without its tag and length. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are recorded in. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure](context) { + return measureNumberField(kLocationId, this.id) + + measureNumberField(kLocationMappingId, this.mappingId) + + measureNumberField(kLocationAddress, this.address) + + measureMessageArrayField(kLocationLine, this.line, context) + + measureBoolField(kLocationIsFolded, this.isFolded); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are read from. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset, context) { + offset = encodeNumberField(buffer, offset, kLocationId, this.id); + offset = encodeNumberField(buffer, offset, kLocationMappingId, + this.mappingId); + offset = encodeNumberField(buffer, offset, kLocationAddress, + this.address); + offset = encodeMessageArrayField(buffer, offset, kLocationLine, this.line, + context); + return encodeBoolField(buffer, offset, kLocationIsFolded, this.isFolded); + } +} + +/** + * A function that the frames of a profile are in, which `Line`s refer to by + * `id`: its name, as `name`, and as `systemName` for the name used by the + * system, such as a mangled C++ name, its source file, as `filename`, and its + * first line, as `startLine`. Strings are indices in the profile's string + * table. Several locations can refer to the same function, such as the + * locations of the lines of one function. Not named `Function`, so that it + * does not shadow the global. + */ +class ProfileFunction extends Message { + /** + * Returns `data` if it is a `ProfileFunction`, or creates one from it, so that + * messages and plain objects can be mixed in the fields of other messages. + * @param {ProfileFunction|object} data A `ProfileFunction`, or an object with the fields of one. + * @returns {ProfileFunction} `data`, or a new `ProfileFunction` with the fields of `data`. + */ + static create(data) { + return data instanceof ProfileFunction ? data : new ProfileFunction(data); + } + + /** + * Creates a `Function` message: the name and source file of a function. + * @param {object} data The fields of the message. Missing fields take their + * default value. + */ + constructor(data) { + super(); + this.id = data.id || 0; + this.name = data.name || 0; + this.systemName = data.systemName || 0; + this.filename = data.filename || 0; + this.startLine = data.startLine || 0; + } + + /** + * Measures the message, without its tag and length. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure]() { + return measureNumberField(kFunctionId, this.id) + + measureNumberField(kFunctionName, this.name) + + measureNumberField(kFunctionSystemName, this.systemName) + + measureNumberField(kFunctionFilename, this.filename) + + measureNumberField(kFunctionStartLine, this.startLine); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset) { + offset = encodeNumberField(buffer, offset, kFunctionId, this.id); + offset = encodeNumberField(buffer, offset, kFunctionName, this.name); + offset = encodeNumberField(buffer, offset, kFunctionSystemName, + this.systemName); + offset = encodeNumberField(buffer, offset, kFunctionFilename, + this.filename); + return encodeNumberField(buffer, offset, kFunctionStartLine, + this.startLine); + } +} + +/** + * A complete profile, as the pprof tools read it. It holds: + * - `sampleType`: the `ValueType` of each value of the samples. + * - `sample`: the `Sample`s, which refer to locations by ID. + * - `location` and `function`: the `Location`s and `ProfileFunction`s that + * the stacks of the samples are made of. + * - `stringTable`: the strings that the other fields refer to by index. + * - `timeNanos` and `durationNanos`: when the profile started, in + * nanoseconds since the epoch, and how long it lasted. + * - `periodType` and `period`: what separates two samples, such as 1000000 + * nanoseconds of wall time. + * This is the class of the `pprof.Profile` objects that the time profiler + * returns, and that `encode()` and `encodeSync()` accept. + */ +class Profile extends Message { + /** + * Creates a `Profile` message: the samples of a profile, and the locations, + * functions and strings that they refer to. + * @param {object} [data] The fields of the message. Missing fields take their + * default value. + */ + constructor(data = { __proto__: null }) { + super(); + this.sampleType = ArrayPrototypeMap(data.sampleType || [], + ValueType.create); + this.sample = ArrayPrototypeMap(data.sample || [], Sample.create); + this.mapping = ArrayPrototypeMap(data.mapping || [], Mapping.create); + this.location = ArrayPrototypeMap(data.location || [], Location.create); + this.function = ArrayPrototypeMap(data.function || [], + ProfileFunction.create); + this.stringTable = data.stringTable || new StringTable(); + this.dropFrames = data.dropFrames || 0; + this.keepFrames = data.keepFrames || 0; + this.timeNanos = data.timeNanos || 0; + this.durationNanos = data.durationNanos || 0; + this.periodType = data.periodType ? + ValueType.create(data.periodType) : undefined; + this.period = data.period || 0; + this.comment = data.comment || []; + this.defaultSampleType = data.defaultSampleType || 0; + this.docUrl = data.docUrl || 0; + } + + /** + * Measures the message, without its tag and length. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are recorded in. + * @returns {number} The number of bytes that the message takes. + */ + [kMeasure](context) { + return measureMessageArrayField(kProfileSampleType, this.sampleType, + context) + + measureMessageArrayField(kProfileSample, this.sample, context) + + measureMessageArrayField(kProfileMapping, this.mapping, context) + + measureMessageArrayField(kProfileLocation, this.location, context) + + measureMessageArrayField(kProfileFunction, this.function, context) + + this.stringTable[kMeasure](kProfileStringTable) + + measureNumberField(kProfileDropFrames, this.dropFrames) + + measureNumberField(kProfileKeepFrames, this.keepFrames) + + measureNumberField(kProfileTimeNanos, this.timeNanos) + + measureNumberField(kProfileDurationNanos, this.durationNanos) + + measureMessageField(kProfilePeriodType, this.periodType, context) + + measureNumberField(kProfilePeriod, this.period) + + measurePackedNumbersField(kProfileComment, this.comment, context) + + measureNumberField(kProfileDefaultSampleType, this.defaultSampleType) + + measureNumberField(kProfileDocUrl, this.docUrl); + } + + /** + * Encodes the fields of the message that follow the string table. + * @param {Buffer} buffer The buffer to write the fields to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the fields. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are read from. + * @returns {number} The offset after the fields. + */ + #encodeBasicValuesToBuffer(buffer, offset, context) { + offset = encodeNumberField(buffer, offset, kProfileDropFrames, + this.dropFrames); + offset = encodeNumberField(buffer, offset, kProfileKeepFrames, + this.keepFrames); + offset = encodeNumberField(buffer, offset, kProfileTimeNanos, + this.timeNanos); + offset = encodeNumberField(buffer, offset, kProfileDurationNanos, + this.durationNanos); + offset = encodeMessageField(buffer, offset, kProfilePeriodType, + this.periodType, context); + offset = encodeNumberField(buffer, offset, kProfilePeriod, this.period); + offset = encodePackedNumbersField(buffer, offset, kProfileComment, + this.comment, context); + offset = encodeNumberField(buffer, offset, kProfileDefaultSampleType, + this.defaultSampleType); + return encodeNumberField(buffer, offset, kProfileDocUrl, this.docUrl); + } + + /** + * Encodes the message, without its tag and length. + * @param {Buffer} buffer The buffer to write the message to, which is at + * least as large as measured. + * @param {number} offset The offset at which to write the message. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the fields are read from. + * @returns {number} The offset after the message. + */ + [kEncodeToBuffer](buffer, offset, context) { + offset = encodeMessageArrayField(buffer, offset, kProfileSampleType, + this.sampleType, context); + offset = encodeMessageArrayField(buffer, offset, kProfileSample, + this.sample, context); + offset = encodeMessageArrayField(buffer, offset, kProfileMapping, + this.mapping, context); + offset = encodeMessageArrayField(buffer, offset, kProfileLocation, + this.location, context); + offset = encodeMessageArrayField(buffer, offset, kProfileFunction, + this.function, context); + offset = this.stringTable[kEncodeToBuffer](buffer, offset, + kProfileStringTable); + return this.#encodeBasicValuesToBuffer(buffer, offset, context); + } + + /** + * Like `encode()`, but yields to the event loop between the encoding of the + * repeated fields. The profile must not be mutated until the returned promise + * settles. + * @returns {Promise} The uncompressed protobuf encoding of the + * message. + * @throws {Error} Rejects with an `ERR_INTERNAL_ASSERTION` error if the + * profile was mutated while it was being encoded. + */ + async encodeAsync() { + const context = newEncodeContext(); + const length = this[kMeasure](context); + const buffer = new FastBuffer(length); + let offset = 0; + offset = encodeMessageArrayField(buffer, offset, kProfileSampleType, + this.sampleType, context); + await yieldToEventLoop(); + offset = encodeMessageArrayField(buffer, offset, kProfileSample, + this.sample, context); + await yieldToEventLoop(); + offset = encodeMessageArrayField(buffer, offset, kProfileMapping, + this.mapping, context); + await yieldToEventLoop(); + offset = encodeMessageArrayField(buffer, offset, kProfileLocation, + this.location, context); + await yieldToEventLoop(); + offset = encodeMessageArrayField(buffer, offset, kProfileFunction, + this.function, context); + await yieldToEventLoop(); + offset = this.stringTable[kEncodeToBuffer](buffer, offset, + kProfileStringTable); + await yieldToEventLoop(); + offset = this.#encodeBasicValuesToBuffer(buffer, offset, context); + verifyEncodedLength(offset, length); + return buffer; + } +} + +module.exports = { + Label, + Line, + Location, + Mapping, + Profile, + ProfileFunction, + Sample, + StringTable, + ValueType, +}; diff --git a/lib/internal/perf/pprof/protobuf.js b/lib/internal/perf/pprof/protobuf.js new file mode 100644 index 000000000000..c6a8ed18d472 --- /dev/null +++ b/lib/internal/perf/pprof/protobuf.js @@ -0,0 +1,451 @@ +// Copyright 2022 Datadog, Inc. +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). +// +// Modified for inclusion in Node.js core: ported from the encoding half of +// https://github.com/DataDog/pprof-format/blob/53548398f38b16eb096cc04a75927316a68a9b54/src/protobuf.ts +// +// SPDX-License-Identifier: MIT + +'use strict'; + +// Protobuf wire-format encoding helpers for the pprof messages. + +const { + ArrayPrototypePush, + BigIntAsUintN, + Number, + Promise, + Symbol, +} = primordials; + +const assert = require('internal/assert'); +const { FastBuffer } = require('internal/buffer'); +const { setImmediate } = require('timers'); + +const lowMax = 2 ** 32 - 1; +const lowMaxPlus1 = lowMax + 1; + +const kTypeVarInt = 0; +const kTypeLengthDelim = 2; + +// The methods that messages implement to be encoded, as fields of other +// messages or by `Message.prototype.encode()`. They are keyed by symbols so +// that they are not part of the public API of `pprof.Profile`. +const kMeasure = Symbol('kMeasure'); +const kEncodeToBuffer = Symbol('kEncodeToBuffer'); + +/** + * Splits a number or bigint into the high and low 32 bits of its two's + * complement 64-bit representation. + * @param {number|bigint} number The integer to split. Numbers must be safe + * integers. + * @returns {number[]} The high and low 32 bits, as unsigned integers. + */ +function long(number) { + if (typeof number === 'bigint') { + return [ + Number(BigIntAsUintN(32, number >> 32n)), + Number(BigIntAsUintN(32, number)), + ]; + } + + const sign = number < 0; + if (sign) { + number = -number; + } + + let lo = (number >>> 0) % lowMaxPlus1; + let hi = (number / lowMaxPlus1) >>> 0; + + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > lowMax) { + lo = 0; + if (++hi > lowMax) { + hi = 0; + } + } + } + + return [hi, lo]; +} + +/** + * Computes the tag of a field: its number and wire type, as encoded before + * its value. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {number} wireType The wire type of the field's value, such as + * `kTypeVarInt` or `kTypeLengthDelim`. + * @returns {number} The tag, before its varint encoding. + */ +function fieldTag(field, wireType) { + return field * 8 + wireType; +} + +/** + * Measures the encoded tag of a field. + * @param {number} field The field number, as declared in the `.proto` file. + * @returns {number} The number of bytes that the tag takes. + */ +function measureTag(field) { + // Tags of fields 1 to 15 fit in one byte. + return field < 16 ? 1 : measureNumber(fieldTag(field, 0)); +} + +/** + * Encodes the tag of a field. + * @param {Buffer} buffer The buffer to write the tag to. + * @param {number} offset The offset at which to write the tag. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {number} wireType The wire type of the field's value, such as + * `kTypeVarInt` or `kTypeLengthDelim`. + * @returns {number} The offset after the tag. + */ +function encodeTag(buffer, offset, field, wireType) { + if (field < 16) { + buffer[offset++] = fieldTag(field, wireType); + return offset; + } + return encodeNumber(buffer, offset, fieldTag(field, wireType)); +} + +/** + * Measures the varint encoding of a number, so that fields with a default + * value can be omitted. + * @param {number|bigint} number The integer to measure. + * @returns {number} The number of bytes that the encoding takes, or `0` for + * `0`. + */ +function measureNumber(number) { + let lo; + if (typeof number === 'number' && number >= 0 && number <= lowMax) { + if (number === 0) { + return 0; + } + lo = number; + } else { + if (number === 0n) { + return 0; + } + const words = long(number); + const hi = words[0]; + lo = words[1]; + if (hi !== 0) { + const c = hi >>> 24; + if (c !== 0) { + return c < 128 ? 9 : 10; + } + const b = (lo >>> 28 | hi << 4) >>> 0; + if (b < 16384) { + return b < 128 ? 5 : 6; + } + return b < 2097152 ? 7 : 8; + } + } + + if (lo < 16384) { + return lo < 128 ? 1 : 2; + } + if (lo < 268435456) { + return lo < 2097152 ? 3 : 4; + } + return 5; +} + +/** + * Like `measureNumber()`, but counts the one byte that a `0` takes when it is + * encoded anyway, such as an empty string's length or a packed array element. + * @param {number|bigint} number The integer to measure. + * @returns {number} The number of bytes that the encoding takes. + */ +function varintLength(number) { + return measureNumber(number) || 1; +} + +/** + * Encodes a number as a varint. Negative numbers are encoded as their two's + * complement 64-bit representation. + * @param {Buffer} buffer The buffer to write the varint to. + * @param {number} i The offset at which to write the varint. + * @param {number|bigint} number The integer to encode. + * @returns {number} The offset after the varint. + */ +function encodeNumber(buffer, i, number) { + let lo = number; + if (typeof number !== 'number' || number < 0 || number > lowMax) { + const words = long(number); + let hi = words[0]; + lo = words[1]; + while (hi) { + buffer[i++] = lo & 127 | 128; + lo = (lo >>> 7 | hi << 25) >>> 0; + hi >>>= 7; + } + } + + lo >>>= 0; + while (lo > 127) { + buffer[i++] = lo & 127 | 128; + lo >>>= 7; + } + buffer[i++] = lo; + + return i; +} + +/** + * The payload lengths of one encoding, recorded in length-prefix order while + * measuring and read back sequentially while encoding, to avoid measuring + * twice. No state is stored on the messages. + * @typedef {object} EncodeContext + * @property {number[]} lengths The payload lengths, in length-prefix order. + * @property {number} cursor The index in `lengths` of the next length to + * encode. + */ + +/** + * Creates the context of a new encoding. + * @returns {EncodeContext} A context with no recorded lengths. + */ +function newEncodeContext() { + return { lengths: [], cursor: 0 }; +} + +/** + * Waits for the next iteration of the event loop, so that a long encoding + * does not block other work. + * @returns {Promise} A promise that resolves in the check phase of the + * event loop. + */ +function yieldToEventLoop() { + return new Promise((resolve) => setImmediate(resolve)); +} + +/** + * Checks that an encoding wrote as many bytes as were measured, which fails + * only because of a bug in the encoder or a mutation of the message while it + * was being encoded. + * @param {number} end The offset at which the encoding ended. + * @param {number} length The measured length. + * @throws {Error} An `ERR_INTERNAL_ASSERTION` error if the lengths differ. + */ +function verifyEncodedLength(end, length) { + assert(end === length, `Encoded ${end} bytes but measured ${length}`); +} + +/** + * The base class of the messages. Subclasses implement `[kMeasure](context)`, + * which returns the length of the message without its tag and length, and + * `[kEncodeToBuffer](buffer, offset, context)`, which writes the message + * without its tag and length and returns the offset after it. Messages must + * not be mutated while they are being encoded. + */ +class Message { + /** + * Encodes the message. + * @returns {Buffer} The uncompressed protobuf encoding of the message. + * @throws {Error} An `ERR_INTERNAL_ASSERTION` error if the message was + * mutated while it was being encoded. + */ + encode() { + const context = newEncodeContext(); + const length = this[kMeasure](context); + const buffer = new FastBuffer(length); + verifyEncodedLength(this[kEncodeToBuffer](buffer, 0, context), length); + return buffer; + } +} + +// Field helpers take a field number. Singular fields omit default values, and +// message fields are omitted only if undefined. Repeated fields encode every +// element, defaults included, so that indices are preserved; only an empty +// array is omitted. + +/** + * Measures a varint field, which is omitted if it is `0`. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {number|bigint} number The value of the field. + * @returns {number} The number of bytes that the field takes. + */ +function measureNumberField(field, number) { + const length = measureNumber(number); + return length ? measureTag(field) + length : 0; +} + +/** + * Encodes a varint field, unless it is `0`. + * @param {Buffer} buffer The buffer to write the field to. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {number|bigint} number The value of the field. + * @returns {number} The offset after the field. + */ +function encodeNumberField(buffer, offset, field, number) { + if (!number) return offset; + offset = encodeTag(buffer, offset, field, kTypeVarInt); + return encodeNumber(buffer, offset, number); +} + +/** + * Measures a bool field, which is omitted if it is `false`. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {boolean} value The value of the field. + * @returns {number} The number of bytes that the field takes. + */ +function measureBoolField(field, value) { + return value ? measureTag(field) + 1 : 0; +} + +/** + * Encodes a bool field, unless it is `false`. + * @param {Buffer} buffer The buffer to write the field to. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {boolean} value The value of the field. + * @returns {number} The offset after the field. + */ +function encodeBoolField(buffer, offset, field, value) { + if (!value) return offset; + offset = encodeTag(buffer, offset, field, kTypeVarInt); + buffer[offset++] = 1; + return offset; +} + +/** + * Measures a packed repeated varint field, which is omitted if it is empty, + * and records its payload length in the context. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Array} values The elements of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload length is recorded in. + * @returns {number} The number of bytes that the field takes. + */ +function measurePackedNumbersField(field, values, context) { + // Packed arrays are encoded as tag, length, concatenated elements. + let total = 0; + for (let i = 0; i < values.length; i++) { + total += varintLength(values[i]); + } + if (!total) { + return 0; + } + ArrayPrototypePush(context.lengths, total); + return measureTag(field) + measureNumber(total) + total; +} + +/** + * Encodes a packed repeated varint field, unless it is empty. + * @param {Buffer} buffer The buffer to write the field to. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Array} values The elements of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload length is read from. + * @returns {number} The offset after the field. + */ +function encodePackedNumbersField(buffer, offset, field, values, context) { + if (!values.length) { + return offset; + } + offset = encodeTag(buffer, offset, field, kTypeLengthDelim); + offset = encodeNumber(buffer, offset, context.lengths[context.cursor++]); + for (let i = 0; i < values.length; i++) { + offset = encodeNumber(buffer, offset, values[i]); + } + return offset; +} + +/** + * Measures a message field, which is omitted if it is `undefined`, and + * records its payload length in the context. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Message|undefined} message The value of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the message and of its fields are recorded in. + * @returns {number} The number of bytes that the field takes. + */ +function measureMessageField(field, message, context) { + if (message === undefined) return 0; + // Reserve the parent's slot first, to match the length-prefix order. + const slot = ArrayPrototypePush(context.lengths, 0) - 1; + const length = message[kMeasure](context); + context.lengths[slot] = length; + return measureTag(field) + varintLength(length) + length; +} + +/** + * Encodes a message field, unless it is `undefined`. + * @param {Buffer} buffer The buffer to write the field to. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Message|undefined} message The value of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the message and of its fields are read from. + * @returns {number} The offset after the field. + */ +function encodeMessageField(buffer, offset, field, message, context) { + if (message === undefined) return offset; + offset = encodeTag(buffer, offset, field, kTypeLengthDelim); + offset = encodeNumber(buffer, offset, context.lengths[context.cursor++]); + return message[kEncodeToBuffer](buffer, offset, context); +} + +/** + * Measures a repeated message field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Message[]} messages The elements of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the elements are recorded in. + * @returns {number} The number of bytes that the elements take. + */ +function measureMessageArrayField(field, messages, context) { + let total = 0; + for (let i = 0; i < messages.length; i++) { + total += measureMessageField(field, messages[i], context); + } + return total; +} + +/** + * Encodes a repeated message field. + * @param {Buffer} buffer The buffer to write the field to. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number, as declared in the `.proto` file. + * @param {Message[]} messages The elements of the field. + * @param {EncodeContext} context The context of the encoding, which the + * payload lengths of the elements are read from. + * @returns {number} The offset after the elements. + */ +function encodeMessageArrayField(buffer, offset, field, messages, context) { + for (let i = 0; i < messages.length; i++) { + offset = encodeMessageField(buffer, offset, field, messages[i], context); + } + return offset; +} + +module.exports = { + Message, + encodeBoolField, + encodeMessageArrayField, + encodeMessageField, + encodeNumber, + encodeNumberField, + encodePackedNumbersField, + encodeTag, + kEncodeToBuffer, + kMeasure, + kTypeLengthDelim, + measureBoolField, + measureMessageArrayField, + measureMessageField, + measureNumber, + measureNumberField, + measurePackedNumbersField, + measureTag, + newEncodeContext, + varintLength, + verifyEncodedLength, + yieldToEventLoop, +}; diff --git a/lib/internal/perf/pprof/serializer.js b/lib/internal/perf/pprof/serializer.js new file mode 100644 index 000000000000..7157a315a0c8 --- /dev/null +++ b/lib/internal/perf/pprof/serializer.js @@ -0,0 +1,193 @@ +// Copyright 2017 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from the time profile parts +// of +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/ts/src/profile-serializer.ts +// without labels, column numbers and source maps. +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const { + ArrayPrototypeMap, + ArrayPrototypePush, + Number, + SafeMap, +} = primordials; + +const { + Line, + Location, + Profile, + ProfileFunction, + Sample, + StringTable, + ValueType, +} = require('internal/perf/pprof/profile'); +const { + frameFunctionName, + visitTimeProfile, +} = require('internal/perf/pprof/normalizer'); + +/** + * Builds a pprof `Profile` message. The normalizer does not build the profile + * itself: it walks a profile and calls methods of an object, the visitor, for + * each frame, stack and sample it finds (see `TimeProfileVisitor` in + * `internal/perf/pprof/normalizer`). This function creates a visitor whose + * methods turn each frame into a `Location` and a `ProfileFunction`, and + * each sample into a `Sample`, passes it to `visit`, and returns the + * `Profile` made of what the visitor received. + * @param {(visitor: TimeProfileVisitor) => void} visit Called once with the + * visitor, and must deliver a normalized profile to it, such as by calling + * `visitTimeProfile()` with it. + * @returns {Profile} The profile, ready to be encoded. + */ +function serialize(visit) { + const stringTable = new StringTable(); + const samples = []; + const locations = []; + const stacks = []; + const functions = []; + const functionIds = new SafeMap(); + let data = { __proto__: null }; + + /** + * Creates a pprof ValueType, interning its type and unit. + * @param {{ type: string, unit: string }} type The names of the type and + * of the unit, such as `wall` and `nanoseconds`. + * @returns {ValueType} The ValueType, which refers to the names by index + * in the string table. + */ + function valueType(type) { + return new ValueType({ + type: stringTable.dedup(type.type), + unit: stringTable.dedup(type.unit), + }); + } + + /** + * Returns the pprof Function of a frame, creating it the first time. + * @param {object} frame A frame delivered by the normalizer. + * @returns {ProfileFunction} The Function, which the profile holds. + */ + function getFunction(frame) { + // A function is identified by script, file and name, or by script, file + // and position for anonymous functions. The prefixes keep the two kinds + // apart, and the file's length makes the key unambiguous. + const file = frame.file; + const key = frame.name ? + `n:${frame.scriptId}:${file.length}:${file}:${frame.name}` : + `a:${frame.scriptId}:${frame.line}:${frame.column}:${file}`; + let id = functionIds.get(key); + if (id !== undefined) { + return functions[id - 1]; + } + // IDs are indices + 1, since 0 is not a valid ID. + id = functions.length + 1; + functionIds.set(key, id); + const nameId = stringTable.dedup(frameFunctionName(frame)); + const fn = new ProfileFunction({ + id, + name: nameId, + systemName: nameId, + filename: stringTable.dedup(file), + }); + ArrayPrototypePush(functions, fn); + return fn; + } + + visit({ + /** + * Records the profile's sample types, times and period. + * @param {object} metadata The metadata delivered by the normalizer: the + * `sampleTypes`, `startTimeNanos`, `durationNanos`, `periodType` and + * `period` of the profile. + */ + metadata(metadata) { + data = { + __proto__: null, + sampleType: ArrayPrototypeMap(metadata.sampleTypes, valueType), + // pprof Profile objects have always had a number here, which rounds + // the time to a double. + timeNanos: Number(metadata.startTimeNanos), + durationNanos: metadata.durationNanos, + periodType: valueType(metadata.periodType), + period: metadata.period, + }; + }, + /** + * Creates the pprof Location of a frame. + * @param {object} frame A frame delivered by the normalizer, with its + * `name`, `file`, `line`, `column` and `scriptId`. + * @returns {number} The ID of the Location. + */ + frame(frame) { + // IDs are indices + 1, since 0 is not a valid ID. + const id = locations.length + 1; + const line = new Line({ + functionId: getFunction(frame).id, + line: frame.line, + }); + ArrayPrototypePush(locations, new Location({ id, line: [line] })); + return id; + }, + /** + * Records a stack. + * @param {number[]} frameIds The Location IDs of the stack, leaf first. + * @returns {number} The index of the stack. + */ + stack(frameIds) { + return ArrayPrototypePush(stacks, frameIds) - 1; + }, + /** + * Creates a pprof Sample. + * @param {{ stackId: number, values: number[] }} sample A sample delivered + * by the normalizer: the index of its stack, as returned by `stack()`, + * and one value per sample type. + */ + sample(sample) { + ArrayPrototypePush(samples, new Sample({ + locationId: stacks[sample.stackId], + value: sample.values, + })); + }, + }); + + data.sample = samples; + data.location = locations; + data.function = functions; + data.stringTable = stringTable; + return new Profile(data); +} + +/** + * Converts a time profile produced by the pprof binding into a pprof Profile. + * @param {object} profile The flat node table that the pprof binding's `stop()` + * returns. + * @param {number} intervalMicros The requested average time between samples. + * @param {boolean} [recomputeSamplingInterval] Whether to replace the + * requested interval with the average interval between samples. + * @returns {Profile} The profile, ready to be encoded. + */ +function serializeTimeProfile(profile, intervalMicros, + recomputeSamplingInterval = false) { + const options = { intervalMicros, recomputeSamplingInterval }; + return serialize((visitor) => visitTimeProfile(profile, visitor, options)); +} + +module.exports = { + serializeTimeProfile, +}; diff --git a/lib/internal/perf/pprof/string_table.js b/lib/internal/perf/pprof/string_table.js new file mode 100644 index 000000000000..5f86108785f1 --- /dev/null +++ b/lib/internal/perf/pprof/string_table.js @@ -0,0 +1,104 @@ +// Copyright 2022 Datadog, Inc. +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). +// +// Modified for inclusion in Node.js core: ported from the encoding half of +// https://github.com/DataDog/pprof-format/blob/53548398f38b16eb096cc04a75927316a68a9b54/src/string-table.ts +// +// SPDX-License-Identifier: MIT + +'use strict'; + +const { + ArrayPrototypePush, + SafeMap, +} = primordials; + +const { Buffer } = require('buffer'); +const { utf8Write } = require('internal/buffer'); +const { + encodeNumber, + encodeTag, + kEncodeToBuffer, + kMeasure, + kTypeLengthDelim, + measureTag, + varintLength, +} = require('internal/perf/pprof/protobuf'); + +/** + * The strings of a profile, such as function names, file names and the names + * of sample types. Each distinct string is stored once, and the other + * messages of the profile refer to strings by their index in the table, so + * that a file name shared by many functions is encoded once. The first + * string is always the empty string, so that index 0 means no string. The + * UTF-8 bytes of a string are written straight into the output when the + * table is encoded, so adding a string allocates no buffer. + */ +class StringTable { + strings = []; + #byteLengths = []; + #positions = new SafeMap(); + #encodedLength = 0; + + /** + * Creates a string table that holds the empty string. + */ + constructor() { + // The first string of a pprof string table is always the empty string. + this.dedup(''); + } + + /** + * Returns the index of a string, adding it to the table if needed. + * @param {string} value The string to look up. + * @returns {number} The index of the string in the table. + */ + dedup(value) { + let position = this.#positions.get(value); + if (position === undefined) { + const byteLength = Buffer.byteLength(value, 'utf8'); + position = ArrayPrototypePush(this.strings, value) - 1; + this.#positions.set(value, position); + ArrayPrototypePush(this.#byteLengths, byteLength); + this.#encodedLength += varintLength(byteLength) + byteLength; + } + return position; + } + + /** + * Measures the strings as the repeated string field `field`. + * @param {number} field The field number of the string table, as declared + * in the `.proto` file. + * @returns {number} The number of bytes that the field takes. + */ + [kMeasure](field) { + return this.#byteLengths.length * measureTag(field) + this.#encodedLength; + } + + /** + * Encodes the strings as the repeated string field `field`. + * @param {Buffer} buffer The buffer to write the field to, which is at least + * as large as measured. + * @param {number} offset The offset at which to write the field. + * @param {number} field The field number of the string table, as declared + * in the `.proto` file. + * @returns {number} The offset after the field. + */ + [kEncodeToBuffer](buffer, offset, field) { + for (let i = 0; i < this.#byteLengths.length; i++) { + const byteLength = this.#byteLengths[i]; + offset = encodeTag(buffer, offset, field, kTypeLengthDelim); + offset = encodeNumber(buffer, offset, byteLength); + if (byteLength > 0) { + utf8Write(buffer, this.strings[i], offset, byteLength); + } + offset += byteLength; + } + return offset; + } +} + +module.exports = { + StringTable, +}; diff --git a/lib/internal/perf/pprof/time_profiler.js b/lib/internal/perf/pprof/time_profiler.js new file mode 100644 index 000000000000..bd58646b0701 --- /dev/null +++ b/lib/internal/perf/pprof/time_profiler.js @@ -0,0 +1,343 @@ +// Copyright 2017 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/ts/src/time-profiler.ts +// without sampling contexts, source maps and labels. +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const { + ObjectFreeze, +} = primordials; + +const { + WallProfiler, + signalSamplingSupported, +} = internalBinding('pprof'); +const { + codes: { + ERR_FEATURE_UNAVAILABLE_ON_PLATFORM, + ERR_INCOMPATIBLE_OPTION_PAIR, + ERR_INVALID_STATE, + ERR_OUT_OF_RANGE, + }, +} = require('internal/errors'); +const { kEmptyObject } = require('internal/util'); +const { + validateAbortSignal, + validateBoolean, + validateInteger, + validateObject, +} = require('internal/validators'); +const { + throwIfBuildingSnapshot, +} = require('internal/v8/startup_snapshot'); +const { + GARBAGE_COLLECTION_FUNCTION_NAME, + NON_JS_THREADS_FUNCTION_NAME, +} = require('internal/perf/pprof/normalizer'); +const { + serializeTimeProfile, +} = require('internal/perf/pprof/serializer'); + +const kMaxInt32 = 2 ** 31 - 1; +const kDefaultIntervalMicros = 1000; +const kDefaultDurationMillis = 60000; + +// The state of the profiler of this thread. +let profiler; +let profilerIntervalMicros; +let stuckEventLoopDetected = 0; + +/** + * Validates the options of `start()`, and fills in their defaults. + * @param {object} options The options passed to `start()`. + * @param {number} [options.intervalMicros] The average time between samples, + * in microseconds. + * @param {number} [options.durationMillis] The expected time between calls + * to `stop()`, in milliseconds, used to size buffers upfront. + * @param {boolean} [options.lineNumbers] Whether to aggregate samples by line + * rather than by function. + * @param {boolean} [options.collectCpuTime] Whether to attribute the thread's + * CPU time to samples. + * @param {boolean} [options.workaroundV8Bug] Whether to work around the V8 + * bug that can leave the profiler stuck when it is restarted. + * @returns {{ + * intervalMicros: number, + * durationMillis: number, + * lineNumbers: boolean, + * collectCpuTime: boolean, + * workaroundV8Bug: boolean, + * }} The options, with the defaults of those that were not set. + * @throws {TypeError} An `ERR_INVALID_ARG_TYPE` error if `options` or one of its + * properties has the wrong type. + * @throws {RangeError} An `ERR_OUT_OF_RANGE` error if `intervalMicros` or + * `durationMillis` is out of range, or if `durationMillis` is shorter than + * `intervalMicros`. + * @throws {TypeError} An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` error if + * `collectCpuTime` is enabled on Windows. + * @throws {TypeError} An `ERR_INCOMPATIBLE_OPTION_PAIR` error if + * `collectCpuTime` and `lineNumbers` are both enabled. + */ +function validateOptions(options) { + validateObject(options, 'options'); + const { + intervalMicros = kDefaultIntervalMicros, + durationMillis = kDefaultDurationMillis, + lineNumbers = false, + collectCpuTime = false, + workaroundV8Bug = true, + } = options; + validateInteger(intervalMicros, 'options.intervalMicros', 1, kMaxInt32); + validateInteger(durationMillis, 'options.durationMillis', 1, kMaxInt32); + if (durationMillis * 1000 < intervalMicros) { + throw new ERR_OUT_OF_RANGE( + 'options.durationMillis', + `>= options.intervalMicros / 1000 (${intervalMicros / 1000})`, + durationMillis); + } + validateBoolean(lineNumbers, 'options.lineNumbers'); + validateBoolean(collectCpuTime, 'options.collectCpuTime'); + validateBoolean(workaroundV8Bug, 'options.workaroundV8Bug'); + if (collectCpuTime && !signalSamplingSupported) { + throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('options.collectCpuTime'); + } + if (collectCpuTime && lineNumbers) { + throw new ERR_INCOMPATIBLE_OPTION_PAIR('collectCpuTime', 'lineNumbers'); + } + return { + intervalMicros, + durationMillis, + lineNumbers, + collectCpuTime, + workaroundV8Bug, + }; +} + +/** + * Checks that the profiler of this thread is started, before it is used. + * @throws {Error} An `ERR_INVALID_STATE` error if the profiler of this thread + * is not started. + */ +function assertStarted() { + if (profiler === undefined) { + throw new ERR_INVALID_STATE('The time profiler is not started'); + } +} + +/** + * Updates the state of the profiler after it was stopped and restarted. + * + * Works around a V8 bug where the profiler's event processor thread gets + * stuck in a loop eating 100% CPU, which leads to empty profiles: when the + * restart found V8's CPU profiler stuck, the profiler is stopped, which + * disposes of V8's CPU profiler, and started again with a new one. If that + * start fails, the profiler is torn down, as when the profiler fails to + * restart in the first place: the profile that was stopped is still valid, + * and is returned rather than lost. + */ +function handleStopRestart() { + stuckEventLoopDetected = profiler.v8ProfilerStuckEventLoopDetected(); + if (stuckEventLoopDetected > 0) { + profiler.stop(false); + try { + profiler.start(); + } catch { + handleStopNoRestart(); + } + } +} + +/** + * Tears down the profiler of this thread after it was stopped without being + * restarted. + */ +function handleStopNoRestart() { + stuckEventLoopDetected = 0; + profiler.dispose(); + profiler = undefined; +} + +/** + * Starts profiling the current thread. + * @param {object} [options] Tuning parameters for the profiler. + * @param {number} [options.intervalMicros] The average time between samples, + * in microseconds. + * @param {number} [options.durationMillis] The expected time between calls + * to `stop()`, in milliseconds, used to size buffers upfront. + * @param {boolean} [options.lineNumbers] Whether to aggregate samples by line + * rather than by function. + * @param {boolean} [options.collectCpuTime] Whether to attribute the thread's + * CPU time to samples. + * @param {boolean} [options.workaroundV8Bug] Whether to work around the V8 + * bug that can leave the profiler stuck when it is restarted. + * @throws {TypeError} An `ERR_INVALID_ARG_TYPE` error if `options` or one of its + * properties has the wrong type. + * @throws {RangeError} An `ERR_OUT_OF_RANGE` error if `intervalMicros` or + * `durationMillis` is out of range, or if `durationMillis` is shorter than + * `intervalMicros`. + * @throws {TypeError} An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` error if + * `collectCpuTime` is enabled on Windows. + * @throws {TypeError} An `ERR_INCOMPATIBLE_OPTION_PAIR` error if + * `collectCpuTime` and `lineNumbers` are both enabled. + * @throws {Error} An `ERR_INVALID_STATE` error if the profiler of this thread + * is already started, or if the `SIGPROF` signal handler cannot be + * installed. + * @throws {Error} An `ERR_NOT_SUPPORTED_IN_SNAPSHOT` error if a startup + * snapshot is being built. + * @throws {Error} An `ERR_CPU_PROFILE_TOO_MANY` error if V8 has too many CPU + * profiles running. + */ +function start(options = kEmptyObject) { + const { + intervalMicros, + durationMillis, + lineNumbers, + collectCpuTime, + workaroundV8Bug, + } = validateOptions(options); + if (profiler !== undefined) { + throw new ERR_INVALID_STATE('The time profiler is already started'); + } + throwIfBuildingSnapshot('Starting the pprof time profiler'); + + const newProfiler = new WallProfiler(intervalMicros, + durationMillis, + lineNumbers, + workaroundV8Bug, + collectCpuTime); + newProfiler.start(); + profiler = newProfiler; + profilerIntervalMicros = intervalMicros; + stuckEventLoopDetected = 0; +} + +/** + * Stops the current profile, and returns it. + * @param {boolean} [restart] Whether to start a new profile immediately, with + * the same options. + * @returns {Profile} The profile that was stopped. + * @throws {TypeError} An `ERR_INVALID_ARG_TYPE` error if `restart` is not a + * boolean. + * @throws {Error} An `ERR_INVALID_STATE` error if the profiler of this thread + * is not started. + */ +function stop(restart = false) { + validateBoolean(restart, 'restart'); + assertStarted(); + + const profile = profiler.stop(restart); + if (profile.restarted) { + // The next profile already started: process this one after restarting + // the profiler, so that the cost of processing it is captured in the next + // profile. + handleStopRestart(); + return serializeTimeProfile(profile, profilerIntervalMicros, true); + } + + try { + return serializeTimeProfile(profile, profilerIntervalMicros, true); + } finally { + // The native profiler has already stopped, so tear down even if + // processing throws. + handleStopNoRestart(); + } +} + +/** + * Profiles the current thread for `options.durationMillis` milliseconds. + * @param {object} [options] Tuning parameters for the profiler, as for + * `start()`, and the signal that stops it early. + * @param {number} [options.intervalMicros] The average time between samples, + * in microseconds. + * @param {number} [options.durationMillis] The expected time between calls + * to `stop()`, in milliseconds, used to size buffers upfront. + * @param {boolean} [options.lineNumbers] Whether to aggregate samples by line + * rather than by function. + * @param {boolean} [options.collectCpuTime] Whether to attribute the thread's + * CPU time to samples. + * @param {boolean} [options.workaroundV8Bug] Whether to work around the V8 + * bug that can leave the profiler stuck when it is restarted. + * @param {AbortSignal} [options.signal] Stops profiling, and rejects the + * returned promise, when aborted. + * @returns {Promise} The profile, once `options.durationMillis` has + * elapsed. + * @throws {Error} Rejects with the errors that `start()` throws, with an + * `ERR_INVALID_ARG_TYPE` error if `options.signal` is not an `AbortSignal`, + * and with an `AbortError` if `options.signal` is aborted. + */ +async function profile(options = kEmptyObject) { + validateObject(options, 'options'); + const { signal } = options; + if (signal !== undefined) { + validateAbortSignal(signal, 'options.signal'); + } + start(options); + const profilerOfThisCall = profiler; + const { durationMillis = kDefaultDurationMillis } = options; + try { + const { setTimeout } = require('timers/promises'); + await setTimeout(durationMillis, undefined, { signal }); + } catch (err) { + if (profiler === profilerOfThisCall) { + stop(false); + } + throw err; + } + return stop(false); +} + +/** + * Returns whether the profiler of this thread is started. + * @returns {boolean} `true` if the profiler is started, `false` otherwise. + */ +function isStarted() { + return profiler !== undefined; +} + +/** + * Returns whether the latest restart of the profiler found V8's CPU profiler + * stuck. + * @returns {number} 0 if no issue was detected, 1 if one possibly was, or 2 + * if one certainly was. It is reset to 0 when the profiler is started, or + * stopped without being restarted. + */ +function v8ProfilerStuckEventLoopDetected() { + return stuckEventLoopDetected; +} + +/** + * The names of the synthetic frames that the time profiler reports, exposed + * as `pprof.time.constants`. + * @type {{ + * GARBAGE_COLLECTION_FUNCTION_NAME: string, + * NON_JS_THREADS_FUNCTION_NAME: string, + * }} + */ +const constants = ObjectFreeze({ + GARBAGE_COLLECTION_FUNCTION_NAME, + NON_JS_THREADS_FUNCTION_NAME, +}); + +module.exports = { + constants, + isStarted, + profile, + start, + stop, + v8ProfilerStuckEventLoopDetected, +}; diff --git a/lib/perf_hooks/pprof.js b/lib/perf_hooks/pprof.js new file mode 100644 index 000000000000..bc1d5964e0e5 --- /dev/null +++ b/lib/perf_hooks/pprof.js @@ -0,0 +1,39 @@ +'use strict'; + +// Public entry point for the pprof profiler. +// Usage: require('perf_hooks/pprof') or require('node:perf_hooks/pprof') + +const { + ObjectFreeze, +} = primordials; + +const { emitExperimentalWarning } = require('internal/util'); +emitExperimentalWarning('perf_hooks/pprof'); + +const { + constants, + isStarted, + profile, + start, + stop, + v8ProfilerStuckEventLoopDetected, +} = require('internal/perf/pprof/time_profiler'); +const { + encode, + encodeSync, +} = require('internal/perf/pprof/encoder'); + +const time = ObjectFreeze({ + constants, + isStarted, + profile, + start, + stop, + v8ProfilerStuckEventLoopDetected, +}); + +module.exports = { + encode, + encodeSync, + time, +}; diff --git a/node.gyp b/node.gyp index 8dc598dc4022..ac5cc8dd86b1 100644 --- a/node.gyp +++ b/node.gyp @@ -157,6 +157,7 @@ 'src/node_platform.cc', 'src/node_profiling.cc', 'src/node_postmortem_metadata.cc', + 'src/node_pprof.cc', 'src/node_process_events.cc', 'src/node_process_methods.cc', 'src/node_process_object.cc', @@ -189,6 +190,9 @@ 'src/permission/env_permission.cc', 'src/permission/fs_permission.cc', 'src/permission/permission.cc', + 'src/pprof/cpu_clock.cc', + 'src/pprof/sigprof_handler.cc', + 'src/pprof/time_profile.cc', 'src/pipe_wrap.cc', 'src/process_wrap.cc', 'src/signal_wrap.cc', @@ -297,6 +301,7 @@ 'src/node_perf_common.h', 'src/node_platform.h', 'src/node_profiling.h', + 'src/node_pprof.h', 'src/node_process.h', 'src/node_process-inl.h', 'src/node_realm.h', @@ -326,6 +331,9 @@ 'src/permission/fs_permission.h', 'src/permission/permission.h', 'src/permission/permission_base.h', + 'src/pprof/cpu_clock.h', + 'src/pprof/sigprof_handler.h', + 'src/pprof/time_profile.h', 'src/pipe_wrap.h', 'src/req_wrap.h', 'src/req_wrap-inl.h', diff --git a/src/node_binding.cc b/src/node_binding.cc index b8a1a6f64c47..616939f90eed 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc @@ -88,6 +88,7 @@ V(performance) \ V(permission) \ V(pipe_wrap) \ + V(pprof) \ V(process_wrap) \ V(process_methods) \ V(report) \ diff --git a/src/node_external_reference.h b/src/node_external_reference.h index abdf6a36cbcb..896fc5c5877e 100644 --- a/src/node_external_reference.h +++ b/src/node_external_reference.h @@ -92,6 +92,7 @@ class ExternalReferenceRegistry { V(os) \ V(performance) \ V(permission) \ + V(pprof) \ V(process_methods) \ V(process_object) \ V(process_wrap) \ diff --git a/src/node_pprof.cc b/src/node_pprof.cc new file mode 100644 index 000000000000..b18864e5ab1a --- /dev/null +++ b/src/node_pprof.cc @@ -0,0 +1,818 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.cc +// and +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/translate-time-profile.cc +// (Copyright 2018 Google Inc.), without sampling contexts, CPED and async ID +// support. Profiles are returned as flat tables of nodes rather than as trees +// of objects. +// +// SPDX-License-Identifier: Apache-2.0 + +#include "node_pprof.h" +#include "env-inl.h" +#include "memory_tracker-inl.h" +#include "node_errors.h" +#include "node_external_reference.h" +#include "util-inl.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +namespace node { +namespace pprof { + +using v8::ArrayBuffer; +using v8::Boolean; +using v8::Context; +using v8::CpuProfile; +using v8::CpuProfileNode; +using v8::CpuProfiler; +using v8::CpuProfilingMode; +using v8::CpuProfilingResult; +using v8::CpuProfilingStatus; +using v8::Float64Array; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::Int32Array; +using v8::Isolate; +using v8::Local; +using v8::LocalVector; +using v8::MaybeLocal; +using v8::Number; +using v8::Object; +using v8::ProfilerId; +using v8::String; +using v8::Uint32Array; +using v8::Undefined; +using v8::Value; + +namespace { + +// Upper bound of the number of SampleRecords buffered per profile. +constexpr size_t kMaxSampleRecords = 1 << 22; + +// The profiler running on the current thread, if any. There is at most one +// per thread, even when several Environments share it, since V8 delivers its +// sampling signals to threads, and samples are attributed through a single +// per-thread signal sink. +// NOLINTNEXTLINE(runtime/thread_local) +thread_local WallProfiler* thread_profiler = nullptr; + +// Registry of the profilers running on all threads. Profilers publish the CPU +// time consumed by their thread through it, so that the main thread's profiler +// can compute the CPU time consumed by threads that do not run JavaScript. +class ActiveProfilers { + public: + void Add(WallProfiler* profiler) { + std::lock_guard lock(mutex_); + profilers_.insert(profiler); + } + + void Remove(WallProfiler* profiler) { + std::lock_guard lock(mutex_); + auto it = profilers_.find(profiler); + if (it == profilers_.end()) return; + terminated_threads_cpu_time_ += profiler->GetAndResetThreadCpu(); + profilers_.erase(it); + } + + int64_t GatherTotalThreadCpuAndReset() { + std::lock_guard lock(mutex_); + int64_t total = terminated_threads_cpu_time_; + terminated_threads_cpu_time_ = 0; + for (WallProfiler* profiler : profilers_) { + total += profiler->GetAndResetThreadCpu(); + } + return total; + } + + private: + std::mutex mutex_; + std::unordered_set profilers_; + int64_t terminated_threads_cpu_time_ = 0; +}; + +// Never destroyed, since worker threads may still use it while the process +// exits. +ActiveProfilers& GetActiveProfilers() { + static ActiveProfilers* profilers = new ActiveProfilers(); + return *profilers; +} + +// Returns the total hit count of the profile, and whether it has a leaf node +// without hits. +int GetTotalHitCount(const CpuProfileNode* root, bool* no_hit_leaf) { + int total = 0; + std::vector stack{root}; + while (!stack.empty()) { + const CpuProfileNode* node = stack.back(); + stack.pop_back(); + int hit_count = node->GetHitCount(); + int child_count = node->GetChildrenCount(); + total += hit_count; + if (child_count == 0 && hit_count == 0) *no_hit_leaf = true; + for (int i = 0; i < child_count; i++) stack.push_back(node->GetChild(i)); + } + return total; +} + +// Returns 0 if no bug was detected, 1 if one possibly was (which may be a +// false positive), or 2 if one certainly was. +// +// When the profiler works correctly, at least one node has hits, and there +// are strictly more samples than hits, because of the sample taken when +// profiling starts and possibly some deoptimization samples. Otherwise, +// v8::SamplingEventsProcessor::ProcessOneSample() is stuck on ticks_buffer_ or +// vm_ticks_buffer_. +int DetectV8Bug(const CpuProfile* profile) { + bool no_hit_leaf = false; + int total_hit_count = + GetTotalHitCount(profile->GetTopDownRoot(), &no_hit_leaf); + if (total_hit_count == 0) return 2; + // Tick samples older than the start of the profile can be discarded because + // of queueing, which can make the sample count equal to the hit count even + // though the profiler works. A leaf without hits means that a non-tick + // sample was processed. + if (profile->GetSamplesCount() == total_hit_count && !no_hit_leaf) return 1; + return 0; +} + +#ifndef _WIN32 +// Returns the offset to add to a V8 timer value to get microseconds since the +// Unix epoch. Makes at most kMaxAttempts attempts to read the system clock +// within a single V8 timer microsecond, and keeps the one with the smallest +// error. This is redone for every profile, since the difference between the +// clocks can drift. +int64_t GetV8ToEpochOffset() { + constexpr int kMaxAttempts = 20; + int64_t offset = 0; + int64_t smallest_diff = std::numeric_limits::max(); + for (int i = 0; i < kMaxAttempts; i++) { + int64_t v8_now = MonotonicNowMicros(); + int64_t epoch_now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + int64_t v8_now2 = MonotonicNowMicros(); + int64_t diff = v8_now2 - v8_now; + if (diff < smallest_diff) { + offset = epoch_now - Midpoint(v8_now, v8_now2); + if (diff == 0) break; + smallest_diff = diff; + } + } + return offset; +} + +// Spins until the V8 timer moves on, so that samples taken from now on cannot +// have the same timestamp as those taken before. +void WaitForTimerTick() { + int64_t now = MonotonicNowMicros(); + while (MonotonicNowMicros() == now) { + } +} +#endif // _WIN32 + +template +Local NewTypedArray(Isolate* isolate, const std::vector& values) { + Local buffer = + ArrayBuffer::New(isolate, values.size() * sizeof(T)); + if (!values.empty()) { + memcpy(buffer->Data(), values.data(), values.size() * sizeof(T)); + } + return Array::New(buffer, 0, values.size()); +} + +} // namespace + +WallProfiler::WallProfiler(Environment* env, + Local object, + const Options& options) + : BaseObject(env, object), + options_(options), + is_main_thread_(env->is_main_thread()) { + MakeWeak(); + if (options_.collect_cpu_time) { + // Records are taken once per sample, i.e. about duration / interval times + // per profile. Leave room for twice as many. + size_t capacity = static_cast(options_.duration_ms) * 1000 * 2 / + options_.sampling_interval_us; + records_.reserve( + std::min(std::max(capacity, 1), kMaxSampleRecords)); + } +} + +WallProfiler::~WallProfiler() { + DisposeProfiler(); +} + +void WallProfiler::MemoryInfo(MemoryTracker* tracker) const { + tracker->TrackFieldWithSize("records", + records_.capacity() * sizeof(SampleRecord)); +} + +bool WallProfiler::InterceptSignal() const { +#ifdef _WIN32 + return false; +#else + return options_.workaround_v8_bug || options_.collect_cpu_time; +#endif +} + +void WallProfiler::SetCollectionMode(CollectionMode mode) { + std::atomic_signal_fence(std::memory_order_release); + collection_mode_.store(mode, std::memory_order_relaxed); +} + +#ifndef _WIN32 +void WallProfiler::OnProfilerSignal(int sig, siginfo_t* info, void* context) { + CollectionMode mode = collection_mode_.load(std::memory_order_relaxed); + std::atomic_signal_fence(std::memory_order_acquire); + switch (mode) { + case CollectionMode::kNoCollect: + // Drop the sample, and let WaitForSignal() know that a signal arrived. + no_collect_call_count_.fetch_add(1, std::memory_order_relaxed); + return; + case CollectionMode::kPassThrough: + SignalHandler::ForwardSignal(sig, info, context); + return; + case CollectionMode::kCollect: + break; + } + + int64_t cpu_time = CurrentThreadCpuNanos(); + int64_t time_from = MonotonicNowMicros(); + SignalHandler::ForwardSignal(sig, info, context); + int64_t time_to = MonotonicNowMicros(); + // The capacity was reserved upfront, so this never allocates. + if (records_.size() < records_.capacity()) { + records_.push_back({time_from, time_to, cpu_time}); + } +} +#endif // _WIN32 + +bool WallProfiler::WaitForSignal(uint64_t target_call_count) { + uint64_t call_count = no_collect_call_count_.load(std::memory_order_relaxed); + std::atomic_signal_fence(std::memory_order_acquire); + if (target_call_count != 0) { + if (call_count >= target_call_count) return true; + } else { + target_call_count = call_count + 1; + } +#ifndef _WIN32 + // Wait for at most two sampling intervals. Unlike uv_sleep(), nanosleep() + // returns as soon as a signal interrupts it. + constexpr int64_t kNanosPerSecond = 1000 * 1000 * 1000; + int64_t nanos = int64_t{options_.sampling_interval_us} * 2 * 1000; + timespec ts; + ts.tv_sec = static_cast(nanos / kNanosPerSecond); + ts.tv_nsec = + static_cast(nanos % kNanosPerSecond); // NOLINT(runtime/int) + nanosleep(&ts, nullptr); +#endif // _WIN32 + call_count = no_collect_call_count_.load(std::memory_order_relaxed); + std::atomic_signal_fence(std::memory_order_acquire); + return call_count >= target_call_count; +} + +WallProfiler::StartStatus WallProfiler::StartInternal() { + Isolate* isolate = env()->isolate(); + // The strings used as profile titles are only released when the + // v8::CpuProfiler is disposed, so alternate between two of them. + Local title = (profile_index_++ % 2 == 0) + ? FIXED_ONE_BYTE_STRING(isolate, "pprof-0") + : FIXED_ONE_BYTE_STRING(isolate, "pprof-1"); + // Always record samples, to be able to tell whether non-tick samples (the + // starting sample and deoptimization samples) were processed, and therefore + // whether SamplingEventsProcessor::ProcessOneSample() is stuck on + // vm_ticks_buffer_. + CpuProfilingResult result = cpu_profiler_->Start( + title, + options_.line_numbers ? CpuProfilingMode::kCallerLineNumbers + : CpuProfilingMode::kLeafNodeLineNumbers, + /* record_samples */ true); + if (result.status == CpuProfilingStatus::kErrorTooManyProfilers) { + return StartStatus::kTooManyProfiles; + } + profile_id_ = result.id; + +#ifndef _WIN32 + // V8 installs its SIGPROF handler when it starts sampling, so ours goes in + // front of it, and is (re)installed for every profile. + if (InterceptSignal()) { + if (!SignalHandler::IncreaseUseCount()) { + return StartStatus::kSignalHandlerFailed; + } + signal_handler_uses_++; + } +#endif // _WIN32 + + if (options_.collect_cpu_time) { + start_thread_cpu_time_ = CurrentThreadCpuNanos(); + start_process_cpu_time_ = ProcessCpuNanos(); + } + + // Collect two more non-tick samples, which do not add to the hit count, so + // that DetectV8Bug() can tell when V8's event processor is stuck on + // ticks_from_vm_buffer_. A non-tick sample is already taken when profiling + // starts, but the first tick sample can be discarded if its timestamp + // predates the start of the profile because of queueing, while it still + // adds to the hit count. This is not needed with the workaround, which waits + // for a signal before starting a new profile, leaving time to process + // in-flight tick samples. + if (!options_.workaround_v8_bug) { + CpuProfiler::CollectSample(isolate); + CpuProfiler::CollectSample(isolate); + } + return StartStatus::kOk; +} + +MaybeLocal WallProfiler::StopImpl(bool restart) { + CHECK(started_); + uint64_t call_count = 0; + ProfilerId old_profile_id = profile_id_; + +#ifndef _WIN32 + if (restart && options_.workaround_v8_bug) { + SetCollectionMode(CollectionMode::kNoCollect); + WaitForSignal(); + } else if (options_.collect_cpu_time) { + SetCollectionMode(CollectionMode::kNoCollect); + // Make sure that the timer moves on, so that no sample of the next profile + // is matched with a record of this one. + WaitForTimerTick(); + } +#endif // _WIN32 + + int64_t start_thread_cpu_time = start_thread_cpu_time_; + int64_t start_process_cpu_time = start_process_cpu_time_; + + bool restarted = false; + if (restart) { + // Start the next profile before stopping this one, so that no sample is + // missed in between. This cannot fail in practice: the profiler only ever + // runs two profiles, and the signal handler is already installed. + restarted = StartInternal() == StartStatus::kOk; + call_count = no_collect_call_count_.load(std::memory_order_relaxed); + std::atomic_signal_fence(std::memory_order_acquire); + } + +#ifndef _WIN32 + // Release the use of the signal handler taken for the profile being stopped. + if (InterceptSignal() && signal_handler_uses_ > 0) { + SignalHandler::DecreaseUseCount(); + signal_handler_uses_--; + } +#endif // _WIN32 + + CpuProfile* profile = cpu_profiler_->Stop(old_profile_id); + + std::vector records; + if (options_.collect_cpu_time) { + records.reserve(records_.capacity()); + std::swap(records, records_); + } + + v8_profiler_stuck_event_loop_detected_ = + profile != nullptr ? DetectV8Bug(profile) : 2; + +#ifndef _WIN32 + if (restarted && options_.collect_cpu_time && !options_.workaround_v8_bug) { + // Make sure that the starting sample of the next profile is not mixed up + // with a sample taken from the signal handler. With the workaround, + // collection resumes at the end instead. + WaitForTimerTick(); + SetCollectionMode(CollectionMode::kCollect); + } +#endif // _WIN32 + + MaybeLocal result; + if (profile != nullptr) { + int64_t non_js_threads_cpu_time = 0; + AttributionByNode attribution; + if (options_.collect_cpu_time) { + if (is_main_thread_) { + // The CPU time of the threads that do not run JavaScript is the + // process CPU time minus that of all the threads that do, during the + // profile of the main thread. It is only accounted for there. + int64_t threads_cpu_time = + GetActiveProfilers().GatherTotalThreadCpuAndReset(); + int64_t process_cpu_time = ProcessCpuNanos() - start_process_cpu_time; + non_js_threads_cpu_time = + std::max(process_cpu_time - threads_cpu_time, 0); + } + std::vector samples; + int sample_count = profile->GetSamplesCount(); + samples.reserve(sample_count); + for (int i = 0; i < sample_count; i++) { + const CpuProfileNode* node = profile->GetSample(i); + samples.push_back( + {profile->GetSampleTimestamp(i), + node, + strcmp(node->GetFunctionNameStr(), "(program)") == 0}); + } + attribution = AttributeSamples(samples, records, start_thread_cpu_time); + } + +#ifdef _WIN32 + int64_t v8_to_epoch_offset = 0; +#else + // One offset for the profile, so that its start and end times and its + // samples' timestamps agree. + int64_t v8_to_epoch_offset = GetV8ToEpochOffset(); +#endif // _WIN32 + result = + TranslateProfile(profile, + options_.collect_cpu_time ? &attribution : nullptr, + non_js_threads_cpu_time, + v8_to_epoch_offset, + restarted); + profile->Delete(); + } + + if (!restarted) { + DisposeProfiler(); + } else if (options_.workaround_v8_bug) { + WaitForSignal(call_count + 1); + SetCollectionMode(options_.collect_cpu_time ? CollectionMode::kCollect + : CollectionMode::kPassThrough); + } + + return result; +} + +MaybeLocal WallProfiler::TranslateProfile( + const CpuProfile* profile, + const AttributionByNode* attribution, + int64_t non_js_threads_cpu_time, + int64_t v8_to_epoch_offset, + bool restarted) { + Environment* env = this->env(); + Isolate* isolate = env->isolate(); + Local context = env->context(); + + // The nodes of the profile tree, in pre-order, root first. Every node comes + // after its parent. + std::vector parents; + std::vector script_ids; + std::vector line_numbers; + std::vector column_numbers; + std::vector hit_counts; + std::vector cpu_times; + LocalVector names(isolate); + LocalVector script_names(isolate); + double total_hit_count = 0; + + // `metadata` is the V8 node that the row describes the function of. + auto add_row = [&](int32_t parent, + const CpuProfileNode* metadata, + int line_number, + int column_number, + uint32_t hit_count, + int64_t cpu_time) { + parents.push_back(parent); + names.push_back(metadata->GetFunctionName()); + script_names.push_back(metadata->GetScriptResourceName()); + script_ids.push_back(metadata->GetScriptId()); + line_numbers.push_back(line_number); + column_numbers.push_back(column_number); + hit_counts.push_back(hit_count); + if (attribution != nullptr) { + cpu_times.push_back(static_cast(cpu_time)); + } + total_hit_count += hit_count; + return static_cast(parents.size() - 1); + }; + + const CpuProfileNode* root = profile->GetTopDownRoot(); + // Pairs of the row of a node's parent, and the node. + std::vector> stack; + + if (!options_.line_numbers) { + stack.emplace_back(-1, root); + while (!stack.empty()) { + auto [parent, node] = stack.back(); + stack.pop_back(); + uint32_t hit_count = node->GetHitCount(); + int64_t cpu_time = 0; + if (attribution != nullptr) { + // Samples that matched no record were not taken by the signal handler + // (e.g. deoptimization samples), so they are discarded. + auto it = attribution->find(node); + hit_count = it != attribution->end() ? it->second.hit_count : 0; + cpu_time = it != attribution->end() ? it->second.cpu_time : 0; + } + int32_t row = add_row(parent, + node, + node->GetLineNumber(), + node->GetColumnNumber(), + hit_count, + cpu_time); + for (int i = node->GetChildrenCount() - 1; i >= 0; i--) { + stack.emplace_back(row, node->GetChild(i)); + } + } + } else { + // In caller line numbers mode, the line of a node is the line from which + // its function was called. Each node turns into one leaf per line of its + // function that has hits, and one node per call it makes, at the line of + // the call. The children of the root are flattened into it. + add_row(-1, root, root->GetLineNumber(), root->GetColumnNumber(), 0, 0); + for (int i = root->GetChildrenCount() - 1; i >= 0; i--) { + stack.emplace_back(0, root->GetChild(i)); + } + std::vector line_ticks; + while (!stack.empty()) { + auto [parent, node] = stack.back(); + stack.pop_back(); + unsigned int hit_line_count = node->GetHitLineCount(); + if (hit_line_count > 0) { + line_ticks.resize(hit_line_count); + if (node->GetLineTicks(line_ticks.data(), hit_line_count)) { + for (const CpuProfileNode::LineTick& tick : line_ticks) { + add_row(parent, node, tick.line, tick.column, tick.hit_count, 0); + } + } + } else if (node->GetHitCount() > 0) { + // Pseudo-functions such as `(program)` and `(garbage collector)` have + // no line ticks. + add_row(parent, + node, + node->GetLineNumber(), + node->GetColumnNumber(), + node->GetHitCount(), + 0); + } + for (int i = node->GetChildrenCount() - 1; i >= 0; i--) { + const CpuProfileNode* child = node->GetChild(i); + int32_t row = add_row(parent, + node, + child->GetLineNumber(), + child->GetColumnNumber(), + 0, + 0); + stack.emplace_back(row, child); + } + } + } + + Local result = Object::New(isolate); + auto set = [&](const char* key, Local value) { + return result->Set(context, OneByteString(isolate, key), value).IsJust(); + }; + Local epoch_offset = +#ifdef _WIN32 + Undefined(isolate).As(); +#else + Number::New(isolate, static_cast(v8_to_epoch_offset)).As(); +#endif // _WIN32 + Local cpu_time_column = + attribution != nullptr + ? NewTypedArray(isolate, cpu_times).As() + : Undefined(isolate).As(); + + if (!set( + "startTime", + Number::New(isolate, static_cast(profile->GetStartTime()))) || + !set("endTime", + Number::New(isolate, static_cast(profile->GetEndTime()))) || + !set("epochOffset", epoch_offset) || + !set("hasCpuTime", Boolean::New(isolate, attribution != nullptr)) || + !set( + "nonJSThreadsCpuTime", + Number::New(isolate, static_cast(non_js_threads_cpu_time))) || + !set("totalHitCount", Number::New(isolate, total_hit_count)) || + !set("restarted", Boolean::New(isolate, restarted)) || + !set("parent", NewTypedArray(isolate, parents)) || + !set("scriptId", + NewTypedArray(isolate, script_ids)) || + !set("lineNumber", + NewTypedArray(isolate, line_numbers)) || + !set("columnNumber", + NewTypedArray(isolate, column_numbers)) || + !set("hitCount", + NewTypedArray(isolate, hit_counts)) || + !set("cpuTime", cpu_time_column) || + !set("name", v8::Array::New(isolate, names.data(), names.size())) || + !set("scriptName", + v8::Array::New(isolate, script_names.data(), script_names.size()))) { + return MaybeLocal(); + } + return result; +} + +void WallProfiler::DisposeProfiler() { + SetCollectionMode(CollectionMode::kNoCollect); +#ifndef _WIN32 + if (SignalHandler::GetThreadSink() == this) { + SignalHandler::SetThreadSink(nullptr); + } + // Restore the signal handler before V8 restores its own, when the profiler + // is disposed below. + while (signal_handler_uses_ > 0) { + SignalHandler::DecreaseUseCount(); + signal_handler_uses_--; + } +#endif // _WIN32 + if (cpu_profiler_ != nullptr) { + // Stop the running profile before disposing of the profiler, as + // Environment does with its own, e.g. when the profiler is torn down at + // exit without having been stopped. + if (started_) { + CpuProfile* profile = cpu_profiler_->Stop(profile_id_); + if (profile != nullptr) profile->Delete(); + } + cpu_profiler_->Dispose(); + cpu_profiler_ = nullptr; + GetActiveProfilers().Remove(this); + } + if (thread_profiler == this) thread_profiler = nullptr; + started_ = false; +} + +void WallProfiler::MakeWeakIfStopped() { + if (!started_ && !IsWeakOrDetached()) MakeWeak(); +} + +void WallProfiler::New(const FunctionCallbackInfo& args) { + CHECK(args.IsConstructCall()); + Environment* env = Environment::GetCurrent(args); + CHECK(args[0]->IsInt32()); // samplingIntervalMicros + CHECK(args[1]->IsInt32()); // durationMillis + CHECK(args[2]->IsBoolean()); // lineNumbers + CHECK(args[3]->IsBoolean()); // workaroundV8Bug + CHECK(args[4]->IsBoolean()); // collectCpuTime + + Options options; + options.sampling_interval_us = args[0].As()->Value(); + options.duration_ms = args[1].As()->Value(); + options.line_numbers = args[2]->IsTrue(); + options.workaround_v8_bug = args[3]->IsTrue(); + options.collect_cpu_time = args[4]->IsTrue(); + CHECK_GT(options.sampling_interval_us, 0); + CHECK_GT(options.duration_ms, 0); +#ifdef _WIN32 + // There is no signal to intercept. + options.workaround_v8_bug = false; + CHECK(!options.collect_cpu_time); +#endif // _WIN32 + // Caller line numbers cannot be attributed CPU time: samples are associated + // with profile nodes, not with line ticks. + CHECK(!(options.collect_cpu_time && options.line_numbers)); + + new WallProfiler(env, args.This(), options); +} + +void WallProfiler::Start(const FunctionCallbackInfo& args) { + WallProfiler* profiler; + ASSIGN_OR_RETURN_UNWRAP(&profiler, args.This()); + Environment* env = profiler->env(); + + if (profiler->started_) { + return THROW_ERR_INVALID_STATE(env, "The profiler is already started"); + } + if (thread_profiler != nullptr) { + return THROW_ERR_INVALID_STATE( + env, "Another time profiler is already running on this thread"); + } + + profiler->cpu_profiler_ = CpuProfiler::New(env->isolate()); + profiler->cpu_profiler_->SetSamplingInterval( + profiler->options_.sampling_interval_us); + thread_profiler = profiler; + profiler->thread_cpu_stop_watch_.GetAndReset(); + GetActiveProfilers().Add(profiler); +#ifndef _WIN32 + // Used by the signal handler and to compute the profile's epoch offset. + InitializeMonotonicClock(); + if (profiler->InterceptSignal()) { + SignalHandler::SetThreadSink(profiler); + } +#endif // _WIN32 + + profiler->profile_index_ = 0; + profiler->v8_profiler_stuck_event_loop_detected_ = 0; + profiler->records_.clear(); + // Keep the profiler alive while it runs. + profiler->started_ = true; + profiler->ClearWeak(); + + switch (profiler->StartInternal()) { + case StartStatus::kOk: + break; + case StartStatus::kTooManyProfiles: + profiler->DisposeProfiler(); + profiler->MakeWeakIfStopped(); + return THROW_ERR_CPU_PROFILE_TOO_MANY(env, + "There are too many CPU profiles"); + case StartStatus::kSignalHandlerFailed: + profiler->DisposeProfiler(); + profiler->MakeWeakIfStopped(); + return THROW_ERR_INVALID_STATE( + env, "Failed to install the SIGPROF signal handler"); + } + + profiler->SetCollectionMode(profiler->options_.collect_cpu_time + ? CollectionMode::kCollect + : (profiler->InterceptSignal() + ? CollectionMode::kPassThrough + : CollectionMode::kNoCollect)); +} + +void WallProfiler::Stop(const FunctionCallbackInfo& args) { + WallProfiler* profiler; + ASSIGN_OR_RETURN_UNWRAP(&profiler, args.This()); + CHECK(args[0]->IsBoolean()); + if (!profiler->started_) { + return THROW_ERR_INVALID_STATE(profiler->env(), + "The profiler is not started"); + } + Local profile; + bool translated = profiler->StopImpl(args[0]->IsTrue()).ToLocal(&profile); + profiler->MakeWeakIfStopped(); + if (translated) args.GetReturnValue().Set(profile); +} + +void WallProfiler::Dispose(const FunctionCallbackInfo& args) { + WallProfiler* profiler; + ASSIGN_OR_RETURN_UNWRAP(&profiler, args.This()); + profiler->DisposeProfiler(); + profiler->MakeWeakIfStopped(); +} + +void WallProfiler::V8ProfilerStuckEventLoopDetected( + const FunctionCallbackInfo& args) { + WallProfiler* profiler; + ASSIGN_OR_RETURN_UNWRAP(&profiler, args.This()); + args.GetReturnValue().Set(profiler->v8_profiler_stuck_event_loop_detected_); +} + +void WallProfiler::Initialize(Local target, + Local unused, + Local context, + void* priv) { + Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); + + Local tmpl = NewFunctionTemplate(isolate, New); + tmpl->InstanceTemplate()->SetInternalFieldCount( + WallProfiler::kInternalFieldCount); + SetProtoMethod(isolate, tmpl, "start", Start); + SetProtoMethod(isolate, tmpl, "stop", Stop); + SetProtoMethod(isolate, tmpl, "dispose", Dispose); + SetProtoMethodNoSideEffect(isolate, + tmpl, + "v8ProfilerStuckEventLoopDetected", + V8ProfilerStuckEventLoopDetected); + SetConstructorFunction(context, target, "WallProfiler", tmpl); + +#ifdef _WIN32 + constexpr bool kSignalSamplingSupported = false; +#else + constexpr bool kSignalSamplingSupported = true; +#endif // _WIN32 + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "signalSamplingSupported"), + Boolean::New(isolate, kSignalSamplingSupported)) + .Check(); +} + +void WallProfiler::RegisterExternalReferences( + ExternalReferenceRegistry* registry) { + registry->Register(New); + registry->Register(Start); + registry->Register(Stop); + registry->Register(Dispose); + registry->Register(V8ProfilerStuckEventLoopDetected); +} + +} // namespace pprof +} // namespace node + +NODE_BINDING_CONTEXT_AWARE_INTERNAL(pprof, + node::pprof::WallProfiler::Initialize) +NODE_BINDING_EXTERNAL_REFERENCE( + pprof, node::pprof::WallProfiler::RegisterExternalReferences) diff --git a/src/node_pprof.h b/src/node_pprof.h new file mode 100644 index 000000000000..a8a934de3fa5 --- /dev/null +++ b/src/node_pprof.h @@ -0,0 +1,141 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.hh +// without sampling contexts, CPED and async ID support. +// +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_NODE_PPROF_H_ +#define SRC_NODE_PPROF_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "base_object.h" +#include "memory_tracker.h" +#include "pprof/cpu_clock.h" +#include "pprof/sigprof_handler.h" +#include "pprof/time_profile.h" +#include "v8-profiler.h" +#include "v8.h" + +#include +#include +#include + +namespace node { + +class ExternalReferenceRegistry; + +namespace pprof { + +// A wall time profiler built on v8::CpuProfiler that produces the profiles +// that lib/internal/perf/pprof turns into pprof profiles. +// +// On POSIX systems, it can intercept the SIGPROF signals that V8's sampler +// sends, to work around a V8 bug that leaves the profiler's event processor +// stuck, and to attribute thread CPU time to the samples. +class WallProfiler final : public BaseObject, public SignalSampleSink { + public: + enum class CollectionMode { kNoCollect, kPassThrough, kCollect }; + + struct Options { + int sampling_interval_us; + int duration_ms; + bool line_numbers; + bool workaround_v8_bug; + bool collect_cpu_time; + }; + + static void Initialize(v8::Local target, + v8::Local unused, + v8::Local context, + void* priv); + static void RegisterExternalReferences(ExternalReferenceRegistry* registry); + + static void New(const v8::FunctionCallbackInfo& args); + static void Start(const v8::FunctionCallbackInfo& args); + static void Stop(const v8::FunctionCallbackInfo& args); + static void Dispose(const v8::FunctionCallbackInfo& args); + static void V8ProfilerStuckEventLoopDetected( + const v8::FunctionCallbackInfo& args); + + WallProfiler(Environment* env, + v8::Local object, + const Options& options); + ~WallProfiler() override; + + void MemoryInfo(MemoryTracker* tracker) const override; + SET_MEMORY_INFO_NAME(WallProfiler) + SET_SELF_SIZE(WallProfiler) + +#ifndef _WIN32 + void OnProfilerSignal(int sig, siginfo_t* info, void* context) override; +#endif + + // Returns the CPU time consumed by the profiler's thread since the previous + // call. Called with the registry of active profilers locked. + int64_t GetAndResetThreadCpu() { + return thread_cpu_stop_watch_.GetAndReset(); + } + + private: + enum class StartStatus { kOk, kTooManyProfiles, kSignalHandlerFailed }; + + // Lets the profiler be garbage collected once it no longer runs. + void MakeWeakIfStopped(); + StartStatus StartInternal(); + v8::MaybeLocal StopImpl(bool restart); + v8::MaybeLocal TranslateProfile( + const v8::CpuProfile* profile, + const AttributionByNode* attribution, + int64_t non_js_threads_cpu_time, + int64_t v8_to_epoch_offset, + bool restarted); + void DisposeProfiler(); + bool InterceptSignal() const; + void SetCollectionMode(CollectionMode mode); + bool WaitForSignal(uint64_t target_call_count = 0); + + const Options options_; + const bool is_main_thread_; + + v8::CpuProfiler* cpu_profiler_ = nullptr; + v8::ProfilerId profile_id_ = 0; + uint64_t profile_index_ = 0; + bool started_ = false; + int v8_profiler_stuck_event_loop_detected_ = 0; + // Number of uses of the SIGPROF handler held by the running profiles. + int signal_handler_uses_ = 0; + + std::atomic collection_mode_{CollectionMode::kNoCollect}; + // Number of signals received while not collecting. + std::atomic no_collect_call_count_{0}; + + int64_t start_thread_cpu_time_ = 0; + int64_t start_process_cpu_time_ = 0; + ThreadCpuStopWatch thread_cpu_stop_watch_; + + // Appended to by the signal handler, which runs on the profiler's thread, so + // its capacity is reserved upfront to never allocate there. + std::vector records_; +}; + +} // namespace pprof +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_NODE_PPROF_H_ diff --git a/src/pprof/cpu_clock.cc b/src/pprof/cpu_clock.cc new file mode 100644 index 000000000000..a9eff6a253f3 --- /dev/null +++ b/src/pprof/cpu_clock.cc @@ -0,0 +1,181 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/thread-cpu-clock.cc +// +// SPDX-License-Identifier: Apache-2.0 + +#include "pprof/cpu_clock.h" + +#ifdef __APPLE__ +#include +#include +#include +#include +#endif + +#include + +namespace node { +namespace pprof { + +namespace { + +constexpr int64_t kNanosPerSecond = 1000 * 1000 * 1000; +constexpr int64_t kNanosPerMicro = 1000; + +#ifdef _WIN32 +int64_t FileTimeToNanos(FILETIME t) { + return static_cast((static_cast(t.dwHighDateTime) << 32) | + static_cast(t.dwLowDateTime)) * + 100; +} + +int64_t ThreadTimesNanos(HANDLE thread) { + FILETIME creation_time, exit_time, kernel_time, user_time; + if (!GetThreadTimes( + thread, &creation_time, &exit_time, &kernel_time, &user_time)) { + return 0; + } + return FileTimeToNanos(kernel_time) + FileTimeToNanos(user_time); +} +#else +int64_t ClockNanos(clockid_t clock_id) { + timespec ts; + if (clock_gettime(clock_id, &ts) != 0) return 0; + return static_cast(ts.tv_sec) * kNanosPerSecond + ts.tv_nsec; +} +#endif // _WIN32 + +#ifdef __APPLE__ +// Written once by InitializeMonotonicClock() before any signal handler reads +// it, then read-only. +std::atomic timebase_numer{0}; +std::atomic timebase_denom{0}; +#endif // __APPLE__ + +} // namespace + +int64_t CurrentThreadCpuNanos() { +#ifdef _WIN32 + return ThreadTimesNanos(GetCurrentThread()); +#else + return ClockNanos(CLOCK_THREAD_CPUTIME_ID); +#endif +} + +int64_t ProcessCpuNanos() { +#ifdef _WIN32 + FILETIME creation_time, exit_time, kernel_time, user_time; + if (!GetProcessTimes(GetCurrentProcess(), + &creation_time, + &exit_time, + &kernel_time, + &user_time)) { + return 0; + } + return FileTimeToNanos(kernel_time) + FileTimeToNanos(user_time); +#else + return ClockNanos(CLOCK_PROCESS_CPUTIME_ID); +#endif +} + +#ifndef _WIN32 +void InitializeMonotonicClock() { +#ifdef __APPLE__ + if (timebase_denom.load(std::memory_order_acquire) != 0) return; + mach_timebase_info_data_t info; + if (mach_timebase_info(&info) != KERN_SUCCESS || info.denom == 0) { + info.numer = 1; + info.denom = 1; + } + timebase_numer.store(info.numer, std::memory_order_relaxed); + timebase_denom.store(info.denom, std::memory_order_release); +#endif // __APPLE__ +} + +int64_t MonotonicNowMicros() { + int64_t ticks; +#ifdef __APPLE__ + uint64_t numer = timebase_numer.load(std::memory_order_relaxed); + uint64_t denom = timebase_denom.load(std::memory_order_acquire); + if (denom == 0) { + numer = 1; + denom = 1; + } + ticks = static_cast(mach_absolute_time() * numer / + (kNanosPerMicro * denom)); +#else + ticks = ClockNanos(CLOCK_MONOTONIC) / kNanosPerMicro; +#endif // __APPLE__ + // V8 makes sure TimeTicks::Now() never returns 0. + return ticks + 1; +} +#endif // _WIN32 + +ThreadCpuClock::ThreadCpuClock() { +#ifdef _WIN32 + // GetCurrentThread() returns a pseudo handle that always refers to the + // calling thread, so it must be duplicated to read this thread's times from + // another thread. + if (!DuplicateHandle(GetCurrentProcess(), + GetCurrentThread(), + GetCurrentProcess(), + &thread_, + THREAD_QUERY_LIMITED_INFORMATION, + FALSE, + 0)) { + thread_ = nullptr; + } +#elif defined(__APPLE__) + // Unlike mach_thread_self(), this does not add a reference to the port. + thread_ = pthread_mach_thread_np(pthread_self()); +#else + valid_ = pthread_getcpuclockid(pthread_self(), &clockid_) == 0; +#endif +} + +ThreadCpuClock::~ThreadCpuClock() { +#ifdef _WIN32 + if (thread_ != nullptr) CloseHandle(thread_); +#endif +} + +int64_t ThreadCpuClock::NowNanos() const { +#ifdef _WIN32 + if (thread_ == nullptr) return 0; + return ThreadTimesNanos(thread_); +#elif defined(__APPLE__) + mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; + thread_basic_info_data_t info; + kern_return_t kr = thread_info(thread_, + THREAD_BASIC_INFO, + reinterpret_cast(&info), + &count); + if (kr != KERN_SUCCESS) return 0; + return (static_cast(info.user_time.seconds) + + info.system_time.seconds) * + kNanosPerSecond + + (static_cast(info.user_time.microseconds) + + info.system_time.microseconds) * + kNanosPerMicro; +#else + if (!valid_) return 0; + return ClockNanos(clockid_); +#endif +} + +} // namespace pprof +} // namespace node diff --git a/src/pprof/cpu_clock.h b/src/pprof/cpu_clock.h new file mode 100644 index 000000000000..bc1bdb236479 --- /dev/null +++ b/src/pprof/cpu_clock.h @@ -0,0 +1,104 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/thread-cpu-clock.hh +// and +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/thread-cpu-clock.cc +// +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_PPROF_CPU_CLOCK_H_ +#define SRC_PPROF_CPU_CLOCK_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include + +#ifdef _WIN32 +#include +#elif defined(__APPLE__) +#include +#else +#include +#include +#endif + +namespace node { +namespace pprof { + +// CPU time consumed by the calling thread, in nanoseconds. Async-signal-safe +// on POSIX. +int64_t CurrentThreadCpuNanos(); + +// CPU time consumed by the whole process, in nanoseconds. +int64_t ProcessCpuNanos(); + +#ifndef _WIN32 +// Must be called at least once, outside of a signal handler, before +// MonotonicNowMicros() is used from one. +void InitializeMonotonicClock(); + +// The current value of the clock that V8's base::TimeTicks::Now() reads, in +// microseconds, so that it can be compared with CpuProfile sample timestamps. +// V8's base library is not available to Node.js sources, so this replicates +// TimeTicks::Now() from deps/v8/src/base/platform/time.cc. Async-signal-safe. +int64_t MonotonicNowMicros(); +#endif // _WIN32 + +// Reads the CPU time of the thread that created it, from any thread. +class ThreadCpuClock { + public: + ThreadCpuClock(); + ~ThreadCpuClock(); + ThreadCpuClock(const ThreadCpuClock&) = delete; + ThreadCpuClock& operator=(const ThreadCpuClock&) = delete; + + int64_t NowNanos() const; + + private: +#ifdef _WIN32 + HANDLE thread_ = nullptr; +#elif defined(__APPLE__) + mach_port_t thread_ = MACH_PORT_NULL; +#else + clockid_t clockid_{}; + bool valid_ = false; +#endif +}; + +// Measures the CPU time consumed by the thread that created it since the +// previous call to GetAndReset(). +class ThreadCpuStopWatch { + public: + ThreadCpuStopWatch() : last_(clock_.NowNanos()) {} + + int64_t GetAndReset() { + int64_t now = clock_.NowNanos(); + int64_t elapsed = now - last_; + last_ = now; + return elapsed; + } + + private: + ThreadCpuClock clock_; + int64_t last_; +}; + +} // namespace pprof +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_PPROF_CPU_CLOCK_H_ diff --git a/src/pprof/sigprof_handler.cc b/src/pprof/sigprof_handler.cc new file mode 100644 index 000000000000..7ca1f48a4717 --- /dev/null +++ b/src/pprof/sigprof_handler.cc @@ -0,0 +1,144 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from the SignalHandler class +// in +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.cc +// +// SPDX-License-Identifier: Apache-2.0 + +#include "pprof/sigprof_handler.h" + +#ifndef _WIN32 + +#include +#include + +namespace node { +namespace pprof { + +namespace { + +using SigactionFunc = void (*)(int, siginfo_t*, void*); +using SighandlerFunc = void (*)(int); + +// Protects the process-wide state below, except for the atomics, which the +// signal handler reads. +std::mutex handler_mutex; +int use_count = 0; +bool installed = false; +struct sigaction previous_action; + +// The previous handler, in one of its two forms. Both are null when there is +// no handler to forward to (SIG_DFL or SIG_IGN). +std::atomic previous_sigaction{nullptr}; +std::atomic previous_handler{nullptr}; + +// Signals are delivered to threads, and in Node.js each isolate runs on a +// single thread, so the sink of the thread that receives a signal is the one +// of the isolate that V8 is sampling. This is per-thread rather than +// per-Environment state on purpose. +// The initial-exec TLS model makes every access a single load, without the +// __tls_get_addr() call (which is not async-signal-safe) that the default +// model may compile to when Node.js is built as a shared library. +#if defined(__GLIBC__) +__attribute__((tls_model("initial-exec"))) +#endif +// NOLINTNEXTLINE(runtime/thread_local) +thread_local SignalSampleSink* thread_sink = nullptr; + +} // namespace + +bool SignalHandler::IncreaseUseCount() { + std::lock_guard lock(handler_mutex); + struct sigaction sa; + sa.sa_sigaction = &HandleProfilerSignal; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK; + if (installed) { + // Reinstall in case someone else replaced the handler in the meantime. + sigaction(SIGPROF, &sa, nullptr); + ++use_count; + return true; + } + + struct sigaction prev; + if (sigaction(SIGPROF, &sa, &prev) != 0) return false; + if ((prev.sa_flags & SA_SIGINFO) && + prev.sa_sigaction == &HandleProfilerSignal) { + sigaction(SIGPROF, &prev, nullptr); + return false; + } + + previous_action = prev; + if (prev.sa_flags & SA_SIGINFO) { + previous_handler.store(nullptr, std::memory_order_relaxed); + previous_sigaction.store(prev.sa_sigaction, std::memory_order_release); + } else if (prev.sa_handler != SIG_DFL && prev.sa_handler != SIG_IGN) { + previous_sigaction.store(nullptr, std::memory_order_relaxed); + previous_handler.store(prev.sa_handler, std::memory_order_release); + } else { + previous_sigaction.store(nullptr, std::memory_order_relaxed); + previous_handler.store(nullptr, std::memory_order_release); + } + installed = true; + ++use_count; + return true; +} + +void SignalHandler::DecreaseUseCount() { + std::lock_guard lock(handler_mutex); + if (use_count == 0 || --use_count > 0 || !installed) return; + sigaction(SIGPROF, &previous_action, nullptr); + installed = false; + previous_sigaction.store(nullptr, std::memory_order_relaxed); + previous_handler.store(nullptr, std::memory_order_relaxed); +} + +void SignalHandler::SetThreadSink(SignalSampleSink* sink) { + std::atomic_signal_fence(std::memory_order_release); + thread_sink = sink; + std::atomic_signal_fence(std::memory_order_release); +} + +SignalSampleSink* SignalHandler::GetThreadSink() { + return thread_sink; +} + +void SignalHandler::ForwardSignal(int sig, siginfo_t* info, void* context) { + SigactionFunc action = previous_sigaction.load(std::memory_order_acquire); + if (action != nullptr) { + action(sig, info, context); + return; + } + SighandlerFunc handler = previous_handler.load(std::memory_order_acquire); + if (handler != nullptr) handler(sig); +} + +void SignalHandler::HandleProfilerSignal(int sig, + siginfo_t* info, + void* context) { + SignalSampleSink* sink = thread_sink; + std::atomic_signal_fence(std::memory_order_acquire); + if (sink == nullptr) { + ForwardSignal(sig, info, context); + return; + } + sink->OnProfilerSignal(sig, info, context); +} + +} // namespace pprof +} // namespace node + +#endif // _WIN32 diff --git a/src/pprof/sigprof_handler.h b/src/pprof/sigprof_handler.h new file mode 100644 index 000000000000..7caf8bfbd045 --- /dev/null +++ b/src/pprof/sigprof_handler.h @@ -0,0 +1,98 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: ported from the SignalHandler class +// in +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.cc +// +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_PPROF_SIGPROF_HANDLER_H_ +#define SRC_PPROF_SIGPROF_HANDLER_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#ifdef _WIN32 + +namespace node { +namespace pprof { + +// V8 does not sample with signals on Windows. +class SignalSampleSink { + protected: + ~SignalSampleSink() = default; +}; + +} // namespace pprof +} // namespace node + +#else // _WIN32 + +#include + +namespace node { +namespace pprof { + +// Receives the SIGPROF signals that V8's CPU profiler sends to the thread that +// registered it with SignalHandler::SetThreadSink(). +class SignalSampleSink { + public: + // Runs in signal handler context, so it must be async-signal-safe: no + // allocations, no locks, no V8 API calls. It is responsible for calling + // SignalHandler::ForwardSignal() so that V8 can take its sample. + virtual void OnProfilerSignal(int sig, siginfo_t* info, void* context) = 0; + + protected: + ~SignalSampleSink() = default; +}; + +// Process-wide SIGPROF handler installed in front of the one that V8's sampler +// installs, so that the time at which V8 takes each sample can be observed. +// +// It must be installed after V8's handler, i.e. after a v8::CpuProfiler has +// started profiling, and removed before that profiling stops, so that both +// handlers are restored in the reverse order of their installation. +class SignalHandler { + public: + // Installs the handler if it is not installed yet. Returns false if + // sigaction() failed or if the previous handler was already this one (which + // happens when another SIGPROF user restored a disposition it captured while + // this handler was installed): chaining to it would loop, and V8's sampler + // would be unreachable. On failure the use count is left unchanged. + static bool IncreaseUseCount(); + + // Restores the previous handler once the last user is gone. + static void DecreaseUseCount(); + + // Sets the sink that receives the signals delivered to the calling thread, + // or clears it if `sink` is nullptr. Signals delivered to threads without a + // sink are forwarded to the previous handler. + static void SetThreadSink(SignalSampleSink* sink); + static SignalSampleSink* GetThreadSink(); + + // Calls the handler that was installed before this one. + static void ForwardSignal(int sig, siginfo_t* info, void* context); + + private: + static void HandleProfilerSignal(int sig, siginfo_t* info, void* context); +}; + +} // namespace pprof +} // namespace node + +#endif // !_WIN32 + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_PPROF_SIGPROF_HANDLER_H_ diff --git a/src/pprof/time_profile.cc b/src/pprof/time_profile.cc new file mode 100644 index 000000000000..5793c293d70b --- /dev/null +++ b/src/pprof/time_profile.cc @@ -0,0 +1,92 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: the sample attribution logic of +// WallProfiler::GetContextsByNode() from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.cc +// rewritten as a function that does not depend on V8. +// +// SPDX-License-Identifier: Apache-2.0 + +#include "pprof/time_profile.h" + +namespace node { +namespace pprof { + +AttributionByNode AttributeSamples(const std::vector& samples, + const std::vector& records, + int64_t start_cpu_time) { + AttributionByNode result; + const size_t sample_count = samples.size(); + if (records.empty() || sample_count == 0) return result; + + auto record = records.begin(); + int64_t last_cpu_time = start_cpu_time; + // Offset of the sample to process relative to the iteration index, to + // handle out-of-order samples. + int delta = 0; + + // Skip the first sample, which V8 takes when profiling starts, outside of + // the signal handler. + for (size_t i = 1; i < sample_count; i++) { + if (delta == 1) { + // The previous iteration processed the next sample, so process the + // previous one now. + delta = -1; + } else if (delta == -1) { + // Back to the normal order. + delta = 0; + } else if (i < sample_count - 1 && + samples[i + 1].timestamp < samples[i].timestamp) { + // Out-of-order sample: process the next one first. The hypothesis is + // that at most two consecutive samples are out of order. + delta = 1; + } + + const ProfileSample& sample = samples[i + delta]; + + // Drop the records that are too old to match this sample. A sample + // matches the record whose [time_from, time_to] interval contains its + // timestamp. + while (record != records.end()) { + if (record->time_to < sample.timestamp) { + ++record; + } else if (record->time_from > sample.timestamp) { + // Too recent: try to match it with the next sample. + break; + } else { + NodeAttribution& attribution = result[sample.node]; + attribution.hit_count++; + // The CPU time of a `(program)` sample goes to the next sample. + if (!sample.is_program) { + attribution.cpu_time += record->cpu_time - last_cpu_time; + last_cpu_time = record->cpu_time; + } + // Match at most one record with each sample. + ++record; + break; + } + } + } + + return result; +} + +int64_t Midpoint(int64_t x, int64_t y) { + static_assert((-1L >> 1) == -1L, "Right shift is not arithmetic"); + return ((x ^ y) >> 1) + (x & y); +} + +} // namespace pprof +} // namespace node diff --git a/src/pprof/time_profile.h b/src/pprof/time_profile.h new file mode 100644 index 000000000000..4c9b80bb51cc --- /dev/null +++ b/src/pprof/time_profile.h @@ -0,0 +1,82 @@ +// Copyright 2023 Datadog, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Modified for inclusion in Node.js core: the sample attribution logic of +// WallProfiler::GetContextsByNode() from +// https://github.com/DataDog/pprof-nodejs/blob/3905f382723fc2554284e1abbba2df0f2dc6f82b/bindings/profilers/wall.cc +// rewritten as a function that does not depend on V8. +// +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_PPROF_TIME_PROFILE_H_ +#define SRC_PPROF_TIME_PROFILE_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include +#include +#include + +namespace node { +namespace pprof { + +// What the SIGPROF handler records around each sample that V8 takes: the +// interval, in V8 timer microseconds, during which V8's handler ran, and the +// CPU time of the thread, in nanoseconds, when the signal arrived. +struct SampleRecord { + int64_t time_from; + int64_t time_to; + int64_t cpu_time; +}; + +// A sample of a CpuProfile, as far as attribution is concerned. +struct ProfileSample { + int64_t timestamp; + // Identifies the profile node the sample belongs to. + const void* node; + // The sample is a `(program)` sample, i.e. no JS was running. + bool is_program; +}; + +// The samples of a profile node that matched a SampleRecord, and the thread +// CPU time attributed to them. +struct NodeAttribution { + uint32_t hit_count = 0; + int64_t cpu_time = 0; +}; + +using AttributionByNode = std::unordered_map; + +// Matches each sample of a profile with the record whose interval contains its +// timestamp, and attributes the thread CPU time consumed since the previous +// matched sample to its node. +// +// The first sample is skipped, since V8 takes it when profiling starts rather +// than from the signal handler. Up to two consecutive samples may be out of +// order. Samples without a matching record (e.g. deoptimization samples) are +// not attributed. The CPU time of `(program)` samples is carried over to the +// next sample. +AttributionByNode AttributeSamples(const std::vector& samples, + const std::vector& records, + int64_t start_cpu_time); + +// Returns ((x + y) / 2) rounded towards negative infinity, without overflow. +int64_t Midpoint(int64_t x, int64_t y); + +} // namespace pprof +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_PPROF_TIME_PROFILE_H_ diff --git a/test/cctest/test_pprof.cc b/test/cctest/test_pprof.cc new file mode 100644 index 000000000000..04b37a1fd36a --- /dev/null +++ b/test/cctest/test_pprof.cc @@ -0,0 +1,219 @@ +#include "pprof/cpu_clock.h" +#include "pprof/sigprof_handler.h" +#include "pprof/time_profile.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +using node::pprof::AttributeSamples; +using node::pprof::AttributionByNode; +using node::pprof::CurrentThreadCpuNanos; +using node::pprof::Midpoint; +using node::pprof::ProfileSample; +using node::pprof::SampleRecord; +using node::pprof::ThreadCpuClock; + +namespace { + +// Stand-ins for profile nodes. +char nodes[3]; +const void* const a = &nodes[0]; +const void* const b = &nodes[1]; +const void* const program = &nodes[2]; + +void Spin(int64_t cpu_nanos) { + int64_t end = CurrentThreadCpuNanos() + cpu_nanos; + volatile uint64_t x = 0; + while (CurrentThreadCpuNanos() < end) x = x + 1; +} + +} // namespace + +TEST(PprofAttributeSamples, Empty) { + EXPECT_TRUE(AttributeSamples({}, {}, 0).empty()); + EXPECT_TRUE( + AttributeSamples({{10, a, false}, {20, a, false}}, {}, 0).empty()); + EXPECT_TRUE(AttributeSamples({}, {{9, 11, 100}}, 0).empty()); +} + +TEST(PprofAttributeSamples, MatchesRecordsAroundSamples) { + std::vector samples = { + // The starting sample is skipped, even if it matches a record. + {10, a, false}, + {20, a, false}, + {30, b, false}, + // No record matches this one, e.g. a deoptimization sample. + {35, b, false}, + {40, a, false}, + }; + std::vector records = { + {9, 11, 50}, + // Too old for any sample. + {12, 13, 60}, + {19, 21, 100}, + {29, 30, 250}, + {40, 40, 400}, + // Too recent for any sample. + {50, 51, 1000}, + }; + AttributionByNode attribution = AttributeSamples(samples, records, 40); + ASSERT_EQ(attribution.size(), 2u); + EXPECT_EQ(attribution[a].hit_count, 2u); + // 100 - 40 for the sample at 20, and 400 - 250 for the sample at 40. + EXPECT_EQ(attribution[a].cpu_time, 60 + 150); + EXPECT_EQ(attribution[b].hit_count, 1u); + EXPECT_EQ(attribution[b].cpu_time, 250 - 100); +} + +TEST(PprofAttributeSamples, OutOfOrderSamples) { + std::vector samples = { + {0, a, false}, + {10, a, false}, + // These two are swapped. + {30, b, false}, + {20, a, false}, + {40, b, false}, + }; + std::vector records = { + {10, 10, 10}, + {20, 20, 20}, + {30, 30, 30}, + {40, 40, 40}, + }; + AttributionByNode attribution = AttributeSamples(samples, records, 0); + EXPECT_EQ(attribution[a].hit_count, 2u); + EXPECT_EQ(attribution[a].cpu_time, 20); + EXPECT_EQ(attribution[b].hit_count, 2u); + EXPECT_EQ(attribution[b].cpu_time, 20); +} + +TEST(PprofAttributeSamples, ProgramCpuTimeGoesToTheNextSample) { + std::vector samples = { + {0, a, false}, + {10, program, true}, + {20, a, false}, + }; + std::vector records = { + {10, 10, 100}, + {20, 20, 300}, + }; + AttributionByNode attribution = AttributeSamples(samples, records, 0); + EXPECT_EQ(attribution[program].hit_count, 1u); + EXPECT_EQ(attribution[program].cpu_time, 0); + EXPECT_EQ(attribution[a].hit_count, 1u); + EXPECT_EQ(attribution[a].cpu_time, 300); +} + +TEST(PprofMidpoint, RoundsDown) { + EXPECT_EQ(Midpoint(0, 0), 0); + EXPECT_EQ(Midpoint(1, 2), 1); + EXPECT_EQ(Midpoint(2, 4), 3); + EXPECT_EQ(Midpoint(-1, -2), -2); + EXPECT_EQ(Midpoint(INT64_MAX, INT64_MAX - 2), INT64_MAX - 1); +} + +TEST(PprofCpuClock, ThreadCpuTime) { + int64_t start = CurrentThreadCpuNanos(); + Spin(5 * 1000 * 1000); + EXPECT_GE(CurrentThreadCpuNanos() - start, 5 * 1000 * 1000); +} + +TEST(PprofCpuClock, ThreadCpuClockReadsItsThread) { + ThreadCpuClock clock; + int64_t start = clock.NowNanos(); + // Another thread that spins does not add to this thread's CPU time. + int64_t other_thread_cpu = 0; + std::thread thread([&]() { + ThreadCpuClock other_clock; + Spin(20 * 1000 * 1000); + other_thread_cpu = other_clock.NowNanos(); + }); + thread.join(); + EXPECT_GE(other_thread_cpu, 20 * 1000 * 1000); + EXPECT_LT(clock.NowNanos() - start, other_thread_cpu); +} + +#ifndef _WIN32 + +using node::pprof::MonotonicNowMicros; +using node::pprof::SignalHandler; +using node::pprof::SignalSampleSink; + +TEST(PprofCpuClock, MonotonicClock) { + node::pprof::InitializeMonotonicClock(); + int64_t previous = MonotonicNowMicros(); + EXPECT_GT(previous, 0); + for (int i = 0; i < 1000; i++) { + int64_t now = MonotonicNowMicros(); + EXPECT_GE(now, previous); + previous = now; + } +} + +namespace { + +int previous_handler_calls = 0; +void PreviousHandler(int, siginfo_t*, void*) { + previous_handler_calls++; +} + +class CountingSink : public SignalSampleSink { + public: + void OnProfilerSignal(int sig, siginfo_t* info, void* context) override { + calls++; + SignalHandler::ForwardSignal(sig, info, context); + } + int calls = 0; +}; + +} // namespace + +TEST(PprofSignalHandler, ChainsToThePreviousHandler) { + struct sigaction original; + ASSERT_EQ(sigaction(SIGPROF, nullptr, &original), 0); + + struct sigaction previous; + previous.sa_sigaction = &PreviousHandler; + sigemptyset(&previous.sa_mask); + previous.sa_flags = SA_SIGINFO; + ASSERT_EQ(sigaction(SIGPROF, &previous, nullptr), 0); + + ASSERT_TRUE(SignalHandler::IncreaseUseCount()); + // Signals delivered to a thread without a sink go to the previous handler. + previous_handler_calls = 0; + raise(SIGPROF); + EXPECT_EQ(previous_handler_calls, 1); + + CountingSink sink; + SignalHandler::SetThreadSink(&sink); + EXPECT_EQ(SignalHandler::GetThreadSink(), &sink); + raise(SIGPROF); + EXPECT_EQ(sink.calls, 1); + EXPECT_EQ(previous_handler_calls, 2); + SignalHandler::SetThreadSink(nullptr); + + // The handler stays installed until its last use is released. + ASSERT_TRUE(SignalHandler::IncreaseUseCount()); + SignalHandler::DecreaseUseCount(); + struct sigaction current; + ASSERT_EQ(sigaction(SIGPROF, nullptr, ¤t), 0); + EXPECT_NE(current.sa_sigaction, &PreviousHandler); + SignalHandler::DecreaseUseCount(); + ASSERT_EQ(sigaction(SIGPROF, nullptr, ¤t), 0); + EXPECT_EQ(current.sa_sigaction, &PreviousHandler); + + // Installing refuses to chain to itself. + ASSERT_TRUE(SignalHandler::IncreaseUseCount()); + struct sigaction installed; + ASSERT_EQ(sigaction(SIGPROF, nullptr, &installed), 0); + SignalHandler::DecreaseUseCount(); + ASSERT_EQ(sigaction(SIGPROF, &installed, nullptr), 0); + EXPECT_FALSE(SignalHandler::IncreaseUseCount()); + + ASSERT_EQ(sigaction(SIGPROF, &original, nullptr), 0); +} + +#endif // _WIN32 diff --git a/test/common/README.md b/test/common/README.md index ee13afcb4c7a..ac92f6f94c5d 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -43,6 +43,7 @@ several other tasks: * [HTTP2 module](#http2-module) * [Internet module](#internet-module) * [ongc module](#ongc-module) +* [pprof module](#pprof-module) * [process-exit-code-test-cases module](#process-exit-code-test-cases-module) * [Report module](#report-module) * [tick module](#tick-module) @@ -1049,6 +1050,41 @@ a full `setImmediate()` invocation passes. `listener` is an object to make it easier to use a closure; the target object should not be in scope when `listener.ongc()` is created. +## pprof module + +The `pprof` module provides a minimal decoder of the pprof profiles that +`node:perf_hooks/pprof` encodes, independent of its encoder. + +### `decodeProfile(buffer)` + +* `buffer` [\][] An uncompressed pprof `Profile` message. +* return [\][] + +Decodes the fields of a pprof `Profile` message. Strings are left as indices +into its `stringTable`. + +### `decodeGzippedProfile(buffer)` + +* `buffer` [\][] A gzip-compressed pprof `Profile` message. +* return [\][] + +Decodes a gzip-compressed pprof profile into `{ profile, strings, sampleTypes, +samples }`, where each sample is `{ stack, values }`: `stack` lists its frames, +leaf first, as `{ name, file, line }`, and `values` maps sample types to values. + +### `pprofTestBusyLoop(cpuMicros)` + +* `cpuMicros` [\][] The CPU time to use, in microseconds. +* return [\][] + +Keeps the thread busy until it has used `cpuMicros` microseconds of CPU time, +so that profiles have samples of a known function, named `pprofTestBusyLoop`, +in `test/common/pprof.js`. The loop is bounded by CPU time so that it gets about +as many samples on a loaded machine as on an idle one. Tests that use it should +prevent its optimization with `--allow-natives-syntax` and +`eval('%NeverOptimizeFunction(pprofTestBusyLoop)')`, since profiles lack the +inlined frames of code that was optimized before the profiler started. + ## process-exit-code-test-cases module The `process-exit-code-test-cases` module provides a set of shared test cases diff --git a/test/common/pprof.js b/test/common/pprof.js new file mode 100644 index 000000000000..408958696957 --- /dev/null +++ b/test/common/pprof.js @@ -0,0 +1,269 @@ +'use strict'; + +// A minimal decoder of pprof profiles, for the tests of node:perf_hooks/pprof. +// +// node:perf_hooks/pprof returns profiles as gzip-compressed protobuf +// messages, so tests can only check what a profile contains by decoding one. +// Core has no protobuf decoder, and the pprof code in lib/ only encodes. +// Decoding with code from the implementation would hide bugs that the encoder +// and the decoder share, and inspecting the Profile object before it is +// encoded would not test the bytes at all. This decoder is written +// independently of the encoder instead: it only knows the protobuf wire +// format and the field numbers of pprof's profile.proto, at +// https://github.com/google/pprof/blob/084b33a85f63291f0513dc6a6284e5dfa66c8e3a/proto/profile.proto +// It decodes the fields that the time profiler writes, and ignores the others. +// +// Tests usually pass the output of encode() or encodeSync() to +// decodeGzippedProfile(), and check the samples that it returns, which have +// their stacks resolved to function names, files and lines: +// +// const { samples } = decodeGzippedProfile(encodeSync(time.stop())); +// assert.ok(samples.some(({ stack }) => stack[0].name === 'busyLoop')); +// +// Tests of the encoding itself pass the uncompressed output of a Profile's +// encode() method to decodeProfile(), which returns the raw fields, with +// strings left as indices in the string table. + +require('./'); +const zlib = require('node:zlib'); + +/** + * Reads a varint at `state.offset`, and advances the offset past it. + * @param {Buffer} buffer The encoded message that holds the varint. + * @param {{ offset: number }} state The offset of the varint in `buffer`, + * which is updated to the offset after it. + * @returns {number | bigint} A number if the value is a safe integer, or a + * bigint otherwise. + */ +function readVarint(buffer, state) { + let result = 0n; + let shift = 0n; + let byte; + do { + byte = buffer[state.offset++]; + result |= BigInt(byte & 0x7f) << shift; + shift += 7n; + } while (byte & 0x80); + return result <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(result) : result; +} + +/** + * Calls `onField(field, value)` for each field of a message, where `value` is + * a number (or bigint) for varints and a Buffer for length-delimited fields. + * @param {Buffer} buffer The encoded message. + * @param {(field: number, value: number | bigint | Buffer) => void} onField + * Called with the field number and the value of each field, in order. + * @throws {Error} If a field has a wire type other than varint and + * length-delimited, which pprof messages do not use. + */ +function decodeFields(buffer, onField) { + const state = { offset: 0 }; + while (state.offset < buffer.length) { + const tag = readVarint(buffer, state); + const field = Math.floor(tag / 8); + const wireType = tag % 8; + if (wireType === 0) { + onField(field, readVarint(buffer, state)); + } else if (wireType === 2) { + const length = readVarint(buffer, state); + onField(field, buffer.subarray(state.offset, state.offset + length)); + state.offset += length; + } else { + throw new Error(`Unexpected wire type ${wireType}`); + } + } +} + +/** + * Decodes the varints of a packed repeated field. + * @param {Buffer} buffer The payload of the field, without its tag and + * length. + * @returns {Array} The elements of the field. + */ +function decodePacked(buffer) { + const values = []; + const state = { offset: 0 }; + while (state.offset < buffer.length) { + values.push(readVarint(buffer, state)); + } + return values; +} + +/** + * Decodes a message according to `schema`, which maps property names to + * `{ field, repeated, packed, decode }`, where `field` is the field number and + * `decode` optionally decodes the raw value. Repeated properties default to + * `[]`, others to `0`, and unknown fields are ignored. + * @param {Buffer} buffer The encoded message, without its tag and length. + * @param {object} schema The properties to decode, each mapped to its + * `{ field, repeated, packed, decode }`. + * @returns {object} The message, with one property per property of + * `schema`. + * @throws {Error} If the message has a field with an unsupported wire type. + */ +function decodeMessage(buffer, schema) { + const message = {}; + for (const [name, { repeated }] of Object.entries(schema)) { + message[name] = repeated ? [] : 0; + } + const names = Object.keys(schema); + decodeFields(buffer, (field, value) => { + const name = names.find((n) => schema[n].field === field); + if (name === undefined) return; + const { decode, packed, repeated } = schema[name]; + if (packed) { + // Repeated scalars may be packed or not. + message[name].push(...(Buffer.isBuffer(value) ? decodePacked(value) : [value])); + } else if (repeated) { + message[name].push(decode ? decode(value) : value); + } else { + message[name] = decode ? decode(value) : value; + } + }); + return message; +} + +const valueTypeSchema = { + type: { field: 1 }, + unit: { field: 2 }, +}; +const lineSchema = { + functionId: { field: 1 }, + line: { field: 2 }, + column: { field: 3 }, +}; +const profileSchema = { + sampleType: { + field: 1, + repeated: true, + decode: (b) => decodeMessage(b, valueTypeSchema), + }, + sample: { + field: 2, + repeated: true, + decode: (b) => decodeMessage(b, { + locationId: { field: 1, packed: true, repeated: true }, + value: { field: 2, packed: true, repeated: true }, + }), + }, + location: { + field: 4, + repeated: true, + decode: (b) => decodeMessage(b, { + id: { field: 1 }, + line: { + field: 4, + repeated: true, + decode: (l) => decodeMessage(l, lineSchema), + }, + }), + }, + function: { + field: 5, + repeated: true, + decode: (b) => decodeMessage(b, { + id: { field: 1 }, + name: { field: 2 }, + systemName: { field: 3 }, + filename: { field: 4 }, + }), + }, + stringTable: { + field: 6, + repeated: true, + decode: (b) => b.toString('utf8'), + }, + timeNanos: { field: 9 }, + durationNanos: { field: 10 }, + periodType: { field: 11, decode: (b) => decodeMessage(b, valueTypeSchema) }, + period: { field: 12 }, + comment: { field: 13, packed: true, repeated: true }, +}; + +/** + * Decodes an uncompressed pprof Profile message. + * @param {Buffer} buffer The encoded Profile message. + * @returns {object} The fields of the profile, with the property names of + * `profile.proto`, and messages decoded into objects. + * @throws {Error} If the message has a field with an unsupported wire type. + */ +function decodeProfile(buffer) { + return decodeMessage(buffer, profileSchema); +} + +/** + * Decodes a gzip-compressed pprof profile, and resolves its samples into + * `{ stack, values }`, where `stack` lists the frames, leaf first, as + * `{ name, file, line }`, and `values` maps sample types to values. + * @param {Buffer} buffer The gzip-compressed encoding of a profile, as + * returned by `encode()` or `encodeSync()`. + * @returns {{ + * profile: object, + * strings: string[], + * sampleTypes: string[], + * samples: Array<{ stack: object[], values: object }>, + * }} The decoded profile, its string table, the names of its sample types, + * and its resolved samples. + * @throws {Error} If `buffer` is not gzip-compressed, or if the profile has a + * field with an unsupported wire type. + */ +function decodeGzippedProfile(buffer) { + const profile = decodeProfile(zlib.gunzipSync(buffer)); + const strings = profile.stringTable; + const functions = new Map(profile.function.map((f) => [f.id, f])); + const locations = new Map(profile.location.map((l) => [l.id, l])); + const sampleTypes = profile.sampleType.map((t) => strings[t.type]); + const samples = profile.sample.map((sample) => ({ + stack: sample.locationId.map((id) => { + const line = locations.get(id).line[0]; + const fn = functions.get(line.functionId); + return { + name: strings[fn.name], + file: strings[fn.filename], + line: line.line, + }; + }), + values: Object.fromEntries( + sampleTypes.map((type, i) => [type, sample.value[i] ?? 0])), + })); + return { profile, strings, sampleTypes, samples }; +} + +/** + * Keeps the thread busy until it has used `cpuMicros` microseconds of CPU + * time, so that profiles attribute samples to this function. Tests look for + * it in profiles by its name, `pprofTestBusyLoop`, and its file, this one. + * + * The loop is bounded by CPU time rather than wall time, so that it gets + * about as many samples on a loaded machine as on an idle one. V8 takes a + * sample by interrupting the thread, so a thread that the operating system + * does not run gets no samples. A loop bounded by wall time would run for + * less and less of that time as the load grows, and get fewer samples. + * + * The loop mostly runs plain JavaScript rather than builtins, because V8 can + * attribute the samples taken in a builtin to its caller. + * + * Optimized code that was compiled before a profiler started lacks the source + * positions that attribute samples to inlined functions, so tests that use + * this function prevent its optimization, with `--allow-natives-syntax` and + * `eval('%NeverOptimizeFunction(pprofTestBusyLoop)')`. + * @param {number} cpuMicros The CPU time to use, in microseconds. + * @returns {number} A value computed by the loop, so that it has an effect. + */ +function pprofTestBusyLoop(cpuMicros) { + const start = process.threadCpuUsage(); + let x = 0; + let used = 0; + while (used < cpuMicros) { + for (let i = 0; i < 100_000; i++) x = (x + i * i) % 1_000_003; + const { user, system } = process.threadCpuUsage(start); + used = user + system; + } + return x; +} + +module.exports = { + decodeGzippedProfile, + decodeProfile, + pprofTestBusyLoop, +}; diff --git a/test/fixtures/snapshot/perf-hooks-pprof.js b/test/fixtures/snapshot/perf-hooks-pprof.js new file mode 100644 index 000000000000..af6a4e59dac0 --- /dev/null +++ b/test/fixtures/snapshot/perf-hooks-pprof.js @@ -0,0 +1,6 @@ +'use strict'; + +// Entry point of a startup snapshot that starts the pprof time profiler, which +// must throw: see test/parallel/test-snapshot-perf-hooks-pprof.js. +const { time } = require('node:perf_hooks/pprof'); +time.start(); diff --git a/test/parallel/test-perf-hooks-pprof-coexist.js b/test/parallel/test-perf-hooks-pprof-coexist.js new file mode 100644 index 000000000000..4f16150729a0 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-coexist.js @@ -0,0 +1,82 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks that the time profiler works alongside the other CPU profilers: +// v8.startCpuProfile() and the inspector's Profiler domain. + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const assert = require('node:assert'); +const inspector = require('node:inspector'); +const v8 = require('node:v8'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +/** + * Asserts that a pprof profile contains samples of `pprofTestBusyLoop`. + * @param {object} profile A profile returned by `time.stop()`. + * @throws {AssertionError} If the profile has no samples of the function. + */ +function checkPprof(profile) { + const { samples } = decodeGzippedProfile(encodeSync(profile)); + assert.ok(samples.some(({ stack }) => + stack.some(({ name }) => name === 'pprofTestBusyLoop'))); +} + +/** + * Asserts that a V8 CPU profile contains a node of `pprofTestBusyLoop`. + * @param {object} cpuProfile A profile in the V8 CPU profile format. + * @throws {AssertionError} If the profile has no node of the function. + */ +function checkCpuProfile(cpuProfile) { + assert.ok(cpuProfile.nodes.some(({ callFrame }) => + callFrame.functionName === 'pprofTestBusyLoop')); +} + +const collectCpuTime = !common.isWindows; + +// v8.startCpuProfile() started before, and stopped before. +{ + const handle = v8.startCpuProfile(); + time.start({ collectCpuTime }); + pprofTestBusyLoop(200_000); + checkCpuProfile(JSON.parse(handle.stop())); + pprofTestBusyLoop(200_000); + checkPprof(time.stop()); +} + +// v8.startCpuProfile() started after, and stopped after. +{ + time.start({ collectCpuTime }); + const handle = v8.startCpuProfile(); + pprofTestBusyLoop(200_000); + checkPprof(time.stop(true)); + pprofTestBusyLoop(200_000); + checkPprof(time.stop()); + checkCpuProfile(JSON.parse(handle.stop())); +} + +// The inspector's profiler. +{ + const session = new inspector.Session(); + session.connect(); + session.post('Profiler.enable'); + session.post('Profiler.start', common.mustSucceed(() => { + time.start({ collectCpuTime }); + pprofTestBusyLoop(200_000); + session.post('Profiler.stop', common.mustSucceed(({ profile }) => { + checkCpuProfile(profile); + pprofTestBusyLoop(200_000); + checkPprof(time.stop()); + session.disconnect(); + })); + })); +} diff --git a/test/parallel/test-perf-hooks-pprof-encode.js b/test/parallel/test-perf-hooks-pprof-encode.js new file mode 100644 index 000000000000..a722621d7a62 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-encode.js @@ -0,0 +1,42 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks that profiles encode to the same gzip-compressed pprof protobuf +// message synchronously and asynchronously. + +const common = require('../common'); +const assert = require('node:assert'); +const zlib = require('node:zlib'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encode, encodeSync } = require('node:perf_hooks/pprof'); + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +time.start(); +pprofTestBusyLoop(100_000); +const profile = time.stop(); + +const encoded = encodeSync(profile); +assert.ok(Buffer.isBuffer(encoded)); +// gzip magic number. +assert.strictEqual(encoded[0], 0x1f); +assert.strictEqual(encoded[1], 0x8b); +assert.deepStrictEqual(zlib.gunzipSync(encoded), profile.encode()); + +const decoded = decodeGzippedProfile(encoded); +assert.strictEqual(decoded.strings[0], ''); +assert.ok(decoded.samples.some(({ stack }) => + stack.some(({ name }) => name === 'pprofTestBusyLoop'))); + +const promise = encode(profile); +assert.ok(promise instanceof Promise); +promise.then(async (asyncEncoded) => { + assert.ok(Buffer.isBuffer(asyncEncoded)); + assert.deepStrictEqual(zlib.gunzipSync(asyncEncoded), profile.encode()); + assert.deepStrictEqual(await profile.encodeAsync(), profile.encode()); +}).then(common.mustCall()); diff --git a/test/parallel/test-perf-hooks-pprof-exit.js b/test/parallel/test-perf-hooks-pprof-exit.js new file mode 100644 index 000000000000..3b0b519aa23c --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-exit.js @@ -0,0 +1,32 @@ +'use strict'; + +// Checks that processes exit cleanly while the time profiler runs. + +const common = require('../common'); +const { spawnSyncAndExitWithoutError } = require('../common/child_process'); + +const collectCpuTime = !common.isWindows; + +for (const exit of [ + // The event loop drains. + '', + // process.exit() is called. + 'process.exit(0);', + // process.exit() is called from a timer, while samples are taken. + 'setTimeout(() => process.exit(0), 50);', +]) { + for (const workaroundV8Bug of [true, false]) { + const script = ` + const { time } = require('node:perf_hooks/pprof'); + time.start(${JSON.stringify({ collectCpuTime, workaroundV8Bug })}); + const end = Date.now() + 100; + while (Date.now() < end); + ${exit} + `; + spawnSyncAndExitWithoutError(process.execPath, [ + '--no-warnings', + '-e', + script, + ]); + } +} diff --git a/test/parallel/test-perf-hooks-pprof-module.js b/test/parallel/test-perf-hooks-pprof-module.js new file mode 100644 index 000000000000..492ce3cf54ad --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-module.js @@ -0,0 +1,48 @@ +'use strict'; + +const common = require('../common'); +const assert = require('node:assert'); + +common.expectWarning( + 'ExperimentalWarning', + 'perf_hooks/pprof is an experimental feature and might change at any time'); + +assert.ok(!process.moduleLoadList.includes('NativeModule perf_hooks/pprof')); +// Loading node:perf_hooks does not load node:perf_hooks/pprof. +require('node:perf_hooks'); +assert.ok(!process.moduleLoadList.includes('NativeModule perf_hooks/pprof')); + +const pprof = require('node:perf_hooks/pprof'); +assert.strictEqual(require('perf_hooks/pprof'), pprof); +assert.strictEqual(process.getBuiltinModule('node:perf_hooks/pprof'), pprof); + +assert.deepStrictEqual(Object.keys(pprof).sort(), [ + 'encode', + 'encodeSync', + 'time', +]); +assert.strictEqual(typeof pprof.encode, 'function'); +assert.strictEqual(typeof pprof.encodeSync, 'function'); + +const { time } = pprof; +assert.ok(Object.isFrozen(time)); +assert.deepStrictEqual(Object.keys(time).sort(), [ + 'constants', + 'isStarted', + 'profile', + 'start', + 'stop', + 'v8ProfilerStuckEventLoopDetected', +]); +assert.ok(Object.isFrozen(time.constants)); +assert.deepStrictEqual({ ...time.constants }, { + GARBAGE_COLLECTION_FUNCTION_NAME: 'Garbage Collection', + NON_JS_THREADS_FUNCTION_NAME: 'Non JS threads activity', +}); +assert.strictEqual(time.isStarted(), false); +assert.strictEqual(time.v8ProfilerStuckEventLoopDetected(), 0); + +import('node:perf_hooks/pprof').then(common.mustCall((ns) => { + assert.strictEqual(ns.default, pprof); + assert.strictEqual(ns.time, time); +})); diff --git a/test/parallel/test-perf-hooks-pprof-protobuf.js b/test/parallel/test-perf-hooks-pprof-protobuf.js new file mode 100644 index 000000000000..2f83dce2750d --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-protobuf.js @@ -0,0 +1,167 @@ +// Flags: --expose-internals +'use strict'; + +// Checks the protobuf encoding of the pprof messages. + +const common = require('../common'); +const assert = require('node:assert'); +const { decodeProfile } = require('../common/pprof'); +const { + encodeNumber, + measureNumber, + varintLength, +} = require('internal/perf/pprof/protobuf'); +const { + Label, + Line, + Location, + Mapping, + Profile, + ProfileFunction, + Sample, + StringTable, + ValueType, +} = require('internal/perf/pprof/profile'); + +/** + * Formats bytes as a hexadecimal string. + * @param {Buffer | Uint8Array | number[]} bytes The bytes to format. + * @returns {string} Two hexadecimal digits per byte, without separators. + */ +function hex(bytes) { + return Buffer.from(bytes).toString('hex'); +} + +// Varints. +for (const { number, encoded } of [ + { number: 0, encoded: '00' }, + { number: 1, encoded: '01' }, + { number: 127, encoded: '7f' }, + { number: 128, encoded: '8001' }, + { number: 300, encoded: 'ac02' }, + { number: 16384, encoded: '808001' }, + { number: 2 ** 32 - 1, encoded: 'ffffffff0f' }, + { number: 2 ** 32, encoded: '8080808010' }, + { number: Number.MAX_SAFE_INTEGER, encoded: 'ffffffffffffff0f' }, + { number: 2n ** 63n, encoded: '80808080808080808001' }, + { number: 2n ** 64n - 1n, encoded: 'ffffffffffffffffff01' }, + // Negative numbers are encoded as 64-bit two's complement. + { number: -1, encoded: 'ffffffffffffffffff01' }, + { number: -1n, encoded: 'ffffffffffffffffff01' }, + { number: -2, encoded: 'feffffffffffffffff01' }, +]) { + const buffer = new Uint8Array(10); + const end = encodeNumber(buffer, 0, number); + assert.strictEqual(hex(buffer.subarray(0, end)), encoded, `${number}`); + assert.strictEqual(varintLength(number), encoded.length / 2, `${number}`); + const isZero = number === 0; + assert.strictEqual(measureNumber(number), isZero ? 0 : encoded.length / 2); +} + +// Default values are omitted. +for (const message of [ + new ValueType({}), + new Label({}), + new Line({}), + new Mapping({}), + new ProfileFunction({}), + new Location({}), + new Sample({}), +]) { + assert.strictEqual(message.encode().length, 0); +} + +assert.strictEqual(hex(new ValueType({ type: 1, unit: 2 }).encode()), + '08011002'); +assert.strictEqual(hex(new Mapping({ id: 1, hasFunctions: true }).encode()), + '08013801'); +// Packed repeated fields keep zeros, to preserve indices. +const locationId = [ + 1, + 0, + 300, +]; +assert.strictEqual(hex(new Sample({ locationId }).encode()), '0a040100ac02'); +// Sub-messages are length-delimited. +assert.strictEqual( + hex(new Location({ id: 1, line: [{ functionId: 2, line: 3 }] }).encode()), + '0801220408021003'); + +// The string table starts with the empty string, and deduplicates strings. +{ + const table = new StringTable(); + assert.strictEqual(table.dedup(''), 0); + assert.strictEqual(table.dedup('a'), 1); + assert.strictEqual(table.dedup('€'), 2); + assert.strictEqual(table.dedup('a'), 1); + assert.deepStrictEqual(table.strings, [ + '', + 'a', + '€', + ]); + assert.strictEqual(hex(new Profile({ stringTable: table }).encode()), + '32003201613203e282ac'); +} + +// A whole profile round-trips through an independent decoder. +{ + const stringTable = new StringTable(); + const wall = { + type: stringTable.dedup('wall'), + unit: stringTable.dedup('nanoseconds'), + }; + const profile = new Profile({ + sampleType: [ + { type: stringTable.dedup('sample'), unit: stringTable.dedup('count') }, + wall, + ], + sample: [ + { locationId: [2, 1], value: [3, 3000000] }, + { locationId: [1], value: [0, 0] }, + ], + location: [ + { id: 1, line: [{ functionId: 1, line: 10 }] }, + { id: 2, line: [{ functionId: 2, line: 20 }] }, + ], + function: [ + { + id: 1, + name: stringTable.dedup('outer'), + filename: stringTable.dedup('a.js'), + }, + { + id: 2, + name: stringTable.dedup('inner'), + filename: stringTable.dedup('a.js'), + }, + ], + stringTable, + timeNanos: 1700000000000000000, + durationNanos: 2 ** 40, + periodType: wall, + period: 1000000, + }); + const encoded = profile.encode(); + assert.ok(Buffer.isBuffer(encoded)); + + const decoded = decodeProfile(encoded); + assert.deepStrictEqual(decoded.stringTable, stringTable.strings); + assert.deepStrictEqual(decoded.sampleType, [ + { type: 3, unit: 4 }, + { type: 1, unit: 2 }, + ]); + assert.deepStrictEqual(decoded.sample, [ + { locationId: [2, 1], value: [3, 3000000] }, + { locationId: [1], value: [0, 0] }, + ]); + assert.deepStrictEqual(decoded.location.map((l) => l.line[0].line), [10, 20]); + assert.deepStrictEqual(decoded.function.map((f) => f.name), [5, 7]); + assert.strictEqual(BigInt(decoded.timeNanos), 1700000000000000000n); + assert.strictEqual(decoded.durationNanos, 2 ** 40); + assert.deepStrictEqual(decoded.periodType, { type: 1, unit: 2 }); + assert.strictEqual(decoded.period, 1000000); + + profile.encodeAsync().then(common.mustCall((asyncEncoded) => { + assert.deepStrictEqual(asyncEncoded, encoded); + })); +} diff --git a/test/parallel/test-perf-hooks-pprof-serializer.js b/test/parallel/test-perf-hooks-pprof-serializer.js new file mode 100644 index 000000000000..3c420d2a2239 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-serializer.js @@ -0,0 +1,210 @@ +// Flags: --expose-internals +'use strict'; + +// Checks how time profiles produced by the pprof binding are normalized and +// serialized, with synthetic profiles. + +require('../common'); +const assert = require('node:assert'); +const { decodeGzippedProfile } = require('../common/pprof'); +const { encodeSync } = require('node:perf_hooks/pprof'); +const { + serializeTimeProfile, +} = require('internal/perf/pprof/serializer'); +const { + frameFunctionName, +} = require('internal/perf/pprof/normalizer'); + +/** + * Builds a profile in the format of the `pprof` binding from nodes, in + * pre-order, root first. + * @param {object[]} nodes Nodes with `parent`, `name`, `file`, `scriptId`, + * `line`, `column`, `hits` and `cpu` properties, all optional. + * @param {object} [extra] Properties that override those of the profile. + * @returns {object} The profile, as the binding's `stop()` returns it. + */ +function makeProfile(nodes, extra = {}) { + const hasCpuTime = extra.hasCpuTime ?? false; + /** + * Returns the values of a property of the nodes. + * @param {string} key The name of the property. + * @param {any} defaultValue The value of nodes without the property. + * @returns {any[]} The value of the property for each node, in order. + */ + const column = (key, defaultValue) => + nodes.map((node) => node[key] ?? defaultValue); + const hitCount = new Uint32Array(column('hits', 0)); + return { + startTime: 1000, + endTime: 1000 + 10000, + epochOffset: 1_700_000_000_000_000, + hasCpuTime, + nonJSThreadsCpuTime: 0, + totalHitCount: hitCount.reduce((a, b) => a + b, 0), + restarted: false, + parent: new Int32Array(column('parent', 0)), + name: column('name', ''), + scriptName: column('file', ''), + scriptId: new Int32Array(column('scriptId', 0)), + lineNumber: new Int32Array(column('line', 0)), + columnNumber: new Int32Array(column('column', 0)), + hitCount, + cpuTime: hasCpuTime ? new Float64Array(column('cpu', 0)) : undefined, + ...extra, + }; +} + +const root = { parent: -1, name: '(root)' }; + +/** + * Serializes a binding profile, encodes it, and decodes the result. + * @param {object} profile A profile returned by `makeProfile()`. + * @param {number} [intervalMicros] The sampling interval. + * @param {boolean} [recompute] Whether to recompute the sampling interval. + * @returns {object} The result of `decodeGzippedProfile()`. + */ +function decode(profile, intervalMicros = 1000, recompute = false) { + return decodeGzippedProfile( + encodeSync(serializeTimeProfile(profile, intervalMicros, recompute))); +} + +/** + * Replaces the frames of decoded samples with their names. + * @param {object[]} samples Samples returned by `decodeGzippedProfile()`. + * @returns {Array<{ stack: string[], values: object }>} The samples, with + * the names of their frames, leaf first, and their values. + */ +function stacks(samples) { + return samples.map(({ stack, values }) => ({ + stack: stack.map(({ name }) => name), + values, + })); +} + +// Without CPU time. +{ + const main = { file: 'file:///app/main.mjs', scriptId: 1 }; + const profile = makeProfile([ + root, + { name: '(program)', hits: 5 }, + { name: '(idle)', hits: 3 }, + { name: '(garbage collector)', hits: 2 }, + { ...main, name: 'main', line: 1, column: 1 }, + { ...main, parent: 4, name: 'work', line: 5, column: 10, hits: 4 }, + { ...main, parent: 4, name: '', line: 9, column: 3, hits: 1 }, + // A child of `(program)` is removed with it. + { parent: 1, name: 'removed', hits: 7 }, + ]); + const { samples, profile: decoded, strings, sampleTypes } = decode(profile); + assert.deepStrictEqual(sampleTypes, ['sample', 'wall']); + assert.strictEqual(decoded.period, 1000000); + assert.strictEqual(decoded.durationNanos, 10000 * 1000); + // The start time of the profile, since the epoch, rounded to a double. + assert.strictEqual(BigInt(decoded.timeNanos), + BigInt(Number((1_700_000_000_000_000n + 1000n) * 1000n))); + assert.deepStrictEqual(stacks(samples), [ + { + stack: ['Garbage Collection', 'Node.js'], + values: { sample: 2, wall: 2000000 }, + }, + { + stack: ['work', 'main'], + values: { sample: 4, wall: 4000000 }, + }, + { + stack: ['(anonymous:L#9:C#3)', 'main'], + values: { sample: 1, wall: 1000000 }, + }, + ]); + // file:// prefixes are removed. + assert.ok(strings.includes('/app/main.mjs')); + assert.ok(!strings.some((s) => s.startsWith('file://'))); +} + +// With CPU time. +{ + const main = { file: '/app/main.js', scriptId: 1 }; + const profile = makeProfile([ + root, + { name: '(program)', hits: 1 }, + { name: '(idle)', hits: 3, cpu: 500 }, + { ...main, name: 'main', line: 1, column: 1 }, + { ...main, parent: 3, name: 'work', line: 5, column: 10, hits: 4, cpu: 4000 }, + ], { hasCpuTime: true, nonJSThreadsCpuTime: 700 }); + const { samples, sampleTypes } = decode(profile); + assert.deepStrictEqual(sampleTypes, [ + 'sample', + 'wall', + 'cpu', + ]); + assert.deepStrictEqual(stacks(samples), [ + // `(idle)` gets no wall time, but keeps its CPU time. + { + stack: ['(idle)'], + values: { sample: 3, wall: 0, cpu: 500 }, + }, + { + stack: ['work', 'main'], + values: { sample: 4, wall: 4000000, cpu: 4000 }, + }, + { + stack: ['Non JS threads activity', 'Node.js'], + values: { sample: 0, wall: 0, cpu: 700 }, + }, + ]); +} + +// Frames with the same position share a location and a function, and +// functions with the same name in the same script share a function. +{ + const main = { file: '/app/main.js', scriptId: 1, column: 1, hits: 1 }; + const profile = makeProfile([ + root, + { ...main, name: 'a', line: 1 }, + { ...main, parent: 1, name: 'b', line: 2 }, + { ...main, name: 'b', line: 2 }, + { ...main, name: 'b', line: 3 }, + ]); + const { profile: decoded } = decode(profile); + assert.strictEqual(decoded.location.length, 3); + assert.strictEqual(decoded.function.length, 2); + assert.strictEqual(decoded.sample.length, 4); +} + +// The sampling interval is recomputed from the duration and the hit count, +// within [interval, 2 * interval]. +{ + const rows = [ + root, + { name: 'a', file: '/app/main.js', scriptId: 1, line: 1, hits: 8 }, + ]; + // 10000us for 8 hits. + assert.strictEqual(decode(makeProfile(rows), 1000, true).profile.period, + 1250000); + assert.strictEqual(decode(makeProfile(rows), 1000, false).profile.period, + 1000000); + assert.strictEqual(decode(makeProfile(rows), 5000, true).profile.period, + 5000000); + assert.strictEqual(decode(makeProfile(rows), 500, true).profile.period, + 1000000); +} + +// Without an epoch offset, the start time is estimated from the current time. +{ + const before = BigInt(Date.now()) * 1000000n; + const profile = makeProfile([root], { + epochOffset: undefined, + }); + const { profile: decoded } = decode(profile); + const after = BigInt(Date.now()) * 1000000n; + const timeNanos = BigInt(decoded.timeNanos); + assert.ok(timeNanos >= before - 10000n * 1000n - 1000000n); + assert.ok(timeNanos <= after); +} + +assert.strictEqual(frameFunctionName({ name: 'f' }), 'f'); +assert.strictEqual(frameFunctionName({ name: '', line: 3, column: 4 }), + '(anonymous:L#3:C#4)'); +assert.strictEqual(frameFunctionName({ name: '', line: 3 }), + '(anonymous:L#3)'); +assert.strictEqual(frameFunctionName({ name: '' }), '(anonymous)'); diff --git a/test/parallel/test-perf-hooks-pprof-time-cpu.js b/test/parallel/test-perf-hooks-pprof-time-cpu.js new file mode 100644 index 000000000000..f4aa82616fc8 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-cpu.js @@ -0,0 +1,100 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks the CPU time that the time profiler attributes to samples. + +const common = require('../common'); +if (common.isWindows) { + common.skip('CPU time collection relies on SIGPROF'); +} + +const assert = require('node:assert'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +// The CPU time that each profile spends in `pprofTestBusyLoop`. +const loopCpuMicros = 300_000; + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +/** + * Returns the CPU time that the current thread used since `previous`. + * @param {{ user: number, system: number }} previous A value returned by + * `process.threadCpuUsage()`. + * @returns {number} The CPU time, in nanoseconds. + */ +function threadCpuNanosSince(previous) { + const { user, system } = process.threadCpuUsage(previous); + return (user + system) * 1000; +} + +/** + * Asserts that a profile reports CPU time, and that the profiled thread and + * the threads that do not run JavaScript account for it as expected. + * @param {object} profile A profile returned by `time.stop()`. + * @param {number} maxThreadCpuNanos The CPU time that the thread used while + * the profile was collected, and more: the profile cannot attribute more. + * @throws {AssertionError} If the profile does not report CPU time as + * expected. + */ +function check(profile, maxThreadCpuNanos) { + const { sampleTypes, samples } = decodeGzippedProfile(encodeSync(profile)); + assert.deepStrictEqual(sampleTypes, [ + 'sample', + 'wall', + 'cpu', + ]); + // The CPU time of the profiled thread is attributed to its samples. Which + // frame of a stack a sample is attributed to depends on V8's sampler, + // which attributes some of the samples of a function to its caller, more + // so when the machine is loaded, so the CPU time of the thread is checked + // as a whole, and the loop's frame only has to get some of it. + let threadCpu = 0; + let loopCpu = 0; + for (const { stack, values } of samples) { + assert.ok(values.cpu >= 0); + if (stack[0].name === 'Non JS threads activity') { + assert.strictEqual(stack.length, 2); + assert.strictEqual(stack[1].name, 'Node.js'); + assert.strictEqual(values.sample, 0); + assert.strictEqual(values.wall, 0); + assert.ok(values.cpu > 0); + continue; + } + threadCpu += values.cpu; + if (stack.some(({ name }) => name === 'pprofTestBusyLoop')) { + loopCpu += values.cpu; + } + } + // The loop alone uses `loopCpuMicros` of CPU time. A few samples can miss + // their CPU time, e.g. the last ones before the profile stops. + assert.ok(threadCpu >= loopCpuMicros * 1000 * 0.8, + `${threadCpu} < 80% of ${loopCpuMicros * 1000}`); + // `process.threadCpuUsage()` and the profiler can read the CPU time of the + // thread from different clocks, which can disagree slightly. + const maxCpu = maxThreadCpuNanos * 1.1 + 10e6; + assert.ok(threadCpu <= maxCpu, `${threadCpu} > ${maxCpu}`); + assert.ok(loopCpu > 0); +} + +for (const workaroundV8Bug of [true, false]) { + // The duration sizes the buffer that CPU time is attributed with: make it + // large enough for the loop to run on a loaded machine. + let before = process.threadCpuUsage(); + time.start({ collectCpuTime: true, durationMillis: 30_000, workaroundV8Bug }); + pprofTestBusyLoop(loopCpuMicros); + const restarted = process.threadCpuUsage(); + const first = time.stop(true); + const firstMax = threadCpuNanosSince(before); + before = restarted; + pprofTestBusyLoop(loopCpuMicros); + const second = time.stop(); + const secondMax = threadCpuNanosSince(before); + check(first, firstMax); + check(second, secondMax); +} diff --git a/test/parallel/test-perf-hooks-pprof-time-line-numbers.js b/test/parallel/test-perf-hooks-pprof-time-line-numbers.js new file mode 100644 index 000000000000..f2af3bc94212 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-line-numbers.js @@ -0,0 +1,56 @@ +'use strict'; + +// Checks that the time profiler can aggregate samples at the line level. + +require('../common'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +/** + * Returns the lines of a file. + * @param {string} file The path of the file. + * @returns {string[]} The lines of the file, without their line terminators. + */ +function readLines(file) { + return fs.readFileSync(file, 'utf8').split(/\r?\n/); +} + +// The first and last lines of pprofTestBusyLoop, from the source of its +// module, and the line of its call, from the source of this test. +const loopFile = require.resolve('../common/pprof'); +const loopLines = readLines(loopFile); +const functionLine = + loopLines.indexOf('function pprofTestBusyLoop(cpuMicros) {') + 1; +const functionEndLine = + functionLine + loopLines.slice(functionLine).indexOf('}') + 1; +const callLine = readLines(__filename).indexOf('pprofTestBusyLoop(300_000);') + 1; +assert.ok(functionLine > 0); +assert.ok(functionEndLine > functionLine); +assert.ok(callLine > 0); + +time.start({ lineNumbers: true }); +pprofTestBusyLoop(300_000); +const { samples } = decodeGzippedProfile(encodeSync(time.stop())); + +const leaves = samples + .map(({ stack }) => stack[0]) + .filter(({ name }) => name === 'pprofTestBusyLoop'); +assert.ok(leaves.length > 0); +// Samples in the body of the function are at lines after its first one. +for (const { line, file } of leaves) { + assert.strictEqual(file, loopFile); + assert.ok(line > functionLine, `${line}`); + assert.ok(line <= functionEndLine, `${line}`); +} + +// In caller line number mode, the line of a non-leaf frame is the line of the +// call it makes, e.g. `callLine` for the frame that calls pprofTestBusyLoop. +const callers = samples + .filter(({ stack }) => stack[0].name === 'pprofTestBusyLoop') + .map(({ stack }) => stack[1]); +assert.ok(callers.some(({ line }) => line === callLine), `${callLine}`); diff --git a/test/parallel/test-perf-hooks-pprof-time-profile.js b/test/parallel/test-perf-hooks-pprof-time-profile.js new file mode 100644 index 000000000000..59ce74a230b1 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-profile.js @@ -0,0 +1,81 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks the content of the time profiles that node:perf_hooks/pprof +// collects. + +require('../common'); +const assert = require('node:assert'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +const intervalMicros = 1000; +const startNanos = BigInt(Date.now()) * 1000000n; +time.start({ intervalMicros }); +pprofTestBusyLoop(500_000); +const profile = time.stop(); +const endNanos = BigInt(Date.now()) * 1000000n; +assert.strictEqual(time.isStarted(), false); + +const { strings, sampleTypes, samples, profile: decoded } = + decodeGzippedProfile(encodeSync(profile)); + +assert.deepStrictEqual(sampleTypes, ['sample', 'wall']); +assert.deepStrictEqual(decoded.sampleType.map((t) => strings[t.unit]), [ + 'count', + 'nanoseconds', +]); +assert.strictEqual(strings[decoded.periodType.type], 'wall'); +assert.strictEqual(strings[decoded.periodType.unit], 'nanoseconds'); +// The period is the recomputed sampling interval, which is bounded to +// [interval, 2 * interval]. +assert.ok(decoded.period >= intervalMicros * 1000, `${decoded.period}`); +assert.ok(decoded.period <= intervalMicros * 2000, `${decoded.period}`); + +// The profile starts within the collection period. +const timeNanos = BigInt(decoded.timeNanos); +const slackNanos = 50n * 1000000n; +assert.ok(timeNanos >= startNanos - slackNanos, `${timeNanos} ${startNanos}`); +assert.ok(timeNanos <= endNanos, `${timeNanos} ${endNanos}`); +assert.ok(decoded.durationNanos > 0); +assert.ok(BigInt(decoded.durationNanos) <= endNanos - startNanos + slackNanos); + +assert.ok(samples.length > 0); +for (const { stack, values } of samples) { + assert.ok(stack.length > 0); + // `(program)` and `(idle)` samples are removed. + for (const frame of stack) { + assert.notStrictEqual(frame.name, '(program)'); + assert.notStrictEqual(frame.name, '(idle)'); + assert.notStrictEqual(frame.name, '(root)'); + } + assert.ok(values.sample > 0); + assert.strictEqual(values.wall, values.sample * decoded.period); +} + +// The busy loop is in the profile. +const busySamples = samples.filter(({ stack }) => + stack.some(({ name }) => name === 'pprofTestBusyLoop')); +assert.ok(busySamples.length > 0); +const busyFrame = busySamples[0].stack.find( + ({ name }) => name === 'pprofTestBusyLoop'); +assert.strictEqual(busyFrame.file, require.resolve('../common/pprof')); +// The share of the samples that the busy loop's own frame gets is not +// checked: V8's sampler attributes some of the samples of a function to its +// callers, more so when the machine is loaded. + +// Garbage collection is reported under a Node.js frame. +for (const { stack } of samples) { + const index = stack.findIndex(({ name }) => name === 'Garbage Collection'); + if (index !== -1) { + assert.strictEqual(index, stack.length - 2); + assert.strictEqual(stack.at(-1).name, 'Node.js'); + } +} diff --git a/test/parallel/test-perf-hooks-pprof-time-recovery.js b/test/parallel/test-perf-hooks-pprof-time-recovery.js new file mode 100644 index 000000000000..af79467a93a2 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-recovery.js @@ -0,0 +1,60 @@ +// Flags: --expose-internals +'use strict'; + +// Checks how `time.stop(true)` recovers when it finds V8's CPU profiler +// stuck. A stuck profiler cannot be produced on demand, so the binding reports +// one. + +require('../common'); +const assert = require('node:assert'); +const { internalBinding } = require('internal/test/binding'); +const { time } = require('node:perf_hooks/pprof'); + +const { prototype } = internalBinding('pprof').WallProfiler; +const { start, v8ProfilerStuckEventLoopDetected } = prototype; + +/** + * Calls `time.stop(true)` while the binding reports V8's CPU profiler as + * stuck, and while `startOverride`, if any, replaces the binding's `start()`. + * @param {Function} [startOverride] A replacement for the binding's + * `start()`, used to make the restart fail. + * @returns {object} The profile that `time.stop(true)` returns. + */ +function stopAndRestartStuckProfiler(startOverride) { + prototype.v8ProfilerStuckEventLoopDetected = () => 2; + if (startOverride !== undefined) { + prototype.start = startOverride; + } + try { + return time.stop(true); + } finally { + prototype.v8ProfilerStuckEventLoopDetected = + v8ProfilerStuckEventLoopDetected; + prototype.start = start; + } +} + +// The profiler is restarted with a new V8 CPU profiler. +time.start(); +let profile = stopAndRestartStuckProfiler(); +assert.strictEqual(typeof profile.encode, 'function'); +assert.strictEqual(time.isStarted(), true); +assert.strictEqual(time.v8ProfilerStuckEventLoopDetected(), 2); +time.stop(); +assert.strictEqual(time.isStarted(), false); + +// When restarting fails, the profile is still returned, and the profiler is +// stopped. +time.start(); +profile = stopAndRestartStuckProfiler(() => { + throw new Error('start failed'); +}); +assert.strictEqual(typeof profile.encode, 'function'); +assert.strictEqual(time.isStarted(), false); +assert.strictEqual(time.v8ProfilerStuckEventLoopDetected(), 0); +assert.throws(() => time.stop(), { code: 'ERR_INVALID_STATE' }); + +// The profiler can be started again. +time.start(); +assert.strictEqual(time.isStarted(), true); +time.stop(); diff --git a/test/parallel/test-perf-hooks-pprof-time-restart.js b/test/parallel/test-perf-hooks-pprof-time-restart.js new file mode 100644 index 000000000000..08a82c2b7ec1 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-restart.js @@ -0,0 +1,39 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks that profiles can be collected repeatedly by restarting the +// profiler, with and without the V8 bug workaround. + +require('../common'); +const assert = require('node:assert'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +for (const workaroundV8Bug of [true, false]) { + time.start({ intervalMicros: 1000, durationMillis: 100, workaroundV8Bug }); + let previousTimeNanos = 0; + for (let i = 0; i < 5; i++) { + pprofTestBusyLoop(100_000); + const profile = time.stop(true); + assert.strictEqual(time.isStarted(), true); + const stuck = time.v8ProfilerStuckEventLoopDetected(); + assert.ok(stuck >= 0 && stuck <= 2, `${stuck}`); + + const { samples, profile: decoded } = + decodeGzippedProfile(encodeSync(profile)); + assert.ok(decoded.timeNanos > previousTimeNanos); + previousTimeNanos = decoded.timeNanos; + assert.ok(samples.some(({ stack }) => + stack.some(({ name }) => name === 'pprofTestBusyLoop'))); + } + time.stop(); + assert.strictEqual(time.isStarted(), false); + assert.strictEqual(time.v8ProfilerStuckEventLoopDetected(), 0); +} diff --git a/test/parallel/test-perf-hooks-pprof-time-validation.js b/test/parallel/test-perf-hooks-pprof-time-validation.js new file mode 100644 index 000000000000..dc599826ac51 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-time-validation.js @@ -0,0 +1,73 @@ +'use strict'; + +const common = require('../common'); +const assert = require('node:assert'); +const { time, encode, encodeSync } = require('node:perf_hooks/pprof'); + +for (const options of [null, 1, 'string', true]) { + assert.throws(() => time.start(options), { code: 'ERR_INVALID_ARG_TYPE' }); +} + +for (const intervalMicros of ['1', true]) { + assert.throws(() => time.start({ intervalMicros }), { + code: 'ERR_INVALID_ARG_TYPE', + }); +} +for (const intervalMicros of [1.5, 0, -1, 2 ** 31]) { + assert.throws(() => time.start({ intervalMicros }), { + code: 'ERR_OUT_OF_RANGE', + }); +} + +for (const durationMillis of ['1', true]) { + assert.throws(() => time.start({ durationMillis }), { + code: 'ERR_INVALID_ARG_TYPE', + }); +} +for (const durationMillis of [1.5, 0, -1, 2 ** 31]) { + assert.throws(() => time.start({ durationMillis }), { + code: 'ERR_OUT_OF_RANGE', + }); +} +// The duration must not be shorter than the interval. +assert.throws(() => time.start({ intervalMicros: 5000, durationMillis: 4 }), { + code: 'ERR_OUT_OF_RANGE', +}); + +for (const name of ['lineNumbers', 'collectCpuTime', 'workaroundV8Bug']) { + assert.throws(() => time.start({ [name]: 1 }), { + code: 'ERR_INVALID_ARG_TYPE', + }); +} + +if (common.isWindows) { + assert.throws(() => time.start({ collectCpuTime: true }), { + code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM', + }); +} else { + assert.throws(() => time.start({ collectCpuTime: true, lineNumbers: true }), { + code: 'ERR_INCOMPATIBLE_OPTION_PAIR', + }); +} + +assert.strictEqual(time.isStarted(), false); + +assert.throws(() => time.stop(), { code: 'ERR_INVALID_STATE' }); +assert.throws(() => time.stop(true), { code: 'ERR_INVALID_STATE' }); + +time.start(); +assert.strictEqual(time.isStarted(), true); +assert.throws(() => time.start(), { code: 'ERR_INVALID_STATE' }); +assert.throws(() => time.stop('true'), { code: 'ERR_INVALID_ARG_TYPE' }); +time.stop(); +assert.strictEqual(time.isStarted(), false); + +for (const profile of [undefined, null, {}, Buffer.alloc(0)]) { + assert.throws(() => encodeSync(profile), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.rejects(encode(profile), { code: 'ERR_INVALID_ARG_TYPE' }) + .then(common.mustCall()); +} + +assert.rejects(time.profile({ signal: 'signal' }), { + code: 'ERR_INVALID_ARG_TYPE', +}).then(common.mustCall()); diff --git a/test/parallel/test-perf-hooks-pprof-worker.js b/test/parallel/test-perf-hooks-pprof-worker.js new file mode 100644 index 000000000000..b4c4c81610c1 --- /dev/null +++ b/test/parallel/test-perf-hooks-pprof-worker.js @@ -0,0 +1,84 @@ +// Flags: --allow-natives-syntax +'use strict'; + +// Checks that the time profiler runs in the main thread and in workers at the +// same time, including when workers are terminated while profiling. + +const common = require('../common'); +const assert = require('node:assert'); +const { once } = require('node:events'); +const { Worker, isMainThread, parentPort } = require('node:worker_threads'); +const { + decodeGzippedProfile, + pprofTestBusyLoop, +} = require('../common/pprof'); +const { time, encodeSync } = require('node:perf_hooks/pprof'); + +// Profiles lack inlined frames of optimized code that was compiled before the +// profiler started: see pprofTestBusyLoop() in test/common/pprof.js. +eval('%NeverOptimizeFunction(pprofTestBusyLoop)'); + +const collectCpuTime = !common.isWindows; + +/** + * Profiles `pprofTestBusyLoop` on the current thread, and asserts that the + * profile contains samples of it. + * @throws {AssertionError} If the profile has no samples of the function. + */ +function profileLoop() { + // The duration sizes the buffer that CPU time is attributed with: make it + // large enough for the loop to run on a loaded machine. + time.start({ collectCpuTime, durationMillis: 30_000 }); + pprofTestBusyLoop(200_000); + const { samples } = decodeGzippedProfile(encodeSync(time.stop())); + assert.ok(samples.some(({ stack }) => + stack.some(({ name }) => name === 'pprofTestBusyLoop'))); +} + +if (!isMainThread) { + if (process.argv[2] === 'terminate') { + time.start({ collectCpuTime }); + parentPort.postMessage('started'); + // Keep sampling until terminated. + for (;;) pprofTestBusyLoop(10_000); + } + profileLoop(); + parentPort.postMessage('done'); + return; +} + +// Workers that profile and stop normally, alongside the main thread. +for (let i = 0; i < 2; i++) { + const worker = new Worker(__filename); + worker.on('message', common.mustCall((message) => { + assert.strictEqual(message, 'done'); + })); + worker.on('exit', common.mustCall((code) => assert.strictEqual(code, 0))); +} +profileLoop(); + +// Workers that are terminated while profiling. +/** + * Terminates workers while they are profiling, `count` at a time, `rounds` + * times. + * @param {number} rounds The number of times to start and terminate + * workers. + * @param {number} count The number of workers to run at the same time. + * @returns {Promise} Resolves once all the workers were terminated. + * @throws {Error} Rejects if a worker sends another message than `started`. + */ +async function terminateWhileProfiling(rounds, count) { + for (let round = 0; round < rounds; round++) { + await Promise.all(Array.from({ length: count }, async () => { + const worker = new Worker(__filename, { argv: ['terminate'] }); + const [message] = await once(worker, 'message'); + if (message !== 'started') throw new Error(`Unexpected ${message}`); + await worker.terminate(); + })); + } +} + +terminateWhileProfiling(3, 5).then(common.mustCall(() => { + // The main thread can still profile afterwards. + profileLoop(); +})); diff --git a/test/parallel/test-snapshot-perf-hooks-pprof.js b/test/parallel/test-snapshot-perf-hooks-pprof.js new file mode 100644 index 000000000000..15b1619e321e --- /dev/null +++ b/test/parallel/test-snapshot-perf-hooks-pprof.js @@ -0,0 +1,30 @@ +'use strict'; + +// Checks that the pprof time profiler cannot be started while building a +// startup snapshot. + +require('../common'); +const assert = require('node:assert'); +const { spawnSync } = require('node:child_process'); +const tmpdir = require('../common/tmpdir'); +const fixtures = require('../common/fixtures'); +const fs = require('node:fs'); + +tmpdir.refresh(); +const blobPath = tmpdir.resolve('snapshot.blob'); +const entry = fixtures.path('snapshot', 'perf-hooks-pprof.js'); +const child = spawnSync(process.execPath, [ + '--snapshot-blob', + blobPath, + '--build-snapshot', + entry, +], { + cwd: tmpdir.path, +}); +const stderr = child.stderr.toString(); +assert.match( + stderr, + /Starting the pprof time profiler is not supported in startup snapshot/); +assert.match(stderr, /ERR_NOT_SUPPORTED_IN_SNAPSHOT/); +assert.strictEqual(child.status, 1); +assert(!fs.existsSync(blobPath)); diff --git a/tools/license-builder.sh b/tools/license-builder.sh index 852bfca8c96b..5850815a54da 100755 --- a/tools/license-builder.sh +++ b/tools/license-builder.sh @@ -154,4 +154,13 @@ addlicense "on-exit-leak-free" "lib/internal/process/finalization" "$licenseText licenseText="$(curl -sL https://raw.githubusercontent.com/pinojs/sonic-boom/refs/heads/master/LICENSE)" addlicense "sonic-boom" "lib/internal/streams/fast-utf8-stream.js" "$licenseText" +licenseText="$(curl -sL https://raw.githubusercontent.com/DataDog/pprof-nodejs/3905f382723fc2554284e1abbba2df0f2dc6f82b/LICENSE)" +addlicense "pprof-nodejs" "src/node_pprof.cc, src/node_pprof.h, src/pprof, lib/internal/perf/pprof" "$licenseText" + +# The LICENSE file of pprof-format ends with a stray "Footer" line. +licenseText="$(curl -sL https://raw.githubusercontent.com/DataDog/pprof-format/53548398f38b16eb096cc04a75927316a68a9b54/LICENSE | sed '/^Footer$/d') + +$(curl -sL https://raw.githubusercontent.com/DataDog/pprof-format/53548398f38b16eb096cc04a75927316a68a9b54/NOTICE)" +addlicense "pprof-format" "lib/internal/perf/pprof/profile.js, lib/internal/perf/pprof/protobuf.js, lib/internal/perf/pprof/string_table.js" "$licenseText" + mv "$tmplicense" "$licensefile" diff --git a/typings/globals.d.ts b/typings/globals.d.ts index 4a7c52ab7744..955a5c68cada 100644 --- a/typings/globals.d.ts +++ b/typings/globals.d.ts @@ -28,6 +28,7 @@ import { OptionsBinding } from './internalBinding/options'; import { OSBinding } from './internalBinding/os'; import { PerformanceBinding } from './internalBinding/performance'; import { PermissionBinding } from './internalBinding/permission'; +import { PprofBinding } from './internalBinding/pprof'; import { ProcessBinding } from './internalBinding/process'; import { ProcessWrapBinding } from './internalBinding/process_wrap'; import { ProfilerBinding } from './internalBinding/profiler'; @@ -82,6 +83,7 @@ interface InternalBindingMap { os: OSBinding; performance: PerformanceBinding; permission: PermissionBinding; + pprof: PprofBinding; process: ProcessBinding; process_wrap: ProcessWrapBinding; profiler: ProfilerBinding; diff --git a/typings/internalBinding/pprof.d.ts b/typings/internalBinding/pprof.d.ts new file mode 100644 index 000000000000..ccb2d46403f5 --- /dev/null +++ b/typings/internalBinding/pprof.d.ts @@ -0,0 +1,44 @@ +declare namespace InternalPprofBinding { + // A time profile, as a table of the nodes of the profile tree in pre-order, + // root first. Every node comes after its parent. + interface TimeProfile { + // V8 timer values, in microseconds. + startTime: number; + endTime: number; + // Microseconds to add to a V8 timer value to get microseconds since the + // Unix epoch. Undefined on Windows. + epochOffset: number | undefined; + hasCpuTime: boolean; + nonJSThreadsCpuTime: number; + totalHitCount: number; + restarted: boolean; + parent: Int32Array; + scriptId: Int32Array; + lineNumber: Int32Array; + columnNumber: Int32Array; + hitCount: Uint32Array; + // Nanoseconds. Only set if hasCpuTime is true. + cpuTime: Float64Array | undefined; + name: string[]; + scriptName: string[]; + } + + class WallProfiler { + constructor( + intervalMicros: number, + durationMillis: number, + lineNumbers: boolean, + workaroundV8Bug: boolean, + collectCpuTime: boolean, + ); + start(): void; + stop(restart: boolean): TimeProfile; + dispose(): void; + v8ProfilerStuckEventLoopDetected(): 0 | 1 | 2; + } +} + +export interface PprofBinding { + WallProfiler: typeof InternalPprofBinding.WallProfiler; + signalSamplingSupported: boolean; +}