public void TokenAware_TargetPartition_NoHops()
        {
            // Setup
            PolicyTestTools policyTestTools = new PolicyTestTools();
            ITestCluster    testCluster     = TestClusterManager.CreateNew(3);

            testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
            testCluster.InitClient();

            // Test
            policyTestTools.TableName = TestUtils.GetUniqueTableName();
            policyTestTools.CreateSchema(testCluster.Session, 1);
            var traces = new List <QueryTrace>();

            for (var i = -10; i < 10; i++)
            {
                var partitionKey = BitConverter.GetBytes(i).Reverse().ToArray();
                var statement    = new SimpleStatement(String.Format("INSERT INTO " + policyTestTools.TableName + " (k, i) VALUES ({0}, {0})", i))
                                   .SetRoutingKey(new RoutingKey()
                {
                    RawRoutingKey = partitionKey
                })
                                   .EnableTracing();
                var rs = testCluster.Session.Execute(statement);
                traces.Add(rs.Info.QueryTrace);
            }
            //Check that there weren't any hops
            foreach (var t in traces)
            {
                //The coordinator must be the only one executing the query
                Assert.True(t.Events.All(e => e.Source.ToString() == t.Coordinator.ToString()), "There were trace events from another host for coordinator " + t.Coordinator);
            }
        }
Esempio n. 2
0
 public void Should_Remove_Decommissioned_Node()
 {
     _testCluster = TestClusterManager.CreateNew(2);
     using (var cluster = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint).Build())
     {
         var session = cluster.Connect();
         Assert.AreEqual(2, cluster.AllHosts().Count);
         _testCluster.DecommissionNode(2);
         Trace.TraceInformation("Node decommissioned");
         Thread.Sleep(10000);
         var decommisionedNode = _testCluster.ClusterIpPrefix + 2;
         Assert.False(TestHelper.TryConnect(decommisionedNode), "Removed node should not accept connections");
         //New node should be part of the metadata
         Assert.AreEqual(1, cluster.AllHosts().Count);
         var queried = false;
         for (var i = 0; i < 10; i++)
         {
             var rs = session.Execute("SELECT key FROM system.local");
             if (rs.Info.QueriedHost.Address.ToString() == decommisionedNode)
             {
                 queried = true;
                 break;
             }
         }
         Assert.False(queried, "Removed node should be queried");
     }
 }
 public virtual void OneTimeSetUp()
 {
     if (_reuse && _reusableInstance != null && ReferenceEquals(_reusableInstance, TestClusterManager.LastInstance))
     {
         Trace.WriteLine("Reusing single node ccm instance");
         TestCluster = _reusableInstance;
     }
     else
     {
         TestCluster = TestClusterManager.CreateNew(AmountOfNodes);
         if (_reuse)
         {
             _reusableInstance = TestCluster;
         }
         else
         {
             _reusableInstance = null;
         }
     }
     if (CreateSession)
     {
         CreateCommonSession();
         if (SetupQueries != null)
         {
             ExecuteSetupQueries();
         }
     }
 }
        public void Reconnection_Attempts_Are_Made_In_The_Background()
        {
            var testCluster = TestClusterManager.CreateNew(2);

            using (var cluster = Cluster.Builder()
                                 .AddContactPoint(testCluster.InitialContactPoint)
                                 .WithPoolingOptions(
                       new PoolingOptions()
                       .SetCoreConnectionsPerHost(HostDistance.Local, 2)
                       .SetHeartBeatInterval(0))
                                 .WithReconnectionPolicy(new ConstantReconnectionPolicy(2000))
                                 .Build())
            {
                var session = (Session)cluster.Connect();
                TestHelper.Invoke(() => session.Execute("SELECT * FROM system.local"), 10);
                var host = cluster.AllHosts().First(h => TestHelper.GetLastAddressByte(h) == 2);
                // Check that the control connection is connected to another host
                Assert.AreNotEqual(cluster.Metadata.ControlConnection.Address, host.Address);
                Assert.True(host.IsUp);
                Trace.TraceInformation("Setting host #2 as down");
                host.SetDown();
                Assert.False(host.IsUp);
                Trace.TraceInformation("Waiting for 5 seconds");
                Thread.Sleep(5000);
                Assert.True(host.IsUp);
            }
        }
