Skip to content

Commit ec64ac8

Browse files
committed
v8: add setHeapSnapshotNearHeapLimit
1 parent ab89024 commit ec64ac8

11 files changed

+332
-9
lines changed

doc/api/v8.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,21 @@ if (isMainThread) {
356356
}
357357
```
358358

359+
## `v8.setHeapSnapshotNearHeapLimit(limit)`
360+
361+
<!-- YAML
362+
added: REPLACEME
363+
-->
364+
365+
> Stability: 1 - Experimental
366+
367+
The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the
368+
command line. And if `--heapsnapshot-near-heap-limit` is not set, the API can
369+
be called with the value greater than 0. After the limit is set, you can call
370+
this API with 0 to tell Node.js stop writing heap snapshot to disk.
371+
Other case is also a no-op. See [`--heapsnapshot-near-heap-limit`][] for
372+
more information.
373+
359374
## Serialization API
360375

361376
The serialization API provides means of serializing JavaScript values in a way
@@ -1020,6 +1035,7 @@ Returns true if the Node.js instance is run to build a snapshot.
10201035
[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
10211036
[Hook Callbacks]: #hook-callbacks
10221037
[V8]: https://developers.google.com/v8/
1038+
[`--heapsnapshot-near-heap-limit`]: cli.md#--heapsnapshot-near-heap-limitmax_count
10231039
[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
10241040
[`Buffer`]: buffer.md
10251041
[`DefaultDeserializer`]: #class-v8defaultdeserializer

lib/v8.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const {
3333
} = primordials;
3434

3535
const { Buffer } = require('buffer');
36-
const { validateString } = require('internal/validators');
36+
const { validateString, validateNumber } = require('internal/validators');
3737
const {
3838
Serializer,
3939
Deserializer
@@ -59,7 +59,6 @@ const {
5959
} = internalBinding('heap_utils');
6060
const { HeapSnapshotStream } = require('internal/heap_utils');
6161
const promiseHooks = require('internal/promise_hooks');
62-
6362
/**
6463
* Generates a snapshot of the current V8 heap
6564
* and writes it to a JSON file.
@@ -95,6 +94,7 @@ const {
9594
updateHeapStatisticsBuffer,
9695
updateHeapSpaceStatisticsBuffer,
9796
updateHeapCodeStatisticsBuffer,
97+
setHeapSnapshotNearHeapLimit: _setHeapSnapshotNearHeapLimit,
9898

9999
// Properties for heap statistics buffer extraction.
100100
kTotalHeapSizeIndex,
@@ -226,6 +226,11 @@ function getHeapCodeStatistics() {
226226
};
227227
}
228228

229+
function setHeapSnapshotNearHeapLimit(limit) {
230+
validateNumber(limit, 'limit', 0);
231+
_setHeapSnapshotNearHeapLimit(limit);
232+
}
233+
229234
/* V8 serialization API */
230235

231236
/* JS methods for the base objects */
@@ -387,5 +392,6 @@ module.exports = {
387392
serialize,
388393
writeHeapSnapshot,
389394
promiseHooks,
390-
startupSnapshot
395+
startupSnapshot,
396+
setHeapSnapshotNearHeapLimit,
391397
};

src/env.cc

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,8 @@ Environment::Environment(IsolateData* isolate_data,
720720
inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
721721
options_->debug_options().host_port);
722722

723+
set_heap_snapshot_near_heap_limit(options_->heap_snapshot_near_heap_limit);
724+
723725
if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
724726
set_abort_on_uncaught_exception(false);
725727
}
@@ -834,7 +836,8 @@ Environment::~Environment() {
834836
// FreeEnvironment() should have set this.
835837
CHECK(is_stopping());
836838

837-
if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
839+
if (heapsnapshot_near_heap_limit_callback_added()) {
840+
set_heapsnapshot_near_heap_limit_callback_added(false);
838841
isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
839842
0);
840843
}
@@ -1952,6 +1955,7 @@ size_t Environment::NearHeapLimitCallback(void* data,
19521955
Debug(env,
19531956
DebugCategory::DIAGNOSTICS,
19541957
"Not generating snapshots because it's too risky.\n");
1958+
env->set_heapsnapshot_near_heap_limit_callback_added(false);
19551959
env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
19561960
initial_heap_limit);
19571961
// The new limit must be higher than current_heap_limit or V8 might
@@ -1973,16 +1977,17 @@ size_t Environment::NearHeapLimitCallback(void* data,
19731977

19741978
// Remove the callback first in case it's triggered when generating
19751979
// the snapshot.
1980+
env->set_heapsnapshot_near_heap_limit_callback_added(false);
19761981
env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
19771982
initial_heap_limit);
19781983

19791984
heap::WriteSnapshot(env, filename.c_str());
1980-
env->heap_limit_snapshot_taken_ += 1;
1985+
env->set_heap_limit_snapshot_taken(env->heap_limit_snapshot_taken() + 1);
19811986

19821987
// Don't take more snapshots than the number specified by
19831988
// --heapsnapshot-near-heap-limit.
1984-
if (env->heap_limit_snapshot_taken_ <
1985-
env->options_->heap_snapshot_near_heap_limit) {
1989+
if (env->heap_limit_snapshot_taken() < env->heap_snapshot_near_heap_limit()) {
1990+
env->set_heapsnapshot_near_heap_limit_callback_added(true);
19861991
env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
19871992
}
19881993

src/env.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,30 @@ class Environment : public MemoryRetainer {
14891489
template <typename T>
14901490
void ForEachBaseObject(T&& iterator);
14911491

1492+
inline int64_t heap_limit_snapshot_taken() {
1493+
return heap_limit_snapshot_taken_;
1494+
}
1495+
1496+
inline int64_t set_heap_limit_snapshot_taken(int64_t count) {
1497+
return heap_limit_snapshot_taken_ = count;
1498+
}
1499+
1500+
inline int64_t heap_snapshot_near_heap_limit() {
1501+
return heap_snapshot_near_heap_limit_;
1502+
}
1503+
1504+
inline void set_heap_snapshot_near_heap_limit(int64_t limit) {
1505+
heap_snapshot_near_heap_limit_ = limit;
1506+
}
1507+
1508+
inline bool heapsnapshot_near_heap_limit_callback_added() {
1509+
return near_heap_callback_is_added_;
1510+
}
1511+
1512+
inline void set_heapsnapshot_near_heap_limit_callback_added(bool added) {
1513+
near_heap_callback_is_added_ = added;
1514+
}
1515+
14921516
private:
14931517
inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
14941518
const char* errmsg);
@@ -1547,6 +1571,8 @@ class Environment : public MemoryRetainer {
15471571

15481572
bool is_processing_heap_limit_callback_ = false;
15491573
int64_t heap_limit_snapshot_taken_ = 0;
1574+
int64_t heap_snapshot_near_heap_limit_ = 0;
1575+
bool near_heap_callback_is_added_ = false;
15501576

15511577
uint32_t module_id_counter_ = 0;
15521578
uint32_t script_id_counter_ = 0;

src/node.cc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,8 @@ static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
273273
void Environment::InitializeDiagnostics() {
274274
isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
275275
Environment::BuildEmbedderGraph, this);
276-
if (options_->heap_snapshot_near_heap_limit > 0) {
276+
if (heap_snapshot_near_heap_limit() > 0) {
277+
set_heapsnapshot_near_heap_limit_callback_added(true);
277278
isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
278279
this);
279280
}

src/node_v8.cc

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,30 @@ void CachedDataVersionTag(const FunctionCallbackInfo<Value>& args) {
157157
args.GetReturnValue().Set(result);
158158
}
159159

160+
void SetHeapSnapshotNearHeapLimit(const FunctionCallbackInfo<Value>& args) {
161+
CHECK(args[0]->IsNumber());
162+
Environment* env = Environment::GetCurrent(args);
163+
Isolate* const isolate = args.GetIsolate();
164+
int64_t limit = args[0].As<v8::Number>()->Value();
165+
CHECK_GE(limit, 0);
166+
// Do not set twice which will make the process crash.
167+
if (limit == 0) {
168+
if (env->heapsnapshot_near_heap_limit_callback_added()) {
169+
env->set_heapsnapshot_near_heap_limit_callback_added(false);
170+
isolate->RemoveNearHeapLimitCallback(
171+
Environment::NearHeapLimitCallback, 0);
172+
env->set_heap_snapshot_near_heap_limit(limit);
173+
}
174+
} else {
175+
if (!env->heapsnapshot_near_heap_limit_callback_added()) {
176+
env->set_heapsnapshot_near_heap_limit_callback_added(true);
177+
isolate->AddNearHeapLimitCallback(
178+
Environment::NearHeapLimitCallback, env);
179+
env->set_heap_snapshot_near_heap_limit(limit);
180+
}
181+
}
182+
}
183+
160184
void UpdateHeapStatisticsBuffer(const FunctionCallbackInfo<Value>& args) {
161185
BindingData* data = Environment::GetBindingData<BindingData>(args);
162186
HeapStatistics s;
@@ -212,6 +236,10 @@ void Initialize(Local<Object> target,
212236

213237
SetMethodNoSideEffect(
214238
context, target, "cachedDataVersionTag", CachedDataVersionTag);
239+
SetMethodNoSideEffect(context,
240+
target,
241+
"setHeapSnapshotNearHeapLimit",
242+
SetHeapSnapshotNearHeapLimit);
215243
SetMethod(context,
216244
target,
217245
"updateHeapStatisticsBuffer",
@@ -267,6 +295,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
267295
registry->Register(UpdateHeapCodeStatisticsBuffer);
268296
registry->Register(UpdateHeapSpaceStatisticsBuffer);
269297
registry->Register(SetFlagsFromString);
298+
registry->Register(SetHeapSnapshotNearHeapLimit);
270299
}
271300

272301
} // namespace v8_utils
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
const path = require('path');
3+
const v8 = require('v8');
4+
5+
v8.setHeapSnapshotNearHeapLimit(+process.env.limit);
6+
if (process.env.limit2) {
7+
v8.setHeapSnapshotNearHeapLimit(+process.env.limit2);
8+
}
9+
require(path.resolve(__dirname, 'grow.js'));
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
'use strict';
2+
const path = require('path');
3+
const { Worker } = require('worker_threads');
4+
const max_snapshots = parseInt(process.env.TEST_SNAPSHOTS) || 1;
5+
new Worker(path.join(__dirname, 'grow-and-set-near-heap-limit.js'), {
6+
env: {
7+
...process.env,
8+
limit: max_snapshots,
9+
},
10+
resourceLimits: {
11+
maxOldGenerationSizeMb:
12+
parseInt(process.env.TEST_OLD_SPACE_SIZE) || 20
13+
}
14+
});
15+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copy from test-heapsnapshot-near-heap-limit-worker.js
2+
'use strict';
3+
4+
require('../common');
5+
const tmpdir = require('../common/tmpdir');
6+
const assert = require('assert');
7+
const { spawnSync } = require('child_process');
8+
const fixtures = require('../common/fixtures');
9+
const fs = require('fs');
10+
11+
const env = {
12+
...process.env,
13+
NODE_DEBUG_NATIVE: 'diagnostics'
14+
};
15+
16+
{
17+
tmpdir.refresh();
18+
const child = spawnSync(process.execPath, [
19+
fixtures.path('workload', 'grow-worker-and-set-near-heap-limit.js'),
20+
], {
21+
cwd: tmpdir.path,
22+
env: {
23+
TEST_SNAPSHOTS: 1,
24+
TEST_OLD_SPACE_SIZE: 50,
25+
...env
26+
}
27+
});
28+
console.log(child.stdout.toString());
29+
const stderr = child.stderr.toString();
30+
console.log(stderr);
31+
const risky = /Not generating snapshots because it's too risky/.test(stderr);
32+
if (!risky) {
33+
// There should be one snapshot taken and then after the
34+
// snapshot heap limit callback is popped, the OOM callback
35+
// becomes effective.
36+
assert(stderr.includes('ERR_WORKER_OUT_OF_MEMORY'));
37+
const list = fs.readdirSync(tmpdir.path)
38+
.filter((file) => file.endsWith('.heapsnapshot'));
39+
assert.strictEqual(list.length, 1);
40+
}
41+
}

0 commit comments

Comments
 (0)