internal CassandraConnection(Session owner, IPAddress serverAddress, ProtocolOptions protocolOptions,
                                     SocketOptions socketOptions, ClientOptions clientOptions,
                                     IAuthInfoProvider authInfoProvider)
        {
            this._owner = owner;
            _bufferingMode = null;
            switch (protocolOptions.Compression)
            {
                case CompressionType.Snappy:
                    _bufferingMode = new FrameBuffering();
                    break;
                case CompressionType.NoCompression:
                    _bufferingMode = clientOptions.WithoutRowSetBuffering ? new NoBuffering() : new FrameBuffering();
                    break;
                default:
                    throw new ArgumentException();
            }

            this._authInfoProvider = authInfoProvider;
            if (protocolOptions.Compression == CompressionType.Snappy)
            {
                _startupOptions.Add("COMPRESSION", "snappy");
                _compressor = new SnappyProtoBufCompressor();
            }
            this._serverAddress = serverAddress;
            this._port = protocolOptions.Port;
            this._queryAbortTimeout = clientOptions.QueryAbortTimeout;
            this._asyncCallAbortTimeout = clientOptions.AsyncCallAbortTimeout;

            this._socketOptions = socketOptions;

            CreateConnection();
            if (IsHealthy)
                BeginReading();
        }
Example #2
0
 internal CqlRowSet(OutputRows rawrows, Session session, bool ownRows = true)
 {
     this._rawrows = rawrows;
     this._ownRows = ownRows;
     if (rawrows.TraceID != null)
         _queryTrace = new QueryTrace(rawrows.TraceID.Value, session);
 }
	    //private ExecutorService executor;

        public VideoDbBasicImpl(List<String> contactPoints, String keyspace) 
        {
		    cluster = Cluster
			        .Builder()
			        .AddContactPoints(contactPoints.ToArray())
			        .WithRetryPolicy(Policies.DefaultRetryPolicy)
			        .Build();

		    session = cluster.Connect(keyspace);

		    getUserByNamePreparedStatement = session.Prepare(GET_USER_BY_USERNAME);
		    setUser = session.Prepare(SET_USER);
		    getVideosByUsernamePreparedStatement = session
				    .Prepare(GET_VIDEOS_BY_USERNAME);
            getVideoByIDPreparedStatement = session.Prepare(GET_VIDEO_BY_ID);
            getVideosByTagPreparedStatement = session.Prepare(GET_VIDEOS_BY_TAG);
		    getRatingByVideoPreparedStatement = session
                    .Prepare(GET_RATING_BY_VIDEO);
            setCommentByVideo = session.Prepare(SET_COMMENT_BY_VIDEO);
            setCommentByUsername = session.Prepare(SET_COMMENT_BY_USERNAME);
            getCommentByUsername = session.Prepare(GET_COMMENT_BY_USERNAME);
            getCommentByVideoId = session.Prepare(GET_COMMENT_BY_VIDEOID);

		    timeOfDayRetryPolicy = new TimeOfDayRetryPolicy(9, 17);

		    // Create a thread pool equal to the number of cores
            /*
		    executor = Executors.newFixedThreadPool(Runtime.getRuntime()
				    .availableProcessors());
             */
	    }
