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");
        }
Beispiel #2
0
        /// <summary>
        /// Initialize the cache instance.
        /// </summary>
        internal NCache(string cacheId, ClientManager client)
        {
            this._cacheId = cacheId;
            this._client = client;

            try
            {
              _cache = CacheProvider.Provider.GetCacheInstanceIgnoreReplica(cacheId);
            }
            catch (Exception) { throw; }

            if (_cache == null) throw new Exception("Cache is not registered");
            if (!_cache.IsRunning) throw new Exception("Cache is not running");

            _onItemUpdatedCallback = new CustomUpdateCallback(CustomUpdate);
            _cache.CustomUpdateCallbackNotif += _onItemUpdatedCallback;

            _onItemRemoveCallback = new CustomRemoveCallback(CustomRemove);
            _cache.CustomRemoveCallbackNotif += _onItemRemoveCallback;

            if (SocketServer.Logger.IsErrorLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Error(_cacheserver+".ctor", "Registering cache stopped event for " + _client.ClientID);
            }

            _cacheStopped = new CacheStoppedCallback(OnCacheStopped);
            _cache.CacheStopped += _cacheStopped;

            if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error(_cacheserver+".ctor", "Cache stopped event registered for " + _client.ClientID);
            _cache.ClientsInvalidated += new ClientsInvalidatedCallback(OnClientsInvalidated);

            _cache.OnClientConnected(client.ClientID, cacheId);
        }
        private void AcceptCallback(IAsyncResult result)
        {
            Socket clientSocket = null;
            bool objectDisposed = false;
            try
            {
                clientSocket = ((Socket)result.AsyncState).EndAccept(result);
            }
            catch (Exception e)
            {
                if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "An error occurred on EndAccept. " + e.ToString());
                return;
            }
            finally
            {
                try
                {
                    if (_serverSocket != null)
                        _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket);
                }
                catch (ObjectDisposedException)
                {
                    objectDisposed = true;
                }
            }

            if (objectDisposed) return;

            try
            {
                ClientManager clientManager = new ClientManager(this,clientSocket, totSizeHolderBytesCount, pinnedBufferSize);
                clientManager.ClientDisposed += new ClientDisposedCallback(OnClientDisposed);

                //Different network options depends on the underlying OS, which may support them or not
                //therefore we should handle error if they are not supported.
                try
                {
                    clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, _clientSendBufferSize);
                }
                catch (Exception e)
                {
                    if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set SendBuffer value. " + e.ToString());
                }
                try
                {
                    clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, _clientReceiveBufferSize);
                }
                catch (Exception e)
                {
                    if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set ReceiveBuffer value. " + e.ToString());
                }
                try
                {
                    clientManager.ClientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
                }
                catch (Exception e)
                {
                    if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "Can not set NoDelay option. " + e.ToString());
                }
                if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.AcceptCallback", "accepted client : " + clientSocket.RemoteEndPoint.ToString());

                clientManager.ClientSocket.BeginReceive(clientManager.Buffer,
                    0,
                    clientManager.discardingBuffer.Length,
                    SocketFlags.None,
                    new AsyncCallback(RecieveCallback),
                    clientManager);
            }
            catch (Exception e)
            {
                if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.AcceptCallback", "can not set async receive callback Error " + e.ToString());
                return;
            }
        }
Beispiel #4
0
        async Task FillPipeAsync(Socket socket, PipeWriter writer, ClientManager clientManager)
        {
            try
            {
                const int minimumBufferSize = 4 * 1024;

                while (true)
                {
                    // Allocate at least 512 bytes from the PipeWriter
                    Memory <byte> memory = writer.GetMemory(minimumBufferSize);

                    if (MemoryMarshal.TryGetArray(memory, out ArraySegment <byte> arraySegment))
                    {
                        if (!socket.Connected)
                        {
                            break;
                        }

                        int bytesRead = await socket.ReceiveAsync(arraySegment, SocketFlags.None);

                        clientManager.AddToClientsBytesRecieved(bytesRead);

                        if (SocketServer.IsServerCounterEnabled)
                        {
                            PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRead);
                        }

                        if (bytesRead == 0)
                        {
                            DisposeClient(clientManager);
                            break;
                        }
                        // Tell the PipeWriter how much was read from the Socket
                        writer.Advance(bytesRead);
                    }


                    // Make the data available to the PipeReader
                    FlushResult result = await writer.FlushAsync();

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }

                // Tell the PipeReader that there's no more data coming
                writer.Complete();
                DisposeClient(clientManager);
            }
            catch (SocketException so_ex)
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString());
                }

                DisposeClient(clientManager);
            }
            catch (Exception e)
            {
                var clientIsDisposed = clientManager.IsDisposed;
                DisposeClient(clientManager);

                if (!clientIsDisposed)
                {
                    AppUtil.LogEvent(e.ToString(), EventLogEntryType.Error);
                }

                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString());
                }
                if (SocketServer.Logger.IsErrorLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " Error " + e.ToString());
                }

                try
                {
                    if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder();
                        log.GenerateConnectionManagerLog(clientManager, e.ToString());
                    }
                }
                catch
                {
                }
            }
            finally
            {
                //  clientManager.StopCommandExecution();
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.StopClientActivity(clientManager.ClientID);
                }
            }
        }
