RestClient.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Threading.Tasks;
  35. using System.Web;
  36. using log4net;
  37. using OpenSim.Framework.ServiceAuth;
  38. namespace OpenSim.Framework
  39. {
  40. /// <summary>
  41. /// Implementation of a generic REST client
  42. /// </summary>
  43. /// <remarks>
  44. /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
  45. /// class is designed to execute both synchronously and asynchronously.
  46. ///
  47. /// Internally the implementation works as a two stage asynchronous web-client.
  48. /// When the request is initiated, RestClient will query asynchronously for for a web-response,
  49. /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
  50. /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
  51. /// object into a memorystream as a sequence of asynchronous reads.
  52. ///
  53. /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
  54. /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
  55. /// invoked by the caller in either synchronous mode or asynchronous modes.
  56. /// </remarks>
  57. public class RestClient : IDisposable
  58. {
  59. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  60. // private string realuri;
  61. #region member variables
  62. /// <summary>
  63. /// The base Uri of the web-service e.g. http://www.google.com
  64. /// </summary>
  65. private string _url;
  66. /// <summary>
  67. /// Path elements of the query
  68. /// </summary>
  69. private List<string> _pathElements = new List<string>();
  70. /// <summary>
  71. /// Parameter elements of the query, e.g. min=34
  72. /// </summary>
  73. private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
  74. /// <summary>
  75. /// Request method. E.g. GET, POST, PUT or DELETE
  76. /// </summary>
  77. private string _method;
  78. /// <summary>
  79. /// Temporary buffer used to store bytes temporarily as they come in from the server
  80. /// </summary>
  81. private byte[] _readbuf;
  82. /// <summary>
  83. /// MemoryStream representing the resulting resource
  84. /// </summary>
  85. private Stream _resource;
  86. /// <summary>
  87. /// WebRequest object, held as a member variable
  88. /// </summary>
  89. private HttpWebRequest _request;
  90. /// <summary>
  91. /// WebResponse object, held as a member variable, so we can close it
  92. /// </summary>
  93. private HttpWebResponse _response;
  94. /// <summary>
  95. /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
  96. /// </summary>
  97. //public static ManualResetEvent _allDone = new ManualResetEvent(false);
  98. /// <summary>
  99. /// Default time out period
  100. /// </summary>
  101. //private const int DefaultTimeout = 10*1000; // 10 seconds timeout
  102. /// <summary>
  103. /// Default Buffer size of a block requested from the web-server
  104. /// </summary>
  105. private const int BufferSize = 4 * 4096; // Read blocks of 4 * 4 KB.
  106. /// <summary>
  107. /// if an exception occours during async processing, we need to save it, so it can be
  108. /// rethrown on the primary thread;
  109. /// </summary>
  110. private Exception _asyncException;
  111. #endregion member variables
  112. #region constructors
  113. /// <summary>
  114. /// Instantiate a new RestClient
  115. /// </summary>
  116. /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
  117. public RestClient(string url)
  118. {
  119. _url = url;
  120. _readbuf = new byte[BufferSize];
  121. _resource = new MemoryStream();
  122. _request = null;
  123. _response = null;
  124. _lock = new object();
  125. }
  126. private object _lock;
  127. #endregion constructors
  128. #region Dispose
  129. private bool disposed = false;
  130. public void Dispose()
  131. {
  132. Dispose(true);
  133. GC.SuppressFinalize(this);
  134. }
  135. protected virtual void Dispose(bool disposing)
  136. {
  137. if (disposed)
  138. return;
  139. if (disposing)
  140. {
  141. _resource.Dispose();
  142. }
  143. disposed = true;
  144. }
  145. #endregion Dispose
  146. /// <summary>
  147. /// Add a path element to the query, e.g. assets
  148. /// </summary>
  149. /// <param name="element">path entry</param>
  150. public void AddResourcePath(string element)
  151. {
  152. _pathElements.Add(Util.TrimEndSlash(element));
  153. }
  154. /// <summary>
  155. /// Add a query parameter to the Url
  156. /// </summary>
  157. /// <param name="name">Name of the parameter, e.g. min</param>
  158. /// <param name="value">Value of the parameter, e.g. 42</param>
  159. public void AddQueryParameter(string name, string value)
  160. {
  161. try
  162. {
  163. _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
  164. }
  165. catch (ArgumentException)
  166. {
  167. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  168. }
  169. catch (Exception e)
  170. {
  171. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  172. }
  173. }
  174. /// <summary>
  175. /// Add a query parameter to the Url
  176. /// </summary>
  177. /// <param name="name">Name of the parameter, e.g. min</param>
  178. public void AddQueryParameter(string name)
  179. {
  180. try
  181. {
  182. _parameterElements.Add(HttpUtility.UrlEncode(name), null);
  183. }
  184. catch (ArgumentException)
  185. {
  186. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  187. }
  188. catch (Exception e)
  189. {
  190. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  191. }
  192. }
  193. /// <summary>
  194. /// Web-Request method, e.g. GET, PUT, POST, DELETE
  195. /// </summary>
  196. public string RequestMethod
  197. {
  198. get { return _method; }
  199. set { _method = value; }
  200. }
  201. /// <summary>
  202. /// Build a Uri based on the initial Url, path elements and parameters
  203. /// </summary>
  204. /// <returns>fully constructed Uri</returns>
  205. private Uri buildUri()
  206. {
  207. StringBuilder sb = new StringBuilder();
  208. sb.Append(_url);
  209. foreach (string e in _pathElements)
  210. {
  211. sb.Append("/");
  212. sb.Append(e);
  213. }
  214. bool firstElement = true;
  215. foreach (KeyValuePair<string, string> kv in _parameterElements)
  216. {
  217. if (firstElement)
  218. {
  219. sb.Append("?");
  220. firstElement = false;
  221. }
  222. else
  223. sb.Append("&");
  224. sb.Append(kv.Key);
  225. if (!string.IsNullOrEmpty(kv.Value))
  226. {
  227. sb.Append("=");
  228. sb.Append(kv.Value);
  229. }
  230. }
  231. // realuri = sb.ToString();
  232. //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
  233. return new Uri(sb.ToString());
  234. }
  235. #region Async communications with server
  236. /// <summary>
  237. /// Async method, invoked when a block of data has been received from the service
  238. /// </summary>
  239. /// <param name="ar"></param>
  240. private void StreamIsReadyDelegate(IAsyncResult ar)
  241. {
  242. try
  243. {
  244. Stream s = (Stream) ar.AsyncState;
  245. int read = s.EndRead(ar);
  246. if (read > 0)
  247. {
  248. _resource.Write(_readbuf, 0, read);
  249. // IAsyncResult asynchronousResult =
  250. // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
  251. s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
  252. // TODO! Implement timeout, without killing the server
  253. //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
  254. }
  255. else
  256. {
  257. s.Close();
  258. //_allDone.Set();
  259. }
  260. }
  261. catch (Exception e)
  262. {
  263. //_allDone.Set();
  264. _asyncException = e;
  265. }
  266. }
  267. #endregion Async communications with server
  268. /// <summary>
  269. /// Perform a synchronous request
  270. /// </summary>
  271. public Stream Request()
  272. {
  273. return Request(null);
  274. }
  275. /// <summary>
  276. /// Perform a synchronous request
  277. /// </summary>
  278. public Stream Request(IServiceAuth auth)
  279. {
  280. lock (_lock)
  281. {
  282. _request = (HttpWebRequest) WebRequest.Create(buildUri());
  283. _request.ContentType = "application/xml";
  284. _request.Timeout = 90000;
  285. _request.Method = RequestMethod;
  286. _asyncException = null;
  287. if (auth != null)
  288. auth.AddAuthorization(_request.Headers);
  289. int reqnum = WebUtil.RequestNumber++;
  290. if (WebUtil.DebugLevel >= 3)
  291. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
  292. try
  293. {
  294. using (_response = (HttpWebResponse) _request.GetResponse())
  295. {
  296. using (Stream src = _response.GetResponseStream())
  297. {
  298. int length = src.Read(_readbuf, 0, BufferSize);
  299. while (length > 0)
  300. {
  301. _resource.Write(_readbuf, 0, length);
  302. length = src.Read(_readbuf, 0, BufferSize);
  303. }
  304. }
  305. }
  306. }
  307. catch (WebException e)
  308. {
  309. using (HttpWebResponse errorResponse = e.Response as HttpWebResponse)
  310. {
  311. if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
  312. {
  313. // This is often benign. E.g., requesting a missing asset will return 404.
  314. m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
  315. }
  316. else
  317. {
  318. m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
  319. }
  320. }
  321. return null;
  322. }
  323. if (_asyncException != null)
  324. throw _asyncException;
  325. if (_resource != null)
  326. {
  327. _resource.Flush();
  328. _resource.Seek(0, SeekOrigin.Begin);
  329. }
  330. if (WebUtil.DebugLevel >= 5)
  331. WebUtil.LogResponseDetail(reqnum, _resource);
  332. return _resource;
  333. }
  334. }
  335. // just post data, ignoring result
  336. public async Task AsyncPOSTRequest(byte[] src, IServiceAuth auth)
  337. {
  338. _request = (HttpWebRequest)WebRequest.Create(buildUri());
  339. _request.ContentType = "application/xml";
  340. _request.Timeout = 90000;
  341. _request.Method = "POST";
  342. _asyncException = null;
  343. _request.ContentLength = src.Length;
  344. if (auth != null)
  345. auth.AddAuthorization(_request.Headers);
  346. int reqnum = WebUtil.RequestNumber++;
  347. try
  348. {
  349. using (Stream dst = _request.GetRequestStream())
  350. {
  351. await dst.WriteAsync(src, 0, src.Length).ConfigureAwait(false);
  352. }
  353. using(HttpWebResponse response = (HttpWebResponse)await _request.GetResponseAsync().ConfigureAwait(false))
  354. {
  355. if (WebUtil.DebugLevel >= 5)
  356. {
  357. using (Stream responseStream = response.GetResponseStream())
  358. {
  359. using (StreamReader reader = new StreamReader(responseStream))
  360. {
  361. string responseStr = await reader.ReadToEndAsync().ConfigureAwait(false);
  362. WebUtil.LogResponseDetail(reqnum, responseStr);
  363. }
  364. }
  365. }
  366. }
  367. }
  368. catch (WebException e)
  369. {
  370. m_log.WarnFormat("[REST]: AsyncPOST {0} failed with status {1} and message {2}",
  371. _request.RequestUri, e.Status, e.Message);
  372. return;
  373. }
  374. catch (Exception e)
  375. {
  376. m_log.WarnFormat("[REST]: AsyncPOST {0} failed with exception {1} {2}",
  377. _request.RequestUri, e.Message, e.StackTrace);
  378. return;
  379. }
  380. }
  381. #region Async Invocation
  382. public IAsyncResult BeginRequest(AsyncCallback callback, object state)
  383. {
  384. /// <summary>
  385. /// In case, we are invoked asynchroneously this object will keep track of the state
  386. /// </summary>
  387. AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
  388. Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest");
  389. return ar;
  390. }
  391. public Stream EndRequest(IAsyncResult asyncResult)
  392. {
  393. AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
  394. // Wait for operation to complete, then return result or
  395. // throw exception
  396. return ar.EndInvoke();
  397. }
  398. private void RequestHelper(Object asyncResult)
  399. {
  400. // We know that it's really an AsyncResult<DateTime> object
  401. AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
  402. try
  403. {
  404. // Perform the operation; if sucessful set the result
  405. Stream s = Request(null);
  406. ar.SetAsCompleted(s, false);
  407. }
  408. catch (Exception e)
  409. {
  410. // If operation fails, set the exception
  411. ar.HandleException(e, false);
  412. }
  413. }
  414. #endregion Async Invocation
  415. }
  416. internal class SimpleAsyncResult : IAsyncResult
  417. {
  418. private readonly AsyncCallback m_callback;
  419. /// <summary>
  420. /// Is process completed?
  421. /// </summary>
  422. /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
  423. private byte m_completed;
  424. /// <summary>
  425. /// Did process complete synchronously?
  426. /// </summary>
  427. /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
  428. /// booleans and VolatileRead as m_completed
  429. /// </remarks>
  430. private byte m_completedSynchronously;
  431. private readonly object m_asyncState;
  432. private ManualResetEvent m_waitHandle;
  433. private Exception m_exception;
  434. internal SimpleAsyncResult(AsyncCallback cb, object state)
  435. {
  436. m_callback = cb;
  437. m_asyncState = state;
  438. m_completed = 0;
  439. m_completedSynchronously = 1;
  440. }
  441. #region IAsyncResult Members
  442. public object AsyncState
  443. {
  444. get { return m_asyncState; }
  445. }
  446. public WaitHandle AsyncWaitHandle
  447. {
  448. get
  449. {
  450. if (m_waitHandle == null)
  451. {
  452. bool done = IsCompleted;
  453. ManualResetEvent mre = new ManualResetEvent(done);
  454. if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
  455. {
  456. mre.Close();
  457. }
  458. else
  459. {
  460. if (!done && IsCompleted)
  461. {
  462. m_waitHandle.Set();
  463. }
  464. }
  465. }
  466. return m_waitHandle;
  467. }
  468. }
  469. public bool CompletedSynchronously
  470. {
  471. get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
  472. }
  473. public bool IsCompleted
  474. {
  475. get { return Thread.VolatileRead(ref m_completed) == 1; }
  476. }
  477. #endregion
  478. #region class Methods
  479. internal void SetAsCompleted(bool completedSynchronously)
  480. {
  481. m_completed = 1;
  482. if (completedSynchronously)
  483. m_completedSynchronously = 1;
  484. else
  485. m_completedSynchronously = 0;
  486. SignalCompletion();
  487. }
  488. internal void HandleException(Exception e, bool completedSynchronously)
  489. {
  490. m_completed = 1;
  491. if (completedSynchronously)
  492. m_completedSynchronously = 1;
  493. else
  494. m_completedSynchronously = 0;
  495. m_exception = e;
  496. SignalCompletion();
  497. }
  498. private void SignalCompletion()
  499. {
  500. if (m_waitHandle != null) m_waitHandle.Set();
  501. if (m_callback != null) m_callback(this);
  502. }
  503. public void EndInvoke()
  504. {
  505. // This method assumes that only 1 thread calls EndInvoke
  506. if (!IsCompleted)
  507. {
  508. // If the operation isn't done, wait for it
  509. AsyncWaitHandle.WaitOne();
  510. AsyncWaitHandle.Close();
  511. m_waitHandle.Close();
  512. m_waitHandle = null; // Allow early GC
  513. }
  514. // Operation is done: if an exception occured, throw it
  515. if (m_exception != null) throw m_exception;
  516. }
  517. #endregion
  518. }
  519. internal class AsyncResult<T> : SimpleAsyncResult
  520. {
  521. private T m_result = default(T);
  522. public AsyncResult(AsyncCallback asyncCallback, Object state) :
  523. base(asyncCallback, state)
  524. {
  525. }
  526. public void SetAsCompleted(T result, bool completedSynchronously)
  527. {
  528. // Save the asynchronous operation's result
  529. m_result = result;
  530. // Tell the base class that the operation completed
  531. // sucessfully (no exception)
  532. base.SetAsCompleted(completedSynchronously);
  533. }
  534. public new T EndInvoke()
  535. {
  536. base.EndInvoke();
  537. return m_result;
  538. }
  539. }
  540. }