1
0

RestClient.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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.Web;
  35. using log4net;
  36. using OpenSim.Framework.ServiceAuth;
  37. namespace OpenSim.Framework
  38. {
  39. /// <summary>
  40. /// Implementation of a generic REST client
  41. /// </summary>
  42. /// <remarks>
  43. /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
  44. /// class is designed to execute both synchronously and asynchronously.
  45. ///
  46. /// Internally the implementation works as a two stage asynchronous web-client.
  47. /// When the request is initiated, RestClient will query asynchronously for for a web-response,
  48. /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
  49. /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
  50. /// object into a memorystream as a sequence of asynchronous reads.
  51. ///
  52. /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
  53. /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
  54. /// invoked by the caller in either synchronous mode or asynchronous modes.
  55. /// </remarks>
  56. public class RestClient : IDisposable
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. // private string realuri;
  60. #region member variables
  61. /// <summary>
  62. /// The base Uri of the web-service e.g. http://www.google.com
  63. /// </summary>
  64. private string _url;
  65. /// <summary>
  66. /// Path elements of the query
  67. /// </summary>
  68. private List<string> _pathElements = new List<string>();
  69. /// <summary>
  70. /// Parameter elements of the query, e.g. min=34
  71. /// </summary>
  72. private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
  73. /// <summary>
  74. /// Request method. E.g. GET, POST, PUT or DELETE
  75. /// </summary>
  76. private string _method;
  77. /// <summary>
  78. /// Temporary buffer used to store bytes temporarily as they come in from the server
  79. /// </summary>
  80. private byte[] _readbuf;
  81. /// <summary>
  82. /// MemoryStream representing the resulting resource
  83. /// </summary>
  84. private MemoryStream _resource;
  85. /// <summary>
  86. /// WebRequest object, held as a member variable
  87. /// </summary>
  88. private HttpWebRequest _request;
  89. /// <summary>
  90. /// WebResponse object, held as a member variable, so we can close it
  91. /// </summary>
  92. private HttpWebResponse _response;
  93. /// <summary>
  94. /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
  95. /// </summary>
  96. //public static ManualResetEvent _allDone = new ManualResetEvent(false);
  97. /// <summary>
  98. /// Default time out period
  99. /// </summary>
  100. //private const int DefaultTimeout = 10*1000; // 10 seconds timeout
  101. /// <summary>
  102. /// Default Buffer size of a block requested from the web-server
  103. /// </summary>
  104. private const int BufferSize = 4 * 4096; // Read blocks of 4 * 4 KB.
  105. /// <summary>
  106. /// if an exception occours during async processing, we need to save it, so it can be
  107. /// rethrown on the primary thread;
  108. /// </summary>
  109. private Exception _asyncException;
  110. #endregion member variables
  111. #region constructors
  112. /// <summary>
  113. /// Instantiate a new RestClient
  114. /// </summary>
  115. /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
  116. public RestClient(string url)
  117. {
  118. _url = url;
  119. _readbuf = new byte[BufferSize];
  120. _resource = new MemoryStream();
  121. _request = null;
  122. _response = null;
  123. _lock = new object();
  124. }
  125. private object _lock;
  126. #endregion constructors
  127. #region Dispose
  128. private bool disposed = false;
  129. public void Dispose()
  130. {
  131. Dispose(true);
  132. GC.SuppressFinalize(this);
  133. }
  134. protected virtual void Dispose(bool disposing)
  135. {
  136. if (disposed)
  137. return;
  138. if (disposing)
  139. {
  140. _resource.Dispose();
  141. }
  142. disposed = true;
  143. }
  144. #endregion Dispose
  145. /// <summary>
  146. /// Add a path element to the query, e.g. assets
  147. /// </summary>
  148. /// <param name="element">path entry</param>
  149. public void AddResourcePath(string element)
  150. {
  151. _pathElements.Add(Util.TrimEndSlash(element));
  152. }
  153. /// <summary>
  154. /// Add a query parameter to the Url
  155. /// </summary>
  156. /// <param name="name">Name of the parameter, e.g. min</param>
  157. /// <param name="value">Value of the parameter, e.g. 42</param>
  158. public void AddQueryParameter(string name, string value)
  159. {
  160. try
  161. {
  162. _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
  163. }
  164. catch (ArgumentException)
  165. {
  166. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  167. }
  168. catch (Exception e)
  169. {
  170. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  171. }
  172. }
  173. /// <summary>
  174. /// Add a query parameter to the Url
  175. /// </summary>
  176. /// <param name="name">Name of the parameter, e.g. min</param>
  177. public void AddQueryParameter(string name)
  178. {
  179. try
  180. {
  181. _parameterElements.Add(HttpUtility.UrlEncode(name), null);
  182. }
  183. catch (ArgumentException)
  184. {
  185. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  186. }
  187. catch (Exception e)
  188. {
  189. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  190. }
  191. }
  192. /// <summary>
  193. /// Web-Request method, e.g. GET, PUT, POST, DELETE
  194. /// </summary>
  195. public string RequestMethod
  196. {
  197. get { return _method; }
  198. set { _method = value; }
  199. }
  200. /// <summary>
  201. /// Build a Uri based on the initial Url, path elements and parameters
  202. /// </summary>
  203. /// <returns>fully constructed Uri</returns>
  204. private Uri buildUri()
  205. {
  206. StringBuilder sb = new StringBuilder();
  207. sb.Append(_url);
  208. foreach (string e in _pathElements)
  209. {
  210. sb.Append("/");
  211. sb.Append(e);
  212. }
  213. bool firstElement = true;
  214. foreach (KeyValuePair<string, string> kv in _parameterElements)
  215. {
  216. if (firstElement)
  217. {
  218. sb.Append("?");
  219. firstElement = false;
  220. }
  221. else
  222. sb.Append("&");
  223. sb.Append(kv.Key);
  224. if (!string.IsNullOrEmpty(kv.Value))
  225. {
  226. sb.Append("=");
  227. sb.Append(kv.Value);
  228. }
  229. }
  230. // realuri = sb.ToString();
  231. //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
  232. return new Uri(sb.ToString());
  233. }
  234. #region Async communications with server
  235. /// <summary>
  236. /// Async method, invoked when a block of data has been received from the service
  237. /// </summary>
  238. /// <param name="ar"></param>
  239. private void StreamIsReadyDelegate(IAsyncResult ar)
  240. {
  241. try
  242. {
  243. Stream s = (Stream) ar.AsyncState;
  244. int read = s.EndRead(ar);
  245. if (read > 0)
  246. {
  247. _resource.Write(_readbuf, 0, read);
  248. // IAsyncResult asynchronousResult =
  249. // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
  250. s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
  251. // TODO! Implement timeout, without killing the server
  252. //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
  253. }
  254. else
  255. {
  256. s.Close();
  257. //_allDone.Set();
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. //_allDone.Set();
  263. _asyncException = e;
  264. }
  265. }
  266. #endregion Async communications with server
  267. /// <summary>
  268. /// Perform a synchronous request
  269. /// </summary>
  270. public MemoryStream Request()
  271. {
  272. return Request(null);
  273. }
  274. /// <summary>
  275. /// Perform a synchronous request
  276. /// </summary>
  277. public MemoryStream Request(IServiceAuth auth)
  278. {
  279. lock (_lock)
  280. {
  281. try
  282. {
  283. _request = (HttpWebRequest) WebRequest.Create(buildUri());
  284. _request.ContentType = "application/xml";
  285. _request.Timeout = 90000;
  286. _request.Method = RequestMethod;
  287. _asyncException = null;
  288. if (auth != null)
  289. auth.AddAuthorization(_request.Headers);
  290. else
  291. _request.AllowWriteStreamBuffering = false;
  292. if (WebUtil.DebugLevel >= 3)
  293. m_log.DebugFormat("[REST CLIENT] {0} to {1}", _request.Method, _request.RequestUri);
  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.LogOutgoingDetail("[REST CLIENT]", _resource);
  332. return _resource;
  333. }
  334. }
  335. // just sync post data, ignoring result
  336. public void POSTRequest(byte[] src, IServiceAuth auth)
  337. {
  338. try
  339. {
  340. _request = (HttpWebRequest)WebRequest.Create(buildUri());
  341. _request.ContentType = "application/xml";
  342. _request.Timeout = 90000;
  343. _request.Method = "POST";
  344. _asyncException = null;
  345. _request.ContentLength = src.Length;
  346. if (auth != null)
  347. auth.AddAuthorization(_request.Headers);
  348. else
  349. _request.AllowWriteStreamBuffering = false;
  350. }
  351. catch (Exception e)
  352. {
  353. m_log.WarnFormat("[REST]: POST {0} failed with exception {1} {2}",
  354. _request.RequestUri, e.Message, e.StackTrace);
  355. return;
  356. }
  357. try
  358. {
  359. using (Stream dst = _request.GetRequestStream())
  360. {
  361. dst.Write(src, 0, src.Length);
  362. }
  363. using(HttpWebResponse response = (HttpWebResponse)_request.GetResponse())
  364. {
  365. using (Stream responseStream = response.GetResponseStream())
  366. {
  367. using (StreamReader reader = new StreamReader(responseStream))
  368. {
  369. string responseStr = reader.ReadToEnd();
  370. if (WebUtil.DebugLevel >= 5)
  371. {
  372. int reqnum = WebUtil.RequestNumber++;
  373. WebUtil.LogOutgoingDetail("REST POST", responseStr);
  374. }
  375. }
  376. }
  377. }
  378. }
  379. catch (WebException e)
  380. {
  381. m_log.WarnFormat("[REST]: POST {0} failed with status {1} and message {2}",
  382. _request.RequestUri, e.Status, e.Message);
  383. return;
  384. }
  385. catch (Exception e)
  386. {
  387. m_log.WarnFormat("[REST]: AsyncPOST {0} failed with exception {1} {2}",
  388. _request.RequestUri, e.Message, e.StackTrace);
  389. return;
  390. }
  391. }
  392. }
  393. internal class SimpleAsyncResult : IAsyncResult
  394. {
  395. private readonly AsyncCallback m_callback;
  396. /// <summary>
  397. /// Is process completed?
  398. /// </summary>
  399. /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
  400. private byte m_completed;
  401. /// <summary>
  402. /// Did process complete synchronously?
  403. /// </summary>
  404. /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
  405. /// booleans and VolatileRead as m_completed
  406. /// </remarks>
  407. private byte m_completedSynchronously;
  408. private readonly object m_asyncState;
  409. private ManualResetEvent m_waitHandle;
  410. private Exception m_exception;
  411. internal SimpleAsyncResult(AsyncCallback cb, object state)
  412. {
  413. m_callback = cb;
  414. m_asyncState = state;
  415. m_completed = 0;
  416. m_completedSynchronously = 1;
  417. }
  418. #region IAsyncResult Members
  419. public object AsyncState
  420. {
  421. get { return m_asyncState; }
  422. }
  423. public WaitHandle AsyncWaitHandle
  424. {
  425. get
  426. {
  427. if (m_waitHandle == null)
  428. {
  429. bool done = IsCompleted;
  430. ManualResetEvent mre = new ManualResetEvent(done);
  431. if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
  432. {
  433. mre.Close();
  434. }
  435. else
  436. {
  437. if (!done && IsCompleted)
  438. {
  439. m_waitHandle.Set();
  440. }
  441. }
  442. }
  443. return m_waitHandle;
  444. }
  445. }
  446. public bool CompletedSynchronously
  447. {
  448. get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
  449. }
  450. public bool IsCompleted
  451. {
  452. get { return Thread.VolatileRead(ref m_completed) == 1; }
  453. }
  454. #endregion
  455. #region class Methods
  456. internal void SetAsCompleted(bool completedSynchronously)
  457. {
  458. m_completed = 1;
  459. if (completedSynchronously)
  460. m_completedSynchronously = 1;
  461. else
  462. m_completedSynchronously = 0;
  463. SignalCompletion();
  464. }
  465. internal void HandleException(Exception e, bool completedSynchronously)
  466. {
  467. m_completed = 1;
  468. if (completedSynchronously)
  469. m_completedSynchronously = 1;
  470. else
  471. m_completedSynchronously = 0;
  472. m_exception = e;
  473. SignalCompletion();
  474. }
  475. private void SignalCompletion()
  476. {
  477. if (m_waitHandle != null) m_waitHandle.Set();
  478. if (m_callback != null) m_callback(this);
  479. }
  480. public void EndInvoke()
  481. {
  482. // This method assumes that only 1 thread calls EndInvoke
  483. if (!IsCompleted)
  484. {
  485. // If the operation isn't done, wait for it
  486. AsyncWaitHandle.WaitOne();
  487. AsyncWaitHandle.Close();
  488. m_waitHandle.Close();
  489. m_waitHandle = null; // Allow early GC
  490. }
  491. // Operation is done: if an exception occured, throw it
  492. if (m_exception != null) throw m_exception;
  493. }
  494. #endregion
  495. }
  496. internal class AsyncResult<T> : SimpleAsyncResult
  497. {
  498. private T m_result = default(T);
  499. public AsyncResult(AsyncCallback asyncCallback, Object state) :
  500. base(asyncCallback, state)
  501. {
  502. }
  503. public void SetAsCompleted(T result, bool completedSynchronously)
  504. {
  505. // Save the asynchronous operation's result
  506. m_result = result;
  507. // Tell the base class that the operation completed
  508. // sucessfully (no exception)
  509. base.SetAsCompleted(completedSynchronously);
  510. }
  511. public new T EndInvoke()
  512. {
  513. base.EndInvoke();
  514. return m_result;
  515. }
  516. }
  517. }