Example #4
0
 public TwitterContext(Session session)
     : base(session)
 {
     AddTable<Tweet>();
     AddTable<Author>();
     AddTable<FollowedTweet>();
     AddTable<Statistics>();
     CreateTablesIfNotExist();
 }
 public void Connect(String node)
 {
     _cluster = Cluster.Builder()
         .AddContactPoint(node).Build();
     Metadata metadata = _cluster.Metadata;
     Console.WriteLine("Connected to cluster: "
         + metadata.ClusterName.ToString());
     _session = _cluster.Connect();
      
 }
        internal ControlConnection(Cluster cluster, 
                                   IEnumerable<IPAddress> clusterEndpoints,
                                   Policies policies,
                                   ProtocolOptions protocolOptions,
                                   PoolingOptions poolingOptions,
                                   SocketOptions socketOptions,
                                   ClientOptions clientOptions,
                                   IAuthInfoProvider authProvider,
                                   bool metricsEnabled)
        {
            this._cluster = cluster;
            this._reconnectionTimer = new Timer(ReconnectionClb, null, Timeout.Infinite, Timeout.Infinite);

            _session = new Session(cluster, clusterEndpoints, policies, protocolOptions, poolingOptions, socketOptions,
                                   clientOptions, authProvider, metricsEnabled, "", _cluster._hosts);
        }
        internal ControlConnection(Cluster cluster,
                                   IEnumerable<IPAddress> clusterEndpoints,
                                   Policies policies,
                                   ProtocolOptions protocolOptions,
                                   PoolingOptions poolingOptions,
                                   SocketOptions socketOptions,
                                   ClientOptions clientOptions,
                                   IAuthInfoProvider authProvider)
        {
            this._cluster = cluster;
            this._reconnectionSchedule = _reconnectionPolicy.NewSchedule();
            this._reconnectionTimer = new Timer(ReconnectionClb, null, Timeout.Infinite, Timeout.Infinite);

            _session = new Session(cluster, policies, protocolOptions, poolingOptions, socketOptions,
                                   clientOptions, authProvider, "", false);
        }
        public void checkKSMetadata()
        {
            CCMCluster = CCMBridge.CCMCluster.Create(2, Cluster.Builder());
            try
            {
                Session = CCMCluster.Session;
                Cluster = CCMCluster.Cluster;
                Session.CreateKeyspaceIfNotExists(Keyspace);
                Session.ChangeKeyspace(Keyspace);

                string keyspacename = "keyspace" + Guid.NewGuid().ToString("N").ToLower();
                bool durableWrites = false;
                string strgyClass = "SimpleStrategy";
                short rplctnFactor = 1;
                Session.Cluster.WaitForSchemaAgreement(
                    Session.Execute(
            string.Format(@"CREATE KEYSPACE {0}
             WITH replication = {{ 'class' : '{1}', 'replication_factor' : {2} }}
             AND durable_writes={3};"
            , keyspacename, strgyClass, rplctnFactor.ToString(), durableWrites.ToString())).QueriedHost
                );
                Session.ChangeKeyspace(keyspacename);

                for (int i = 0; i < 10; i++)
                    checkPureMetadata("table" + Guid.NewGuid().ToString("N"), keyspacename);

                KeyspaceMetadata ksmd = Cluster.Metadata.GetKeyspace(keyspacename);
                Assert.True(ksmd.DurableWrites == durableWrites);
                Assert.True(ksmd.Replication.Where(opt => opt.Key == "replication_factor").First().Value == rplctnFactor);
                Assert.True(ksmd.StrategyClass == strgyClass);

            }
            finally
            {
                CCMCluster.Discard();
            }
        }
Example #9
0
 public void SetFixture()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
     CCMBridge.ReusableCCMCluster.Setup(2);
     CCMBridge.ReusableCCMCluster.Build(Cluster.Builder());
     Session = CCMBridge.ReusableCCMCluster.Connect("tester");
     Session.CreateKeyspaceIfNotExists(KeyspaceName);
     Session.ChangeKeyspace(KeyspaceName);
 }
        public void checkMetadata(string TableName = null, string KeyspaceName = null, TableOptions tableOptions = null)
        {
            CCMCluster = CCMBridge.CCMCluster.Create(2, Cluster.Builder());
            try
            {
                Session = CCMCluster.Session;
                Cluster = CCMCluster.Cluster;
                Session.CreateKeyspaceIfNotExists(Keyspace);
                Session.ChangeKeyspace(Keyspace);

                checkPureMetadata(TableName, KeyspaceName, tableOptions);
            }
            finally
            {
                CCMCluster.Discard();
            }
        }