Beispiel #5
0
        public override void ProcessCommand(ClientManager clientManager, object cmd, short cmdType, long acknowledgementId, UsageStats stats, bool waitforResponse)
        {
            Alachisoft.NCache.Common.Protobuf.Command command = cmd as Alachisoft.NCache.Common.Protobuf.Command;
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "enter");
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "" + command);
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + command.type.ToString() + " RequestId :" + command.requestID);
            }

            bool clientDisposed = false;

            CommandBase incommingCmd    = null;
            bool        isUnsafeCommand = false;

            switch (command.type)
            {
            case Alachisoft.NCache.Common.Protobuf.Command.Type.INIT:
                Alachisoft.NCache.Common.Protobuf.InitCommand initCommand = command.initCommand;
                initCommand.requestId = command.requestID;
                if (SocketServer.Logger.IsDetailedLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " RequestId :" + command.requestID);
                }
                incommingCmd = new ServiceInitializeCommand(base.RequestLogger.RequestLoggingEnabled, acknowledgementId);
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_OPTIMAL_SERVER:
                command.getOptimalServerCommand.requestId = command.requestID;
                incommingCmd = new ServiceGetOptimalServerCommand(acknowledgementId);
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_CACHE_BINDING:
                command.getCacheBindingCommand.requestId = command.requestID;
                incommingCmd = new ServiceCacheBindingCommand(acknowledgementId);
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_SERVER_MAPPING:
                command.getServerMappingCommand.requestId = command.requestID;
                incommingCmd = new GetServerMappingCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_CACHE_MANAGEMENT_PORT:
                command.getCacheManagementPortCommand.requestId = command.requestID;
                incommingCmd = new GetCacheManagementPortCommand();
                break;
            }


            if (SocketServer.IsServerCounterEnabled)
            {
                base.PerfStatsCollector.MsecPerCacheOperationBeginSample();
            }
            try
            {
                if (isUnsafeCommand && clientManager.SupportAcknowledgement)
                {
                    if (clientDisposed)
                    {
                        base.RequestLogger.RemoveClientAccount(clientManager.ClientID);
                    }
                    else
                    {
                        base.RequestLogger.RegisterRequest(clientManager.ClientID, command.requestID, command.commandID,
                                                           acknowledgementId);
                    }
                }
                incommingCmd.ExecuteCommand(clientManager, command);
            }
            catch (Exception ex)
            {
                if (isUnsafeCommand && clientManager.SupportAcknowledgement)
                {
                    base.RequestLogger.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID,
                                                     Alachisoft.NCache.Common.Enum.RequestStatus.RECEIVED_WITH_ERROR, null);
                }
                throw;
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + command.type.ToString() + " RequestId :" + command.requestID);
            }


            if (SocketServer.IsServerCounterEnabled)
            {
                base.PerfStatsCollector.MsecPerCacheOperationEndSample();
            }


#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 (isUnsafeCommand && clientManager.SupportAcknowledgement)
            {
                if (clientManager != null && clientManager.IsDisposed &&
                    incommingCmd.OperationResult == OperationResult.Failure)
                {
                    base.RequestLogger.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID, Alachisoft.NCache.Common.Enum.RequestStatus.RECEIVED_WITH_ERROR, null);
                }
                else
                {
                    base.RequestLogger.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID,
                                                     Alachisoft.NCache.Common.Enum.RequestStatus.RECEIVED_AND_EXECUTED, incommingCmd.SerializedResponsePackets);
                }
            }


            if (clientManager != null && incommingCmd.SerializedResponsePackets != null && !clientManager.IsCacheStopped)
            {
                if (SocketServer.IsServerCounterEnabled)
                {
                    base.PerfStatsCollector.IncrementResponsesPerSecStats(1);
                }

                foreach (IList reponse in incommingCmd.SerializedResponsePackets)
                {
                    ConnectionManager.AssureSendSync(clientManager, reponse);
                }
            }

            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "exit");
            }
        }
Beispiel #6
0
        internal NCache(string cacheId, bool isDotNetClient, ClientManager client, string licenceInfo, string userId, string password, byte[] userIdBinary, byte[] paswordBinary, Runtime.Caching.ClientInfo clientInfo)
        {
            this._cacheId        = cacheId;
            this._isDotNetClient = isDotNetClient;
            this._client         = client;
            this._licenceCode    = licenceInfo;


            _cache = CacheProvider.Provider.GetCacheInstanceIgnoreReplica(cacheId);

            if (_cache == null)
            {
                throw new Exception("Cache is not registered");
            }

            if (!_cache.IsRunning)
            {
                throw new Exception("Cache is not running");
            }

            EventHelper.EventDataFormat = _cache.SocketServerDataService;

            _onItemUpdatedCallback            = new CustomUpdateCallback(CustomUpdate);
            _cache.CustomUpdateCallbackNotif += _onItemUpdatedCallback;

            _onItemRemoveCallback             = new CustomRemoveCallback(CustomRemove);
            _cache.CustomRemoveCallbackNotif += _onItemRemoveCallback;

            _pollRequestCallback             = new Caching.PollRequestCallback(PollRequest);
            _cache.PollRequestCallbackNotif += _pollRequestCallback;


            if (SocketServer.Logger.IsErrorLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Error(_cacheserver + ".ctor", "Registering cache stopped event for " + _client.ClientID);
            }

            _cacheStopped        = new CacheStoppedCallback(OnCacheStopped);
            _cache.CacheStopped += _cacheStopped;

            if (SocketServer.Logger.IsErrorLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Error(_cacheserver + ".ctor", "Cache stopped event registered for " + _client.ClientID);
            }



            _asyncOperationCallback         = new AsyncOperationCompletedCallback(AsyncOperationCompleted);
            _cache.AsyncOperationCompleted += _asyncOperationCallback;


            _cacheBecomeActive        = new CacheBecomeActiveCallback(OnCacheBecomeActive);
            _cache.CacheBecomeActive += _cacheBecomeActive;

            _configModified = new ConfigurationModified(OnConfigModified);
            _cache.ConfigurationModified += _configModified;

            _onCompactTypeModifiedCallback = new CompactTypeModifiedCallback(CompactTypesModified);
            _cache.CompactTypeModified    += _onCompactTypeModifiedCallback;

            _blockClientActivity  = new BlockClientActivity(BlockClientActivity);
            _cache.BlockActivity += this._blockClientActivity;

            _unblockClientActivity  = new UnBlockClientActivity(UnBlockClientActivity);
            _cache.UnBlockActivity += this._unblockClientActivity;

            _operationModeChanged       += new OperationModeChangedCallback(OperationModeChanged);
            _cache.OperationModeChanged += _operationModeChanged;
        }
