예제 #1
0
 public virtual void handleIsClusterInStateTransfer(Address sender)
 {
     Message msg = new Message(sender, null, new byte[0]);
     GMS.HDR hdr = new GMS.HDR(GMS.HDR.IS_NODE_IN_STATE_TRANSFER_RSP);
     gms.Stack.NCacheLog.Debug("gmsImpl.handleIsClusterInStateTransfer", "(state transfer request) sender: " + sender + " ->" + isInStateTransfer);
     hdr.arg = isInStateTransfer;
     msg.putHeader(HeaderType.GMS,hdr);
     gms.passDown(new Event(Event.MSG,msg,Alachisoft.NCache.Common.Enum.Priority.Critical));
 }
예제 #2
0
 public bool SendInitializationPhaseRsp(bool initializationPhase)
 {
     self_close = true;
     ConnectionHeader header = new ConnectionHeader(ConnectionHeader.INITIALIZATION_PHASE_RSP);
     header.InitializationPhase = initializationPhase;
     Message closeMsg = new Message(peer_addr, null, new byte[0]);
     closeMsg.putHeader("ConnectionHeader", header);
     if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending silent close request");
     try
     {
         lock (initializationPhase_mutex)
         {
             byte[] binaryMsg = Util.Util.serializeMessage(closeMsg);
             SendInternal(binaryMsg);
             Monitor.Wait(initializationPhase_mutex);
             return inInitializationPhase;
         }
     }
     catch (Exception e)
     {
         NCacheLog.Error("Connection.SendSilentCloseNotification",   e.ToString());
     }
     return false;
 }
예제 #3
0
        internal virtual void sendJoinMessage(Address coord, Address mbr, string subGroup_name, bool isStartedAsMirror)
        {
            
            Message msg;
            GMS.HDR hdr;

            msg = new Message(coord, null, null);
            hdr = new GMS.HDR(GMS.HDR.JOIN_REQ, mbr, subGroup_name, isStartedAsMirror);
            hdr.GMSId = gms.unique_id;
            msg.putHeader(HeaderType.GMS, hdr);
            gms.passDown(new Event(Event.MSG_URGENT, msg, Priority.Critical));
        }
예제 #4
0
        public override void handleNodeRejoining(Address node)
        {
            if (node != null)
            {
                if (gms.Stack.NCacheLog.IsInfoEnabled) gms.Stack.NCacheLog.Info("ParticipantGmsImpl.handleNodeRejoining", "I should inform coordinator about node rejoining with " + node);

                if (gms.members.contains(node))
                {
                    //inform coordinator about the node rejoining in the cluster.
                    GMS.HDR header = new GMS.HDR(GMS.HDR.INFORM_NODE_REJOINING, node);
                    Message rejoiningMsg = new Message(gms.determineCoordinator(), null, new byte[0]);
                    rejoiningMsg.putHeader(HeaderType.GMS, header);
                    gms.passDown(new Event(Event.MSG, rejoiningMsg, Priority.Critical));
                }
            }
        }
예제 #5
0
        public override void handleConnectedNodesRequest(Address src,int reqId)
        {
            if (gms.determineCoordinator().Equals(src))
            {
                ArrayList mbrs = gms.members.Members;
                ArrayList suspected = suspected_mbrs.Clone() as ArrayList;

                foreach (Address suspect in suspected_mbrs)
                {
                    mbrs.Remove(suspect);
                }

                if (gms.Stack.NCacheLog.IsInfoEnabled) gms.Stack.NCacheLog.Info("ParticipantGmsImp.handleConnectedNodesRequest    " + gms.local_addr + " --> " + Global.ArrayListToString(mbrs));

                Message rspMsg = new Message(src,null,new byte[0]);
                GMS.HDR hdr = new GMS.HDR(GMS.HDR.CONNECTED_NODES_RESPONSE,(Object)reqId);
                hdr.nodeList = mbrs;
                rspMsg.putHeader(HeaderType.GMS,hdr);
                gms.passDown(new Event(Event.MSG,rspMsg,Priority.Critical));
            }
        }
예제 #6
0
        public virtual Message makeReply( )
        {
            Message m =  new Message(src_addr, null, null);
			m.IsUserMsg = IsUserMsg;
            m.dest_addr = src_addr;
            m.profileid = profileid;
            m.isProfilable = isProfilable;
            if(IsProfilable)  m.TraceMsg = traceMsg + "-->complete";
            return m;
        }
