Пример #1
0
 protected void SetupNewTestCluster()
 {
     Dispose();
     Session     = null;
     TestCluster = null;
     Init();
 }
Пример #2
0
        private void Init()
        {
            var listener = new TestTraceListener();

            Trace.Listeners.Add(listener);
            try
            {
                TestCluster = _simulacronManager == null
                    ? SimulacronManager.DefaultInstance.CreateNew(_options)
                    : _simulacronManager.CreateNew(_options);
            }
            catch (Exception ex)
            {
                Trace.Flush();
                throw new Exception(string.Join(Environment.NewLine, listener.Queue.ToArray()), ex);
            }
            finally
            {
                Trace.Listeners.Remove(listener);
            }

            if (_connect)
            {
                Session = CreateSession();
                if (_keyspace != null)
                {
                    Session.ChangeKeyspace(_keyspace);
                }
            }
        }
Пример #3
0
        public void The_Query_Plan_Should_Contain_A_Single_Host_When_Targeting_Single_Host()
        {
            var builder = Cluster.Builder();

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    const string query = "SELECT * FROM simulated_ks.table1";
                    testCluster.Prime(new
                    {
                        when = new { query },
                        then = new { result = "overloaded", message = "Test overloaded error" }
                    });

                    var session = cluster.Connect();
                    var host    = cluster.AllHosts().Last();

                    var statement = new SimpleStatement(query).SetHost(host).SetIdempotence(true);

                    // Overloaded exceptions should be retried on the next host
                    // but only 1 host in the query plan is expected
                    var ex = Assert.Throws <NoHostAvailableException>(() => session.Execute(statement));

                    Assert.That(ex.Errors, Has.Count.EqualTo(1));
                    Assert.IsInstanceOf <OverloadedException>(ex.Errors.First().Value);
                    Assert.That(ex.Errors.First().Key, Is.EqualTo(host.Address));
                }
        }
Пример #4
0
        public async Task Should_Not_Use_The_LoadBalancingPolicy_When_Targeting_Single_Host()
        {
            var queryPlanCounter = 0;
            var lbp = new TestHelper.CustomLoadBalancingPolicy((cluster, ks, stmt) =>
            {
                Interlocked.Increment(ref queryPlanCounter);
                return(cluster.AllHosts());
            });

            var builder = Cluster.Builder().WithLoadBalancingPolicy(lbp);

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    var session = await cluster.ConnectAsync();

                    var host = cluster.AllHosts().Last();
                    Interlocked.Exchange(ref queryPlanCounter, 0);

                    await TestHelper.TimesLimit(() =>
                    {
                        var statement = new SimpleStatement("SELECT * FROM system.local").SetHost(host);
                        return(session.ExecuteAsync(statement));
                    }, 1, 1);

                    Assert.Zero(Volatile.Read(ref queryPlanCounter));
                }
        }
        public async Task Should_RetryOnNextHost_When_SendFailsOnCurrentHostRetryPolicy(bool async)
        {
            using (var simulacronCluster = SimulacronCluster.CreateNew(3))
            {
                var contactPoint = simulacronCluster.InitialContactPoint;
                var nodes        = simulacronCluster.GetNodes().ToArray();
                var queryPlan    = new List <SimulacronNode>
                {
                    nodes[1],
                    nodes[2],
                    nodes[0]
                };
                await queryPlan[0].Stop().ConfigureAwait(false);
                var   currentHostRetryPolicy = new CurrentHostRetryPolicy(10, null);
                var   loadBalancingPolicy    = new CustomLoadBalancingPolicy(
                    queryPlan.Select(n => n.ContactPoint).ToArray());
                var builder = Cluster.Builder()
                              .AddContactPoint(contactPoint)
                              .WithSocketOptions(new SocketOptions()
                                                 .SetConnectTimeoutMillis(10000)
                                                 .SetReadTimeoutMillis(5000))
                              .WithLoadBalancingPolicy(loadBalancingPolicy)
                              .WithRetryPolicy(currentHostRetryPolicy);
                using (var cluster = builder.Build())
                {
                    var          session = (Session)cluster.Connect();
                    const string cql     = "select * from table2";

                    queryPlan[1].PrimeFluent(
                        b => b.WhenQuery(cql).
                        ThenRowsSuccess(new[] { ("text", DataType.Ascii) }, rows => rows.WithRow("test1").WithRow("test2")));
Пример #6
0
 public void Should_Failover_When_First_Node_Timeouts()
 {
     Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Verbose;
     using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
         Nodes = "3"
     }))
         using (var cluster = Cluster.Builder()
                              .AddContactPoint(simulacronCluster.InitialContactPoint)
                              .WithQueryOptions(new QueryOptions().SetPrepareOnAllHosts(false))
                              .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(400))
                              .WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy()).Build())
         {
             var session   = cluster.Connect();
             var firstHost = cluster.AllHosts().First();
             foreach (var h in cluster.AllHosts())
             {
                 var node = simulacronCluster.GetNode(h.Address);
                 node.Prime(QueryPrime(h == firstHost ? 5000 : 0));
             }
             var ps = session.Prepare(Query);
             Assert.NotNull(ps);
             // Should have been executed in the first node (timed out) and in the second one (succeeded)
             Assert.AreEqual(2, simulacronCluster.GetQueries(Query, "PREPARE").Count);
         }
 }
