aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework/RestClient.cs
blob: 4939cf7bfd35faf6cb5b8205922bcd1bea784359 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using log4net;

using OpenSim.Framework.ServiceAuth;

namespace OpenSim.Framework
{
    /// <summary>
    /// Implementation of a generic REST client
    /// </summary>
    /// <remarks>
    /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
    /// class is designed to execute both synchronously and asynchronously.
    ///
    /// Internally the implementation works as a two stage asynchronous web-client.
    /// When the request is initiated, RestClient will query asynchronously for for a web-response,
    /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
    /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
    /// object into a memorystream as a sequence of asynchronous reads.
    ///
    /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
    /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
    /// invoked by the caller in either synchronous mode or asynchronous modes.
    /// </remarks>
    public class RestClient : IDisposable
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        // private string realuri;

        #region member variables

        /// <summary>
        /// The base Uri of the web-service e.g. http://www.google.com
        /// </summary>
        private string _url;

        /// <summary>
        /// Path elements of the query
        /// </summary>
        private List<string> _pathElements = new List<string>();

        /// <summary>
        /// Parameter elements of the query, e.g. min=34
        /// </summary>
        private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();

        /// <summary>
        /// Request method. E.g. GET, POST, PUT or DELETE
        /// </summary>
        private string _method;

        /// <summary>
        /// Temporary buffer used to store bytes temporarily as they come in from the server
        /// </summary>
        private byte[] _readbuf;

        /// <summary>
        /// MemoryStream representing the resulting resource
        /// </summary>
        private Stream _resource;

        /// <summary>
        /// WebRequest object, held as a member variable
        /// </summary>
        private HttpWebRequest _request;

        /// <summary>
        /// WebResponse object, held as a member variable, so we can close it
        /// </summary>
        private HttpWebResponse _response;

        /// <summary>
        /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
        /// </summary>
        //public static ManualResetEvent _allDone = new ManualResetEvent(false);

        /// <summary>
        /// Default time out period
        /// </summary>
        //private const int DefaultTimeout = 10*1000; // 10 seconds timeout

        /// <summary>
        /// Default Buffer size of a block requested from the web-server
        /// </summary>
        private const int BufferSize = 4096; // Read blocks of 4 KB.


        /// <summary>
        /// if an exception occours during async processing, we need to save it, so it can be
        /// rethrown on the primary thread;
        /// </summary>
        private Exception _asyncException;

        #endregion member variables

        #region constructors

        /// <summary>
        /// Instantiate a new RestClient
        /// </summary>
        /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
        public RestClient(string url)
        {
            _url = url;
            _readbuf = new byte[BufferSize];
            _resource = new MemoryStream();
            _request = null;
            _response = null;
            _lock = new object();
        }

        private object _lock;

        #endregion constructors


        #region Dispose

        private bool disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
            {
                _resource.Dispose();
            }

