-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongograte.js
356 lines (299 loc) · 12.2 KB
/
mongograte.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
import { MongoClient } from 'mongodb';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import log4js from 'log4js';
import axios from 'axios';
import chalk from 'chalk';
import info from './package.json' with {type: 'json'};
(async () => {
const argv = yargs(hideBin(process.argv)).exitProcess(false).help(false).parse();
await checkForUpdate(argv.skipUpdate);
const args = getYargs();
const config = buildConfig(args);
const log = getLogger(config.errorLevel);
log.trace(config);
await migrateDatabases().catch(error => {
console.error(error.message);
});
function buildConfig(args) {
return {
databases: args.databases,
sourceDB: args.source,
targetDB: args.target,
collections: args.collections,
drop: args.drop,
dropAll: args.dropAll,
truncate: args.truncate,
limit: args.limit,
queryLimit: args.queryLimit,
timeout: args.timeout,
listen: args.listen,
insecure: args.insecure,
skipUpdate: args.skipUpdate,
verbose: args.verbose,
errorLevel: args.verbose ? 'TRACE' : 'DEBUG'
}
}
function getLogger(level = 'DEBUG') {
log4js.configure({
appenders: {
console: {
type: 'console',
layout: {
type: 'pattern',
pattern: '%[[%d{hh:mm:ss}]%] %[[%p]%] - %m'
}
}
},
categories: {
default: { appenders: ['console'], level: level }
}
});
return log4js.getLogger('console');
}
function getYargs() {
const yarg = yargs(hideBin(process.argv));
return yarg.scriptName("mongograte").usage('Usage: $0 [options]')
.option('databases', {
alias: 'd',
description: 'Target databases',
type: 'array',
demandOption: true,
})
.option('source', {
alias: 's',
description: 'Source server uri',
type: 'string',
demandOption: true,
})
.option('target', {
alias: 't',
description: 'Target server uri',
type: 'string',
demandOption: true,
})
.option('collections', {
description: 'Collections to be migrated from source database',
type: 'array'
})
.option('drop', {
description: 'Drop target collections in the target database',
type: 'boolean',
default: false
})
.option('drop-all', {
description: 'Drop all collections in the target database',
type: 'boolean',
default: false
})
.option('truncate', {
description: 'Truncate target collections in the target database',
type: 'boolean',
default: true
})
.option('limit', {
alias: 'l',
description: 'Limit of records to be migrated',
type: 'number',
default: 1000
})
.option('query-limit', {
description: 'Limit of records per query',
type: 'number',
default: 1000
})
.option('timeout', {
description: 'Allows increasing the default timeout (ms)',
type: 'number',
default: 5000
})
.option('listen', {
description: 'Listen changes in target databases|collections',
type: 'boolean',
default: false
})
.option('insecure', {
alias: 'i',
description: 'Allow use remote database as the target database',
type: 'boolean',
default: false
})
.option('skip-update', {
description: 'Skip checking for updates',
type: 'boolean',
default: false
})
.option('verbose', {
type: 'boolean',
default: false
})
.check(argv => {
if (!argv.insecure && argv.target.includes('mongodb.net')) {
throw new Error(chalk.red('It is not possible to use a remote database as the target database'));
}
if (argv.timeout < 1000) {
throw new Error(chalk.red('Timeout must be greater than 1000 ms'));
}
return true;
})
.hide('verbose')
.version('1.0.0').alias('version', 'v')
.showHelpOnFail(false, 'Specify --help for available options')
.help().alias('help', 'h')
.parserConfiguration({
'short-option-groups': false
})
.fail(error => {
console.error(error);
console.error();
yarg.showHelp();
process.exit(1);
})
.argv;
}
async function migrateDatabases() {
const sourceDbClient = new MongoClient(config.sourceDB, { serverSelectionTimeoutMS: config.timeout });
const targetDbClient = new MongoClient(config.targetDB, { serverSelectionTimeoutMS: config.timeout });
try {
log.debug(`Connecting to source database: ${config.sourceDB}`)
await sourceDbClient.connect();
log.debug(`Connecting to target database: ${config.targetDB}`)
await targetDbClient.connect();
for (const db of config.databases) {
migrateDbInitLog(db);
const sourceDb = sourceDbClient.db(db);
const targetDb = targetDbClient.db(db);
if (config.dropAll) {
await dropAllTargetCollections(targetDb);
}
log.debug('Retrieving all collections from the source database')
let sourceCollections = (await sourceDb.listCollections().toArray()).map(collection => collection.name);
if (config.collections) {
sourceCollections = getUserCollections(sourceCollections);
}
sourceCollections.sort();
log.debug('Collections found: ' + sourceCollections.join(', '));
for (const name of sourceCollections) {
const sourceCollection = sourceDb.collection(name);
const targetCollection = targetDb.collection(name);
await migrateCollection(sourceCollection, targetCollection);
if (config.listen) {
setupChangeListener(sourceCollection, targetCollection);
}
}
}
} catch (error) {
throw new Error(error.message);
} finally {
if (!config.listen) {
await sourceDbClient.close();
await targetDbClient.close();
}
}
}
function getUserCollections(sourceCollections) {
let nonExistingCollections = config.collections.filter(collection => !sourceCollections.includes(collection));
if (nonExistingCollections.length > 0) {
throw new Error(`The following collections do not exist in the source database: ${nonExistingCollections.join(", ")}`);
}
return config.collections;
}
function migrateDbInitLog(db) {
const logMessage = `==================== DATABASE ${db} ====================`;
log.debug('='.repeat(logMessage.length));
log.debug(logMessage);
log.debug('='.repeat(logMessage.length));
}
async function migrateCollection(sourceCollection, targetCollection) {
log.debug(`Migrating ${sourceCollection.collectionName}`);
if (!config.dropAll && config.drop) {
await targetCollection.drop();
} else if (config.truncate) {
await targetCollection.deleteMany({});
}
log.debug(` Deleted?: ${(config.dropAll || config.drop) ? 'yes' : 'no'}`);
log.debug(` Truncated?: ${(!config.dropAll && !config.drop && config.truncate) ? 'yes' : 'no'}`);
log.debug(' Records: ' + (await sourceCollection.countDocuments()));
const documents = [];
const BATCH_SIZE = config.queryLimit;
const cursor = sourceCollection.find().limit(config.limit).batchSize(BATCH_SIZE);
let count = 0;
while (await cursor.hasNext()) {
const document = await cursor.next();
documents.push(document);
count++;
if (documents.length === BATCH_SIZE) {
await targetCollection.insertMany(documents);
log.debug(` Documents migrated: ${count}`);
documents.length = 0;
}
}
if (documents.length > 0) {
await targetCollection.insertMany(documents);
log.debug(` Documents migrated: ${documents.length}`);
}
}
async function dropAllTargetCollections(targetDb) {
log.debug('Retrieving all collections from the target database');
const targetCollectionsNames = (await targetDb.listCollections().toArray()).map(collection => collection.name);
targetCollectionsNames.sort();
if (targetCollectionsNames.length == 0) {
log.debug('No collections found, they will be created automatically');
return;
}
log.debug('Collections found: ' + targetCollectionsNames.join(', '));
log.debug('Dropping all collections in the target database');
for (const name of targetCollectionsNames) {
await targetDb.collection(name).drop();
log.debug(`Collection deleted: ${name}`);
}
}
function setupChangeListener(sourceCollection, targetCollection) {
log.debug(` Listening changes in: ${sourceCollection.dbName}|${sourceCollection.collectionName}`);
const changeStream = sourceCollection.watch();
changeStream.on('change', async (change) => {
log.debug(`Change detected in ${sourceCollection.dbName}|${sourceCollection.collectionName}: `, change);
switch (change.operationType) {
case 'insert':
await targetCollection.insertOne(change.fullDocument);
break;
case 'update':
await targetCollection.updateOne(
{ _id: change.documentKey._id },
{ $set: change.updateDescription.updatedFields }
);
break;
case 'replace':
await targetCollection.replaceOne(
{ _id: change.documentKey._id },
change.fullDocument
);
break;
case 'delete':
await targetCollection.deleteOne({ _id: change.documentKey._id });
break;
default:
log.debug(`Operation not supported: ${change.operationType}`);
}
});
}
async function checkForUpdate(skipUpdate = false) {
if (skipUpdate) return;
const { version, author, name } = info;
let updateAvailable = false;
try {
const response = await axios.get(`https://api.github.com/repos/${author}/${name}/releases/latest`);
const latestVersion = response.data.tag_name;
if (version !== latestVersion) {
updateAvailable = true;
}
} catch (error) {
console.error(`Error checking updates, go to: https://github.com/${author}/${name}/releases/latest`);
}
if (updateAvailable) {
console.error("A new version is available!");
console.error(`Please update ${name}: https://github.com/${author}/${name}/releases/latest`);
process.exit(2);
}
}
})();