예제 #7
0
		/// <summary> Create a copy of the message. If offset and length are used (to refer to another buffer), the copy will
		/// contain only the subset offset and length point to, copying the subset into the new copy.
		/// </summary>
		/// <param name="">copy_buffer
		/// </param>
		/// <returns>
		/// </returns>
		public virtual Message copy(bool copy_buffer,MemoryManager memManaager)
		{
            Message retval = null;
            if (memManaager != null)
            {
                ObjectProvider provider = memManaager.GetProvider(typeof(Message));
                if(provider != null)
                    retval = (Message)provider.RentAnObject();
            }
            else
                retval = new Message();

			retval.dest_addr = dest_addr;
			retval.dest_addrs = dest_addrs;
			retval.src_addr = src_addr;
			retval.prio = prio;
			retval.isUserMsg = isUserMsg;
            retval.isProfilable = IsProfilable;
            retval.ProfileId = profileid;
            retval.psTime = psTime;
            retval.tnspTime = tnspTime;
            retval.traceMsg = traceMsg;
            retval.RequestId = reqId;
            retval.handledAsynchronously = handledAsynchronously;
            retval.responseExpected = responseExpected;

			if (copy_buffer && buf != null)
			{
				retval.setBuffer(buf, offset, length);
			}
            
            if (headers != null)
            {
                retval.headers = (Hashtable)headers.Clone();
                
            }
            retval.Payload = this.Payload;
			return retval;
		}
예제 #8
0
        /// <summary>
        /// Send a broadcast no reply message to a specific node
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="msg"></param>
        /// <param name="part"></param>
        protected internal void SendNoReplyMessage(Address dest, Object msg, Priority priority, bool isSeqRequired)
        {
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.SendNoRepMsg", "dest_addr :" + dest);

            byte[] serializedMsg = SerializeMessage(msg);
            Message m = new Message(dest, null, serializedMsg);
            m.IsSeqRequired = isSeqRequired;
            m.Priority = priority;
            _channel.send(m);
        }
예제 #9
0
 /// <summary>
 /// Send a multicast no reply message 
 /// </summary>
 /// <param name="dest"></param>
 /// <param name="msg"></param>
 /// <param name="part"></param>
 protected internal void SendNoReplyMulticastMessage(ArrayList dest, Object msg, Priority priority, bool isSeqRequired)
 {
     byte[] serializedMsg = SerializeMessage(msg);
     Message m = new Message(null, null, serializedMsg);
     m.IsSeqRequired = isSeqRequired;
     m.Priority = priority;
     m.Dests = dest;
     _channel.send(m);
 }