Esempio n. 5
0
        public void PreparedStatement_Is_Usable_After_Node_Restart_When_Connecting_Providing_A_Keyspace()
        {
            var testCluster = TestClusterManager.CreateNew();

            using (var cluster = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
                                 .WithReconnectionPolicy(new ConstantReconnectionPolicy(500)).Build())
            {
                // Connect using a keyspace
                var session = cluster.Connect("system");
                var ps      = session.Prepare("SELECT key FROM local");
                var host    = cluster.AllHosts().First();
                var row     = session.Execute(ps.Bind()).First();
                Assert.NotNull(row.GetValue <string>("key"));

                // Stop the node
                testCluster.Stop(1);
                TestHelper.WaitUntil(() => !host.IsUp, 500, 40);
                Assert.False(host.IsUp);

                // Restart the node
                testCluster.Start(1);
                TestHelper.WaitUntil(() => host.IsUp, 500, 40);
                Assert.True(host.IsUp);

                // The same prepared statement should be valid
                row = session.Execute(ps.Bind()).First();
                Assert.NotNull(row.GetValue <string>("key"));
            }
        }
Esempio n. 6
0
        public void TokenMap_Should_RebuildTokenMap_When_NodeIsBootstrapped(bool metadataSync)
        {
            TestCluster = TestClusterManager.CreateNew(2, new TestClusterOptions {
                UseVNodes = true
            });
            var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();

            ClusterObj = Cluster.Builder()
                         .AddContactPoint(TestCluster.InitialContactPoint)
                         .WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(metadataSync))
                         .Build();

            var session           = ClusterObj.Connect();
            var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";

            session.Execute(createKeyspaceCql);
            TestUtils.WaitForSchemaAgreement(ClusterObj);
            session.ChangeKeyspace(keyspaceName);

            var replicas = ClusterObj.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123"));

            Assert.AreEqual(metadataSync ? 2 : 1, replicas.Count);
            Assert.AreEqual(2, ClusterObj.Metadata.Hosts.Count);
            var oldTokenMap = ClusterObj.Metadata.TokenToReplicasMap;

            this.TestCluster.BootstrapNode(3);
            TestHelper.RetryAssert(() =>
            {
                Assert.AreEqual(3, ClusterObj.Metadata.Hosts.Count);
                replicas = ClusterObj.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123"));
                Assert.AreEqual(metadataSync ? 3 : 1, replicas.Count);
                Assert.IsFalse(object.ReferenceEquals(ClusterObj.Metadata.TokenToReplicasMap, oldTokenMap));
            }, 100, 150);
        }
Esempio n. 7
0
        public void SetupFixture()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.2"), Comparison.LessThan))
            {
                Assert.Ignore("Requires Cassandra version >= 2.2");
                return;
            }

            Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;

            _testCluster = TestClusterManager.CreateNew(1, new TestClusterOptions
            {
                CassandraYaml = new[]
                {
                    "batch_size_warn_threshold_in_kb:5",
                    "batch_size_fail_threshold_in_kb:50"
                },
                //Using a mirroring handler, the server will reply providing the same payload that was sent
                JvmArgs = new[] { "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler" }
            });
            _testCluster.InitClient();
            Session = _testCluster.Session;
            Session.Execute(string.Format(TestUtils.CreateKeyspaceSimpleFormat, Keyspace, 1));
            Session.Execute(string.Format(TestUtils.CreateTableSimpleFormat, Table));
        }
Esempio n. 8
0
 public void Should_Add_And_Query_Newly_Bootstrapped_Node()
 {
     _testCluster = TestClusterManager.CreateNew();
     using (var cluster = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint).Build())
     {
         var session = cluster.Connect();
         Assert.AreEqual(1, cluster.AllHosts().Count);
         _testCluster.BootstrapNode(2);
         var queried = false;
         Trace.TraceInformation("Node bootstrapped");
         Thread.Sleep(10000);
         var newNodeAddress = _testCluster.ClusterIpPrefix + 2;
         Assert.True(TestHelper.TryConnect(newNodeAddress), "New node does not accept connections");
         //New node should be part of the metadata
         Assert.AreEqual(2, cluster.AllHosts().Count);
         for (var i = 0; i < 10; i++)
         {
             var rs = session.Execute("SELECT key FROM system.local");
             if (rs.Info.QueriedHost.Address.ToString() == newNodeAddress)
             {
                 queried = true;
                 break;
             }
         }
         Assert.True(queried, "Newly bootstrapped node should be queried");
     }
 }
