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
<?php
namespace MongoDB\Tests\SpecTests;
use IteratorIterator;
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\Exception as DriverException;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Server;
use MongoDB\Driver\WriteConcern;
use MongoDB\Operation\BulkWrite;
use MongoDB\Tests\CommandObserver;
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
use UnexpectedValueException;
use function current;
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests
*/
class PrimaryStepDownSpecTest extends FunctionalTestCase
{
use SetUpTearDownTrait;
const INTERRUPTED_AT_SHUTDOWN = 11600;
const NOT_MASTER = 10107;
const SHUTDOWN_IN_PROGRESS = 91;
/** @var Client */
private $client;
/** @var Collection */
private $collection;
private function doSetUp()
{
parent::setUp();
$this->client = new Client(static::getUri(), ['retryWrites' => false, 'heartbeatFrequencyMS' => 500, 'serverSelectionTimeoutMS' => 20000, 'serverSelectionTryOnce' => false]);
$this->dropAndRecreateCollection();
$this->collection = $this->client->selectCollection($this->getDatabaseName(), $this->getCollectionName());
}
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests#id10
*/
public function testNotMasterKeepsConnectionPool()
{
$runOn = [(object) ['minServerVersion' => '4.1.11', 'topology' => [self::TOPOLOGY_REPLICASET]]];
$this->checkServerRequirements($runOn);
// Set a fail point
$this->configureFailPoint([
'configureFailPoint' => 'failCommand',
'mode' => ['times' => 1],
'data' => [
'failCommands' => ['insert'],
'errorCode' => self::NOT_MASTER,
],
]);
$totalConnectionsCreated = $this->getTotalConnectionsCreated();
// Execute an insert into the test collection of a {test: 1} document.
try {
$this->insertDocuments(1);
} catch (BulkWriteException $e) {
// Verify that the insert failed with an operation failure with 10107 code.
$this->assertSame(self::NOT_MASTER, $e->getCode());
}
// Execute an insert into the test collection of a {test: 1} document and verify that it succeeds.
$result = $this->insertDocuments(1);
$this->assertSame(1, $result->getInsertedCount());
// Verify that the connection pool has not been cleared
$this->assertSame($totalConnectionsCreated, $this->getTotalConnectionsCreated());
}
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests#id11
*/
public function testNotMasterResetConnectionPool()
{
$runOn = [(object) ['minServerVersion' => '4.0.0', 'maxServerVersion' => '4.0.999', 'topology' => [self::TOPOLOGY_REPLICASET]]];
$this->checkServerRequirements($runOn);
// Set a fail point
$this->configureFailPoint([
'configureFailPoint' => 'failCommand',
'mode' => ['times' => 1],
'data' => [
'failCommands' => ['insert'],
'errorCode' => self::NOT_MASTER,
],
]);
$totalConnectionsCreated = $this->getTotalConnectionsCreated();
// Execute an insert into the test collection of a {test: 1} document.
try {
$this->insertDocuments(1);
} catch (BulkWriteException $e) {
// Verify that the insert failed with an operation failure with 10107 code.
$this->assertSame(self::NOT_MASTER, $e->getCode());
}
// Verify that the connection pool has been cleared
$this->assertSame($totalConnectionsCreated + 1, $this->getTotalConnectionsCreated());
}
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests#id12
*/
public function testShutdownResetConnectionPool()
{
$runOn = [(object) ['minServerVersion' => '4.0.0']];
$this->checkServerRequirements($runOn);
// Set a fail point
$this->configureFailPoint([
'configureFailPoint' => 'failCommand',
'mode' => ['times' => 1],
'data' => [
'failCommands' => ['insert'],
'errorCode' => self::SHUTDOWN_IN_PROGRESS,
],
]);
$totalConnectionsCreated = $this->getTotalConnectionsCreated();
// Execute an insert into the test collection of a {test: 1} document.
try {
$this->insertDocuments(1);
} catch (BulkWriteException $e) {
// Verify that the insert failed with an operation failure with 91 code.
$this->assertSame(self::SHUTDOWN_IN_PROGRESS, $e->getCode());
}
// Verify that the connection pool has been cleared
$this->assertSame($totalConnectionsCreated + 1, $this->getTotalConnectionsCreated());
}
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests#id13
*/
public function testInterruptedAtShutdownResetConnectionPool()
{
$runOn = [(object) ['minServerVersion' => '4.0.0']];
$this->checkServerRequirements($runOn);
// Set a fail point
$this->configureFailPoint([
'configureFailPoint' => 'failCommand',
'mode' => ['times' => 1],
'data' => [
'failCommands' => ['insert'],
'errorCode' => self::INTERRUPTED_AT_SHUTDOWN,
],
]);
$totalConnectionsCreated = $this->getTotalConnectionsCreated();
// Execute an insert into the test collection of a {test: 1} document.
try {
$this->insertDocuments(1);
} catch (BulkWriteException $e) {
// Verify that the insert failed with an operation failure with 11600 code.
$this->assertSame(self::INTERRUPTED_AT_SHUTDOWN, $e->getCode());
}
// Verify that the connection pool has been cleared
$this->assertSame($totalConnectionsCreated + 1, $this->getTotalConnectionsCreated());
}
/**
* @see https://github.com/mongodb/specifications/tree/master/source/connections-survive-step-down/tests#id9
*/
public function testGetMoreIteration()
{
$this->markTestSkipped('Test causes subsequent failures in other tests (see PHPLIB-471)');
$runOn = [(object) ['minServerVersion' => '4.1.11', 'topology' => [self::TOPOLOGY_REPLICASET]]];
$this->checkServerRequirements($runOn);
// Insert 5 documents into a collection with a majority write concern.
$this->insertDocuments(5);
// Start a find operation on the collection with a batch size of 2, and retrieve the first batch of results.
$cursor = $this->collection->find([], ['batchSize' => 2]);
$iterator = new IteratorIterator($cursor);
$iterator->rewind();
$this->assertTrue($iterator->valid());
$iterator->next();
$this->assertTrue($iterator->valid());
$totalConnectionsCreated = $this->getTotalConnectionsCreated();
// Send a {replSetStepDown: 5, force: true} command to the current primary and verify that the command succeeded
$primary = $this->client->getManager()->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
$primary->executeCommand('admin', new Command(['replSetStepDown' => 5, 'force' => true]));
// Retrieve the next batch of results from the cursor obtained in the find operation, and verify that this operation succeeded.
$events = [];
$observer = new CommandObserver();
$observer->observe(
function () use ($iterator) {
$iterator->next();
},
function ($event) use (&$events) {
$events[] = $event;
}
);
$this->assertTrue($iterator->valid());
$this->assertCount(1, $events);
$this->assertSame('getMore', $events[0]['started']->getCommandName());
// Verify that no new connections have been created
$this->assertSame($totalConnectionsCreated, $this->getTotalConnectionsCreated($cursor->getServer()));
// Wait to allow primary election to complete and prevent subsequent test failures
$this->waitForMasterReelection();
}
private function insertDocuments($count)
{
$operations = [];
for ($i = 1; $i <= $count; $i++) {
$operations[] = [
BulkWrite::INSERT_ONE => [['test' => $i]],
];
}
return $this->collection->bulkWrite($operations, ['writeConcern' => new WriteConcern('majority')]);
}
private function dropAndRecreateCollection()
{
$this->client->selectCollection($this->getDatabaseName(), $this->getCollectionName())->drop();
$this->client->selectDatabase($this->getDatabaseName())->command(['create' => $this->getCollectionName()]);
}
private function getTotalConnectionsCreated(Server $server = null)
{
$server = $server ?: $this->client->getManager()->selectServer(new ReadPreference('primary'));
$cursor = $server->executeCommand(
$this->getDatabaseName(),
new Command(['serverStatus' => 1]),
new ReadPreference(ReadPreference::RP_PRIMARY)
);
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
$document = current($cursor->toArray());
if (isset($document['connections'], $document['connections']['totalCreated'])) {
return (int) $document['connections']['totalCreated'];
}
throw new UnexpectedValueException('Could not determine number of total connections');
}
private function waitForMasterReelection()
{
try {
$this->insertDocuments(1);
return;
} catch (DriverException $e) {
$this->client->getManager()->selectServer(new ReadPreference('primary'));
return;
}
$this->fail('Expected primary to be re-elected within 20 seconds.');
}
}