Exemple #1
0
        internal override void TouchInternal(string key, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.Touch", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            CacheEntry e = (CacheEntry)_cacheStore.Get(key);

            if (e != null)
            {
                EvictionHint evh = e.EvictionHint;
                if (_evictionPolicy != null && evh != null && evh.IsVariant)
                {
                    _evictionPolicy.Notify(key, evh, null);
                }
                ExpirationHint exh = e.ExpirationHint;
                if (exh != null && exh.IsVariant)
                {
                    try
                    {
                        _context.ExpiryMgr.ResetVariant(exh);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Special purpose internal method. Derived classes don't override this method.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isUserOperation"></param>
        /// <returns></returns>
        internal override CacheEntry GetEntryInternal(object key, bool isUserOperation)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.GetInternal", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            CacheEntry e = (CacheEntry)_cacheStore.Get(key);

            if (e == null)
            {
                return(e);
            }

            EvictionHint evh = e.EvictionHint;

            if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant)
            {
                _evictionPolicy.Notify(key, evh, null);
            }

            return(e);
        }
Exemple #3
0
        /// <summary>
        /// Special purpose internal method. Derived classes don't override this method.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isUserOperation"></param>
        /// <returns></returns>
        internal override CacheEntry GetEntryInternal(object key, bool isUserOperation, OperationContext operationContext, bool cloneCacheEntry, bool needUserPayload)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.GetInternal", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            CacheEntry e = (CacheEntry)_cacheStore.Get(key);

            if (e == null)
            {
                return(e);
            }

            EvictionHint evh = e.EvictionHint;

            if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant)
            {
                _evictionPolicy.Notify(key, evh, null);
            }
            e.MarkInUse(NCModulesConstants.Global);

            if (cloneCacheEntry)
            {
                e = e.DeepClone(operationContext.UseObjectPool ? _context.TransactionalPoolManager : _context.FakeObjectPool);
            }

            return(e);
        }
        /// <summary>
        /// Add the key and entry in the Hashtable for Invalidation by preodic thread.
        /// </summary>
        /// <param name="key">The key of the item to invalidate.</param>
        /// <param name="entry">CacheEntry to Invalidate.</param>
        internal void EnqueueOperation(object key, ReplicationOperation operation)
        {
            try
            {
                if (key == null)
                {
                    key = System.Guid.NewGuid().ToString() + Interlocked.Increment(ref _uniqueKeyNumber);
                }

                _queue.Enqueue(key, operation);

                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("AsyncReplicator.Enque", "queue_size :" + _queue.Count);
                }

                _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count);
            }
            catch (Exception e)
            {
                if (_context.NCacheLog.IsErrorEnabled)
                {
                    _context.NCacheLog.Error("AsyncItemReplicator", string.Format("Exception: {0}", e.ToString()));
                }
            }
        }
Exemple #5
0
        protected Hashtable Clustered_Insert(ArrayList dests, object[] keys, CacheEntry[] cacheEntries, OperationContext operationContext)
        {
            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.InsertBlk", "enter");
                }
                /// Ask every server to update the object, except myself.
                Function func    = new Function((int)OpCodes.Insert, new object[] { keys, cacheEntries, operationContext }, false);
                RspList  results = Cluster.BroadcastToMultiple(dests,
                                                               func,
                                                               GroupRequest.GET_ALL);

                ClusterHelper.ValidateResponses(results, typeof(Hashtable), Name);

                /// Check if the operation failed on any node.
                return(ClusterHelper.FindAtomicBulkInsertStatusReplicated(results));
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.InsertBlk", "exit");
                }
            }
        }
