-
Notifications
You must be signed in to change notification settings - Fork 0
/
backupGenerator.js
71 lines (64 loc) · 2.66 KB
/
backupGenerator.js
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
var fs = require('fs');
var _ = require('lodash');
var exec = require('child_process').exec;
var dbOptions = {
user: '',
pass: '',
host: 'localhost',
port: 27017,
database: '',
autoBackup: true,
removeOldBackup: true,
keepLastDaysBackup: 2,
autoBackupPath: '' // i.e. /var/database-backup/
};
/* return date object */
exports.stringToDate = function (dateString) {
return new Date(dateString);
}
/* return if variable is empty or not. */
exports.empty = function (mixedVar) {
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixedVar === emptyValues[i]) {
return true;
}
}
if (typeof mixedVar === 'object') {
for (key in mixedVar) {
return false;
}
return true;
}
return false;
};
// Auto backup script
dbAutoBackUp: function () {
// check for auto backup is enabled or disabled
if (dbOptions.autoBackup == true) {
var date = new Date();
var beforeDate, oldBackupDir, oldBackupPath;
currentDate = this.stringToDate(date); // Current date
var newBackupDir = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate();
var newBackupPath = dbOptions.autoBackupPath + 'mongodump-' + newBackupDir; // New backup path for current backup process
// check for remove old backup after keeping # of days given in configuration
if (dbOptions.removeOldBackup == true) {
beforeDate = _.clone(currentDate);
beforeDate.setDate(beforeDate.getDate() - dbOptions.keepLastDaysBackup); // Substract number of days to keep backup and remove old backup
oldBackupDir = beforeDate.getFullYear() + '-' + (beforeDate.getMonth() + 1) + '-' + beforeDate.getDate();
oldBackupPath = dbOptions.autoBackupPath + 'mongodump-' + oldBackupDir; // old backup(after keeping # of days)
}
var cmd = 'mongodump --host ' + dbOptions.host + ' --port ' + dbOptions.port + ' --db ' + dbOptions.database + ' --username ' + dbOptions.user + ' --password ' + dbOptions.pass + ' --out ' + newBackupPath; // Command for mongodb dump process
exec(cmd, function (error, stdout, stderr) {
if (this.empty(error)) {
// check for remove old backup after keeping # of days given in configuration
if (dbOptions.removeOldBackup == true) {
if (fs.existsSync(oldBackupPath)) {
exec("rm -rf " + oldBackupPath, function (err) {});
}
}
}
});
}
}