예제 #10
0
		public override void  down(Event evt)
		{
			Message msg;
			long time_to_wait, start_time;
			
			switch (evt.Type)
			{
				
				
				case Event.FIND_INITIAL_MBRS:  // sent by GMS layer, pass up a GET_MBRS_OK event

                    //We pass this event down to tcp so that it can take some measures.
                    passDown(evt);

                    initial_members.Clear();
					msg = new Message(null, null, null);

					msg.putHeader(HeaderType.TCPPING, new PingHeader(PingHeader.GET_MBRS_REQ, (System.Object)local_addr,group_addr));

					// if intitial nodes have been specified and static is true, then only those
					// members will form the cluster, otherwise, nodes having the same IP Multicast and port
					// will form the cluster dyanamically.

                    mbrDiscoveryInProcess = true;
					lock (members.SyncRoot)
					{
						if( initial_hosts != null)
						{
							for (System.Collections.IEnumerator it = initial_hosts.GetEnumerator(); it.MoveNext(); )
							{
								Address addr = (Address) it.Current;
                                msg.Dest = addr;
								if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("[FIND_INITIAL_MBRS] sending PING request to " + msg.Dest);
                                passDown(new Event(Event.MSG_URGENT, msg.copy(), Priority.Critical));
							}
						}
										
					}

					// 2. Wait 'timeout' ms or until 'num_initial_members' have been retrieved

					if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()",  "[FIND_INITIAL_MBRS] waiting for results...............");
					lock (initial_members.SyncRoot)
					{
						start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
						time_to_wait = timeout;
						
						while (initial_members.Count < num_initial_members && time_to_wait > 0)
						{
							try
							{
                                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "initial_members Count: " + initial_members.Count + "initialHosts Count: " + num_initial_members);
                                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()", "Time to wait for next response: " + time_to_wait);
                                ///Big_clusterd: initial members will be pulsed in case connection is not available.
                                ///so here we dont have to wait till each member is timed out.
                                ///this significantly improves time for initial member discovery. 
                                bool timeExpire = System.Threading.Monitor.Wait(initial_members.SyncRoot, TimeSpan.FromMilliseconds(time_to_wait));

							}
							catch (System.Exception e)
							{
								Stack.NCacheLog.Error("TCPPing.down(FIND_INITIAL_MBRS)",  e.ToString());
							}
							time_to_wait = timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
						}
                        mbrDiscoveryInProcess = false;

					}
					if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()",  "[FIND_INITIAL_MBRS] initial members are " + Global.CollectionToString(initial_members));
					if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()",  "[FIND_INITIAL_MBRS] initial members count " + initial_members.Count);

                    //remove those which are not functional due to twoPhaseConnect
                    for (int i = initial_members.Count - 1; i >= 0; i--)
                    {
                        PingRsp rsp = initial_members[i] as PingRsp;
                        if (!rsp.IsStarted) initial_members.RemoveAt(i);
                    }

					// 3. Send response
					passUp(new Event(Event.FIND_INITIAL_MBRS_OK, initial_members));
					break;
				
				
				case Event.TMP_VIEW: 
				case Event.VIEW_CHANGE: 
					System.Collections.ArrayList tmp;
					if ((tmp = ((View) evt.Arg).Members) != null)
					{
						lock (members.SyncRoot)
						{
							members.Clear();
							members.AddRange(tmp);
						}
					}
					passDown(evt);
					break;
                /****************************After removal of NackAck *********************************/
                 //TCPPING emulates a GET_DIGEST call, which is required by GMS. This is needed
                 //since we have now removed NAKACK from the stack!
                case Event.GET_DIGEST:
                    pbcast.Digest digest = new pbcast.Digest(members.Count);
                    for (int i = 0; i < members.Count; i++)
                    {
                        Address sender = (Address)members[i];
                        digest.add(sender, 0, 0);
                    }
                    passUp(new Event(Event.GET_DIGEST_OK, digest));
                    return;

                case Event.SET_DIGEST:
                    // Not needed! Just here to let you know that it is needed by GMS!
                    return;
                /********************************************************************************/

				case Event.BECOME_SERVER:  // called after client has joined and is fully working group member
					if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.down()",  "received BECOME_SERVER event");
					passDown(evt);
					is_server = true;
					break;
				
				
				case Event.CONNECT: 
					object[] addrs = ((object[])evt.Arg);
					group_addr = (string)addrs[0];
					subGroup_addr = (string)addrs[1];
					
                    twoPhaseConnect = (bool)addrs[3];
                    if (twoPhaseConnect) timeout = 1000;
					passDown(evt);
					break;
				
				
				case Event.DISCONNECT: 
					passDown(evt);
					break;

                case Event.HAS_STARTED:
                    hasStarted = true;
                    passDown(evt);
                    break;

				default: 
					passDown(evt); // Pass on to the layer below us
					break;
				
			}
		}
