Esempio n. 1
0
        public void Shutdown()
        {
            lock (_lock)
            {
                _recoveryService.SafeDispose();
                _recoveryService = null;

                _instrumentation.SafeDispose();
                _instrumentation = null;

                _logger.SafeDispose();
                _logger = null;

                _config = null;
            }
        }
Esempio n. 2
0
        // https://www.codeproject.com/Articles/758803/DotNet-Programming-using-Cassandra
        public static ICluster GetCluster(int myPort, string[] myClusters)
        {
            CassandraSharpConfig config        = new CassandraSharpConfig();
            ClusterConfig        clusterConfig = new ClusterConfig();
            TransportConfig      transConfig   = new TransportConfig();

            clusterConfig.Name      = "Test Cluster";
            transConfig.Port        = myPort;
            clusterConfig.Transport = new TransportConfig();

            EndpointsConfig endPointConfig = new EndpointsConfig();

            endPointConfig.Servers = myClusters;
            // endPointConfig.Snitch = SnitchType.Simple;
            // endPointConfig.Strategy = EndpointStrategy.Nearest;

            //BehaviorConfig behaveConfig = new BehaviorConfig();
            //behaveConfig.KeySpace = ConfigEntries.DefaultDatabase;
            //if (!String.IsNullOrWhiteSpace(ConfigEntries.UserName)) behaveConfig.User = ConfigEntries.UserName;
            //if (!String.IsNullOrWhiteSpace(ConfigEntries.Password)) behaveConfig.Password = ConfigEntries.Password;
            //behaveConfig.ReadConsistencyLevel = Apache.Cassandra.ConsistencyLevel.ONE;
            //behaveConfig.WriteConsistencyLevel = Apache.Cassandra.ConsistencyLevel.ONE;

            clusterConfig.Transport = transConfig;
            clusterConfig.Endpoints = endPointConfig;


            // KeyspaceConfig ksc = new KeyspaceConfig();
            // ksc.Name = "";

            // clusterConfig.DefaultKeyspace = ksc;



            config.Clusters = new ClusterConfig[] { clusterConfig };

            //We need to ensure that the connection is not initialized before configuring...
            ClusterManager.Shutdown();

            ClusterManager.Configure(config);

            ICluster cluster = ClusterManager.GetCluster("Test Cluster");

            return(cluster);
        }
Esempio n. 3
0
        public void Configure(CassandraSharpConfig config)
        {
            config.CheckArgumentNotNull("config");

            lock (_lock)
            {
                if (null != _config)
                {
                    throw new InvalidOperationException("ClusterManager is already initialized");
                }

                _logger = ServiceActivator <Logger.Factory> .Create <ILogger>(config.Logger.Type, config.Logger);

                _recoveryService = ServiceActivator <Recovery.Factory> .Create <IRecoveryService>(config.Recovery.Type, config.Recovery, _logger);

                _instrumentation = ServiceActivator <Instrumentation.Factory> .Create <IInstrumentation>(config.Instrumentation.Type, config.Instrumentation);

                _config = config;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// return true for Configure success
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public bool Configure(CassandraSharpConfig config)
        {
            if (config == null)
            {
                return(false);
            }

            if (null != _config)
            {
                return(true);
            }

            _logger = ServiceActivator <Logger.Factory> .Create <ILogger>(config.Logger.Type, config.Logger);

            _recoveryService = ServiceActivator <Recovery.Factory> .Create <IRecoveryService>(config.Recovery.Type, config.Recovery, _logger);

            _instrumentation = ServiceActivator <Instrumentation.Factory> .Create <IInstrumentation>(config.Instrumentation.Type, config.Instrumentation);

            _config = config;
            return(true);
        }
Esempio n. 5
0
        public override void Open(string hostname)
        {
            //run Write Performance Test using cassandra-sharp driver
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig();

            cassandraSharpConfig.Instrumentation      = new InstrumentationConfig();
            cassandraSharpConfig.Instrumentation.Type = typeof(PerformanceInstrumentation).AssemblyQualifiedName;
            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { hostname }
                },
            };

            _cluster = ClusterManager.GetCluster(clusterConfig);

            _cmd = _cluster.CreateOrdinalCommand();
        }
