예제 #1
0
        public void BeginGetResponse(byte[] postData, string contentType, int millisecondsTimeout)
        {
            _PostData    = postData;
            _ContentType = contentType;

            if (_Request != null)
            {
                _Request.Abort();
                _Request = null;
            }

            if (postData == null)
            {
                // GET
                //Logger.Log.Debug("[CapsClient] GET " + _Address);
                _Request = CapsBase.DownloadStringAsync(_Address, _ClientCert, millisecondsTimeout, DownloadProgressHandler,
                                                        RequestCompletedHandler);
            }
            else
            {
                // POST
                //Logger.Log.Debug("[CapsClient] POST (" + postData.Length + " bytes) " + _Address);
                _Request = CapsBase.UploadDataAsync(_Address, _ClientCert, contentType, postData, millisecondsTimeout, null,
                                                    DownloadProgressHandler, RequestCompletedHandler);
            }
        }
예제 #2
0
        private void Client_OpenWriteCompleted(object sender, CapsBase.OpenWriteCompletedEventArgs e)
        {
            bool raiseEvent = false;

            if (!_Dead)
            {
                if (!_Running) raiseEvent = true;

                // We are connected to the event queue
                _Running = true;
            }

            // Create an EventQueueGet request
            OSDMap request = new OSDMap();
            request["ack"] = new OSD();
            request["done"] = OSD.FromBoolean(false);

            byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

            _Client.UploadDataAsync(_Client.Location, postData);

            if (raiseEvent)
            {
                Logger.Log.Debug("Capabilities event queue connected");

                // The event queue is starting up for the first time
                if (OnConnected != null)
                {
                    try { OnConnected(); }
                    catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
                }
            }
        }
예제 #3
0
 void Init(Uri capability, X509Certificate2 clientCert)
 {
     _Client = new CapsBase(capability, clientCert);
     _Client.DownloadProgressChanged += new CapsBase.DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
     _Client.UploadProgressChanged   += new CapsBase.UploadProgressChangedEventHandler(Client_UploadProgressChanged);
     _Client.UploadDataCompleted     += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
     _Client.DownloadStringCompleted += new CapsBase.DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
 }
예제 #4
0
 /// <summary>Constructor</summary>
 public DownloadRequest(Uri address, int millisecondsTimeout,
     string contentType,
     CapsBase.DownloadProgressEventHandler downloadProgressCallback,
     CapsBase.RequestCompletedEventHandler completedCallback)
 {
     this.Address = address;
     this.MillisecondsTimeout = millisecondsTimeout;
     this.DownloadProgressCallback = downloadProgressCallback;
     this.CompletedCallback = completedCallback;
     this.ContentType = contentType;
 }
예제 #5
0
        public void GetRequestAsync(int msTimeout)
        {
            if (_Request != null)
            {
                _Request.Abort();
                _Request = null;
            }

            _Request = CapsBase.GetStringAsync(_Address, _ClientCert, msTimeout, DownloadProgressHandler,
                                               RequestCompletedHandler);
        }
