forked from IBM/couchbackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
385 lines (361 loc) · 14.7 KB
/
app.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
// Copyright © 2017, 2020 IBM Corp. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
/**
* CouchBackup module.
* @module couchbackup
* @see module:couchbackup
*/
const backupFull = require('./includes/backup.js');
const defaults = require('./includes/config.js').apiDefaults;
const error = require('./includes/error.js');
const request = require('./includes/request.js');
const restoreInternal = require('./includes/restore.js');
const backupShallow = require('./includes/shallowbackup.js');
const debug = require('debug')('couchbackup:app');
const events = require('events');
const fs = require('fs');
const URL = require('url').URL;
/**
* Test for a positive, safe integer.
*
* @param {object} x - Object under test.
*/
function isSafePositiveInteger(x) {
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
// Is it a number?
return Object.prototype.toString.call(x) === '[object Number]' &&
// Is it an integer?
x % 1 === 0 &&
// Is it positive?
x > 0 &&
// Is it less than the maximum safe integer?
x <= MAX_SAFE_INTEGER;
}
/**
* Validate arguments.
*
* @param {object} url - URL of database.
* @param {object} opts - Options.
* @param {function} cb - Callback to be called on error.
*/
function validateArgs(url, opts, cb) {
if (typeof url !== 'string') {
cb(new error.BackupError('InvalidOption', 'Invalid URL, must be type string'), null);
return;
}
if (opts && typeof opts.bufferSize !== 'undefined' && !isSafePositiveInteger(opts.bufferSize)) {
cb(new error.BackupError('InvalidOption', 'Invalid buffer size option, must be a positive integer in the range (0, MAX_SAFE_INTEGER]'), null);
return;
}
if (opts && typeof opts.iamApiKey !== 'undefined' && typeof opts.iamApiKey !== 'string') {
cb(new error.BackupError('InvalidOption', 'Invalid iamApiKey option, must be type string'), null);
return;
}
if (opts && typeof opts.log !== 'undefined' && typeof opts.log !== 'string') {
cb(new error.BackupError('InvalidOption', 'Invalid log option, must be type string'), null);
return;
}
if (opts && typeof opts.mode !== 'undefined' && ['full', 'shallow'].indexOf(opts.mode) === -1) {
cb(new error.BackupError('InvalidOption', 'Invalid mode option, must be either "full" or "shallow"'), null);
return;
}
if (opts && typeof opts.output !== 'undefined' && typeof opts.output !== 'string') {
cb(new error.BackupError('InvalidOption', 'Invalid output option, must be type string'), null);
return;
}
if (opts && typeof opts.parallelism !== 'undefined' && !isSafePositiveInteger(opts.parallelism)) {
cb(new error.BackupError('InvalidOption', 'Invalid parallelism option, must be a positive integer in the range (0, MAX_SAFE_INTEGER]'), null);
return;
}
if (opts && typeof opts.requestTimeout !== 'undefined' && !isSafePositiveInteger(opts.requestTimeout)) {
cb(new error.BackupError('InvalidOption', 'Invalid request timeout option, must be a positive integer in the range (0, MAX_SAFE_INTEGER]'), null);
return;
}
if (opts && typeof opts.resume !== 'undefined' && typeof opts.resume !== 'boolean') {
cb(new error.BackupError('InvalidOption', 'Invalid resume option, must be type boolean'), null);
return;
}
// Validate URL and ensure no auth if using key
try {
const urlObject = new URL(url);
// We require a protocol, host and path (for db), fail if any is missing.
if (urlObject.protocol !== 'https:' && urlObject.protocol !== 'http:') {
cb(new error.BackupError('InvalidOption', 'Invalid URL protocol.'));
return;
}
if (!urlObject.host) {
cb(new error.BackupError('InvalidOption', 'Invalid URL host.'));
return;
}
if (!urlObject.pathname || urlObject.pathname === '/') {
cb(new error.BackupError('InvalidOption', 'Invalid URL, missing path element (no database).'));
return;
}
if (opts && opts.iamApiKey && (urlObject.username || url.password)) {
cb(new error.BackupError('InvalidOption', 'URL user information must not be supplied when using IAM API key.'));
return;
}
} catch (err) {
cb(err);
return;
}
// Perform validation of invalid options for shallow mode and WARN
// We don't error for backwards compatibility with scripts that may have been
// written passing complete sets of options through
if (opts && opts.mode === 'shallow') {
if (opts.log || opts.resume) {
console.warn('WARNING: the options "log" and "resume" are invalid when using shallow mode.');
}
if (opts.parallelism) {
console.warn('WARNING: the option "parallelism" has no effect when using shallow mode.');
}
}
if (opts && opts.resume) {
if (!opts.log) {
// This is the second place we check for the presence of the log option in conjunction with resume
// It has to be here for the API case
cb(new error.BackupError('NoLogFileName', 'To resume a backup, a log file must be specified'), null);
return;
} else if (!fs.existsSync(opts.log)) {
cb(new error.BackupError('LogDoesNotExist', 'To resume a backup, the log file must exist'), null);
return;
}
}
return true;
}
function addEventListener(indicator, emitter, event, f) {
emitter.on(event, function(...args) {
if (!indicator.errored) {
if (event === 'error') indicator.errored = true;
f(...args);
}
});
}
/*
Check the referenced database exists and that the credentials used have
visibility. Callback with a fatal error if there is a problem with the DB.
@param {string} db - database object
@param {function(err)} callback - error is undefined if DB exists
*/
function proceedIfDbValid(db, callback) {
db.server.request({ db: db.config.db, method: 'HEAD' }, function(err) {
err = error.convertResponseError(err, function(err) {
if (err && err.statusCode === 404) {
// Override the error type and mesasge for the DB not found case
var msg = `Database ${db.config.url.replace(/\/\/.+@/g, '//****:****@')}` +
`/${db.config.db} does not exist. ` +
'Check the URL and database name have been specified correctly.';
var noDBErr = new Error(msg);
noDBErr.name = 'DatabaseNotFound';
return noDBErr;
} else {
// Delegate to the default error factory if it wasn't a 404
return error.convertResponseError(err);
}
});
// Callback with or without (i.e. undefined) error
callback(err);
});
}
module.exports = {
/**
* Backup a Cloudant database to a stream.
*
* @param {string} srcUrl - URL of database to backup.
* @param {stream.Writable} targetStream - Stream to write content to.
* @param {object} opts - Backup options.
* @param {number} [opts.parallelism=5] - Number of parallel HTTP requests to use.
* @param {number} [opts.bufferSize=500] - Number of documents per batch request.
* @param {number} [opts.requestTimeout=120000] - Milliseconds to wait before retrying a HTTP request.
* @param {string} [opts.iamApiKey] - IAM API key to use to access Cloudant database.
* @param {string} [opts.log] - Log file name. Default uses a temporary file.
* @param {boolean} [opts.resume] - Whether to resume from existing log.
* @param {string} [opts.mode=full] - Use `full` or `shallow` mode.
* @param {backupRestoreCallback} callback - Called on completion.
*/
backup: function(srcUrl, targetStream, opts, callback) {
var listenerErrorIndicator = { errored: false };
if (typeof callback === 'undefined' && typeof opts === 'function') {
callback = opts;
opts = {};
}
if (!validateArgs(srcUrl, opts, callback)) {
// bad args, bail
return;
}
// if there is an error writing to the stream, call the completion
// callback with the error set
addEventListener(listenerErrorIndicator, targetStream, 'error', function(err) {
debug('Error ' + JSON.stringify(err));
if (callback) callback(err);
});
opts = Object.assign({}, defaults(), opts);
const ee = new events.EventEmitter();
// Set up the DB client
const backupDB = request.client(srcUrl, opts);
// Validate the DB exists, before proceeding to backup
proceedIfDbValid(backupDB, function(err) {
if (err) {
if (err.name === 'DatabaseNotFound') {
err.message = `${err.message} Ensure the backup source database exists.`;
}
// Didn't exist, or another fatal error, exit
callback(err);
return;
}
var backup = null;
if (opts.mode === 'shallow') {
backup = backupShallow;
} else { // full mode
backup = backupFull;
}
// If resuming write a newline as it's possible one would be missing from
// an interruption of the previous backup. If the backup was clean this
// will cause an empty line that will be gracefully handled by the restore.
if (opts.resume) {
targetStream.write('\n');
}
// Get the event emitter from the backup process so we can handle events
// before passing them on to the app's event emitter if needed.
const internalEE = backup(backupDB, opts);
addEventListener(listenerErrorIndicator, internalEE, 'changes', function(batch) {
ee.emit('changes', batch);
});
addEventListener(listenerErrorIndicator, internalEE, 'received', function(obj, q, logCompletedBatch) {
// this may be too verbose to have as well as the "backed up" message
// debug(' received batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time);
// Callback to emit the written event when the content is flushed
function writeFlushed() {
ee.emit('written', { total: obj.total, time: obj.time, batch: obj.batch });
if (logCompletedBatch) {
logCompletedBatch(obj.batch);
}
debug(' backed up batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time);
}
// Write the received content to the targetStream
const continueWriting = targetStream.write(JSON.stringify(obj.data) + '\n',
'utf8',
writeFlushed);
if (!continueWriting) {
// The buffer was full, pause the queue to stop the writes until we
// get a drain event
if (q && !q.paused) {
q.pause();
targetStream.once('drain', function() {
q.resume();
});
}
}
});
// For errors we expect, may or may not be fatal
addEventListener(listenerErrorIndicator, internalEE, 'error', function(err) {
debug('Error ' + JSON.stringify(err));
callback(err);
});
addEventListener(listenerErrorIndicator, internalEE, 'finished', function(obj) {
function emitFinished() {
debug('Backup complete - written ' + JSON.stringify(obj));
const summary = { total: obj.total };
ee.emit('finished', summary);
if (callback) callback(null, summary);
}
if (targetStream === process.stdout) {
// stdout cannot emit a finish event so use a final write + callback
targetStream.write('', 'utf8', emitFinished);
} else {
// If we're writing to a file, end the writes and register the
// emitFinished function for a callback when the file stream's finish
// event is emitted.
targetStream.end('', 'utf8', emitFinished);
}
});
});
return ee;
},
/**
* Restore a backup from a stream.
*
* @param {stream.Readable} srcStream - Stream containing backed up data.
* @param {string} targetUrl - Target database.
* @param {object} opts - Restore options.
* @param {number} opts.parallelism - Number of parallel HTTP requests to use. Default 5.
* @param {number} opts.bufferSize - Number of documents per batch request. Default 500.
* @param {number} opts.requestTimeout - Milliseconds to wait before retrying a HTTP request. Default 120000.
* @param {string} opts.iamApiKey - IAM API key to use to access Cloudant database.
* @param {backupRestoreCallback} callback - Called on completion.
*/
restore: function(srcStream, targetUrl, opts, callback) {
var listenerErrorIndicator = { errored: false };
if (typeof callback === 'undefined' && typeof opts === 'function') {
callback = opts;
opts = {};
}
validateArgs(targetUrl, opts, callback);
opts = Object.assign({}, defaults(), opts);
const ee = new events.EventEmitter();
// Set up the DB client
const restoreDB = request.client(targetUrl, opts);
// Validate the DB exists, before proceeding to restore
proceedIfDbValid(restoreDB, function(err) {
if (err) {
if (err.name === 'DatabaseNotFound') {
err.message = `${err.message} Create the target database before restoring.`;
}
// Didn't exist, or another fatal error, exit
callback(err);
return;
}
restoreInternal(
restoreDB,
opts,
srcStream,
ee,
function(err, writer) {
if (err) {
callback(err, null);
return;
}
if (writer != null) {
addEventListener(listenerErrorIndicator, writer, 'restored', function(obj) {
debug(' restored ', obj.total);
ee.emit('restored', { documents: obj.documents, total: obj.total });
});
addEventListener(listenerErrorIndicator, writer, 'error', function(err) {
debug('Error ' + JSON.stringify(err));
// Only call destroy if it is available on the stream
if (srcStream.destroy && srcStream.destroy instanceof Function) {
srcStream.destroy();
}
callback(err);
});
addEventListener(listenerErrorIndicator, writer, 'finished', function(obj) {
debug('restore complete');
ee.emit('finished', { total: obj.total });
callback(null, obj);
});
}
}
);
});
return ee;
}
};
/**
* Backup/restore callback
* @callback backupRestoreCallback
* @param {Error} err - Error object if operation failed.
* @param {object} data - summary data for backup/restore
*/