Esempio n. 6
0
        public void TestLoadConfig()
        {
            CassandraSharpConfig cassandraSharpConfig = (CassandraSharpConfig)ConfigurationManager.GetSection("CassandraSharp");

            Assert.IsNotNull(cassandraSharpConfig);
            Assert.AreEqual("TestClient.Logger4Log4Net, TestClient", cassandraSharpConfig.Logger.Type);
            Assert.AreEqual(5, cassandraSharpConfig.Clusters.Length);
            Assert.IsNotNull(cassandraSharpConfig.Clusters[1]);
//            Assert.IsNotNull(cassandraSharpConfig.Clusters[1].BehaviorConfig);
            Assert.IsNotNull(cassandraSharpConfig.Clusters[1].Endpoints);
            Assert.IsNotNull(cassandraSharpConfig.Clusters[1].Transport);
            Assert.AreEqual("CustomEndpointStrategy", cassandraSharpConfig.Clusters[1].Name);
            //Assert.AreEqual(3, cassandraSharpConfig.Clusters[1].BehaviorConfig.MaxRetries);
            //Assert.AreEqual("TestKeyspace", cassandraSharpConfig.Clusters[1].BehaviorConfig.KeySpace);
            //Assert.AreEqual(ConsistencyLevel.ONE, cassandraSharpConfig.Clusters[1].BehaviorConfig.DefaultReadCL);
            //Assert.AreEqual(ConsistencyLevel.QUORUM, cassandraSharpConfig.Clusters[1].BehaviorConfig.DefaultWriteCL);
            //Assert.AreEqual(null, cassandraSharpConfig.Clusters[1].BehaviorConfig.DefaultTTL);

            Assert.IsNull(cassandraSharpConfig.Clusters[0].DefaultKeyspace);
            Assert.IsNotNull(cassandraSharpConfig.Clusters[4].DefaultKeyspace);
            Assert.AreEqual("Test", cassandraSharpConfig.Clusters[4].DefaultKeyspace.Name);
            Assert.AreEqual("2", cassandraSharpConfig.Clusters[4].DefaultKeyspace.Replication.Options["replication_factor"]);
            Assert.AreEqual("SimpleStrategy", cassandraSharpConfig.Clusters[4].DefaultKeyspace.Replication.Options["class"]);
        }
Esempio n. 7
0
        public void RecoveryTest()
        {
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig
            {
                Logger = new LoggerConfig {
                    Type = typeof(ResilienceLogger).AssemblyQualifiedName
                },
                Recovery = new RecoveryConfig {
                    Interval = 2
                }
            };

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { "cassandra1" },
                },
                Transport = new TransportConfig
                {
                    Port           = 666,
                    ReceiveTimeout = 10 * 1000,
                }
            };

            DisconnectingProxy proxy = new DisconnectingProxy(666, 9042);

            proxy.Start();

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                ICqlCommand cmd = cluster.CreatePocoCommand();

                const string dropFoo = "drop keyspace data";
                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
                catch
                {
                }

                const string createFoo = "CREATE KEYSPACE data WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                cmd.Execute(createFoo).AsFuture().Wait();

                const string createBar = "CREATE TABLE data.test (time text PRIMARY KEY)";
                cmd.Execute(createBar).AsFuture().Wait();

                proxy.EnableKiller();

                for (int i = 0; i < 100000; ++i)
                {
                    int attempt = 0;
                    while (true)
                    {
                        var    now    = DateTime.Now;
                        string insert = String.Format("insert into data.test(time) values ('{0}');", now);
                        Console.WriteLine("{0}.{1}) {2}", i, ++attempt, insert);

                        try
                        {
                            cmd.Execute(insert).AsFuture().Wait();
                            break;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed with error {0}", ex.Message);
                            Thread.Sleep(1000);
                        }
                    }
                }

                Console.WriteLine("Stress test done");

                ClusterManager.Shutdown();
            }

            proxy.Stop();
        }