Exemple #6
0
 protected void Clustered_UnLock(object key, object lockId, bool isPreemptive, OperationContext operationContext)
 {
     try
     {
         if (ServerMonitor.MonitorActivity)
         {
             ServerMonitor.LogClientActivity("RepCacheBase.Unlock", "enter");
         }
         Function func = new Function((int)OpCodes.UnLockKey, new object[] { key, lockId, isPreemptive, operationContext }, false);
         Cluster.BroadcastToMultiple(Cluster.Servers,
                                     func,
                                     GroupRequest.GET_ALL);
     }
     catch (Exception e)
     {
         throw;
     }
     finally
     {
         if (ServerMonitor.MonitorActivity)
         {
             ServerMonitor.LogClientActivity("RepCacheBase.Unlock", "exit");
         }
     }
 }
Exemple #7
0
        /// <summary>
        /// Remove the objects from the cluster.
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="keys">keys of the entries.</param>
        /// <param name="ir"></param>
        /// <param name="cbEntry"></param>
        /// <param name="notify"></param>
        /// <param name="operationContext"></param>
        /// <returns>list of failed keys</returns>
        /// <remarks>
        /// This method invokes <see cref="handleRemove"/> on every server node in the cluster.
        /// </remarks>
        protected Hashtable Clustered_Remove(Address dest, object[] keys, ItemRemoveReason ir, CallbackEntry cbEntry, bool notify, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.RemoveBlk", "");
            }

            Hashtable removedEntries = new Hashtable();
            ArrayList dests          = new ArrayList();

            dests.Add(dest);
            try
            {
                Function func    = new Function((int)OpCodes.Remove, new object[] { keys, ir, notify, cbEntry, operationContext }, false);
                RspList  results = Cluster.Multicast(dests, func, GetFirstResponse, false);

                if (results == null)
                {
                    return(removedEntries);
                }

                //muds:
                if (results.SuspectedMembers.Count == dests.Count)
                {
                    //All the members of this group has gone down.
                    //we must try this operation on some other group.
                    throw new Runtime.Exceptions.SuspectedException("operation failed because the group member was suspected");
                }

                ClusterHelper.ValidateResponses(results, typeof(Hashtable), Name);
                ArrayList rspList = ClusterHelper.GetAllNonNullRsp(results, typeof(Hashtable));

                if (rspList.Count <= 0)
                {
                    return(removedEntries);
                }

                IEnumerator ia = rspList.GetEnumerator();
                while (ia.MoveNext())
                {
                    Rsp       rsp     = (Rsp)ia.Current;
                    Hashtable removed = (Hashtable)rsp.Value;

                    IDictionaryEnumerator ide = removed.GetEnumerator();
                    while (ide.MoveNext())
                    {
                        removedEntries.Add(ide.Key, ide.Value);
                    }
                }
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            return(removedEntries);
        }
Exemple #8
0
        /// <summary>
        /// Add the ExpirationHint to a specfied node in the cluster.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method either invokes <see cref="handleAdd"/> on every server-node in the cluster.
        /// </remarks>
        protected bool Clustered_Add(Address dest, object key, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.Add_2", "");
            }

            bool retVal = false;

            try
            {
                Function func   = new Function((int)OpCodes.AddSyncDependency, new object[] { key, operationContext });
                object   result = Cluster.SendMessage(dest, func, GroupRequest.GET_FIRST);
                if (result == null)
                {
                    return(retVal);
                }
                retVal = (bool)result; //retvals[0];
            }
            catch (StateTransferException e)
            {
                throw;
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            return(retVal);
        }
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            ClientId = clientManager.ClientID;

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                serailizationContext = nCache.CacheId;
                cmdInfo = base.ParseCommand(command, clientManager, serailizationContext);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("BulkInsCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                _insertBulkResult = OperationResult.Failure;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                return;
            }

            byte[] dataPackage = null;

            try
            {
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                if (!string.IsNullOrEmpty(cmdInfo.IntendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.IntendedRecipient);
                }

                Hashtable insertResult = (Hashtable)nCache.Cache.Insert(cmdInfo.Keys, cmdInfo.Entries, operationContext);
                Alachisoft.NCache.Common.Protobuf.Response           response           = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.BulkInsertResponse bulkInsertResponse = new Alachisoft.NCache.Common.Protobuf.BulkInsertResponse();
                response.requestId                     = Convert.ToInt64(cmdInfo.RequestId);
                response.intendedRecipient             = cmdInfo.IntendedRecipient;
                bulkInsertResponse.keyExceptionPackage = new Alachisoft.NCache.Common.Protobuf.KeyExceptionPackageResponse();

                //TODO : Package Key Value
                Alachisoft.NCache.SocketServer.Util.KeyPackageBuilder.PackageKeysExceptions(insertResult, bulkInsertResponse.keyExceptionPackage);

                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT_BULK;
                response.bulkInsert   = bulkInsertResponse;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _insertBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("BulkInsCmd.Exec", "cmd executed on cache");
            }
        }
