File: sdam_error_handling_spec.rb

package info (click to toggle)
ruby-mongo 2.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,764 kB
  • sloc: ruby: 108,806; makefile: 5; sh: 2
file content (491 lines) | stat: -rw-r--r-- 14,106 bytes parent folder | download
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
# frozen_string_literal: true
# rubocop:todo all

require 'spec_helper'

describe 'SDAM error handling' do
  require_topology :single, :replica_set, :sharded
  require_mri

  clean_slate

  retry_test

  after do
    # Close all clients after every test to avoid leaking expectations into
    # subsequent tests because we set global assertions on sockets.
    ClientRegistry.instance.close_all_clients
  end

  # These tests operate on specific servers, and don't work in a multi
  # shard cluster where multiple servers are equally eligible
  require_no_multi_mongos

  let(:diagnostic_subscriber) { Mrss::VerboseEventSubscriber.new }

  let(:client) do
    new_local_client(SpecConfig.instance.addresses,
      SpecConfig.instance.all_test_options.merge(
        socket_timeout: 3, connect_timeout: 3,
        heartbeat_frequency: 100,
        populator_io: false,
        # Uncomment to print all events to stdout:
        #sdam_proc: Utils.subscribe_all_sdam_proc(diagnostic_subscriber),
        **Utils.disable_retries_client_options)
    )
  end

  let(:server) { client.cluster.next_primary }

  shared_examples_for 'marks server unknown' do
    before do
      server.monitor.stop!
    end

    after do
      client.close
    end

    it 'marks server unknown' do
      expect(server).not_to be_unknown
      RSpec::Mocks.with_temporary_scope do
        operation
        expect(server).to be_unknown
      end
    end
  end

  shared_examples_for 'does not mark server unknown' do
    before do
      server.monitor.stop!
    end

    after do
      client.close
    end

    it 'does not mark server unknown' do
      expect(server).not_to be_unknown
      RSpec::Mocks.with_temporary_scope do
        operation
        expect(server).not_to be_unknown
      end
    end
  end

  shared_examples_for 'requests server scan' do
    it 'requests server scan' do
      RSpec::Mocks.with_temporary_scope do
        expect(server.scan_semaphore).to receive(:signal)
        operation
      end
    end
  end

  shared_examples_for 'does not request server scan' do
    it 'does not request server scan' do
      RSpec::Mocks.with_temporary_scope do
        expect(server.scan_semaphore).not_to receive(:signal)
        operation
      end
    end
  end

  shared_examples_for 'clears connection pool' do
    it 'clears connection pool' do
      generation = server.pool.generation
      RSpec::Mocks.with_temporary_scope do
        operation
        new_generation = server.pool_internal.generation
        expect(new_generation).to eq(generation + 1)
      end
    end
  end

  shared_examples_for 'does not clear connection pool' do
    it 'does not clear connection pool' do
      generation = server.pool.generation
      RSpec::Mocks.with_temporary_scope do
        operation
        new_generation = server.pool_internal.generation
        expect(new_generation).to eq(generation)
      end
    end
  end

  describe 'when there is an error during an operation' do

    before do
      client.cluster.next_primary
      # we also need a connection to the primary so that our error
      # expectations do not get triggered during handshakes which
      # have different behavior from non-handshake errors
      client.database.command(ping: 1)
    end

    let(:operation) do
      expect_any_instance_of(Mongo::Server::Connection).to receive(:deliver).and_return(reply)
      expect do
        client.database.command(ping: 1)
      end.to raise_error(Mongo::Error::OperationFailure, exception_message)
    end

    shared_examples_for 'not master or node recovering' do
      it_behaves_like 'marks server unknown'
      it_behaves_like 'requests server scan'

      context 'server 4.2 or higher' do
        min_server_fcv '4.2'

        it_behaves_like 'does not clear connection pool'
      end

      context 'server 4.0 or lower' do
        max_server_version '4.0'

        it_behaves_like 'clears connection pool'
      end
    end

    shared_examples_for 'node shutting down' do
      it_behaves_like 'marks server unknown'
      it_behaves_like 'requests server scan'
      it_behaves_like 'clears connection pool'
    end

    context 'not master error' do
      let(:exception_message) do
        /not master/
      end

      let(:reply) do
        make_not_master_reply
      end

      it_behaves_like 'not master or node recovering'
    end

    context 'node recovering error' do
      let(:exception_message) do
        /DueToStepDown/
      end

      let(:reply) do
        make_node_recovering_reply
      end

      it_behaves_like 'not master or node recovering'
    end

    context 'node shutting down error' do
      let(:exception_message) do
        /shutdown in progress/
      end

      let(:reply) do
        make_node_shutting_down_reply
      end

      it_behaves_like 'node shutting down'
    end

    context 'network error' do
      # With 4.4 servers we set up two monitoring connections, hence global
      # socket expectations get hit twice.
      max_server_version '4.2'

      let(:operation) do
        expect_any_instance_of(Mongo::Socket).to receive(:read).and_raise(exception)
        expect do
          client.database.command(ping: 1)
        end.to raise_error(exception)
      end

      context 'non-timeout network error' do
        let(:exception) do
          Mongo::Error::SocketError
        end

        it_behaves_like 'marks server unknown'
        it_behaves_like 'does not request server scan'
        it_behaves_like 'clears connection pool'
      end

      context 'network timeout error' do
        let(:exception) do
          Mongo::Error::SocketTimeoutError
        end

        it_behaves_like 'does not mark server unknown'
        it_behaves_like 'does not request server scan'
        it_behaves_like 'does not clear connection pool'
      end
    end
  end

  describe 'when there is an error during connection establishment' do
    require_topology :single

    # The push monitor creates sockets unpredictably and interferes with this
    # test.
    max_server_version '4.2'

    # When TLS is used there are two socket classes and we can't simply
    # mock the base Socket class.
    require_no_tls

    {
      SystemCallError => Mongo::Error::SocketError,
      Errno::ETIMEDOUT => Mongo::Error::SocketTimeoutError,
    }.each do |raw_error_cls, mapped_error_cls|
      context raw_error_cls.name do
        let(:socket) do
          double('mock socket').tap do |socket|
            allow(socket).to receive(:set_encoding)
            allow(socket).to receive(:setsockopt)
            allow(socket).to receive(:getsockopt)
            allow(socket).to receive(:connect)
            allow(socket).to receive(:close)
            socket.should receive(:write).and_raise(raw_error_cls, 'mocked failure')
          end
        end

        it 'marks server unknown' do
          server = client.cluster.next_primary
          pool = client.cluster.pool(server)
          client.cluster.servers.map(&:disconnect!)

          RSpec::Mocks.with_temporary_scope do

            Socket.should receive(:new).with(any_args).ordered.once.and_return(socket)
            allow(pool).to receive(:paused?).and_return(false)
            lambda do
              client.command(ping: 1)
            end.should raise_error(mapped_error_cls, /mocked failure/)

            server.should be_unknown
          end
        end

        it 'recovers' do
          server = client.cluster.next_primary
          # If we do not kill the monitor, the client will recover automatically.

          RSpec::Mocks.with_temporary_scope do

            Socket.should receive(:new).with(any_args).ordered.once.and_return(socket)
            Socket.should receive(:new).with(any_args).ordered.once.and_call_original

            lambda do
              client.command(ping: 1)
            end.should raise_error(mapped_error_cls, /mocked failure/)

            client.command(ping: 1)
          end
        end
      end
    end

    after do
      # Since we stopped monitoring on the client, close it.
      ClientRegistry.instance.close_all_clients
    end
  end

  describe 'when there is an error on monitoring connection' do
    clean_slate_for_all

    let(:subscriber) { Mrss::EventSubscriber.new }

    let(:set_subscribers) do
      client.subscribe(Mongo::Monitoring::SERVER_DESCRIPTION_CHANGED, subscriber)
      client.subscribe(Mongo::Monitoring::CONNECTION_POOL, subscriber)
    end

    let(:operation) do
      expect(server.monitor.connection).not_to be nil
      set_subscribers
      RSpec::Mocks.with_temporary_scope do
        expect(server.monitor).to receive(:check).and_raise(exception)
        server.monitor.scan!
      end
      expect_server_state_change
    end

    shared_examples_for 'marks server unknown - sdam event' do
      it 'marks server unknown' do
        expect(server).not_to be_unknown

        #subscriber.clear_events!
        events = subscriber.select_succeeded_events(Mongo::Monitoring::Event::ServerDescriptionChanged)
        events.should be_empty

        RSpec::Mocks.with_temporary_scope do
          operation

          events = subscriber.select_succeeded_events(Mongo::Monitoring::Event::ServerDescriptionChanged)
          events.should_not be_empty
          event = events.detect do |event|
            event.new_description.address == server.address &&
            event.new_description.unknown?
          end
          event.should_not be_nil
        end
      end
    end

    shared_examples_for 'clears connection pool - cmap event' do
      it 'clears connection pool' do
        #subscriber.clear_events!
        events = subscriber.select_published_events(Mongo::Monitoring::Event::Cmap::PoolCleared)
        events.should be_empty

        RSpec::Mocks.with_temporary_scope do
          operation

          events = subscriber.select_published_events(Mongo::Monitoring::Event::Cmap::PoolCleared)
          events.should_not be_empty
          event = events.detect do |event|
            event.address == server.address
          end
          event.should_not be_nil
        end
      end
    end

    shared_examples_for 'marks server unknown and clears connection pool' do