예제 #11
0
		public override void  up(Event evt)
		{
			Message msg, rsp_msg;
			System.Object obj;
			PingHeader hdr, rsp_hdr;
			PingRsp rsp;
			Address coord;
			
			
			switch (evt.Type)
			{
				 
				case Event.MSG: 
					msg = (Message) evt.Arg;
                   
                    obj = msg.getHeader(HeaderType.TCPPING);
					if (obj == null || !(obj is PingHeader))
					{
						passUp(evt);
						return ;
					}
                    
                    hdr = (PingHeader)msg.removeHeader(HeaderType.TCPPING);
					
				switch (hdr.type)
				{
											
					case PingHeader.GET_MBRS_REQ:  

                       
						if( !hdr.group_addr.Equals(group_addr))
						{
                            if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.up()",   "GET_MBRS_REQ from different group , so discarded");
							return;
						}
						Address src = (Address) hdr.arg;
						msg.Src = src;

						if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()",  "GET_MBRS_REQ from " + msg.Src.ToString());

						
						lock (members.SyncRoot)
						{
							coord = members.Count > 0 ? (Address)members[0] : local_addr;
						}
						if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()",   "my coordinator is " + coord.ToString());

						rsp_msg = new Message(msg.Src, null, null);
						rsp_hdr = new PingHeader(PingHeader.GET_MBRS_RSP, new PingRsp(local_addr, coord, Stack.IsOperational,Stack.IsOperational));
						rsp_msg.putHeader(HeaderType.TCPPING, rsp_hdr);
						if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()",   "responding to GET_MBRS_REQ back to " + msg.Src.ToString());

                       if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info(local_addr + " - [FIND_INITIAL_MBRS] replying PING request to " + rsp_msg.Dest);

                        
						passDown(new Event(Event.MSG, rsp_msg, Priority.Critical));

return ;
						
						
					case PingHeader.GET_MBRS_RSP:  // add response to vector and notify waiting thread
                       

						if(Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()",  "GET_MBRS_RSP from " + msg.Src.ToString());
						rsp = (PingRsp) hdr.arg;


                        //muds:
                        //check if the received response is valid i.e. successful security authorization
                        //at other end.
                        if (rsp.OwnAddress == null && rsp.CoordAddress == null && rsp.HasJoined == false)
                        {
                            lock (initial_members.SyncRoot)
                            {
                                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "I am not authorized to join to " + msg.Src.ToString());
                                System.Threading.Monitor.PulseAll(initial_members.SyncRoot);
                            }
                        }
                        else
                        {
                            if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Before Adding initial members response");
                            lock (initial_members.SyncRoot)
                            {
                                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Adding initial members response");
                                if (!initial_members.Contains(rsp))
                                {
                                    initial_members.Add(rsp);
                                    if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TCPPING.up()", "Adding initial members response for " + rsp.OwnAddress);
                                }
                                else
                                    if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TcpPing.up()", "response already received");

                                System.Threading.Monitor.PulseAll(initial_members.SyncRoot);
                            }
                        }

                       
						return ;
						
						
					default:
                        Stack.NCacheLog.Warn("got TCPPING header with unknown type (" + hdr.type + ')');
						return ;
						
				}
					//goto case Event.SET_LOCAL_ADDRESS;
				
				
				
				case Event.SET_LOCAL_ADDRESS: 
					passUp(evt);
					local_addr = (Address) evt.Arg;
					// Add own address to initial_hosts if not present: we must always be able to ping ourself !
					if (initial_hosts != null && local_addr != null)
					{
						if (!initial_hosts.Contains(local_addr))
						{
                            Stack.NCacheLog.Debug("[SET_LOCAL_ADDRESS]: adding my own address (" + local_addr + ") to initial_hosts; initial_hosts=" + Global.CollectionToString(initial_hosts));
							initial_hosts.Add(local_addr);
						}
					}
					break;
				case Event.CONNECT_OK: 
					obj = evt.Arg;

					if(obj != null && obj is Address)
					{
						tcpServerPort = ((Address)obj).Port;
					}
					passUp(evt);
					break;
                case Event.CONNECTION_NOT_OPENED:
                    if (mbrDiscoveryInProcess)
                    {
                        Address node = evt.Arg as Address;
                        PingRsp response = new PingRsp(node, node, true, false);
                        lock (initial_members.SyncRoot)
                        {
                            initial_members.Add(response);
                            System.Threading.Monitor.PulseAll(initial_members.SyncRoot);
                        }
                        Stack.NCacheLog.CriticalInfo(Name + ".up", "connection failure with " + node);
                    }

                    break;
				// end services
				default: 
					passUp(evt); // Pass up to the layer above us
					break;
				
			}
		}
예제 #12
0
            public void SendSecondaryAddressofPeer()
            {
                Address secondaryAddress = null;
                Connection.ConnectionHeader header = new ConnectionHeader(ConnectionHeader.GET_SECOND_ADDRESS_RSP);
                header.MySecondaryAddress = enclosingInstance.local_addr_s;

                Message msg = new Message(peer_addr, null, new byte[0]);
                msg.putHeader("ConnectionHeader", header);
                NCacheLog.Error("Connection.SendSecondaryAddress",   "secondaryAddr: " + header.MySecondaryAddress);
                SendInternal(Util.Util.serializeMessage(msg));

            }
예제 #13
0
 public Address GetSecondaryAddressofPeer()
 {
     Connection.ConnectionHeader header = new ConnectionHeader(ConnectionHeader.GET_SECOND_ADDRESS_REQ);
     Message msg = new Message(peer_addr, null, new byte[0]);
     msg.putHeader("ConnectionHeader", header);
     lock (get_addr_sync)
     {
         SendInternal(Util.Util.serializeMessage(msg));
         Monitor.Wait(get_addr_sync);
     }
     return secondaryAddress;
 }