Esempio n. 9
0
        public async Task Should_Remove_Decommissioned_Node(bool asyncConnect)
        {
            _testCluster = TestClusterManager.CreateNew(2);
            var cluster = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint).Build();

            await Connect(cluster, asyncConnect, session =>
            {
                Assert.AreEqual(2, cluster.AllHosts().Count);
                _testCluster.DecommissionNode(2);
                Trace.TraceInformation("Node decommissioned");
                Thread.Sleep(10000);
                var decommisionedNode = _testCluster.ClusterIpPrefix + 2;
                Assert.False(TestUtils.IsNodeReachable(IPAddress.Parse(decommisionedNode)));
                //New node should be part of the metadata
                Assert.AreEqual(1, cluster.AllHosts().Count);
                var queried = false;
                for (var i = 0; i < 10; i++)
                {
                    var rs = session.Execute("SELECT key FROM system.local");
                    if (rs.Info.QueriedHost.Address.ToString() == decommisionedNode)
                    {
                        queried = true;
                        break;
                    }
                }
                Assert.False(queried, "Removed node should be queried");
            }).ConfigureAwait(false);
        }
Esempio n. 10
0
        public void Should_Not_Leak_Connections_Test()
        {
            var testCluster   = TestClusterManager.CreateNew();
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(1).SetConnectTimeoutMillis(1);
            var builder       = Cluster.Builder()
                                .AddContactPoint(testCluster.InitialContactPoint)
                                .WithSocketOptions(socketOptions);

            testCluster.PauseNode(1);
            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);
                testCluster.ResumeNode(1);
                Assert.Less(GC.GetTotalMemory(true) / initialLength, 1.3M,
                            "Should not exceed a 30% (1.3) more than was previously allocated");
            }
        }
        public void TokenAware_TargetWrongPartition_HopsOccur()
        {
            // Setup
            PolicyTestTools policyTestTools = new PolicyTestTools();
            ITestCluster    testCluster     = TestClusterManager.CreateNew(3);

            testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
            testCluster.InitClient();

            var session = testCluster.Session;

            policyTestTools.TableName = TestUtils.GetUniqueTableName();
            policyTestTools.CreateSchema(session, 1);
            var traces = new List <QueryTrace>();

            for (var i = 1; i < 10; i++)
            {
                //The partition key is wrongly calculated
                var statement = new SimpleStatement(String.Format("INSERT INTO " + policyTestTools.TableName + " (k, i) VALUES ({0}, {0})", i))
                                .SetRoutingKey(new RoutingKey()
                {
                    RawRoutingKey = new byte[] { 0, 0, 0, 0 }
                })
                                .EnableTracing();
                var rs = session.Execute(statement);
                traces.Add(rs.Info.QueryTrace);
            }
            //Check that there were hops
            var hopsPerQuery = traces.Select(t => t.Events.Any(e => e.Source.ToString() == t.Coordinator.ToString()));

            Assert.True(hopsPerQuery.Any(v => v));
        }
Esempio n. 12
0
        public void ExceptionsOnPartialTrust()
        {
            var testCluster = TestClusterManager.CreateNew();
            var appDomain   = CreatePartialTrustDomain();

            appDomain.DoCallBack(() => PreserveStackTraceOnConnectAndAssert(testCluster.InitialContactPoint));
        }