Esempio n. 8
0
        public void TestNull()
        {
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig();

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { CQLBinaryProtocol.DefaultKeyspaceTest.CassandraServerIp }
                }
            };

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                var cmd = cluster.CreatePropertyBagCommand();

                const string dropFoo = "drop keyspace Tests";

                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
                catch
                {
                }

                const string createFoo = "CREATE KEYSPACE Tests WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                Console.WriteLine("============================================================");
                Console.WriteLine(createFoo);
                Console.WriteLine("============================================================");

                cmd.Execute(createFoo).AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                const string createBar = @"CREATE TABLE Tests.AllTypes (a int, b int, primary key (a))";
                Console.WriteLine("============================================================");
                Console.WriteLine(createBar);
                Console.WriteLine("============================================================");
                cmd.Execute(createBar).AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                //const string useBar = @"use Tests";
                //Console.WriteLine("============================================================");
                //Console.WriteLine(useBar);
                //Console.WriteLine("============================================================");
                //cmd.Execute(useBar).AsFuture().Wait();
                //Console.WriteLine();
                //Console.WriteLine();

                const string insertBatch = @"insert into Tests.AllTypes (a, b) values (?, ?)";
                var          prepared    = cmd.Prepare(insertBatch);

                PropertyBag insertBag = new PropertyBag();
                insertBag["a"] = 1;
                insertBag["b"] = null;

                prepared.Execute(insertBag).AsFuture().Wait();

                const string selectAll = "select * from Tests.AllTypes";
                var          res       = cmd.Execute(selectAll).AsFuture();
                Assert.IsTrue(1 == res.Result.Count);
                PropertyBag selectBag = res.Result.Single();
                Assert.IsTrue(selectBag.Keys.Contains("a"));
                Assert.IsTrue(1 == (int)selectBag["a"]);
                Assert.IsTrue(null == selectBag["b"]);
                // to test case in-sensistive
                Assert.IsTrue(1 == (int)selectBag["A"]);
                Assert.IsTrue(null == selectBag["B"]);
            }
        }
        public void StreamStarvationMultiThread()
        {
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig
            {
                Logger = new LoggerConfig {
                    Type = typeof(ConsoleDebugLogger).AssemblyQualifiedName
                }
            };

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { "cassandra1" }
                },
            };

            ICluster    cluster = ClusterManager.GetCluster(clusterConfig);
            ICqlCommand cmd     = cluster.CreatePocoCommand();

            const string dropKeySpace = "drop keyspace Tests";

            try
            {
                cmd.Execute(dropKeySpace).AsFuture().Wait();
            }
            catch
            {
            }

            const string createKeySpace = "CREATE KEYSPACE Tests WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";

            Console.WriteLine("============================================================");
            Console.WriteLine(createKeySpace);
            Console.WriteLine("============================================================");

            cmd.Execute(createKeySpace).AsFuture().Wait();
            Console.WriteLine();
            Console.WriteLine();

            const string createFoo = "CREATE TABLE Tests.foo (strid varchar,bar varchar,intid int,PRIMARY KEY (strid))";

            Console.WriteLine("============================================================");
            Console.WriteLine(createFoo);
            Console.WriteLine("============================================================");
            cmd.Execute(createFoo).AsFuture().Wait();
            Console.WriteLine();
            Console.WriteLine();

            const string insertPerf = "UPDATE Tests.foo SET bar = ?, intid = ? WHERE strid = ?";

            Console.WriteLine("============================================================");
            Console.WriteLine(" Cassandra-Sharp Driver reproducing stream starvation ");
            Console.WriteLine("============================================================");

            using (var prepared = cmd.WithConsistencyLevel(ConsistencyLevel.ONE).Prepare(insertPerf))
            {
                Thread[] failsThreads = new Thread[NUM_THREADS];

                for (int i = 0; i < NUM_THREADS; i++)
                {
                    failsThreads[i] = new Thread(() => FailingThread(prepared));
                    failsThreads[i].Start();
                    //Thread.Sleep(5000);
                }

                foreach (Thread thread in failsThreads)
                {
                    thread.Join();
                }
            }

            ClusterManager.Shutdown();
        }
Esempio n. 10
0
        public void PacketSizeTest()
        {
            long time1423;
            long time1424;

            //run Write Performance Test using cassandra-sharp driver
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig();

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { "localhost" }
                },
            };

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                ICqlCommand cmd = cluster.CreatePocoCommand();

                const string dropFoo = "drop keyspace Tests";
                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
// ReSharper disable EmptyGeneralCatchClause
                catch
