private void AssertAuthenticationSucceeds(
     MongoClientSettings settings,
     bool async,
     bool speculativeAuthenticatationShouldSucceedIfPossible = true)
 {
     // If we don't use a DisposableClient, the second run of AuthenticationSucceedsWithMongoDB_X509_mechanism
     // will fail because the backing Cluster's connections will be associated with a dropped user
     using (var client = DriverTestConfiguration.CreateDisposableClient(settings))
     {
         // The first command executed with the MongoClient triggers either the sync or async variation of the
         // MongoClient's IAuthenticator
         if (async)
         {
             _ = client.ListDatabaseNamesAsync().GetAwaiter().GetResult().ToList();
         }
         else
         {
             _ = client.ListDatabaseNames().ToList();
         }
         if (Feature.SpeculativeAuthentication.IsSupported(CoreTestConfiguration.ServerVersion) &&
             speculativeAuthenticatationShouldSucceedIfPossible)
         {
             var cancellationToken = CancellationToken.None;
             var serverSelector    = new ReadPreferenceServerSelector(settings.ReadPreference);
             var server            = client.Cluster.SelectServer(serverSelector, cancellationToken);
             var channel           = server.GetChannel(cancellationToken);
             var isMasterResult    = channel.ConnectionDescription.IsMasterResult;
             isMasterResult.SpeculativeAuthenticate.Should().NotBeNull();
         }
     }
 }
예제 #2
0
        public void Should_call_custom_server_selector()
        {
            var eventCapturer = new EventCapturer()
                                .Capture <ClusterSelectingServerEvent>()
                                .Capture <ClusterSelectedServerEvent>();
            var customServerSelector = new CustomServerSelector();

            using (var client = DriverTestConfiguration.CreateDisposableClient(
                       clientSettings =>
                       clientSettings.ClusterConfigurator =
                           c =>
            {
                c.ConfigureCluster(s => s.With(postServerSelector: customServerSelector));
                c.Subscribe(eventCapturer);
            },
                       logger: null))
            {
                var collection = client
                                 .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                                 .GetCollection <BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName)
                                 .WithReadPreference(ReadPreference.Nearest);

                customServerSelector.CustomSelectorWasCalled = false;
                eventCapturer.Clear();

                collection.CountDocuments(new BsonDocument());

                customServerSelector.CustomSelectorWasCalled.Should().BeTrue();
                eventCapturer.Next().Should().BeOfType <ClusterSelectingServerEvent>();
                eventCapturer.Next().Should().BeOfType <ClusterSelectedServerEvent>();
            }
        }
        public void KillCursor_should_actually_work()
        {
            RequireServer.Check().Supports(Feature.KillCursorsCommand);
            var eventCapturer = new EventCapturer().Capture <CommandSucceededEvent>(x => x.CommandName.Equals("killCursors"));

            using (var client = DriverTestConfiguration.CreateDisposableClient(eventCapturer))
            {
                IAsyncCursor <BsonDocument> cursor;
                var database   = client.GetDatabase("test");
                var collection = database.GetCollection <BsonDocument>(GetType().Name);
                var documents  = new List <BsonDocument>();
                for (int i = 0; i < 1000; i++)
                {
                    documents.Add(new BsonDocument("x", i));
                }

                collection.InsertMany(documents);
                cursor = collection.FindSync("{}");
                cursor.MoveNext();

                var cursorId = ((AsyncCursor <BsonDocument>)cursor)._cursorId();
                cursorId.Should().NotBe(0);
                cursor.Dispose();

                var desiredResult = BsonDocument.Parse($"{{ \"cursorsKilled\" : [{cursorId}], \"cursorsNotFound\" : [], " +
                                                       $"\"cursorsAlive\" : [], \"cursorsUnknown\" : [], \"ok\" : 1.0 }}");
                var result = ((CommandSucceededEvent)eventCapturer.Events[0]).Reply;
                result.IsSameOrEqualTo(desiredResult);
            }
        }
 private DisposableMongoClient GetClient(Action <ClusterBuilder> clusterConfigurator)
 {
     return(DriverTestConfiguration.CreateDisposableClient((MongoClientSettings clientSettings) =>
     {
         clientSettings.ClusterConfigurator = clusterConfigurator;
         clientSettings.RetryWrites = true;
     }));
 }
 // private methods
 private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer, ReadPreference readPreference)
 {
     return(DriverTestConfiguration.CreateDisposableClient((MongoClientSettings settings) =>
     {
         settings.ClusterConfigurator = c => c.Subscribe(eventCapturer);
         settings.ReadPreference = readPreference;
     }));
 }
예제 #6
0
 private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer, bool useMultipleShardRouters)
 {
     return(DriverTestConfiguration.CreateDisposableClient((MongoClientSettings settings) =>
     {
         settings.ClusterConfigurator = c => c.Subscribe(eventCapturer);
     },
                                                           useMultipleShardRouters));
 }
예제 #7
0
 private DisposableMongoClient GetClient(Action <ClusterBuilder> clusterConfigurator, bool retryWrites = true)
 {
     return(DriverTestConfiguration.CreateDisposableClient((MongoClientSettings clientSettings) =>
     {
         clientSettings.ClusterConfigurator = clusterConfigurator;
         clientSettings.RetryWrites = retryWrites;
     },
                                                           logger: CreateLogger <DisposableMongoClient>()));
 }
