Esempio n. 1
0
        /// <summary>
        /// 将 Excel 2003 版本以下的 Execl 数据导入到 DataSet
        /// </summary>
        /// <param name="xlsPath">Excel 路径</param>
        /// <param name="sheetIndex">工作簿的索引</param>
        /// <param name="hdr">工作簿首行行为</param>
        /// <returns></returns>
        public static DataSet Excel120ToDataSet(string xlsPath, int sheetIndex = 1, HDR hdr = HDR.YES)
        {
            if (!File.Exists(xlsPath))
            {
                throw new FileNotFoundException("xlsPath");
            }
            if (sheetIndex < 0)
            {
                throw new ArgumentOutOfRangeException("sheetIndex", "参数 sheetIndex 必须大于等于 1");
            }
            var strConn =
                string.Format(
                    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0};Extended Properties='Excel 12.0 Xml;HDR={1};IMEX=1';", xlsPath, hdr.ToString());

            using (var conn = new OleDbConnection(strConn))
            {
                conn.Open();
                var cmd = new OleDbCommand(string.Format("SELECT * From [sheet{0}$]", sheetIndex), conn);
                var da  = new OleDbDataAdapter(cmd);
                var ds  = new DataSet();
                da.Fill(ds);
                conn.Close();
                return(ds);
            }
        }
Esempio n. 2
0
 /// <summary>
 /// 将 Excel 2003 版本以下的 Execl 数据导入到 DataSet
 /// </summary>
 /// <param name="xlsPath">Excel 路径</param>
 /// <param name="sheetIndex">工作簿的索引</param>
 /// <param name="hdr">工作簿首行行为</param>
 /// <returns></returns>
 public static DataSet Excel120ToDataSet(string xlsPath, int sheetIndex = 1, HDR hdr = HDR.YES)
 {
     if (!File.Exists(xlsPath))
     {
         throw new FileNotFoundException("xlsPath");
     }
     if (sheetIndex < 0)
     {
         throw new ArgumentOutOfRangeException("sheetIndex", "参数 sheetIndex 必须大于等于 1");
     }
     var strConn =
         string.Format(
             "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0};Extended Properties='Excel 12.0 Xml;HDR={1};IMEX=1';", xlsPath, hdr.ToString());
     using (var conn = new OleDbConnection(strConn))
     {
         conn.Open();
         var cmd = new OleDbCommand(string.Format("SELECT * From [sheet{0}$]", sheetIndex),conn);
         var da = new OleDbDataAdapter(cmd);
         var ds = new DataSet();
         da.Fill(ds);
         conn.Close();
         return ds;
     }
 }
Esempio n. 3
0
        /// <summary> Received an mcast request - Ignore if not the sequencer, else send an
        /// mcast reply
        /// 
        /// </summary>
        /// <param name="msg">the multicast request message
        /// </param>
        private void _recvMcastRequest(Message msg)
        {
            HDR header;
            Message repMsg;

            // i. If blocked, discard the mcast request
            // ii. Assign a seqID to the message and send it back to the requestor

            if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TOTAL._recvMcastRequest()", "hdr = " + Global.CollectionToString(msg.Headers));

            if (!addr.Equals(_groupSequencerAddr))
            {
                Stack.NCacheLog.Error("Received mcast request from " + msg.Src.ToString() + " but not a group sequencer");
                return;
            }
            if (state == BLOCK)
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Blocked, discard mcast req");
                return;
            }

            header = (HDR)msg.getHeader(HeaderType.TOTAL);
            repMsg = new Message(msg.Src, addr, new byte[0]);
            repMsg.Priority = msg.Priority;
            int viewId = -1;
            try
            {
                stateLock.AcquireReaderLock(Timeout.Infinite);
                viewId = (int)(currentViewId != null ? currentViewId.Id : -1);
            }
            finally
            {
                stateLock.ReleaseReaderLock();
            }

            HDR reqHdr = new HDR(HDR.REPMCAST, header.localSeqID, NextMCastSeqID, viewId);
            repMsg.putHeader(HeaderType.TOTAL, reqHdr);
            repMsg.IsUserMsg = true;
            repMsg.Type = MsgType.TOKEN_SEEKING;

            passDown(new Event(Event.MSG, repMsg));
        }
Esempio n. 4
0
        /// <summary>
        /// Fetches the request status from the nodes.
        /// </summary>
        /// <param name="nodes"></param>
        /// <returns></returns>
        public Hashtable FetchRequestStatus(ArrayList nodes, ArrayList clusterMembership, long reqId)
        {
            Hashtable result = new Hashtable();
            if (nodes != null && nodes.Count > 0)
            {
                HDR hdr = new HDR(HDR.GET_REQ_STATUS, NextRequestId,true, null);
                hdr.status_reqId = reqId;
                Message msg = new Message();
                msg.putHeader(HeaderType.REQUEST_COORELATOR, hdr);
                msg.Dests = nodes;
                msg.IsSeqRequired = false;
                msg.IsUserMsg = true;
                msg.RequestId = reqId;
                msg.setBuffer(new byte[0]);

                GroupRequest req = new GroupRequest(msg, this, nodes, clusterMembership, GroupRequest.GET_ALL, 2000, 0, this._ncacheLog);
                req.execute();

                RspList rspList = req.Results;
                RequestStatus reqStatus = null;
                if (rspList != null)
                {
                    for (int i = 0; i < rspList.size(); i++)
                    {
                        Rsp rsp = rspList.elementAt(i) as Rsp;
                        if (rsp != null)
                        {
                            if (rsp.received)
                            {
                                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ReqCorrelator.FetchReqStatus", reqId + " status response received from " + rsp.sender);
                                object rspValue = rsp.Value;
                                if (rspValue is byte[])
                                    reqStatus = CompactBinaryFormatter.Deserialize(new MemoryStream((byte[])rspValue), null) as RequestStatus;
                                else
                                    reqStatus = rsp.Value as RequestStatus;

                                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ReqCorrelator.FetchReqStatus", reqId + " status response: " + reqStatus);

                                result[rsp.Sender] = reqStatus;
                            }
                            else
                            {
                                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ReqCorrelator.FetchReqStatus", reqId + " status response NOT received from " + rsp.sender);
                                result[rsp.Sender] = new RequestStatus(reqId,RequestStatus.NONE);
                            }
                        }
                    }
                }

            }
            return result;
        }