예제 #6
0
        public void Start()
        {
            _Dead = false;

            // Create an EventQueueGet request
            OSDMap request = new OSDMap {
                ["ack"] = new OSD(), ["done"] = OSD.FromBoolean(false)
            };

            byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

            _Request = CapsBase.PostDataAsync(_Address, null, REQUEST_CONTENT_TYPE, postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
        }
예제 #7
0
        public void DeleteRequestAsync(byte[] postData, string contentType, int msTimeout)
        {
            _PostData    = postData;
            _ContentType = contentType;

            if (_Request != null)
            {
                _Request.Abort();
                _Request = null;
            }

            _Request = CapsBase.DeleteDataAsync(_Address, _ClientCert, contentType, postData, msTimeout,
                                                null, DownloadProgressHandler, RequestCompletedHandler);
        }
예제 #8
0
        public void Start()
        {
            _Dead = false;

            // Create an EventQueueGet request
            OSDMap request = new OSDMap();

            request["ack"]  = new OSD();
            request["done"] = OSD.FromBoolean(false);

            byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

            _Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
        }
예제 #9
0
        void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
        {
            // We don't care about this request now that it has completed
            _Request = null;

            OSDArray events = null;
            int      ack    = 0;

            if (responseData != null)
            {
                _errorCount = 0;
                // Got a response
                OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap;

                if (result != null)
                {
                    events = result["events"] as OSDArray;
                    ack    = result["id"].AsInteger();
                }
                else
                {
                    Logger.Log("Got an unparseable response from the event queue: \"" +
                               System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
                }
            }
            else if (error != null)
            {
                #region Error handling

                HttpStatusCode code = HttpStatusCode.OK;

                if (error is WebException)
                {
                    WebException webException = (WebException)error;

                    if (webException.Response != null)
                    {
                        code = ((HttpWebResponse)webException.Response).StatusCode;
                    }
                    else if (webException.Status == WebExceptionStatus.RequestCanceled)
                    {
                        goto HandlingDone;
                    }
                }

                if (error is WebException && ((WebException)error).Response != null)
                {
                    code = ((HttpWebResponse)((WebException)error).Response).StatusCode;
                }

                if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
                {
                    Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead    = true;
                }
                else if (code == HttpStatusCode.BadGateway)
                {
                    // This is not good (server) protocol design, but it's normal.
                    // The EventQueue server is a proxy that connects to a Squid
                    // cache which will time out periodically. The EventQueue server
                    // interprets this as a generic error and returns a 502 to us
                    // that we ignore
                }
                else
                {
                    ++_errorCount;

                    // Try to log a meaningful error message
                    if (code != HttpStatusCode.OK)
                    {
                        Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}",
                                                 _Address, code), Helpers.LogLevel.Warning);
                    }
                    else if (error.InnerException != null)
                    {
                        Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}",
                                                 _Address, error.InnerException.Message), Helpers.LogLevel.Warning);
                    }
                    else
                    {
                        Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
                                                 _Address, error.Message), Helpers.LogLevel.Warning);
                    }
                }

                #endregion Error handling
            }
            else
            {
                ++_errorCount;

                Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
            }

HandlingDone:

            #region Resume the connection

            if (_Running)
            {
                OSDMap osdRequest = new OSDMap();
                if (ack != 0)
                {
                    osdRequest["ack"] = OSD.FromInteger(ack);
                }
                else
                {
                    osdRequest["ack"] = new OSD();
                }
                osdRequest["done"] = OSD.FromBoolean(_Dead);

                byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);

                if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
                {
                    Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount)));
                }

                // Resume the connection. The event handler for the connection opening
                // just sets class _Request variable to the current HttpWebRequest
                CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT,
                                         delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    Logger.DebugLog("Sent event queue shutdown message");
                }
            }

            #endregion Resume the connection

            #region Handle incoming events

            if (OnEvent != null && events != null && events.Count > 0)
            {
                // Fire callbacks for each event received
                foreach (OSDMap evt in events)
                {
                    string msg  = evt["message"].AsString();
                    OSDMap body = (OSDMap)evt["body"];

                    try { OnEvent(msg, body); }
                    catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
                }
            }

            #endregion Handle incoming events
        }
예제 #10
0
        private void Client_UploadDataCompleted(object sender, CapsBase.UploadDataCompletedEventArgs e)
        {
            OSDArray events = null;
            int ack = 0;

            if (e.Error != null)
            {
                HttpStatusCode code = HttpStatusCode.OK;
                if (e.Error is WebException && ((WebException)e.Error).Response != null)
                    code = ((HttpWebResponse)((WebException)e.Error).Response).StatusCode;

                if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
                {
                    Logger.Log.InfoFormat("Closing event queue at {0} due to missing caps URI", _Client.Location);

                    _Running = false;
                    _Dead = true;
                }
                else if (code == HttpStatusCode.BadGateway)
                {
                    // This is not good (server) protocol design, but it's normal.
                    // The EventQueue server is a proxy that connects to a Squid
                    // cache which will time out periodically. The EventQueue server
                    // interprets this as a generic error and returns a 502 to us
                    // that we ignore
                }
                else if (!e.Cancelled)
                {
                    // Try to log a meaningful error message
                    if (code != HttpStatusCode.OK)
                    {
                        Logger.Log.WarnFormat("Unrecognized caps connection problem from {0}: {1}",
                            _Client.Location, code);
                    }
                    else if (e.Error.InnerException != null)
                    {
                        Logger.Log.WarnFormat("Unrecognized caps exception from {0}: {1}",
                            _Client.Location, e.Error.InnerException.Message);
                    }
                    else
                    {
                        Logger.Log.WarnFormat("Unrecognized caps exception from {0}: {1}",
                            _Client.Location, e.Error.Message);
                    }
                }
            }
            else if (!e.Cancelled && e.Result != null)
            {
                // Got a response
                OSD result = OSDParser.DeserializeLLSDXml(e.Result);
                if (result != null && result.Type == OSDType.Map)
                {
                    // Parse any events returned by the event queue
                    OSDMap map = (OSDMap)result;

                    events = (OSDArray)map["events"];
                    ack = map["id"].AsInteger();
                }
            }
            else if (e.Cancelled)
            {
                // Connection was cancelled
                Logger.Log.Debug("Cancelled connection to event queue at " + _Client.Location);
            }

            if (_Running)
            {
                OSDMap request = new OSDMap();
                if (ack != 0) request["ack"] = OSD.FromInteger(ack);
                else request["ack"] = new OSD();
                request["done"] = OSD.FromBoolean(_Dead);

                byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);

                _Client.UploadDataAsync(_Client.Location, postData);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    Logger.Log.Debug("Sent event queue shutdown message");
                }
            }

            if (OnEvent != null && events != null && events.Count > 0)
            {
                // Fire callbacks for each event received
                foreach (OSDMap evt in events)
                {
                    string msg = evt["message"].AsString();
                    OSDMap body = (OSDMap)evt["body"];

                    try { OnEvent(msg, body); }
                    catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
                }
            }
        }