예제 #14
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);

                }
            }
예제 #15
0
 /// <summary>
 /// Sends notification to other node about leaving.
 /// </summary>
 public void SendLeaveNotification()
 {
     leavingGracefully = true;
     ConnectionHeader header = new ConnectionHeader(ConnectionHeader.LEAVE);
     Message leaveMsg = new Message(peer_addr, null, new byte[0]);
     leaveMsg.putHeader("ConnectionHeader", header);
     if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending leave request");
     try
     {
         byte[] binaryMsg = Util.Util.serializeMessage(leaveMsg);
         SendInternal(binaryMsg);
     }
     catch (Exception e)
     {
         NCacheLog.Error("Connection.SendLeaveNotification",   e.ToString());
     }
 }
예제 #16
0
        protected internal object SendMessage(Address dest, object msg, byte mode, bool isSeqRequired, long timeout) 
        {
            try
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.SendMsg", "dest_addr :" + dest);

               
                byte[] serializedMsg = SerializeMessage(msg);
                Message m = new Message(dest, null, serializedMsg);
                if (msg is Function)
                    m.Payload = ((Function)msg).UserPayload;
                m.IsSeqRequired = isSeqRequired;

                object result = _msgDisp.sendMessage(m, mode, timeout);
                if (result is OperationResponse)
                {
                    ((OperationResponse)result).SerializablePayload = CompactBinaryFormatter.FromByteBuffer((byte[])((OperationResponse)result).SerializablePayload, _context.SerializationContext);
                }
                else if (result is byte[])
                {
                    result = CompactBinaryFormatter.FromByteBuffer((byte[])result, _context.SerializationContext);
                }

                if (result != null && result is Exception) throw (Exception)result;
                return result;
            }
            catch (Alachisoft.NGroups.SuspectedException e)
            {
                throw new Runtime.Exceptions.SuspectedException("operation failed because the group member was suspected " + e.suspect);
            }
            catch (Runtime.Exceptions.TimeoutException e)
            {
                throw;
            }
            finally
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.SendMsg", "completed");
            }
        }
예제 #17
0
        protected internal object SendMessage(Address dest, object msg, byte mode, long timeout, bool handleAsync)
        {
            try
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.SendMsg", "dest_addr :" + dest);

                byte[] serializedMsg = SerializeMessage(msg);
                Message m = new Message(dest, null, serializedMsg);
                m.HandledAysnc = handleAsync;
                m.IsUserMsg = true;
                object result = _msgDisp.sendMessage(m, mode, timeout);
                if (result is byte[])
                    result = CompactBinaryFormatter.FromByteBuffer((byte[])result, _context.SerializationContext);
                return result;
            }
            catch (Alachisoft.NGroups.SuspectedException e)
            {
                throw new Runtime.Exceptions.SuspectedException("operation failed because the group member was suspected " + e.suspect);
            }
            catch (Runtime.Exceptions.TimeoutException e)
            {
                throw;
            }
            finally
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.SendMsg", "completed");
            }
        }
예제 #18
0
 /// <summary>
 /// Notify the target object of a received Message.
 /// </summary>
 /// <param name="msg">Received Message</param>
 void MessageListener.receive(Message msg)
 {
     ((RequestHandler)this).handle(msg);
 }
예제 #19
0
        public virtual object HandleClusterMessage(Address src, Function func, out Address destination, out Message replicationMsg)
        {
            destination = null;
            replicationMsg = null;

            return null;
        }
예제 #20
0
 public object handleFunction(Address src, Function func, out Address destination, out Message replicationMsg)
 {
     return _participant.HandleClusterMessage(src, func, out destination, out replicationMsg);
 }
예제 #21
0
		public virtual Message makeReply(ObjectProvider MsgProvider)
		{
            Message m = null;
            if (MsgProvider != null)
            {
                m = (Message) MsgProvider.RentAnObject();
            }
            else
                m = new Message(src_addr, null, null);

            m.dest_addr = src_addr;
            m.profileid = profileid;
            m.isProfilable = isProfilable;
            return m;
		}
