summaryrefslogtreecommitdiff
path: root/jstests/concurrency/fsm_libs/runner.js
blob: 696794f8efab76aa682207baf9cb8c50715463b3 (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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
'use strict';

load('jstests/concurrency/fsm_libs/assert.js');
load('jstests/concurrency/fsm_libs/cluster.js');
load('jstests/concurrency/fsm_libs/errors.js'); // for IterationEnd
load('jstests/concurrency/fsm_libs/parse_config.js');
load('jstests/concurrency/fsm_libs/thread_mgr.js');
load('jstests/concurrency/fsm_utils/name_utils.js'); // for uniqueCollName and uniqueDBName
load('jstests/concurrency/fsm_utils/setup_teardown_functions.js');

var runner = (function() {

    function validateExecutionMode(mode) {
        var allowedKeys = [
            'composed',
            'parallel'
        ];

        Object.keys(mode).forEach(function(option) {
            assert.contains(option, allowedKeys,
                            'invalid option: ' + tojson(option) +
                            '; valid options are: ' + tojson(allowedKeys));
        });

        mode.composed = mode.composed || false;
        assert.eq('boolean', typeof mode.composed);

        mode.parallel = mode.parallel || false;
        assert.eq('boolean', typeof mode.parallel);

        assert(!mode.composed || !mode.parallel,
               "properties 'composed' and 'parallel' cannot both be true");

        return mode;
    }

    function validateExecutionOptions(mode, options) {
        var allowedKeys = [
            'backgroundWorkloads',
            'dbNamePrefix',
            'iterationMultiplier',
            'threadMultiplier'
        ];

        if (mode.parallel || mode.composed) {
            allowedKeys.push('numSubsets');
            allowedKeys.push('subsetSize');
        }
        if (mode.composed) {
            allowedKeys.push('composeProb');
            allowedKeys.push('iterations');
        }

        Object.keys(options).forEach(function(option) {
            assert.contains(option, allowedKeys,
                            'invalid option: ' + tojson(option) +
                            '; valid options are: ' + tojson(allowedKeys));
        });

        if (typeof options.subsetSize !== 'undefined') {
            assert(Number.isInteger(options.subsetSize),
                   'expected subset size to be an integer');
            assert.gt(options.subsetSize, 1);
        }

        if (typeof options.numSubsets !== 'undefined') {
            assert(Number.isInteger(options.numSubsets),
                   'expected number of subsets to be an integer');
            assert.gt(options.numSubsets, 0);
        }

        if (typeof options.iterations !== 'undefined') {
            assert(Number.isInteger(options.iterations),
                   'expected number of iterations to be an integer');
            assert.gt(options.iterations, 0);
        }

        if (typeof options.composeProb !== 'undefined') {
            assert.eq('number', typeof options.composeProb);
            assert.gt(options.composeProb, 0);
            assert.lte(options.composeProb, 1);
        }

        options.backgroundWorkloads = options.backgroundWorkloads || [];
        assert(Array.isArray(options.backgroundWorkloads),
               'expected backgroundWorkloads to be an array');

        if (typeof options.dbNamePrefix !== 'undefined') {
            assert.eq('string', typeof options.dbNamePrefix,
                      'expected dbNamePrefix to be a string');
        }

        options.iterationMultiplier = options.iterationMultiplier || 1;
        assert(Number.isInteger(options.iterationMultiplier),
               'expected iterationMultiplier to be an integer');
        assert.gte(options.iterationMultiplier, 1,
                   'expected iterationMultiplier to be greater than or equal to 1');

        options.threadMultiplier = options.threadMultiplier || 1;
        assert(Number.isInteger(options.threadMultiplier),
               'expected threadMultiplier to be an integer');
        assert.gte(options.threadMultiplier, 1,
                   'expected threadMultiplier to be greater than or equal to 1');

        return options;
    }

    function validateCleanupOptions(options) {
        var allowedKeys = [
            'dropDatabaseBlacklist',
            'keepExistingDatabases'
        ];

        Object.keys(options).forEach(function(option) {
            assert.contains(option, allowedKeys,
                            'invalid option: ' + tojson(option) +
                            '; valid options are: ' + tojson(allowedKeys));
        });

        if (typeof options.dropDatabaseBlacklist !== 'undefined') {
            assert(Array.isArray(options.dropDatabaseBlacklist),
                   'expected dropDatabaseBlacklist to be an array');
        }

        if (typeof options.keepExistingDatabases !== 'undefined') {
            assert.eq('boolean', typeof options.keepExistingDatabases,
                      'expected keepExistingDatabases to be a boolean');
        }

        return options;
    }

    /**
     * Returns an array containing sets of workloads.
     * Each set of workloads is executed together according to the execution mode.
     *
     * For example, returning [ [ workload1, workload2 ], [ workload2, workload3 ] ]
     * when 'executionMode.parallel == true' causes workloads #1 and #2 to be
     * executed simultaneously, followed by workloads #2 and #3 together.
     */
    function scheduleWorkloads(workloads, executionMode, executionOptions) {
        if (!executionMode.composed && !executionMode.parallel) { // serial execution
            return Array.shuffle(workloads).map(function(workload) {
                return [workload]; // run each workload by itself
            });
        }

        var schedule = [];

        // Take 'numSubsets' random subsets of the workloads, each
        // of size 'subsetSize'. Each workload must get scheduled
        // once before any workload can be scheduled again.
        var subsetSize = executionOptions.subsetSize || 10;

        // If the number of subsets is not specified, then have each
        // workload get scheduled 2 to 3 times.
        var numSubsets = executionOptions.numSubsets;
        if (!numSubsets) {
            numSubsets = Math.ceil(2.5 * workloads.length / subsetSize);
        }

        workloads = workloads.slice(0); // copy
        workloads = Array.shuffle(workloads);

        var start = 0;
        var end = subsetSize;

        while (schedule.length < numSubsets) {
            schedule.push(workloads.slice(start, end));

            start = end;
            end += subsetSize;

            // Check if there are not enough elements remaining in
            // 'workloads' to make a subset of size 'subsetSize'.
            if (end > workloads.length) {
                // Re-shuffle the beginning of the array, and prepend it
                // with the workloads that have not been scheduled yet.
                var temp = Array.shuffle(workloads.slice(0, start));
                for (var i = workloads.length - 1; i >= start; --i) {
                    temp.unshift(workloads[i]);
                }
                workloads = temp;

                start = 0;
                end = subsetSize;
            }
        }

        return schedule;
    }

    function prepareCollections(workloads, context, cluster, clusterOptions, executionOptions) {
        var dbName, collName, myDB;
        var firstWorkload = true;

        workloads.forEach(function(workload) {
            // Workloads cannot have a shardKey if sameCollection is specified
            if (clusterOptions.sameCollection &&
                    cluster.isSharded() &&
                    context[workload].config.data.shardKey) {
                throw new Error('cannot specify a shardKey with sameCollection option');
            }
            if (firstWorkload || !clusterOptions.sameCollection) {
                if (firstWorkload || !clusterOptions.sameDB) {
                    dbName = uniqueDBName(executionOptions.dbNamePrefix);
                }
                collName = uniqueCollName();

                myDB = cluster.getDB(dbName);
                myDB[collName].drop();

                if (cluster.isSharded()) {
                    var shardKey = context[workload].config.data.shardKey || { _id: 'hashed' };
                    // TODO: allow workload config data to specify split
                    cluster.shardCollection(myDB[collName], shardKey, false);
                }
            }

            context[workload].db = myDB;
            context[workload].dbName = dbName;
            context[workload].collName = collName;

            firstWorkload = false;
        });
    }

    function dropAllDatabases(db, blacklist) {
        var res = db.adminCommand('listDatabases');
        assert.commandWorked(res);

        res.databases.forEach(function(dbInfo) {
            if (!Array.contains(blacklist, dbInfo.name)) {
                var res = db.getSiblingDB(dbInfo.name).dropDatabase();
                assert.commandWorked(res);
                assert.eq(dbInfo.name, res.dropped);
            }
        });
    }

    function cleanupWorkloadData(workloads, context, clusterOptions) {
        // If no other workloads will be using this collection,
        // then drop it to avoid having too many files open
        if (!clusterOptions.sameCollection) {
            workloads.forEach(function(workload) {
                var config = context[workload];
                config.db[config.collName].drop();
            });
        }

        // If no other workloads will be using this database,
        // then drop it to avoid having too many files open
        if (!clusterOptions.sameDB) {
            workloads.forEach(function(workload) {
                var config = context[workload];
                config.db.dropDatabase();
            });
        }
    }

    function WorkloadFailure(err, stack, kind) {
        this.err = err;
        this.stack = stack;
        this.kind = kind;

        this.format = function format() {
            return this.kind + '\n' + this.err + '\n\n' + this.stack;
        };
    }

    function throwError(workerErrs) {

        // Returns an array containing all unique values from the specified array
        // and their corresponding number of occurrences in the original array.
        function freqCount(arr) {
            var unique = [];
            var freqs = [];

            arr.forEach(function(item) {
                var i = unique.indexOf(item);
                if (i < 0) {
                    unique.push(item);
                    freqs.push(1);
                } else {
                    freqs[i]++;
                }
            });

            return unique.map(function(value, i) {
                return { value: value, freq: freqs[i] };
            });
        }

        // Indents a multiline string with the specified number of spaces.
        function indent(str, size) {
            var prefix = new Array(size + 1).join(' ');
            return prefix + str.split('\n').join('\n' + prefix);
        }

        function pluralize(str, num) {
            var suffix = num > 1 ? 's' : '';
            return num + ' ' + str + suffix;
        }

        function prepareMsg(stackTraces) {
            var uniqueTraces = freqCount(stackTraces);
            var numUniqueTraces = uniqueTraces.length;

            // Special case message when threads all have the same trace
            if (numUniqueTraces === 1) {
                return pluralize('thread', stackTraces.length) + ' threw\n\n' +
                       indent(uniqueTraces[0].value, 8);
            }

            var summary = pluralize('thread', stackTraces.length) + ' threw ' +
                          numUniqueTraces + ' different exceptions:\n\n';

            return summary + uniqueTraces.map(function(obj) {
                var line = pluralize('thread', obj.freq) + ' threw\n';
                return indent(line + obj.value, 8);
            }).join('\n\n');
        }

        if (workerErrs.length > 0) {
            var stackTraces = workerErrs.map(function(e) {
                return e.format();
            });

            var err = new Error(prepareMsg(stackTraces) + '\n');

            // Avoid having any stack traces omitted from the logs
            var maxLogLine = 10 * 1024; // 10KB

            // Check if the combined length of the error message and the stack traces
            // exceeds the maximum line-length the shell will log.
            if ((err.message.length + err.stack.length) >= maxLogLine) {
                print(err.message);
                print(err.stack);
                throw new Error('stack traces would have been snipped, see logs');
            }

            throw err;
        }
    }

    function setupWorkload(workload, context, cluster) {
        var myDB = context[workload].db;
        var collName = context[workload].collName;

        var config = context[workload].config;
        config.setup.call(config.data, myDB, collName, cluster);
    }

    function teardownWorkload(workload, context, cluster) {
        var myDB = context[workload].db;
        var collName = context[workload].collName;

        var config = context[workload].config;
        config.teardown.call(config.data, myDB, collName, cluster);
    }

    function setIterations(config) {
        // This property must be enumerable because of SERVER-21338, which prevents
        // objects with non-enumerable properties from being serialized properly in
        // ScopedThreads.
        Object.defineProperty(config.data, 'iterations', {
            enumerable: true,
            value: config.iterations
        });
    }

    function setThreadCount(config) {
        // This property must be enumerable because of SERVER-21338, which prevents
        // objects with non-enumerable properties from being serialized properly in
        // ScopedThreads.
        Object.defineProperty(config.data, 'threadCount', {
            enumerable: true,
            value: config.threadCount
        });
    }

    function useDropDistLockFailPoint(cluster, clusterOptions) {
        assert(cluster.isSharded(), 'cluster is not sharded');

        // For sharded clusters, enable a fail point that allows dropCollection to wait longer
        // to acquire the distributed lock. This prevents tests from failing if the distributed
        // lock is already held by the balancer or by a workload operation. The increased wait
        // is shorter than the distributed-lock-takeover period because otherwise the node
        // would be assumed to be down and the lock would be overtaken.
        if (cluster.isUsingLegacyConfigServers()) {
            clusterOptions.setupFunctions.mongos.push(increaseDropDistLockTimeoutSCCC);
            clusterOptions.teardownFunctions.mongos.push(resetDropDistLockTimeoutSCCC);
        } else {
            clusterOptions.setupFunctions.mongos.push(increaseDropDistLockTimeout);
            clusterOptions.teardownFunctions.mongos.push(resetDropDistLockTimeout);
        }
    }

    function loadWorkloadContext(workloads, context, executionOptions) {
        workloads.forEach(function(workload) {
            load(workload); // for $config
            assert.neq('undefined', typeof $config, '$config was not defined by ' + workload);
            context[workload] = { config: parseConfig($config) };
            context[workload].config.iterations *= executionOptions.iterationMultiplier;
            context[workload].config.threadCount *= executionOptions.threadMultiplier;
        });
    }

    function printWorkloadSchedule(schedule, backgroundWorkloads) {
        // Print out the entire schedule of workloads to make it easier to run the same
        // schedule when debugging test failures.
        jsTest.log('The entire schedule of FSM workloads:');

        // Note: We use printjsononeline (instead of just plain printjson) to make it
        // easier to reuse the output in variable assignments.
        printjsononeline(schedule);
        if (backgroundWorkloads.length > 0) {
            jsTest.log('Background Workloads:');
            printjsononeline(backgroundWorkloads);
        }

        jsTest.log('End of schedule');
    }

    function cleanupWorkload(workload, context, cluster, errors, kind, dbHashBlacklist) {
        // Returns true if the workload's teardown succeeds and false if the workload's
        // teardown fails.

        try {
            // Ensure that secondaries have caught up before workload teardown.
            cluster.awaitReplication('before workload teardown');

            // Check dbHash, for all DBs not in dbHashBlacklist, on all nodes
            // before the workload's teardown method is called.
            cluster.checkDbHashes(dbHashBlacklist, 'before workload teardown');
        } catch (e) {
            errors.push(new WorkloadFailure(e.toString(), e.stack,
                                            kind + ' checking consistency on secondaries'));
            return false;
        }

        try {
            teardownWorkload(workload, context, cluster);
        } catch (e) {
            errors.push(new WorkloadFailure(e.toString(), e.stack, kind + ' Teardown'));
            return false;
        }
        return true;
    }

    function runWorkloadGroup(threadMgr, workloads, context, cluster, clusterOptions,
                              executionMode, executionOptions, errors, maxAllowedThreads,
                              dbHashBlacklist) {
        var cleanup = [];
        var teardownFailed = false;
        var startTime = Date.now(); // Initialize in case setupWorkload fails below.
        var totalTime;

        jsTest.log('Workload(s) started: ' + workloads.join(' '));

        prepareCollections(workloads, context, cluster, clusterOptions, executionOptions);

        try {
            // Set up the thread manager for this set of foreground workloads.
            startTime = Date.now();
            threadMgr.init(workloads, context, maxAllowedThreads);

            // Call each foreground workload's setup function.
            workloads.forEach(function(workload) {
                // Define "iterations" and "threadCount" properties on the foreground workload's
                // $config.data object so that they can be used within its setup(), teardown(), and
                // state functions. This must happen after calling threadMgr.init() in case the
                // thread counts needed to be scaled down.
                setIterations(context[workload].config);
                setThreadCount(context[workload].config);

                setupWorkload(workload, context, cluster);
                cleanup.push(workload);
            });

            try {
                // Start this set of foreground workload threads.
                threadMgr.spawnAll(cluster, executionOptions);
                // Allow 20% of foreground threads to fail. This allows the workloads to run on
                // underpowered test hosts.
                threadMgr.checkFailed(0.2);
            } finally {
                // Threads must be joined before destruction, so do this
                // even in the presence of exceptions.
                errors.push(...threadMgr.joinAll().map(e =>
                    new WorkloadFailure(e.err, e.stack, 'Foreground')));
            }
        } finally {
            // Call each foreground workload's teardown function. After all teardowns have completed
            // check if any of them failed.
            var cleanupResults = cleanup.map(workload =>
                cleanupWorkload(workload, context, cluster, errors,
                                'Foreground', dbHashBlacklist));
            teardownFailed = cleanupResults.some(success => (success === false));

            totalTime = Date.now() - startTime;
            jsTest.log('Workload(s) completed in ' + totalTime + ' ms: ' +
                        workloads.join(' '));
        }

        // Only drop the collections/databases if all the workloads ran successfully.
        if (!errors.length && !teardownFailed) {
            cleanupWorkloadData(workloads, context, clusterOptions);
        }

        // Throw any existing errors so that the schedule aborts.
        throwError(errors);

        // Ensure that secondaries have caught up after workload teardown.
        cluster.awaitReplication('after workload-group teardown and data clean-up');

        // Check dbHash, for all DBs not in dbHashBlacklist, on all nodes
        // after the workload's teardown method is called.
        cluster.checkDbHashes(dbHashBlacklist, 'after workload-group teardown and data clean-up');
    }

    function runWorkloads(workloads,
                          clusterOptions,
                          executionMode,
                          executionOptions,
                          cleanupOptions) {
        assert.gt(workloads.length, 0, 'need at least one workload to run');

        executionMode = validateExecutionMode(executionMode);
        Object.freeze(executionMode); // immutable after validation (and normalization)

        validateExecutionOptions(executionMode, executionOptions);
        Object.freeze(executionOptions); // immutable after validation (and normalization)

        Object.freeze(cleanupOptions); // immutable prior to validation
        validateCleanupOptions(cleanupOptions);

        if (executionMode.composed) {
            clusterOptions.sameDB = true;
            clusterOptions.sameCollection = true;
        }

        // Determine how strong to make assertions while simultaneously executing
        // different workloads.
        var assertLevel = AssertLevel.OWN_DB;
        if (clusterOptions.sameDB) {
            // The database is shared by multiple workloads, so only make the asserts
            // that apply when the collection is owned by an individual workload.
            assertLevel = AssertLevel.OWN_COLL;
        }
        if (clusterOptions.sameCollection) {
            // The collection is shared by multiple workloads, so only make the asserts
            // that always apply.
            assertLevel = AssertLevel.ALWAYS;
        }
        globalAssertLevel = assertLevel;

        var context = {};
        loadWorkloadContext(workloads, context, executionOptions);
        var threadMgr = new ThreadManager(clusterOptions, executionMode);

        var bgContext = {};
        var bgWorkloads = executionOptions.backgroundWorkloads;
        loadWorkloadContext(bgWorkloads, bgContext, executionOptions);
        var bgThreadMgr = new ThreadManager(clusterOptions, { composed: false });

        var cluster = new Cluster(clusterOptions);
        if (cluster.isSharded()) {
            useDropDistLockFailPoint(cluster, clusterOptions);
        }
        cluster.setup();

        // Clean up the state left behind by other tests in the concurrency suite
        // to avoid having too many open files.

        // List of DBs that will not be dropped.
        var dbBlacklist = ['admin', 'config', 'local', '$external'];

        // List of DBs that dbHash is not run on.
        var dbHashBlacklist = ['local'];

        if (cleanupOptions.dropDatabaseBlacklist) {
            dbBlacklist.push(...cleanupOptions.dropDatabaseBlacklist);
            dbHashBlacklist.push(...cleanupOptions.dropDatabaseBlacklist);
        }
        if (!cleanupOptions.keepExistingDatabases) {
            dropAllDatabases(cluster.getDB('test'), dbBlacklist);
        }

        var maxAllowedThreads = 100 * executionOptions.threadMultiplier;
        Random.setRandomSeed(clusterOptions.seed);
        var bgCleanup = [];
        var errors = [];

        try {
            prepareCollections(bgWorkloads, bgContext, cluster, clusterOptions, executionOptions);

            // Set up the background thread manager for background workloads.
            bgThreadMgr.init(bgWorkloads, bgContext, maxAllowedThreads);

            // Call each background workload's setup function.
            bgWorkloads.forEach(function(bgWorkload) {
                // Define "iterations" and "threadCount" properties on the background workload's
                // $config.data object so that they can be used within its setup(), teardown(), and
                // state functions. This must happen after calling bgThreadMgr.init() in case the
                // thread counts needed to be scaled down.
                setIterations(bgContext[bgWorkload].config);
                setThreadCount(bgContext[bgWorkload].config);

                setupWorkload(bgWorkload, bgContext, cluster);
                bgCleanup.push(bgWorkload);
            });

            try {
                // Start background workload threads.
                bgThreadMgr.spawnAll(cluster, executionOptions);
                bgThreadMgr.checkFailed(0);

                var schedule = scheduleWorkloads(workloads, executionMode, executionOptions);
                printWorkloadSchedule(schedule, bgWorkloads);

                schedule.forEach(function(workloads) {
                    // Check if any background workloads have failed.
                    if (bgThreadMgr.checkForErrors()){
                        var msg = 'Background workload failed before all foreground workloads ran';
                        throw new IterationEnd(msg);
                    }

                    // Make a deep copy of the $config object for each of the workloads that are
                    // going to be run to ensure the workload starts with a fresh version of its
                    // $config.data. This is necessary because $config.data keeps track of
                    // thread-local state that may be updated during a workload's setup(),
                    // teardown(), and state functions.
                    var groupContext = {};
                    workloads.forEach(function(workload) {
                        groupContext[workload] = Object.extend({}, context[workload], true);
                    });

                    // Run the next group of workloads in the schedule.
                    runWorkloadGroup(threadMgr, workloads, groupContext, cluster,
                                     clusterOptions, executionMode, executionOptions,
                                     errors, maxAllowedThreads, dbHashBlacklist);
                });
            } finally {
                // Set a flag so background threads know to terminate.
                bgThreadMgr.markAllForTermination();
                errors.push(...bgThreadMgr.joinAll().map(e =>
                    new WorkloadFailure(e.err, e.stack, 'Background')));
            }
        } finally {
            try {
                // Call each background workload's teardown function.
                bgCleanup.forEach(bgWorkload => cleanupWorkload(bgWorkload, bgContext, cluster,
                                                                errors, 'Background',
                                                                dbHashBlacklist));
                // TODO: Call cleanupWorkloadData() on background workloads here if no background
                // workload teardown functions fail.

                // Replace the active exception with an exception describing the errors from all
                // the foreground and background workloads. IterationEnd errors are ignored because
                // they are thrown when the background workloads are instructed by the thread
                // manager to terminate.
                throwError(errors.filter(e => (e.err.startsWith('IterationEnd:') === false)));
            } finally {
                cluster.teardown();
            }
        }
    }

    return {
        serial: function serial(workloads, clusterOptions, executionOptions, cleanupOptions) {
            clusterOptions = clusterOptions || {};
            executionOptions = executionOptions || {};
            cleanupOptions = cleanupOptions || {};

            runWorkloads(workloads, clusterOptions, {}, executionOptions, cleanupOptions);
        },

        parallel: function parallel(workloads, clusterOptions, executionOptions, cleanupOptions) {
            clusterOptions = clusterOptions || {};
            executionOptions = executionOptions || {};
            cleanupOptions = cleanupOptions || {};

            runWorkloads(workloads,
                         clusterOptions,
                         { parallel: true },
                         executionOptions,
                         cleanupOptions);
        },

        composed: function composed(workloads, clusterOptions, executionOptions, cleanupOptions) {
            clusterOptions = clusterOptions || {};
            executionOptions = executionOptions || {};
            cleanupOptions = cleanupOptions || {};

            runWorkloads(workloads,
                         clusterOptions,
                         { composed: true },
                         executionOptions,
                         cleanupOptions);
        }
    };

})();

var runWorkloadsSerially = runner.serial;
var runWorkloadsInParallel = runner.parallel;
var runCompositionOfWorkloads = runner.composed;