Esempio n. 5
0
        /// <summary>
        /// Checks if state transfer is in progress any where in the cluster. First status is checked
        /// on local node. If current node is not in state transfer then it is verified from other nodes
        /// in the cluster.
        /// </summary>
        /// <returns></returns>
        public bool IsClusterInStateTransfer()
        {
            
            if(GetStateTransferStatus()) return true;
            //check with other members
            
            if (this.members != null)
            {
                ArrayList allmembers = this.members.Members;
                if (allmembers != null && allmembers.Count > 0)
                {
                    _stateTransferPromise = new SateTransferPromise(allmembers.Count);
                    Message msg = new Message(null, null, new byte[0]);
                    msg.Dests = allmembers;
                    GMS.HDR hdr = new HDR(GMS.HDR.IS_NODE_IN_STATE_TRANSFER);
                    msg.putHeader(HeaderType.GMS, hdr);
                    down(new Event(Event.MSG, msg, Priority.Critical));

                    
                    Object objectState = _stateTransferPromise.WaitResult(_stateTransferQueryTimesout);
                    // Service crash fix.
                    bool isInstateTransfer = objectState != null ? (bool)objectState : false;
                    if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("gms.IsClusterInStateTransfer", "result : " + (isInstateTransfer));
                    return isInstateTransfer;

                }
            }

            return false;
        }
Esempio n. 6
0
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                this.Enabled       = false;
                this.UseWaitCursor = true;
                Cursor.Current     = Cursors.WaitCursor;

                if (string.IsNullOrWhiteSpace(txtAccountNumber.Text) ||
                    string.IsNullOrWhiteSpace(txtAWBNumber.Text))
                {
                    MessageBox.Show("Missing data.");
                    return;
                }
                if ((string)cmbPODType.SelectedItem == "")
                {
                    cmbPODType.SelectedIndex = 1;
                }

                txtAccountNumber.Text = txtAccountNumber.Text.Trim();
                txtAWBNumber.Text     = txtAWBNumber.Text.Trim();

                shipmentDocumentRetrieveReqMSG req = new shipmentDocumentRetrieveReqMSG();
                HDR hdr = new HDR
                {
                    Dtm  = DateTime.Now,
                    Id   = "TareTesting", // Guid.NewGuid().ToString("N"),
                    Sndr = new PartIdentification()
                    {
                        AppCd    = "DCG"
                        , AppNm  = "DCG"
                        , CmptNm = "HP"
                    },
                    Ver = "1.038"
                };

                req.Hdr = hdr;

                shipmentDocumentRetrieveReqMSGBD bd = new shipmentDocumentRetrieveReqMSGBD();
                List <CdmGenericRequest_GenericRequestCriteria> genrc_rq = new List <CdmGenericRequest_GenericRequestCriteria>();

                switch ((string)cmbPODType.SelectedItem)
                {
                case "Detailed":
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "IMG_CONTENT", Val = "epod-detail-esig"
                    });
                    break;

                case "Table Summary":
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "IMG_CONTENT", Val = "epod-table-detail"
                    });
                    break;

                case "Table Detailed":
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "IMG_CONTENT", Val = "epod-table-summary"
                    });
                    break;

                case "Summary":
                default:
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "IMG_CONTENT", Val = "epod-summary-esig"
                    });
                    break;
                }

                genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                {
                    TyCd = "IMG_FORMAT", Val = "PDF"
                });
                genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                {
                    TyCd = "DOC_RND_REQ", Val = "true"
                });
                if (cbxInternalFlag.Checked)
                {
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "EXT_REQ", Val = "false"
                    });
                }
                else
                {
                    genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                    {
                        TyCd = "EXT_REQ", Val = "true"
                    });
                }
                genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                {
                    TyCd = "DUPL_HANDL", Val = "CORE_WB_NO"
                });
                genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                {
                    TyCd = "SORT_BY", Val = "$INGEST_DATE,D"
                });
                genrc_rq.Add(new CdmGenericRequest_GenericRequestCriteria()
                {
                    TyCd = "LANGUAGE", Val = "en"
                });

                bd.GenrcRq = genrc_rq.ToArray();

                List <CdmShipment_Shipment> shps = new List <CdmShipment_Shipment>();
                CdmShipment_Shipment        shp  = new CdmShipment_Shipment();
                shp.Id = txtAWBNumber.Text;
                List <CdmShipment_ShipmentTransaction>    shp_trs = new List <CdmShipment_ShipmentTransaction>();
                CdmShipment_ShipmentTransaction           shp_tr  = new CdmShipment_ShipmentTransaction();
                List <CdmShipment_ShipmentCustomerDetail> scdtls  = new List <CdmShipment_ShipmentCustomerDetail>();
                scdtls.Add(new CdmShipment_ShipmentCustomerDetail()
                {
                    AccNo = txtAccountNumber.Text, CRlTyCd = "SP"
                });
                shp_tr.SCDtl = scdtls.ToArray();
                shp_trs.Add(shp_tr);
                shp.ShpTr = shp_trs.ToArray();
                List <CdmShipment_CustomsDocuments_ShipmentDocumentation> shpindocs = new List <CdmShipment_CustomsDocuments_ShipmentDocumentation>();
                CdmShipment_CustomsDocuments_ShipmentDocumentation        shpindoc  = new CdmShipment_CustomsDocuments_ShipmentDocumentation();
                shpindoc.DocTyCd = "POD";
                shpindocs.Add(shpindoc);
                shp.ShpInDoc = shpindocs.ToArray();
                shps.Add(shp);
                bd.Shp = shps.ToArray();
                req.Bd = bd;

                GloWS_Request = Common.XMLToString(req.GetType(), req);

                var glowsAuthData = Common.PrepareGlowsAuth("getePOD");

                gblDHLExpressePODClient client = new gblDHLExpressePODClient(new CustomBinding(glowsAuthData.Item2), glowsAuthData.Item1);
                client.ClientCredentials.UserName.UserName = glowsAuthData.Item3;
                client.ClientCredentials.UserName.Password = glowsAuthData.Item4;

                shipmentDocumentRetrieveRespMSG resp;

                try
                {
                    resp = client.ShipmentDocumentRetrieve(req);
                }
                catch (Exception ex)
                {
                    var text = ex.Message;
                    label1.Text = label1.Text + ".";
                    return;
                }

                XDocument       xd   = XDocument.Parse(client.RawResponse);
                List <XElement> pods = xd.Descendants(XName.Get("SDoc")).ToList();

                foreach (XElement pod in pods)
                {
                    XElement img       = pod.Descendants(XName.Get("Img")).First();
                    string   base64pod = img.Attribute(XName.Get("Img")).Value;
                    byte[]   binpod    = System.Convert.FromBase64String(base64pod);
                    if (null != (string)img.Attribute(XName.Get("ImgMineTy")))
                    {
                        string mimeType = img.Attribute(XName.Get("ImgMimeTy")).Value;
                    }
                    string tempFilename = System.IO.Path.GetTempFileName();
                    System.IO.File.WriteAllBytes(tempFilename, binpod);

                    System.Diagnostics.Process.Start(tempFilename);
                }

                //string jsonText = JsonConvert.SerializeXNode(xd);
                //dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);

                //dynamic msg = ((dynamic)((IDictionary<string, object>) dyn).First().Value).MSG;

                //var msg2 = msg.MSG;

                //if (resp.DatTrErr.Any())
                //{
                //    MessageBox.Show("There was an error in tracking.");
                //    return;
                //}

                GloWS_Response = Common.XMLToString(resp.GetType(), resp);

                //var blah = new com.dhl.wsbexpress.epod.gblDHLExpressePODClient();

                //blah.ShipmentDocumentRetrieve(new shipmentDocumentRetrieveReqMSG()
                //{
                //    Hdr = new com.dhl.wsbexpress.epod.HDR
                //});
            }
            catch (Exception ex)
            {
                var text = ex.Message;
                label1.Text = label1.Text + ".";
                return;
            }
            finally
            {
                this.Enabled       = true;
                this.UseWaitCursor = false;
                Cursor.Current     = Cursors.Default;
            }
        }