Пример #7
0
        public async Task Should_Reprepare_On_Up_Node()
        {
            using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = Cluster.Builder()
                                     .AddContactPoint(simulacronCluster.InitialContactPoint)
                                     .WithReconnectionPolicy(new ConstantReconnectionPolicy(500))
                                     .WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy()).Build())
                {
                    var session = cluster.Connect();
                    simulacronCluster.Prime(QueryPrime());
                    var ps = await session.PrepareAsync(Query).ConfigureAwait(false);

                    Assert.NotNull(ps);
                    Assert.AreEqual(3, simulacronCluster.GetQueries(Query, "PREPARE").Count);
                    var node = simulacronCluster.GetNodes().Skip(1).First();
                    // It should have been prepared once on the node we are about to stop
                    Assert.AreEqual(1, node.GetQueries(Query, "PREPARE").Count);
                    await node.Stop().ConfigureAwait(false);

                    await TestHelper.WaitUntilAsync(() => cluster.AllHosts().Any(h => !h.IsUp)).ConfigureAwait(false);

                    Assert.AreEqual(1, cluster.AllHosts().Count(h => !h.IsUp));
                    await node.Start().ConfigureAwait(false);

                    await TestHelper.WaitUntilAsync(() => cluster.AllHosts().All(h => h.IsUp)).ConfigureAwait(false);

                    Assert.AreEqual(0, cluster.AllHosts().Count(h => !h.IsUp));
                    TestHelper.WaitUntil(() => node.GetQueries(Query, "PREPARE").Count == 2);
                    // It should be prepared 2 times
                    Assert.AreEqual(2, node.GetQueries(Query, "PREPARE").Count);
                }
        }
Пример #8
0
        public void Should_Throw_NoHostAvailableException_When_Targeting_Single_Ignored_Host()
        {
            const string query = "SELECT * FROM system.local";
            // Mark the last host as ignored
            var lbp = new TestHelper.CustomLoadBalancingPolicy(
                (cluster, ks, stmt) => cluster.AllHosts(),
                (cluster, host) => host.Equals(cluster.AllHosts().Last()) ? HostDistance.Ignored : HostDistance.Local);
            var builder = Cluster.Builder().WithLoadBalancingPolicy(lbp);

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    var session  = cluster.Connect();
                    var lastHost = cluster.AllHosts().Last();

                    // Use the last host
                    var statement = new SimpleStatement(query).SetHost(lastHost);
                    Parallel.For(0, 10, _ =>
                    {
                        var ex = Assert.ThrowsAsync <NoHostAvailableException>(() => session.ExecuteAsync(statement));
                        Assert.That(ex.Errors.Count, Is.EqualTo(1));
                        Assert.That(ex.Errors.First().Key, Is.EqualTo(lastHost.Address));
                    });
                }
        }
