protected async Task <ISession> CreateSessionAsync(
            string creds = "creds-v1.zip", int retries = SharedCloudClusterTest.MaxRetries, Action <Builder> act = null)
        {
            Exception last    = null;
            ICluster  cluster = null;

            for (var i = 0; i < SharedCloudClusterTest.MaxRetries; i++)
            {
                try
                {
                    cluster = CreateTemporaryCluster(creds, act);
                    return(await cluster.ConnectAsync().ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    last = ex;
                    Task.Delay(1000).GetAwaiter().GetResult();
                    if (cluster != null)
                    {
                        cluster.Dispose();
                        cluster = null;
                    }
                }
            }
            throw last;
        }
Example #2
0
        private async ValueTask <ISession> Session()
        {
            if (_session != null && !_session.IsDisposed)
            {
                return(_session);
            }

            _session = await _cluster.ConnectAsync();

            return(_session);
        }
        public async Task <IActionResult> CreateSchema()
        {
            using (var context = await _cassandraCluster.ConnectAsync())
            {
                context.CreateKeyspaceIfNotExists(KEY_SPACE, ReplicationStrategies.CreateSimpleStrategyReplicationProperty(REPLICA_COUNT));
            }

            using (var context = await _cassandraCluster.ConnectAsync(KEY_SPACE))
            {
                await context.ExecuteAsync(new SimpleStatement($@"
CREATE TABLE IF NOT EXISTS {nameof(TestEntity)} (
id uuid PRIMARY KEY, 
name text,
age int,
description text,
address text,
phone text,
email text);"));
            }

            return(Ok());
        }
Example #4
0
        private static SemaphoreSlim threadGate = new SemaphoreSlim(1); // Instantiate a Singleton of the Semaphore with a value of 1. This means that only 1 thread can be granted access at a time

        public async Task <ISession> GetSessionAsync()
        {
            try
            {
                if (session is null || session.IsDisposed)
                {
                    await threadGate.WaitAsync(30000).ConfigureAwait(false);

                    try
                    {
                        if (session is null || session.IsDisposed)
                        {
                            logger.Info(() => "Refreshing cassandra session...");
                            try
                            {
                                ICluster cluster = await GetClusterAsync().ConfigureAwait(false);

                                session = await cluster.ConnectAsync(GetKeyspace()).ConfigureAwait(false);
                            }
                            catch (InvalidQueryException)
                            {
                                ICluster cluster = await GetClusterAsync().ConfigureAwait(false);

                                using (ISession schemaSession = await cluster.ConnectAsync().ConfigureAwait(false))
                                {
                                    string     createKeySpaceQuery  = replicationStrategy.CreateKeySpaceTemplate(GetKeyspace());
                                    IStatement createTableStatement = await GetKreateKeySpaceQuery(schemaSession).ConfigureAwait(false);

                                    await schemaSession.ExecuteAsync(createTableStatement).ConfigureAwait(false);
                                }

                                ICluster server = await GetClusterAsync().ConfigureAwait(false);

                                session = await server.ConnectAsync(GetKeyspace()).ConfigureAwait(false);
                            }
                        }
                    }
                    finally
                    {
                        threadGate?.Release();
                    }
                }
            }
            catch (ObjectDisposedException) { }


            return(session);
        }
Example #5
0
        private async Task MainAsync(string[] args)
        {
            // feel free to change these two const variables
            const int maxConcurrencyLevel = 32;
            const int totalLength         = 10000;

            Console.WriteLine($"MaxConcurrencyLevel={maxConcurrencyLevel}\tTotalLength={totalLength}");

            // build cluster
            _cluster =
                Cluster.Builder()
                .AddContactPoint("127.0.0.1")
                .Build();

            // create session
            _session = await _cluster.ConnectAsync().ConfigureAwait(false);

            // prepare schema
            await _session.ExecuteAsync(new SimpleStatement("CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '1' }")).ConfigureAwait(false);

            await _session.ExecuteAsync(new SimpleStatement("USE examples")).ConfigureAwait(false);

            await _session.ExecuteAsync(new SimpleStatement("CREATE TABLE IF NOT EXISTS tbl_sample_kv(id uuid, value text, PRIMARY KEY(id))")).ConfigureAwait(false);

            // prepare query
            _ps = await _session.PrepareAsync(Program.CqlQuery).ConfigureAwait(false);

            var concurrencyLevel = maxConcurrencyLevel >= totalLength ? totalLength : maxConcurrencyLevel;

            // The maximum amount of async executions that are going to be launched in parallel at any given time
            var tasks = new List <Task>(concurrencyLevel);

            try
            {
                // Compute operations per Task (rounded up, so the first tasks will process more operations)
                var maxCount = (int)Math.Ceiling(totalLength / (double)concurrencyLevel);

                // Launch up to N Tasks in parallel (N being the max concurrency level)
                var k = 0;
                while (k < totalLength)
                {
                    var inc = maxCount;
                    if (k + maxCount > totalLength)
                    {
                        inc = (totalLength - k);
                    }

                    tasks.Add(ExecuteOneAtATimeAsync(k, inc));
                    k += inc;
                }

                Console.WriteLine($"Executing {k} queries with a concurrency level of {tasks.Count}, i.e., {tasks.Count} tasks. Each task will process up to {maxCount} operations.");

                // The task returned by Task.WhenAll completes when all the executions are completed.
                await Task.WhenAll(tasks).ConfigureAwait(false);

                Console.WriteLine($"Finished executing {k} queries with a concurrency level of {tasks.Count}.");
                Console.WriteLine("Press enter to exit.");
                Console.ReadLine();
            }
            finally
            {
                await _cluster.ShutdownAsync().ConfigureAwait(false);
            }
        }
 public Task <ISession> GetConnectionAsync(ICluster cluster)
 {
     return(cluster.ConnectAsync());
 }
        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 = ClusterBuilder().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 = await testCluster.GetConnectedPortsAsync().ConfigureAwait(false);
                        for (var i = connections.Count - 3; i < connections.Count; i++)
                        {
                            try
                            {
                                await testCluster.DropConnection(connections.Last()).ConfigureAwait(false);
                            }
                            catch
                            {
                                // Connection might be already closed
                            }
                        }
                    }

                    ICluster cluster = null;
                    try
                    {
                        cluster = builder.Build();
                        await cluster.ConnectAsync().ConfigureAwait(false);
                    }
                    finally
                    {
                        await(cluster?.ShutdownAsync() ?? TaskHelper.Completed).ConfigureAwait(false);
                    }

                    return(0);
                }, 60, 5).ConfigureAwait(false);
            }
        }