// ReSharper restore EmptyGeneralCatchClause
                {
                }

                const string createFoo = "CREATE KEYSPACE Tests WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                Console.WriteLine("============================================================");
                Console.WriteLine(createFoo);
                Console.WriteLine("============================================================");

                var resCount = cmd.Execute(createFoo).AsFuture();
                resCount.Wait();
                Console.WriteLine();
                Console.WriteLine();

                const string createBar = "CREATE TABLE Tests.tbl ( x varchar primary key, y varchar )";
                Console.WriteLine("============================================================");
                Console.WriteLine(createBar);
                Console.WriteLine("============================================================");
                resCount = cmd.Execute(createBar).AsFuture();
                resCount.Wait();
                Console.WriteLine();
                Console.WriteLine();

                using (var preparedQuery = cmd.Prepare("insert into Tests.tbl (x, y) values (?, ?)"))
                {
                    time1423 = InsertData(new string('x', 1423), preparedQuery);
                    Console.WriteLine();

                    time1424 = InsertData(new string('x', 1424), preparedQuery);
                    Console.WriteLine();
                }

                Console.WriteLine("============================================================");
                Console.WriteLine(dropFoo);
                Console.WriteLine("============================================================");

                resCount = cmd.Execute(dropFoo).AsFuture();
                resCount.Wait();
            }

            ClusterManager.Shutdown();

            long   delta   = Math.Abs(time1424 - time1423);
            long   min     = Math.Max(time1423, time1424);
            double percent = delta / (double)min;

            Assert.IsTrue(percent < 1.0);
        }
Esempio n. 11
0
        private static void Run(IStatementReader statementReader)
        {
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig
            {
                Logger = new LoggerConfig {
                    Type = typeof(ConsoleDebugLogger).AssemblyQualifiedName
                },
                Instrumentation = new InstrumentationConfig {
                    Type = typeof(ConsoleInstrumentation).AssemblyQualifiedName
                }
            };

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Transport = new TransportConfig
                {
                    User     = _cliArgs.User,
                    Password = _cliArgs.Password
                },
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { _cliArgs.Hostname },
                }
            };

            if (!_cliArgs.Discovery)
            {
                clusterConfig.Endpoints.Discovery = new DiscoveryConfig {
                    Type = "Null"
                };
            }

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                CommandContext.Cluster = cluster;

                if (_cliArgs.CheckConnection)
                {
                    Console.WriteLine("Connecting to {0}:{1}...", _cliArgs.Hostname, _cliArgs.Port);
                    const string checkStatement = "select cluster_name, data_center, rack, release_version from system.local";
                    new Exec {
                        Statement = checkStatement
                    }.Execute();
                    if (CommandContext.LastCommandFailed)
                    {
                        return;
                    }

                    Console.WriteLine();
                    Console.WriteLine("Querying ring state...");
                    const string peersStatement = "select rpc_address,tokens,release_version from system.peers";
                    new Exec {
                        Statement = peersStatement
                    }.Execute();
                    Console.WriteLine();

                    if (CommandContext.LastCommandFailed)
                    {
                        return;
                    }
                }

                if (!_cliArgs.NoHelp)
                {
                    new Exec {
                        Statement = "!help"
                    }.Execute();
                }

                foreach (string statement in statementReader.Read())
                {
                    new Exec {
                        Statement = statement
                    }.Execute();
                    if (CommandContext.Exit)
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 12
0
        private void BinaryProtocolRunWritePerformanceParallel(string transportType)
        {
            //run Write Performance Test using cassandra-sharp driver
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig();

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { "localhost" }
                },
                Transport = new TransportConfig
                {
                    Type = transportType
                }
            };

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                ICqlCommand cmd = cluster.CreatePocoCommand();

                const string dropFoo = "drop keyspace Endurance";
                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
                catch
                {
                }

                const string createFoo = "CREATE KEYSPACE Endurance WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                Console.WriteLine("============================================================");
                Console.WriteLine(createFoo);
                Console.WriteLine("============================================================");

                var resCount = cmd.Execute(createFoo);
                resCount.AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                const string createBar = "CREATE TABLE Endurance.stresstest (strid varchar,intid int,PRIMARY KEY (strid))";
                Console.WriteLine("============================================================");
                Console.WriteLine(createBar);
                Console.WriteLine("============================================================");
                resCount = cmd.Execute(createBar);
                resCount.AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                const string insertPerf = "UPDATE Endurance.stresstest SET intid = ? WHERE strid = ?";
                Console.WriteLine("============================================================");
                Console.WriteLine(" Cassandra-Sharp Driver write performance test single thread ");
                Console.WriteLine("============================================================");
                var prepared = cmd.Prepare(insertPerf);

                var timer = Stopwatch.StartNew();

                int running = 0;
                for (int i = 0; i < 100000; i++)
                {
                    if (0 == i % 1000)
                    {
                        Console.WriteLine("Sent {0} requests - pending requests {1}", i, Interlocked.CompareExchange(ref running, 0, 0));
                    }

                    Interlocked.Increment(ref running);
                    prepared.Execute(new { intid = i, strid = i.ToString("X") }).AsFuture().ContinueWith(_ => Interlocked.Decrement(ref running));
                }

                while (0 != Interlocked.CompareExchange(ref running, 0, 0))
                {
                    Console.WriteLine("{0} requests still running", running);
                    Thread.Sleep(1 * 1000);
                }
                timer.Stop();
                Console.WriteLine("Endurance ran in {0} ms", timer.ElapsedMilliseconds);

                Console.WriteLine("============================================================");
                Console.WriteLine(dropFoo);
                Console.WriteLine("============================================================");

                cmd.Execute(dropFoo).AsFuture().Wait();
            }

            ClusterManager.Shutdown();
        }