Beispiel #7
0
        async Task ReadPipeAsync(PipeReader reader, ClientManager clientManager, RequestReader requestReader)
        {
            try
            {
                while (true)
                {
                    ReadResult result = await reader.ReadAsync();

                    ReadOnlySequence <byte> buffer = result.Buffer;
                    clientManager.MarkActivity();
                    requestReader.Read(ref buffer);


                    // Tell the PipeReader how much of the buffer we have consumed
                    reader.AdvanceTo(buffer.Start, buffer.End);

                    // Stop reading if there's no more data coming
                    if (result.IsCompleted)
                    {
                        break;
                    }
                }

                // Mark the PipeReader as complete
                reader.Complete();
                DisposeClient(clientManager);
            }
            catch (SocketException so_ex)
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString());
                }

                DisposeClient(clientManager);
            }
            catch (Exception e)
            {
                var clientIsDisposed = clientManager.IsDisposed;
                DisposeClient(clientManager);

                if (!clientIsDisposed)
                {
                    AppUtil.LogEvent(e.ToString(), EventLogEntryType.Error);
                }

                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString());
                }
                if (SocketServer.Logger.IsErrorLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " Error " + e.ToString());
                }

                try
                {
                    if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder();
                        log.GenerateConnectionManagerLog(clientManager, e.ToString());
                    }
                }
                catch
                {
                }
            }
            finally
            {
                //  clientManager.StopCommandExecution();
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.StopClientActivity(clientManager.ClientID);
                }
            }
        }
 internal static void AssureSend(ClientManager clientManager, byte[] buffer, Alachisoft.NCache.Common.Enum.Priority priority)
 {
     SendFragmentedResponse(clientManager, buffer, priority);
 }
Beispiel #9
0
 internal NCache(string cacheId, bool isDonNetClient, ClientManager client)
     : this(cacheId, isDonNetClient, client, string.Empty)
 {
 }
Beispiel #10
0
 /// <summary>
 /// Dispose the cahce and Unregister the callbacks being registered with that cache
 /// </summary>
 public void Dispose()
 {
     if (_cache != null)
     {
         UnRegisterNotifications();
         _client = null;
     }
 }
Beispiel #11
0
 //PROTOBUF
 public abstract void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command);
Beispiel #12
0
        private static void Send(ClientManager clientManager, byte[] buffer, int count)
        {
            int bytesSent = 0;
            lock (clientManager.SendMutex)
            {
                while (bytesSent < count)
                {
                    try
                    {
                        clientManager.ResetAsyncSendTime();

                        bytesSent += clientManager.ClientSocket.Send(buffer, bytesSent, count - bytesSent, SocketFlags.None);

                        clientManager.AddToClientsBytesSent(bytesSent);
                        if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementBytesSentPerSecStats(bytesSent);
                    }
                    catch (SocketException e)
                    {

                        if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                            continue;
                        else throw;
                    }
                }

                clientManager.ResetAsyncSendTime();
            }
        }
Beispiel #13
0
        private static void SendFragmentedResponse(ClientManager client, byte[] bMessage, Alachisoft.NCache.Common.Enum.Priority priority)
        {
            if (bMessage != null)
            {
                //client older then 4.1 sp2 private patch 2 does not support message fragmentation.
                if (bMessage.Length <= _messageFragmentSize  ||  client.ClientVersion < 4122)
                {
                    AssureSend(client, bMessage, null, priority);
                }
                else
                {
                    long messageId = NextFragmentedMessageID;
                    int messageLength = bMessage.Length - cmdSizeHolderBytesCount;

                    int noOfFragments = messageLength / _messageFragmentSize;
                    if (bMessage.Length % _messageFragmentSize > 0)
                        noOfFragments++;

                    int srcOffset = cmdSizeHolderBytesCount;
                    int remainingBytes = messageLength;

                    Alachisoft.NCache.Common.Protobuf.FragmentedResponse fragmentedResponse = new Alachisoft.NCache.Common.Protobuf.FragmentedResponse();

                    for (int i = 0; i < noOfFragments; i++)
                    {
                        int chunkSize = remainingBytes > _messageFragmentSize ? _messageFragmentSize : remainingBytes;

                        if (fragmentedResponse.message == null || fragmentedResponse.message.Length != chunkSize)
                            fragmentedResponse.message = new byte[chunkSize];

                        Buffer.BlockCopy(bMessage, srcOffset, fragmentedResponse.message, 0, chunkSize);

                        remainingBytes -= chunkSize;
                        srcOffset += chunkSize;
                        //fragmentedResponses.Add(fragmentedResponse);

                        Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                        response.requestId = -1;
                        fragmentedResponse.messageId = messageId;
                        fragmentedResponse.totalFragments = noOfFragments;
                        fragmentedResponse.fragmentNo = i;
                        response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.RESPONSE_FRAGMENT;
                        response.getResponseFragment = fragmentedResponse;

                        byte[] serializedReponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response);

                        AssureSend(client, serializedReponse, null, priority);
                    }
                }
            }
        }
Beispiel #14
0
        private static void AssureSendOld(ClientManager clientManager, byte[] buffer, int count, SendContext context)
        {
            TimeSpan tempTaken;

            try
            {
                Send(clientManager, buffer, count);
                SendContext opContext = null;

                do
                {
                    opContext = null;
                    lock (clientManager)
                    {
                        if (clientManager.PendingSendOperationQueue.Count > 0)
                        {
                            object operation = clientManager.PendingSendOperationQueue.remove();
                            opContext = (SendContext)operation;
                            clientManager.ResetAsyncSendTime();

                            if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueCountStats();
                            if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.DecrementResponsesQueueSizeStats(opContext.expectedSize);
                        }
                    }

                    if (opContext != null)
                    {
                        Send(opContext.clientManager, opContext.buffer, opContext.expectedSize);
                    }

                    lock (clientManager)
                    {
                        if (clientManager.PendingSendOperationQueue.Count == 0)
                        {
                            clientManager.DeMarkOperationInProcess();
                            return;
                        }
                    }

                } while (clientManager.PendingSendOperationQueue.Count > 0);

            }
            catch (Exception e)
            {
                if (SocketServer.Logger != null && SocketServer.Logger.IsErrorLogsEnabled)
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.AssureSend", e.ToString());

                DisposeClient(clientManager);
            }
        }
Beispiel #15
0
        private static void AssureSend(ClientManager clientManager, byte[] buffer, int count, SendContext context)
        {
            try
            {
                Send(clientManager, buffer, count);

                lock (clientManager)
                {
                    if (clientManager.PendingSendOperationQueue.Count == 0)
                    {
                        clientManager.DeMarkOperationInProcess();
                        return;
                    }
                }

            #if !NET20
                try
                {
                    Task t = null;
                    //as there are times in the queue; let's start sending pending responses in separate thread.
                    TaskFactory factory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
                    t = factory.StartNew(() => ProccessResponseQueue(clientManager), TaskCreationOptions.LongRunning);

                }
                catch (AggregateException aggEx)
                {
                }

            #else
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProccessResponseQueue), clientManager);
            #endif

            }
            catch (Exception e)
            {
                if (SocketServer.Logger != null && SocketServer.Logger.IsErrorLogsEnabled)
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.AssureSend", e.ToString());

                DisposeClient(clientManager);
            }
        }
