Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

inspector: implement --cpu-prof-interval #27535

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,16 @@ added: v12.0.0
Specify the directory where the CPU profiles generated by `--cpu-prof` will
be placed.

### `--cpu-prof-interval`
<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

Specify the sampling interval in microseconds for the CPU profiles generated
by `--cpu-prof`. The default is 1000 microseconds.

### `--cpu-prof-name`
<!-- YAML
added: v12.0.0
Expand Down
6 changes: 6 additions & 0 deletions doc/node.1
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ The directory where the CPU profiles generated by
.Fl -cpu-prof
will be placed.
.
.It Fl -cpu-prof-interval
The sampling interval in microseconds for the CPU profiles generated by
.Fl -cpu-prof .
The default is
.Sy 1000 .
.
.It Fl -cpu-prof-name
File name of the V8 CPU profile generated with
.Fl -cpu-prof
Expand Down
8 changes: 8 additions & 0 deletions src/env-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,14 @@ Environment::cpu_profiler_connection() {
return cpu_profiler_connection_.get();
}

inline void Environment::set_cpu_prof_interval(uint64_t interval) {
cpu_prof_interval_ = interval;
}

inline uint64_t Environment::cpu_prof_interval() const {
return cpu_prof_interval_;
}

inline void Environment::set_cpu_prof_name(const std::string& name) {
cpu_prof_name_ = name;
}
Expand Down
4 changes: 4 additions & 0 deletions src/env.h
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,9 @@ class Environment : public MemoryRetainer {
inline void set_cpu_prof_name(const std::string& name);
inline const std::string& cpu_prof_name() const;

inline void set_cpu_prof_interval(uint64_t interval);
inline uint64_t cpu_prof_interval() const;

inline void set_cpu_prof_dir(const std::string& dir);
inline const std::string& cpu_prof_dir() const;
#endif // HAVE_INSPECTOR
Expand Down Expand Up @@ -1183,6 +1186,7 @@ class Environment : public MemoryRetainer {
std::string coverage_directory_;
std::string cpu_prof_dir_;
std::string cpu_prof_name_;
uint64_t cpu_prof_interval_;
#endif // HAVE_INSPECTOR

std::shared_ptr<EnvironmentOptions> options_;
Expand Down
80 changes: 34 additions & 46 deletions src/inspector_profiler.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "inspector_profiler.h"
#include <sstream>
#include "base_object-inl.h"
#include "debug_utils.h"
#include "node_file.h"
Expand All @@ -20,7 +21,6 @@ using v8::Object;
using v8::String;
using v8::Value;

using v8_inspector::StringBuffer;
using v8_inspector::StringView;

#ifdef _WIN32
Expand All @@ -33,21 +33,34 @@ const char* const kPathSeparator = "/";
#define CWD_BUFSIZE (PATH_MAX)
#endif

std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
Local<Value> value) {
TwoByteValue buffer(isolate, value);
return StringBuffer::create(StringView(*buffer, buffer.length()));
}

V8ProfilerConnection::V8ProfilerConnection(Environment* env)
: session_(env->inspector_agent()->Connect(
std::make_unique<V8ProfilerConnection::V8ProfilerSessionDelegate>(
this),
false)),
env_(env) {}

void V8ProfilerConnection::DispatchMessage(Local<String> message) {
session_->Dispatch(ToProtocolString(env()->isolate(), message)->string());
size_t V8ProfilerConnection::DispatchMessage(const char* method,
const char* params) {
std::stringstream ss;
size_t id = next_id();
ss << R"({ "id": )" << id;
DCHECK(method != nullptr);
ss << R"(, "method": ")" << method << '"';
if (params != nullptr) {
ss << R"(, "params": )" << params;
}
ss << " }";
std::string message = ss.str();
const uint8_t* message_data =
reinterpret_cast<const uint8_t*>(message.c_str());
Debug(env(),
DebugCategory::INSPECTOR_PROFILER,
"Dispatching message %s\n",
message.c_str());
session_->Dispatch(StringView(message_data, message.length()));
// TODO(joyeecheung): use this to identify the ending message.
return id;
}

static void WriteResult(Environment* env,
Expand Down Expand Up @@ -202,34 +215,15 @@ std::string V8CoverageConnection::GetDirectory() const {
}

void V8CoverageConnection::Start() {
Debug(env(),
DebugCategory::INSPECTOR_PROFILER,
"Sending Profiler.startPreciseCoverage\n");
Isolate* isolate = env()->isolate();
Local<String> enable = FIXED_ONE_BYTE_STRING(
isolate, R"({"id": 1, "method": "Profiler.enable"})");
Local<String> start = FIXED_ONE_BYTE_STRING(isolate, R"({
"id": 2,
"method": "Profiler.startPreciseCoverage",
"params": { "callCount": true, "detailed": true }
})");
DispatchMessage(enable);
DispatchMessage(start);
DispatchMessage("Profiler.enable");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really liking the added clarity in these methods! 👍

DispatchMessage("Profiler.startPreciseCoverage",
R"({ "callCount": true, "detailed": true })");
}

void V8CoverageConnection::End() {
CHECK_EQ(ending_, false);
ending_ = true;
Debug(env(),
DebugCategory::INSPECTOR_PROFILER,
"Sending Profiler.takePreciseCoverage\n");
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<String> end = FIXED_ONE_BYTE_STRING(isolate, R"({
"id": 3,
"method": "Profiler.takePreciseCoverage"
})");
DispatchMessage(end);
DispatchMessage("Profiler.takePreciseCoverage");
}