Пример #9
0
        public async Task Should_Failover_With_Connections_Closing()
        {
            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "4"
            }))
            {
                var initialContactPoint = testCluster.InitialContactPoint.Address.GetAddressBytes();
                var port          = testCluster.InitialContactPoint.Port;
                var contactPoints = new IPEndPoint[4];
                for (byte i = 0; i < 4; i++)
                {
                    var arr = (byte[])initialContactPoint.Clone();
                    arr[3]          += i;
                    contactPoints[i] = new IPEndPoint(new IPAddress(arr), port);
                }
                var builder = Cluster.Builder().AddContactPoints(contactPoints);
                var index   = 0;
                await TestHelper.TimesLimit(async() =>
                {
                    var nodeAsDown   = -1;
                    var currentIndex = Interlocked.Increment(ref index);
                    switch (currentIndex)
                    {
                    case 11:
                        nodeAsDown = 0;
                        break;

                    case 18:
                        nodeAsDown = 1;
                        break;
                    }

                    if (nodeAsDown >= 0)
                    {
                        await testCluster.GetNodes().Skip(nodeAsDown).First().DisableConnectionListener()
                        .ConfigureAwait(false);
                        var connections = testCluster.GetConnectedPorts();
                        for (var i = connections.Count - 3; i < connections.Count; i++)
                        {
                            try
                            {
                                await testCluster.DropConnection(connections.Last()).ConfigureAwait(false);
                            }
                            catch
                            {
                                // Connection might be already closed
                            }
                        }
                    }

                    using (var cluster = builder.Build())
                    {
                        await cluster.ConnectAsync().ConfigureAwait(false);
                    }


                    return(0);
                }, 60, 5).ConfigureAwait(false);
            }
        }
Пример #10
0
        public void Should_Move_To_Next_Host_For_Bound_Statements()
        {
            _testCluster = SimulacronCluster.CreateNew(2);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(500);
            var builder       = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                var ps      = session.Prepare("SELECT key FROM system.local");
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                var nodes = _testCluster.GetNodes().ToList();
                var node  = nodes[0];
                node.Prime(new
                {
                    when = new { query = "SELECT key FROM system.local" },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 2000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });
                TestHelper.Invoke(() =>
                {
                    var rs = session.Execute(ps.Bind());
                    Assert.AreEqual(nodes[1].ContactPoint, rs.Info.QueriedHost.ToString());
                }, 10);
            }
        }
        public void ShouldUseChildRetryPolicy_OnWriteTimeout()
        {
            var tableName = TestUtils.GetUniqueTableName();
            var cql       = $"INSERT INTO {tableName}(k, i) VALUES (0, 0)";

            using (var simulacronCluster = SimulacronCluster.CreateNew(1))
                using (var cluster = Cluster.Builder().AddContactPoint(simulacronCluster.InitialContactPoint)
                                     .Build())
                {
                    var session = cluster.Connect();
                    simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenWriteTimeout("write_timeout", 5, 1, 2, "SIMPLE"));

                    var testPolicy = new TestRetryPolicy();
                    var policy     = new IdempotenceAwareRetryPolicy(testPolicy);

                    Assert.Throws <WriteTimeoutException>(() => session.Execute(
                                                              new SimpleStatement(cql)
                                                              .SetIdempotence(true)
                                                              .SetConsistencyLevel(ConsistencyLevel.All)
                                                              .SetRetryPolicy(policy)));

                    Assert.AreEqual(1L, Interlocked.Read(ref testPolicy.WriteTimeoutCounter));

                    Interlocked.Exchange(ref testPolicy.WriteTimeoutCounter, 0);

                    Assert.Throws <WriteTimeoutException>(() => session.Execute(
                                                              new SimpleStatement(cql)
                                                              .SetIdempotence(false)
                                                              .SetConsistencyLevel(ConsistencyLevel.All)
                                                              .SetRetryPolicy(policy)));

                    Assert.AreEqual(0L, Interlocked.Read(ref testPolicy.WriteTimeoutCounter));
                }
        }
Пример #12
0
        public void Should_Throw_NoHostAvailableException_When_All_Hosts_Down()
        {
            _testCluster = SimulacronCluster.CreateNew(2);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(500);
            var builder       = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                _testCluster.Prime(new
                {
                    when = new { query = "SELECT key FROM system.local" },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 10000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });
                var ex = Assert.Throws <NoHostAvailableException>(() => session.Execute("SELECT key FROM system.local"));
                Assert.AreEqual(2, ex.Errors.Count);
                foreach (var innerException in ex.Errors.Values)
                {
                    Assert.IsInstanceOf <OperationTimedOutException>(innerException);
                }
            }
        }
