コード例 #1
0
        /// <summary>
        /// Handles the reconnection attempts.
        /// If it succeeds, it marks the host as UP.
        /// If not, it marks the host as DOWN
        /// </summary>
        internal void AttemptReconnection()
        {
            _poolModificationSemaphore.Wait();
            var toRemove = _connections.Where(c => c.IsClosed).ToArray();

            foreach (var c in toRemove)
            {
                _connections.Remove(c);
            }
            if (_connections.Count > 0)
            {
                //there is already an open connection
                _poolModificationSemaphore.Release();
                return;
            }
            Logger.Info("Attempting reconnection to host {0}", _host.Address);
            CreateConnection().ContinueWith(t =>
            {
                if (t.Status == TaskStatus.RanToCompletion)
                {
                    _connections.Add(t.Result);
                    //Release as soon as possible
                    _poolModificationSemaphore.Release();
                    Logger.Info("Reconnection attempt to host {0} succeeded", _host.Address);
                    _host.BringUpIfDown();
                }
                else
                {
                    _poolModificationSemaphore.Release();
                    Logger.Info("Reconnection attempt to host {0} failed", _host.Address);
                    _host.SetDown();
                }
            }, TaskContinuationOptions.ExecuteSynchronously);
        }
コード例 #2
0
 public void CopyOnWriteList_Should_Add_And_Count()
 {
     var list = new CopyOnWriteList<string>();
     list.Add("one");
     list.Add("two");
     Assert.AreEqual(2, list.Count);
     CollectionAssert.AreEqual(new[] { "one", "two" }, list);
 }
コード例 #3
0
        /// <summary>
        /// Handles the reconnection attempts.
        /// If it succeeds, it marks the host as UP.
        /// If not, it marks the host as DOWN
        /// </summary>
        internal void AttemptReconnection()
        {
            _isShuttingDown = false;
            if (_isDisposed)
            {
                return;
            }
            var tcs = new TaskCompletionSource <Connection[]>();
            //While there is a single thread here, there might be another thread
            //Calling MaybeCreateFirstConnection()
            //Guard for multiple creations
            var creationTcs = Interlocked.CompareExchange(ref _creationTcs, tcs, null);

            if (creationTcs != null || _connections.Count > 0)
            {
                //Already creating as host is back UP (possibly via events)
                return;
            }
            Logger.Info("Attempting reconnection to host {0}", _host.Address);
            //There is a single thread creating a connection
            CreateConnection().ContinueWith(t =>
            {
                if (t.Status == TaskStatus.RanToCompletion)
                {
                    if (_isShuttingDown)
                    {
                        t.Result.Dispose();
                        TransitionCreationTask(tcs, EmptyConnectionsArray);
                        return;
                    }
                    _connections.Add(t.Result);
                    Logger.Info("Reconnection attempt to host {0} succeeded", _host.Address);
                    _host.BringUpIfDown();
                    TransitionCreationTask(tcs, new [] { t.Result });
                    return;
                }
                Logger.Info("Reconnection attempt to host {0} failed", _host.Address);
                Exception ex = null;
                if (t.Exception != null)
                {
                    t.Exception.Handle(e => true);
                    ex = t.Exception.InnerException;
                    //This makes sure that the exception is observed, but still sets _creationTcs' exception
                    //for MaybeCreateFirstConnection
                    tcs.Task.ContinueWith(x =>
                    {
                        if (x.Exception != null)
                        {
                            x.Exception.Handle(_ => true);
                        }
                    });
                }
                TransitionCreationTask(tcs, EmptyConnectionsArray, ex);
                _host.SetDown(failedReconnection: true);
            }, TaskContinuationOptions.ExecuteSynchronously);
        }
コード例 #4
0
        // Checks type and adds to cache
        private static bool CheckAddType(
            Type[] classes,
            Type type,
            CopyOnWriteList<Pair<Type, bool>> resultCache)
        {
            lock (resultCache) {
                // check again in synchronized block
                foreach (Pair<Type, bool> pair in resultCache) {
                    if (pair.First == type) {
                        return pair.Second;
                    }
                }

                // get the types superclasses and interfaces, and their superclasses and interfaces
                ISet<Type> classesToCheck = new HashSet<Type>();
                TypeHelper.GetBase(type, classesToCheck);
                classesToCheck.Add(type);

                // check type against each class
                var fits = false;
                foreach (var clazz in classes) {
                    if (classesToCheck.Contains(clazz)) {
                        fits = true;
                        break;
                    }
                }

                resultCache.Add(new Pair<Type, bool>(type, fits));
                return fits;
            }
        }
