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);
        }
 /// <summary>
 /// Creates a new instance. This class is also used to shareable a context across all instance that are created below one Cluster instance.
 /// One configuration instance per Cluster instance.
 /// </summary>
 internal Configuration(Policies policies,
     ProtocolOptions protocolOptions,
     PoolingOptions poolingOptions,
     SocketOptions socketOptions,
     ClientOptions clientOptions,
     IAuthProvider authProvider,
     IAuthInfoProvider authInfoProvider,
     QueryOptions queryOptions,
     IAddressTranslator addressTranslator)
 {
     if (addressTranslator == null)
     {
         throw new ArgumentNullException("addressTranslator");
     }
     if (queryOptions == null)
     {
         throw new ArgumentNullException("queryOptions");
     }
     _policies = policies;
     _protocolOptions = protocolOptions;
     _poolingOptions = poolingOptions;
     _socketOptions = socketOptions;
     _clientOptions = clientOptions;
     _authProvider = authProvider;
     _authInfoProvider = authInfoProvider;
     _queryOptions = queryOptions;
     _addressTranslator = addressTranslator;
 }
        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);
        }
        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);
        }
Exemple #5
0
        private Cluster(IEnumerable<IPAddress> contactPoints, Configuration configuration)
        {
            _contactPoints = contactPoints;
            _configuration = configuration;
            _metadata = new Metadata(configuration.Policies.ReconnectionPolicy);

            var controlpolicies = new Policies(
                _configuration.Policies.LoadBalancingPolicy,
                new ExponentialReconnectionPolicy(2*1000, 5*60*1000),
                Policies.DefaultRetryPolicy);

            foreach (IPAddress ep in _contactPoints)
                Metadata.AddHost(ep);

            //Use 1 connection per host
            //The connection will be reused, it wont create a connection per host.
            var controlPoolingOptions = new PoolingOptions()
                .SetCoreConnectionsPerHost(HostDistance.Local, 1)
                .SetMaxConnectionsPerHost(HostDistance.Local, 1)
                .SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 0)
                .SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 127);

            var controlConnection = new ControlConnection
                (this,
                new List<IPAddress>(),
                controlpolicies,
                new ProtocolOptions(_configuration.ProtocolOptions.Port, configuration.ProtocolOptions.SslOptions),
                controlPoolingOptions,
                _configuration.SocketOptions,
                new ClientOptions(true, _configuration.ClientOptions.QueryAbortTimeout, null),
                _configuration.AuthProvider,
                _configuration.AuthInfoProvider
                );

            _metadata.SetupControllConnection(controlConnection);
            _binaryProtocolVersion = controlConnection.ProtocolVersion;
            _logger.Info("Binary protocol version: [" + _binaryProtocolVersion + "]");
        }
Exemple #6
0
        /// <summary>
        ///  The configuration that will be used for the new cluster. <p> You <b>should
        ///  not</b> modify this object directly as change made to the returned object may
        ///  not be used by the cluster build. Instead, you should use the other methods
        ///  of this <code>Builder</code></p>.
        /// </summary>
        /// 
        /// <returns>the configuration to use for the new cluster.</returns>
        public Configuration GetConfiguration()
        {
            var policies = new Policies(
                _loadBalancingPolicy ?? Cassandra.Policies.DefaultLoadBalancingPolicy,
                _reconnectionPolicy ?? Cassandra.Policies.DefaultReconnectionPolicy,
                _retryPolicy ?? Cassandra.Policies.DefaultRetryPolicy
                );

            return new Configuration(policies,
                                     new ProtocolOptions(_port).SetCompression(_compression),
                                     _poolingOptions,
                                     _socketOptions,
                                     new ClientOptions(_withoutRowSetBuffering, _queryAbortTimeout, _defaultKeyspace, _asyncCallAbortTimeout),
                                     _authProvider
                );
        }
