示例#1
0
 private void OnAppDomainUnload(object unusedObject, EventArgs unusedEventArgs)
 {
     try
     {
         System.Threading.Thread.GetDomain().DomainUnload -= LegacyProvider.s_onAppDomainUnload;
         if (_cache != null)
         {
             lock (s_dataLock)
             {
                 s_cacheNeedInit = true;
                 _cache.Dispose();
                 _cache = null;
             }
         }
         if (_logs)
         {
             NCacheLog.Info(" disposed");
         }
     }
     catch (Exception exc)
     {
         RaiseException(exc);
     }
     finally
     {
     }
 }
示例#2
0
        protected DistributionMaps GetMapsOnNodeJoining(DistributionInfoData distInfoData)
        {
            if (NCacheLog.IsInfoEnabled)
            {
                NCacheLog.Info("DistributionMgr.GetMapsOnNodeJoining()", "Total Data Size : " + TotalDataSize.ToString());
            }
            ArrayList tmpMap = null;
            Hashtable bucketsOwnershipMap = null;
            ArrayList partitionNodes      = new ArrayList();

            ArrayList newHashMap = DistributeHashMap.BalanceBuckets(distInfoData, _lastCreatedHashMap, _bucketsStats, _existingMembers, _cacheSizePerNode, NCacheLog);

            _existingMembers.Add(distInfoData.AffectedNode.NodeAddress);

            tmpMap = ChangeOwnerShip(newHashMap, distInfoData.AffectedNode.NodeAddress);

            _lastCreatedHashMap = tmpMap.Clone() as ArrayList;

            bucketsOwnershipMap = GetBucketsOwnershipMap(_lastCreatedHashMap);
            if (NCacheLog.IsInfoEnabled)
            {
                NCacheLog.Info("DistributionMgr.GetMaps()", "Sending new map as a new node joined the cluster");
            }
            return(new DistributionMaps(_lastCreatedHashMap, bucketsOwnershipMap));
        }
示例#3
0
        /// <summary>
        /// Stop notification listening
        /// </summary>
        public override void Stop()
        {
            try
            {
                // As the notify once is set to false, we have to remove registered notification
                // so change notifications are no longer sent.
                OracleConnection connection = (OracleConnection)base._connectionPool.GetConnection(base._connString);
                if (connection != null)
                {
                    this._oracleDep.RemoveRegistration(connection);
                }

                this._rowids.Clear();
            }
            catch (InvalidOperationException)
            {
                // Notification registration is in an unregistered state
            }
            catch (Exception exc)
            {
                NCacheLog.Error("NotificationBasedDependencyManager.OracleDependencyListener", exc.ToString());
            }
            finally
            {
                base.Stop();
            }
        }
示例#4
0
 /// <summary>
 /// Verifies whether a given node is the permanent owner of the bucket or not
 /// </summary>
 /// <param name="bucketId"></param>
 /// <param name="perOwner"></param>
 /// <returns></returns>
 public bool VerifyPermanentOwnership(int bucketId, Address perOwner)
 {
     try
     {
         if (perOwner != null)
         {
             Sync.AcquireReaderLock(Timeout.Infinite);
             try
             {
                 lock (InstalledHashMap.SyncRoot)
                 {
                     HashMapBucket bucket = (HashMapBucket)InstalledHashMap[bucketId];
                     return(perOwner.Equals(bucket.TempAddress));
                 }
             }
             finally
             {
                 Sync.ReleaseReaderLock();
             }
         }
     }
     catch (Exception e)
     {
         NCacheLog.Error("DistributionMgr.VerifyPermanentOwnership", e.ToString());
     }
     return(false);
 }
示例#5
0
        /// <summary>
        /// Removes all entries from the store.
        /// </summary>
        internal override void ClearInternal()
        {
            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            _cacheStore.Clear();

            _topicManager.Clear();

            _context.PerfStatsColl.SetCacheSize(0); // on clear cache cachesize set to zero

            if (_evictionThread != null)
            {
                NCacheLog.Flush();
#if !NETCORE
                _evictionThread.Abort();
#elif NETCORE
                _evictionThread.Interrupt();
#endif
            }

            if (_evictionPolicy != null)
            {
                _evictionPolicy.Clear();

                if (_context.PerfStatsColl != null)
                {
                    _context.PerfStatsColl.SetEvictionIndexSize(_evictionPolicy.IndexInMemorySize);
                }
            }
        }