예제 #8
0
 private DisposableMongoClient CreateDisposableClient(EventCapturer capturedEvents)
 {
     return(DriverTestConfiguration.CreateDisposableClient(
                settings =>
     {
         settings.RetryWrites = false;
         settings.ClusterConfigurator = c => { c.Subscribe(capturedEvents); };
     }));
 }
 private DisposableMongoClient CreateDisposableClient(EventCapturer capturedEvents)
 {
     return(DriverTestConfiguration.CreateDisposableClient(
                settings =>
     {
         settings.HeartbeatInterval = TimeSpan.FromMilliseconds(5);     // the default value for spec tests
         settings.RetryWrites = false;
         settings.ClusterConfigurator = c => { c.Subscribe(capturedEvents); };
     }));
 }
        private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer, bool useMultipleShardRouters)
        {
            // Increase localThresholdMS and wait until all nodes are discovered to avoid false positives.
            var client = DriverTestConfiguration.CreateDisposableClient((MongoClientSettings settings) =>
            {
                settings.ClusterConfigurator = c => c.Subscribe(eventCapturer);
                settings.LocalThreshold      = TimeSpan.FromMilliseconds(1000);
            },
                                                                        useMultipleShardRouters);
            var timeOut = TimeSpan.FromSeconds(60);

            SpinWait.SpinUntil(() => client.Cluster.Description.Type != ClusterType.Unknown, timeOut).Should().BeTrue();
            return(client);
        }
        private void AssertAuthenticationFails(MongoClientSettings settings, bool async)
        {
            using (var client = DriverTestConfiguration.CreateDisposableClient(settings))
            {
                Exception exception;
                if (async)
                {
                    exception = Record.Exception(() => client.ListDatabaseNamesAsync().GetAwaiter().GetResult().ToList());
                }
                else
                {
                    exception = Record.Exception(() => client.ListDatabaseNames().ToList());
                }

                exception.Should().BeOfType <MongoAuthenticationException>();
            }
        }
        public void Connection_pool_should_not_be_cleared_when_replSetStepDown_and_GetMore([Values(false, true)] bool async)
        {
            RequireServer.Check().Supports(Feature.KeepConnectionPoolWhenReplSetStepDown).ClusterType(ClusterType.ReplicaSet);

            var eventCapturer = new EventCapturer().Capture <ConnectionPoolClearedEvent>();

            using (var client = CreateDisposableClient(eventCapturer))
            {
                var database = client.GetDatabase(_databaseName, new MongoDatabaseSettings {
                    WriteConcern = WriteConcern.WMajority
                });
                database.DropCollection(_databaseName);
                var collection = database.GetCollection <BsonDocument>(_collectionName, new MongoCollectionSettings {
                    WriteConcern = WriteConcern.WMajority
                });
                var adminDatabase = client.GetDatabase("admin").WithWriteConcern(WriteConcern.W1);

                collection.InsertMany(
                    new[]
                {
                    new BsonDocument("x", 1),
                    new BsonDocument("x", 2),
                    new BsonDocument("x", 3),
                    new BsonDocument("x", 4),
                    new BsonDocument("x", 5),
                });
                eventCapturer.Clear();

                var cursor = collection.FindSync(FilterDefinition <BsonDocument> .Empty, new FindOptions <BsonDocument> {
                    BatchSize = 2
                });
                cursor.MoveNext();

                foreach (var secondary in client.Cluster.Description.Servers.Where(c => c.Type == ServerType.ReplicaSetSecondary))
                {
                    RunOnSecondary(client, secondary.EndPoint, BsonDocument.Parse("{ replSetFreeze : 0 }"));
                }

                var          replSetStepDownCommand = BsonDocument.Parse("{ replSetStepDown : 30, force : true }");
                BsonDocument replSetStepDownResult;
                if (async)
                {
                    replSetStepDownResult = adminDatabase.RunCommandAsync <BsonDocument>(replSetStepDownCommand).GetAwaiter().GetResult();
                }
                else
                {
                    replSetStepDownResult = adminDatabase.RunCommand <BsonDocument>(replSetStepDownCommand);
                }

                replSetStepDownResult.Should().NotBeNull();
                replSetStepDownResult.GetValue("ok", false).ToBoolean().Should().BeTrue();

                cursor.MoveNext();

                eventCapturer.Events.Should().BeEmpty(); // it also means that no new PoolClearedEvent
            }

            void RunOnSecondary(IMongoClient primaryClient, EndPoint secondaryEndpoint, BsonDocument command)
            {
                var secondarySettings = primaryClient.Settings.Clone();

                secondarySettings.ClusterConfigurator = null;
#pragma warning disable CS0618 // Type or member is obsolete
                secondarySettings.ConnectionMode = ConnectionMode.Direct;
#pragma warning restore CS0618 // Type or member is obsolete
                var secondaryDnsEndpoint = (DnsEndPoint)secondaryEndpoint;
                secondarySettings.Server = new MongoServerAddress(secondaryDnsEndpoint.Host, secondaryDnsEndpoint.Port);
                using (var secondaryClient = DriverTestConfiguration.CreateDisposableClient(secondarySettings))
                {
                    var adminDatabase = secondaryClient.GetDatabase(DatabaseNamespace.Admin.DatabaseName);
                    adminDatabase.RunCommand <BsonDocument>(command);
                }
            }
        }
예제 #13
0
 private DisposableMongoClient GetClient(EventCapturer capturer)
 {
     return(DriverTestConfiguration.CreateDisposableClient(capturer));
 }