예제 #22
0
        object RequestHandler.handleNHopRequest(Message req, out Address destination, out Message replicationMsg)
        {
            destination = null;
            replicationMsg = null;

            if (req == null || req.Length == 0)
                return null;

            try
            {
                bool isLocalReq = LocalAddress.CompareTo(req.Src) == 0;
                object body = req.getFlatObject();
                try
                {
                    if (body is Byte[])
                        body = CompactBinaryFormatter.FromByteBuffer((byte[])body, _context.SerializationContext);
                }
                catch (Exception e)
                {
                    return e;
                }

                object result = null;
                if (body is Function)
                {
                    Function func = (Function)body;
                    func.UserPayload = req.Payload;
                    if (isLocalReq && func.ExcludeSelf)
                    {
                        if (req.HandledAysnc && req.RequestId > 0)
                            SendResponse(req.Src, null, req.RequestId);
                        return null;
                    }
                    if (req.HandledAysnc)
                    {
                        AsyncRequst asyncReq = new AsyncRequst(func, func.SyncKey);
                        asyncReq.Src = req.Src;
                        asyncReq.RequsetId = req.RequestId;
                        _asynHandler.HandleRequest(asyncReq);
                        return null;
                    }
                    else
                    {
                        result = handleFunction(req.Src, func, out destination, out replicationMsg);
                    }
                }
                else if (body is AggregateFunction)
                {
                    AggregateFunction funcs = (AggregateFunction)body;
                    object[] results = new object[funcs.Functions.Length];
                    for (int i = 0; i < results.Length; i++)
                    {
                        Function func = (Function)funcs.Functions.GetValue(i);
                        if (isLocalReq && func.ExcludeSelf)
                        {
                            if (req.HandledAysnc && req.RequestId > 0)
                            {
                                SendResponse(req.Src, null, req.RequestId);
                                continue;
                            }
                            results[i] = null;
                        }
                        else
                        {
                            if (req.HandledAysnc)
                            {
                                AsyncRequst asyncReq = new AsyncRequst(func, func.SyncKey);
                                asyncReq.Src = req.Src;
                                asyncReq.RequsetId = req.RequestId;
                                _asynHandler.HandleRequest(asyncReq);
                                continue;
                            }
                            results[i] = handleFunction(req.Src, func);
                        }
                    }
                    result = results;
                }

                if (result is OperationResponse)
                {
                    ((OperationResponse)result).SerializablePayload = CompactBinaryFormatter.ToByteBuffer(((OperationResponse)result).SerializablePayload, _context.SerializationContext);
                }
                else
                {
                    result = CompactBinaryFormatter.ToByteBuffer(result, _context.SerializationContext);
                }

                return result;
            }
            catch (Exception e)
            {
                return e;
            }

            return null;
        }
예제 #23
0
        private void sendMemberLeftNotificationToCoordinator(Address suspected,Address coordinator)
        {
            if (gms.Stack.NCacheLog.IsInfoEnabled) gms.Stack.NCacheLog.Info("ParticipantGmsImp.sendMemberLeftNotification", "informing coordinator about abnormal connection breakage with " + suspected);

            GMS.HDR hdr = new GMS.HDR(GMS.HDR.CONNECTION_BROKEN, suspected);
            Message nodeLeftMsg = new Message(coordinator, null, new byte[0]);
            nodeLeftMsg.putHeader(HeaderType.GMS, hdr);
            gms.passDown(new Event(Event.MSG, nodeLeftMsg, Priority.Critical));
        }
예제 #24
0
        private RspList BroadcastToMultiple(ArrayList dests, object msg, byte mode, long timeout, bool isSeqRequired, string traceMsg,Priority priority)
        {
            ///TODO: remove this conditional compilation

            byte[] serializedMsg = SerializeMessage(msg);
            Message m = new Message(null, null, serializedMsg);
            if (msg is Function)
            {
                m.Payload = ((Function)msg).UserPayload;
                m.responseExpected = ((Function)msg).ResponseExpected;
            }

            m.setBuffer(serializedMsg);
            m.IsSeqRequired = isSeqRequired;
            m.Priority = priority;
            RspList rspList = null;

            try
            {
                rspList = _msgDisp.castMessage(dests, m, mode, timeout);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.BcastToMultiple", "completed");

            }
            if (rspList.size() == 0)
            {
                return null;
            }
            Rsp rsp;
            for (int i = 0; i < rspList.size(); i++)
            {
                rsp = (Rsp)rspList.elementAt(i);
                rsp.Deflate(_context.SerializationContext);
            }
            return rspList;
        }
