コード例 #1
0
ファイル: Message.cs プロジェクト: javithalion/NCache
		public void SerializeLocal(BinaryWriter writer)
		{
			//Check in sequence of headers.. 
			FlagsByte bFlags = new FlagsByte();
			if (IsUserMsg)
				bFlags.SetOn(FlagsByte.Flag.TRANS);

			object tmpHdr;
			tmpHdr = (Header)headers[(object)(HeaderType.REQUEST_COORELATOR)];
			if (tmpHdr != null)
			{
				RequestCorrelator.HDR corHdr = (RequestCorrelator.HDR)tmpHdr;
				corHdr.SerializeLocal(writer);
				bFlags.SetOn(FlagsByte.Flag.COR);
			}

			tmpHdr = (Header)headers[(object)(HeaderType.TOTAL)];
			if (tmpHdr != null)
			{
				TOTAL.HDR totalHdr = (TOTAL.HDR)tmpHdr;
				totalHdr.SerializeLocal(writer);
				bFlags.SetOn(FlagsByte.Flag.TOTAL);
			}

			tmpHdr = (Header)headers[(object)(HeaderType.TCP)];
			if (tmpHdr != null)
			{
				TcpHeader tcpHdr = (TcpHeader)tmpHdr;
				tcpHdr.SerializeLocal(writer);
				bFlags.SetOn(FlagsByte.Flag.TCP);
			}

			writer.Write(Convert.ToInt16(prio));
			writer.Write(handledAsynchronously);
            writer.Write(arrivalTime.Ticks);
            writer.Write(sendTime.Ticks);
            writer.Write(responseExpected);
            writer.Write(_type);
            if (stream != null)
            {
                writer.Write(length);
                writer.Write(((MemoryStream)stream).GetBuffer(), 0, length);
            }
            else
            {
                int length = buf.Length;
                writer.Write(length);
                writer.Write(buf);
            }
			long curPos = writer.BaseStream.Position;
			writer.BaseStream.Position = 8; //afte 4 bytes of total size and 4 bytes of message size ..here comes the flag.
			writer.Write(bFlags.DataByte);
			writer.BaseStream.Position = curPos;
		}
コード例 #2
0
ファイル: ConnectionTable.cs プロジェクト: javithalion/NCache
            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);

                }
            }
コード例 #3
0
ファイル: Message.cs プロジェクト: javithalion/NCache
		public void DeserializeLocal(BinaryReader reader)
		{
			isUserMsg = true;
			reader.BaseStream.Position = 0;
			byte flags = reader.ReadByte();
			FlagsByte bFlags = new FlagsByte();
			bFlags.DataByte = flags;
			//Headers are in sequence 1. COR  2. TOTAL 3. TCP
			headers = new Hashtable();
			if (bFlags.AnyOn(FlagsByte.Flag.COR))
			{
				RequestCorrelator.HDR corHdr = new RequestCorrelator.HDR();
				corHdr.DeserializeLocal(reader);
				headers.Add(HeaderType.REQUEST_COORELATOR, corHdr);
			}

			if (bFlags.AnyOn(FlagsByte.Flag.TOTAL))
			{
				TOTAL.HDR totalHdr = new TOTAL.HDR();
				totalHdr.DeserializeLocal(reader);
				headers.Add(HeaderType.TOTAL, totalHdr);

			}

			if (bFlags.AnyOn(FlagsByte.Flag.TCP))
			{
				TcpHeader tcpHdr = new TcpHeader();
				tcpHdr.DeserializeLocal(reader);
				headers.Add(HeaderType.TCP, tcpHdr);
			}

			prio = (Priority)Enum.ToObject(typeof(Priority), reader.ReadInt16());
			handledAsynchronously = reader.ReadBoolean();
            long ticks = reader.ReadInt64();
            arrivalTime = new DateTime(ticks);
            ticks = reader.ReadInt64();
            sendTime = new DateTime(ticks);
            responseExpected = reader.ReadBoolean();
            _type = reader.ReadByte();
           
			length = reader.ReadInt32();
			buf = (byte[])reader.ReadBytes(length);
			
		}
コード例 #4
0
ファイル: Util.cs プロジェクト: javithalion/NCache
        internal static byte[] serializeMessage(Message msg)
        {
            int len = 0;
            byte[] buffie;
            FlagsByte flags = new FlagsByte();

            msg.Dest = null;
            msg.Dests = null;

            RequestCorrelator.HDR rqHeader = (RequestCorrelator.HDR)msg.getHeader(HeaderType.REQUEST_COORELATOR);

            if (rqHeader != null)
            {
                rqHeader.serializeFlag = false;
            }

            Stream stmOut = new MemoryStream();
            stmOut.Write(Util.WriteInt32(len), 0, 4);
            stmOut.Write(Util.WriteInt32(len), 0, 4);

            if (msg.IsUserMsg)
            {
                BinaryWriter msgWriter = new BinaryWriter(stmOut, new UTF8Encoding(true));
                flags.SetOn(FlagsByte.Flag.TRANS);
                msgWriter.Write(flags.DataByte);
                msg.SerializeLocal(msgWriter);
            }
            else
            {
                flags.SetOff(FlagsByte.Flag.TRANS);
                stmOut.WriteByte(flags.DataByte);
                CompactBinaryFormatter.Serialize(stmOut, msg, null, false);
            }

            len = (int)stmOut.Position - 4;

            int payloadLength = 0;
            // the user payload size. payload is passed on untill finally send on the socket.
            if (msg.Payload != null)
            {
                for (int i = 0; i < msg.Payload.Length; i++)
                {
                    payloadLength += ((byte[])msg.Payload.GetValue(i)).Length;
                }
                len += payloadLength;
            }

            stmOut.Position = 0;
            stmOut.Write(Util.WriteInt32(len), 0, 4);
            stmOut.Write(Util.WriteInt32(len - 4 - payloadLength), 0, 4);
            stmOut.Position = 0;
            buffie = new byte[len + 4 - payloadLength];
            stmOut.Read(buffie, 0, len + 4 - payloadLength);
            stmOut.Position = 0;

            return buffie;
        }