=begin These tests are not reliable
      context 'via object inspection' do
        let(:expect_server_state_change) do
          server.summary.should =~ /unknown/i
          expect(server).to be_unknown
        end

        it_behaves_like 'marks server unknown'
        it_behaves_like 'clears connection pool'
      end
=end

      context 'via events' do
        # When we use events we do not need to examine object state, therefore
        # it does not matter whether the server stays unknown or gets
        # successfully checked.
        let(:expect_server_state_change) do
          # nothing
        end

        it_behaves_like 'marks server unknown - sdam event'
        it_behaves_like 'clears connection pool - cmap event'
      end
    end

    context 'via stubs' do
      # With 4.4 servers we set up two monitoring connections, hence global
      # socket expectations get hit twice.
      max_server_version '4.2'

      context 'network timeout' do
        let(:exception) { Mongo::Error::SocketTimeoutError }

        it_behaves_like 'marks server unknown and clears connection pool'
      end

      context 'non-timeout network error' do
        let(:exception) { Mongo::Error::SocketError }

        it_behaves_like 'marks server unknown and clears connection pool'
      end
    end

    context 'non-timeout network error via fail point' do
      require_fail_command

      let(:admin_client) { client.use(:admin) }

      let(:set_fail_point) do
        admin_client.command(
          configureFailPoint: 'failCommand',
          mode: {times: 2},
          data: {
            failCommands: %w(isMaster hello),
            closeConnection: true,
          },
        )
      end

      let(:operation) do
        expect(server.monitor.connection).not_to be nil
        set_subscribers
        set_fail_point
        server.monitor.scan!
        expect_server_state_change
      end

      # https://jira.mongodb.org/browse/RUBY-2523
      # it_behaves_like 'marks server unknown and clears connection pool'

      after do
        admin_client.command(configureFailPoint: 'failCommand', mode: 'off')
      end
    end
  end

  context "when there is an error on the handshake" do
    # require appName for fail point
    min_server_version "4.9"

    let(:admin_client) do
      new_local_client(
        [SpecConfig.instance.addresses.first],
        SpecConfig.instance.test_options.merge({
          connect: :direct,
          populator_io: false,
          direct_connection: true,
          app_name: "SDAMMinHeartbeatFrequencyTest",
          database: 'admin'
        })
      )
    end

    let(:cmd_client) do
      # Change the server selection timeout so that we are given a new cluster.
      admin_client.with(server_selection_timeout: 5)
    end

    let(:set_fail_point) do
      admin_client.command(
        configureFailPoint: 'failCommand',
        mode: { times: 5 },
        data: {
          failCommands: %w(isMaster hello),
          errorCode: 1234,
          appName: "SDAMMinHeartbeatFrequencyTest"
        },
      )
    end

    let(:operation) do
      expect(server.monitor.connection).not_to be nil
      set_fail_point
    end

    it "waits 500ms between failed hello checks" do
      operation
      start = Mongo::Utils.monotonic_time
      cmd_client.command(hello: 1)
      duration = Mongo::Utils.monotonic_time - start
      expect(duration).to be >= 2
      expect(duration).to be <= 3.5

      # The cluster that we use to set up the failpoint should not be the same
      # one we ping on, so that the ping will have to select a server. The admin
      # client has already selected a server.
      expect(admin_client.cluster.object_id).to_not eq(cmd_client.cluster.object_id)
    end

    after do
      admin_client.command(configureFailPoint: 'failCommand', mode: 'off')
      cmd_client.close
    end
  end
end