예제 #11
0
 private void Client_UploadProgressChanged(object sender, CapsBase.UploadProgressChangedEventArgs e)
 {
     if (OnProgress != null)
     {
         try { OnProgress(this, e.BytesReceived, e.BytesSent, e.TotalBytesToReceive, e.TotalBytesToSend); }
         catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
     }
 }
예제 #12
0
        private void Client_UploadDataCompleted(object sender, CapsBase.UploadDataCompletedEventArgs e)
        {
            if (OnComplete != null && !e.Cancelled)
            {
                if (e.Error == null)
                {
                    OSD result = OSDParser.DeserializeLLSDXml(e.Result);

                    try { OnComplete(this, result, e.Error); }
                    catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
                }
                else
                {
                    // Some error occurred, try to figure out what happened
                    HttpStatusCode code = HttpStatusCode.OK;
                    if (e.Error is WebException && ((WebException)e.Error).Response != null)
                        code = ((HttpWebResponse)((WebException)e.Error).Response).StatusCode;

                    if (code == HttpStatusCode.BadGateway)
                    {
                        // This is not good (server) protocol design, but it's normal.
                        // The CAPS server is a proxy that connects to a Squid
                        // cache which will time out periodically. The CAPS server
                        // interprets this as a generic error and returns a 502 to us
                        // that we ignore
                        StartRequest(_PostData, _ContentType);
                    }
                    else if (code != HttpStatusCode.OK)
                    {
                        // Status code was set to something unknown, this is a failure
                        Logger.Log.DebugFormat("Caps error at {0}: {1}", _Client.Location, code);

                        try { OnComplete(this, null, e.Error); }
                        catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
                    }
                    else
                    {
                        // Status code was not set, some other error occurred. This is a failure
                        Logger.Log.DebugFormat("Caps error at {0}: {1}", _Client.Location, e.Error.Message);

                        try { OnComplete(this, null, e.Error); }
                        catch (Exception ex) { Logger.Log.Error(ex.Message, ex); }
                    }
                }
            }
            else if (e.Cancelled)
            {
                Logger.Log.Debug("Capability action at " + _Client.Location + " cancelled");
            }
        }
예제 #13
0
 void Init(Uri capability, X509Certificate2 clientCert)
 {
     _Client = new CapsBase(capability, clientCert);
     _Client.DownloadProgressChanged += new CapsBase.DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
     _Client.UploadProgressChanged += new CapsBase.UploadProgressChangedEventHandler(Client_UploadProgressChanged);
     _Client.UploadDataCompleted += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
     _Client.DownloadStringCompleted += new CapsBase.DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
 }