示例#6
0
        public void RemoveSyncData()
        {
            if (_cacheID == null)
            {
                return;
            }

            try
            {
                _oledbConPool.RemoveSyncData(SYNC_TABLE, _cacheID);
            }
            catch (Exception e)
            {
                NCacheLog.Error("CacheDbSyncManager", e.ToString());
            }

            try
            {
                _sqlConPool.RemoveSyncData(SYNC_TABLE, _cacheID);
            }
            catch (Exception e)
            {
                NCacheLog.Error("CacheDbSyncManager", e.ToString());
            }
        }
示例#7
0
 /// <summary>
 /// Disposes of the resources (other than memory) used by the module that implements
 /// <see cref="System.Web.IHttpModule"/>.
 /// </summary>
 /// <remarks>
 /// Dispose performs any final cleanup work prior to removal of the module from
 /// the execution pipeline.
 /// </remarks>
 void IHttpModule.Dispose()
 {
     if (NCacheLog != null)
     {
         NCacheLog.Info("NSessionStateModule disposed");
     }
 }
示例#8
0
 private bool ReleaseSessionItemLock(string sessionid, object lockID)
 {
     try
     {
         _cache.Unlock(GetUniqueSessionId(sessionid));//, lockID);
         return(true);
     }
     catch (Exception)
     {
         try
         {
             _cache.Unlock(GetUniqueSessionId(sessionid));
             return(true);
         }
         catch (Exception e)
         {
             if (_detailedLogs)
             {
                 NCacheLog.Debug("ReleaseSessionItemLock failed ( " + sessionid + "). Exception = " + e.ToString());
             }
             RaiseException(e, sessionid);
         }
     }
     return(false);
 }
示例#9
0
        /// <summary>
        /// Called when items in cache expires
        /// </summary>
        /// <param name="key">Expired item key</param>
        /// <param name="value">Expired item value</param>
        /// <param name="reason">Reason of expiration</param>
        //private void OnItemRemoved(object key, object value, CacheItemRemovedReason reason)
        //{
        //    if (reason == CacheItemRemovedReason.Expired)
        //        _expireCallback.Invoke((string)key, _data);
        //}

        public void LogError(Exception exception, string sessionID)
        {
            try
            {
                if (sessionID == null)
                {
                    sessionID = "";
                }
                if (NCacheLog != null)
                {
                    NCacheLog.Error("[Error]", sessionID + " :" + exception);
                }
            }
            catch (Exception ex)
            {
                if (_writeExceptionsToEventLog)
                {
                    try
                    {
                        AppUtil.LogEvent(SOURCE, ex.ToString(), EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError);
                    }
                    catch (Exception exc)
                    {
                        throw new ProviderException(exc.Message, exc);
                    }
                }
            }
            RaiseException(exception, sessionID);
        }
示例#10
0
        /**<summary>
         * Inserts item in store.
         * When an items expires, its automatically been removed from cache, so we do not have
         * to check the expiration time, and simply an Insert call to cache will add the items if
         * its new or updates the item if it already exists, so newItem parameter is also useless
         * </summary>**/
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData items, object lockID, bool newItem)
        {
            try
            {
                PutInNCache(id, InsertContents(context, items, SessionStateActions.None, items.Timeout), lockID, true);
            }
            catch (Exception)
            {
                try
                {
                    if (_cache != null)
                    {
                        _cache.Remove(GetUniqueSessionId(id), true);
                    }
                }
                catch (Exception ex)
                {
                    if (_detailedLogs)
                    {
                        NCacheLog.Debug("SetAndReleaseItemExclusive failed ( " + id + "). Exception = " + ex.ToString());
                    }
                }

                try
                {
                    PutInNCache(id, InsertContents(context, items, SessionStateActions.None, items.Timeout), lockID, false);
                }
                catch (Exception exc)
                {
                    RaiseException(exc, id);
                }
            }
        }
示例#11
0
        /// <summary> Iterates through all the protocols <em>from top to bottom</em> and does the following:
        /// <ol>
        /// <li>Waits until all messages in the down queue have been flushed (ie., size is 0)
        /// <li>Calls stop() on the protocol
        /// </ol>
        /// </summary>
        public virtual void  stopStack()
        {
            if (timer != null)
            {
                try
                {
                    timer.Dispose();
                }
                catch (System.Exception ex)
                {
                    NCacheLog.Error("ProtocolStack.stopStack", "exception=" + ex);
                }
            }

            if (stopped)
            {
                return;
            }

            if (stop_promise == null)
            {
                stop_promise = new Promise();
            }
            else
            {
                stop_promise.Reset();
            }

            down(new Event(Event.STOP));
            stop_promise.WaitResult(5000);

            operational = false;
            stopped     = true;
        }
