/
memory.ts
123 lines (115 loc) · 3.87 KB
/
memory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import * as appRoot from "app-root-path";
import * as fs from "fs";
import * as os from "os";
import { logger } from "../../util/logger";
import { broadcast } from "../transport/cluster/messages";
let DataDirectory = `${appRoot.path}/heap`;
/**
* Initialise memory monitoring. This is will set the data directory for heap dumps and
* print the head usage to the console every 60 seconds.
* @param {string} dataDirectory
*/
export function initMemoryMonitoring(dataDirectory: string = `${appRoot.path}/heap`, log: boolean = true) {
logger.debug("Initialising memory monitoring");
DataDirectory = dataDirectory;
if (log) {
setInterval(() => {
logger.debug("Memory statistics '%j'", memoryUsage());
}, 60000);
}
}
/**
* Create a head dump that can be downloaded and used to profile head usage.
* @returns {string}
*/
export function mtrace(): void {
try {
logger.debug("Memory statistics '%j'", memoryUsage());
const mtrace = require("mtrace");
gc();
const filename = mtrace.mtrace();
if (!!filename) {
logger.debug("mtrace dump written to '%s'", filename);
} else {
logger.warn("mtrace not supported");
}
broadcast({ type: "atomist:gc" });
broadcast({ type: "atomist:mtrace" });
return;
} catch (err) {
logger.error("Failed to initialise mtrace. Required 'mtrace' module is missing or can't be" +
" loaded. Please install with 'npm install --save mtrace'");
}
}
/**
* Create a head dump that can be downloaded and used to profile head usage.
* @returns {string}
*/
export function heapDump(): string {
try {
logger.debug("Memory statistics '%j'", memoryUsage());
// tslint:disable-next-line:no-implicit-dependencies
const heapdump = require("heapdump");
const name = `heapdump-${process.pid}-${Date.now()}.heapsnapshot`;
if (!fs.existsSync(DataDirectory)) {
fs.mkdirSync(DataDirectory);
}
gc();
heapdump.writeSnapshot(`${DataDirectory}/${name}`, (err, filename) => {
logger.debug("Heap dump written to '%s'", filename);
});
broadcast({ type: "atomist:gc" });
broadcast({ type: "atomist:heapdump" });
return name;
} catch (err) {
logger.error("Failed to initialise memory monitoring. Required 'heapdump' module is missing or can't be" +
" loaded. Please install with 'npm install --save heapdump'");
}
}
/**
* Get some memory statistics.
* @returns {{heap: {rss: string; total: string; used: string}; memory: {free: string; total: string}; up_time: string}}
*/
export function memoryUsage() {
const mem = process.memoryUsage();
const usage = {
heap: {
rss: (mem.rss / 1024 / 1024).toFixed(2),
total: (mem.heapTotal / 1024 / 1024).toFixed(2),
used: (mem.heapUsed / 1024 / 1024).toFixed(2),
},
memory: {
free: (os.freemem() / 1024 / 1024).toFixed(2),
total: (os.totalmem() / 1024 / 1024).toFixed(2),
},
up_time: formatMillis(process.uptime() * 1000),
};
return usage;
}
/**
* Trigger gargabe collect.
* This required the process to run with --expose_gc.
*/
export function gc() {
if (global.gc) {
logger.debug("Triggering GC");
global.gc();
logger.debug("Memory statistics: %j", memoryUsage());
broadcast({ type: "atomist:gc" });
}
}
function formatMillis(millis: number): string {
const date = new Date(millis);
let str = "";
if (date.getUTCDate() > 1) {
str += date.getUTCDate() - 1 + " d, ";
}
if (date.getUTCHours() > 0) {
str += date.getUTCHours() + " hr, ";
}
if (date.getUTCMinutes() > 0) {
str += date.getUTCMinutes() + " min, ";
}
str += date.getUTCSeconds() + " s";
return str;
}