Esempio n. 13
0
        public async Task Should_Add_And_Query_Newly_Bootstrapped_Node(bool asyncConnect)
        {
            _testCluster = TestClusterManager.CreateNew();
            var cluster = Cluster.Builder().AddContactPoint(_testCluster.InitialContactPoint).Build();

            await Connect(cluster, asyncConnect, session =>
            {
                Assert.AreEqual(1, cluster.AllHosts().Count);
                _testCluster.BootstrapNode(2);
                var queried = false;
                Trace.TraceInformation("Node bootstrapped");
                Thread.Sleep(10000);
                var newNodeAddress = _testCluster.ClusterIpPrefix + 2;
                Assert.True(TestUtils.IsNodeReachable(IPAddress.Parse(newNodeAddress)));
                //New node should be part of the metadata
                Assert.AreEqual(2, cluster.AllHosts().Count);
                for (var i = 0; i < 10; i++)
                {
                    var rs = session.Execute("SELECT key FROM system.local");
                    if (rs.Info.QueriedHost.Address.ToString() == newNodeAddress)
                    {
                        queried = true;
                        break;
                    }
                }
                Assert.True(queried, "Newly bootstrapped node should be queried");
            });
        }
        public void TokenAware_BindInt_NoHops()
        {
            // Setup
            PolicyTestTools policyTestTools = new PolicyTestTools();
            ITestCluster    testCluster     = TestClusterManager.CreateNew(3);

            testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
            testCluster.InitClient();

            // Test
            var session = testCluster.Session;

            policyTestTools.TableName = TestUtils.GetUniqueTableName();
            policyTestTools.CreateSchema(session, 1);
            var traces = new List <QueryTrace>();
            var pstmt  = session.Prepare("INSERT INTO " + policyTestTools.TableName + " (k, i) VALUES (?, ?)");

            for (var i = (int)short.MinValue; i < short.MinValue + 40; i++)
            {
                var statement = pstmt
                                .Bind(i, i)
                                .EnableTracing();
                var rs = session.Execute(statement);
                traces.Add(rs.Info.QueryTrace);
            }
            //Check that there weren't any hops
            foreach (var t in traces)
            {
                //The coordinator must be the only one executing the query
                Assert.True(t.Events.All(e => e.Source.ToString() == t.Coordinator.ToString()), "There were trace events from another host for coordinator " + t.Coordinator);
            }
        }
        public void TokenAware_Prepared_Composite_NoHops()
        {
            // Setup
            PolicyTestTools policyTestTools = new PolicyTestTools();
            ITestCluster    testCluster     = TestClusterManager.CreateNew(3);

            testCluster.Builder = Cluster.Builder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
            testCluster.InitClient();

            // Test
            var session = testCluster.Session;

            policyTestTools.CreateSchema(session);
            policyTestTools.TableName = TestUtils.GetUniqueTableName();
            session.Execute(String.Format("CREATE TABLE {0} (k1 text, k2 int, i int, PRIMARY KEY ((k1, k2)))", policyTestTools.TableName));
            Thread.Sleep(1000);
            var ps     = session.Prepare(String.Format("INSERT INTO {0} (k1, k2, i) VALUES (?, ?, ?)", policyTestTools.TableName));
            var traces = new List <QueryTrace>();

            for (var i = 0; i < 10; i++)
            {
                var statement = ps.Bind(i.ToString(), i, i).EnableTracing();
                //Routing key is calculated by the driver
                Assert.NotNull(statement.RoutingKey);
                var rs = session.Execute(statement);
                traces.Add(rs.Info.QueryTrace);
            }
            //Check that there weren't any hops
            foreach (var t in traces)
            {
                //The coordinator must be the only one executing the query
                Assert.True(t.Events.All(e => e.Source.ToString() == t.Coordinator.ToString()), "There were trace events from another host for coordinator " + t.Coordinator);
            }
        }
Esempio n. 16
0
        private ITestCluster GetTestCcmClusterForAuthTests()
        {
            var testCluster = TestClusterManager.CreateNew(1, null, false);

            testCluster.UpdateConfig("authenticator: PasswordAuthenticator");
            testCluster.Start(new[] { "-Dcassandra.superuser_setup_delay_ms=0" });
            return(testCluster);
        }
        private ITestCluster GetTestCcmClusterForAuthTests()
        {
            var testCluster = TestClusterManager.CreateNew(1, null, false);

            testCluster.UpdateConfig("authenticator: PasswordAuthenticator");
            testCluster.Start();
            return(testCluster);
        }