Exemple #10
0
        /// <summary>
        /// Updates or Adds the object to the cluster.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method invokes <see cref="handleInsert"/> on the specified node.
        /// </remarks>
        protected CacheInsResultWithEntry Clustered_Insert(Address dest, object key, CacheEntry cacheEntry, string taskId, object lockId, ulong version, LockAccessType accessType, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.Insert", "");
            }
            CacheInsResultWithEntry retVal = null;
            CacheEntry cloneValue          = null;

            try
            {
                operationContext?.MarkInUse(NCModulesConstants.Topology);

                Array userPayLoad; long payLoadSize;
                _context.CachingSubSystemDataService.GetEntryClone(cacheEntry, out cloneValue, out userPayLoad, out payLoadSize);

                Function func = new Function((int)OpCodes.Insert, new object[] { key, cloneValue, taskId, lockId, accessType, version, operationContext });
                func.UserPayload      = userPayLoad;
                func.ResponseExpected = true;
                object result = Cluster.SendMessage(dest, func, GroupRequest.GET_FIRST, false);
                if (result == null)
                {
                    return(retVal);
                }

                retVal = (CacheInsResultWithEntry)((OperationResponse)result).SerializablePayload;
                if (retVal.Entry != null && ((OperationResponse)result).UserPayload != null)
                {
                    retVal.Entry.Value = ((OperationResponse)result).UserPayload;
                }
            }
            catch (Runtime.Exceptions.SuspectedException se)
            {
                throw;
            }
            catch (Runtime.Exceptions.TimeoutException te)
            {
                throw;
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                operationContext?.MarkFree(NCModulesConstants.Topology);
                if (retVal == null)
                {
                    retVal = CacheInsResultWithEntry.CreateCacheInsResultWithEntry(_context.TransactionalPoolManager);
                }

                MiscUtil.ReturnEntryToPool(cloneValue, Context.TransactionalPoolManager);
            }
            return(retVal);
        }
        /// <summary>
        /// Determines whether the store contains a specific key.
        /// </summary>
        /// <param name="key">The key to locate in the store.</param>
        /// <returns>true if the store contains an element
        /// with the specified key; otherwise, false.</returns>
        public override bool Contains(object key)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("Store.Cont", "");
            }

            return(_itemDict.ContainsKey(key));
        }