コード例 #5
0
        // Checks type and adds to cache
        private bool?CheckAddType(Type type)
        {
            using (_oLock.Acquire())
            {
                // check again in synchronized block
                foreach (Pair <Type, Boolean> pair in _resultCache)
                {
                    if (pair.First == type)
                    {
                        return(pair.Second);
                    }
                }

                // get the types superclasses and interfaces, and their superclasses and interfaces
                ICollection <Type> classesToCheck = new HashSet <Type>();
                TypeHelper.GetBase(type, classesToCheck);
                classesToCheck.Add(type);

                // check type against each class
                bool fits = false;
                foreach (Type clazz in _classes)
                {
                    if (classesToCheck.Contains(clazz))
                    {
                        fits = true;
                        break;
                    }
                }

                _resultCache.Add(new Pair <Type, Boolean>(type, fits));
                return(fits);
            }
        }
コード例 #6
0
        public override void OnWireReceived(UnsafeReader reader)
        {
            var contextBase = RdContextBase.Read(SerializationContext, reader);

            contextBase.RegisterOn(this);

            myCounterpartHandlers.Add(myHandlersMap[contextBase]);
        }
コード例 #7
0
        public void AddListener(ContextPartitionStateListener listener)
        {
            if (listenersLazy == null) {
                listenersLazy = new CopyOnWriteList<ContextPartitionStateListener>();
            }

            listenersLazy.Add(listener);
        }
コード例 #8
0
        /// <summary>
        /// NOTE: Code-generation-invoked method, method name and parameter order matters
        /// </summary>
        /// <param name="clazz">class</param>
        /// <param name="field">field</param>
        /// <param name="cache">cache</param>
        /// <returns>descriptor</returns>
        public static DynamicPropertyDescriptorByField DynamicPropertyCacheAdd(
            Type clazz,
            FieldInfo field,
            CopyOnWriteList <DynamicPropertyDescriptorByField> cache)
        {
            var propertyDescriptor = new DynamicPropertyDescriptorByField(clazz, field);

            cache.Add(propertyDescriptor);
            return(propertyDescriptor);
        }
コード例 #9
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, _serializer);

            session.Init();
            _connectedSessions.Add(session);
            _logger.Info("Session connected ({0})", session.GetHashCode());
            return(session);
        }
コード例 #10
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 async Task <ISession> ConnectAsync(string keyspace)
        {
            await Init().ConfigureAwait(false);

            var session = new Session(this, Configuration, keyspace, _serializer);
            await session.Init().ConfigureAwait(false);

            _connectedSessions.Add(session);
            _logger.Info("Session connected ({0})", session.GetHashCode());
            return(session);
        }
コード例 #11
0
        public void Add_does_not_cause_concurrent_modifications()
        {
            var list = new CopyOnWriteList <int> {
                1, 2, 3
            };
            var e = list.GetEnumerator();

            // Adding an item should not cause concurrent modifications
            list.Add(4);
            Assert.DoesNotThrow(() => e.MoveNext());
        }
コード例 #12
0
ファイル: Cluster.cs プロジェクト: mlag/csharp-driver
        async Task <TSession> IInternalCluster.ConnectAsync <TSession>(ISessionFactory <TSession> sessionFactory, string keyspace)
        {
            await Init().ConfigureAwait(false);

            var session = await sessionFactory.CreateSessionAsync(keyspace, _serializer).ConfigureAwait(false);

            await session.Init().ConfigureAwait(false);

            _connectedSessions.Add(session);
            Cluster.Logger.Info("Session connected ({0})", session.GetHashCode());
            return(session);
        }
コード例 #13
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 async Task <ISession> ConnectAsync(string keyspace)
        {
            await Init().ConfigureAwait(false);

            var newSessionName = GetNewSessionName();
            var session        = await Configuration.SessionFactory.CreateSessionAsync(this, keyspace, _controlConnection.Serializer, newSessionName).ConfigureAwait(false);

            await session.Init().ConfigureAwait(false);

            _connectedSessions.Add(session);
            Cluster.Logger.Info("Session connected ({0})", session.GetHashCode());
            return(session);
        }
コード例 #14
0
ファイル: EmRoute.cs プロジェクト: ArturD/Daemons
        public IDisposable Subscribe <T>(string path, Action <T> consumeAction)
        {
            Action <string, object> consumer = (pattern, message) =>
            {
                if (path == pattern && message is T)
                {
                    consumeAction((T)message);
                }
            };

            _list.Add(consumer);
            return(new AnonymousDisposer(() => _list.Remove(consumer)));
        }