std::string V8CpuProfilerConnection::GetDirectory() const {
Expand Down Expand Up @@ -257,25 +251,18 @@ MaybeLocal<Object> V8CpuProfilerConnection::GetProfile(Local<Object> result) {
}

void V8CpuProfilerConnection::Start() {
Debug(env(), DebugCategory::INSPECTOR_PROFILER, "Sending Profiler.start\n");
Isolate* isolate = env()->isolate();
Local<String> enable = FIXED_ONE_BYTE_STRING(
isolate, R"({"id": 1, "method": "Profiler.enable"})");
Local<String> start = FIXED_ONE_BYTE_STRING(
isolate, R"({"id": 2, "method": "Profiler.start"})");
DispatchMessage(enable);
DispatchMessage(start);
DispatchMessage("Profiler.enable");
DispatchMessage("Profiler.start");
std::string params = R"({ "interval": )";
params += std::to_string(env()->cpu_prof_interval());
params += " }";
DispatchMessage("Profiler.setSamplingInterval", params.c_str());
}

void V8CpuProfilerConnection::End() {
CHECK_EQ(ending_, false);
ending_ = true;
Debug(env(), DebugCategory::INSPECTOR_PROFILER, "Sending Profiler.stop\n");
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<String> end =
FIXED_ONE_BYTE_STRING(isolate, R"({"id": 3, "method": "Profiler.stop"})");
DispatchMessage(end);
DispatchMessage("Profiler.stop");
}

// For now, we only support coverage profiling, but we may add more
Expand Down Expand Up @@ -320,6 +307,7 @@ void StartProfilers(Environment* env) {
}
if (env->options()->cpu_prof) {
const std::string& dir = env->options()->cpu_prof_dir;
env->set_cpu_prof_interval(env->options()->cpu_prof_interval);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could just use env->options()->cpu_prof_interval everywhere instead of an extra setter/getter pair, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about making this profiling capability available on-demand during runtime in the future, as requested here, in that case I think it makes more sense to put the options on the Environment itself (or in a separate struct when we have too many of them), because these may not come from CLI at that point.

env->set_cpu_prof_dir(dir.empty() ? GetCwd() : dir);
if (env->options()->cpu_prof_name.empty()) {
DiagnosticFilename filename(env, "CPU", "cpuprofile");
Expand Down
10 changes: 9 additions & 1 deletion src/inspector_profiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ class V8ProfilerConnection {
virtual ~V8ProfilerConnection() = default;

Environment* env() const { return env_; }
void DispatchMessage(v8::Local<v8::String> message);

// Dispatch a protocol message, and returns the id of the message.
// `method` does not need to be surrounded by quotes.
// The optional `params` should be formatted in JSON.
// The strings should be in one byte characters - which is enough for
// the commands we use here.
size_t DispatchMessage(const char* method, const char* params = nullptr);

// Use DispatchMessage() to dispatch necessary inspector messages
// to start and end the profiling.
Expand All @@ -55,9 +61,11 @@ class V8ProfilerConnection {
v8::Local<v8::Object> result) = 0;

private:
size_t next_id() { return id_++; }
void WriteProfile(v8::Local<v8::String> message);
std::unique_ptr<inspector::InspectorSession> session_;
Environment* env_ = nullptr;
size_t id_ = 1;
};

class V8CoverageConnection : public V8ProfilerConnection {
Expand Down
9 changes: 9 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
if (!cpu_prof_dir.empty()) {
errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
}
// We can't catch the case where the value passed is the default value,
// then the option just becomes a noop which is fine.
if (cpu_prof_interval != kDefaultCpuProfInterval) {
errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
}
}

debug_options_.CheckOptions(errors);
Expand Down Expand Up @@ -351,6 +356,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
"specified file name of the V8 CPU profile generated with "
"--cpu-prof",
&EnvironmentOptions::cpu_prof_name);
AddOption("--cpu-prof-interval",
"specified sampling interval in microseconds for the V8 CPU "
"profile generated with --cpu-prof. (default: 1000)",
&EnvironmentOptions::cpu_prof_interval);
AddOption("--cpu-prof-dir",
"Directory where the V8 profiles generated by --cpu-prof will be "
"placed. Does not affect --prof.",
Expand Down
2 changes: 2 additions & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ class EnvironmentOptions : public Options {
bool prof_process = false;
#if HAVE_INSPECTOR
std::string cpu_prof_dir;
static const uint64_t kDefaultCpuProfInterval = 1000;
uint64_t cpu_prof_interval = kDefaultCpuProfInterval;
std::string cpu_prof_name;
bool cpu_prof = false;
#endif // HAVE_INSPECTOR
Expand Down
6 changes: 5 additions & 1 deletion test/fixtures/workload/fibonacci-worker-argv.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,9 @@
const { Worker } = require('worker_threads');
const path = require('path');
new Worker(path.join(__dirname, 'fibonacci.js'), {
execArgv: ['--cpu-prof']
execArgv: [
'--cpu-prof',
'--cpu-prof-interval',
process.env.CPU_PROF_INTERVAL || '100'
]
});
Loading