Пример #13
0
        public void Should_Not_Leak_Connections_Test()
        {
            _testCluster = SimulacronCluster.CreateNew(1);
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(1).SetConnectTimeoutMillis(1);
            var builder       = Cluster.Builder()
                                .AddContactPoint(_testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            var node = _testCluster.GetNodes().First();

            node.DisableConnectionListener(0, "reject_startup").GetAwaiter().GetResult();
            const int length = 1000;

            using (var cluster = builder.Build())
            {
                decimal initialLength = GC.GetTotalMemory(true);
                for (var i = 0; i < length; i++)
                {
                    var ex = Assert.Throws <NoHostAvailableException>(() => cluster.Connect());
                    Assert.AreEqual(1, ex.Errors.Count);
                }
                GC.Collect();
                Thread.Sleep(1000);
                Assert.Less(GC.GetTotalMemory(true) / initialLength, 1.3M,
                            "Should not exceed a 30% (1.3) more than was previously allocated");
            }
        }
Пример #14
0
        public void Should_Wait_When_ReadTimeout_Is_Zero()
        {
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(0);

            using (var simulacronCluster = SimulacronCluster.CreateNew(3))
            {
                const string cql = "SELECT key FROM system.local";
                simulacronCluster.Prime(new
                {
                    when = new { query = cql },
                    then = new
                    {
                        result            = "success",
                        delay_in_ms       = 30000,
                        rows              = new[] { new { key = "123" } },
                        column_types      = new { key = "ascii" },
                        ignore_on_prepare = false
                    }
                });

                using (var cluster = Cluster.Builder().AddContactPoint(simulacronCluster.InitialContactPoint).WithSocketOptions(socketOptions).Build())
                {
                    var session = cluster.Connect();
                    var query   = new SimpleStatement(cql);
                    var task    = session.ExecuteAsync(query);
                    Thread.Sleep(15000);
                    Assert.AreEqual(TaskStatus.WaitingForActivation, task.Status);
                    Thread.Sleep(15000);
                    TestHelper.RetryAssert(
                        () => { Assert.AreEqual(TaskStatus.RanToCompletion, task.Status, task.Exception?.ToString() ?? "no exception"); },
                        100,
                        50);
                }
            }
        }
Пример #15
0
        public void Should_UseSerialConsistencyLevel_From_QueryOptions(ConsistencyLevel consistencyLevel,
                                                                       string consistencyLevelString,
                                                                       ConsistencyLevel serialConsistency,
                                                                       string serialConsistencyLevelString)
        {
            using (var simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3,3"
            }))
                using (var cluster = Cluster.Builder()
                                     .AddContactPoint(simulacronCluster.InitialContactPoint)
                                     .WithQueryOptions(new QueryOptions()
                                                       .SetConsistencyLevel(consistencyLevel)
                                                       .SetSerialConsistencyLevel(serialConsistency))
                                     .Build())
                {
                    const string conditionalQuery = "update tbl_serial set value=3 where id=2 if exists";
                    var          session          = cluster.Connect();
                    var          simpleStatement  = new SimpleStatement(conditionalQuery);

                    var result = session.Execute(simpleStatement);
                    Assert.AreEqual(consistencyLevel, result.Info.AchievedConsistency);
                    VerifyConsistency(simulacronCluster, conditionalQuery, consistencyLevelString,
                                      serialConsistencyLevelString);
                }
        }
Пример #16
0
 public void OneTimeSetup()
 {
     _testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
         Nodes = "1"
     });
     _testCluster.PrimeFluent(b => b.WhenQuery(HeartbeatTests.Query).ThenVoidSuccess());
 }
Пример #17
0
 public void TestTearDown()
 {
     _testCluster?.Dispose();
     _testCluster = null;
     TestClusterManager.TryRemove();
     _realCluster = null;
 }