Exemple #7
0
        /// <summary>
        ///  The configuration that will be used for the new cluster. <p> You <b>should
        ///  not</b> modify this object directly as change made to the returned object may
        ///  not be used by the cluster build. Instead, you should use the other methods
        ///  of this <c>Builder</c></p>.
        /// </summary>
        /// 
        /// <returns>the configuration to use for the new cluster.</returns>
        public Configuration GetConfiguration()
        {
            var policies = new Policies(
                _loadBalancingPolicy ?? Policies.DefaultLoadBalancingPolicy,
                _reconnectionPolicy ?? Policies.DefaultReconnectionPolicy,
                _retryPolicy ?? Policies.DefaultRetryPolicy
                );

            return new Configuration(policies,
                                     new ProtocolOptions(_port, _sslOptions).SetCompression(_compression).SetCustomCompressor(_customCompressor),
                                     _poolingOptions,
                                     _socketOptions,
                                     new ClientOptions(_withoutRowSetBuffering, _queryAbortTimeout, _defaultKeyspace),
                                     _authProvider,
                                     _authInfoProvider,
                                     _queryOptions,
                                     _addressTranslator
                );
        }
Exemple #8
0
        internal Session(Cluster cluster,
                         Policies policies,
                         ProtocolOptions protocolOptions,
                         PoolingOptions poolingOptions,
                         SocketOptions socketOptions,
                         ClientOptions clientOptions,
                         IAuthInfoProvider authProvider,
                         string keyspace, bool init)
        {
            try
            {
                this._cluster = cluster;

                this._protocolOptions = protocolOptions;
                this._poolingOptions = poolingOptions;
                this._socketOptions = socketOptions;
                this._clientOptions = clientOptions;
                this._authProvider = authProvider;

                this._policies = policies ?? Policies.DefaultPolicies;

                this._policies.LoadBalancingPolicy.Initialize(_cluster);

                _keyspace = keyspace ?? clientOptions.DefaultKeyspace;

                Guid = Guid.NewGuid();

                _trashcanCleaner = new Timer(TranscanCleanup, null, Timeout.Infinite, Timeout.Infinite);

                if (init)
                {
                    var ci = this._policies.LoadBalancingPolicy.NewQueryPlan(null).GetEnumerator();
                    if (!ci.MoveNext())
                    {
                        var ex = new NoHostAvailableException(new Dictionary<IPAddress, List<Exception>>());
                        _logger.Error(ex.Message);
                        throw ex;
                    }

                    var triedHosts = new List<IPAddress>();
                    var innerExceptions = new Dictionary<IPAddress, List<Exception>>();
                    int streamId;
                    var con = Connect(ci, triedHosts, innerExceptions, out streamId);
                    con.FreeStreamId(streamId);
                }
            }
            catch
            {
                InternalDispose();
                throw;
            }
        }
Exemple #9
0
        internal Session(Cluster cluster,
                         Policies policies,
                         ProtocolOptions protocolOptions,
                         PoolingOptions poolingOptions,
                         SocketOptions socketOptions,
                         ClientOptions clientOptions,
                         IAuthInfoProvider authProvider,
                         string keyspace)
        {
            this._cluster = cluster;

            this._protocolOptions = protocolOptions;
            this._poolingOptions = poolingOptions;
            this._socketOptions = socketOptions;
            this._clientOptions = clientOptions;
            this._authProvider = authProvider;

            this._policies = policies ?? Policies.DefaultPolicies;

            this._policies.LoadBalancingPolicy.Initialize(_cluster);

            _keyspace = keyspace ?? clientOptions.DefaultKeyspace;
        }