Esempio n. 18
0
 public void OneTimeSetUp()
 {
     _testCluster = TestClusterManager.CreateNew(1, new TestClusterOptions
     {
         Workloads = new[] { "graph", "spark" }
     });
     Trace.TraceInformation("Waiting additional time for test Cluster to be ready");
     Thread.Sleep(20000);
 }
 private ITestCluster GetTestCcmClusterForAuthTests()
 {
     return
         (TestClusterManager.CreateNew(1, new TestClusterOptions
     {
         DseYaml = new[] { "authentication_options.default_scheme: internal", "authentication_options.enabled: true" },
         CassandraYaml = new[] { "authenticator: com.datastax.bdp.cassandra.auth.DseAuthenticator" },
         JvmArgs = new[] { "-Dcassandra.superuser_setup_delay_ms=0" }
     }));
 }
Esempio n. 20
0
 protected virtual void TestFixtureSetUp()
 {
     TestCluster = TestClusterManager.CreateNew(AmountOfNodes);
     if (CreateSession)
     {
         Cluster = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint).Build();
         Session = (Session)Cluster.Connect();
         Session.CreateKeyspace(KeyspaceName, null, false);
         Session.ChangeKeyspace(KeyspaceName);
     }
 }
Esempio n. 21
0
 public void OneTimeSetUp()
 {
     TestClusterManager.CreateNew(1, new TestClusterOptions {
         Workloads = new[] { "graph" }
     });
     CreateClassicGraph(TestClusterManager.InitialContactPoint, GraphTests.GraphName);
     _cluster = ClusterBuilder()
                .AddContactPoint(TestClusterManager.InitialContactPoint)
                .WithGraphOptions(new GraphOptions().SetName(GraphTests.GraphName))
                .Build();
     _session = _cluster.Connect();
 }
Esempio n. 22
0
        private ITestCluster GetTestCcmClusterForAuthTests()
        {
            var testCluster = TestClusterManager.CreateNew(1, null, false);

            testCluster.UpdateConfig("authenticator:com.datastax.bdp.cassandra.auth.DseAuthenticator");
            testCluster.UpdateDseConfig(
                "authentication_options.enabled:true",
                "authentication_options.default_scheme:internal",
                "authentication_options.transitional_mode:normal");
            testCluster.Start(new[] { "-Dcassandra.superuser_setup_delay_ms=0" });
            return(testCluster);
        }
Esempio n. 23
0
        public void Reconnection_Attempted_Multiple_Times()
        {
            var testCluster = TestClusterManager.CreateNew();

            using (var cluster = Cluster.Builder()
                                 .AddContactPoint(testCluster.InitialContactPoint)
                                 .WithPoolingOptions(
                       new PoolingOptions()
                       .SetCoreConnectionsPerHost(HostDistance.Local, 2)
                       .SetHeartBeatInterval(0))
                                 .WithReconnectionPolicy(new ConstantReconnectionPolicy(2000))
                                 .Build())
            {
                var session = (Session)cluster.Connect();
                TestHelper.Invoke(() => session.Execute("SELECT * FROM system.local"), 10);
                //Another session to have multiple pools
                var dummySession = cluster.Connect();
                TestHelper.Invoke(() => dummySession.Execute("SELECT * FROM system.local"), 10);
                var host        = cluster.AllHosts().First();
                var upCounter   = 0;
                var downCounter = 0;
                cluster.Metadata.HostsEvent += (sender, e) =>
                {
                    if (e.What == HostsEventArgs.Kind.Up)
                    {
                        Interlocked.Increment(ref upCounter);
                        return;
                    }
                    Interlocked.Increment(ref downCounter);
                };
                Assert.True(host.IsUp);
                Trace.TraceInformation("Stopping node");
                testCluster.Stop(1);
                // Make sure the node is considered down
                Assert.Throws <NoHostAvailableException>(() => session.Execute("SELECT * FROM system.local"));
                Assert.False(host.IsUp);
                Assert.AreEqual(1, Volatile.Read(ref downCounter));
                Assert.AreEqual(0, Volatile.Read(ref upCounter));
                Trace.TraceInformation("Waiting for 15 seconds");
                Thread.Sleep(15000);
                Assert.False(host.IsUp);
                Trace.TraceInformation("Restarting node");
                testCluster.Start(1);
                Trace.TraceInformation("Waiting up to 20s");
                var attempts = TestHelper.WaitUntil(() => host.IsUp, 1000, 20);
                Trace.TraceInformation("Waited {0}s", attempts);
                Assert.True(host.IsUp);
                Assert.AreEqual(1, Volatile.Read(ref downCounter));
                Assert.AreEqual(1, Volatile.Read(ref upCounter));
            }
        }