Esempio n. 13
0
 public static void Configure(CassandraSharpConfig config)
 {
     EnlightenmentMgr.ClusterManager().Configure(config);
 }
Esempio n. 14
0
        public void TestAllTypes()
        {
            ClusterManager.Shutdown();
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig();

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers = new[] { CQLBinaryProtocol.DefaultKeyspaceTest.CassandraServerIp }
                }
            };

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                ICqlCommand cmd = cluster.CreatePocoCommand();

                const string dropFoo = "drop keyspace Tests";

                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
                catch
                {
                }

                const string createFoo = "CREATE KEYSPACE Tests WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                Console.WriteLine("============================================================");
                Console.WriteLine(createFoo);
                Console.WriteLine("============================================================");

                cmd.Execute(createFoo).AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                // http://www.datastax.com/docs/1.1/references/cql/cql_data_types
                const string createBar = @"CREATE TABLE Tests.AllTypes (cAscii ascii, 
                                                                            cBigint bigint,
                                                                            cBlob blob,
                                                                            cBoolean boolean,
                                                                            
                                                                            cDouble double,
                                                                            cFloat float,
                                                                            cInet inet,
                                                                            cInt int,
                                                                            cText text,
                                                                            cTimestamp timestamp,
                                                                            cTimeuuid timeuuid,
                                                                            cUuid uuid,
                                                                            cVarchar varchar,
                                                                           
                                                                            cList list<int>,
                                                                            cSet set<int>,
                                                                            cMap map<text, int>,
                                                                            cEnum int,
                                                                            
                                                                            cPoint blob,
                                                          PRIMARY KEY (cInt))";
                Console.WriteLine("============================================================");
                Console.WriteLine(createBar);
                Console.WriteLine("============================================================");
                cmd.Execute(createBar).AsFuture().Wait();
                Console.WriteLine();
                Console.WriteLine();

                const string insertBatch = @"insert into Tests.AllTypes (cAscii, cBigint, cBlob, cBoolean, cDouble, cFloat,
                                                                         cInet, cInt, cText, cTimestamp, cTimeuuid, cUuid, cVarchar, cList, cSet, cMap, cEnum, cPoint)
                                             values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                var          prepared    = cmd.Prepare(insertBatch);

                var allTypesInsert = new AllTypes
                {
                    CAscii     = new string('x', 8000),
                    CBigint    = 0x0102030405060708,
                    CBlob      = Enumerable.Repeat((byte)42, 33000).ToArray(),
                    CBoolean   = true,
                    CDouble    = 1234.5678,
                    CFloat     = 234.567f,
                    CInet      = new IPAddress(new byte[] { 0x01, 0x02, 0x03, 0x04 }),
                    CInt       = 42,
                    CText      = new string('x', 100000),
                    CTimestamp = new DateTime(2013, 1, 16, 14, 20, 0),
                    CTimeuuid  = TimedUuid.GenerateTimeBasedGuid(DateTime.Now),
                    CUuid      = Guid.NewGuid(),
                    CVarchar   = new string('x', 5000),
                    CList      = new List <int> {
                        1, 2, 3
                    },
                    CSet = new HashSet <int> {
                        1, 2, 3
                    },
                    CMap = new Dictionary <string, int> {
                        { "one", 1 }, { "two", 2 }, { new string('x', 65510), 3 }
                    },
                    CEnum  = TestEnum.ValueB,
                    CPoint = new Point {
                        X = 1, Y = 3
                    }
                };

                prepared.Execute(allTypesInsert).AsFuture().Wait();

                const string selectAll      = "select * from Tests.AllTypes";
                AllTypes     allTypesSelect = cmd.Execute <AllTypes>(selectAll).AsFuture().Result.Single();

                cmd.Execute(dropFoo).AsFuture().Wait();

                Assert.AreEqual(allTypesInsert.CAscii, allTypesSelect.CAscii);
                Assert.AreEqual(allTypesInsert.CBigint, allTypesSelect.CBigint);
                Assert.AreEqual(allTypesInsert.CBlob, allTypesSelect.CBlob);
                Assert.AreEqual(allTypesInsert.CBoolean, allTypesSelect.CBoolean);
                Assert.AreEqual(allTypesInsert.CDouble, allTypesSelect.CDouble);
                Assert.AreEqual(allTypesInsert.CFloat, allTypesSelect.CFloat);
                Assert.AreEqual(allTypesInsert.CInet, allTypesSelect.CInet);
                Assert.AreEqual(allTypesInsert.CInt, allTypesSelect.CInt);
                Assert.AreEqual(allTypesInsert.CText, allTypesSelect.CText);
                Assert.AreEqual(allTypesInsert.CTimestamp, allTypesSelect.CTimestamp);
                Assert.AreEqual(allTypesInsert.CTimeuuid, allTypesSelect.CTimeuuid);
                Assert.AreEqual(allTypesInsert.CUuid, allTypesSelect.CUuid);
                Assert.AreEqual(allTypesInsert.CVarchar, allTypesSelect.CVarchar);
                Assert.AreEqual(allTypesInsert.CList, allTypesSelect.CList);
                Assert.AreEqual(allTypesInsert.CSet, allTypesSelect.CSet);
                Assert.AreEqual(allTypesInsert.CMap, allTypesSelect.CMap);
                Assert.AreEqual(allTypesInsert.CEnum, allTypesSelect.CEnum);

                Assert.AreEqual(allTypesInsert.CPoint.X, allTypesSelect.CPoint.X);
                Assert.AreEqual(allTypesInsert.CPoint.Y, allTypesSelect.CPoint.Y);
            }

            ClusterManager.Shutdown();
        }