Beispiel #16
0
        private static void AssureSend(ClientManager clientManager, byte[] buffer, Array userpayLoad, Alachisoft.NCache.Common.Enum.Priority priority)
        {
            SendContext context = new SendContext();
            context.clientManager = clientManager;
            context.buffer = buffer;
            context.expectedSize = buffer.Length;

            try
            {
                bool doOperation = true;
                if (clientManager != null)
                {
                    lock (clientManager)
                    {
                        doOperation = clientManager.MarkOperationInProcess();
                        if (!doOperation)
                        {
                            if (clientManager.IsDisposed) return;
                            clientManager.PendingSendOperationQueue.add(context, priority);

                            if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementResponsesQueueCountStats();
                            if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementResponsesQueueSizeStats(buffer.Length);

                            return;
                        }
                    }

                    AssureSend(clientManager, buffer, buffer.Length, context);
                }
            }
            catch (SocketException se)
            {
                DisposeClient(clientManager);
            }
            catch (ObjectDisposedException o)
            {
                return;
            }
        }
Beispiel #17
0
        /// <summary>
        /// The Receives data less than the buffer size. i.e buffer length and size may not be equal. (used to avoid pinning of unnecessary byte buffers.)
        /// </summary>
        /// <param name="clientManager"></param>
        /// <param name="buffer"></param>
        /// <param name="size"></param>
        private static void AssureRecieve(ClientManager clientManager, ref byte[] buffer, int size)
        {
            int bytesRecieved = 0;
            int totalBytesReceived = 0;

            do
            {
                try
                {
                    bytesRecieved = clientManager.ClientSocket.Receive(buffer, totalBytesReceived, size - totalBytesReceived, SocketFlags.None);
                    totalBytesReceived += bytesRecieved;

                    clientManager.AddToClientsBytesRecieved(bytesRecieved);
                    if (SocketServer.IsServerCounterEnabled) clientManager.ConnectionManager.PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRecieved);
                }
                catch (SocketException se)
                {
                    if (se.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue;
                    else throw;
                }
                catch (ObjectDisposedException)
                { }
            } while (totalBytesReceived < size && bytesRecieved > 0);
        }
Beispiel #18
0
        /// <summary>
        /// Dispose the client
        /// </summary>
        /// <param name="clientManager">Client manager object representing the client to be diposed</param>
        internal static void DisposeClient(ClientManager clientManager)
        {
            try
            {
                if (clientManager != null)
                {
                    if (clientManager._leftGracefully)
                    {
                        if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " left gracefully");
                    }
                    else
                    {
                        if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", "Connection lost with client (" + clientManager.ToString() + ")");
                    }

                    if (clientManager.ClientID != null)
                    {
                        lock (ConnectionTable)
                            ConnectionTable.Remove(clientManager.ClientID);
                    }

                    clientManager.Dispose();
                    clientManager = null;
                }
            }
            catch (Exception) { }
        }
Beispiel #19
0
        private void AssureRecieve(ClientManager clientManager, out Object command, out byte[] value, out long tranSize)
        {
            value = null;

            int commandSize = HelperFxn.ToInt32(clientManager.Buffer, 0, cmdSizeHolderBytesCount, "Command");
            tranSize = commandSize;
            using (Stream str = new ClusteredMemoryStream())
            {
                //byte[] buffer = new byte[commandSize + dataSize];
                while (commandSize >= 0)
                {
                    int apparentSize = commandSize < 81920 ? commandSize : 81920;
                    byte[] buffer = clientManager.GetPinnedBuffer((int)apparentSize);

                    AssureRecieve(clientManager, ref buffer, (int)apparentSize);
                    str.Write(buffer, 0, apparentSize);
                    commandSize -= 81920;
                }
                str.Position = 0;
                command = cmdManager.Deserialize(str);
            }
        }
Beispiel #20
0
 private void CommandContext(ClientManager clientManager, out long tranSize)
 {
     int commandSize = HelperFxn.ToInt32(clientManager.Buffer, 0, cmdSizeHolderBytesCount, "Command");
     tranSize = commandSize;
 }