Esempio n. 24
0
 protected virtual void TestFixtureSetUp()
 {
     TestCluster = TestClusterManager.CreateNew(AmountOfNodes);
     if (CreateSession)
     {
         Cluster = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint)
                   .WithQueryTimeout(60000)
                   .WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(30000))
                   .Build();
         Session = (Session)Cluster.Connect();
         Session.CreateKeyspace(KeyspaceName, null, false);
         Session.ChangeKeyspace(KeyspaceName);
     }
 }
        public void TwoSessionsConnectedToSameDcUseSeparatePolicyInstances()
        {
            var builder     = Cluster.Builder();
            var testCluster = TestClusterManager.CreateNew();

            using (var cluster1 = builder.WithConnectionString(String.Format("Contact Points={0}1", testCluster.ClusterIpPrefix)).Build())
                using (var cluster2 = builder.WithConnectionString(String.Format("Contact Points={0}2", testCluster.ClusterIpPrefix)).Build())
                {
                    var session1 = (Session)cluster1.Connect();
                    var session2 = (Session)cluster2.Connect();
                    Assert.AreNotSame(session1.Policies.LoadBalancingPolicy, session2.Policies.LoadBalancingPolicy, "Load balancing policy instances should be different");
                    Assert.AreNotSame(session1.Policies.ReconnectionPolicy, session2.Policies.ReconnectionPolicy, "Reconnection policy instances should be different");
                    Assert.AreNotSame(session1.Policies.RetryPolicy, session2.Policies.RetryPolicy, "Retry policy instances should be different");
                }
        }
Esempio n. 26
0
        public void Cluster_Connect_Should_Initialize_Loadbalancing_With_ControlConnection_Address_Set()
        {
            _testCluster = TestClusterManager.CreateNew(2);
            var lbp     = new TestLoadBalancingPolicy();
            var builder = Cluster.Builder()
                          .AddContactPoint(_testCluster.InitialContactPoint)
                          .WithLoadBalancingPolicy(lbp);

            using (var cluster = builder.Build())
            {
                cluster.Connect();
                Assert.NotNull(lbp.ControlConnectionHost);
                Assert.AreEqual(IPAddress.Parse(_testCluster.InitialContactPoint),
                                lbp.ControlConnectionHost.Address.Address);
            }
        }
Esempio n. 27
0
        public Task Cluster_Connect_Should_Initialize_Loadbalancing_With_ControlConnection_Address_Set(bool asyncConnect)
        {
            _testCluster = TestClusterManager.CreateNew(2);
            var lbp     = new TestLoadBalancingPolicy();
            var cluster = Cluster.Builder()
                          .AddContactPoint(_testCluster.InitialContactPoint)
                          .WithLoadBalancingPolicy(lbp)
                          .Build();

            return(Connect(cluster, asyncConnect, session =>
            {
                Assert.NotNull(lbp.ControlConnectionHost);
                Assert.AreEqual(IPAddress.Parse(_testCluster.InitialContactPoint),
                                lbp.ControlConnectionHost.Address.Address);
            }));
        }
