summaryrefslogtreecommitdiff
path: root/jstests/noPassthrough/backup_restore.js
blob: 40d283873e703382f10bc55bda89d2311e4733ba (plain)
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
/**
 * Test the backup/restore process:
 * - 3 node replica set
 * - Mongo CRUD client
 * - Mongo FSM client
 * - fsyncLock (or stop) Secondary
 * - cp (or rsync) DB files
 * - fsyncUnlock (or start) Secondary
 * - Start mongod as hidden secondary
 * - Wait until new hidden node becomes secondary
 *
 * Some methods for backup used in this test checkpoint the files in the dbpath. This technique will
 * not work for ephemeral storage engines, as they do not store any data in the dbpath.
 * @tags: [requires_persistence]
 */

(function() {
    "use strict";

    function runCmd (cmd) {
        runProgram('bash', '-c',  cmd);
    }

    function crudClient(host, dbName, coll) {
        // Launch CRUD client
        var crudClientCmds = "var bulkNum = 1000;" +
            "var baseNum = 100000;" +
            "var coll = db.getSiblingDB('" + dbName + "')." + coll + ";" +
            "coll.ensureIndex({x: 1});" +
            "var largeValue = new Array(1024).join('L');" +
            "Random.setRandomSeed();" +
            // run indefinitely
            "while (true) {" +
            "   try {" +
            "       var op = Random.rand();" +
            "       var match = Math.floor(Random.rand() * baseNum);" +
            "       if (op < 0.2) {" +
            // 20% of the operations: bulk insert bulkNum docs
            "           var bulk = coll.initializeUnorderedBulkOp();" +
            "           for (var i = 0; i < bulkNum; i++) {" +
            "               bulk.insert({x: (match * i) % baseNum," +
            "                   doc: largeValue.substring(0, match % largeValue.length)});" +
            "           }" +
            "           assert.writeOK(bulk.execute());" +
            "       } else if (op < 0.4) {" +
            // 20% of the operations: update docs;
            "           var updateOpts = {upsert: true, multi: true};" +
            "           assert.writeOK(coll.update(" +
            "               {x: {$gte: match}}," +
            "               {$inc: {x: baseNum}, $set: {n: 'hello'}}," +
            "               updateOpts));" +
            "       } else if (op < 0.9) {" +
            // 50% of the operations: find matchings docs
            // itcount() consumes the cursor
            "           coll.find({x: {$gte: match}}).itcount();" +
            "       } else {" +
            // 10% of the operations: remove matching docs
            "           assert.writeOK(coll.remove({x: {$gte: match}}));" +
            "       }" +
            "   } catch(e) {" +
            "       if (e instanceof ReferenceError || e instanceof TypeError) {" +
            "           throw e;" +
            "       }" +
            "   }" +
            "}";

        // Returns the pid of the started mongo shell so the CRUD test client can be terminated
        // without waiting for its execution to finish.
        return startMongoProgramNoConnect("mongo", "--eval", crudClientCmds, host);
    }

    function fsmClient(host, blackListDb, numNodes) {
        // Launch FSM client
        // SERVER-19488 The FSM framework assumes that there is an implicit 'db' connection when
        // started without any cluster options. Since the shell running this test was started with
        // --nodb, another mongo shell is used to allow implicit connections to be made to the
        // primary of the replica set.
        var fsmClientCmds = "'use strict';" +
            "load('jstests/concurrency/fsm_libs/runner.js');" +
            "var dir = 'jstests/concurrency/fsm_workloads';" +
            "var blacklist = [" +
            "    'agg_group_external.js'," +
            "    'agg_sort_external.js'," +
            "    'auth_create_role.js'," +
            "    'auth_create_user.js'," +
            "    'auth_drop_role.js'," +
            "    'auth_drop_user.js'," +
            "    'reindex_background.js'," +
            "    'yield_sort.js'," +
            "].map(function(file) { return dir + '/' + file; });" +
            "Random.setRandomSeed();" +
            // run indefinitely
            "while (true) {" +
            "   try {" +
            "       var workloads = Array.shuffle(ls(dir).filter(function(file) {" +
            "           return !Array.contains(blacklist, file);" +
            "       }));" +
            // Run workloads one at a time, so we ensure replication completes
            "       workloads.forEach(function(workload) {" +
            "           runWorkloadsSerially([workload]," +
            "               {}, {}, {dropDatabaseBlacklist: ['" + blackListDb + "']});" +
            // Wait for replication to complete between workloads
            "           var wc = {writeConcern: {w: " + numNodes + ", wtimeout: 300000}};" +
            "           var result = db.getSiblingDB('test').fsm_teardown.insert({ a: 1 }, wc);" +
            "           assert.writeOK(result, 'teardown insert failed: ' + tojson(result));" +
            "           result = db.getSiblingDB('test').fsm_teardown.drop();" +
            "           assert(result, 'teardown drop failed');" +
            "       });" +
            "   } catch(e) {" +
            "       if (e instanceof ReferenceError || e instanceof TypeError) {" +
            "           throw e;" +
            "       }" +
            "   }" +
            "}";

        // Returns the pid of the started mongo shell so the FSM test client can be terminated
        // without waiting for its execution to finish.
        return startMongoProgramNoConnect("mongo", "--eval", fsmClientCmds, host);
    }

    function runTest(options) {
        jsTestLog("Backup restore " + tojson(options));

        // Test options
        // Test name
        assert(options.name, 'Test name option not supplied');
        var testName = options.name;

        // Storage engine being tested
        var storageEngine = options.storageEngine;

        // Backup type (must be specified)
        var allowedBackupKeys = ['fsyncLock', 'stopStart', 'rolling'];
        assert(options.backup, "Backup option not supplied");
        assert.contains(options.backup, allowedBackupKeys,
                        'invalid option: ' + tojson(options.backup) +
                        '; valid options are: ' + tojson(allowedBackupKeys));

        // Number of nodes in initial replica set (default 3)
        var numNodes = options.nodes || 3;

        // Time for clients to run before getting the new secondary it's data (default 10 seconds)
        var clientTime = options.clientTime || 10000;

        // Set the dbpath for the replica set
        var dbpathPrefix = MongoRunner.dataPath + 'backupRestore';
        resetDbpath(dbpathPrefix);
        var dbpathFormat = dbpathPrefix + '/mongod-$port';

        // Start numNodes node replSet
        var replSetName = 'backupRestore';
        var rst = new ReplSetTest({
            name: replSetName,
            nodes: numNodes,
            nodeOptions: {
                oplogSize: 1024,
                storageEngine: storageEngine,
                dbpath: dbpathFormat
            }
        });
        var nodes = rst.startSet();

        // Wait up to 5 minutes for the replica set to initiate. We allow extra time because
        // allocating 1GB oplogs on test hosts can be slow with mmapv1.
        rst.initiate(null, null, 5 * 60 * 1000);
        var primary = rst.getPrimary();
        var secondary = rst.getSecondary();

        // Launch CRUD client
        var crudDb = "crud";
        var crudColl = "backuprestore";
        var crudPid = crudClient(primary.host, crudDb, crudColl);

        // Launch FSM client
        var fsmPid = fsmClient(primary.host, crudDb, numNodes);

        // Let clients run for specified time before backing up secondary
        sleep(clientTime);

        // Perform fsync to create checkpoint. We doublecheck if the storage engine
        // supports fsync here.
        var ret = primary.adminCommand({fsync : 1});

        if (!ret.ok) {
            assert.commandFailedWithCode(ret, ErrorCodes.CommandNotSupported);
            jsTestLog("Skipping test of " + options.backup
                + " for " + storageEngine + ' as it does not support fsync');
            return;
        }

        // Configure new hidden secondary
        var dbpathSecondary = secondary.dbpath;
        var hiddenDbpath = dbpathPrefix + '/mongod-hiddensecondary';
        resetDbpath(hiddenDbpath);

        var sourcePath = dbpathSecondary + "/";
        var destPath = hiddenDbpath;
        // Windows paths for rsync
        if (_isWindows()) {
            sourcePath = "$(cygpath $(cygpath $SYSTEMDRIVE)'" + sourcePath + "')/";
            destPath = "$(cygpath $(cygpath $SYSTEMDRIVE)'" + hiddenDbpath + "')";
        }
        var copiedFiles;

        // Compare dbHash of crudDb when possible on hidden secondary
        var dbHash;

        // Perform the data backup to new secondary
        if (options.backup == 'fsyncLock') {
            // Test that the secondary supports fsyncLock
            var ret = secondary.getDB("admin").fsyncLock();
            if (!ret.ok) {
                assert.commandFailedWithCode(ret, ErrorCodes.CommandNotSupported);
                jsTestLog("Skipping test of " + options.backup
                    + " for " + storageEngine + ' as it does not support fsync');
                return;
            }

            dbHash = secondary.getDB(crudDb).runCommand({dbhash: 1}).md5;
            copyDbpath(dbpathSecondary, hiddenDbpath);
            removeFile(hiddenDbpath + '/mongod.lock');
            print("Source directory:", tojson(ls(dbpathSecondary)));
            copiedFiles = ls(hiddenDbpath);
            print("Copied files:", tojson(copiedFiles));
            assert.gt(copiedFiles.length, 0, testName + ' no files copied');
            assert.commandWorked(secondary.getDB("admin").fsyncUnlock(), testName +
                                 ' failed to fsyncUnlock');
        } else if (options.backup == 'rolling') {
            var rsyncCmd = "rsync -aKkz --del " + sourcePath + " " + destPath;
            // Simulate a rolling rsync, do it 3 times before stopping process
            for (var i = 0; i < 3; i++) {
                runCmd(rsyncCmd);
                sleep(10000);
            }
            // Stop the mongod process
            rst.stop(secondary.nodeId);
            // One final rsync
            runCmd(rsyncCmd);
            removeFile(hiddenDbpath + '/mongod.lock');
            print("Source directory:", tojson(ls(dbpathSecondary)));
            copiedFiles = ls(hiddenDbpath);
            print("Copied files:", tojson(copiedFiles));
            assert.gt(copiedFiles.length, 0, testName + ' no files copied');
            rst.start(secondary.nodeId, {}, true);
        } else if (options.backup == 'stopStart') {
            // Stop the mongod process
            rst.stop(secondary.nodeId);
            copyDbpath(dbpathSecondary, hiddenDbpath);
            removeFile(hiddenDbpath + '/mongod.lock');
            print("Source directory:", tojson(ls(dbpathSecondary)));
            copiedFiles = ls(hiddenDbpath);
            print("Copied files:", tojson(copiedFiles));
            assert.gt(copiedFiles.length, 0, testName + ' no files copied');
            rst.start(secondary.nodeId, {}, true);
        }

        // Wait up to 60 seconds until restarted node is in state secondary
        rst.waitForState(rst.getSecondaries(), ReplSetTest.State.SECONDARY, 60 * 1000);

        // Add new hidden node to replSetTest
        var hiddenCfg = {
            restart: true,
            oplogSize: 1024,
            dbpath: hiddenDbpath,
            replSet: replSetName
        };
        rst.add(hiddenCfg);
        var hiddenHost = rst.nodes[numNodes].host;

        // Verify if dbHash is the same on hidden secondary for crudDb
        // Note the dbhash can only run when the DB is inactive to get a result
        // that can be compared, which is only in the fsyncLock/fsynUnlock case
        if (dbHash !== undefined) {
            assert.eq(dbHash, rst.nodes[numNodes].getDB(crudDb).runCommand({dbhash: 1}).md5,
                      testName + ' dbHash');
        }

        // Add new hidden secondary to replica set
        var rsConfig = primary.getDB("local").system.replset.findOne();
        rsConfig.version += 1;
        var hiddenMember = {
            _id: numNodes,
            host: hiddenHost,
            priority: 0,
            hidden: true
        };
        rsConfig.members.push(hiddenMember);
        assert.commandWorked(primary.adminCommand({replSetReconfig : rsConfig}), testName +
                             ' failed to reconfigure replSet ' + tojson(rsConfig));

        // Wait up to 60 seconds until the new hidden node is in state RECOVERING.
        rst.waitForState(rst.nodes[numNodes],
                         [ReplSetTest.State.RECOVERING, ReplSetTest.State.SECONDARY],
                         60 * 1000);

        // Stop CRUD client and FSM client.
        assert(checkProgram(crudPid), testName + ' CRUD client was not running at end of test');
        assert(checkProgram(fsmPid), testName + ' FSM client was not running at end of test');
        stopMongoProgramByPid(crudPid);
        stopMongoProgramByPid(fsmPid);

        // Wait up to 60 seconds until the new hidden node is in state SECONDARY.
        rst.waitForState(rst.nodes[numNodes], ReplSetTest.State.SECONDARY, 60 * 1000);

        // Stop set.
        rst.stopSet();

        // Cleanup the files from the test
        // This is not done properly for replSetTest if dbpath is provided
        resetDbpath(dbpathPrefix);
        resetDbpath(hiddenDbpath);
    }

    // Main

    // Add storage engines which are to be skipped entirely to this array
    var noBackupTests = [ 'inMemoryExperiment' ];

    // Grab the storage engine, default is wiredTiger
    var storageEngine = jsTest.options().storageEngine || "wiredTiger";

    if (noBackupTests.indexOf(storageEngine) != -1) {
        jsTestLog("Skipping test for " + storageEngine);
        return;
    }

    if (storageEngine === "wiredTiger") {
        // if rsync is not available on the host, then this test is skipped
        if (!runProgram('bash', '-c', 'which rsync')) {
            runTest({
                name: storageEngine + ' rolling',
                storageEngine: storageEngine,
                backup: 'rolling',
                clientTime: 30000
            });
        } else {
            jsTestLog("Skipping test for " + storageEngine + ' rolling');
        }
    }

    // Run the fsyncLock test. Will return before testing for any engine that doesn't 
    // support fsyncLock
    runTest({
        name: storageEngine + ' fsyncLock/fsyncUnlock',
        storageEngine: storageEngine,
        backup: 'fsyncLock'
    });

    runTest({
        name: storageEngine + ' stop/start',
        storageEngine: storageEngine,
        backup: 'stopStart',
        clientTime: 30000
    });

}());