1 #include "env-inl.h"
2 #include "json_utils.h"
3 #include "node_report.h"
4 #include "debug_utils-inl.h"
5 #include "diagnosticfilename-inl.h"
6 #include "node_internals.h"
7 #include "node_metadata.h"
8 #include "node_mutex.h"
9 #include "node_worker.h"
10 #include "util.h"
11
12 #ifdef _WIN32
13 #include <Windows.h>
14 #else // !_WIN32
15 #include <cxxabi.h>
16 #include <sys/resource.h>
17 #include <dlfcn.h>
18 #endif
19
20 #include <iostream>
21 #include <cstring>
22 #include <ctime>
23 #include <cwctype>
24 #include <fstream>
25
26 constexpr int NODE_REPORT_VERSION = 2;
27 constexpr int NANOS_PER_SEC = 1000 * 1000 * 1000;
28 constexpr double SEC_PER_MICROS = 1e-6;
29
30 namespace report {
31 using node::arraysize;
32 using node::ConditionVariable;
33 using node::DiagnosticFilename;
34 using node::Environment;
35 using node::JSONWriter;
36 using node::Mutex;
37 using node::NativeSymbolDebuggingContext;
38 using node::TIME_TYPE;
39 using node::worker::Worker;
40 using v8::Array;
41 using v8::Context;
42 using v8::HeapSpaceStatistics;
43 using v8::HeapStatistics;
44 using v8::Isolate;
45 using v8::Local;
46 using v8::Object;
47 using v8::String;
48 using v8::TryCatch;
49 using v8::V8;
50 using v8::Value;
51
52 namespace per_process = node::per_process;
53
54 // Internal/static function declarations
55 static void WriteNodeReport(Isolate* isolate,
56 Environment* env,
57 const char* message,
58 const char* trigger,
59 const std::string& filename,
60 std::ostream& out,
61 Local<Object> error,
62 bool compact);
63 static void PrintVersionInformation(JSONWriter* writer);
64 static void PrintJavaScriptErrorStack(JSONWriter* writer,
65 Isolate* isolate,
66 Local<Object> error,
67 const char* trigger);
68 static void PrintJavaScriptErrorProperties(JSONWriter* writer,
69 Isolate* isolate,
70 Local<Object> error);
71 static void PrintNativeStack(JSONWriter* writer);
72 static void PrintResourceUsage(JSONWriter* writer);
73 static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate);
74 static void PrintSystemInformation(JSONWriter* writer);
75 static void PrintLoadedLibraries(JSONWriter* writer);
76 static void PrintComponentVersions(JSONWriter* writer);
77 static void PrintRelease(JSONWriter* writer);
78 static void PrintCpuInfo(JSONWriter* writer);
79 static void PrintNetworkInterfaceInfo(JSONWriter* writer);
80
81 // External function to trigger a report, writing to file.
TriggerNodeReport(Isolate * isolate,Environment * env,const char * message,const char * trigger,const std::string & name,Local<Object> error)82 std::string TriggerNodeReport(Isolate* isolate,
83 Environment* env,
84 const char* message,
85 const char* trigger,
86 const std::string& name,
87 Local<Object> error) {
88 std::string filename;
89
90 // Determine the required report filename. In order of priority:
91 // 1) supplied on API 2) configured on startup 3) default generated
92 if (!name.empty()) {
93 // Filename was specified as API parameter.
94 filename = name;
95 } else {
96 std::string report_filename;
97 {
98 Mutex::ScopedLock lock(per_process::cli_options_mutex);
99 report_filename = per_process::cli_options->report_filename;
100 }
101 if (report_filename.length() > 0) {
102 // File name was supplied via start-up option.
103 filename = report_filename;
104 } else {
105 filename = *DiagnosticFilename(env != nullptr ? env->thread_id() : 0,
106 "report", "json");
107 }
108 }
109
110 // Open the report file stream for writing. Supports stdout/err,
111 // user-specified or (default) generated name
112 std::ofstream outfile;
113 std::ostream* outstream;
114 if (filename == "stdout") {
115 outstream = &std::cout;
116 } else if (filename == "stderr") {
117 outstream = &std::cerr;
118 } else {
119 std::string report_directory;
120 {
121 Mutex::ScopedLock lock(per_process::cli_options_mutex);
122 report_directory = per_process::cli_options->report_directory;
123 }
124 // Regular file. Append filename to directory path if one was specified
125 if (report_directory.length() > 0) {
126 std::string pathname = report_directory;
127 pathname += node::kPathSeparator;
128 pathname += filename;
129 outfile.open(pathname, std::ios::out | std::ios::binary);
130 } else {
131 outfile.open(filename, std::ios::out | std::ios::binary);
132 }
133 // Check for errors on the file open
134 if (!outfile.is_open()) {
135 std::cerr << "\nFailed to open Node.js report file: " << filename;
136
137 if (report_directory.length() > 0)
138 std::cerr << " directory: " << report_directory;
139
140 std::cerr << " (errno: " << errno << ")" << std::endl;
141 return "";
142 }
143 outstream = &outfile;
144 std::cerr << "\nWriting Node.js report to file: " << filename;
145 }
146
147 bool compact;
148 {
149 Mutex::ScopedLock lock(per_process::cli_options_mutex);
150 compact = per_process::cli_options->report_compact;
151 }
152 WriteNodeReport(isolate, env, message, trigger, filename, *outstream,
153 error, compact);
154
155 // Do not close stdout/stderr, only close files we opened.
156 if (outfile.is_open()) {
157 outfile.close();
158 }
159
160 // Do not mix JSON and free-form text on stderr.
161 if (filename != "stderr") {
162 std::cerr << "\nNode.js report completed" << std::endl;
163 }
164 return filename;
165 }
166
167 // External function to trigger a report, writing to a supplied stream.
GetNodeReport(Isolate * isolate,Environment * env,const char * message,const char * trigger,Local<Object> error,std::ostream & out)168 void GetNodeReport(Isolate* isolate,
169 Environment* env,
170 const char* message,
171 const char* trigger,
172 Local<Object> error,
173 std::ostream& out) {
174 WriteNodeReport(isolate, env, message, trigger, "", out, error, false);
175 }
176
177 // Internal function to coordinate and write the various
178 // sections of the report to the supplied stream
WriteNodeReport(Isolate * isolate,Environment * env,const char * message,const char * trigger,const std::string & filename,std::ostream & out,Local<Object> error,bool compact)179 static void WriteNodeReport(Isolate* isolate,
180 Environment* env,
181 const char* message,
182 const char* trigger,
183 const std::string& filename,
184 std::ostream& out,
185 Local<Object> error,
186 bool compact) {
187 // Obtain the current time and the pid.
188 TIME_TYPE tm_struct;
189 DiagnosticFilename::LocalTime(&tm_struct);
190 uv_pid_t pid = uv_os_getpid();
191
192 // Save formatting for output stream.
193 std::ios old_state(nullptr);
194 old_state.copyfmt(out);
195
196 // File stream opened OK, now start printing the report content:
197 // the title and header information (event, filename, timestamp and pid)
198
199 JSONWriter writer(out, compact);
200 writer.json_start();
201 writer.json_objectstart("header");
202 writer.json_keyvalue("reportVersion", NODE_REPORT_VERSION);
203 writer.json_keyvalue("event", message);
204 writer.json_keyvalue("trigger", trigger);
205 if (!filename.empty())
206 writer.json_keyvalue("filename", filename);
207 else
208 writer.json_keyvalue("filename", JSONWriter::Null{});
209
210 // Report dump event and module load date/time stamps
211 char timebuf[64];
212 #ifdef _WIN32
213 snprintf(timebuf,
214 sizeof(timebuf),
215 "%4d-%02d-%02dT%02d:%02d:%02dZ",
216 tm_struct.wYear,
217 tm_struct.wMonth,
218 tm_struct.wDay,
219 tm_struct.wHour,
220 tm_struct.wMinute,
221 tm_struct.wSecond);
222 writer.json_keyvalue("dumpEventTime", timebuf);
223 #else // UNIX, OSX
224 snprintf(timebuf,
225 sizeof(timebuf),
226 "%4d-%02d-%02dT%02d:%02d:%02dZ",
227 tm_struct.tm_year + 1900,
228 tm_struct.tm_mon + 1,
229 tm_struct.tm_mday,
230 tm_struct.tm_hour,
231 tm_struct.tm_min,
232 tm_struct.tm_sec);
233 writer.json_keyvalue("dumpEventTime", timebuf);
234 #endif
235
236 uv_timeval64_t ts;
237 if (uv_gettimeofday(&ts) == 0) {
238 writer.json_keyvalue("dumpEventTimeStamp",
239 std::to_string(ts.tv_sec * 1000 + ts.tv_usec / 1000));
240 }
241
242 // Report native process ID
243 writer.json_keyvalue("processId", pid);
244 if (env != nullptr)
245 writer.json_keyvalue("threadId", env->thread_id());
246 else
247 writer.json_keyvalue("threadId", JSONWriter::Null{});
248
249 {
250 // Report the process cwd.
251 char buf[PATH_MAX_BYTES];
252 size_t cwd_size = sizeof(buf);
253 if (uv_cwd(buf, &cwd_size) == 0)
254 writer.json_keyvalue("cwd", buf);
255 }
256
257 // Report out the command line.
258 if (!node::per_process::cli_options->cmdline.empty()) {
259 writer.json_arraystart("commandLine");
260 for (const std::string& arg : node::per_process::cli_options->cmdline) {
261 writer.json_element(arg);
262 }
263 writer.json_arrayend();
264 }
265
266 // Report Node.js and OS version information
267 PrintVersionInformation(&writer);
268 writer.json_objectend();
269
270 if (isolate != nullptr) {
271 writer.json_objectstart("javascriptStack");
272 // Report summary JavaScript error stack backtrace
273 PrintJavaScriptErrorStack(&writer, isolate, error, trigger);
274
275 // Report summary JavaScript error properties backtrace
276 PrintJavaScriptErrorProperties(&writer, isolate, error);
277 writer.json_objectend(); // the end of 'javascriptStack'
278
279 // Report V8 Heap and Garbage Collector information
280 PrintGCStatistics(&writer, isolate);
281 }
282
283 // Report native stack backtrace
284 PrintNativeStack(&writer);
285
286 // Report OS and current thread resource usage
287 PrintResourceUsage(&writer);
288
289 writer.json_arraystart("libuv");
290 if (env != nullptr) {
291 uv_walk(env->event_loop(), WalkHandle, static_cast<void*>(&writer));
292
293 writer.json_start();
294 writer.json_keyvalue("type", "loop");
295 writer.json_keyvalue("is_active",
296 static_cast<bool>(uv_loop_alive(env->event_loop())));
297 writer.json_keyvalue("address",
298 ValueToHexString(reinterpret_cast<int64_t>(env->event_loop())));
299
300 // Report Event loop idle time
301 uint64_t idle_time = uv_metrics_idle_time(env->event_loop());
302 writer.json_keyvalue("loopIdleTimeSeconds", 1.0 * idle_time / 1e9);
303 writer.json_end();
304 }
305
306 writer.json_arrayend();
307
308 writer.json_arraystart("workers");
309 if (env != nullptr) {
310 Mutex workers_mutex;
311 ConditionVariable notify;
312 std::vector<std::string> worker_infos;
313 size_t expected_results = 0;
314
315 env->ForEachWorker([&](Worker* w) {
316 expected_results += w->RequestInterrupt([&](Environment* env) {
317 std::ostringstream os;
318
319 GetNodeReport(env->isolate(),
320 env,
321 "Worker thread subreport",
322 trigger,
323 Local<Object>(),
324 os);
325
326 Mutex::ScopedLock lock(workers_mutex);
327 worker_infos.emplace_back(os.str());
328 notify.Signal(lock);
329 });
330 });
331
332 Mutex::ScopedLock lock(workers_mutex);
333 worker_infos.reserve(expected_results);
334 while (worker_infos.size() < expected_results)
335 notify.Wait(lock);
336 for (const std::string& worker_info : worker_infos)
337 writer.json_element(JSONWriter::ForeignJSON { worker_info });
338 }
339 writer.json_arrayend();
340
341 // Report operating system information
342 PrintSystemInformation(&writer);
343
344 writer.json_objectend();
345
346 // Restore output stream formatting.
347 out.copyfmt(old_state);
348 }
349
350 // Report Node.js version, OS version and machine information.
PrintVersionInformation(JSONWriter * writer)351 static void PrintVersionInformation(JSONWriter* writer) {
352 std::ostringstream buf;
353 // Report Node version
354 buf << "v" << NODE_VERSION_STRING;
355 writer->json_keyvalue("nodejsVersion", buf.str());
356 buf.str("");
357
358 #ifndef _WIN32
359 // Report compiler and runtime glibc versions where possible.
360 const char* (*libc_version)();
361 *(reinterpret_cast<void**>(&libc_version)) =
362 dlsym(RTLD_DEFAULT, "gnu_get_libc_version");
363 if (libc_version != nullptr)
364 writer->json_keyvalue("glibcVersionRuntime", (*libc_version)());
365 #endif /* _WIN32 */
366
367 #ifdef __GLIBC__
368 buf << __GLIBC__ << "." << __GLIBC_MINOR__;
369 writer->json_keyvalue("glibcVersionCompiler", buf.str());
370 buf.str("");
371 #endif
372
373 // Report Process word size
374 writer->json_keyvalue("wordSize", sizeof(void*) * 8);
375 writer->json_keyvalue("arch", node::per_process::metadata.arch);
376 writer->json_keyvalue("platform", node::per_process::metadata.platform);
377
378 // Report deps component versions
379 PrintComponentVersions(writer);
380
381 // Report release metadata.
382 PrintRelease(writer);
383
384 // Report operating system and machine information
385 uv_utsname_t os_info;
386
387 if (uv_os_uname(&os_info) == 0) {
388 writer->json_keyvalue("osName", os_info.sysname);
389 writer->json_keyvalue("osRelease", os_info.release);
390 writer->json_keyvalue("osVersion", os_info.version);
391 writer->json_keyvalue("osMachine", os_info.machine);
392 }
393
394 PrintCpuInfo(writer);
395 PrintNetworkInterfaceInfo(writer);
396
397 char host[UV_MAXHOSTNAMESIZE];
398 size_t host_size = sizeof(host);
399
400 if (uv_os_gethostname(host, &host_size) == 0)
401 writer->json_keyvalue("host", host);
402 }
403
404 // Report CPU info
PrintCpuInfo(JSONWriter * writer)405 static void PrintCpuInfo(JSONWriter* writer) {
406 uv_cpu_info_t* cpu_info;
407 int count;
408 if (uv_cpu_info(&cpu_info, &count) == 0) {
409 writer->json_arraystart("cpus");
410 for (int i = 0; i < count; i++) {
411 writer->json_start();
412 writer->json_keyvalue("model", cpu_info[i].model);
413 writer->json_keyvalue("speed", cpu_info[i].speed);
414 writer->json_keyvalue("user", cpu_info[i].cpu_times.user);
415 writer->json_keyvalue("nice", cpu_info[i].cpu_times.nice);
416 writer->json_keyvalue("sys", cpu_info[i].cpu_times.sys);
417 writer->json_keyvalue("idle", cpu_info[i].cpu_times.idle);
418 writer->json_keyvalue("irq", cpu_info[i].cpu_times.irq);
419 writer->json_end();
420 }
421 writer->json_arrayend();
422 uv_free_cpu_info(cpu_info, count);
423 }
424 }
425
PrintNetworkInterfaceInfo(JSONWriter * writer)426 static void PrintNetworkInterfaceInfo(JSONWriter* writer) {
427 uv_interface_address_t* interfaces;
428 char ip[INET6_ADDRSTRLEN];
429 char netmask[INET6_ADDRSTRLEN];
430 char mac[18];
431 int count;
432
433 if (uv_interface_addresses(&interfaces, &count) == 0) {
434 writer->json_arraystart("networkInterfaces");
435
436 for (int i = 0; i < count; i++) {
437 writer->json_start();
438 writer->json_keyvalue("name", interfaces[i].name);
439 writer->json_keyvalue("internal", !!interfaces[i].is_internal);
440 snprintf(mac,
441 sizeof(mac),
442 "%02x:%02x:%02x:%02x:%02x:%02x",
443 static_cast<unsigned char>(interfaces[i].phys_addr[0]),
444 static_cast<unsigned char>(interfaces[i].phys_addr[1]),
445 static_cast<unsigned char>(interfaces[i].phys_addr[2]),
446 static_cast<unsigned char>(interfaces[i].phys_addr[3]),
447 static_cast<unsigned char>(interfaces[i].phys_addr[4]),
448 static_cast<unsigned char>(interfaces[i].phys_addr[5]));
449 writer->json_keyvalue("mac", mac);
450
451 if (interfaces[i].address.address4.sin_family == AF_INET) {
452 uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
453 uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
454 writer->json_keyvalue("address", ip);
455 writer->json_keyvalue("netmask", netmask);
456 writer->json_keyvalue("family", "IPv4");
457 } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
458 uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
459 uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
460 writer->json_keyvalue("address", ip);
461 writer->json_keyvalue("netmask", netmask);
462 writer->json_keyvalue("family", "IPv6");
463 writer->json_keyvalue("scopeid",
464 interfaces[i].address.address6.sin6_scope_id);
465 } else {
466 writer->json_keyvalue("family", "unknown");
467 }
468
469 writer->json_end();
470 }
471
472 writer->json_arrayend();
473 uv_free_interface_addresses(interfaces, count);
474 }
475 }
476
PrintJavaScriptErrorProperties(JSONWriter * writer,Isolate * isolate,Local<Object> error)477 static void PrintJavaScriptErrorProperties(JSONWriter* writer,
478 Isolate* isolate,
479 Local<Object> error) {
480 writer->json_objectstart("errorProperties");
481 if (!error.IsEmpty()) {
482 TryCatch try_catch(isolate);
483 Local<Context> context = error->GetIsolate()->GetCurrentContext();
484 Local<Array> keys;
485 if (!error->GetOwnPropertyNames(context).ToLocal(&keys)) {
486 return writer->json_objectend(); // the end of 'errorProperties'
487 }
488 uint32_t keys_length = keys->Length();
489 for (uint32_t i = 0; i < keys_length; i++) {
490 Local<Value> key;
491 if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
492 continue;
493 }
494 Local<Value> value;
495 Local<String> value_string;
496 if (!error->Get(context, key).ToLocal(&value) ||
497 !value->ToString(context).ToLocal(&value_string)) {
498 continue;
499 }
500 String::Utf8Value k(isolate, key);
501 if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
502 String::Utf8Value v(isolate, value_string);
503 writer->json_keyvalue(std::string(*k, k.length()),
504 std::string(*v, v.length()));
505 }
506 }
507 writer->json_objectend(); // the end of 'errorProperties'
508 }
509
510 // Report the JavaScript stack.
PrintJavaScriptErrorStack(JSONWriter * writer,Isolate * isolate,Local<Object> error,const char * trigger)511 static void PrintJavaScriptErrorStack(JSONWriter* writer,
512 Isolate* isolate,
513 Local<Object> error,
514 const char* trigger) {
515 Local<Value> stackstr;
516 std::string ss = "";
517 TryCatch try_catch(isolate);
518 if ((!strcmp(trigger, "FatalError")) ||
519 (!strcmp(trigger, "Signal"))) {
520 ss = "No stack.\nUnavailable.\n";
521 } else if (!error.IsEmpty() &&
522 error
523 ->Get(isolate->GetCurrentContext(),
524 node::FIXED_ONE_BYTE_STRING(isolate,
525 "stack"))
526 .ToLocal(&stackstr)) {
527 String::Utf8Value sv(isolate, stackstr);
528 ss = std::string(*sv, sv.length());
529 }
530 int line = ss.find('\n');
531 if (line == -1) {
532 writer->json_keyvalue("message", ss);
533 } else {
534 std::string l = ss.substr(0, line);
535 writer->json_keyvalue("message", l);
536 writer->json_arraystart("stack");
537 ss = ss.substr(line + 1);
538 line = ss.find('\n');
539 while (line != -1) {
540 l = ss.substr(0, line);
541 l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
542 return !std::iswspace(ch);
543 }));
544 writer->json_element(l);
545 ss = ss.substr(line + 1);
546 line = ss.find('\n');
547 }
548 writer->json_arrayend();
549 }
550 }
551
552 // Report a native stack backtrace
PrintNativeStack(JSONWriter * writer)553 static void PrintNativeStack(JSONWriter* writer) {
554 auto sym_ctx = NativeSymbolDebuggingContext::New();
555 void* frames[256];
556 const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
557 writer->json_arraystart("nativeStack");
558 int i;
559 for (i = 1; i < size; i++) {
560 void* frame = frames[i];
561 writer->json_start();
562 writer->json_keyvalue("pc",
563 ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
564 writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
565 writer->json_end();
566 }
567 writer->json_arrayend();
568 }
569
570 // Report V8 JavaScript heap information.
571 // This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
572 // The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
573 // provide some more useful information - the GC history and the handle counts
PrintGCStatistics(JSONWriter * writer,Isolate * isolate)574 static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
575 HeapStatistics v8_heap_stats;
576 isolate->GetHeapStatistics(&v8_heap_stats);
577 HeapSpaceStatistics v8_heap_space_stats;
578
579 writer->json_objectstart("javascriptHeap");
580 writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
581 writer->json_keyvalue("totalCommittedMemory",
582 v8_heap_stats.total_physical_size());
583 writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
584 writer->json_keyvalue("availableMemory",
585 v8_heap_stats.total_available_size());
586 writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
587
588 writer->json_objectstart("heapSpaces");
589 // Loop through heap spaces
590 for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
591 isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
592 writer->json_objectstart(v8_heap_space_stats.space_name());
593 writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
594 writer->json_keyvalue(
595 "committedMemory",
596 v8_heap_space_stats.physical_space_size());
597 writer->json_keyvalue(
598 "capacity",
599 v8_heap_space_stats.space_used_size() +
600 v8_heap_space_stats.space_available_size());
601 writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
602 writer->json_keyvalue(
603 "available", v8_heap_space_stats.space_available_size());
604 writer->json_objectend();
605 }
606
607 writer->json_objectend();
608 writer->json_objectend();
609 }
610
PrintResourceUsage(JSONWriter * writer)611 static void PrintResourceUsage(JSONWriter* writer) {
612 // Get process uptime in seconds
613 uint64_t uptime =
614 (uv_hrtime() - node::per_process::node_start_time) / (NANOS_PER_SEC);
615 if (uptime == 0) uptime = 1; // avoid division by zero.
616
617 // Process and current thread usage statistics
618 uv_rusage_t rusage;
619 writer->json_objectstart("resourceUsage");
620 if (uv_getrusage(&rusage) == 0) {
621 double user_cpu =
622 rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
623 double kernel_cpu =
624 rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
625 writer->json_keyvalue("userCpuSeconds", user_cpu);
626 writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
627 double cpu_abs = user_cpu + kernel_cpu;
628 double cpu_percentage = (cpu_abs / uptime) * 100.0;
629 writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
630 writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
631 writer->json_objectstart("pageFaults");
632 writer->json_keyvalue("IORequired", rusage.ru_majflt);
633 writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
634 writer->json_objectend();
635 writer->json_objectstart("fsActivity");
636 writer->json_keyvalue("reads", rusage.ru_inblock);
637 writer->json_keyvalue("writes", rusage.ru_oublock);
638 writer->json_objectend();
639 }
640 writer->json_objectend();
641 #ifdef RUSAGE_THREAD
642 struct rusage stats;
643 if (getrusage(RUSAGE_THREAD, &stats) == 0) {
644 writer->json_objectstart("uvthreadResourceUsage");
645 double user_cpu =
646 stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
647 double kernel_cpu =
648 stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
649 writer->json_keyvalue("userCpuSeconds", user_cpu);
650 writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
651 double cpu_abs = user_cpu + kernel_cpu;
652 double cpu_percentage = (cpu_abs / uptime) * 100.0;
653 writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
654 writer->json_objectstart("fsActivity");
655 writer->json_keyvalue("reads", stats.ru_inblock);
656 writer->json_keyvalue("writes", stats.ru_oublock);
657 writer->json_objectend();
658 writer->json_objectend();
659 }
660 #endif
661 }
662
663 // Report operating system information.
PrintSystemInformation(JSONWriter * writer)664 static void PrintSystemInformation(JSONWriter* writer) {
665 uv_env_item_t* envitems;
666 int envcount;
667 int r;
668
669 writer->json_objectstart("environmentVariables");
670
671 {
672 Mutex::ScopedLock lock(node::per_process::env_var_mutex);
673 r = uv_os_environ(&envitems, &envcount);
674 }
675
676 if (r == 0) {
677 for (int i = 0; i < envcount; i++)
678 writer->json_keyvalue(envitems[i].name, envitems[i].value);
679
680 uv_os_free_environ(envitems, envcount);
681 }
682
683 writer->json_objectend();
684
685 #ifndef _WIN32
686 static struct {
687 const char* description;
688 int id;
689 } rlimit_strings[] = {
690 {"core_file_size_blocks", RLIMIT_CORE},
691 {"data_seg_size_kbytes", RLIMIT_DATA},
692 {"file_size_blocks", RLIMIT_FSIZE},
693 #if !(defined(_AIX) || defined(__sun))
694 {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
695 #endif
696 #ifndef __sun
697 {"max_memory_size_kbytes", RLIMIT_RSS},
698 #endif
699 {"open_files", RLIMIT_NOFILE},
700 {"stack_size_bytes", RLIMIT_STACK},
701 {"cpu_time_seconds", RLIMIT_CPU},
702 #ifndef __sun
703 {"max_user_processes", RLIMIT_NPROC},
704 #endif
705 #ifndef __OpenBSD__
706 {"virtual_memory_kbytes", RLIMIT_AS}
707 #endif
708 };
709
710 writer->json_objectstart("userLimits");
711 struct rlimit limit;
712 std::string soft, hard;
713
714 for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
715 if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
716 writer->json_objectstart(rlimit_strings[i].description);
717
718 if (limit.rlim_cur == RLIM_INFINITY)
719 writer->json_keyvalue("soft", "unlimited");
720 else
721 writer->json_keyvalue("soft", limit.rlim_cur);
722
723 if (limit.rlim_max == RLIM_INFINITY)
724 writer->json_keyvalue("hard", "unlimited");
725 else
726 writer->json_keyvalue("hard", limit.rlim_max);
727
728 writer->json_objectend();
729 }
730 }
731 writer->json_objectend();
732 #endif // _WIN32
733
734 PrintLoadedLibraries(writer);
735 }
736
737 // Report a list of loaded native libraries.
PrintLoadedLibraries(JSONWriter * writer)738 static void PrintLoadedLibraries(JSONWriter* writer) {
739 writer->json_arraystart("sharedObjects");
740 std::vector<std::string> modules =
741 NativeSymbolDebuggingContext::GetLoadedLibraries();
742 for (auto const& module_name : modules) writer->json_element(module_name);
743 writer->json_arrayend();
744 }
745
746 // Obtain and report the node and subcomponent version strings.
PrintComponentVersions(JSONWriter * writer)747 static void PrintComponentVersions(JSONWriter* writer) {
748 std::stringstream buf;
749
750 writer->json_objectstart("componentVersions");
751
752 #define V(key) \
753 writer->json_keyvalue(#key, node::per_process::metadata.versions.key);
754 NODE_VERSIONS_KEYS(V)
755 #undef V
756
757 writer->json_objectend();
758 }
759
760 // Report runtime release information.
PrintRelease(JSONWriter * writer)761 static void PrintRelease(JSONWriter* writer) {
762 writer->json_objectstart("release");
763 writer->json_keyvalue("name", node::per_process::metadata.release.name);
764 #if NODE_VERSION_IS_LTS
765 writer->json_keyvalue("lts", node::per_process::metadata.release.lts);
766 #endif
767
768 #ifdef NODE_HAS_RELEASE_URLS
769 writer->json_keyvalue("headersUrl",
770 node::per_process::metadata.release.headers_url);
771 writer->json_keyvalue("sourceUrl",
772 node::per_process::metadata.release.source_url);
773 #ifdef _WIN32
774 writer->json_keyvalue("libUrl", node::per_process::metadata.release.lib_url);
775 #endif // _WIN32
776 #endif // NODE_HAS_RELEASE_URLS
777
778 writer->json_objectend();
779 }
780
781 } // namespace report
782