Esempio n. 28
0
        public virtual void OneTimeSetUp()
        {
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;

            if (_reuse && _reusableInstance != null &&
                ReferenceEquals(_reusableInstance, TestClusterManager.LastInstance) &&
                ((Options != null && Options.Equals(TestClusterManager.LastOptions)) || (Options == null && TestClusterManager.LastOptions == null)) &&
                AmountOfNodes == TestClusterManager.LastAmountOfNodes)
            {
                Trace.WriteLine("Reusing ccm instance");
                TestCluster = _reusableInstance;
            }
            else
            {
                TestCluster = TestClusterManager.CreateNew(AmountOfNodes, Options);
                if (_reuse)
                {
                    _reusableInstance = TestCluster;
                }
                else
                {
                    _reusableInstance = null;
                }
            }
            if (CreateSession)
            {
                Cluster = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint)
                          .WithQueryTimeout(60000)
                          .WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(30000))
                          .Build();
                Session = (Session)Cluster.Connect();
                Session.CreateKeyspace(KeyspaceName, null, false);
                Session.ChangeKeyspace(KeyspaceName);
                if (SetupQueries != null)
                {
                    foreach (var query in SetupQueries)
                    {
                        Session.Execute(query);
                    }
                }
            }
        }
Esempio n. 29
0
        public async Task Cluster_Should_Honor_MaxProtocolVersion_Set(bool asyncConnect)
        {
            _testCluster = TestClusterManager.CreateNew(2);

            // Default MaxProtocolVersion
            var clusterDefault = Cluster.Builder()
                                 .AddContactPoint(_testCluster.InitialContactPoint)
                                 .Build();

            Assert.AreEqual(Cluster.MaxProtocolVersion, clusterDefault.Configuration.ProtocolOptions.MaxProtocolVersion);

            // MaxProtocolVersion set
            var clusterMax = Cluster.Builder()
                             .AddContactPoint(_testCluster.InitialContactPoint)
                             .WithMaxProtocolVersion(3)
                             .Build();

            Assert.AreEqual(3, clusterMax.Configuration.ProtocolOptions.MaxProtocolVersion);
            await Connect(clusterMax, asyncConnect, session =>
            {
                if (CassandraVersion < Version.Parse("2.1"))
                {
                    Assert.AreEqual(2, session.BinaryProtocolVersion);
                }
                else
                {
                    Assert.AreEqual(3, session.BinaryProtocolVersion);
                }
            }).ConfigureAwait(false);

            // Arbitary MaxProtocolVersion set, will negotiate down upon connect
            var clusterNegotiate = Cluster.Builder()
                                   .AddContactPoint(_testCluster.InitialContactPoint)
                                   .WithMaxProtocolVersion(10)
                                   .Build();

            Assert.AreEqual(10, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion);
            await Connect(clusterNegotiate, asyncConnect, session =>
            {
                Assert.LessOrEqual(4, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion);
            }).ConfigureAwait(false);

            // ProtocolVersion 0 does not exist
            Assert.Throws <ArgumentException>(
                () => Cluster.Builder().AddContactPoint("127.0.0.1").WithMaxProtocolVersion((byte)0));
        }
Esempio n. 30
0
        public void TokenAware_VNodes_Test()
        {
            var testCluster = TestClusterManager.CreateNew(3, new TestClusterOptions {
                UseVNodes = true
            });
            var cluster = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).Build();

            try
            {
                var session = cluster.Connect();
                Assert.AreEqual(256, cluster.AllHosts().First().Tokens.Count());
                session.Execute("CREATE KEYSPACE ks1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
                Thread.Sleep(3000);
                session.ChangeKeyspace("ks1");
                session.Execute("CREATE TABLE tbl1 (id uuid primary key)");
                Thread.Sleep(3000);
                var ps     = session.Prepare("INSERT INTO tbl1 (id) VALUES (?)");
                var traces = new List <QueryTrace>();
                for (var i = 0; i < 10; i++)
                {
                    var id    = Guid.NewGuid();
                    var bound = ps
                                .Bind(id)
                                .SetRoutingKey(new RoutingKey()
                    {
                        RawRoutingKey = TypeCodec.GuidShuffle(id.ToByteArray())
                    })
                                .EnableTracing();
                    var rs = session.Execute(bound);
                    traces.Add(rs.Info.QueryTrace);
                }
                //Check that there weren't any hops
                foreach (var t in traces)
                {
                    //The coordinator must be the only one executing the query
                    Assert.True(t.Events.All(e => e.Source.ToString() == t.Coordinator.ToString()), "There were trace events from another host for coordinator " + t.Coordinator);
                }
            }
            finally
            {
                cluster.Dispose();
                testCluster.Remove();
            }
        }