-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
436 lines (375 loc) · 11.7 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
'use strict'
const co = require('co');
const got = require('got');
const moment = require('moment');
const spawn = require('cross-spawn');
const webdavFactory = require('webdav');
const yargs = require('yargs');
const TIMEOUT = 12 * 60 * 60 * 1000;
const REQUEST_TIMEOUT = 4 * 60 * 60 * 1000;
const RETRY_DELAY = 10 * 1000;
const DAV_BASE_URLS = {
box: 'https://dav.box.com/dav',
yandex: 'https://webdav.yandex.com'
};
module.exports = (args) => {
const defaultOptions = {
mysqlHost: 'localhost',
'mysql-host': 'localhost',
mysqlPort: 3306,
'mysql-port': 3306,
mongoHost: 'localhost',
'mongo-host': 'localhost',
mongoPort: 27017,
'mongo-port': 27017
};
const options = parseOptions(args);
for (const defaultOptionKey of Object.keys(defaultOptions)) {
// missing yargs args are `undefined`
if (options[defaultOptionKey] === undefined) {
options[defaultOptionKey] = defaultOptions[defaultOptionKey];
}
}
const { dirs, name, daysToKeep, retries, dav: davType, davDir, davLogin, davPass, mysqlDb, mongoDb } = options;
console.time('Execution time');
process.on('exit', () => {
console.timeEnd('Execution time');
});
setTimeout(() => {
console.warn('Timeout');
process.exit(1);
}, TIMEOUT);
if (!(dirs && dirs.length) && !mysqlDb && !mongoDb) {
console.log('No directories or databases to backup');
process.exit(1);
}
const davBaseUrl = DAV_BASE_URLS[davType] || davType;
const dav = webdavFactory(davBaseUrl, davLogin, davPass);
const BACKUP_FILENAME_REGEXP = new RegExp(`^backup-${name}_(?:(mysql|mongo)-.+?_|)(\\d{4}-\\d{2}-\\d{2})_(\\d{2}-\\d{2}-\\d{2}-\\d{3})(?:\\.tgz|\\.tar(?:\\.gz|)|\\.sql(?:\\.gz|))$`);
co(function* () {
let davDirContents;
const davDirSegments = davDir.split('/').filter(Boolean);
let i = 0;
do {
// start with no segment
const segmentedDavDir = '/' + davDirSegments.slice(0, i).join('/');
try {
davDirContents = yield dav.getDirectoryContents(segmentedDavDir);
} catch (err) {
// create backup dir if doesn't exists
if (err.status === 404) {
console.log(`Creating directory: ${segmentedDavDir}`);
yield dav.createDirectory(segmentedDavDir);
} else if (err.status === 401) {
console.warn('Wrong credentials');
process.exit(1);
} else {
throw err;
}
}
i++;
} while (i <= davDirSegments.length);
// delete older backups
if (daysToKeep > 0 && daysToKeep < Infinity) {
const obsoleteMoment = moment().subtract(moment.duration(daysToKeep, 'days').asMilliseconds(), 'ms');
for (const { type, lastmod, filename: filePath, basename } of davDirContents) {
const lastModifiedMoment = moment(lastmod);
if (type === 'file' && BACKUP_FILENAME_REGEXP.test(basename) && lastModifiedMoment.isBefore(obsoleteMoment)) {
console.log(`Deleting old backup: ${filePath}`);
yield dav.deleteFile(filePath);
}
}
}
function* backup(backupFn, retriesCount = 0) {
try {
yield backupFn(davBaseUrl, options);
} catch (err) {
console.warn(err);
const { backupFilename } = err;
if (backupFilename) {
const brokenFilePath = `${davDir}/${err.backupFilename}`;
try {
console.log(`Deleting broken backup: ${brokenFilePath}`);
yield dav.deleteFile(brokenFilePath);
} catch (err) {
if (err.status === 401) {
console.warn('Wrong credentials');
} else if (err.status !== 404) {
console.warn(err);
}
}
}
if (retriesCount < retries) {
retriesCount++;
console.log(`Retrying`);
const delayPromise = new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
yield delayPromise;
yield* backup(backupFn, retriesCount);
}
}
}
// backup directories
if (dirs && dirs.length) {
yield* backup(backupTar);
console.log('Directory dump completed');
}
// backup MySQL database
if (mysqlDb) {
yield* backup(backupMysql);
console.log('MySQL dump completed');
}
// backup Mongo database
if (mongoDb) {
yield* backup(backupMongo);
console.log('MongoDB dump completed');
}
})
.then(() => {
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
};
function backupTar(davBaseUrl, options) {
const { dirs, excludeDirs, name, davDir, davLogin, davPass } = options;
const backupPromise = new Promise((resolve, reject) => {
const backupFilename = `backup-${name}_` + moment().format('YYYY-MM-DD_HH-mm-ss-SSS') + '.tgz';
const excludeDirsArgs = (excludeDirs && excludeDirs.length)
? excludeDirs.map(dir => `--exclude="${dir}"`)
: [];
// tar --create --gzip --absolute-names
const tarProcess = spawn('tar', ['--create', '--gzip', '--absolute-names', '--warning=no-file-changed', '--warning=no-file-removed', ...excludeDirsArgs, ...dirs], { stdio: ['ignore', 'pipe', 'inherit'] });
tarProcess.on('error', reject);
tarProcess.on('exit', (code, _signal) => {
// ignore warnings
if (code > 1) {
const err = new Error(`Directory backup failed with code ${code}`);
err.backupFilename = backupFilename;
reject(err);
}
});
const tarStream = tarProcess.stdout;
const credentials = new Buffer(`${davLogin}:${davPass}`).toString('base64');
const putUrl = `${davBaseUrl}${davDir}/${backupFilename}`;
console.log(`Uploading: ${putUrl}`);
const putRequestStream = got.stream.put(putUrl, {
headers: { Authorization: `Basic ${credentials}` },
timeout: REQUEST_TIMEOUT,
followRedirect: true // avoid 302 Found errors
});
putRequestStream.on('error', err => {
if (err.statusCode === 507) {
console.warn('Not enough storage space');
process.exit(1);
} else {
reject(err);
}
});
// should wait for response
putRequestStream.on('response', ({ statusCode, statusMessage }) => {
if (statusCode === 201) {
resolve();
} else {
const err = new Error(`Directory backup upload failed with ${statusCode} ${statusMessage}`);
err.backupFilename = backupFilename;
reject(err);
}
});
tarStream.pipe(putRequestStream);
});
return backupPromise;
}
function backupMysql(davBaseUrl, options) {
const { name, davDir, davLogin, davPass, mysqlDb, mysqlHost, mysqlPort, mysqlLogin, mysqlPass } = options;
const backupPromise = new Promise((resolve, reject) => {
const backupFilename = `backup-${name}_mysql-${mysqlDb}_` + moment().format('YYYY-MM-DD_HH-mm-ss-SSS') + '.sql.gz';
const mysqlPassArg = mysqlPass ? `--password=${mysqlPass}` : '';
// TODO: stderr Warning: Using a password on the command line interface can be insecure
const mysqldumpProcess = spawn(
[
`mysqldump --databases ${mysqlDb} --host=${mysqlHost} --port=${mysqlPort} --user=${mysqlLogin} ${mysqlPassArg}`,
`gzip --stdout -9`
].join(' | '),
{
shell: true,
stdio: ['ignore', 'pipe', 'inherit']
}
);
mysqldumpProcess.on('error', reject);
mysqldumpProcess.on('exit', (code, _signal) => {
if (code) {
const err = new Error(`Database backup failed with code ${code}`);
err.backupFilename = backupFilename;
reject(err);
}
});
const mysqlStream = mysqldumpProcess.stdout;
const credentials = new Buffer(`${davLogin}:${davPass}`).toString('base64');
const putUrl = `${davBaseUrl}${davDir}/${backupFilename}`;
console.log(`Uploading: ${putUrl}`);
const putRequestStream = got.stream.put(putUrl, {
headers: { Authorization: `Basic ${credentials}` },
timeout: REQUEST_TIMEOUT,
followRedirect: true // avoid 302 Found errors
});
putRequestStream.on('error', err => {
if (err.statusCode === 507) {
console.warn('Not enough storage space');
process.exit(1);
} else {
reject(err);
}
});
// should wait for response
putRequestStream.on('response', ({ statusCode, statusMessage }) => {
if (statusCode === 201) {
resolve();
} else {
const err = new Error(`Database backup upload failed with ${statusCode} ${statusMessage}`);
err.backupFilename = backupFilename;
reject(err);
}
});
mysqlStream.pipe(putRequestStream);
});
return backupPromise;
}
function backupMongo(davBaseUrl, options) {
const { name, davDir, davLogin, davPass, mongoDb, mongoHost, mongoPort, mongoLogin, mongoPass } = options;
const backupPromise = new Promise((resolve, reject) => {
const backupFilename = `backup-${name}_mongo-${mongoDb}_` + moment().format('YYYY-MM-DD_HH-mm-ss-SSS') + '.sql.gz';
const mongoLoginArg = mongoLogin ? `--username=${mongoLogin}` : '';
const mongoPassArg = mongoPass ? `--password=${mongoPass}` : '';
const mongodumpProcess = spawn(
`mongodump`,
[`--quiet`, `--archive`, `--gzip`, `--db=${mongoDb}`, `--host=${mongoHost}`, `--port=${mongoPort}`, ...[mongoLoginArg, mongoPassArg].filter(Boolean)],
{ stdio: ['ignore', 'pipe', 'inherit'] }
);
mongodumpProcess.on('error', reject);
mongodumpProcess.on('exit', (code, _signal) => {
if (code) {
const err = new Error(`Database backup failed with code ${code}`);
err.backupFilename = backupFilename;
reject(err);
}
});
const mongoStream = mongodumpProcess.stdout;
const credentials = new Buffer(`${davLogin}:${davPass}`).toString('base64');
const putUrl = `${davBaseUrl}${davDir}/${backupFilename}`;
console.log(`Uploading: ${putUrl}`);
const putRequestStream = got.stream.put(putUrl, {
headers: { Authorization: `Basic ${credentials}` },
timeout: REQUEST_TIMEOUT,
followRedirect: true // avoid 302 Found errors
});
putRequestStream.on('error', err => {
if (err.statusCode === 507) {
console.warn('Not enough storage space');
process.exit(1);
} else {
reject(err);
}
});
// should wait for response
putRequestStream.on('response', ({ statusCode, statusMessage }) => {
if (statusCode === 201) {
resolve();
} else {
const err = new Error(`Database backup upload failed with ${statusCode} ${statusMessage}`);
err.backupFilename = backupFilename;
reject(err);
}
});
mongoStream.pipe(putRequestStream);
});
return backupPromise;
}
function parseOptions(args) {
const options = yargs(args)
.option('name', {
type: 'string',
check: name => /^[a-z0-9]+$/i.test(name),
demandOption: true,
desc: 'Alphanumeric'
})
.option('daysToKeep', {
type: 'number',
default: Infinity
})
.option('retries', {
type: 'number',
default: 1
})
.option('dirs', {
type: 'array'
})
.option('excludeDirs', {
type: 'array',
implies: 'dirs'
})
.option('dav', {
type: 'string',
choices: ['box', 'yandex'],
implies: 'davLogin',
demandOption: true
})
.option('davDir', {
type: 'string',
default: '/backup',
coerce: path => '/' + path.replace(/^\/|\/$/, ''),
implies: 'dav'
})
.option('davLogin', {
type: 'string',
demandOption: true,
implies: 'davPass'
})
.option('davPass', {
type: 'string',
demandOption: true
})
.option('mysqlDb', {
type: 'string',
implies: 'mysqlLogin'
})
.option('mysqlLogin', {
type: 'string',
implies: 'mysqlDb'
})
.option('mysqlPass', {
type: 'string',
implies: 'mysqlDb'
})
.option('mysqlHost', {
type: 'string',
implies: 'mysqlDb'
})
.option('mysqlPort', {
type: 'number',
implies: 'mysqlDb'
})
.option('mongoDb', {
type: 'string'
})
.option('mongoLogin', {
type: 'string',
implies: 'mongoDb'
})
.option('mongoPass', {
type: 'string',
implies: 'mongoDb'
})
.option('mongoHost', {
type: 'string',
implies: 'mongoDb'
})
.option('mongoPort', {
type: 'number',
implies: 'mongoDb'
})
.help()
.argv;
return options;
}