コード例 #15
0
        public IDisposable Subscribe(string topicPattern, Action <string, object> messageConsumer)
        {
            var topicExpression = new Regex(topicPattern);
            Action <string, object> conditionalConsume =
                (path, message) =>
            {
                if (topicExpression.IsMatch(path))
                {
                    messageConsumer(path, message);
                }
            };

            _subscribtions.Add(conditionalConsume);
            return(new AnonymousDisposer(() => _subscribtions.Remove(conditionalConsume)));
        }
コード例 #16
0
        private DynamicPropertyDescriptor GetPopulateCache(Object obj)
        {
            // Check if the method is already there
            Type target = obj.GetType();

            foreach (DynamicPropertyDescriptor desc in _cache)
            {
                if (desc.GetClazz() == target)
                {
                    return(desc);
                }
            }

            // need to add it
            using (_iLock.Acquire())
            {
                foreach (DynamicPropertyDescriptor desc in _cache)
                {
                    if (desc.GetClazz() == target)
                    {
                        return(desc);
                    }
                }

                // Lookup method to use
                MethodInfo method = DetermineMethod(target);

                // Cache descriptor and create fast method
                DynamicPropertyDescriptor propertyDescriptor;
                if (method == null)
                {
                    propertyDescriptor = new DynamicPropertyDescriptor(target, null, false);
                }
                else
                {
                    FastClass  fastClass  = FastClass.Create(target);
                    FastMethod fastMethod = fastClass.GetMethod(method);
                    propertyDescriptor = new DynamicPropertyDescriptor(target, fastMethod, fastMethod.ParameterCount > 0);
                }
                _cache.Add(propertyDescriptor);
                return(propertyDescriptor);
            }
        }
コード例 #17
0
        /// <summary>
        /// NOTE: Code-generation-invoked method, method name and parameter order matters
        /// </summary>
        /// <param name="clazz">class</param>
        /// <param name="method">method</param>
        /// <param name="cache">cache</param>
        /// <returns>descriptor</returns>
        public static DynamicPropertyDescriptorByMethod DynamicPropertyCacheAdd(
            Type clazz,
            MethodInfo method,
            CopyOnWriteList <DynamicPropertyDescriptorByMethod> cache)
        {
            DynamicPropertyDescriptorByMethod propertyDescriptor;

            if (method == null)
            {
                propertyDescriptor = new DynamicPropertyDescriptorByMethod(clazz, null, false);
            }
            else
            {
                propertyDescriptor = new DynamicPropertyDescriptorByMethod(clazz, method, method.GetParameters().Length > 0);
            }

            cache.Add(propertyDescriptor);
            return(propertyDescriptor);
        }
コード例 #18
0
        private static DynamicPropertyDescriptor GetPopulateCache(CopyOnWriteList <DynamicPropertyDescriptor> cache, DynamicPropertyGetterBase dynamicPropertyGetterBase, Object obj, EventAdapterService eventAdapterService)
        {
            // Check if the method is already there
            var target = obj.GetType();

            foreach (DynamicPropertyDescriptor desc in cache)
            {
                if (desc.Clazz == target)
                {
                    return(desc);
                }
            }

            // need to add it
            lock (dynamicPropertyGetterBase)
            {
                foreach (DynamicPropertyDescriptor desc in cache)
                {
                    if (desc.Clazz == target)
                    {
                        return(desc);
                    }
                }

                // Lookup method to use
                var method = dynamicPropertyGetterBase.DetermineMethod(target);

                // Cache descriptor and create fast method
                DynamicPropertyDescriptor propertyDescriptor;
                if (method == null)
                {
                    propertyDescriptor = new DynamicPropertyDescriptor(target, null, false);
                }
                else
                {
                    var fastClass  = FastClass.Create(target);
                    var fastMethod = fastClass.GetMethod(method);
                    propertyDescriptor = new DynamicPropertyDescriptor(target, fastMethod, fastMethod.ParameterCount > 0);
                }
                cache.Add(propertyDescriptor);
                return(propertyDescriptor);
            }
        }
コード例 #19
0
 public void CopyOnWriteList_Should_Allow_Parallel_Calls_To_Remove()
 {
     var actions = new List<Action>();
     var list = new CopyOnWriteList<int>();
     for (var i = 0; i < 100; i++)
     {
         list.Add(i);
     }
     Assert.AreEqual(100, list.Count);
     for (var i = 0; i < 100; i++)
     {
         var item = i;
         actions.Add(() =>
         {
             list.Remove(item);
         });
     }
     TestHelper.ParallelInvoke(actions);
     Assert.AreEqual(0, list.Count);
 }