            disposed = true;
        }

        #endregion Dispose


        /// <summary>
        /// Add a path element to the query, e.g. assets
        /// </summary>
        /// <param name="element">path entry</param>
        public void AddResourcePath(string element)
        {
            if (isSlashed(element))
                _pathElements.Add(element.Substring(0, element.Length - 1));
            else
                _pathElements.Add(element);
        }

        /// <summary>
        /// Add a query parameter to the Url
        /// </summary>
        /// <param name="name">Name of the parameter, e.g. min</param>
        /// <param name="value">Value of the parameter, e.g. 42</param>
        public void AddQueryParameter(string name, string value)
        {
            try
            {
                _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
            }
            catch (ArgumentException)
            {
                m_log.Error("[REST]: Query parameter " + name + " is already added.");
            }
            catch (Exception e)
            {
                m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
            }
        }

        /// <summary>
        /// Add a query parameter to the Url
        /// </summary>
        /// <param name="name">Name of the parameter, e.g. min</param>
        public void AddQueryParameter(string name)
        {
            try
            {
                _parameterElements.Add(HttpUtility.UrlEncode(name), null);
            }
            catch (ArgumentException)
            {
                m_log.Error("[REST]: Query parameter " + name + " is already added.");
            }
            catch (Exception e)
            {
                m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
            }
        }

        /// <summary>
        /// Web-Request method, e.g. GET, PUT, POST, DELETE
        /// </summary>
        public string RequestMethod
        {
            get { return _method; }
            set { _method = value; }
        }

        /// <summary>
        /// True if string contains a trailing slash '/'
        /// </summary>
        /// <param name="s">string to be examined</param>
        /// <returns>true if slash is present</returns>
        private static bool isSlashed(string s)
        {
            return s.Substring(s.Length - 1, 1) == "/";
        }

        /// <summary>
        /// Build a Uri based on the initial Url, path elements and parameters
        /// </summary>
        /// <returns>fully constructed Uri</returns>
        private Uri buildUri()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(_url);

            foreach (string e in _pathElements)
            {
                sb.Append("/");
                sb.Append(e);
            }

            bool firstElement = true;
            foreach (KeyValuePair<string, string> kv in _parameterElements)
            {
                if (firstElement)
                {
                    sb.Append("?");
                    firstElement = false;
                }
                else
                    sb.Append("&");

                sb.Append(kv.Key);
                if (!string.IsNullOrEmpty(kv.Value))
                {
                    sb.Append("=");
                    sb.Append(kv.Value);
                }
            }
            // realuri = sb.ToString();
            //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
            return new Uri(sb.ToString());
        }

        #region Async communications with server

        /// <summary>
        /// Async method, invoked when a block of data has been received from the service
        /// </summary>
        /// <param name="ar"></param>
        private void StreamIsReadyDelegate(IAsyncResult ar)
        {
            try
            {
                Stream s = (Stream) ar.AsyncState;
                int read = s.EndRead(ar);

                if (read > 0)
                {
                    _resource.Write(_readbuf, 0, read);
                    // IAsyncResult asynchronousResult =
                    //     s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
                    s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);

                    // TODO! Implement timeout, without killing the server
                    //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
                }
                else
                {
                    s.Close();
                    //_allDone.Set();
                }
            }
            catch (Exception e)
            {
                //_allDone.Set();
                _asyncException = e;
            }
        }

        #endregion Async communications with server

        /// <summary>
        /// Perform a synchronous request
        /// </summary>
        public Stream Request()
        {
            return Request(null);
        }

        /// <summary>
        /// Perform a synchronous request
        /// </summary>
        public Stream Request(IServiceAuth auth)
        {
            lock (_lock)
            {
                _request = (HttpWebRequest) WebRequest.Create(buildUri());
                _request.KeepAlive = false;
                _request.ContentType = "application/xml";
                _request.Timeout = 200000;
                _request.Method = RequestMethod;
                _asyncException = null;
                if (auth != null)
                    auth.AddAuthorization(_request.Headers);

                int reqnum = WebUtil.RequestNumber++;
                if (WebUtil.DebugLevel >= 3)
                    m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);

//                IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);

                try
                {
                    using (_response = (HttpWebResponse) _request.GetResponse())
                    {
                        using (Stream src = _response.GetResponseStream())
                        {
                            int length = src.Read(_readbuf, 0, BufferSize);
                            while (length > 0)
                            {
                                _resource.Write(_readbuf, 0, length);
                                length = src.Read(_readbuf, 0, BufferSize);
                            }

                            // TODO! Implement timeout, without killing the server
                            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
                            //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);

                            //                _allDone.WaitOne();
                        }
                    }
                }
                catch (WebException e)
                {
                    using (HttpWebResponse errorResponse = e.Response as HttpWebResponse)
                    {
                        if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
                        {
                            // This is often benign. E.g., requesting a missing asset will return 404.
                            m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
                        }
                        else
                        {
                            m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
                        }
                    }
                    return null;
                }


                if (_asyncException != null)
                    throw _asyncException;

                if (_resource != null)
                {
                    _resource.Flush();
                    _resource.Seek(0, SeekOrigin.Begin);
                }

                if (WebUtil.DebugLevel >= 5)
                    WebUtil.LogResponseDetail(reqnum, _resource);

                return _resource;
            }
        }

        public Stream Request(Stream src, IServiceAuth auth)
        {
            _request = (HttpWebRequest) WebRequest.Create(buildUri());
            _request.KeepAlive = false;
            _request.ContentType = "application/xml";
            _request.Timeout = 90000;
            _request.Method = RequestMethod;
            _asyncException = null;
            _request.ContentLength = src.Length;
            if (auth != null)
                auth.AddAuthorization(_request.Headers);

            src.Seek(0, SeekOrigin.Begin);

            int reqnum = WebUtil.RequestNumber++;
            if (WebUtil.DebugLevel >= 3)
                m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
            if (WebUtil.DebugLevel >= 5)
                WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);

            
            try
            {
                using (Stream dst = _request.GetRequestStream())
                {
//                    m_log.Debug("[REST]: GetRequestStream is ok");

                    byte[] buf = new byte[1024];
                    int length = src.Read(buf, 0, 1024);
//                    m_log.Debug("[REST]: First Read is ok");
                    while (length > 0)
                    {
                        dst.Write(buf, 0, length);
                        length = src.Read(buf, 0, 1024);
                    }
                }

                _response = (HttpWebResponse)_request.GetResponse();
            }
            catch (WebException e)
            {
                m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}",
                                  RequestMethod, _request.RequestUri, e.Status, e.Message);
                return null;
            }
            catch (Exception e)
            {
                m_log.WarnFormat(
                    "[REST]: Request {0} {1} failed with exception {2} {3}",
                    RequestMethod, _request.RequestUri, e.Message, e.StackTrace);
                return null;
            }

            if (WebUtil.DebugLevel >= 5)
            {
                using (Stream responseStream = _response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        string responseStr = reader.ReadToEnd();
                        WebUtil.LogResponseDetail(reqnum, responseStr);
                    }
                }
            }

            if (_response != null)
                _response.Close();