Esempio n. 7
0
        /// <summary> Replace the original message with a broadcast request sent to the
        /// sequencer. The original bcast message is stored locally until a reply
        /// to bcast is received from the sequencer
        /// 
        /// </summary>
        /// <param name="msg">the message to broadcast
        /// </param>
        /// <param name="id">the local sequence ID to use
        /// </param>
        private void _sendBcastRequest(Message msg, long id)
        {

            // i. Store away the message while waiting for the sequencer's reply
            // ii. Send a bcast request immediatelly and also schedule a
            // retransmission
            msg.Dest = null;  //Taimoor:FIX: To make sure that this message will be broadcasted.
            if (addr.CompareTo(this.sequencerAddr) == 0)
            {
                long seqid = NextSequenceID;
                int viewId = -1;
                try
                {
                    stateLock.AcquireReaderLock(Timeout.Infinite);
                    viewId = (int)(currentViewId != null ? currentViewId.Id : -1);
                }
                finally
                {
                    stateLock.ReleaseReaderLock();
                }
                //Rent the event
                Event evt = null;
               
                evt = new Event();
                evt.Type = Event.MSG;
                evt.Priority = msg.Priority;
                evt.Arg = msg;

                //Rent the header
              
                HDR hdr = new HDR();
                hdr.type = HDR.BCAST;
                hdr.localSeqID = id;
                hdr.seqID = seqid;
                hdr.viewId = viewId;
                msg.putHeader(HeaderType.TOTAL, hdr);

                msg.Dest = null;
                msg.Type = MsgType.SEQUENCED;
                passDown(evt);
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TOTAL._sendBcastRequest()", "shortcut bcast seq# " + seqid);
                return;
            }
            
            request_lock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                reqTbl[(long)id] = msg;
            }
            finally
            {
                request_lock.ReleaseWriterLock();
            }
            _transmitBcastRequest(id);
            retransmitter.add(id, msg);
        }
Esempio n. 8
0
 public static void WriteTotalHeader(CompactWriter writer, HDR hdr)
 {
     byte isNull = 1;
     if (hdr == null)
         writer.Write(isNull);
     else
     {
         isNull = 0;
         writer.Write(isNull);
         hdr.Serialize(writer);
     }
     return;
 }
Esempio n. 9
0
 public override object Clone(ObjectProvider provider)
 {
     HDR hdr = null;
     if (provider != null)
         hdr = (HDR)provider.RentAnObject();
     else
         hdr = new HDR();
     hdr.type = this.type;
     hdr.seqID = seqID;
     hdr.localSeqID = localSeqID;
     hdr.viewId = viewId;
     return hdr;
 }
Esempio n. 10
0
        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)
            {
                RequestCorrelatorHDR corHdr = (RequestCorrelatorHDR)tmpHdr;
                corHdr.SerializeLocal(writer);
                bFlags.SetOn(FlagsByte.Flag.COR);
            }

            tmpHdr = (Header)headers[(object)(HeaderType.TOTAL)];
            if (tmpHdr != null)
            {
                HDR totalHdr = (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(true);
                writer.Write(length);
                writer.Write(((MemoryStream)stream).GetBuffer(), 0, length);
            }
            else
            {
                writer.Write(buf != null);
                int length = buf != null ? buf.Length: 0;
                writer.Write(length);
                if (buf != null)
                {
                    writer.Write(buf);
                }
            }

            writer.Write(Buffers != null);
            int bufferCount = Buffers != null ? Buffers.Count : 0;

            writer.Write(bufferCount);

            if (Buffers != null)
            {
                foreach (byte[] buff in Buffers)
                {
                    writer.Write(buff.Length);
                    writer.Write(buff, 0, buff.Length);
                }
            }
            //bool st = _stackTrace != null;
            //writer.Write(st);
            //if(st)
            //    CompactBinaryFormatter.Serialize(writer.BaseStream, _stackTrace, null,false);
            //st = _stackTrace2 != null;
            //writer.Write(st);
            //if (st)
            //    CompactBinaryFormatter.Serialize(writer.BaseStream, _stackTrace2, null, false);

            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;
        }
Esempio n. 11
0
        public void DeserializeLocal(BinaryReader reader)
        {
            isUserMsg = true;
            reader.BaseStream.Position -= 1;
            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))
            {
                RequestCorrelatorHDR corHdr = new RequestCorrelatorHDR();
                corHdr.DeserializeLocal(reader);
                headers.Add(HeaderType.REQUEST_COORELATOR, corHdr);
            }

            if (bFlags.AnyOn(FlagsByte.Flag.TOTAL))
            {
                HDR totalHdr = new 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();
            //bool st = reader.ReadBoolean();
            //if(st)
            //    _stackTrace = CompactBinaryFormatter.Deserialize(reader.BaseStream,  null,false) as Hashtable;

            //st = reader.ReadBoolean();
            //if (st)
            //    _stackTrace2 = CompactBinaryFormatter.Deserialize(reader.BaseStream, null, false) as Hashtable;

            //Console.WriteLine("4:                                                   " + TimeStats.FormatNOW());

            bool bufferNotNull = reader.ReadBoolean();

            length = reader.ReadInt32();
            if (bufferNotNull)
            {
                buf = (byte[])reader.ReadBytes(length);
            }

            bool bufferListNotNull = reader.ReadBoolean();
            int  bufferCount       = reader.ReadInt32();

            if (bufferListNotNull)
            {
                buffers = new ClusteredArrayList(bufferCount);

                for (int i = 0; i < bufferCount; i++)
                {
                    buffers.Add(reader.ReadBytes(reader.ReadInt32()));
                }
            }


            //Console.WriteLine("5:                                                   " + TimeStats.FormatNOW());
            //length = (buf != null) ? buf.Length : 0;
        }
 /// <summary>
 /// 将Excel转化成表格
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="hdr"></param>
 /// <returns></returns>
 public System.Data.DataTable ExcelToDataTable(string fileName,HDR hdr)
 {
     System.Data.DataTable dt;
     string HeadFlag = hdr == 0 ? "NO" : "YES";
     string conStr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1};IMEX=1'", fileName, HeadFlag);
     OleDbConnection myConn = new OleDbConnection(conStr);
     string strCom = " SELECT * FROM [Sheet1$]";
     myConn.Open();
     OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
     dt = new System.Data.DataTable();
     myCommand.Fill(dt);
     myConn.Close();
     return dt;
 }
