-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_dbbackup.js
68 lines (61 loc) · 2.03 KB
/
app_dbbackup.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
const FS = require('fs');
const Path = require('path');
const mongoose = require('mongoose');
const Moment = require('moment');
const Bunyan = require('bunyan');
const log = Bunyan.createLogger({ name: "polamikat:app", streams:[{path: Path.join(__dirname, 'dbbackup.log')}] });
var mode = process.env.MODE ? process.env.MODE : "local";
process.env.TZ = 'Asia/Jakarta';
//read properties.json
PROPERTIES = JSON.parse(FS.readFileSync(Path.join(__dirname, 'resources/properties.json'), 'utf8'))[mode];
var backup = require('mongodb-backup');
var backupDir = Path.join(__dirname, 'backup');
try {
FS.accessSync(backupDir);
} catch (e) {
log.warn("backup dir doesnot exist yet, creating...");
FS.mkdirSync(backupDir);
}
var todayDateStr = Moment().format("YYYYMMDD");
var backupFileName = 'dump'+todayDateStr+'.tar';
log.info("Starting backup");
backup({
uri: PROPERTIES.mongodb,
root: backupDir, // write files into this dir
tar: backupFileName, // save backup into this tar file
callback: function(err) {
if (err) {
log.error(err);
} else {
log.info('Finish backup to ', backupFileName);
// check dir backup
FS.readdir(backupDir, function(err, items) {
if (items.length > 10) {
var checkTime = Moment();
var oldest = checkTime;
for (var i = 0; i < items.length; ++i) {
var matched = items[i].match(/[0-9]{8}/);
if (matched) {
var m = Moment(matched[0],"YYYYMMDD");
if (m < oldest) {
oldest = m;
}
}
}
if (checkTime != oldest) {
log.info("oldest ", oldest.format("YYYYMMDD"));
FS.unlink(Path.join(backupDir, 'dump'+oldest.format("YYYYMMDD")+'.tar'), function(err) {
if (err) {
log.error("unlink error ", err);
} else {
log.info("Oldest file deleted.");
}
});
} else {
log.info("no oldest is found");
}
}
});
}
}
});