/// <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));
        }
Example #2
0
 public void SetUp()
 {
     queueChangedCount        = pollCount = 0;
     mockServerManager        = new DynamicMock(typeof(ICruiseServerManager));
     mockServerManager.Strict = true;
     monitor               = new ServerMonitor((ICruiseServerManager)mockServerManager.MockInstance);
     monitor.Polled       += new MonitorServerPolledEventHandler(Monitor_Polled);
     monitor.QueueChanged += new MonitorServerQueueChangedEventHandler(Monitor_QueueChanged);
 }
Example #3
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);
        }
Example #4
0
        public void PararServico()
        {
            logger.Info("Tentando parar o servico");
            // _Monitor.LoopControler = false;
            _Monitor = null;
            GC.Collect();

            _ServiceStatus = ServicoStatus.Parado;
            logger.Info("Servico Parado com sucesso.");
        }
        /// <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);
        }
Example #7
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);
        }
Example #8
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");
                }
            }
        }
Example #9
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");
            }
        }
 public ISingleServerMonitor[] GetServerMonitors()
 {
     BuildServer[]          buildServers   = GetUniqueBuildServerList();
     ISingleServerMonitor[] serverMonitors = new ISingleServerMonitor[buildServers.Length];
     for (int i = 0; i < buildServers.Length; i++)
     {
         BuildServer          buildServer   = buildServers[i];
         ICruiseServerManager serverManager = cruiseServerManagerFactory.Create(buildServer);
         serverManagersList[buildServer] = serverManager;
         serverMonitors[i] = new ServerMonitor(serverManager);
     }
     return(serverMonitors);
 }
Example #11
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));
        }
Example #12
0
 public void loadMainStaff()
 {
     rsafile = new RSA_File_manager();
     panel1.Controls.Add(rsafile);
     panel2.Hide();
     rsafile.Show();
     dt = new DecryptText();
     panel1.Controls.Add(dt);
     dt.Hide();
     serverm = new ServerMonitor();
     panel1.Controls.Add(serverm);
     serverm.Hide();
 }
        public static void UpdateServerMonitor(ServerMonitor serverMonitor, Interface.Server.ServerMonitor ism)
        {
            serverMonitor.Started   = ism.Started;
            serverMonitor.StartedBy = ism.StartedBy;

            RemoveOldStrategies(serverMonitor.Strategies, ism.Strategies);

            UpdateStrategies(serverMonitor.Strategies, ism.Strategies);

            AddStrategies(serverMonitor.Strategies, ism.Strategies);

            serverMonitor.StrategyCount = serverMonitor.Strategies.Count;
        }
Example #14
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);
        }
Example #15
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("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;
            }
        }
Example #17
0
        //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");
            }
        }
        /// <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);
        }
Example #19
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);
        }
Example #20
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);
            }
        }
Example #22
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);
        }
Example #23
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);
        }
Example #25
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");
                }
            }
        }
Example #26
0
        /// <summary>
        /// Removes the object and key pair from the cache. The key is specified as parameter.
        /// Moreover it take a removal reason and a boolean specifying if a notification should
        /// be raised.
        /// </summary>
        /// <param name="key">key of the entry.</param>
        /// <param name="removalReason">reason for the removal.</param>
        /// <param name="notify">boolean specifying to raise the event.</param>
        /// <returns>item value</returns>
        internal override CacheEntry RemoveInternal(object key, ItemRemoveReason removalReason, bool isUserOperation, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("LocalCache.Remove", "");
            }

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

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

            if (e != null)
            {
                if (_evictionPolicy != null && e.EvictionHint != null)
                {
                    _evictionPolicy.Remove(key, e.EvictionHint);
                }

                if (_notifyCacheFull)
                {
                    _notifyCacheFull = false;
                }
            }

            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(e);
        }
Example #27
0
        public static ServerNotification GetNotification(this ServerMonitor serverMonitor, List <ServerStrategy> serverStrategies)
        {
            var clone = new ServerMonitor
            {
                Name = serverMonitor.Name,
                Url  = serverMonitor.Url,
                MaxDegreeOfParallelism = serverMonitor.MaxDegreeOfParallelism,
                StartedBy  = serverMonitor.StartedBy,
                Started    = serverMonitor.Started,
                StoppedBy  = serverMonitor.StoppedBy,
                Stopped    = serverMonitor.Stopped,
                Strategies = serverStrategies
            };

            return(new ServerNotification
            {
                Machine = Environment.MachineName,
                Message = clone.ToString()
            });
        }
Example #28
0
        private static void RunServer()
        {
            var streamingUrl = ConfigurationManager.AppSettings["StreamingUrl"];

            DependencyContainer.Instance.Resolve <IStreamingClient>().Init(streamingUrl, false);

            var settings = new ServerSettings
            {
                Port       = Settings.Port(),
                Backlog    = Settings.Backlog(),
                BufferSize = Settings.BufferSize()
            };

            var protocol = DependencyContainer.Instance.Resolve <IProtocol>();

            _monitor = new ServerMonitor();

            _socketServer = new SocketServer(settings, _monitor, protocol);
            _socketServer.Start();
        }
        /// <summary>
        /// Remove the object from the cluster.
        /// </summary>
        /// <param name="dest"></param>
        /// <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(Address dest, object key, ItemRemoveReason ir, CallbackEntry cbEntry, bool notify, object lockId, LockAccessType accessType, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("PartCacheBase.Remove", "");
            }

            CacheEntry retVal = null;

            try
            {
                Function func = new Function((int)OpCodes.Remove, new object[] { key, ir, notify, cbEntry, lockId, accessType, operationContext }, false);
                func.ResponseExpected = true;
                object result = Cluster.SendMessage(dest, func, GroupRequest.GET_FIRST, false);
                if (result != null)
                {
                    retVal = ((OperationResponse)result).SerializablePayload as CacheEntry;
                    if (retVal != null)
                    {
                        retVal.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);
        }
Example #30
0
        private void ObserveServerMonitor(ServerMonitor serverMonitor)
        {
            var serverMonitorObservable = Observable.FromEventPattern <ServerMonitorEventArgs>(
                eventHandler => serverMonitor.OnServerMonitorNotification += eventHandler,
                eventHandler => serverMonitor.OnServerMonitorNotification -= eventHandler)
                                          .Select(eventPattern => eventPattern.EventArgs);

            var serverMonitorSubscription = serverMonitorObservable.Subscribe(args =>
            {
                if (args.HasException)
                {
                    OnServerMonitorCacheNotification($"{args.Value.Name} : {args.Exception.Message}", args.Exception);
                }
                else
                {
                    OnServerMonitorCacheNotification($"{args.Value.Name}");
                }
            });

            serverMonitorSubscriptions.Add(serverMonitor.Name, serverMonitorSubscription);
        }