Esempio n. 13
0
 private void SendViewAcknowledgment(Address coordinator)
 {
     Message m = new Message(coordinator, null, null);
     HDR hdr = new HDR(HDR.VIEW_RESPONSE, true);
     m.putHeader(HeaderType.GMS, hdr);
     passDown(new Event(Event.MSG, m, Priority.Critical));
 }
Esempio n. 14
0
        public virtual void castViewChange(View new_view, Digest digest)
        {
            Message view_change_msg;
            HDR hdr;

            Stack.NCacheLog.Debug("pb.GMS.castViewChange()", "mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n");

            if (new_view != null)
                new_view.BridgeSourceCacheId = impl.UniqueId;

            view_change_msg = new Message(); // bcast to all members
           

            hdr = new HDR(HDR.VIEW, new_view);
            hdr.digest = digest;
            view_change_msg.putHeader(HeaderType.GMS, hdr);
            view_change_msg.Dests = new_view.Members.Clone() as ArrayList;

            if(stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("CastView.Watch", "Count of members: " + new_view.Members.Count.ToString());
            //TODO: we need to handle scenario when we dont recive castView change from a node
            _promise = new ViewPromise(new_view.Members.Count);

            bool waitForViewAcknowledgement = true ;
            if (!new_view.containsMember(local_addr)) //i am leaving
            {
                waitForViewAcknowledgement = false;
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("GMS.castViewChange()", "I am coordinator and i am leaving");
                passDown(new Event(Event.MSG, view_change_msg, Priority.Critical));
            }
            else
                passDown(new Event(Event.MSG, view_change_msg, Priority.Critical));

            if (waitForViewAcknowledgement)
            {
                _promise.WaitResult(_castViewChangeTimeOut);

                if (!_promise.AllResultsReceived()) //retry
                {
                    view_change_msg.Dests = new_view.Members.Clone() as ArrayList;
                    passDown(new Event(Event.MSG, view_change_msg, Priority.Critical));
                    _promise.WaitResult(_castViewChangeTimeOut);
                }

                if (_promise.AllResultsReceived())
                {
                    Stack.NCacheLog.CriticalInfo("GMS.castViewChange()", "View applied");
                }
            }
        }
Esempio n. 15
0
        internal virtual void handleJoinRequest(Address mbr, string subGroup_name, bool isStartedAsMirror, string gmsId)
        {
          
            JoinRsp join_rsp = null;
            Message m;
            HDR hdr;

            if (mbr == null)
            {
                Stack.NCacheLog.Error( "mbr is null");
                return;
            }

            Stack.NCacheLog.Debug("pbcast.GMS.handleJoinRequest()", "mbr=" + mbr);

            if (!isStartedAsMirror)
            {
                lock (join_mutex)
                {
                   
                    if (_nodeJoiningInProgress || _isLeavingInProgress || (_isStarting && !local_addr.IpAddress.Equals(mbr.IpAddress)))
                    {
                        Stack.NCacheLog.CriticalInfo("GMS.HandleJoinRequest()", "node join already in progess" + mbr);
                       
                        join_rsp = new JoinRsp(null, null);
                        join_rsp.JoinResult = JoinResult.MembershipChangeAlreadyInProgress;
                        
                        m = new Message(mbr, null, null);
                        hdr = new HDR(HDR.JOIN_RSP, join_rsp);
                        m.putHeader(HeaderType.GMS, hdr);
                        passDown(new Event(Event.MSG, m, Priority.Critical));
                        return;
                    }
                    else
                    {
                        _nodeJoiningInProgress = true;
                    }
                } 
            }

           
            // 1. Get the new view and digest
            if (members.contains(mbr))
            {

                string oldGmsId = GetGmsId(mbr);

                if (oldGmsId != null && oldGmsId != gmsId)
                {
                    Stack.NCacheLog.Error("pbcast.GMS.handleJoinRequest()", mbr + " has sent a joining request while it is already in member list and has wrong gmsID");
                    
                   
                    join_rsp = null;
                    m = new Message(mbr, null, null);
                    hdr = new HDR(HDR.JOIN_RSP, join_rsp);
                    m.putHeader(HeaderType.GMS, hdr);
                    passDown(new Event(Event.MSG, m, Priority.Critical));

                    
                    impl.handleSuspect(mbr);
                    
                    lock (join_mutex)
                    {
                        _nodeJoiningInProgress = false;
                    }
                    return;
                }
                else
                {

                    Stack.NCacheLog.Error("pbcast.GMS.handleJoinRequest()", mbr + " has sent a joining request while it is already in member list - Resending current view and digest");
                   
                    View view = new View(this.view_id, members.Members);
                    view.CoordinatorGmsId = unique_id;
                    join_rsp = new JoinRsp(view, this.digest, JoinResult.Success);
                    m = new Message(mbr, null, null);
                    hdr = new HDR(HDR.JOIN_RSP, join_rsp);
                    m.putHeader(HeaderType.GMS, hdr);
                    passDown(new Event(Event.MSG, m, Priority.Critical));
                    lock (join_mutex)
                    {
                        _nodeJoiningInProgress = false;
                    }
                    return;
                }
            }

            

            if (allowJoin(mbr, isStartedAsMirror))
            {
                Stack.NCacheLog.Debug("pbcast.GMS.handleJoinRequest()", " joining allowed");
                bool acauireHashmap = true;

                join_rsp = impl.handleJoin(mbr, subGroup_name, isStartedAsMirror, gmsId, ref acauireHashmap);

                if (join_rsp == null)
                    Stack.NCacheLog.Error("pbcast.GMS.handleJoinRequest()", impl.GetType().ToString() + ".handleJoin(" + mbr + ") returned null: will not be able to multicast new view");

                //muds:
                //sends a request to the caching layer for the new hashmap after this member joins.
                System.Collections.ArrayList mbrs = new System.Collections.ArrayList(1);
                mbrs.Add(mbr);

                //muds:
                //some time coordinator gms impl returns the same existing view in join response. 
                //we dont need to acquire the hashmap again in this case coz that hashmap has already been acquired.
                if (acauireHashmap)
                    acquireHashmap(mbrs, true, subGroup_name, isStartedAsMirror);

                // 2. Send down a local TMP_VIEW event. This is needed by certain layers (e.g. NAKACK) to compute correct digest
                //    in case client's next request (e.g. getState()) reaches us *before* our own view change multicast.
                // Check NAKACK's TMP_VIEW handling for details
                if (join_rsp != null && join_rsp.View != null)
                {
                    //muds:
                    //add the hash map as part of view.
                    if (_hashmap != null)
                    {
                        Object[] mapsArray = (Object[])_hashmap;
                        DistributionMaps maps = (DistributionMaps)mapsArray[0];
                        if (maps != null)
                        {
                           
                            join_rsp.View.DistributionMaps = maps;
                        }
                        

                        join_rsp.View.MirrorMapping = mapsArray[1] as CacheNode[];

                    }
                    passDown(new Event(Event.TMP_VIEW, join_rsp.View));
                } 
            }
            else
                Stack.NCacheLog.Debug("pbcast.GMS.handleJoinRequest()", " joining not allowed");

            // 3. Return result to client
            m = new Message(mbr, null, null);
            hdr = new HDR(HDR.JOIN_RSP, join_rsp);
            m.putHeader(HeaderType.GMS, hdr);
            passDown(new Event(Event.MSG, m, Priority.Critical));

            // 4. Bcast the new view
            if (join_rsp != null)
                castViewChange(join_rsp.View);

            lock (join_mutex)
            {
                _nodeJoiningInProgress = false;
            }

           
        }
Esempio n. 16
0
        /// <summary> Received a bcast reply - Match with the pending bcast request and move
        /// the message in the list of messages to be delivered above
        /// 
        /// </summary>
        /// <param name="header">the header of the bcast reply
        /// </param>
        private void _recvBcastReply(HDR header, Message rspMsg)
        {
            Message msg;
            long id;

            // i. If blocked, discard the bcast reply
            //
            // ii. Assign the received seqID to the message and broadcast it
            //
            // iii.
            // - Acknowledge the message to the retransmitter
            // - If non-existent BCAST_REQ, send a fake bcast to avoid seqID gaps
            // - If localID == NULL_ID, it's a null BCAST, else normal BCAST
            // - Set the seq ID of the message to the one sent by the sequencer

            if (state == BLOCK)
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Blocked, discard bcast rep");
                return;
            }
         
            request_lock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                object tempObject = reqTbl[(long)header.localSeqID];
                reqTbl.Remove((long)header.localSeqID);
                msg = (Message)tempObject;
            }
            finally
            {
                request_lock.ReleaseWriterLock();
            }
            if (msg != null)
            {
                retransmitter.ack(header.localSeqID);
                id = header.localSeqID;
            }
            else
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Bcast reply to " + "non-existent BCAST_REQ[" + header.localSeqID + "], Sending NULL bcast");
                id = NULL_ID;
                msg = new Message(null, addr, new byte[0]);
                msg.IsUserMsg = true;
            }


            
            HDR hdr = new HDR();
            hdr.type = HDR.BCAST;
            hdr.localSeqID = id;
            hdr.seqID = header.seqID;
            hdr.viewId = header.viewId;

            msg.putHeader(HeaderType.TOTAL, hdr);
            msg.IsUserMsg = true;
            msg.Type = MsgType.SEQUENCED;
           
            Event evt = new Event();
            evt.Type = Event.MSG;
            evt.Arg = msg;
            evt.Priority = msg.Priority;
            msg.Dest = null;
            msg.Dests = null;

            passDown(evt);
        }