Пример #18
0
        public async Task Should_Create_Core_Connections_To_Hosts_In_Local_Dc_When_Warmup_Is_Enabled()
        {
            const int nodeLength     = 4;
            var       poolingOptions = PoolingOptions.Create().SetCoreConnectionsPerHost(HostDistance.Local, 5);

            // Use multiple DCs: 4 nodes in first DC and 3 nodes in second DC
            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = $"{nodeLength},3"
            }))
                using (var cluster = Cluster.Builder()
                                     .AddContactPoint(testCluster.InitialContactPoint)
                                     .WithPoolingOptions(poolingOptions).Build())
                {
                    var session = await cluster.ConnectAsync().ConfigureAwait(false);

                    var state = session.GetState();
                    var hosts = state.GetConnectedHosts();

                    Assert.AreEqual(nodeLength, hosts.Count);
                    foreach (var host in hosts)
                    {
                        Assert.AreEqual(poolingOptions.GetCoreConnectionsPerHost(HostDistance.Local),
                                        state.GetOpenConnections(host));
                    }
                }
        }
Пример #19
0
        public async Task Should_Use_Single_Host_When_Configured_At_Statement_Level()
        {
            const string query   = "SELECT * FROM system.local";
            var          builder = Cluster.Builder().WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy());

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    var session = await cluster.ConnectAsync();

                    var firstHost = cluster.AllHosts().First();
                    var lastHost  = cluster.AllHosts().Last();

                    // The test load-balancing policy targets always the first host
                    await TestHelper.TimesLimit(async() =>
                    {
                        var rs = await session.ExecuteAsync(new SimpleStatement(query));
                        Assert.AreEqual(rs.Info.QueriedHost, firstHost.Address);
                        return(rs);
                    }, 10, 10);

                    // Use a specific host
                    var statement = new SimpleStatement(query).SetHost(lastHost);
                    await TestHelper.TimesLimit(async() =>
                    {
                        var rs = await session.ExecuteAsync(statement);
                        // The queried host should be the last one
                        Assert.AreEqual(rs.Info.QueriedHost, lastHost.Address);
                        return(rs);
                    }, 10, 10);
                }
        }
Пример #20
0
        public void PoolingOptions_Create_Based_On_Protocol(ProtocolVersion protocolVersion, int coreConnectionLength)
        {
            var sCluster = SimulacronCluster.CreateNew(new SimulacronOptions());
            var options1 = PoolingOptions.Create(protocolVersion);

            using (var cluster = Cluster.Builder()
                                 .AddContactPoint(sCluster.InitialContactPoint)
                                 .WithPoolingOptions(options1)
                                 .Build())
            {
                var session  = (IInternalSession)cluster.Connect();
                var allHosts = cluster.AllHosts();
                var host     = allHosts.First();
                var pool     = session.GetOrCreateConnectionPool(host, HostDistance.Local);

                TestHelper.WaitUntil(() =>
                                     pool.OpenConnections == coreConnectionLength);
                var ports = sCluster.GetConnectedPorts();
                TestHelper.RetryAssert(() =>
                {
                    ports = sCluster.GetConnectedPorts();
                    //coreConnectionLength + 1 (the control connection)
                    Assert.AreEqual(coreConnectionLength + 1, ports.Count);
                }, 100, 200);
            }
        }
Пример #21
0
        protected virtual SimulacronCluster CreateNew(SimulacronOptions options)
        {
            Options = options;
            var c = SimulacronCluster.CreateNew(options);

            _simulacronClusters.Add(c);
            return(c);
        }
Пример #22
0
 public void OneTimeSetup()
 {
     _testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
         Nodes = "3"
     });
     _testCluster.PrimeFluent(b =>
                              b.WhenQuery(Query)
                              .ThenRowsSuccess(new[] { ("id", DataType.Uuid) }, rows => rows.WithRow(Guid.NewGuid())).WithDelayInMs(20));