Exemple #10
0
        /// <summary>
        /// Creates a new instance. This class is also used to shareable a context across all instance that are created below one Cluster instance.
        /// One configuration instance per Cluster instance.
        /// </summary>
        internal Configuration(Policies policies,
                               ProtocolOptions protocolOptions,
                               PoolingOptions poolingOptions,
                               SocketOptions socketOptions,
                               ClientOptions clientOptions,
                               IAuthProvider authProvider,
                               IAuthInfoProvider authInfoProvider,
                               QueryOptions queryOptions,
                               IAddressTranslator addressTranslator,
                               IStartupOptionsFactory startupOptionsFactory,
                               ISessionFactoryBuilder <IInternalCluster, IInternalSession> sessionFactoryBuilder,
                               IReadOnlyDictionary <string, IExecutionProfile> executionProfiles,
                               IRequestOptionsMapper requestOptionsMapper,
                               MetadataSyncOptions metadataSyncOptions,
                               IEndPointResolver endPointResolver,
                               IDriverMetricsProvider driverMetricsProvider,
                               DriverMetricsOptions metricsOptions,
                               string sessionName,
                               IRequestHandlerFactory requestHandlerFactory         = null,
                               IHostConnectionPoolFactory hostConnectionPoolFactory = null,
                               IRequestExecutionFactory requestExecutionFactory     = null,
                               IConnectionFactory connectionFactory = null,
                               IControlConnectionFactory controlConnectionFactory = null,
                               IPrepareHandlerFactory prepareHandlerFactory       = null,
                               ITimerFactory timerFactory = null,
                               IObserverFactoryBuilder observerFactoryBuilder = null)
        {
            AddressTranslator     = addressTranslator ?? throw new ArgumentNullException(nameof(addressTranslator));
            QueryOptions          = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions));
            Policies              = policies;
            ProtocolOptions       = protocolOptions;
            PoolingOptions        = poolingOptions;
            SocketOptions         = socketOptions;
            ClientOptions         = clientOptions;
            AuthProvider          = authProvider;
            AuthInfoProvider      = authInfoProvider;
            StartupOptionsFactory = startupOptionsFactory;
            SessionFactoryBuilder = sessionFactoryBuilder;
            RequestOptionsMapper  = requestOptionsMapper;
            MetadataSyncOptions   = metadataSyncOptions?.Clone() ?? new MetadataSyncOptions();
            DnsResolver           = new DnsResolver();
            EndPointResolver      = endPointResolver ?? new EndPointResolver(DnsResolver, protocolOptions);
            MetricsOptions        = metricsOptions ?? new DriverMetricsOptions();
            MetricsProvider       = driverMetricsProvider ?? new NullDriverMetricsProvider();
            SessionName           = sessionName;
            MetricsEnabled        = driverMetricsProvider != null;

            ObserverFactoryBuilder    = observerFactoryBuilder ?? (MetricsEnabled ? (IObserverFactoryBuilder) new MetricsObserverFactoryBuilder() : new NullObserverFactoryBuilder());
            RequestHandlerFactory     = requestHandlerFactory ?? new RequestHandlerFactory();
            HostConnectionPoolFactory = hostConnectionPoolFactory ?? new HostConnectionPoolFactory();
            RequestExecutionFactory   = requestExecutionFactory ?? new RequestExecutionFactory();
            ConnectionFactory         = connectionFactory ?? new ConnectionFactory();
            ControlConnectionFactory  = controlConnectionFactory ?? new ControlConnectionFactory();
            PrepareHandlerFactory     = prepareHandlerFactory ?? new PrepareHandlerFactory();
            TimerFactory = timerFactory ?? new TaskBasedTimerFactory();

            RequestOptions    = RequestOptionsMapper.BuildRequestOptionsDictionary(executionProfiles, policies, socketOptions, clientOptions, queryOptions);
            ExecutionProfiles = BuildExecutionProfilesDictionary(executionProfiles, RequestOptions);

            // Create the buffer pool with 16KB for small buffers and 256Kb for large buffers.
            // The pool does not eagerly reserve the buffers, so it doesn't take unnecessary memory
            // to create the instance.
            BufferPool = new RecyclableMemoryStreamManager(16 * 1024, 256 * 1024, ProtocolOptions.MaximumFrameLength);
            Timer      = new HashedWheelTimer();
        }
        /// <summary>
        /// Creates a new instance. This class is also used to shareable a context across all instance that are created below one Cluster instance.
        /// One configuration instance per Cluster instance.
        /// </summary>
        internal Configuration(Policies policies,
                               ProtocolOptions protocolOptions,
                               PoolingOptions poolingOptions,
                               SocketOptions socketOptions,
                               ClientOptions clientOptions,
                               IAuthProvider authProvider,
                               IAuthInfoProvider authInfoProvider,
                               QueryOptions queryOptions,
                               IAddressTranslator addressTranslator,
                               IReadOnlyDictionary <string, IExecutionProfile> executionProfiles,
                               MetadataSyncOptions metadataSyncOptions,
                               IEndPointResolver endPointResolver,
                               IDriverMetricsProvider driverMetricsProvider,
                               DriverMetricsOptions metricsOptions,
                               string sessionName,
                               GraphOptions graphOptions,
                               Guid?clusterId,
                               string appVersion,
                               string appName,
                               MonitorReportingOptions monitorReportingOptions,
                               TypeSerializerDefinitions typeSerializerDefinitions,
                               bool?keepContactPointsUnresolved,
                               ISessionFactory sessionFactory                       = null,
                               IRequestOptionsMapper requestOptionsMapper           = null,
                               IStartupOptionsFactory startupOptionsFactory         = null,
                               IInsightsSupportVerifier insightsSupportVerifier     = null,
                               IRequestHandlerFactory requestHandlerFactory         = null,
                               IHostConnectionPoolFactory hostConnectionPoolFactory = null,
                               IRequestExecutionFactory requestExecutionFactory     = null,
                               IConnectionFactory connectionFactory                 = null,
                               IControlConnectionFactory controlConnectionFactory   = null,
                               IPrepareHandlerFactory prepareHandlerFactory         = null,
                               ITimerFactory timerFactory = null,
                               IObserverFactoryBuilder observerFactoryBuilder = null,
                               IInsightsClientFactory insightsClientFactory   = null,
                               IContactPointParser contactPointParser         = null,
                               IServerNameResolver serverNameResolver         = null,
                               IDnsResolver dnsResolver = null)
        {
            AddressTranslator = addressTranslator ?? throw new ArgumentNullException(nameof(addressTranslator));
            QueryOptions      = queryOptions ?? throw new ArgumentNullException(nameof(queryOptions));
            GraphOptions      = graphOptions ?? new GraphOptions();

            ClusterId                   = clusterId ?? Guid.NewGuid();
            ApplicationVersion          = appVersion ?? Configuration.DefaultApplicationVersion;
            ApplicationName             = appName ?? Configuration.FallbackApplicationName;
            ApplicationNameWasGenerated = appName == null;

            Policies                    = policies;
            ProtocolOptions             = protocolOptions;
            PoolingOptions              = poolingOptions;
            SocketOptions               = socketOptions;
            ClientOptions               = clientOptions;
            AuthProvider                = authProvider;
            AuthInfoProvider            = authInfoProvider;
            StartupOptionsFactory       = startupOptionsFactory ?? new StartupOptionsFactory(ClusterId, ApplicationVersion, ApplicationName);
            SessionFactory              = sessionFactory ?? new SessionFactory();
            RequestOptionsMapper        = requestOptionsMapper ?? new RequestOptionsMapper();
            MetadataSyncOptions         = metadataSyncOptions?.Clone() ?? new MetadataSyncOptions();
            DnsResolver                 = dnsResolver ?? new DnsResolver();
            MetricsOptions              = metricsOptions ?? new DriverMetricsOptions();
            MetricsProvider             = driverMetricsProvider ?? new NullDriverMetricsProvider();
            SessionName                 = sessionName;
            MetricsEnabled              = driverMetricsProvider != null;
            TypeSerializers             = typeSerializerDefinitions?.Definitions;
            KeepContactPointsUnresolved = keepContactPointsUnresolved ?? false;

            ObserverFactoryBuilder    = observerFactoryBuilder ?? (MetricsEnabled ? (IObserverFactoryBuilder) new MetricsObserverFactoryBuilder() : new NullObserverFactoryBuilder());
            RequestHandlerFactory     = requestHandlerFactory ?? new RequestHandlerFactory();
            HostConnectionPoolFactory = hostConnectionPoolFactory ?? new HostConnectionPoolFactory();
            RequestExecutionFactory   = requestExecutionFactory ?? new RequestExecutionFactory();
            ConnectionFactory         = connectionFactory ?? new ConnectionFactory();
            ControlConnectionFactory  = controlConnectionFactory ?? new ControlConnectionFactory();
            PrepareHandlerFactory     = prepareHandlerFactory ?? new PrepareHandlerFactory();
            TimerFactory = timerFactory ?? new TaskBasedTimerFactory();

            RequestOptions    = RequestOptionsMapper.BuildRequestOptionsDictionary(executionProfiles, policies, socketOptions, clientOptions, queryOptions, GraphOptions);
            ExecutionProfiles = BuildExecutionProfilesDictionary(executionProfiles, RequestOptions);

            MonitorReportingOptions = monitorReportingOptions ?? new MonitorReportingOptions();
            InsightsSupportVerifier = insightsSupportVerifier ?? Configuration.DefaultInsightsSupportVerifier;
            InsightsClientFactory   = insightsClientFactory ?? Configuration.DefaultInsightsClientFactory;
            ServerNameResolver      = serverNameResolver ?? new ServerNameResolver(ProtocolOptions);
            EndPointResolver        = endPointResolver ?? new EndPointResolver(ServerNameResolver);
            ContactPointParser      = contactPointParser ?? new ContactPointParser(DnsResolver, ProtocolOptions, ServerNameResolver, KeepContactPointsUnresolved);

            // Create the buffer pool with 16KB for small buffers and 256Kb for large buffers.
            // The pool does not eagerly reserve the buffers, so it doesn't take unnecessary memory
            // to create the instance.
            BufferPool = new RecyclableMemoryStreamManager(16 * 1024, 256 * 1024, ProtocolOptions.MaximumFrameLength);
            Timer      = new HashedWheelTimer();
        }