//            IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);

            // TODO! Implement timeout, without killing the server
            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
            //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);

            return null;
        }

        #region Async Invocation

        public IAsyncResult BeginRequest(AsyncCallback callback, object state)
        {
            /// <summary>
            /// In case, we are invoked asynchroneously this object will keep track of the state
            /// </summary>
            AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
            Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest");
            return ar;
        }

        public Stream EndRequest(IAsyncResult asyncResult)
        {
            AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;

            // Wait for operation to complete, then return result or
            // throw exception
            return ar.EndInvoke();
        }

        private void RequestHelper(Object asyncResult)
        {
            // We know that it's really an AsyncResult<DateTime> object
            AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
            try
            {
                // Perform the operation; if sucessful set the result
                Stream s = Request(null);
                ar.SetAsCompleted(s, false);
            }
            catch (Exception e)
            {
                // If operation fails, set the exception
                ar.HandleException(e, false);
            }
        }

        #endregion Async Invocation
    }

    internal class SimpleAsyncResult : IAsyncResult
    {
        private readonly AsyncCallback m_callback;

        /// <summary>
        /// Is process completed?
        /// </summary>
        /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
        private byte m_completed;

        /// <summary>
        /// Did process complete synchronously?
        /// </summary>
        /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
        /// booleans and VolatileRead as m_completed
        /// </remarks>
        private byte m_completedSynchronously;

        private readonly object m_asyncState;
        private ManualResetEvent m_waitHandle;
        private Exception m_exception;

        internal SimpleAsyncResult(AsyncCallback cb, object state)
        {
            m_callback = cb;
            m_asyncState = state;
            m_completed = 0;
            m_completedSynchronously = 1;
        }

        #region IAsyncResult Members

        public object AsyncState
        {
            get { return m_asyncState; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                if (m_waitHandle == null)
                {
                    bool done = IsCompleted;
                    ManualResetEvent mre = new ManualResetEvent(done);
                    if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
                    {
                        mre.Close();
                    }
                    else
                    {
                        if (!done && IsCompleted)
                        {
                            m_waitHandle.Set();
                        }
                    }
                }

                return m_waitHandle;
            }
        }


        public bool CompletedSynchronously
        {
            get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
        }


        public bool IsCompleted
        {
            get { return Thread.VolatileRead(ref m_completed) == 1; }
        }

        #endregion

        #region class Methods

        internal void SetAsCompleted(bool completedSynchronously)
        {
            m_completed = 1;
            if (completedSynchronously)
                m_completedSynchronously = 1;
            else
                m_completedSynchronously = 0;

            SignalCompletion();
        }

        internal void HandleException(Exception e, bool completedSynchronously)
        {
            m_completed = 1;
            if (completedSynchronously)
                m_completedSynchronously = 1;
            else
                m_completedSynchronously = 0;
            m_exception = e;

            SignalCompletion();
        }

        private void SignalCompletion()
        {
            if (m_waitHandle != null) m_waitHandle.Set();

            if (m_callback != null) m_callback(this);
        }

        public void EndInvoke()
        {
            // This method assumes that only 1 thread calls EndInvoke
            if (!IsCompleted)
            {
                // If the operation isn't done, wait for it
                AsyncWaitHandle.WaitOne();
                AsyncWaitHandle.Close();
                m_waitHandle.Close();
                m_waitHandle = null; // Allow early GC
            }

            // Operation is done: if an exception occured, throw it
            if (m_exception != null) throw m_exception;
        }

        #endregion
    }

    internal class AsyncResult<T> : SimpleAsyncResult
    {
        private T m_result = default(T);

        public AsyncResult(AsyncCallback asyncCallback, Object state) :
            base(asyncCallback, state)
        {
        }

        public void SetAsCompleted(T result, bool completedSynchronously)
        {
            // Save the asynchronous operation's result
            m_result = result;

            // Tell the base class that the operation completed
            // sucessfully (no exception)
            base.SetAsCompleted(completedSynchronously);
        }

        public new T EndInvoke()
        {
            base.EndInvoke();
            return m_result;
        }
    }

}