示例#12
0
        /// <summary>
        /// Remove the related record from ncache_db_sync table
        /// </summary>
        /// <returns></returns>
        private bool RemoveSyncData()
        {
            object[] tableInfo = new object[] { CacheDbSyncManager.SYNC_TABLE, _cacheName, _dbCacheKey };

            IDbCommand command = null;

            try
            {
                command             = _connection.CreateCommand();
                command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE CACHE_ID = '{1}' AND CACHE_KEY = '{2}'", tableInfo);
                command.CommandType = CommandType.Text;

                if (_connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                }

                command.ExecuteNonQuery();
                return(true);
            }
            catch (Exception ex)
            {
                NCacheLog.Error("DBCacheDependency", ex.ToString());
                return(false);
            }
            finally
            {
                if (command != null)
                {
                    command.Dispose();
                    command = null;
                }
            }
        }
示例#13
0
        /// <summary>
        /// Locks the buckets which are under the process of state transfer. A locked
        /// bucket can not be assigned to a node while loadbalancing. Only a coordinator
        /// node can lock the buckets.
        /// </summary>
        /// <param name="buckets"></param>
        /// <param name="requestingNode"></param>
        /// <returns></returns>
        public virtual Hashtable LockBuckets(ArrayList buckets, Address requestingNode)
        {
            ArrayList lockAcquired = new ArrayList();
            ArrayList ownerChanged = new ArrayList();

            Hashtable result = new Hashtable();

            Sync.AcquireWriterLock(Timeout.Infinite);
            try
            {
                if (buckets != null)
                {
                    IEnumerator ie = buckets.GetEnumerator();
                    while (ie.MoveNext())
                    {
                        lock (InstalledHashMap.SyncRoot)
                        {
                            HashMapBucket bucket = (HashMapBucket)InstalledHashMap[(int)ie.Current];

                            if (requestingNode.Equals(bucket.TempAddress))
                            {
                                if (NCacheLog.IsInfoEnabled)
                                {
                                    NCacheLog.Info("DistributionMgr.lockbuckets", "acquired locked on bucket [" + bucket.BucketId + "] by " + requestingNode);
                                }

                                bucket.Status = BucketStatus.UnderStateTxfr;
                                if (!lockAcquired.Contains(ie.Current))
                                {
                                    lockAcquired.Add(ie.Current);
                                }
                            }
                            else if (!ownerChanged.Contains(ie.Current))
                            {
                                if (NCacheLog.IsInfoEnabled)
                                {
                                    NCacheLog.Info("DistributionMgr.lockbuckets", "bucket [" + bucket.BucketId + "] owner ship is changed; new owner is " + bucket.TempAddress);
                                }
                                ownerChanged.Add(ie.Current);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                NCacheLog.Error("DistributionMgr.lockbuckets", e.ToString());
                return(result);
            }
            finally
            {
                Sync.ReleaseWriterLock();
            }
            result[BucketLockResult.OwnerChanged] = ownerChanged;
            result[BucketLockResult.LockAcquired] = lockAcquired;

            return(result);
        }
示例#14
0
        public void UpdateBucketStats(NodeInfo localNode)
        {
            try
            {
                Sync.AcquireWriterLock(Timeout.Infinite);

                if (localNode == null)
                {
                    return;
                }

                if (_bucketsStats == null)
                {
                    _bucketsStats = new Hashtable();
                }

                if (localNode.Statistics != null && localNode.Statistics.LocalBuckets != null)
                {
                    Hashtable bucketStats = localNode.Statistics.LocalBuckets.Clone() as Hashtable;
                    if (bucketStats != null)
                    {
                        IDictionaryEnumerator ide = bucketStats.GetEnumerator();
                        while (ide.MoveNext())
                        {
                            //muds:
                            //see if this node is the permanent owner of the bucket
                            //otherwise its quite possible that we override the
                            //stats of the bucket from the temporary owner.
                            HashMapBucket bucket = (HashMapBucket)_installedHashMap[(int)ide.Key];
                            if (bucket.PermanentAddress.Equals(localNode.Address))
                            {
                                BucketStatistics stats = ide.Value as BucketStatistics;
                                _bucketsStats[ide.Key] = ide.Value;
                            }
                            else
                            {
                            }
                        }
                    }

                    if (NCacheLog.IsInfoEnabled)
                    {
                        NCacheLog.Info("DistributionMgr.UpdateBucketStats()", "bucketStats = " + _bucketsStats == null ? "null" : _bucketsStats.Count.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                if (NCacheLog.IsErrorEnabled)
                {
                    NCacheLog.Error("DistributionMgr.UpdateBucketStats()", e.ToString());
                }
            }
            finally
            {
                Sync.ReleaseWriterLock();
            }
        }
示例#15
0
        private void InitializeCache()
        {
            lock (s_dataLock)
            {
                try
                {
                    if (_cache == null)
                    {
                        LegacyProvider.s_onAppDomainUnload = new EventHandler(OnAppDomainUnload);
                        System.Threading.Thread.GetDomain().DomainUnload += LegacyProvider.s_onAppDomainUnload;

                        if (_logs || _detailedLogs)
                        {
                            if (_ncacheLog == null)
                            {
                                _ncacheLog = new NCacheLogger();
                                _ncacheLog.Initialize(LoggerNames.SessionStoreProvider, _cacheId);

                                if (_detailedLogs)
                                {
                                    NCacheLog.SetLevel("all");
                                }
                                else
                                {
                                    if (_logs)
                                    {
                                        NCacheLog.SetLevel("info");
                                    }
                                }
                            }
                        }
                        if (_isLocationAffinityEnabled)
                        {
                            _cache = new RegionalCache(_ncacheLog, NCacheSessionStateConfigReader.LoadSessionLocationSettings());
                        }
                        else
                        {
                            _cache = new SingleRegionCache(_operationRetry, _operationRetryInterval);
                        }

                        _cache.InitializeCache(_cacheId);
                        _cache.ExceptionsEnabled = true;
                        s_cacheNeedInit          = false;
                        if (_logs)
                        {
                            NCacheLog.Info("NSessionStoreProvider initialized");
                        }
                        Thread.Sleep(_inprocDelay);
                    }
                }
                catch (Exception exc)
                {
                    _cache = null; // so that next time cache can be initialized. Check the above condition if(_cache == null)
                    RaiseException(exc);
                }
            }
        }
示例#16
0
        public void RemoveDependency(object key, CacheSyncDependency dependency)
        {
            if (_context.IsDbSyncCoordinator)
            {
                if (dependency == null)
                {
                    return;
                }
                try
                {
                    SyncItem item = new SyncItem(key, dependency.Key, dependency.CacheId);

                    lock (_dependenciesStatus.SyncRoot)
                    {
                        if (_dependenciesKeyMap.Contains(item))
                        {
                            ClusteredArrayList dependentKeys = _dependenciesKeyMap[item] as ClusteredArrayList;
                            if (dependentKeys != null)
                            {
                                dependentKeys.Remove(key);
                                if (dependentKeys.Count > 0)
                                {
                                    return;
                                }
                            }
                            _dependenciesKeyMap.Remove(item);
                        }

                        if (_dependenciesStatus.Contains(item))
                        {
                            _dependenciesStatus.Remove(item);
                        }
                        else
                        {
                            return;
                        }
                    }
                    ISyncCache syncCache = _synCaches[item.CacheId] as ISyncCache;
                    ISyncCacheEventsListener listener = _listeners[item.CacheId] as ISyncCacheEventsListener;
                    if (syncCache != null && listener != null)
                    {
                        syncCache.UnRegisterSyncKeyNotifications((string)item.Key, listener);
                    }
                }
                catch (Exception e)
                {
                    NCacheLog.Error("CacheSyncManager:", e.ToString());
                }
            }
            else
            {
                lock (_inactiveDependencies.SyncRoot)
                {
                    _inactiveDependencies.Remove(key);
                }
            }
        }
示例#17
0
        /// <summary>
        /// Initializes the counter instances and category.
        /// </summary>
        public void InitializePerfCounters(bool enableDebuggingCounters)
        {
            try
            {
                if (!UserHasAccessRights)
                {
                    return;
                }

                lock (this)
                {
                    string instname = _instanceName;

                    _instanceName = instname;
                    if (enableDebuggingCounters)
                    {
                        _pcTcpDownQueueCount   = new PerformanceCounter(PC_CATEGORY, "TcpDownQueueCount", _instanceName, false);
                        _pcTcpUpQueueCount     = new PerformanceCounter(PC_CATEGORY, "TcpUpQueueCount", _instanceName, false);
                        _pcBcastQueueCount     = new PerformanceCounter(PC_CATEGORY, "BcastQueueCount", _instanceName, false);
                        _pcMcastQueueCount     = new PerformanceCounter(PC_CATEGORY, "McastQueueCount", _instanceName, false);
                        _pcSocketSendTime      = new PerformanceCounter(PC_CATEGORY, "Socket send time (msec)", _instanceName, false);
                        _pcSocketSendSize      = new PerformanceCounter(PC_CATEGORY, "Socket send size (bytes)", _instanceName, false);
                        _pcSocketReceiveTime   = new PerformanceCounter(PC_CATEGORY, "Socket recv time (msec)", _instanceName, false);
                        _pcSocketReceiveSize   = new PerformanceCounter(PC_CATEGORY, "Socket recv size (bytes)", _instanceName, false);
                        _pcNagglingMsgCount    = new PerformanceCounter(PC_CATEGORY, "NaglingMsgCount", _instanceName, false);
                        _pcBytesSentPerSec     = new PerformanceCounter(PC_CATEGORY, "Bytes sent/sec", _instanceName, false);
                        _pcBytesReceivedPerSec = new PerformanceCounter(PC_CATEGORY, "Bytes received/sec", _instanceName, false);
                    }

                    _pcClusteredOperationsPerSec = new PerformanceCounter(PC_CATEGORY, "Cluster ops/sec", _instanceName, false);

                    if (System.Configuration.ConfigurationSettings.AppSettings["printClusterStats"] != null)
                    {
                        bool printStats = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["printClusterStats"]);
                        if (printStats)
                        {
                            if (System.Configuration.ConfigurationSettings.AppSettings["statsPrintInterval"] != null)
                            {
                                _printInterval = new TimeSpan(Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["statsPrintInterval"]), 0, 0);
                            }

                            _logger = new Logs();
                            _logger.Initialize(instname + ".clstats", "ClusterPerfMonStats");

                            _printThread = new Thread(new ThreadStart(PrintStats));
                            _printThread.Start();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                NCacheLog.Warn("PerfStatsCollector.PerfStatsCollector()    " + e.Message);
            }
        }
示例#18
0
 public override void  down(Event evt)
 {
     if (top_prot != null)
     {
         top_prot.receiveDownEvent(evt);
     }
     else
     {
         NCacheLog.Error("ProtocolStack", "no down protocol available !");
     }
 }
示例#19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="newMap"></param>
        /// <param name="newBucketsOwnershipMap"></param>
        /// <param name="leftMbrs"></param>
        public void InstallHashMap(DistributionMaps distributionMaps, ArrayList leftMbrs)
        {
            ArrayList newMap = null;
            Hashtable newBucketsOwnershipMap = null;

            _sync.AcquireWriterLock(Timeout.Infinite);
            try
            {
                if (distributionMaps == null)
                {
                    return;
                }

                newMap = distributionMaps.Hashmap;
                newBucketsOwnershipMap = distributionMaps.BucketsOwnershipMap;

                if (newMap == null || newBucketsOwnershipMap == null)
                {
                    return;
                }

                if (_installedHashMap != null)
                {
                    for (int i = 0; i < newMap.Count; i++)
                    {
                        HashMapBucket newBucket = (HashMapBucket)newMap[i];
                        int           index     = _installedHashMap.IndexOf(newBucket);
                        HashMapBucket oldBucket = (HashMapBucket)_installedHashMap[index];

                        if (!oldBucket.PermanentAddress.Equals(newBucket.PermanentAddress) && oldBucket.TempAddress.Equals(newBucket.TempAddress))
                        {
                            NCacheLog.Error("Install Hasmap", "BucketID: " + index.ToString() + "\toldBucket: " + oldBucket.PermanentAddress.ToString() + "\toldBucket.Temp: " + oldBucket.TempAddress.ToString() + "\tnewBucket: " + newBucket.PermanentAddress.ToString() + "\tnewBucekt.Temp: " + newBucket.TempAddress.ToString());
                        }
                        else
                        {
                            oldBucket.PermanentAddress = newBucket.PermanentAddress;
                            oldBucket.TempAddress      = newBucket.TempAddress;
                            oldBucket.Status           = newBucket.Status;
                        }
                    }
                }
                else
                {
                    _installedHashMap = newMap;
                }
                _bucketsOwnershipMap = newBucketsOwnershipMap;

                NotifyBucketUpdate();
            }
            finally
            {
                _sync.ReleaseWriterLock();
            }
        }
示例#20
0
 /// <summary>
 /// Called when an existing member leaves the group.
 /// </summary>
 /// <param name="address">address of the joining member</param>
 /// <returns>true if the node left successfuly</returns>
 internal virtual int OnMemberLeft(Address address, Hashtable bucketsOwnershipMap)
 {
     if (_members.Contains(address))
     {
         NCacheLog.Warn("SubCluster.OnMemberJoined()", "Memeber " + address + " left sub-cluster " + _groupid);
         _members.Remove(address);
         _servers.Remove(address);
         return(_members.Count);
     }
     return(-1);
 }
示例#21
0
 internal void RaiseException(Exception exc)
 {
     if (NCacheLog != null)
     {
         NCacheLog.Error(exc.ToString());
     }
     if (this.ExceptionsEnabled)
     {
         throw exc;
     }
 }
示例#22
0
        private void InitializeCache()
        {
            lock (s_dataLock)
            {
                try
                {
                    //if (StaticLogs.IsWriterNull && _logs) StaticLogs.Initialize(_cacheId, "SessionStoreProvider");

                    if (_cache == null)
                    {
                        if (_logs || _detailedLogs)
                        {
                            if (_ncacheLog == null)
                            {
                                string logFileNmae = _cacheId;

                                _ncacheLog = new NCacheLogger();
                                _ncacheLog.Initialize(LoggerNames.SessionStoreProvider, logFileNmae);

                                if (_detailedLogs)
                                {
                                    NCacheLog.SetLevel("all");
                                }
                                else
                                {
                                    if (_logs)
                                    {
                                        NCacheLog.SetLevel("info");
                                    }
                                }
                            }
                        }

                        _cache = new SingleRegionCache(_operationRetry, _operationRetryInterval);

                        _cache.InitializeCache(_cacheId);
                        s_cacheNeedInit = false;
                        OnCacheInitialize();
                        if (_logs)
                        {
                            LogInfo("NSessionStoreProvider initialized", null);
                        }
                        Thread.Sleep(_inprocDelay);
                    }
                }
                catch (Exception exc)
                {
                    _cache = null; //taimoor: so that next time cache can be initialized. Check the above condition if(_cache == null)
                    LogError(exc, null);
                }
            }
        }
示例#23
0
        private void SendPollRequestTask()
        {
            try
            {
                // Waiting 30 minutes to declare a client dead.
                // No of notifications to be sent in 30 minutes
                float deadClientTest = (float)_deadClientInterval / _pollRequestInterval;

                HPTime lastDeadClientCheckTime = HPTime.Now;
                bool   looped = false;
                while (!_isDisposing)
                {
                    try
                    {
                        for (float i = 0; i < deadClientTest; i++)
                        {
                            looped = true;
                            if (_isDisposing)
                            {
                                break;
                            }
                            SendPollRequest();
                            lock (this)
                            {
                                Monitor.Wait(this, _pollRequestInterval);
                            }
                        }

                        if (looped)
                        {
                            CleanDeadClients(lastDeadClientCheckTime);
                        }

                        lastDeadClientCheckTime = HPTime.Now;
                    }
                    catch (ThreadAbortException)
                    {
                        break;
                    }
                    catch (ThreadInterruptedException)
                    {
                        break;
                    }
                }
            }
            catch (ThreadAbortException) { }
            catch (ThreadInterruptedException) { }
            catch (Exception e)
            {
                NCacheLog.Error("PullBasedNotificationManager.SendPollRequest", e.ToString());
            }
        }
示例#24
0
        /// <summary>
        /// Returns the location identifier for this HttpRequest context. Response cookies are searched first
        /// and if no cookie is found then Requeset cookies are searched for location identifier.
        /// If there isno cookie in Request or Response then the Location Identifier in the SessionId id returned.
        /// </summary>
        /// <param name="context">Context of current HttpRequest</param>
        /// <param name="sessionId">SessionId for the Request</param>
        /// <returns>Location Identifer if cookie is found other wise the sessionId is returned.</returns>
        private string GetLocationID(HttpContext context, string sessionId)
        {
            string locationID = sessionId;

            if (_isLocationAffinityEnabled)
            {
                try
                {
                    if (context.Response.Cookies.Get(LOC_IDENTIFIER) == null)
                    {
                        context.Response.Cookies.Remove(LOC_IDENTIFIER);
                    }
                    else if (string.IsNullOrEmpty(context.Response.Cookies.Get(LOC_IDENTIFIER).Value))
                    {
                        context.Response.Cookies.Remove(LOC_IDENTIFIER);
                    }
                    else
                    {
                        if (NCacheLog != null)
                        {
                            NCacheLog.Info(sessionId + " :" + "New Location in Response Cookie = " + context.Response.Cookies.Get(LOC_IDENTIFIER).Value);
                        }
                        return(context.Response.Cookies.Get(LOC_IDENTIFIER).Value);
                    }

                    if (context.Request.Cookies.Get(LOC_IDENTIFIER) == null)
                    {
                        context.Request.Cookies.Remove(LOC_IDENTIFIER);
                    }
                    else if (string.IsNullOrEmpty(context.Request.Cookies.Get(LOC_IDENTIFIER).Value))
                    {
                        context.Request.Cookies.Remove(LOC_IDENTIFIER);
                    }
                    else
                    {
                        if (NCacheLog != null)
                        {
                            NCacheLog.Info(sessionId + " :" + "New Location in Request Cookie = " + context.Request.Cookies.Get(LOC_IDENTIFIER).Value);
                        }
                        return(context.Request.Cookies.Get(LOC_IDENTIFIER).Value);
                    }
                }
                catch (Exception e)
                {
                    if (NCacheLog != null)
                    {
                        NCacheLog.Error(sessionId + " :" + e.ToString());
                    }
                }
            }
            return(locationID);
        }
示例#25
0
        public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeOut)
        {
            SessionStateStoreData data = new SessionStateStoreData(new SessionStateItemCollection(),
                                                                   SessionStateUtility.GetSessionStaticObjects(context),
                                                                   timeOut);

            if (_detailedLogs)
            {
                NCacheLog.Debug("New data object created to be used for current request");
            }

            return(data);
        }
示例#26
0
        private void PrintStats()
        {
            while (_printThread != null)
            {
                try
                {
                    if (_logger != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("[ print_interval :" + _printInterval);

                        if (_pcBcastQueueCount != null)
                        {
                            sb.Append(" ; BCastQueueCount : " + _pcBcastQueueCount.RawValue);
                        }

                        if (_pcBcastQueueCount != null)
                        {
                            sb.Append(" ; TcpDownQueueCount : " + _pcTcpDownQueueCount.RawValue);
                        }

                        if (_pcBcastQueueCount != null)
                        {
                            sb.Append(" ; TcpUpQueueCount : " + _pcTcpUpQueueCount.RawValue);
                        }

                        if (_pcBcastQueueCount != null)
                        {
                            sb.Append(" ; MCastQueueCount : " + _pcMcastQueueCount.RawValue);
                        }

                        sb.Append(" ]");

                        _logger.WriteLogEntry("ClStatsCollector.PrintStats", sb.ToString());
                        System.Threading.Thread.Sleep(_printInterval);
                    }
                }
                catch (ThreadInterruptedException ti)
                {
                    break;
                }
                catch (ThreadAbortException te)
                {
                    break;
                }
                catch (Exception e)
                {
                    NCacheLog.Error("ClusterStatsCollector.PrintStats", e.ToString());
                }
            }
        }
示例#27
0
        /// <summary>
        /// Set the status of the bucket to state transfer and in this way this
        /// bucket becomes locked. A locked bucket can not be assigned during
        /// loadbalancing.
        /// </summary>
        /// <param name="buckets"></param>
        /// <param name="node"></param>
        public void ChangeBucketStatusToStateTransfer(ArrayList buckets, Address node)
        {
            Sync.AcquireWriterLock(Timeout.Infinite);
            try
            {
                if (buckets != null)
                {
                    IEnumerator ie = buckets.GetEnumerator();
                    while (ie.MoveNext())
                    {
                        lock (InstalledHashMap.SyncRoot)
                        {
                            HashMapBucket bucket = (HashMapBucket)InstalledHashMap[(int)ie.Current];
                            if (node.Equals(bucket.TempAddress))
                            {
                                bucket.Status = BucketStatus.UnderStateTxfr;

                                if (NCacheLog.IsInfoEnabled)
                                {
                                    NCacheLog.Info("DistributionMgr.ChangeBucketStatus", bucket.ToString());
                                }
                            }
                        }
                    }

                    if (_bucketsOwnershipMap != null)
                    {
                        ArrayList nodeBuckets = _bucketsOwnershipMap[node] as ArrayList;
                        if (nodeBuckets != null)
                        {
                            foreach (int bucketId in buckets)
                            {
                                int indexOfBucket = nodeBuckets.IndexOf(new HashMapBucket(null, bucketId));
                                if (indexOfBucket != -1)
                                {
                                    HashMapBucket bucket = nodeBuckets[indexOfBucket] as HashMapBucket;
                                    if (node.Equals(bucket.TempAddress))
                                    {
                                        bucket.Status = BucketStatus.UnderStateTxfr;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                Sync.ReleaseWriterLock();
            }
        }
示例#28
0
 /// <summary>
 /// Adds the Current Primary cache's location identifier in the Response cookie collection.
 /// </summary>
 /// <param name="context">Context of current HttpRequest.</param>
 private void UpdateCookies(HttpContext context)
 {
     if (_cache != null)
     {
         if (!string.IsNullOrEmpty(_cache.PrimaryPrefix))
         {
             context.Response.Cookies.Set(new HttpCookie(LOC_IDENTIFIER, _cache.PrimaryPrefix));
             if (_logs)
             {
                 NCacheLog.Info("Session Location Changed: New_Location=" + _cache.PrimaryPrefix);
             }
         }
     }
 }
示例#29
0
        /// <summary>
        /// Initializes the counter instances and category.
        /// </summary>
        public void InitializePerfCounters(bool enableDebuggingCounters)
        {
#if NETCORE
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux))
            {
                return;
            }
#endif
            try
            {
                if (!UserHasAccessRights)
                {
                    return;
                }

                lock (this)
                {
                    string instname = _instanceName;

                    _instanceName = instname;
                    if (enableDebuggingCounters)
                    {
                        _pcTcpDownQueueCount   = new PerformanceCounter(PC_CATEGORY, "TcpDownQueueCount", _instanceName, false);
                        _pcTcpUpQueueCount     = new PerformanceCounter(PC_CATEGORY, "TcpUpQueueCount", _instanceName, false);
                        _pcBcastQueueCount     = new PerformanceCounter(PC_CATEGORY, "BcastQueueCount", _instanceName, false);
                        _pcMcastQueueCount     = new PerformanceCounter(PC_CATEGORY, "McastQueueCount", _instanceName, false);
                        _pcSocketSendTime      = new PerformanceCounter(PC_CATEGORY, "Socket send time (msec)", _instanceName, false);
                        _pcSocketSendSize      = new PerformanceCounter(PC_CATEGORY, "Socket send size (bytes)", _instanceName, false);
                        _pcSocketReceiveTime   = new PerformanceCounter(PC_CATEGORY, "Socket recv time (msec)", _instanceName, false);
                        _pcSocketReceiveSize   = new PerformanceCounter(PC_CATEGORY, "Socket recv size (bytes)", _instanceName, false);
                        _pcBytesSentPerSec     = new PerformanceCounter(PC_CATEGORY, "Bytes sent/sec", _instanceName, false);
                        _pcBytesReceivedPerSec = new PerformanceCounter(PC_CATEGORY, "Bytes received/sec", _instanceName, false);
                    }

                    _pcClusteredOperationsPerSec = new PerformanceCounter(PC_CATEGORY, "Cluster ops/sec", _instanceName, false);

                    _printInterval = ServiceConfiguration.StatsPrintInterval;

                    _logger = new Logs();
                    _logger.Initialize(instname + ".clstats", "ClusterPerfMonStats");

                    _printThread = new Thread(new ThreadStart(PrintStats));
                    _printThread.Start();
                }
            }
            catch (Exception e)
            {
                NCacheLog.Warn("PerfStatsCollector.PerfStatsCollector()    " + e.Message);
            }
        }
示例#30
0
        private Address SelectNodeInternal(string key)
        {
            int hashCode = AppUtil.GetHashCode(key);
            int index    = hashCode / this.BucketSize;

            if (index < 0)
            {
                index = index * -1;
            }

            _sync.AcquireReaderLock(Timeout.Infinite);

            try
            {
                if (_installedHashMap != null)
                {
                    HashMapBucket bucket = _installedHashMap[index] as HashMapBucket;
                    if (bucket != null)
                    {
                        //if (bucket.Status != BucketStatus.Functional)
                        {
                            /// This is special case that handles operations during stateTransfer.
                            /// If a bucket is not yet transfered to the new coordinator from the replica. then
                            /// the replica's address is returned.
                            Address   coordinatorNodeAddress = bucket.TempAddress; // this should be the sub-coordinator addres
                            ArrayList ownershipMap           = _bucketsOwnershipMap[coordinatorNodeAddress] as ArrayList;
                            if (ownershipMap == null)
                            {
                                NCacheLog.Warn("DistributionManager.SelectNodeInternal()", "ownershipMap is null. Returning permanent address of bucket.");
                                return(bucket.PermanentAddress);
                            }
                            int indexOfOwnedBucket = ownershipMap.IndexOf(bucket);

                            if (indexOfOwnedBucket != -1)
                            {
                                HashMapBucket ownedBucket = ownershipMap[indexOfOwnedBucket] as HashMapBucket;
                                return(ownedBucket.PermanentAddress);
                            }
                        }
                        return(bucket.PermanentAddress);
                    }
                }
                return(null);
            }
            finally
            {
                _sync.ReleaseReaderLock();
            }
        }