Esempio n. 17
0
        /// <summary> Received an mcast reply - Match with the pending mcast request and move
        /// the message in the list of messages to be delivered above
        /// 
        /// </summary>
        /// <param name="header">the header of the bcast reply
        /// </param>
        private void _recvMcastReply(HDR header, Address subgroupCoordinator)
        {
            Message msg;
            long id;

            // i. If blocked, discard the mcast reply
            //
            // ii. Assign the received seqID to the message and multicast it
            //
            // iii.
            // - Acknowledge the message to the retransmitter
            // - If non-existent MCAST_REQ, send a fake mcast to avoid seqID gaps
            // - If localID == NULL_ID, it's a null MCAST, else normal MCAST
            // - Set the seq ID of the message to the one sent by the group sequencer

            if (state == BLOCK)
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Blocked, discard mcast rep");
                return;
            }
           
            request_lock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                object tempObject = _mcastReqTbl[(long)header.localSeqID];
                _mcastReqTbl.Remove((long)header.localSeqID);
                msg = (Message)tempObject;

            }
            finally
            {
                request_lock.ReleaseWriterLock();
            }

            if (msg != null)
            {
                _mcastRetransmitter.ack(header.localSeqID);
                id = header.localSeqID;
            }
            else
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Mcast reply to " + "non-existent MCAST_REQ[" + header.localSeqID + "], Sending NULL mcast");
                id = NULL_ID;
                msg = new Message(null, addr, new byte[0]);
                msg.IsUserMsg = true;

                string subGroupID = this._mbrsSubgroupMap[subgroupCoordinator] as string;
                if (subGroupID != null)
                {
                    ArrayList groupMbrs = (ArrayList)this._sequencerTbl[subGroupID] as ArrayList;
                    if (groupMbrs != null && groupMbrs.Count > 0)
                        msg.Dests = groupMbrs.Clone() as ArrayList;

                    if (msg.Dests == null)
                        if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info('[' + subGroupID + "]destination list is empty");

                }
                else
                    return;
            }


           
            HDR hdr = new HDR();
            hdr.type = HDR.MCAST;
            hdr.localSeqID = id;
            hdr.seqID = header.seqID;
            hdr.viewId = header.viewId;

            if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TOTAL._recvMcastReply()", id + " hdr = " + Global.CollectionToString(msg.Headers));
            msg.putHeader(HeaderType.TOTAL, hdr);
            msg.IsUserMsg = true;
            msg.Type = MsgType.SEQUENCED;
           
            Event evt = new Event();
            evt.Type = Event.MSG;
            evt.Arg = msg;
            evt.Priority = msg.Priority;

            passDown(evt);
        }