Exemple #12
0
        internal Session(Cluster cluster,
                         IEnumerable<IPAddress> clusterEndpoints,
                         Policies policies,
                         ProtocolOptions protocolOptions,
                         PoolingOptions poolingOptions,
                         SocketOptions socketOptions,
                         ClientOptions clientOptions,
                         IAuthInfoProvider authProvider,
                         bool metricsEnabled,
                         string keyspace,
                         Hosts hosts,ControlConnection controlConnection=null)
        {
            this._cluster = cluster;

            this._protocolOptions = protocolOptions;
            this._poolingOptions = poolingOptions;
            this._socketOptions = socketOptions;
            this._clientOptions = clientOptions;
            this._authProvider = authProvider;
            this._metricsEnabled = metricsEnabled;

            this._policies = policies ?? Policies.DefaultPolicies;

            _hosts = hosts ;

            this._controlConnection = controlConnection;

            foreach (var ep in clusterEndpoints)
                _hosts.AddIfNotExistsOrBringUpIfDown(ep, this._policies.ReconnectionPolicy);

            this._policies.LoadBalancingPolicy.Initialize(_cluster);

            _keyspace = keyspace ?? clientOptions.DefaultKeyspace;
        }
        internal static QueryProtocolOptions CreateFromQuery(ProtocolVersion protocolVersion, Statement query,
                                                             QueryOptions queryOptions, Policies policies)
        {
            if (query == null)
            {
                return(Default);
            }
            var  consistency = query.ConsistencyLevel ?? queryOptions.GetConsistencyLevel();
            var  pageSize    = query.PageSize != 0 ? query.PageSize : queryOptions.GetPageSize();
            long?timestamp   = null;

            if (query.Timestamp != null)
            {
                timestamp = TypeSerializer.SinceUnixEpoch(query.Timestamp.Value).Ticks / 10;
            }
            else if (protocolVersion.SupportsTimestamp())
            {
                timestamp = policies.TimestampGenerator.Next();
                if (timestamp == long.MinValue)
                {
                    timestamp = null;
                }
            }
            return(new QueryProtocolOptions(
                       consistency,
                       query.QueryValues,
                       query.SkipMetadata,
                       pageSize,
                       query.PagingState,
                       query.SerialConsistencyLevel,
                       timestamp));
        }
