This repository has been archived by the owner on Nov 17, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
202 lines (178 loc) · 5.43 KB
/
index.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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
'use strict';
var s3 = require('s3'),
_ = require('lodash'),
shell = require('shelljs'),
winston = require('winston'),
fs = require('fs'),
q = require('q'),
log = new winston.Logger({
transports: [
new winston.transports.Console({
timestamp: true,
level: 'debug'
}),
new winston.transports.File({
filename: __dirname + '/backups.log',
level: 'debug'
})
]
});
/**
* Checks if the configuration given is valid
* @param {Object} config Config object
* @return {Boolean}
*/
function validateConfig(config) {
return config.accessKeyId && config.secretAccessKey && config.region && config.dbUser
&& config.dbName && config.dbPassword && Number(config.interval)
&& config.bucket;
}
/**
* Retrieves the config options
* @return {Object|undefined} The config object or undefined if is not valid or is missing
*/
function getConfig() {
var config;
try {
config = require(__dirname + '/config.json');
} catch (err) {
log.error(_.template('No config.json file found at "<%= path %>"!', {
path: __dirname
}));
}
return (typeof config === 'object' && validateConfig(config)) ? config : undefined;
}
/**
* Creates a new instance of the S3 client
* @param {Object} config Config object
* @return {Object} S3 client
*/
function createS3Client(config) {
return s3.createClient({
s3Options: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region
}
});
}
/**
* Generates a name for the dump file
* @param {String} dbName Database name
* @return {String} File name
*/
function generateBackupFilename(dbName) {
return __dirname + _.template('/backup_<%= db %>_<%= time %>.sql', {
db: dbName,
time: new Date().getTime() + ''
});
}
/**
* Returns the final Key the file will have in amazon s3.
* @param {String} filename Filename
* @param {Object} config Config object
* @return {String} Amazon s3 key id
*/
function getFinalFilename(filename, config) {
var fileParts = filename.split('/'),
name = fileParts[fileParts.length - 1];
return config.keyPrefix ? config.keyPrefix + name : name;
}
/**
* Dumps the mysql database to a file.
* @param {Object} config Config object
* @return {q.promise}
*/
function performBackup(config) {
var deferred = q.defer(),
cmdTpl = '<%= cmd %> --hex-blob -h <%= host %> -P <%= port %> -u <%= user %> -p\'<%= pass %>\' <%= database %> > <%= filename %>',
filename = generateBackupFilename(config.dbName),
cmd = _.template(cmdTpl, {
cmd: config.overrideCommand || 'mysqldump',
host: config.dbHost || 'localhost',
port: config.dbPort || 3306,
user: config.dbUser,
pass: config.dbPassword,
database: config.dbName,
filename: filename
});
log.info("Running: " , cmd);
shell.exec(cmd, {silent: true}, function (code, output) {
if (code !== undefined && code !== 0) {
log.error("Unable to perform a backup at " + new Date().toISOString());
deferred.reject();
} else {
// we have a limitation of 20 mb, so we exec the command with the filename and dont use the stream:
// output.to(filename);
deferred.resolve(filename);
}
});
return deferred.promise;
}
/**
* Uploads the backup file to amazon s3
* @param {String} filename Filename
* @param {Object} config Config object
* @return {q.promise}
*/
function uploadBackup(filename, config) {
var deferred = q.defer(),
client = createS3Client(config),
uploader = client.uploadFile({
localFile: filename,
s3Params: {
Bucket: config.bucket,
Key: getFinalFilename(filename, config)
}
});
uploader.on('error', function (err) {
log.error('Unable to upload file to Amazon S3 at ' + new Date().toISOString());
deferred.reject();
});
uploader.on('end', function () {
log.info(_.template('Successfully uploaded file "<%= file %>" to amazon s3', {
file: filename
}));
deferred.resolve(true);
});
return deferred.promise;
}
/**
* Performs the database backup
* @param {Object} config Config object
* @return {q.promie}
*/
function run(config) {
var deferred = q.defer();
performBackup(config).then(function (filename) {
var remove = function () {
fs.unlinkSync(filename);
};
uploadBackup(filename, config).then(function () {
remove();
deferred.resolve();
}, function () {
deferred.reject();
});
}, function () {
deferred.reject();
});
return deferred.promise;
}
function main () {
var config = getConfig();
if (!config) {
log.error('Config file is not valid!');
return;
}
log.info('Starting backup daemon...');
var action = function () {
log.info('Performing database backup...');
run(config).then(function () {
log.info('Successfully performed database backup...');
});
setTimeout(action, Number(config.interval) * 1000);
};
action();
}
main();