Exemple #12
0
        /// <summary>
        /// Remove the objects from the cluster.
        /// </summary>
        /// <param name="keys">keys of the entries.</param>
        /// <returns>list of failed keys</returns>
        /// <remarks>
        /// This method invokes <see cref="handleRemove"/> on every server node in the cluster.
        /// </remarks>
        protected Hashtable Clustered_Remove(object[] keys, ItemRemoveReason ir, CallbackEntry cbEntry, bool notify, OperationContext operationContext)
        {
            Hashtable removedEntries = new Hashtable();

            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.RemoveBlk", "enter");
                }
                Function func    = new Function((int)OpCodes.Remove, new object[] { keys, ir, notify, cbEntry, operationContext }, false);
                RspList  results = Cluster.BroadcastToServers(func, GroupRequest.GET_ALL);

                if (results == null)
                {
                    return(removedEntries);
                }

                ClusterHelper.ValidateResponses(results, typeof(Hashtable), Name);
                ArrayList rspList = ClusterHelper.GetAllNonNullRsp(results, typeof(Hashtable));

                if (rspList.Count <= 0)
                {
                    return(removedEntries);
                }

                IEnumerator ia = rspList.GetEnumerator();
                while (ia.MoveNext())
                {
                    Rsp       rsp     = (Rsp)ia.Current;
                    Hashtable removed = (Hashtable)rsp.Value;

                    IDictionaryEnumerator ide = removed.GetEnumerator();
                    while (ide.MoveNext())
                    {
                        removedEntries.Add(ide.Key, ide.Value);
                    }
                }
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.RemoveBlk", "exit");
                }
            }
            return(removedEntries);
        }
        /// <summary>
        /// Add the object to specfied node in the cluster.
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="key">key of the entry.</param>
        /// <param name="cacheEntry"></param>
        /// <param name="operationContext"></param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method either invokes <see cref="handleAdd"/> on every server-node in the cluster.
        /// </remarks>
        protected CacheAddResult Clustered_Add(Address dest, object key, CacheEntry cacheEntry, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.Add_1", "");
            }
            CacheAddResult retVal = CacheAddResult.Success;

            try
            {
                Function func        = new Function((int)OpCodes.Add, new object[] { key, cacheEntry.CloneWithoutValue(), operationContext });
                Array    userPayLoad = null;
                if (cacheEntry.Value is CallbackEntry)
                {
                    CallbackEntry cbEntry = ((CallbackEntry)cacheEntry.Value);
                    userPayLoad = cbEntry.UserData;
                }
                else
                {
                    userPayLoad = cacheEntry.UserData;
                }

                func.UserPayload = userPayLoad;
                object result = Cluster.SendMessage(dest, func, GroupRequest.GET_FIRST);
                if (result == null)
                {
                    return(retVal);
                }
                if (result is CacheAddResult)
                {
                    retVal = (CacheAddResult)result;
                }
                else if (result is System.Exception)
                {
                    throw (Exception)result;
                }
            }
            catch (Runtime.Exceptions.SuspectedException se)
            {
                throw;
            }
            catch (Runtime.Exceptions.TimeoutException te)
            {
                throw;
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            return(retVal);
        }
        /// <summary>
        /// Updates or Adds the object to the cluster.
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="key">key of the entry.</param>
        /// <param name="cacheEntry"></param>
        /// <param name="lockId"></param>
        /// <param name="accessType"></param>
        /// <param name="operationContext"></param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method invokes <see cref="handleInsert"/> on the specified node.
        /// </remarks>
        protected CacheInsResultWithEntry Clustered_Insert(Address dest, object key, CacheEntry cacheEntry, object lockId, LockAccessType accessType, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.Insert", "");
            }

            CacheInsResultWithEntry retVal = new CacheInsResultWithEntry();

            try
            {
                Function func        = new Function((int)OpCodes.Insert, new object[] { key, cacheEntry.CloneWithoutValue(), lockId, accessType, operationContext });
                Array    userPayLoad = null;
                if (cacheEntry.Value is CallbackEntry)
                {
                    CallbackEntry cbEntry = ((CallbackEntry)cacheEntry.Value);
                    userPayLoad = cbEntry.UserData;
                }
                else
                {
                    userPayLoad = cacheEntry.UserData;
                }

                func.UserPayload      = userPayLoad;
                func.ResponseExpected = true;
                object result = Cluster.SendMessage(dest, func, GroupRequest.GET_FIRST, false);
                if (result == null)
                {
                    return(retVal);
                }

                retVal = (CacheInsResultWithEntry)((OperationResponse)result).SerializablePayload;
                if (retVal.Entry != null)
                {
                    retVal.Entry.Value = ((OperationResponse)result).UserPayload;
                }
            }
            catch (Runtime.Exceptions.SuspectedException se)
            {
                throw;
            }
            catch (Runtime.Exceptions.TimeoutException te)
            {
                throw;
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            return(retVal);
        }