Пример #23
0
        public async Task ControlConnection_Should_Reconnect_After_Failed_Attemps()
        {
            const int connectionLength = 1;
            var       builder          = Cluster.Builder()
                                         .WithPoolingOptions(new PoolingOptions()
                                                             .SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
                                                             .SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
                                                             .SetHeartBeatInterval(1000))
                                         .WithReconnectionPolicy(new ConstantReconnectionPolicy(100L));

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    var session  = (Session)cluster.Connect();
                    var allHosts = cluster.AllHosts();
                    Assert.AreEqual(3, allHosts.Count);
                    await TestHelper.TimesLimit(() =>
                                                session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")), 100, 16);

                    var serverConnections = testCluster.GetConnectedPorts();
                    // 1 per hosts + control connection
                    WaitSimulatorConnections(testCluster, 4);
                    Assert.AreEqual(4, serverConnections.Count);

                    // Disable all connections
                    await testCluster.DisableConnectionListener();

                    var ccAddress = cluster.GetControlConnection().Address;

                    // Drop all connections to hosts
                    foreach (var connection in serverConnections)
                    {
                        await testCluster.DropConnection(connection);
                    }

                    TestHelper.WaitUntil(() => !cluster.GetHost(ccAddress).IsUp);

                    // All host should be down by now
                    TestHelper.WaitUntil(() => cluster.AllHosts().All(h => !h.IsUp));

                    Assert.False(cluster.GetHost(ccAddress).IsUp);

                    // Allow new connections to be created
                    await testCluster.EnableConnectionListener();

                    TestHelper.WaitUntil(() => cluster.AllHosts().All(h => h.IsUp));

                    ccAddress = cluster.GetControlConnection().Address;
                    Assert.True(cluster.GetHost(ccAddress).IsUp);

                    // Once all connections are created, the control connection should be usable
                    WaitSimulatorConnections(testCluster, 4);
                    Assert.DoesNotThrowAsync(() => cluster.GetControlConnection().QueryAsync("SELECT * FROM system.local"));
                }
        }
Пример #24
0
        public async Task ControlConnection_Should_Reconnect_To_Up_Host()
        {
            const int connectionLength = 1;
            var       builder          = Cluster.Builder()
                                         .WithPoolingOptions(new PoolingOptions()
                                                             .SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
                                                             .SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
                                                             .SetHeartBeatInterval(1000))
                                         .WithReconnectionPolicy(new ConstantReconnectionPolicy(100L));

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    var session  = (Session)cluster.Connect();
                    var allHosts = cluster.AllHosts();
                    Assert.AreEqual(3, allHosts.Count);
                    await TestHelper.TimesLimit(() =>
                                                session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")), 100, 16);

                    // 1 per hosts + control connection
                    WaitSimulatorConnections(testCluster, 4);
                    Assert.AreEqual(4, testCluster.GetConnectedPorts().Count);

                    var ccAddress      = cluster.GetControlConnection().Address;
                    var simulacronNode = testCluster.GetNode(ccAddress);

                    // Disable new connections to the first host
                    await simulacronNode.DisableConnectionListener();

                    Assert.NotNull(simulacronNode);
                    var connections = simulacronNode.GetConnections();

                    // Drop connections to the host that is being used by the control connection
                    Assert.AreEqual(2, connections.Count);
                    await testCluster.DropConnection(connections[0]);

                    await testCluster.DropConnection(connections[1]);

                    TestHelper.WaitUntil(() => !cluster.GetHost(ccAddress).IsUp);

                    Assert.False(cluster.GetHost(ccAddress).IsUp);

                    TestHelper.WaitUntil(() => !cluster.GetControlConnection().Address.Address.Equals(ccAddress.Address));

                    Assert.AreNotEqual(ccAddress.Address, cluster.GetControlConnection().Address.Address);

                    // Previous host is still DOWN
                    Assert.False(cluster.GetHost(ccAddress).IsUp);

                    // New host is UP
                    ccAddress = cluster.GetControlConnection().Address;
                    Assert.True(cluster.GetHost(ccAddress).IsUp);
                }
        }
Пример #25
0
        protected virtual SimulacronCluster CreateNew(int nodeLength)
        {
            Options = new SimulacronOptions {
                Nodes = nodeLength.ToString()
            };
            var c = SimulacronCluster.CreateNew(Options);

            _simulacronClusters.Add(c);
            return(c);
        }