Example #11
0
            private CCMCluster(CCMBridge ccmBridge, Builder builder)
            {
                int tryNo = 0;
                builder.AddContactPoints(Options.Default.IP_PREFIX + "1");
                if (Options.Default.USE_COMPRESSION)
                {
                    builder.WithCompression(CompressionType.Snappy);
                    Console.WriteLine("Using Compression");
                }
                if (Options.Default.USE_NOBUFFERING)
                {
                    builder.WithoutRowSetBuffering();
                    Console.WriteLine("No buffering");
                }

                this.Cluster = builder.Build();
                RETRY:
                this.CCMBridge = ccmBridge;
                try
                {
                    this.Session = Cluster.Connect();
                    if(tryNo>0)
                        Cluster.RefreshSchema();
                }
                catch (NoHostAvailableException e)
                {
                    if (tryNo < 10)
                    {
                        Console.WriteLine("CannotConnect to CCM node - give another try");
                        tryNo++;
                        Thread.Sleep(1000);
                        goto RETRY;
                    }
                    foreach (var entry in e.Errors)
                        Trace.TraceError("Error connecting to " + entry.Key + ": " + entry.Value);
                    throw new InvalidOperationException(null, e);
                }
            }
        public override void Open()
        {
            _connectionState = System.Data.ConnectionState.Connecting;

            lock (_clusters)
            {
                if (!_clusters.ContainsKey(_connectionStringBuilder.ClusterName))
                {
                    _managedCluster = _connectionStringBuilder.MakeClusterBuilder().Build();
                    _clusters.Add(_connectionStringBuilder.ClusterName, _managedCluster);
                }
                else
                    _managedCluster = _clusters[_connectionStringBuilder.ClusterName];
            }

            if (string.IsNullOrEmpty(_connectionStringBuilder.DefaultKeyspace))
                ManagedConnection = _managedCluster.Connect("");
            else
                ManagedConnection = _managedCluster.Connect(_connectionStringBuilder.DefaultKeyspace);

            _connectionState = System.Data.ConnectionState.Open;
        }
Example #13
0
 public void SetFixture()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
     CCMBridge.ReusableCCMCluster.Setup(2);
     CCMBridge.ReusableCCMCluster.Build(Cluster.Builder());
     Session = CCMBridge.ReusableCCMCluster.Connect("tester");
 }
Example #14
0
 public QueryTrace(Guid traceId, Session session)
 {
     this._traceId = traceId;
     this._session = session;
 }
Example #15
0
 internal CqlRowSet(OutputSetKeyspace output, Session session)
 {
 }
Example #16
0
        /// <summary>
        ///  Creates a new session on this cluster and sets a keyspace to use.
        /// </summary>
        /// <param name="keyspace"> The name of the keyspace to use for the created <code>Session</code>. </param>
        /// <returns>a new session on this cluster set to keyspace: 
        ///  <code>keyspaceName</code>. </returns>
        public Session Connect(string keyspace)
        {
            var scs = new Session(this, _configuration.Policies,
                                  _configuration.ProtocolOptions,
                                  _configuration.PoolingOptions, _configuration.SocketOptions,
                                  _configuration.ClientOptions,
                                  _configuration.AuthInfoProvider, keyspace);
            scs.Init();
            lock (_connectedSessions)
                _connectedSessions.Add(scs);
            _logger.Info("Session connected!");

            _metadata.RefreshSchema();

            return scs;
        }
Example #17
0
 internal void SessionDisposed(Session s)
 {
     lock (_connectedSessions)
         _connectedSessions.Remove(s);
 }
Example #18
0
 /// <summary>
 /// Creates a new session on this cluster and using a keyspace an existing keyspace.
 /// </summary>
 /// <param name="keyspace">Case-sensitive keyspace name to use</param>
 public ISession Connect(string keyspace)
 {
     Init();
     var session = new Session(this, Configuration, keyspace, _protocolVersion);
     session.Init();
     _connectedSessions.Add(session);
     _logger.Info("Session connected ({0})", session.GetHashCode());
     return session;
 }
Example #19
0
 public static Session Connect(string keyspace = null)
 {
     int tryNo = 0;
     RETRY:
     try
     {
         Session = Cluster.Connect();
         if (keyspace != null)
         {
             Session.CreateKeyspaceIfNotExists(keyspace);
             Session.ChangeKeyspace(keyspace);
         }
         return Session;
     }
     catch (NoHostAvailableException e)
     {
         if (tryNo < 10)
         {
             Console.WriteLine("CannotConnect to CCM node - give another try");
             tryNo++;
             Thread.Sleep(1000);
             goto RETRY;
         }
         foreach (var entry in e.Errors)
             Trace.TraceError("Error connecting to " + entry.Key + ": " + entry.Value);
         throw new InvalidOperationException(null, e);
     }
 }