Exemple #15
0
        /// <summary>
        /// Remove the object from the cluster.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method invokes <see cref="handleRemove"/> on every server node in the cluster.
        /// </remarks>
        protected CacheEntry Clustered_Remove(object key, ItemRemoveReason ir, CallbackEntry cbEntry, bool notify, object lockId, LockAccessType accessType, OperationContext operationContext)
        {
            CacheEntry retVal = null;

            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Remove", "enter");
                }
                Function func    = new Function((int)OpCodes.Remove, new object[] { key, ir, notify, cbEntry, lockId, accessType, operationContext }, false, key);
                RspList  results = Cluster.BroadcastToServers(func, GroupRequest.GET_ALL, _asyncOperation);
                if (results == null)
                {
                    return(retVal);
                }

                ClusterHelper.ValidateResponses(results, typeof(OperationResponse), Name);

                Rsp rsp = ClusterHelper.FindAtomicRemoveStatusReplicated(results);
                if (rsp == null)
                {
                    return(retVal);
                }

                OperationResponse opRes = rsp.Value as OperationResponse;
                if (opRes != null)
                {
                    CacheEntry entry = opRes.SerializablePayload as CacheEntry;
                    if (entry != null)
                    {
                        entry.Value = opRes.UserPayload;
                    }
                    return(entry);
                }
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Remove", "exit");
                }
            }
            return(retVal);
        }
Exemple #16
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RemCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                _removeResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }
            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                CallbackEntry    cbEntry          = null;
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                nCache.Cache.Delete(cmdInfo.Key, cmdInfo.FlagMap, cbEntry, cmdInfo.LockId, cmdInfo.LockAccessType, operationContext);
                //PROTOBUF:RESPONSE
                Alachisoft.NCache.Common.Protobuf.Response       response       = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.DeleteResponse removeResponse = new Alachisoft.NCache.Common.Protobuf.DeleteResponse();
                response.responseType   = Alachisoft.NCache.Common.Protobuf.Response.Type.DELETE;
                response.deleteResponse = removeResponse;
                response.requestId      = Convert.ToInt64(cmdInfo.RequestId);
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _removeResult = OperationResult.Failure;

                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(
                    Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RemCmd.Exec", "cmd executed on cache");
                }
            }
        }
Exemple #17
0
        public void ProcessCommand(ClientManager clientManager, object command, short cmdType, long acknowledgementId, UsageStats stats, bool waitforResponse)
        {
            Common.Protobuf.ManagementCommand cmd = command as Common.Protobuf.ManagementCommand;

            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "enter");
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "" + cmd);
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + "Management Command" + " RequestId :" + cmd.requestId);
            }

            NCManagementCommandBase incommingCmd = null;

            incommingCmd = new ManagementCommand();

            incommingCmd.ExecuteCommand(clientManager, cmd);/**/

            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + "Management Command" + " RequestId :" + cmd.requestId);
            }


#if SERVER
            if (clientManager != null &&
                incommingCmd.OperationResult == OperationResult.Success)
            {
                if (clientManager.CmdExecuter != null)
                {
                    clientManager.CmdExecuter.UpdateSocketServerStats(new SocketServerStats(clientManager.ClientsRequests, clientManager.ClientsBytesSent, clientManager.ClientsBytesRecieved));
                }
            }
#endif

            if (clientManager != null && incommingCmd.SerializedResponsePackets != null && !clientManager.IsCacheStopped)
            {
                foreach (IList reponse in incommingCmd.SerializedResponsePackets)
                {
                    ConnectionManager.AssureSend(clientManager, reponse, false);
                }
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "exit");
            }
        }
Exemple #18
0
        /// <summary>
        /// Determines whether the cache contains a specific key.
        /// </summary>
        /// <param name="key">The key to locate in the cache.</param>
        /// <returns>true if the cache contains an element
        /// with the specified key; otherwise, false.</returns>
        internal override bool ContainsInternal(object key)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.Cont", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }
            return(_cacheStore.Contains(key));
        }