예제 #14
0
        void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
        {
            // We don't care about this request now that it has completed
            _Request = null;

            OSDArray events = null;
            int      ack    = 0;

            if (responseData != null)
            {
                _errorCount = 0;
                // Got a response
                if (OSDParser.DeserializeLLSDXml(responseData) is OSDMap result)
                {
                    events = result["events"] as OSDArray;
                    ack    = result["id"].AsInteger();
                }
                else
                {
                    Logger.Log("Got an unparseable response from the event queue: \"" +
                               System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
                }
            }
            else if (error != null)
            {
                #region Error handling

                HttpStatusCode code = HttpStatusCode.OK;

                if (error is WebException webException)
                {
                    // Filter out some of the status requests to skip handling
                    switch (webException.Status)
                    {
                    case WebExceptionStatus.RequestCanceled:
                    case WebExceptionStatus.KeepAliveFailure:
                        goto HandlingDone;
                    }

                    if (webException.Response != null)
                    {
                        code = ((HttpWebResponse)webException.Response).StatusCode;
                    }
                }

                switch (code)
                {
                case HttpStatusCode.NotFound:
                case HttpStatusCode.Gone:
                    Logger.Log($"Closing event queue at {_Address} due to missing caps URI", Helpers.LogLevel.Info);

                    _Running = false;
                    _Dead    = true;
                    break;

                case (HttpStatusCode)499:     // weird error returned occasionally, ignore for now
                case HttpStatusCode.BadGateway:
                    // This is not good (server) protocol design, but it's normal.
                    // The EventQueue server is a proxy that connects to a Squid
                    // cache which will time out periodically. The EventQueue server
                    // interprets this as a generic error and returns a 502 to us
                    // that we ignore
                    break;

                default:
                    ++_errorCount;

                    // Try to log a meaningful error message
                    if (code != HttpStatusCode.OK)
                    {
                        Logger.Log($"Unrecognized caps connection problem from {_Address}: {code}",
                                   Helpers.LogLevel.Warning);
                    }
                    else if (error.InnerException != null)
                    {
                        Logger.Log(
                            $"Unrecognized internal caps exception from {_Address}: {error.InnerException.Message}",
                            Helpers.LogLevel.Warning);
                    }
                    else
                    {
                        Logger.Log($"Unrecognized caps exception from {_Address}: {error.Message}",
                                   Helpers.LogLevel.Warning);
                    }
                    break;
                }

                #endregion Error handling
            }
            else
            {
                ++_errorCount;

                Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
            }

HandlingDone:

            #region Resume the connection

            if (_Running)
            {
                OSDMap osdRequest = new OSDMap();
                if (ack != 0)
                {
                    osdRequest["ack"] = OSD.FromInteger(ack);
                }
                else
                {
                    osdRequest["ack"] = new OSD();
                }
                osdRequest["done"] = OSD.FromBoolean(_Dead);

                byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);

                if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
                {
                    Thread.Sleep(Math.Min(REQUEST_BACKOFF_SECONDS + _errorCount * REQUEST_BACKOFF_SECONDS_INC, REQUEST_BACKOFF_SECONDS_MAX));
                }

                // Resume the connection. The event handler for the connection opening
                // just sets class _Request variable to the current HttpWebRequest
                CapsBase.PostDataAsync(_Address, null, REQUEST_CONTENT_TYPE, postData, REQUEST_TIMEOUT,
                                       delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);

                // If the event queue is dead at this point, turn it off since
                // that was the last thing we want to do
                if (_Dead)
                {
                    _Running = false;
                    Logger.DebugLog("Sent event queue shutdown message");
                }
            }

            #endregion Resume the connection

            #region Handle incoming events

            if (OnEvent == null || events == null || events.Count <= 0)
            {
                return;
            }
            // Fire callbacks for each event received
            foreach (var osd in events)
            {
                var    evt  = (OSDMap)osd;
                string msg  = evt["message"].AsString();
                OSDMap body = (OSDMap)evt["body"];

                try { OnEvent(msg, body); }
                catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
            }

            #endregion Handle incoming events
        }
예제 #15
0
 public void QueueDownlad(Uri address, int millisecondsTimeout,
     string contentType,
     CapsBase.DownloadProgressEventHandler downloadProgressCallback,
     CapsBase.RequestCompletedEventHandler completedCallback)
 {
     lock (queue)
     {
         queue.Enqueue(new QueuedItem(
             address,
             millisecondsTimeout,
             contentType,
             downloadProgressCallback,
             completedCallback
             ));
     }
     EnqueuePending();
 }
예제 #16
0
 public EventQueueClient(Uri eventQueueLocation)
 {
     _Client = new CapsBase(eventQueueLocation, null);
     _Client.OpenWriteCompleted  += new CapsBase.OpenWriteCompletedEventHandler(Client_OpenWriteCompleted);
     _Client.UploadDataCompleted += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
 }
예제 #17
0
 public EventQueueClient(Uri eventQueueLocation)
 {
     _Client = new CapsBase(eventQueueLocation, null);
     _Client.OpenWriteCompleted += new CapsBase.OpenWriteCompletedEventHandler(Client_OpenWriteCompleted);
     _Client.UploadDataCompleted += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
 }