Пример #26
0
 public void Should_Not_Downgrade_Protocol_Version(ProtocolVersion version, params string[] cassandraVersions)
 {
     using (var testCluster = SimulacronCluster.CreateNewWithPostBody(GetSimulatorBody(cassandraVersions)))
         using (var cluster = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).Build())
         {
             var session = cluster.Connect();
             Parallel.For(0, 10, _ => session.Execute("SELECT * FROM system.local"));
             Assert.AreEqual(cluster.InternalRef.GetControlConnection().ProtocolVersion, version);
         }
 }
 public void OneTimeSetup()
 {
     _testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
         Nodes = "1"
     });
     _testCluster.Prime(new
     {
         when = new { query = Query },
         then = new { result = "success" }
     });
 }
        public void Should_CreateSimulacronCluster()
        {
            const string query             = "SELECT * FROM system.traces";
            var          simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            });
            var contactPoint = simulacronCluster.InitialContactPoint;
            var builder      = Cluster.Builder()
                               .AddContactPoint(contactPoint);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();

                var primeQuery = new
                {
                    when = new { query = query },
                    then = new
                    {
                        result      = "success",
                        delay_in_ms = 0,
                        rows        = new []
                        {
                            new
                            {
                                id    = Guid.NewGuid(),
                                value = "value"
                            }
                        },
                        column_types = new
                        {
                            id    = "uuid",
                            value = "varchar"
                        }
                    }
                };

                simulacronCluster.Prime(primeQuery);
                var result   = session.Execute(query);
                var firstRow = result.FirstOrDefault();
                Assert.NotNull(firstRow);
                Assert.AreEqual("value", firstRow["value"]);

                var logs   = simulacronCluster.GetLogs();
                var dcLogs = logs.data_centers as IEnumerable <dynamic>;
                Assert.NotNull(dcLogs);
                Assert.True(
                    dcLogs.Any(dc =>
                               (dc.nodes as IEnumerable <dynamic>).Any(node =>
                                                                       (node.queries as IEnumerable <dynamic>).Any(q =>
                                                                                                                   q.query.ToString() == query)))
                    );
            }
        }
Пример #29
0
        public async Task Should_Use_Next_Host_When_First_Host_Is_Busy()
        {
            const int connectionLength         = 2;
            const int maxRequestsPerConnection = 100;
            var       builder = Cluster.Builder()
                                .WithPoolingOptions(
                PoolingOptions.Create()
                .SetCoreConnectionsPerHost(HostDistance.Local, connectionLength)
                .SetMaxConnectionsPerHost(HostDistance.Local, connectionLength)
                .SetHeartBeatInterval(0)
                .SetMaxRequestsPerConnection(maxRequestsPerConnection))
                                .WithLoadBalancingPolicy(new TestHelper.OrderedLoadBalancingPolicy());

            using (var testCluster = SimulacronCluster.CreateNew(new SimulacronOptions {
                Nodes = "3"
            }))
                using (var cluster = builder.AddContactPoint(testCluster.InitialContactPoint).Build())
                {
                    const string query = "SELECT * FROM simulated_ks.table1";
                    testCluster.Prime(new
                    {
                        when = new { query },
                        then = new { result = "success", delay_in_ms = 3000 }
                    });

                    var session = await cluster.ConnectAsync();

                    var hosts = cluster.AllHosts().ToArray();

                    // Wait until all connections to first host are created
                    await TestHelper.WaitUntilAsync(() =>
                                                    session.GetState().GetInFlightQueries(hosts[0]) == connectionLength);

                    const int overflowToNextHost = 10;
                    var       length             = maxRequestsPerConnection * connectionLength + Environment.ProcessorCount +
                                                   overflowToNextHost;
                    var tasks = new List <Task <RowSet> >(length);

                    for (var i = 0; i < length; i++)
                    {
                        tasks.Add(session.ExecuteAsync(new SimpleStatement(query)));
                    }

                    var results = await Task.WhenAll(tasks);

                    // At least the first n (maxRequestsPerConnection * connectionLength) went to the first host
                    Assert.That(results.Count(r => r.Info.QueriedHost.Equals(hosts[0].Address)),
                                Is.GreaterThanOrEqualTo(maxRequestsPerConnection * connectionLength));

                    // At least the following m (overflowToNextHost) went to the second host
                    Assert.That(results.Count(r => r.Info.QueriedHost.Equals(hosts[1].Address)),
                                Is.GreaterThanOrEqualTo(overflowToNextHost));
                }
        }
 private static Cluster BuildCluster(SimulacronCluster simulacronCluster)
 {
     return(Cluster.Builder()
            .AddContactPoint(simulacronCluster.InitialContactPoint)
            .WithSocketOptions(
                new SocketOptions()
                .SetReadTimeoutMillis(5000)
                .SetConnectTimeoutMillis(10000))
            .WithMaxSchemaAgreementWaitSeconds(MaxSchemaAgreementWaitSeconds)
            .Build());
 }