Exemple #19
0
        /// <summary>
        /// Add the object to the cluster. Does load balancing as well.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <returns>cache entry.</returns>
        /// <remarks>
        /// This method either invokes <see cref="handleAdd"/> on one of the server nodes in the cluster,
        /// or invokes <see cref="Local_Add"/> locally.
        /// </remarks>
        protected CacheAddResult Clustered_Add(ArrayList dests, object key, CacheEntry cacheEntry, OperationContext operationContext)
        {
            CacheAddResult result = CacheAddResult.Failure;

            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Add", "enter");
                }

                /// Ask every server to add the object, except myself.
                Function func        = new Function((int)OpCodes.Add, new object[] { key, cacheEntry, operationContext }, false, key);
                Array    userPayLoad = null;
                if (cacheEntry.Value is CallbackEntry)
                {
                    CallbackEntry cbEntry = ((CallbackEntry)cacheEntry.Value);
                    userPayLoad = cbEntry.UserData;
                }
                else
                {
                    userPayLoad = cacheEntry.UserData;
                }

                func.UserPayload = userPayLoad;
                RspList results = Cluster.BroadcastToMultiple(dests,
                                                              func,
                                                              GroupRequest.GET_ALL, _asyncOperation);

                ClusterHelper.ValidateResponses(results, typeof(CacheAddResult), Name);

                /// Check if the operation failed on any node.
                result = ClusterHelper.FindAtomicAddStatusReplicated(results);
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Add", "exit");
                }
            }
            return(result);
        }
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("BulkGetCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                _getBulkResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            byte[] data = null;

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.ClientLastViewId);
                if (!string.IsNullOrEmpty(cmdInfo.IntendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.IntendedRecipient);
                }

                Hashtable getResult = (Hashtable)nCache.Cache.GetBulk(cmdInfo.Keys, cmdInfo.FlagMap, operationContext);

                BulkGetResponseBuilder.BuildResponse(getResult, cmdInfo.CommandVersion, cmdInfo.RequestId, _serializedResponsePackets, cmdInfo.IntendedRecipient);
            }
            catch (Exception exc)
            {
                _getBulkResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("BulkGetCmd.Exec", "cmd executed on cache");
            }
        }
        /// <summary>
        /// Provides implementation of Insert method of the ICacheStorage interface.
        /// Insert/Add the key value pair to the store.
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="item">object</param>
        /// <returns>returns the result of operation.</returns>
        public override StoreInsResult Insert(object key, object item, Boolean allowExtendedSize)
        {
            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("Store.Insert", "");
                }

                object oldItem = _itemDict[key];

                StoreStatus status = HasSpace(oldItem as ISizable, (ISizable)item, Common.MemoryUtil.GetStringSize(key), allowExtendedSize);

                if (ServiceConfiguration.CacheSizeThreshold > 0)
                {
                    _reportCacheNearEviction = true;
                }
                if (_reportCacheNearEviction)
                {
                    CheckForStoreNearEviction();
                }

                if (status == StoreStatus.HasNotEnoughSpace)
                {
                    return(StoreInsResult.NotEnoughSpace);
                }

                lock (_itemDict.SyncRoot)
                {
                    _itemDict[key] = item;
                    base.Inserted(oldItem as ISizable, item as ISizable, Common.MemoryUtil.GetStringSize(key));
                }
                if (status == StoreStatus.NearEviction)
                {
                    //the store is almost full, need to evict.
                    return(oldItem != null ? StoreInsResult.SuccessOverwriteNearEviction : StoreInsResult.SuccessNearEviction);
                }

                return(oldItem != null ? StoreInsResult.SuccessOverwrite : StoreInsResult.Success);
            }
            catch (OutOfMemoryException e)
            {
                return(StoreInsResult.NotEnoughSpace);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// Provides implementation of Add method of the ICacheStorage interface.
        /// Add the key value pair to the store.
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="item">object</param>
        /// <returns>returns the result of operation.</returns>
        public override StoreAddResult Add(object key, object item, Boolean allowExtendedSize)
        {
            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("Store.Add", "");
                }

                lock (_itemDict.SyncRoot)
                {
                    if (_itemDict.ContainsKey(key))
                    {
                        return(StoreAddResult.KeyExists);
                    }
                }

                StoreStatus status = HasSpace((ISizable)item, Common.MemoryUtil.GetStringSize(key), allowExtendedSize);

                CheckIfCacheNearEviction();

                if (status == StoreStatus.HasNotEnoughSpace)
                {
                    return(StoreAddResult.NotEnoughSpace);
                }

                lock (_itemDict.SyncRoot)
                {
                    _itemDict.Add(key, item);
                    base.Added(item as ISizable, Common.MemoryUtil.GetStringSize(key));
                }

                if (status == StoreStatus.NearEviction)
                {
                    return(StoreAddResult.SuccessNearEviction);
                }
            }
            catch (OutOfMemoryException e)
            {
                return(StoreAddResult.NotEnoughSpace);
            }
            catch (Exception e)
            {
                throw e;
            }

            return(StoreAddResult.Success);
        }
        //PROTOBUF
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            //TODO
            byte[] data = null;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ContCmd.Exec", "cmd parsed");
                }
            }
            catch (Exception exc)
            {
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }

            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                bool exists = nCache.Cache.Contains(cmdInfo.Key, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                Alachisoft.NCache.Common.Protobuf.Response        response         = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.ContainResponse containsResponse = new Alachisoft.NCache.Common.Protobuf.ContainResponse();
                response.requestId      = Convert.ToInt64(cmdInfo.RequestId);
                containsResponse.exists = exists;
                response.responseType   = Alachisoft.NCache.Common.Protobuf.Response.Type.CONTAINS;
                response.contain        = containsResponse;

                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("ContCmd.Exec", "cmd executed on cache");
            }
        }