Esempio n. 18
0
        /// <summary> Handle a request msg for this correlator
        /// 
        /// </summary>
        /// <param name="req">the request msg
        /// </param>
        private void handleNHopRequest(Message req)
        {
            object retval = null;
            byte[] rsp_buf = null;
            HDR hdr, rsp_hdr, replicaMsg_hdr;
            Message rsp;

            Address destination = null;
            Message replicationMsg = null;

            // i. Remove the request correlator header from the msg and pass it to
            // the registered handler
            //
            // ii. If a reply is expected, pack the return value from the request
            // handler to a reply msg and send it back. The reply msg has the same
            // ID as the request and the name of the sender request correlator
            hdr = (HDR)req.removeHeader(HeaderType.REQUEST_COORELATOR);

            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleNHopRequest()", "calling (" + (request_handler != null ? request_handler.GetType().FullName : "null") + ") with request " + hdr.id);

            try
            {
                if (hdr.rsp_expected)
                    req.RequestId = hdr.id;
                else
                    req.RequestId = -1;

                if (req.HandledAysnc)
                {
                    request_handler.handle(req);
                    return;
                }
                if (hdr.type == HDR.NHOP_REQ)
                {
                    MarkRequestArrived(hdr.id, req.Src);
                    retval = request_handler.handleNHopRequest(req, out destination, out replicationMsg);
                }
            }
            catch (System.Exception t)
            {
                NCacheLog.Error("RequestCorrelator.handleNHopRequest()", "error invoking method, exception=" + t.ToString());
                retval = t;
            }

            if (!hdr.rsp_expected || stopReplying)
                return;

            if (transport == null)
            {
                NCacheLog.Error("RequestCorrelator.handleNHopRequest()", "failure sending " + "response; no transport available");
                return;
            }

            //1. send request to other replica.
            //   this node will send the response to original node.
            if (replicationMsg != null)
            {
                replicaMsg_hdr = new HDR();
                replicaMsg_hdr.type = HDR.REQ;
                replicaMsg_hdr.id = hdr.id;
                replicaMsg_hdr.rsp_expected = true;
                replicaMsg_hdr.whomToReply = req.Src;

                replicationMsg.Dest = destination;
                replicationMsg.putHeader(HeaderType.REQUEST_COORELATOR, replicaMsg_hdr);

                try
                {
                    if (transport is Protocol)
                    {
                        Event evt = new Event();
                        evt.Type = Event.MSG;
                        evt.Arg = replicationMsg;
                        ((Protocol)transport).passDown(evt);
                    }
                    else if (transport is Transport)
                        ((Transport)transport).send(replicationMsg);
                    else
                        NCacheLog.Error("RequestCorrelator.handleRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
                }
                catch (System.Exception e)
                {
                    NCacheLog.Error("RequestCorrelator.handleRequest()", e.ToString());
                }
            }
            
            //2. send reply back to original node
            //   and inform the original node that it must expect another response 
            //   from the replica node. (the response of the request sent in part 1)
            rsp = req.makeReply();

            try
            {
                if (retval is OperationResponse)
                {
                    rsp_buf = (byte[])((OperationResponse)retval).SerializablePayload;
                    rsp.Payload = ((OperationResponse)retval).UserPayload;
                    rsp.responseExpected = true;
                }
                else if (retval is Byte[])
                    rsp_buf = (byte[])retval;
                else
                    rsp_buf = CompactBinaryFormatter.ToByteBuffer(retval, null); // retval could be an exception, or a real value
            }
            catch (System.Exception t)
            {
                NCacheLog.Error("RequestCorrelator.handleRequest()", t.ToString());
                try
                {
                    rsp_buf = CompactBinaryFormatter.ToByteBuffer(t, null); // this call shoudl succeed (all exceptions are serializable)
                }
                catch (System.Exception)
                {
                    NCacheLog.Error("RequestCorrelator.handleRequest()", "failed sending response: " + "return value (" + retval + ") is not serializable");
                    return;
                }
            }

            if (rsp_buf != null)
                rsp.setBuffer(rsp_buf);

            rsp_hdr = new HDR();
            rsp_hdr.type = HDR.NHOP_RSP;
            rsp_hdr.id = hdr.id;
            rsp_hdr.rsp_expected = false;

            if (replicationMsg != null)
            {
                rsp_hdr.expectResponseFrom = destination;
            }
            
            rsp.putHeader(HeaderType.REQUEST_COORELATOR, rsp_hdr);

            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleRequest()", "sending rsp for " + rsp_hdr.id + " to " + rsp.Dest);

            try
            {
                if (transport is Protocol)
                {
                    Event evt = new Event();
                    evt.Type = Event.MSG;
                    evt.Arg = rsp;
                    ((Protocol)transport).passDown(evt);
                }
                else if (transport is Transport)
                    ((Transport)transport).send(rsp);
                else
                    NCacheLog.Error("RequestCorrelator.handleRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
            }
            catch (System.Exception e)
            {
                NCacheLog.Error("RequestCorrelator.handleRequest()", e.ToString());
            }

            MarkRequestProcessed(hdr.id, req.Src);
        }
Esempio n. 19
0
 public static HDR ReadTotalHeader(CompactReader reader)
 {
     byte isNull = reader.ReadByte();
     if (isNull == 1)
         return null;
     HDR newHdr = new HDR();
     newHdr.Deserialize(reader);
     return newHdr;
 }
Esempio n. 20
0
		/// <summary> Handle a request msg for this correlator
		/// 
		/// </summary>
		/// <param name="req">the request msg
		/// </param>
		private void  handleRequest(Message req,Address replyTo)
		{
			object retval;
			byte[] rsp_buf = null;
			HDR hdr, rsp_hdr;
			Message rsp;
			
			// i. Remove the request correlator header from the msg and pass it to
			// the registered handler
			//
			// ii. If a reply is expected, pack the return value from the request
			// handler to a reply msg and send it back. The reply msg has the same
			// ID as the request and the name of the sender request correlator
			hdr = (HDR) req.removeHeader(HeaderType.REQUEST_COORELATOR);
			
			if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleRequest()", "calling (" + (request_handler != null?request_handler.GetType().FullName:"null") + ") with request " + hdr.id);

            TimeStats appTimeStats = null;
            bool isProfilable = false;
			try
			{

                if (hdr.rsp_expected)
                    req.RequestId = hdr.id;
                else
                    req.RequestId = -1;

                if (req.HandledAysnc)
                {
                    request_handler.handle(req);
                    return;
                }
                if (hdr.type == HDR.GET_REQ_STATUS)
                {
                    if(NCacheLog.IsInfoEnabled) NCacheLog.Info("ReqCorrelator.handleRequet", hdr.status_reqId + " receive RequestStatus request from " + req.Src);
                    retval = GetRequestStatus(hdr.status_reqId, req.Src);
                    if (NCacheLog.IsInfoEnabled) NCacheLog.Info("ReqCorrelator.handleRequet", hdr.status_reqId + " RequestStatus :" + retval);
                }
                else
                {
                    MarkRequestArrived(hdr.id, req.Src);
                    retval = request_handler.handle(req);
                }

                //request is being handled asynchronously, so response will be send by
                //the the user itself.
                
			}
			catch (System.Exception t)
			{
				NCacheLog.Error("RequestCorrelator.handleRequest()", "error invoking method, exception=" + t.ToString());
				retval = t;
			}

            if (!hdr.rsp_expected || stopReplying)
                // asynchronous call, we don't need to send a response; terminate call here
                return;
			
			if (transport == null)
			{
				NCacheLog.Error("RequestCorrelator.handleRequest()", "failure sending " + "response; no transport available");
				return ;
			}

            rsp = req.makeReply();
            if (replyTo != null) rsp.Dest = replyTo;
			// changed (bela Feb 20 2004): catch exception and return exception
			try
			{
                if (retval is OperationResponse)
                {
                    rsp_buf = (byte[]) ((OperationResponse)retval).SerializablePayload;
                    rsp.Payload = ((OperationResponse)retval).UserPayload;
                    rsp.responseExpected = true;
                }
                else if(retval is Byte[])
					rsp_buf = (byte[])retval;
				else
					rsp_buf = CompactBinaryFormatter.ToByteBuffer(retval,null); // retval could be an exception, or a real value
			}
			catch (System.Exception t)
			{
				NCacheLog.Error("RequestCorrelator.handleRequest()", t.ToString());
				try
				{
					rsp_buf = CompactBinaryFormatter.ToByteBuffer(t,null); // this call shoudl succeed (all exceptions are serializable)
				}
				catch (System.Exception)
				{
					NCacheLog.Error("RequestCorrelator.handleRequest()", "failed sending response: " + "return value (" + retval + ") is not serializable");
					return ;
				}
			}

            if (rsp_buf != null)
				rsp.setBuffer(rsp_buf);

            if (rsp.Dest.Equals(local_addr))
            {                
                //we need not to put our response on the stack.
                rsp.Src = local_addr;
                ReceiveLocalResponse(rsp,hdr.id);
                return;
            }
            
            rsp_hdr = new HDR();
            rsp_hdr.type = HDR.RSP;
            rsp_hdr.id = hdr.id;
            rsp_hdr.rsp_expected = false;


			rsp.putHeader(HeaderType.REQUEST_COORELATOR, rsp_hdr);
			
			if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleRequest()", "sending rsp for " + rsp_hdr.id + " to " + rsp.Dest);
						
			try
			{
               
                if (transport is Protocol)
                {
                    
                    Event evt = new Event();
                    evt.Type = Event.MSG;
                    evt.Arg = rsp;
                    ((Protocol)transport).passDown(evt);
                }
                else if (transport is Transport)
                    ((Transport)transport).send(rsp);
                else
                    NCacheLog.Error("RequestCorrelator.handleRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
			}
			catch (System.Exception e)
			{
				NCacheLog.Error("RequestCorrelator.handleRequest()", e.ToString());
			}
            MarkRequestProcessed(hdr.id, req.Src);
		}
Esempio n. 21
0
        private void _sendMcastRequest(Message msg, long id)
        {
            // i. Store away the message while waiting for the sequencer's reply
            // ii. Send a mcast request immediatelly and also schedule a
            // retransmission
            Address groupSequencerAddr = addr;
            ArrayList dests = msg.Dests;


            groupSequencerAddr = getGroupSequencer(dests);

            if (groupSequencerAddr == null) return;

            if (addr.CompareTo(groupSequencerAddr) == 0)
            {
                long seqid = NextMCastSeqID;

                int viewId = -1;
                try
                {
                    stateLock.AcquireReaderLock(Timeout.Infinite);
                    viewId = (int)(currentViewId != null ? currentViewId.Id : -1);
                }
                finally
                {
                    stateLock.ReleaseReaderLock();
                }
                //Rent the event
                Event evt = null;
               
                evt = new Event();
                evt.Type = Event.MSG;
                evt.Priority = msg.Priority;
                evt.Arg = msg;

                //Rent the header
                
                HDR hdr = new HDR();
                hdr.type = HDR.MCAST;
                hdr.localSeqID = id;
                hdr.seqID = seqid;
                hdr.viewId = viewId;
                msg.Type = MsgType.SEQUENCED;

                msg.putHeader(HeaderType.TOTAL, hdr);

                //msg.Dest = null;
                //===================================================
                //now the message will contain a list of addrs in case of multicast.
                //=======================================================

                passDown(evt);
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("TOTAL._sendMcastRequest()", "shortcut mcast seq# " + seqid);
                return;
            }
           
            request_lock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                _mcastReqTbl[(long)id] = msg;
            }
            finally
            {
                request_lock.ReleaseWriterLock();
            }
            _transmitMcastRequest(id, groupSequencerAddr);
            _mcastRetransmitter.add(id, msg);
        }
Esempio n. 22
0
        private void handleStatusRequest(Message req)
        {
            object retval;
            byte[] rsp_buf = null;
            HDR hdr, rsp_hdr;
            Message rsp;

            // i. Remove the request correlator header from the msg and pass it to
            // the registered handler
            //
            // ii. If a reply is expected, pack the return value from the request
            // handler to a reply msg and send it back. The reply msg has the same
            // ID as the request and the name of the sender request correlator
            hdr = (HDR)req.removeHeader(HeaderType.REQUEST_COORELATOR);

            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleStatusRequest()", "calling (" + (request_handler != null ? request_handler.GetType().FullName : "null") + ") with request " + hdr.id);


            if (transport == null)
            {
                NCacheLog.Error("RequestCorrelator.handleStatusRequest()", "failure sending " + "response; no transport available");
                return;
            }
            RequestStatus status = GetRequestStatus(hdr.id, req.Src);

            rsp_hdr = new HDR();
            rsp_hdr.type = HDR.GET_REQ_STATUS_RSP;
            rsp_hdr.id = hdr.id;
            rsp_hdr.rsp_expected = false;
            rsp_hdr.reqStatus = status;

            rsp = req.makeReply();
            rsp.putHeader(HeaderType.REQUEST_COORELATOR, rsp_hdr);

            if (rsp.Dest.Equals(local_addr))
            {
                //we need not to put our response on the stack.
                rsp.Src = local_addr;
                ReceiveLocalResponse(rsp, hdr.id);
                return;
            }

            if (NCacheLog.IsInfoEnabled) NCacheLog.Info("RequestCorrelator.handleStatusRequest()", "sending rsp for " + rsp_hdr.id + " to " + rsp.Dest);

            try
            {

                if (transport is Protocol)
                {
                    
                    Event evt = new Event();
                    evt.Type = Event.MSG;
                    evt.Arg = rsp;
                    ((Protocol)transport).passDown(evt);
                }
                else if (transport is Transport)
                    ((Transport)transport).send(rsp);
                else
                    NCacheLog.Error("RequestCorrelator.handleStatusRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
            }
            catch (System.Exception e)
            {
                NCacheLog.Error("RequestCorrelator.handleStatusRequest()", e.ToString());
            }
        }
Esempio n. 23
0
        /// <summary> Send the bcast request with the given localSeqID
        /// 
        /// </summary>
        /// <param name="seqID">the local sequence id of the
        /// </param>
        private void _transmitBcastRequest(long seqID)
        {
            Message reqMsg;

            // i. If NULL_STATE, then ignore, just transient state before
            // shutting down the retransmission thread
            // ii. If blocked, be patient - reschedule
            // iii. If the request is not pending any more, acknowledge it
            // iv. Create a broadcast request and send it to the sequencer

            if (state == NULL_STATE)
            {
                if (Stack.NCacheLog.IsInfoEnabled) Stack.NCacheLog.Info("Transmit BCAST_REQ[" + seqID + "] in NULL_STATE");
                return;
            }
            if (state == BLOCK)
                return;

           
            request_lock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                if (!reqTbl.Contains((long)seqID))
                {
                    retransmitter.ack(seqID);
                    return;
                }
            }
            finally
            {
                request_lock.ReleaseReaderLock();
            }

            reqMsg = new Message();
            reqMsg.Dest = sequencerAddr;
            reqMsg.Src = addr;
            reqMsg.setBuffer(new byte[0]);
           
            HDR hdr = new HDR();
            hdr.type = HDR.REQ;
            hdr.localSeqID = seqID;
            hdr.seqID = NULL_ID;

            reqMsg.putHeader(HeaderType.TOTAL, hdr);
            reqMsg.IsUserMsg = true;
            reqMsg.Type = MsgType.TOKEN_SEEKING;
           
            Event evt = new Event();
            evt.Type = Event.MSG;
            evt.Arg = reqMsg;

            passDown(evt);
        }
Esempio n. 24
0
        public void SendResponse(long resp_id, Message response)
        {
            if (response.Dest.Equals(local_addr))
            {
                //we need not to put our response on the stack.
                response.Src = local_addr;
                ReceiveLocalResponse(response, resp_id);
                return;
            }

            HDR rsp_hdr = new HDR();
            rsp_hdr.type = HDR.RSP;
            rsp_hdr.id = resp_id;
            rsp_hdr.rsp_expected = false;

            response.putHeader(HeaderType.REQUEST_COORELATOR, rsp_hdr);

            try
            {

                if (transport is Protocol)
                {
                    
                    Event evt = new Event();
                    evt.Type = Event.MSG;
                    evt.Arg = response;
                    ((Protocol)transport).passDown(evt);
                }
                else if (transport is Transport)
                    ((Transport)transport).send(response);
                else
                    NCacheLog.Error("RequestCorrelator.handleRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
            }
            catch (System.Exception e)
            {
                NCacheLog.Error("RequestCorrelator.handleRequest()", e.ToString());
            }
        }
Esempio n. 25
0
		/// <summary> Send a request to a group. If no response collector is given, no
		/// responses are expected (making the call asynchronous).
		/// 
		/// </summary>
		/// <param name="id">The request ID. Must be unique for this JVM (e.g. current
		/// time in millisecs)
		/// </param>
		/// <param name="dest_mbrs">The list of members who should receive the call. Usually a group RPC
		/// is sent via multicast, but a receiver drops the request if its own address
		/// is not in this list. Will not be used if it is null.
		/// </param>
		/// <param name="msg">The request to be sent. The body of the message carries
		/// the request data
		/// 
		/// </param>
		/// <param name="coll">A response collector (usually the object that invokes
		/// this method). Its methods <code>ReceiveResponse</code> and
		/// <code>Suspect</code> will be invoked when a message has been received
		/// or a member is suspected, respectively.
		/// </param>
		public virtual void  sendRequest(long id, System.Collections.ArrayList dest_mbrs, Message msg, RspCollector coll, byte hdrType)
		{
			HDR hdr = null;
			
			if (transport == null)
			{
				NCacheLog.Warn("RequestCorrelator.sendRequest()", "transport is not available !");
				return ;
			}
			
			// i. Create the request correlator header and add it to the
			// msg
			// ii. If a reply is expected (sync call / 'coll != null'), add a
			// coresponding entry in the pending requests table
			// iii. If deadlock detection is enabled, set/update the call stack
			// iv. Pass the msg down to the protocol layer below

            hdr = msg.getHeader(HeaderType.REQUEST_COORELATOR) as RequestCorrelator.HDR;
            if (hdr == null)
            {
                hdr = new HDR();
                hdr.type = hdrType;
                hdr.id = id;
                hdr.rsp_expected = coll != null ? true : false;
                hdr.dest_mbrs = dest_mbrs;
            }

			if (coll != null)
			{
				if (deadlock_detection)
				{
					if (local_addr == null)
					{
						NCacheLog.Error("RequestCorrelator.sendRequest()", "local address is null !");
						return ;
					}
					System.Collections.ArrayList new_call_stack = (call_stack != null?(System.Collections.ArrayList) call_stack.Clone():new System.Collections.ArrayList());
					new_call_stack.Add(local_addr);
					hdr.call_stack = new_call_stack;
				}
                addEntry(hdr.id, new RequestEntry(coll), dest_mbrs);
			}
			msg.putHeader(HeaderType.REQUEST_COORELATOR, hdr);
			
			try
			{
                if (transport is Protocol)
                {
                   
                    Event evt = new Event();
                    evt.Type = Event.MSG;
                    evt.Arg = msg;
                    ((Protocol)transport).passDown(evt);
                }
                else if (transport is Transport)
                    ((Transport)transport).send(msg);
                else
                    NCacheLog.Error("RequestCorrelator.sendRequest()", "transport object has to be either a " + "Transport or a Protocol, however it is a " + transport.GetType());
			}
			catch (System.Exception e)
			{
				NCacheLog.Error("RequestCorrelator.sendRequest()",e.ToString());				
			}
		}
Esempio n. 26
0
 /// <summary>
 /// We inform other nodes about the possible death of coordinator
 /// 
 /// </summary>
 /// <param name="otherNodes"></param>
 public void InformOthersAboutCoordinatorDeath(ArrayList otherNodes, Address deadNode)
 {
     if (otherNodes != null && otherNodes.Count > 0)
     {
         Message msg = new Message(null, null, new byte[0]);
         msg.Dests = otherNodes;
         GMS.HDR hdr = new HDR(GMS.HDR.INFORM_ABOUT_NODE_DEATH);
         hdr.arg = deadNode;
         msg.putHeader(HeaderType.GMS, hdr);
         down(new Event(Event.MSG,msg,Priority.Critical));
     }
 }