Example #20
0
            public static void CreateCluster()
            {
                erroredOut = false;
                schemaCreated = false;
                cassandraCluster = CCMBridge.Create("test", 1);
                try
                {
                    var builder = Cluster.Builder().AddContactPoints(Options.Default.IP_PREFIX + "1");
                    if (Options.Default.USE_COMPRESSION)
                    {
                        builder.WithCompression(CompressionType.Snappy);
                        Console.WriteLine("Using Compression");
                    }
                    if (Options.Default.USE_NOBUFFERING)
                    {
                        builder.WithoutRowSetBuffering();
                        Console.WriteLine("No buffering");
                    }

                    cluster = builder.Build();
                    session = cluster.Connect();
                }
                catch (NoHostAvailableException e)
                {
                    erroredOut = true;
                    foreach (var entry in e.Errors)
                        Trace.TraceError("Error connecting to " + entry.Key + ": " + entry.Value);
                    throw new InvalidOperationException("", e);
                }
            }
 protected internal override IAsyncResult BeginSessionExecute(Session session, object tag, AsyncCallback callback, object state)
 {
     return session.BeginExecuteQuery(PreparedStatement.Id, PreparedStatement.Metadata, _values, callback, state, ConsistencyLevel, this, this, tag, IsTracing);
 }
 protected internal override IAsyncResult BeginSessionExecute(Session session, object tag, AsyncCallback callback, object state)
 {
     return session.BeginQuery(QueryString, callback, state, ConsistencyLevel,IsTracing, this, this, tag);
 }
 protected internal override CqlRowSet EndSessionExecute(Session session, IAsyncResult ar)
 {
     return session.EndExecuteQuery(ar);
 }
Example #24
0
        public void SetFixture()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            var clusterb = Cluster.Builder().AddContactPoint("cassi.cloudapp.net");
            clusterb.WithDefaultKeyspace(Keyspace);

            if (Cassandra.MSTest.Properties.Settings.Default.Compression)
            {
                clusterb.WithCompression(CompressionType.Snappy);
                Console.WriteLine("Compression: Snappy Compression");
            }
            else Console.WriteLine("Compression: No Compression");

            Cluster = clusterb.Build();
            Diagnostics.CassandraTraceSwitch.Level = System.Diagnostics.TraceLevel.Verbose;
            Diagnostics.CassandraStackTraceIncluded = true;
            Diagnostics.CassandraPerformanceCountersEnabled = true;
            Session = Cluster.ConnectAndCreateDefaultKeyspaceIfNotExists(ReplicationStrategies.CreateSimpleStrategyReplicationProperty(2), true);
        }