Exemple #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="eh"></param>
        /// <returns></returns>
        internal override bool RemoveInternal(object key, ExpirationHint eh)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.Remove", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            CacheEntry e = (CacheEntry)_cacheStore.Get(key);

            if (e == null || e.ExpirationHint == null)
            {
                return(false);
            }
            else if (e.ExpirationHint.Equals(eh))
            {
                e.ExpirationHint = null;
            }

            // Our store may not be an in memory store

            if (_notifyCacheFull)
            {
                _notifyCacheFull = false;
            }
            _cacheStore.Insert(key, e, true);
            e.LastModifiedTime = System.DateTime.Now;

            if (_context.PerfStatsColl != null)
            {
                if (_evictionPolicy != null)
                {
                    _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
                }

                if (_context.ExpiryMgr != null)
                {
                    _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
                }
            }

            return(true);
        }
Exemple #25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="eh"></param>
        /// <returns></returns>
        internal override bool AddInternal(object key, ExpirationHint eh, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.Add_2", "");
            }

            if (_cacheStore == null)
            {
                throw new InvalidOperationException();
            }

            CacheEntry e = (CacheEntry)_cacheStore.Get(key);

            if (e == null)
            {
                return(false);
            }

            //We only allow either idle expiration or Fixed expiration both cannot be set at the same time
            if ((e.ExpirationHint is IdleExpiration && eh is FixedExpiration) ||
                (e.ExpirationHint is FixedExpiration && eh is IdleExpiration))
            {
                return(false);
            }

            e.ExpirationHint = eh;
            _cacheStore.Insert(key, e, true);
            e.LastModifiedTime = System.DateTime.Now;


            if (_context.PerfStatsColl != null)
            {
                if (_evictionPolicy != null)
                {
                    _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
                }

                if (_context.ExpiryMgr != null)
                {
                    _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
                }
            }

            return(true);
        }
        /// <summary>
        /// Provides implementation of Get method of the ICacheStorage interface.
        /// Get an object from the store, specified by the passed in key.
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>object</returns>
        public override object Get(object key)
        {
            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("Store.Get", "");
                }

                return((object)_itemDict[key]);
            }
            catch (Exception e)
            {
                Trace.error("ClrHeapStorageProvider.Get()", e.ToString());
                return(null);
            }
        }