예제 #25
0
 /// <summary>
 /// Informs the coodinator about the nodes to which this node can not establish connection
 /// on receiving the first view.Only the node who has most recently joined the cluster
 /// should inform the coodinator other nodes will neglect this event.
 /// </summary>
 /// <param name="nodes"></param>
 public override void handleConnectionFailure(System.Collections.ArrayList nodes)
 {
     if (nodes != null && nodes.Count > 0)
     {
         if (gms.Stack.NCacheLog.IsInfoEnabled) gms.Stack.NCacheLog.Info("ParticipantGmsImp.handleConnectionFailure", "informing coordinator about connection failure with [" + Global.CollectionToString(nodes) + "]");
         GMS.HDR header = new GMS.HDR(GMS.HDR.CAN_NOT_CONNECT_TO);
         header.nodeList = nodes;
         Message msg = new Message(gms.determineCoordinator(),null,new byte[0]);
         msg.putHeader(HeaderType.GMS,header);
         gms.passDown(new Event(Event.MSG,msg,Priority.Critical));
     }
     
 }
예제 #26
0
        public RspList BroadcastToMultiple(ArrayList dests, object msg, byte mode, long timeout, string traceMsg, bool handleAsync)
        {

            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.BcastToMultiple", "");

            byte[] serializedMsg = SerializeMessage(msg);
            Message m = new Message(null, null, serializedMsg);
            m.HandledAysnc = handleAsync;
            m.setBuffer(serializedMsg);
            m.IsUserMsg = true;
            RspList rspList = null;

            try
            {
                rspList = _msgDisp.castMessage(dests, m, mode, timeout);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.BcastToMultiple", "completed");
            }
            if (rspList.size() == 0)
            {
                return null;
            }
            Rsp rsp;
            for (int i = 0; i < rspList.size(); i++)
            {
                rsp = (Rsp)rspList.elementAt(i);
                rsp.Deflate(_context.SerializationContext);
            }
            return rspList;
        }
예제 #27
0
		internal virtual void  sendLeaveMessage(Address coord, Address mbr)
		{
			Message msg = new Message(coord, null, null);
			GMS.HDR hdr = new GMS.HDR(GMS.HDR.LEAVE_REQ, mbr);

            msg.putHeader(HeaderType.GMS, hdr);
			gms.passDown(new Event(Event.MSG, msg));
        }
예제 #28
0
        public RspList Multicast(ArrayList dests, object msg, byte mode, bool isSeqRequired, long timeout)
        {
            if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.Mcast", "");

            byte[] serializedMsg = SerializeMessage(msg);
            Message m = new Message(null, null, serializedMsg);
            if (msg is Function)
                m.Payload = ((Function)msg).UserPayload;
            m.setBuffer(serializedMsg);
            m.Dests = dests;
            m.IsSeqRequired = isSeqRequired;

            RspList rspList = null;

            try
            {
                rspList = _msgDisp.castMessage(dests, m, mode, timeout);
            }
            finally
            {
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("ClustService.Mcast", "completed");

            }
            if (rspList.size() == 0)
            {
                return null;
            }
            Rsp rsp;
            for (int i = 0; i < rspList.size(); i++)
            {
                rsp = (Rsp)rspList.elementAt(i);
                rsp.Deflate(_context.SerializationContext);
            }

            return rspList;
        }
예제 #29
0
        public void SendResponse(Address dest, object result, long reqId)
        {
            byte[] serializedMsg = SerializeMessage(result);
            Message response = new Message(dest, null, serializedMsg);

            try
            {
                _msgDisp.SendResponse(reqId, response);
            }
            catch (Exception e)
            {
                //Trace.error("ClusterService", e.ToString());
                throw;
            }
            finally
            {

            }

        }
예제 #30
0
            /// <summary>
            /// Sends the notification to the peer that connection is being closed silently.
            /// </summary>
            private void SendSilentCloseNotification()
            {
                self_close = true;
                ConnectionHeader header = new ConnectionHeader(ConnectionHeader.CLOSE_SILENT);
                Message closeMsg = new Message(peer_addr, null, new byte[0]);
                closeMsg.putHeader("ConnectionHeader", header);
                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending silent close request");
                try
                {
                    byte[] binaryMsg = Util.Util.serializeMessage(closeMsg);

                    SendInternal(binaryMsg);
                }
                catch (Exception e)
                {
                    NCacheLog.Error("Connection.SendSilentCloseNotification",   e.ToString());
                }
                

            }