Example #25
0
        /// <summary>
        ///  Creates a new session on this cluster and sets a keyspace to use.
        /// </summary>
        /// <param name="keyspace"> The name of the keyspace to use for the created <code>Session</code>. </param>
        /// <returns>a new session on this cluster set to keyspace: 
        ///  <code>keyspaceName</code>. </returns>
        public Session Connect(string keyspace)
        {
            bool controlConnectionCreated = false;
            lock (_controlConnectionGuard)
            {
                if (_controlConnection == null)
                {
                    controlConnectionCreated = true;
                    var controlpolicies = new Cassandra.Policies(
                        _configuration.Policies.LoadBalancingPolicy,
                        new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000),
                        Cassandra.Policies.DefaultRetryPolicy);

                    _hosts = new Hosts(_configuration.Policies.ReconnectionPolicy);

                    foreach (var ep in _contactPoints)
                        _hosts.AddIfNotExistsOrBringUpIfDown(ep);

                    var poolingOptions = new PoolingOptions().SetCoreConnectionsPerHost(HostDistance.Local, 1);

                    _controlConnection = new ControlConnection(this, new List<IPAddress>(), controlpolicies,
                                                               _configuration.ProtocolOptions,
                                                               poolingOptions, _configuration.SocketOptions,
                                                               new ClientOptions(
                                                                   _configuration.ClientOptions.WithoutRowSetBuffering,
                                                                   _configuration.ClientOptions.QueryAbortTimeout, null,
                                                                   _configuration.ClientOptions.AsyncCallAbortTimeout),
                                                               _configuration.AuthInfoProvider,
                                                               _configuration.MetricsEnabled);

                    _metadata = new Metadata(_hosts, _controlConnection);

                    _controlConnection.Init();
                }
            }
            var scs = new Session(this, _contactPoints, _configuration.Policies,
                                  _configuration.ProtocolOptions,
                                  _configuration.PoolingOptions, _configuration.SocketOptions,
                                  _configuration.ClientOptions,
                                  _configuration.AuthInfoProvider, _configuration.MetricsEnabled, keyspace, _hosts);
            scs.Init();
            lock (_connectedSessions)
                _connectedSessions.Add(scs);
            _logger.Info("Session connected!");

            if (controlConnectionCreated)
                RefreshSchema();

            return scs;
        }
        public void CreateKeyspaceWithPropertiesTest(string strategy_class)
        {
            CCMCluster = CCMBridge.CCMCluster.Create(2, Cluster.Builder());
            try
            {
                Session = CCMCluster.Session;
                Cluster = CCMCluster.Cluster;

                Randomm rndm = new Randomm(DateTime.Now.Millisecond);
                bool durable_writes = rndm.NextBoolean();

                int? replication_factor = null;
                int? data_centers_count = null;
                Dictionary<string, int> datacenters_replication_factors = null;

                if (strategy_class == ReplicationStrategies.SimpleStrategy)
                {
                    replication_factor = rndm.Next(1, 21);
                    Session.CreateKeyspaceIfNotExists(Keyspace,ReplicationStrategies.CreateSimpleStrategyReplicationProperty((int)replication_factor), durable_writes);
                    Session.ChangeKeyspace(Keyspace);
                }
                else
                    if (strategy_class == ReplicationStrategies.NetworkTopologyStrategy)
                    {
                        data_centers_count = rndm.Next(1, 11);
                        datacenters_replication_factors = new Dictionary<string, int>((int)data_centers_count);
                        for (int i = 0; i < data_centers_count; i++)
                            datacenters_replication_factors.Add("dc" + i.ToString(), rndm.Next(1, 21));
                        Session.CreateKeyspaceIfNotExists(Keyspace, ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacenters_replication_factors), durable_writes);
                    }

                KeyspaceMetadata ksmd = Cluster.Metadata.GetKeyspace(Keyspace);
                Assert.Equal(strategy_class, ksmd.StrategyClass);
                Assert.Equal(durable_writes, ksmd.DurableWrites);
                if (replication_factor != null)
                    Assert.Equal(replication_factor, ksmd.Replication["replication_factor"]);
                if (datacenters_replication_factors != null)
                    Assert.True(datacenters_replication_factors.SequenceEqual(ksmd.Replication));
            }
            finally
            {
                CCMCluster.Discard();
            }
        }
Example #27
0
 /// <summary>
 /// Creates a new session on this cluster and using a keyspace an existing keyspace.
 /// </summary>
 /// <param name="keyspace">Case-sensitive keyspace name to use</param>
 public ISession Connect(string keyspace)
 {
     Init();
     var session = new Session(this, Configuration, keyspace, _binaryProtocolVersion);
     session.Init(true);
     _connectedSessions.Add(session);
     _logger.Info("Session connected!");
     return session;
 }
        internal ControlConnection(Cluster cluster,
                                   IEnumerable<IPAddress> clusterEndpoints,
                                   Policies policies,
                                   ProtocolOptions protocolOptions,
                                   PoolingOptions poolingOptions,
                                   SocketOptions socketOptions,
                                   ClientOptions clientOptions,
                                   IAuthProvider authProvider,
                                   IAuthInfoProvider authInfoProvider)
        {
            _cluster = cluster;
            _reconnectionSchedule = _reconnectionPolicy.NewSchedule();
            _reconnectionTimer = new Timer(ReconnectionClb, null, Timeout.Infinite, Timeout.Infinite);

            var config = new Configuration
            (
                policies,
                protocolOptions,
                poolingOptions,
                socketOptions,
                clientOptions,
                authProvider,
                authInfoProvider,
                new QueryOptions()
            );

            _session = new Session(cluster, config, "", ControlConnectionProtocolVersion);
        }