Esempio n. 15
0
        public void ConnectionFailedTest()
        {
            CassandraSharpConfig cassandraSharpConfig = new CassandraSharpConfig
            {
                Logger = new LoggerConfig {
                    Type = typeof(ResilienceLogger).AssemblyQualifiedName
                },
                //Recovery = new RecoveryConfig { Interval = 2 }
            };

            ClusterManager.Configure(cassandraSharpConfig);

            ClusterConfig clusterConfig = new ClusterConfig
            {
                Endpoints = new EndpointsConfig
                {
                    Servers   = new[] { "localhost", CQLBinaryProtocol.DefaultKeyspaceTest.CassandraServerIp },
                    Strategy  = "RoundRobin",
                    Discovery = new DiscoveryConfig()
                    {
                        Type = "Null",
                    },
                },

                Transport = new TransportConfig
                {
                    Port           = 9042,
                    ReceiveTimeout = 10 * 1000,
                }
            };

            DisconnectingProxy proxy = new DisconnectingProxy(9042, 9042);

            proxy.Start();

            using (ICluster cluster = ClusterManager.GetCluster(clusterConfig))
            {
                ICqlCommand cmd = cluster.CreatePocoCommand();

                const string dropFoo = "drop keyspace data";
                try
                {
                    cmd.Execute(dropFoo).AsFuture().Wait();
                }
                catch
                {
                }

                const string createFoo = "CREATE KEYSPACE data WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}";
                cmd.Execute(createFoo).AsFuture().Wait();

                const string createBar = "CREATE TABLE data.test (time text PRIMARY KEY)";
                cmd.Execute(createBar).AsFuture().Wait();

                proxy.EnableKiller();

                var prepared1 = cmd.Prepare("insert into data.test(time) values ('?');");
                var prepared2 = cmd.Prepare("insert into data.test(time) values ('?');");

                for (int i = 0; i < 100; ++i)
                {
                    int attempt = 0;
                    while (true)
                    {
                        var now = DateTime.Now;
                        Console.WriteLine("{0}.{1})", i, ++attempt);
                        try
                        {
                            prepared1.Execute(new { time = now }).AsFuture().Wait();
                            prepared2.Execute(new { time = now }).AsFuture().Wait();
                            break;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed with error {0}", ex.Message);
                            Thread.Sleep(1000);
                            if (attempt >= 3)
                            {
                                break;
                            }
                        }
                    }
                }

                ClusterManager.Shutdown();
            }

            proxy.Stop();
        }