コード例 #20
0
        public void Add_does_not_enumerate_added_items()
        {
            var list = new CopyOnWriteList <int> {
                1, 2, 3
            };
            var e = list.GetEnumerator();

            Assert.True(e.MoveNext());
            Assert.Equal(1, e.Current);

            // Adding an item should not cause concurrent modifications
            list.Add(4);
            Assert.DoesNotThrow(() => e.MoveNext());
            Assert.Equal(2, e.Current);

            Assert.True(e.MoveNext());
            Assert.Equal(3, e.Current);

            Assert.False(e.MoveNext());
        }
コード例 #21
0
 public void CopyOnWriteList_Should_Allow_Parallel_Calls_To_Add()
 {
     var actions = new List<Action>();
     var list = new CopyOnWriteList<int>();
     for (var i = 0; i < 100; i++)
     {
         var item = i;
         actions.Add(() =>
         {
             list.Add(item);
         });
     }
     TestHelper.ParallelInvoke(actions);
     Assert.AreEqual(100, list.Count);
     for (var i = 0; i < 100; i++)
     {
         Assert.True(list.Contains(i));
     }
     var counter = 0;
     CollectionAssert.AreEquivalent(Enumerable.Repeat(0, 100).Select(_ => counter++), list);
 }
コード例 #22
0
        public void Writes_to_original_are_not_visible_to_clones()
        {
            var items = new CopyOnWriteList <string>();

            items.Add("test");
            Assert.Equal("test", items[0]);

            var clone  = items.Clone();
            var clone2 = items.Clone();

            Assert.True(items.HasSameBacking(clone));
            Assert.True(items.HasSameBacking(clone2));

            items[0] = "no";

            Assert.False(items.HasSameBacking(clone));
            Assert.False(items.HasSameBacking(clone2));
            Assert.True(clone.HasSameBacking(clone2));

            Assert.Equal("test", clone[0]);
            Assert.Equal("test", clone2[0]);
        }
コード例 #23
0
 public IDisposable Subscribe(Action <object> consumer)
 {
     _subscribers.Add(consumer);
     EnsureWatching();
     return(new AnonymousDisposer(() => _subscribers.Remove(consumer)));
 }
コード例 #24
0
        public void Register_For_Events()
        {
            var receivedEvents = new CopyOnWriteList <CassandraEventArgs>();

            using (var connection = CreateConnection())
            {
                connection.Open().Wait();
                Query(connection, string.Format("DROP KEYSPACE IF EXISTS test_events_kp", 1)).Wait();
                var eventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange;
                var task       = connection.Send(new RegisterForEventRequest(eventTypes));
                TaskHelper.WaitToComplete(task, 1000);
                Assert.IsInstanceOf <ReadyResponse>(task.Result);
                connection.CassandraEventResponse += (o, e) =>
                {
                    receivedEvents.Add(e);
                };
                //create a keyspace and check if gets received as an event
                Query(connection, string.Format(TestUtils.CreateKeyspaceSimpleFormat, "test_events_kp", 1)).Wait(1000);

                TestHelper.RetryAssert(
                    () =>
                {
                    Assert.Greater(receivedEvents.Count, 0);
                    var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                    var createdEvent = evs.SingleOrDefault(
                        e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                        string.IsNullOrEmpty(e.Table));
                    Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                },
                    100,
                    50);

                //create a table and check if gets received as an event
                Query(connection, string.Format(TestUtils.CreateTableAllTypes, "test_events_kp.test_table", 1)).Wait(1000);
                TestHelper.RetryAssert(
                    () =>
                {
                    Assert.Greater(receivedEvents.Count, 0);
                    var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                    var createdEvent = evs.SingleOrDefault(
                        e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                        e.Table == "test_table");
                    Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                },
                    100,
                    50);

                if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1"), Comparison.GreaterThanOrEqualsTo))
                {
                    Query(connection, "CREATE TYPE test_events_kp.test_type (street text, city text, zip int);").Wait(1000);
                    TestHelper.RetryAssert(
                        () =>
                    {
                        Assert.Greater(receivedEvents.Count, 0);
                        var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                        var createdEvent = evs.SingleOrDefault(
                            e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                            e.Type == "test_type");
                        Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                    },
                        100,
                        50);
                }
            }
        }
コード例 #25
0
 public override void AddHandler(object callableObject, Delegate handler)
 {
     Assert.NotNull(handler);
     _handlers.Add(new KeyValuePair <object, object>(callableObject, handler));
 }
コード例 #26
0
 public override void AddHandler(object callableObject, Delegate handler)
 {
     Assert.NotNull(handler);
     _handlers.Add(new KeyValuePair <WeakReference, WeakReference>(new WeakReference(callableObject), new WeakReference(handler)));
 }