Example #29
0
 internal CqlRowSet(OutputSchemaChange output, Session session)
 {
     if (output.TraceID != null)
         _queryTrace = new QueryTrace(output.TraceID.Value, session);
 }
        internal CassandraConnection(Session owner, IPAddress serverAddress, ProtocolOptions protocolOptions,
                                     SocketOptions socketOptions, ClientOptions clientOptions,
                                     IAuthInfoProvider authInfoProvider)
        {
            this.Guid = Guid.NewGuid();
            this._owner = owner;
            _bufferingMode = null;
            switch (protocolOptions.Compression)
            {
                case CompressionType.Snappy:
                    _bufferingMode = new FrameBuffering();
                    break;
                case CompressionType.NoCompression:
                    _bufferingMode = clientOptions.WithoutRowSetBuffering ? new NoBuffering() : new FrameBuffering();
                    break;
                default:
                    throw new ArgumentException();
            }

            this._authInfoProvider = authInfoProvider;
            if (protocolOptions.Compression == CompressionType.Snappy)
            {
                _startupOptions.Add("COMPRESSION", "snappy");
                _compressor = new SnappyProtoBufCompressor();
            }
            this._serverAddress = serverAddress;
            this._port = protocolOptions.Port;
            this._queryAbortTimeout = clientOptions.QueryAbortTimeout;

            this._socketOptions = socketOptions;

            for (int i = 0; i <= sbyte.MaxValue; i++)
                _freeStreamIDs.Push(i);

            _protocolErrorHandlerAction = new Action<ErrorActionParam>((param) =>
               {
                   if (param.AbstractResponse is ErrorResponse)
                       JobFinished(
                           param.Jar,
                           (param.AbstractResponse as ErrorResponse).Output);
               });

            _frameEventCallback.Value = new Action<ResponseFrame>(EventOccured);

            _buffer = new byte[][] {
                    new byte[_bufferingMode.PreferedBufferSize()],
                    new byte[_bufferingMode.PreferedBufferSize()] };

            var newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (_socketOptions.KeepAlive != null)
                newSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive,
                                        _socketOptions.KeepAlive.Value);

            newSock.SendTimeout = _socketOptions.ConnectTimeoutMillis;

            if (_socketOptions.SoLinger != null)
                newSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,
                                        new LingerOption(true, _socketOptions.SoLinger.Value));

            if (_socketOptions.ReceiveBufferSize != null)
                newSock.ReceiveBufferSize = _socketOptions.ReceiveBufferSize.Value;

            if (_socketOptions.SendBufferSize != null)
                newSock.ReceiveBufferSize = _socketOptions.SendBufferSize.Value;

            if (_socketOptions.TcpNoDelay != null)
                newSock.NoDelay = _socketOptions.TcpNoDelay.Value;

            newSock.Connect(new IPEndPoint(_serverAddress, _port));
            _socket = newSock;
            _bufferingMode.Reset();

            if (protocolOptions.SslOptions == null)
                _socketStream = new NetworkStream(_socket);
            else
            {
                string targetHost;
                try
                {
                    targetHost = Dns.GetHostEntry(_serverAddress).HostName;
                }
                catch (SocketException ex)
                {
                    targetHost = serverAddress.ToString();
                    _logger.Error(string.Format("SSL connection: Can not resolve {0} address. Using IP address instead of hostname. This may cause RemoteCertificateNameMismatch error during Cassandra host authentication. Note that Cassandra node SSL certificate's CN(Common Name) must match the Cassandra node hostname.", _serverAddress.ToString()), ex);
                }

                _socketStream = new SslStream(new NetworkStream(_socket), false, new RemoteCertificateValidationCallback(protocolOptions.SslOptions.RemoteCertValidationCallback), null);
                (_socketStream as SslStream).AuthenticateAsClient(targetHost, new X509CertificateCollection(), protocolOptions.SslOptions.SslProtocol, false);
            }

            if (IsHealthy)
                BeginReading();
        }