Exemple #14
0
 /// <summary>
 ///  The configuration that will be used for the new cluster. <p> You <b>should
 ///  not</b> modify this object directly as change made to the returned object may
 ///  not be used by the cluster build. Instead, you should use the other methods
 ///  of this <c>Builder</c></p>.
 /// </summary>
 /// 
 /// <returns>the configuration to use for the new cluster.</returns>
 public Configuration GetConfiguration()
 {
     var policies = new Policies(
         _loadBalancingPolicy ?? Policies.DefaultLoadBalancingPolicy,
         _reconnectionPolicy ?? Policies.DefaultReconnectionPolicy,
         _retryPolicy ?? Policies.DefaultRetryPolicy,
         _speculativeExecutionPolicy ?? Policies.DefaultSpeculativeExecutionPolicy);
     var config = new Configuration(policies,
         new ProtocolOptions(_port, _sslOptions).SetCompression(_compression)
                                                .SetCustomCompressor(_customCompressor).SetMaxProtocolVersion(_maxProtocolVersion),
         _poolingOptions,
         _socketOptions,
         new ClientOptions(_withoutRowSetBuffering, _queryAbortTimeout, _defaultKeyspace),
         _authProvider,
         _authInfoProvider,
         _queryOptions,
         _addressTranslator);
     if (_typeSerializerDefinitions != null)
     {
         config.TypeSerializers = _typeSerializerDefinitions.Definitions;
     }
     return config;
 }