Beispiel #1
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 #2
0
            public virtual void Run()
            {
                Message msg= null;
                byte[] buf = null;
                int len = 0;
                while (handler != null)
                {
                    Stream stmIn = null;
                    BinaryReader msgReader = null;
                    try
                    {
                        if (sock == null)
                        {
                            NCacheLog.Error("input stream is null !");
                            break;
                        }
                        byte[] lenBuff = new byte[4];
                        buf = null;

                        Util.Util.ReadInput(sock, lenBuff, 0, lenBuff.Length);

                        len = Util.Util.convertToInt32(lenBuff);

                        
                        buf = receiveBuffer;
                        if (len > receiveBuffer.Length)
                            buf = new byte[len];

                        
                        HPTimeStats socketReceiveTimeStats = null;
                        if (enclosingInstance.enableMonitoring)
                        {
                            socketReceiveTimeStats = new HPTimeStats();
                            socketReceiveTimeStats.BeginSample();
                        }
                        DateTime dt = DateTime.Now;
                        int recLength = Util.Util.ReadInput(sock, buf, 0, len);
                        DateTime now = DateTime.Now;

                        TimeSpan ts = now - dt;

                        if (ts.TotalMilliseconds > _worsRecvTime.TotalMilliseconds)
                            _worsRecvTime = ts;


                        if (socketReceiveTimeStats != null)
                        {
                            socketReceiveTimeStats.EndSample();

                            enclosingInstance.enclosingInstance.Stack.perfStatsColl.IncrementSocketReceiveTimeStats((long)socketReceiveTimeStats.Current);
                            enclosingInstance.enclosingInstance.Stack.perfStatsColl.IncrementSocketReceiveSizeStats((long)len);

                        }

                        enclosingInstance.publishBytesReceivedStats(len + 4);
                       

                        if (recLength == len)
                        {
                            int noOfMessages = Util.Util.convertToInt32(buf, 0);
                            int messageBaseIndex = 4;
                            for (int msgCount = 0; msgCount < noOfMessages; msgCount++)
                            {
                                int totalMessagelength = Util.Util.convertToInt32(buf, messageBaseIndex);
                                int messageLength = Util.Util.convertToInt32(buf, messageBaseIndex + 4);
                                
                                stmIn = new MemoryStream();
                                stmIn.Position = 0;
                                stmIn.Write(buf, messageBaseIndex + 8, messageLength);
                                stmIn.Position = 0;
                                msgReader = new BinaryReader(stmIn, new UTF8Encoding(true));
                                FlagsByte flags = new FlagsByte();
                                flags.DataByte = msgReader.ReadByte();

                                if (flags.AnyOn(FlagsByte.Flag.TRANS))
                                {
                                    Message tmpMsg = new Message();
                                    tmpMsg.DeserializeLocal(msgReader);
                                    msg = tmpMsg;
                                }
                                else
                                {
                                    msg = (Message)CompactBinaryFormatter.Deserialize(stmIn, null, false, null);
                                }

                                if (msg != null)
                                {
                                    int payLoadLength = totalMessagelength - messageLength - 4;
                                    if (payLoadLength > 0)
                                    {

                                        int noOfChunks = payLoadLength / LARGE_OBJECT_SIZE;
                                        noOfChunks += (payLoadLength - (noOfChunks * LARGE_OBJECT_SIZE)) != 0 ? 1 : 0;
                                        Array payload = new Array[noOfChunks];

                                        int nextChunk = 0;
                                        int nextChunkSize = 0;
                                        int startIndex = messageBaseIndex + 8 + messageLength;

                                        for (int i = 0; i < noOfChunks; i++)
                                        {
                                            nextChunkSize = payLoadLength - nextChunk;
                                            if (nextChunkSize > LARGE_OBJECT_SIZE)
                                                nextChunkSize = LARGE_OBJECT_SIZE;

                                            byte[] binaryChunk = new byte[nextChunkSize];
                                            Buffer.BlockCopy(buf, startIndex, binaryChunk, 0, nextChunkSize);
                                            nextChunk += nextChunkSize;
                                            startIndex += nextChunkSize;

                                            payload.SetValue(binaryChunk, i);
                                        }

                                        msg.Payload = payload;
                                    }
                                    messageBaseIndex += (totalMessagelength + 4);
                                    ConnectionHeader hdr = msg.getHeader("ConnectionHeader") as ConnectionHeader;
                                    if (hdr != null)
                                    {
                                        switch (hdr.Type)
                                        {
                                            case ConnectionHeader.CLOSE_SILENT:

                                                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.Run", "connection being closed silently");
                                                this.self_close = true;
                                                handler = null;
                                                continue;

                                            case ConnectionHeader.LEAVE:
                                                //The node is leaving the cluster gracefully.
                                                leavingGracefully = true;
                                                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.Run", peer_addr.ToString() + " is leaving gracefully");
                                                handler = null;
                                                continue;

                                            case ConnectionHeader.GET_SECOND_ADDRESS_REQ:
                                                SendSecondaryAddressofPeer();
                                                continue;

                                            case ConnectionHeader.GET_SECOND_ADDRESS_RSP:
                                                lock (get_addr_sync)
                                                {
                                                    secondaryAddress = hdr.MySecondaryAddress;
                                                    Monitor.PulseAll(get_addr_sync);
                                                }
                                                continue;

                                            case ConnectionHeader.ARE_U_IN_INITIALIZATION_PHASE:
                                                try
                                                {
                                                    bool iMinInitializationPhase = !enclosingInstance.enclosingInstance.Stack.IsOperational;
                                                    SendInitializationPhaseRsp(iMinInitializationPhase);
                                                }
                                                catch (Exception e)
                                                {

                                                }
                                                break;

                                            case ConnectionHeader.INITIALIZATION_PHASE_RSP:
                                                lock (initializationPhase_mutex)
                                                {
                                                    inInitializationPhase = hdr.InitializationPhase;
                                                    Monitor.PulseAll(inInitializationPhase);
                                                }
                                                break;
                                        }
                                    }
                                }
                                msg.Src = peer_addr;


                                msg.MarkArrived();
                                Enclosing_Instance.receive(msg); // calls receiver.receiver(msg)
                            }
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        break;
                    }
                    catch (ThreadAbortException)
                    {
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        break;
                    }
                    catch (ThreadInterruptedException)
                    {
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        break;

                    }
                    catch (System.OutOfMemoryException memExc)
                    {
                        lock (send_mutex) { isConnected = false; }
                        NCacheLog.CriticalInfo("Connection.Run()", Enclosing_Instance.local_addr + "-->" + peer_addr.ToString() + " memory exception " + memExc.ToString());
                        break; // continue;
                    }
                    catch (ExtSocketException sock_exp)
                    {
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        // peer closed connection
                        NCacheLog.Error("Connection.Run()", Enclosing_Instance.local_addr + "-->" + peer_addr.ToString() + " exception is " + sock_exp.Message);
                        break;
                    }
                    catch (System.IO.EndOfStreamException eof_ex)
                    {
                        lock (send_mutex) { isConnected = false; }
                        // peer closed connection
                        NCacheLog.Error("Connection.Run()", "data :" + len + Enclosing_Instance.local_addr + "-->" + peer_addr.ToString() + " exception is " + eof_ex);
                        
                        break;
                    }
                    catch (System.Net.Sockets.SocketException io_ex)
                    {
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        NCacheLog.Error("Connection.Run()", Enclosing_Instance.local_addr + "-->" + peer_addr.ToString() + " exception is " + io_ex.Message);
                      
                        break;
                    }
                    catch (System.ArgumentException ex)
                    {
                        lock (send_mutex) { isConnected = false; }
                        break;
                    }
                    catch (System.Exception e)
                    {
                        lock (send_mutex) { isConnected = false; }
                        NCacheLog.Error("Connection.Run()", Enclosing_Instance.local_addr + "-->" + peer_addr.ToString() + " exception is " + e);
                        break;
                    }
                    finally
                    {
                        if (stmIn != null) stmIn.Close();
                        if (msgReader != null) msgReader.Close();
                    }
                }

                handler = null;
                
                if (LeavingGracefully)
                {
                  
                    enclosingInstance.notifyConnectionClosed(peer_addr);
                    enclosingInstance.remove(peer_addr, IsPrimary);

                }
            }
Beispiel #3
0
        /// <summary>Sends a message to a unicast destination. The destination has to be set</summary>
        /// <param name="msg">The message to send
        /// </param>
        /// <throws>  SocketException Thrown if connection cannot be established </throws>
        /// <param name="reEstablishCon">indicate that if connection is not found in
        /// connectin table then re-establish the connection or not.
        /// </param>
        public virtual long send(Address dest, byte[] msg, bool reEstablishCon, Array userPayload,Priority priority)
        {
            Connection conn = null;
            long bytesSent = 0;
            if (dest == null)
            {
                NCacheLog.Error("msg is null or message's destination is null");
                return bytesSent;
            }

            // 1. Try to obtain correct Connection (or create one if not yet existent)
            try
            {
                conn = GetConnection(dest, reEstablishCon);//getConnection(dest, reEstablishCon,useDualConnection);
                if (conn == null)
                {
                    //NCacheLog.Info("ConnectionTable.send", "no connection found with " + dest);
                    if (useDedicatedSender)
                    {
                        DedicatedMessageSendManager dmSenderMgr = dedicatedSenders[dest] as DedicatedMessageSendManager;
                        if (dmSenderMgr != null)
                        {
                            int queueCount = dmSenderMgr.QueueMessage(msg, userPayload,priority);

                            enclosingInstance.Stack.perfStatsColl.IncrementTcpDownQueueCountStats(queueCount);

                            return bytesSent;
                        }
                    }
                    return bytesSent;
                }
            }
            catch (System.Net.Sockets.SocketException sock_ex)
            {
                if (NCacheLog.IsErrorEnabled) NCacheLog.Error("ConnectionTable.GetConnection",   sock_ex.Message);
                for (int i = 0; i < conn_listeners.Count; i++)
                    ((ConnectionTable.ConnectionListener)conn_listeners[i]).couldnotConnectTo(dest);

                return bytesSent;
            }
            catch (ThreadAbortException) { return bytesSent; }
            catch (ThreadInterruptedException) { return bytesSent; }
            catch (System.Exception ex)
            {
                if (NCacheLog.IsErrorEnabled) NCacheLog.Error("ConnectionTable.GetConnection",   "connection to " + dest + " could not be established: " + ex);
                throw new ExtSocketException(ex.ToString());
            }

            // 2. Send the message using that connection
            try
            {
                if (useDedicatedSender)
                {
                    DedicatedMessageSendManager dmSenderMgr = dedicatedSenders[dest] as DedicatedMessageSendManager;
                    if (dmSenderMgr != null)
                    {
                        int queueCount = dmSenderMgr.QueueMessage(msg, userPayload,priority);

                        enclosingInstance.Stack.perfStatsColl.IncrementTcpDownQueueCountStats(queueCount);

                        return bytesSent;
                    }
                }
                HPTimeStats socketSendTimeStats = null;
                if (enclosingInstance.enableMonitoring)
                {
                    socketSendTimeStats = new HPTimeStats();
                    socketSendTimeStats.BeginSample();
                }
                bytesSent = conn.send(msg, userPayload);

                if (socketSendTimeStats != null)
                {
                    socketSendTimeStats.EndSample();
                    long operationsperSec = (long)(1000 / socketSendTimeStats.Avg);
                    
                }
            }
            catch (System.Exception ex)
            {
                if (conn.NeedReconnect)
                {
                    if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ConnectionTable.send",   local_addr + " re-establishing connection with " + dest);

                    conn = ReEstablishConnection(dest);
                    if (conn != null)
                    {
                        if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ConnectionTable.send",   local_addr + " re-established connection successfully with " + dest);

                        try
                        {
                            bytesSent = conn.send(msg, userPayload);
                            return bytesSent;
                        }
                        catch (Exception e)
                        {
                            NCacheLog.Error("ConnectionTable.send",   "send failed after reconnect " + e.ToString());
                        }
                    }
                    else
                        NCacheLog.Error("ConnectionTable.send",   local_addr + " failed to re-establish connection  with " + dest);
                }
                else
                    if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ConnectionTable.send",   local_addr + " need not to re-establish connection with " + dest);

                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Ct.send",   "sending message to " + dest + " failed (ex=" + ex.GetType().FullName + "); removing from connection table");
                throw new ExtSocketException(ex.ToString());
            }
            return bytesSent;
        }
Beispiel #4
0
        /// <summary>
        /// Removes the objects for the given keys from the cache.
        /// The keys are specified as parameter.
        /// </summary>
        /// <param name="keys">array of keys to be removed</param>
        public void Delete(object[] keys, BitSet flagMap, CallbackEntry cbEntry, OperationContext operationContext)
        {
            if (keys == null) throw new ArgumentNullException("keys");

            // Cache has possibly expired so do default.
            if (!IsRunning) return; 

           

            try
            {
                HPTimeStats removeTime = new HPTimeStats();
                removeTime.BeginSample();
                IDictionary removed = CascadedRemove(keys, ItemRemoveReason.Removed, true, operationContext);
                removeTime.EndSample();
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Delete()", inner.ToString());
                throw new OperationFailedException("Delete operation failed. Error : " + inner.Message, inner);
            }
        }
Beispiel #5
0
            internal virtual long send(byte[] msg, Array userPayload, int bytesToSent)
            {
                long bytesSent = 0;
                try
                {
                    HPTimeStats socketSendTimeStats = null;
                    if (enclosingInstance.enableMonitoring)
                    {
                        socketSendTimeStats = new HPTimeStats();
                        socketSendTimeStats.BeginSample();
                    }
                    bytesSent = doSend(msg, userPayload, bytesToSent);
                    if (socketSendTimeStats != null)
                    {
                        socketSendTimeStats.EndSample();

                        enclosingInstance.enclosingInstance.Stack.perfStatsColl.IncrementSocketSendTimeStats((long)socketSendTimeStats.Current);
                        enclosingInstance.enclosingInstance.Stack.perfStatsColl.IncrementSocketSendSizeStats((long)bytesSent);

                    }
                    
                }
          
                catch (ObjectDisposedException)
                {
                    
                    
                        lock (send_mutex)
                        {
                            socket_error = true;
                            isConnected = false;
                        }
                        throw new ExtSocketException("Connection is closed");
                    
                }
                catch (SocketException sock_exc)
                {
                    lock (send_mutex)
                    {
                        socket_error = true;
                        isConnected = false;
                    }
                    throw new ExtSocketException(sock_exc.Message);
                }
                catch (System.Exception ex)
                {
                    NCacheLog.Error("exception is " + ex);
                    throw;
                }
                return bytesSent;
            }
Beispiel #6
0
        public void Delete(string key, BitSet flag, CallbackEntry cbEntry, object lockId, LockAccessType accessType, OperationContext operationContext)
        {
            if (key == null) throw new ArgumentNullException("key");
            if (!key.GetType().IsSerializable)
                throw new ArgumentException("key is not serializable");

            // Cache has possibly expired so do default.
            if (!IsRunning) return;

            try
            {
                HPTimeStats removeTime = new HPTimeStats();
                removeTime.BeginSample();

                _context.PerfStatsColl.MsecPerDelBeginSample();

                object packedKey = key;

                CacheEntry e = CascadedRemove(key, packedKey, ItemRemoveReason.Removed, true, lockId,accessType, operationContext);

                _context.PerfStatsColl.MsecPerDelEndSample();
                _context.PerfStatsColl.IncrementDelPerSecStats();
                removeTime.EndSample();
            }
            catch (OperationFailedException ex)
            {
                if (ex.IsTracable) _context.NCacheLog.Error("Cache.Delete()", ex.ToString());
                throw ex;
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Delete()", inner.ToString());
                throw new OperationFailedException("Delete operation failed. Error : " + inner.Message, inner);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Removes the objects for the given keys from the cache.
        /// The keys are specified as parameter.
        /// </summary>
        /// <param name="keys">array of keys to be removed</param>
        /// <param name="flagMap"></param>
        /// <param name="cbEntry"></param>
        /// <param name="operationContext"></param>
        /// <returns>keys that failed to be removed</returns>
        public IDictionary Remove(object[] keys, BitSet flagMap, CallbackEntry cbEntry, OperationContext operationContext)
        {
            if (keys == null) throw new ArgumentNullException("keys");

            // Cache has possibly expired so do default.
            if (!IsRunning) return null; 

            try
            {
                HPTimeStats removeTime = new HPTimeStats();
                removeTime.BeginSample();

                IDictionary removed = CascadedRemove(keys, ItemRemoveReason.Removed, true, operationContext);
                removeTime.EndSample();

                CompressedValueEntry val = null;
                if (removed != null)
                {
                    object[] keysCollection = new object[removed.Count];
                    removed.Keys.CopyTo(keysCollection, 0);
                    IEnumerator ie = keysCollection.GetEnumerator();
                    while (ie.MoveNext())
                    {
                        CacheEntry entry = removed[ie.Current] as CacheEntry;
                        if (entry != null)
                        {
                            val = new CompressedValueEntry();
                            val.Value = entry.Value;
                            if (val.Value is CallbackEntry)
                                val.Value = ((CallbackEntry)val.Value).Value;
                            val.Flag = entry.Flag;
                            removed[ie.Current] = val;
                        }
                    }
                }
                return removed;
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Remove()", inner.ToString());
                throw new OperationFailedException("Remove operation failed. Error : " + inner.Message, inner);
            }
            return null;
        }
Beispiel #8
0
        /// <summary>
        /// Overload of Insert operation for bulk inserts. Uses EvictionHint and ExpirationHint arrays.
        /// </summary>
        public IDictionary Insert(object[] keys, object[] values, CallbackEntry[] callbackEnteries,
                                           ExpirationHint[] expirations, EvictionHint[] evictions,
                                           Hashtable[] queryInfos, BitSet[] flags,OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Cache.InsertBlk", "");

            if (keys == null) throw new ArgumentNullException("keys");
            if (values == null) throw new ArgumentNullException("items");
            if (keys.Length != values.Length) throw new ArgumentException("keys count is not equals to values count");
           

            CacheEntry[] ce = new CacheEntry[values.Length];
            long[] sizes = null;
            object dataSize = operationContext.GetValueByField(OperationContextFieldName.ValueDataSize);
            if (dataSize != null)
            {
                sizes = (long[])dataSize;
            }
            for (int i = 0; i < values.Length; i++)
            {

                if (keys[i] == null) throw new ArgumentNullException("key");
                if (values[i] == null) throw new ArgumentNullException("value");

                if (!keys[i].GetType().IsSerializable)
                    throw new ArgumentException("key is not serializable");
                if (!values[i].GetType().IsSerializable)
                    throw new ArgumentException("value is not serializable");
                if ((expirations[i] != null) && !expirations[i].GetType().IsSerializable)
                    throw new ArgumentException("expiryHint is not not serializable");
                if ((evictions[i] != null) && !evictions[i].GetType().IsSerializable)
                    throw new ArgumentException("evictionHint is not serializable");

                // Cache has possibly expired so do default.
                if (!IsRunning) return null;

                ce[i] = new CacheEntry(values[i], expirations[i], evictions[i]);



                ce[i].QueryInfo = queryInfos[i];
                ce[i].Flag.Data |= flags[i].Data;
                if(sizes != null)
                    ce[i].DataSize = sizes[i];
                if (callbackEnteries[i] != null)
                {
                    CallbackEntry cloned = callbackEnteries[i].Clone() as CallbackEntry;
                    cloned.Value = values[i];
                    cloned.Flag = ce[i].Flag;
                    ce[i].Value = cloned;
                }
            }

            /// update the counters for various statistics
            try
            {
               

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

                IDictionary result = Insert(keys, ce, operationContext);

                insertTime.EndSample();

                return result;
            }
            catch (Exception inner)
            {
                throw;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Internal Insert operation. Does a write thru as well.
        /// </summary>
        private void Insert(object key, CacheEntry e, object lockId, LockAccessType accessType, OperationContext operationContext)
        {
           
            HPTimeStats insertTime = new HPTimeStats();
            insertTime.BeginSample();

            object value = e.Value;
            try
            {
                CacheInsResultWithEntry retVal = CascadedInsert(key, e, true, lockId, accessType, operationContext);
                insertTime.EndSample();

                switch (retVal.Result)
                {
                    case CacheInsResult.Failure:
                        break;

                    case CacheInsResult.NeedsEviction:
                    case CacheInsResult.NeedsEvictionNotRemove:
                       throw new OperationFailedException("The cache is full and not enough items could be evicted.", false);

                    case CacheInsResult.SuccessOverwrite:
                        _context.PerfStatsColl.IncrementUpdPerSecStats();
                        break;
                    case CacheInsResult.Success:
                        _context.PerfStatsColl.IncrementAddPerSecStats();
                        break;
                    case CacheInsResult.ItemLocked:
                        throw new LockingException("Item is locked.");
                }
            }
            catch (OperationFailedException inner)
            {
                if (inner.IsTracable) _context.NCacheLog.Error("Cache.Insert():", inner.ToString());
                throw;
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Insert():", inner.ToString());
                _context.NCacheLog.CriticalInfo("Cache.Insert():", inner.ToString());

                throw new OperationFailedException("Insert operation failed. Error : " + inner.Message, inner);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Overload of Add operation. uses additional paramer of Flag for checking if compressed or not
        /// </summary>
        public void Add(object key, object value,
                        ExpirationHint expiryHint, EvictionHint evictionHint,
                        Hashtable queryInfo, BitSet flag, 
                       OperationContext operationContext)
        {
            if (key == null) throw new ArgumentNullException("key");
            if (value == null) throw new ArgumentNullException("value");

            if (!key.GetType().IsSerializable)
                throw new ArgumentException("key is not serializable");
            if (!value.GetType().IsSerializable)
                throw new ArgumentException("value is not serializable");
            if ((expiryHint != null) && !expiryHint.GetType().IsSerializable)
                throw new ArgumentException("expiryHint is not serializable");
            if ((evictionHint != null) && !evictionHint.GetType().IsSerializable)
                throw new ArgumentException("evictionHint is not serializable");

            // Cache has possibly expired so do default.
            if (!IsRunning) return; 
           
            CacheEntry e = new CacheEntry(value, expiryHint, evictionHint);
            ////Object size for inproc
            object dataSize = operationContext.GetValueByField(OperationContextFieldName.ValueDataSize);
            if (dataSize != null)
                e.DataSize = Convert.ToInt64(dataSize);
           
            e.QueryInfo = queryInfo;
            e.Flag.Data |= flag.Data;        
            try
            {
                HPTimeStats addTime = new HPTimeStats();
                _context.PerfStatsColl.MsecPerAddBeginSample();
                
                addTime.BeginSample();
                Add(key, e, operationContext);
                addTime.EndSample();
                _context.PerfStatsColl.MsecPerAddEndSample();
            }
            catch (Exception inner)
            {
                throw;
            }
        }
Beispiel #11
0
        /// <summary>
        /// Retrieve the array of objects from the cache.
        /// An array of keys is passed as parameter.
        /// </summary>
        public IDictionary GetBulk(object[] keys, BitSet flagMap, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Cache.GetBlk", "");

            if (keys == null) throw new ArgumentNullException("keys");

            // Cache has possibly expired so do default.
            if (!IsRunning) return null; 

            Hashtable table = null;
            try
            {
              
                HPTimeStats getTime = new HPTimeStats();
                getTime.BeginSample();

                table = _context.CacheImpl.Get(keys, operationContext);

                if (table != null)
                {
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (table.ContainsKey(keys[i]))
                        {
                            if (table[keys[i]] != null)
                            {
                                CacheEntry entry = table[keys[i]] as CacheEntry;
                                CompressedValueEntry val = new CompressedValueEntry();
                                val.Value = entry.Value is CallbackEntry ? ((CallbackEntry)entry.Value).Value : entry.Value;
                                val.Flag = entry.Flag;
                                table[keys[i]] = val;
                            }
                        }
                    }
                }
            }
            catch (OperationFailedException inner)
            {
                if (inner.IsTracable) _context.NCacheLog.Error("Cache.Get()", inner.ToString());
                throw;
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Get()", inner.ToString());
                throw new OperationFailedException("Get operation failed. Error : " + inner.Message, inner);
            }
            return table;
        }
Beispiel #12
0
        public CompressedValueEntry Get(object key, BitSet flagMap,ref object lockId, ref DateTime lockDate, TimeSpan lockTimeout, LockAccessType accessType, OperationContext operationContext)
        {
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Cache.GetGrp", "");
            // Cache has possibly expired so do default.
            if (!IsRunning) return null; 

            CompressedValueEntry result = new CompressedValueEntry();
            CacheEntry e = null;
            try
            {
                _context.PerfStatsColl.MsecPerGetBeginSample();
                _context.PerfStatsColl.IncrementGetPerSecStats();
                _context.PerfStatsColl.IncrementHitsRatioPerSecBaseStats();
                HPTimeStats getTime = new HPTimeStats();
                getTime.BeginSample();

                LockExpiration lockExpiration = null;
                if (accessType == LockAccessType.ACQUIRE)
                {
                    lockId = GetLockId(key);
                    lockDate = DateTime.UtcNow;

                    if (!TimeSpan.Equals(lockTimeout, TimeSpan.Zero))
                    {
                        lockExpiration = new LockExpiration(lockTimeout);
                    }
                }

                object generatedLockId = lockId;

                e = _context.CacheImpl.Get(key, ref lockId, ref lockDate, lockExpiration, accessType, operationContext);
                

                if (e == null && accessType == LockAccessType.ACQUIRE)
                {
                    if (lockId == null || generatedLockId.Equals(lockId))
                    {
                        lockId = null;
                        lockDate = new DateTime();
                    }
                }
                if (flagMap != null)
                {
                    
                    if (e != null)
                    {
                        /// increment the counter for hits/sec
                        _context.PerfStatsColl.MsecPerGetEndSample();
                        result.Value = e.Value;
                        result.Flag = e.Flag;
                    }

                }
                _context.PerfStatsColl.MsecPerGetEndSample();
                getTime.EndSample();
                
                /// update the counter for hits/sec or misses/sec
                if (result.Value != null)
                {
                    _context.PerfStatsColl.IncrementHitsRatioPerSecStats();
                    _context.PerfStatsColl.IncrementHitsPerSecStats();
                }
                else
                {
                    _context.PerfStatsColl.IncrementMissPerSecStats();
                }
                if (result.Value is CallbackEntry)
                    result.Value = ((CallbackEntry)result.Value).Value;
            }
            catch (OperationFailedException inner)
            {
                if (inner.IsTracable) _context.NCacheLog.Error("Cache.Get()", "Get operation failed. Error : " + inner.ToString());
                throw;
            }
            catch (Exception inner)
            {
                _context.NCacheLog.Error("Cache.Get()", "Get operation failed. Error : " + inner.ToString());
                throw new OperationFailedException("Get operation failed. Error :" + inner.Message, inner);
            }

            return result;
        }