Beispiel #21
0
        public void ProcessCommand(ClientManager clientManager, object cmd)
        {
            Alachisoft.NCache.Common.Protobuf.Command command = cmd as Alachisoft.NCache.Common.Protobuf.Command;
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "enter");
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "" + command);
            if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + command.type.ToString() + " RequestId :" + command.requestID);

            HPTimeStats milliSecWatch = new HPTimeStats();
            milliSecWatch.BeginSample();

            CommandBase incommingCmd = null;

            switch (command.type)
            {
                case Alachisoft.NCache.Common.Protobuf.Command.Type.INIT:
                    Alachisoft.NCache.Common.Protobuf.InitCommand initCommand = command.initCommand;
                    initCommand.requestId = command.requestID;
                    if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " RequestId :" + command.requestID);
                    incommingCmd = new InitializeCommand();
                    break;
                    // added in server to cater getProductVersion request from client
                case Common.Protobuf.Command.Type.GET_PRODUCT_VERSION:
                    command.getProductVersionCommand.requestId = command.requestID;
                    incommingCmd = new GetProductVersionCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD:
                    command.addCommand.requestId = command.requestID;
                    incommingCmd = new AddCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_BULK:
                    command.bulkAddCommand.requestId = command.requestID;
                    incommingCmd = new BulkAddCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.CLEAR:
                    command.clearCommand.requestId = command.requestID;
                    incommingCmd = new ClearCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.CONTAINS:
                    command.containsCommand.requestId = command.requestID;
                    incommingCmd = new ContainsCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.COUNT:
                    command.countCommand.requestId = command.requestID;
                    incommingCmd = new CountCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.DISPOSE:
                    command.disposeCommand.requestId = command.requestID;
                    incommingCmd = new DisposeCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET:
                    command.getCommand.requestId = command.requestID;
                    incommingCmd = new GetCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_BULK:
                    command.bulkGetCommand.requestId = command.requestID;
                    incommingCmd = new BulkGetCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_CACHE_ITEM:
                    command.getCacheItemCommand.requestId = command.requestID;
                    incommingCmd = new GetCacheItemCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_ENUMERATOR:
                    command.getEnumeratorCommand.requestId = command.requestID;
                    incommingCmd = new GetEnumeratorCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_NEXT_CHUNK:
                    command.getNextChunkCommand.requestId = command.requestID;
                    incommingCmd = new GetNextChunkCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_HASHMAP:
                    command.getHashmapCommand.requestId = command.requestID;
                    incommingCmd = new GetHashmapCommand();
                    break;
                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_OPTIMAL_SERVER:
                    command.getOptimalServerCommand.requestId = command.requestID;
                    incommingCmd = new GetOptimalServerCommand();
                    break;
                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_RUNNING_SERVERS:
                    command.getRunningServersCommand.requestId = command.requestID;
                    incommingCmd = new GetRunningServersCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_LOGGING_INFO:
                    command.getLoggingInfoCommand.requestId = command.requestID;
                    incommingCmd = new GetLogginInfoCommand();
                    break;
                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_TYPEINFO_MAP:
                    command.getTypeInfoMapCommand.requestId = command.requestID;
                    incommingCmd = new GetTypeInfoMap();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.INSERT:
                    command.insertCommand.requestId = command.requestID;
                    incommingCmd = new InsertCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.INSERT_BULK:
                    command.bulkInsertCommand.requestId = command.requestID;
                    incommingCmd = new BulkInsertCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.ISLOCKED:
                    command.isLockedCommand.requestId = command.requestID;
                    incommingCmd = new IsLockedCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.LOCK:
                    command.lockCommand.requestId = command.requestID;
                    incommingCmd = new LockCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.LOCK_VERIFY:
                    command.lockVerifyCommand.requestId = command.requestID;
                    incommingCmd = new VerifyLockCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_KEY_NOTIF:
                    command.registerKeyNotifCommand.requestId = command.requestID;
                    incommingCmd = new RegisterKeyNotifcationCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_NOTIF:
                    command.registerNotifCommand.requestId = command.requestID;
                    incommingCmd = new NotificationRegistered();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE:
                    command.removeCommand.requestId = command.requestID;
                    incommingCmd = new RemoveCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.DELETE:
                    command.deleteCommand.requestId = command.requestID;
                    incommingCmd = new DeleteCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE_BULK:
                    command.bulkRemoveCommand.requestId = command.requestID;
                    incommingCmd = new BulkRemoveCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.DELETE_BULK:
                    command.bulkDeleteCommand.requestId = command.requestID;
                    incommingCmd = new BulkDeleteCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.SEARCH:
                    Alachisoft.NCache.Common.Protobuf.SearchCommand searchCommand = command.searchCommand;
                    searchCommand.requestId = command.requestID;

                    if (searchCommand.searchEntries)
                        incommingCmd = new SearchEnteriesCommand();
                    else
                        incommingCmd = new SearchCommand();

                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.UNLOCK:
                    command.unlockCommand.requestId = command.requestID;
                    incommingCmd = new UnlockCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.UNREGISTER_KEY_NOTIF:
                    command.unRegisterKeyNotifCommand.requestId = command.requestID;
                    incommingCmd = new UnRegisterKeyNoticationCommand();
                    break;

                case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_ATTRIBUTE:
                    command.addAttributeCommand.requestId = command.requestID;
                    incommingCmd = new AddAttributeCommand();
                    break;
                case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_SERVER_MAPPING:
                    command.getServerMappingCommand.requestId = command.requestID;
                    incommingCmd = new GetServerMappingCommand();
                    break;

            }
            if (SocketServer.IsServerCounterEnabled) _perfStatsCollector.MsecPerCacheOperationBeginSample();
            ///*****************************************************************/
            ///**/incommingCmd.ExecuteCommand(clientManager, command, value);/**/
            ///*****************************************************************/
            //PROTOBUF
            /*****************************************************************/
            /**/
            incommingCmd.ExecuteCommand(clientManager, command);/**/
            /*****************************************************************/
            if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + command.type.ToString() + " RequestId :" + command.requestID);

            if (SocketServer.IsServerCounterEnabled) _perfStatsCollector.MsecPerCacheOperationEndSample();

            if (clientManager != null && incommingCmd.SerializedResponsePackets != null && !clientManager.IsCacheStopped)
            {
                if (SocketServer.IsServerCounterEnabled) _perfStatsCollector.IncrementResponsesPerSecStats(1);

                foreach (byte[] reponse in incommingCmd.SerializedResponsePackets)
                {
                    ConnectionManager.AssureSend(clientManager, reponse, Alachisoft.NCache.Common.Enum.Priority.Normal);
                }
            }

            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "exit");
        }
Beispiel #22
0
        public virtual void ProcessCommand(ClientManager clientManager, object cmd, long acknowledgementId, UsageStats stats)
        {
            Alachisoft.NCache.Common.Protobuf.Command command = cmd as Alachisoft.NCache.Common.Protobuf.Command;
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "enter");
            }
            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "" + command);
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " COMMAND to be executed : " + command.type.ToString() + " RequestId :" + command.requestID);
            }

            HPTimeStats milliSecWatch = new HPTimeStats();

            milliSecWatch.BeginSample();
            bool      clientDisposed   = false;
            bool      isAsync          = false;
            string    _methodName      = command.type.ToString();;
            Stopwatch commandExecution = new Stopwatch();

            commandExecution.Start();

            CommandBase incommingCmd = null;
            bool        isUnsafeCommand = false, doThrottleCommand = true;

            switch (command.type)
            {
            case Alachisoft.NCache.Common.Protobuf.Command.Type.INIT:
                Alachisoft.NCache.Common.Protobuf.InitCommand initCommand = command.initCommand;
                initCommand.requestId = command.requestID;
                if (SocketServer.Logger.IsDetailedLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " RequestId :" + command.requestID);
                }
                incommingCmd      = new InitializeCommand(bookie.RequestLoggingEnabled);
                doThrottleCommand = false;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.EXECUTE_READER:
                Alachisoft.NCache.Common.Protobuf.ExecuteReaderCommand executeReaderCommand = command.executeReaderCommand;
                executeReaderCommand.requestId = command.requestID;
                incommingCmd = new ExecuteReaderCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.EXECUTE_READER_CQ:
                Alachisoft.NCache.Common.Protobuf.ExecuteReaderCQCommand executeReaderCQCommand = command.executeReaderCQCommand;
                executeReaderCQCommand.requestId = command.requestID;
                incommingCmd = new ExecuteReaderCQCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_READER_CHUNK:
                Alachisoft.NCache.Common.Protobuf.GetReaderNextChunkCommand getReaderChunkCommand = command.getReaderNextChunkCommand;
                getReaderChunkCommand.requestId = command.requestID;
                incommingCmd = new GetReaderChunkCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.DISPOSE_READER:
                Alachisoft.NCache.Common.Protobuf.DisposeReaderCommand disposeReaderCommand = command.disposeReaderCommand;
                disposeReaderCommand.requestId = command.requestID;
                incommingCmd = new DisposeReaderCommand();
                break;

            // Added in server to cater getProductVersion request from client
            case Common.Protobuf.Command.Type.GET_PRODUCT_VERSION:
                command.getProductVersionCommand.requestId = command.requestID;
                incommingCmd = new GetProductVersionCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD:
                command.addCommand.requestId = command.requestID;
                isAsync         = command.addCommand.isAsync;
                incommingCmd    = new AddCommand();
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_BULK:
                command.bulkAddCommand.requestId = command.requestID;
                incommingCmd    = new BulkAddCommand();
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_DEPENDENCY:
                command.addDependencyCommand.requestId = command.requestID;
                incommingCmd = new AddDependencyCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_SYNC_DEPENDENCY:
                command.addSyncDependencyCommand.requestId = command.requestID;
                incommingCmd = new AddSyncDependencyCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.CLEAR:
                command.clearCommand.requestId = command.requestID;
                incommingCmd = new ClearCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.CLOSE_STREAM:
                command.closeStreamCommand.requestId = command.requestID;
                incommingCmd = new CloseStreamCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.CONTAINS:
                command.containsCommand.requestId = command.requestID;
                incommingCmd = new ContainsCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.COUNT:
                command.countCommand.requestId = command.requestID;
                incommingCmd = new CountCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.DISPOSE:
                command.disposeCommand.requestId = command.requestID;
                incommingCmd   = new DisposeCommand();
                clientDisposed = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET:
                command.getCommand.requestId = command.requestID;
                incommingCmd = new GetCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_BULK:
                command.bulkGetCommand.requestId = command.requestID;
                incommingCmd = new BulkGetCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_CACHE_ITEM:
                command.getCacheItemCommand.requestId = command.requestID;
                incommingCmd = new GetCacheItemCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_CACHE_BINDING:
                command.getCacheBindingCommand.requestId = command.requestID;
                incommingCmd = new GetCacheBindingCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_ENUMERATOR:
                command.getEnumeratorCommand.requestId = command.requestID;
                incommingCmd = new GetEnumeratorCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_NEXT_CHUNK:
                command.getNextChunkCommand.requestId = command.requestID;
                incommingCmd = new GetNextChunkCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_GROUP_NEXT_CHUNK:
                command.getGroupNextChunkCommand.requestId = command.requestID;
                incommingCmd = new GetGroupNextChunkCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_GROUP:
                Alachisoft.NCache.Common.Protobuf.GetGroupCommand getGroupCommand = command.getGroupCommand;
                getGroupCommand.requestId = command.requestID;
                if (getGroupCommand.getGroupKeys)
                {
                    incommingCmd = new GetGroupKeys();
                    _methodName  = MethodsName.GetGroupKeys;
                }
                else
                {
                    incommingCmd = new GetGroupData();
                    _methodName  = MethodsName.GetGroupData;
                }
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_HASHMAP:
                command.getHashmapCommand.requestId = command.requestID;
                incommingCmd      = new GetHashmapCommand();
                doThrottleCommand = false;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_LOGGING_INFO:
                command.getLoggingInfoCommand.requestId = command.requestID;
                incommingCmd = new GetLogginInfoCommand();
                break;

#if !(DEVELOPMENT)
            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_OPTIMAL_SERVER:
                command.getOptimalServerCommand.requestId = command.requestID;
                incommingCmd      = new GetOptimalServerCommand();
                doThrottleCommand = false;
                break;
#endif
            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_STREAM_LENGTH:
                command.getStreamLengthCommand.requestId = command.requestID;
                incommingCmd = new GetStreamLengthCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_TAG:
                command.getTagCommand.requestId = command.requestID;
                incommingCmd = new GetTagCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE_BY_TAG:
                command.removeByTagCommand.requestId = command.requestID;
                incommingCmd = new RemoveByTagCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_KEYS_TAG:
                command.getKeysByTagCommand.requestId = command.requestID;
                incommingCmd = new GetKeysByTagCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_TYPEINFO_MAP:
                command.getTypeInfoMapCommand.requestId = command.requestID;
                incommingCmd      = new GetTypeInfoMap();
                doThrottleCommand = false;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.INSERT:
                command.insertCommand.requestId = command.requestID;
                incommingCmd    = new InsertCommand();
                isAsync         = command.insertCommand.isAsync;
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.INSERT_BULK:
                command.bulkInsertCommand.requestId = command.requestID;
                incommingCmd    = new BulkInsertCommand();
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ISLOCKED:
                command.isLockedCommand.requestId = command.requestID;
                incommingCmd = new IsLockedCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.LOCK:
                command.lockCommand.requestId = command.requestID;
                incommingCmd = new LockCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.LOCK_VERIFY:
                command.lockVerifyCommand.requestId = command.requestID;
                incommingCmd = new VerifyLockCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.OPEN_STREAM:
                command.openStreamCommand.requestId = command.requestID;
                incommingCmd = new OpenStreamCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.RAISE_CUSTOM_EVENT:
                command.raiseCustomEventCommand.requestId = command.requestID;
                incommingCmd = new RaiseCustomNotifCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.READ_FROM_STREAM:
                command.readFromStreamCommand.requestId = command.requestID;
                incommingCmd = new ReadFromStreamCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_BULK_KEY_NOTIF:
                command.registerBulkKeyNotifCommand.requestId = command.requestID;
                incommingCmd = new RegisterBulkKeyNotifcationCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_KEY_NOTIF:
                command.registerKeyNotifCommand.requestId = command.requestID;
                incommingCmd = new RegisterKeyNotifcationCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_NOTIF:
                command.registerNotifCommand.requestId = command.requestID;
                incommingCmd      = new NotificationRegistered();
                doThrottleCommand = false;
                break;

            case Common.Protobuf.Command.Type.REGISTER_POLLING_NOTIFICATION:
                command.registerPollNotifCommand.requestId = command.requestID;
                incommingCmd = new RegisterPollingNotificationCommand();
                break;

            case Common.Protobuf.Command.Type.POLL:
                command.pollCommand.requestId = command.requestID;
                incommingCmd = new PollCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE:
                command.removeCommand.requestId = command.requestID;
                incommingCmd    = new RemoveCommand();
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.DELETE:
                command.deleteCommand.requestId = command.requestID;
                incommingCmd = new DeleteCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE_BULK:
                command.bulkRemoveCommand.requestId = command.requestID;
                incommingCmd    = new BulkRemoveCommand();
                isUnsafeCommand = true;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.DELETE_BULK:
                command.bulkDeleteCommand.requestId = command.requestID;
                incommingCmd = new BulkDeleteCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REMOVE_GROUP:
                command.removeGroupCommand.requestId = command.requestID;
                incommingCmd = new RemoveGroupCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.SEARCH:
                Alachisoft.NCache.Common.Protobuf.SearchCommand searchCommand = command.searchCommand;
                searchCommand.requestId = command.requestID;

                if (searchCommand.searchEntries)
                {
                    incommingCmd = new SearchEnteriesCommand();
                    _methodName  = "SearchEnteries";
                }
                else
                {
                    incommingCmd = new SearchCommand();
                    _methodName  = "Search";
                }
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.SEARCH_CQ:
                Alachisoft.NCache.Common.Protobuf.SearchCQCommand searchCQCommand = command.searchCQCommand;
                searchCQCommand.requestId = command.requestID;

                if (searchCQCommand.searchEntries)
                {
                    _methodName  = "SearchCQEnteries";
                    incommingCmd = new SearchEnteriesCQCommand();
                }
                else
                {
                    _methodName  = "SearchCQ";
                    incommingCmd = new SearchCQCommand();
                }
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.UNREGISTER_CQ:
                command.unRegisterCQCommand.requestId = command.requestID;
                incommingCmd = new UnRegisterCQCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.REGISTER_CQ:
                command.registerCQCommand.requestId = command.requestID;
                incommingCmd = new RegisterCQCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.DELETEQUERY:
                Alachisoft.NCache.Common.Protobuf.DeleteQueryCommand deleteQueryCommand = command.deleteQueryCommand;
                deleteQueryCommand.requestId = command.requestID;

                if (deleteQueryCommand.isRemove)
                {
                    incommingCmd = new RemoveQueryCommand();
                    _methodName  = "RemoveQuery";
                }
                else
                {
                    incommingCmd = new DeleteQueryCommand();
                    _methodName  = "DeleteQuery";
                }
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.UNLOCK:
                command.unlockCommand.requestId = command.requestID;
                incommingCmd = new UnlockCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.UNREGISTER_BULK_KEY_NOTIF:
                command.unRegisterBulkKeyNotifCommand.requestId = command.requestID;
                incommingCmd = new UnRegsisterBulkKeyNotification();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.UNREGISTER_KEY_NOTIF:
                command.unRegisterKeyNotifCommand.requestId = command.requestID;
                incommingCmd = new UnRegisterKeyNoticationCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.WRITE_TO_STREAM:
                command.writeToStreamCommand.requestId = command.requestID;
                incommingCmd = new WriteToStreamCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.ADD_ATTRIBUTE:
                command.addAttributeCommand.requestId = command.requestID;
                incommingCmd = new AddAttributeCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.SYNC_EVENTS:
                command.syncEventsCommand.requestId = command.requestID;
                incommingCmd = new SyncEventCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.INQUIRY_REQUEST:
                incommingCmd = new InquiryRequestCommand(bookie);
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.MAP_REDUCE_TASK:
                command.mapReduceTaskCommand.requestId = command.requestID;
                incommingCmd = new MapReduceTaskCommand();
                break;

            case Common.Protobuf.Command.Type.TASK_CALLBACK:
                command.TaskCallbackCommand.requestId = command.requestID;
                incommingCmd = new TaskCallbackCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.CANCEL_TASK:
                incommingCmd = new TaskCancelCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.RUNNING_TASKS:
                command.RunningTasksCommand.requestId = command.requestID;
                incommingCmd = new GetRunningTasksCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.TASK_PROGRESS:
                command.TaskProgressCommand.requestId = command.requestID;
                incommingCmd = new TaskProgressCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.TASK_ENUMERATOR:
                incommingCmd = new TaskEnumeratorCommand();
                break;

            case Common.Protobuf.Command.Type.TASK_NEXT_RECORD:
                command.NextRecordCommand.RequestId = command.requestID;
                incommingCmd = new TaskNextRecordCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.INVOKE_ENTRY_PROCESSOR:
                incommingCmd = new InvokeEntryProcessorCommand();
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_RUNNING_SERVERS:
                command.getRunningServersCommand.requestId = command.requestID;
                incommingCmd      = new GetRunningServersCommand();
                doThrottleCommand = false;
                break;

            case Alachisoft.NCache.Common.Protobuf.Command.Type.GET_EXPIRATION:
                command.getExpirationCommand.requestId = command.requestID;
                incommingCmd      = new GetExpirationCommand();
                doThrottleCommand = false;
                break;

            case Common.Protobuf.Command.Type.GET_CONNECTED_CLIENTS:
                command.getConnectedClientsCommand.requestId = command.requestID;
                incommingCmd = new GetConnectedClientsCommand();
                break;

            case Common.Protobuf.Command.Type.TOUCH:
                command.touchCommand.requestId = command.requestID;
                incommingCmd = new TouchCommand();
                break;



                #region PUB_SUB
            case Common.Protobuf.Command.Type.GET_TOPIC:
                command.getTopicCommand.requestId = command.requestID;
                incommingCmd = new GetTopicCommand();
                break;

            case Common.Protobuf.Command.Type.SUBSCRIBE_TOPIC:
                command.subscribeTopicCommand.requestId = command.requestID;
                incommingCmd = new SubscribeTopicCommand();
                break;

            case Common.Protobuf.Command.Type.UNSUBSCRIBE_TOPIC:
                command.unSubscribeTopicCommand.requestId = command.requestID;
                incommingCmd = new UnSubscribeTopicCommand();
                break;

            case Common.Protobuf.Command.Type.REMOVE_TOPIC:
                command.removeTopicCommand.requestId = command.requestID;
                incommingCmd = new RemoveTopicCommand();
                break;

            case Common.Protobuf.Command.Type.MESSAGE_PUBLISH:
                command.messagePublishCommand.requestId = command.requestID;
                incommingCmd = new MessagePublishCommand();
                break;

            case Common.Protobuf.Command.Type.GET_MESSAGE:
                command.getMessageCommand.requestId = command.requestID;
                incommingCmd = new GetMessageCommand();
                break;

            case Common.Protobuf.Command.Type.MESSAGE_ACKNOWLEDGMENT:
                command.mesasgeAcknowledgmentCommand.requestId = command.requestID;
                incommingCmd = new MessageAcknowledgementCommand();
                break;
                #endregion
            }


            if (SocketServer.IsServerCounterEnabled)
            {
                _perfStatsCollector.MsecPerCacheOperationBeginSample();
            }

            try
            {
                if (incommingCmd != null)
                {
                    incommingCmd.RequestTimeout = clientManager.RequestTimeout;

                    if (IsMonitoringCommand(command) && ServiceConfiguration.EnableRequestCancellation)
                    {
                        RequestMonitor.Instance.RegisterClientrequestsInLedger(clientManager.ClientID, ((NCache)clientManager.CmdExecuter).Cache.NCacheLog, command.requestID, incommingCmd);
                    }
                }
                if (isUnsafeCommand && clientManager.SupportAcknowledgement)
                {
                    if (clientDisposed)
                    {
                        bookie.RemoveClientAccount(clientManager.ClientID);
                    }
                    else
                    {
                        bookie.RegisterRequest(clientManager.ClientID, command.requestID, command.commandID,
                                               acknowledgementId);
                    }
                }
                incommingCmd.ExecuteCommand(clientManager, command);
                if (command.type == Alachisoft.NCache.Common.Protobuf.Command.Type.INIT && ServiceConfiguration.EnableRequestCancellation)
                {
                    RequestMonitor.Instance.RegisterClientLedger(clientManager.ClientID, ((NCache)clientManager.CmdExecuter).Cache.NCacheLog);
                }
            }
            catch (Exception ex)
            {
                if (isUnsafeCommand && clientManager.SupportAcknowledgement)
                {
                    bookie.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID,
                                         Alachisoft.NCache.Common.Enum.RequestStatus.RECEIVED_WITH_ERROR, null);
                }
                throw;
            }

            finally
            {
                if (IsMonitoringCommand(command) && ServiceConfiguration.EnableRequestCancellation)
                {
                    incommingCmd.Dispose();
                    RequestMonitor.Instance.UnRegisterClientRequests(clientManager.ClientID, command.requestID);
                }
            }
            if (SocketServer.Logger.IsDetailedLogsEnabled)
            {
                SocketServer.Logger.NCacheLog.Info("ConnectionManager.ReceiveCallback", clientManager.ToString() + " after executing COMMAND : " + command.type.ToString() + " RequestId :" + command.requestID);
            }

            if (SocketServer.IsServerCounterEnabled)
            {
                _perfStatsCollector.MsecPerCacheOperationEndSample();
            }

#if COMMUNITY
            if (clientManager != null && clientManager.CmdExecuter != null && incommingCmd.OperationResult == OperationResult.Success)
            {
                clientManager.CmdExecuter.UpdateSocketServerStats(new SocketServerStats(clientManager.ClientsRequests, clientManager.ClientsBytesSent, clientManager.ClientsBytesRecieved));
            }
#endif
            if (isUnsafeCommand && clientManager.SupportAcknowledgement)
            {
                if (clientManager != null && clientManager.IsDisposed && incommingCmd.OperationResult == OperationResult.Failure)
                {
                    bookie.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID, Common.Enum.RequestStatus.RECEIVED_WITH_ERROR, null);
                }
                else
                {
                    bookie.UpdateRequest(clientManager.ClientID, command.requestID, command.commandID, Common.Enum.RequestStatus.RECEIVED_AND_EXECUTED, incommingCmd.SerializedResponsePackets);
                }
            }
            if (clientManager != null && !clientManager.IsCacheStopped)
            {
                if (incommingCmd.SerializedResponsePackets != null)
                {
                    if (SocketServer.IsServerCounterEnabled)
                    {
                        _perfStatsCollector.IncrementResponsesPerSecStats(1);
                    }

                    foreach (IList reponse in incommingCmd.SerializedResponsePackets)
                    {
                        ConnectionManager.AssureSend(clientManager, reponse, Alachisoft.NCache.Common.Enum.Priority.Normal);
                    }
                }
                commandExecution.Stop();
                if (!isAsync && command.type != Common.Protobuf.Command.Type.PING && (incommingCmd.SerializedResponsePackets == null || incommingCmd.SerializedResponsePackets.Count <= 0))
                {
                    try
                    {
                        if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging)
                        {
                            APILogItemBuilder log = new APILogItemBuilder();
                            log.GenerateCommandManagerLog(_methodName, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString(), commandExecution.Elapsed, "Serialized Response Packets for " + _methodName + " command is null or empty.");
                        }
                    }
                    catch
                    {
                    }
                }
            }
            double commandElapsedSeconds = commandExecution.Elapsed.TotalSeconds;

            if (ServiceConfiguration.EnableCommandThresholdLogging && commandElapsedSeconds > ServiceConfiguration.CommandExecutionThreshold)
            {
                try
                {
                    string   commandName;
                    string   details       = incommingCmd.GetCommandParameters(out commandName);
                    string[] clientIdParts = clientManager.ClientID.Split(':');
                    string   clientipid    = "CLIENT";
                    try
                    {
                        clientipid = clientIdParts[clientIdParts.Length - 2] + ":" + clientIdParts[clientIdParts.Length - 1];
                    }
                    catch { }

                    CommandLogManager.LogInfo(clientipid, commandElapsedSeconds.ToString(), commandName, details);
                }
                catch (Exception ex)
                {
                }
            }

            if (stats != null)
            {
                stats.EndSample();
                if (incommingCmd != null)
                {
                    // Increment Counter
                    incommingCmd.IncrementCounter(_perfStatsCollector, stats.Current);
                }
            }

            if (ServerMonitor.MonitorActivity)
            {
                ServerMonitor.LogClientActivity("CmdMgr.PrsCmd", "exit");
            }
        }