Exemple #27
0
        /// <summary>
        /// Retrieve the object from the cluster.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <param name="excludeSelf">Set false to do a complete cluster lookup.</param>
        /// <returns>cache entry.</returns>
        protected CacheEntry Clustered_Get(Address address, object key, ref object lockId, ref DateTime lockDate, LockAccessType accessType, OperationContext operationContext)
        {
            CacheEntry retVal = null;

            try
            {
                if (operationContext.Contains(OperationContextFieldName.IsClusteredOperation))
                {
                    throw new InvalidReaderException("Reader state has been lost due to state transfer.");
                }
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Get", "enter");
                }
                Function func   = new Function((int)OpCodes.Get, new object[] { key, operationContext });
                object   result = Cluster.SendMessage(address, func, GroupRequest.GET_FIRST, false);
                if (result == null)
                {
                    return(retVal);
                }
                retVal = (CacheEntry)((OperationResponse)result).SerializablePayload;
                if (retVal != null)
                {
                    retVal.Value = ((OperationResponse)result).UserPayload;
                }
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Get", "exit");
                }
            }
            return(retVal);
        }
Exemple #28
0
        protected bool Clustered_Lock(object key, LockExpiration lockExpiration, ref object lockId, ref DateTime lockDate, OperationContext operationContext)
        {
            try
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Lock", "enter");
                }
                Function func = new Function((int)OpCodes.LockKey, new object[] { key, lockId, lockDate, lockExpiration, operationContext }, false);

                RspList results = Cluster.BroadcastToMultiple(Cluster.Servers,
                                                              func,
                                                              GroupRequest.GET_ALL);

                try
                {
                    ClusterHelper.ValidateResponses(results, typeof(LockOptions), Name);
                }
                catch (LockingException le)
                {
                    //release the lock preemptively...
                    Clustered_UnLock(key, null, true, operationContext);
                    return(false);
                }

                return(ClusterHelper.FindAtomicLockStatusReplicated(results, ref lockId, ref lockDate));
            }
            catch (CacheException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GeneralFailureException(e.Message, e);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("RepCacheBase.Lock", "exit");
                }
            }
        }
Exemple #29
0
        public void ProcessCommand(ClientManager clientManager, object command)
        {
            Alachisoft.NCache.Common.Protobuf.ManagementCommand cmd = command as Alachisoft.NCache.Common.Protobuf.ManagementCommand;

            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "enter");
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "" + cmd);
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + "Management Command" + " RequestId :" + cmd.requestId);
            }

            NCManagementCommandBase incommingCmd = null;

            incommingCmd = new ManagementCommand();

            //PROTOBUF
            /*****************************************************************/
            /**/
            incommingCmd.ExecuteCommand(clientManager, cmd);/**/
            /*****************************************************************/
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + "Management Command" + " RequestId :" + cmd.requestId);
            }

            if (clientManager != null && incommingCmd.SerializedResponsePackets != null && !clientManager.IsCacheStopped)
            {
                foreach (byte[] reponse in incommingCmd.SerializedResponsePackets)
                {
                    ConnectionManager.AssureSend(clientManager, reponse, Common.Enum.Priority.Normal);
                }
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "exit");
            }
        }
        /// <summary>
        /// Provides implementation of Remove method of the ICacheStorage interface.
        /// Removes an object from the store, specified by the passed in key
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>object</returns>
        public override object Remove(object key)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("Store.Remove", "");
            }

            object e = Get(key);

            if (e != null)
            {
                lock (_itemDict.SyncRoot)
                {
                    _itemDict.Remove(key);
                    base.Removed(e as ISizable, Common.MemoryUtil.GetStringSize(key));
                }
            }
            return(e);
        }