Skip to content

Instantly share code, notes, and snippets.

@kristofsajdak
Created August 11, 2015 16:37
Show Gist options
  • Save kristofsajdak/7c0e438f3a0642f5e623 to your computer and use it in GitHub Desktop.
Save kristofsajdak/7c0e438f3a0642f5e623 to your computer and use it in GitHub Desktop.
diagnose memory issues logging memwatch diffs and uploading heapdumps to a Box.com folder
var heapdump = require('heapdump');
var memwatch = require('memwatch');
var fs = require('fs');
var os = require("os");
var hostname = os.hostname();
var rest = require('restler');
var timeoutVal = process.env.DUMP_TIMEOUT_VAL;
var accessToken = process.env.BOX_ACCESS_TOKEN;
var parentId = process.env.BOX_FOLDER_PARENT_ID;
var hd = new memwatch.HeapDiff();
var periodicDump = function () {
setTimeout(function () {
var filename = Date.now() + '.heapsnapshot';
heapdump.writeSnapshot('/tmp/' + filename, function (err) {
if (err) {
console.error(err);
diffAndReschedule()
} else {
var filenameWithDirPath = '/tmp/' + filename;
var stats = fs.statSync(filenameWithDirPath);
rest.post("https://upload.box.com/api/2.0/files/content", {
multipart: true,
headers: {Authorization: 'Bearer ' + accessToken},
data: {
attributes: JSON.stringify({
name: hostname + '-' + filename,
parent: {id: parentId}
}),
file: rest.file(filenameWithDirPath, null, stats.size, null, 'image/jpg')
}
}).on("complete", function (data, response) {
if (response.statusCode == 201) {
console.log('memdiag: uploaded heapdump from ' + filename + ' to box.com');
} else {
console.log('memdiag: error uploading heapdump to box.com, status code : ' + response.statusCode);
}
fs.unlink(filenameWithDirPath);
diffAndReschedule();
}).on("error", function (err, response) {
console.log('memdiag: error uploading heapdump to box.com : ' + JSON.stringify(error, null, 2));
fs.unlink(filenameWithDirPath);
diffAndReschedule();
});
}
function diffAndReschedule() {
var diff = hd.end();
console.log('memdiag: ' + JSON.stringify(diff, null, 2));
hd = new memwatch.HeapDiff();
periodicDump();
}
});
}, timeoutVal);
};
periodicDump();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment