2 /* -----------------------------------------------------------------------
3 * <copyright file="RestClient.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
42 using System.Collections.Specialized;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
47 using System.Reflection;
48 using System.Runtime.Serialization;
49 using System.Threading.Tasks;
53 namespace Pithos.Network
56 using System.Collections.Generic;
61 /// TODO: Update summary.
63 public class RestClient:WebClient
65 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
67 public int Timeout { get; set; }
69 public bool TimedOut { get; set; }
71 public HttpStatusCode StatusCode { get; private set; }
73 public string StatusDescription { get; set; }
75 public long? RangeFrom { get; set; }
76 public long? RangeTo { get; set; }
78 public int Retries { get; set; }
80 private readonly Dictionary<string, string> _parameters=new Dictionary<string, string>();
81 public Dictionary<string, string> Parameters
85 Contract.Ensures(_parameters!=null);
91 [ContractInvariantMethod]
92 private void Invariants()
94 Contract.Invariant(Headers!=null);
97 public RestClient():base()
103 public RestClient(RestClient other)
107 throw new ArgumentNullException("other");
108 Contract.EndContractBlock();
111 Timeout = other.Timeout;
112 Retries = other.Retries;
113 BaseAddress = other.BaseAddress;
115 foreach (var parameter in other.Parameters)
117 Parameters.Add(parameter.Key,parameter.Value);
120 this.Proxy = other.Proxy;
124 protected override WebRequest GetWebRequest(Uri address)
127 var webRequest = base.GetWebRequest(address);
128 var request = (HttpWebRequest)webRequest;
129 request.ServicePoint.ConnectionLimit = 50;
130 if (IfModifiedSince.HasValue)
131 request.IfModifiedSince = IfModifiedSince.Value;
132 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
134 request.Timeout = Timeout;
136 if (RangeFrom.HasValue)
138 if (RangeTo.HasValue)
139 request.AddRange(RangeFrom.Value, RangeTo.Value);
141 request.AddRange(RangeFrom.Value);
146 public DateTime? IfModifiedSince { get; set; }
148 //Asynchronous version
149 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
151 Log.InfoFormat("ASYNC [{0}] {1}",request.Method, request.RequestUri);
152 HttpWebResponse response = null;
156 response = (HttpWebResponse)base.GetWebResponse(request, result);
158 catch (WebException exc)
160 if (!TryGetResponse(exc, out response))
164 StatusCode = response.StatusCode;
165 LastModified = response.LastModified;
166 StatusDescription = response.StatusDescription;
172 //Synchronous version
173 protected override WebResponse GetWebResponse(WebRequest request)
175 HttpWebResponse response = null;
178 response = (HttpWebResponse)base.GetWebResponse(request);
180 catch (WebException exc)
182 if (!TryGetResponse(exc, out response))
186 StatusCode = response.StatusCode;
187 LastModified = response.LastModified;
188 StatusDescription = response.StatusDescription;
192 private bool TryGetResponse(WebException exc, out HttpWebResponse response)
195 //Fail on empty response
196 if (exc.Response == null)
199 response = (exc.Response as HttpWebResponse);
200 //Succeed on allowed status codes
201 if (AllowedStatusCodes.Contains(response.StatusCode))
204 //Does the response have any content to log?
205 if (exc.Response.ContentLength > 0)
207 var content = LogContent(exc.Response);
208 Log.ErrorFormat(content);
213 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
215 public List<HttpStatusCode> AllowedStatusCodes
219 return _allowedStatusCodes;
223 public DateTime LastModified { get; private set; }
225 private static string LogContent(WebResponse webResponse)
227 if (webResponse == null)
228 throw new ArgumentNullException("webResponse");
229 Contract.EndContractBlock();
231 //The response stream must be copied to avoid affecting other code by disposing of the
232 //original response stream.
233 var stream = webResponse.GetResponseStream();
234 using(var memStream=new MemoryStream())
235 using (var reader = new StreamReader(memStream))
237 stream.CopyTo(memStream);
238 string content = reader.ReadToEnd();
240 stream.Seek(0,SeekOrigin.Begin);
245 public string DownloadStringWithRetry(string address,int retries=0)
249 throw new ArgumentNullException("address");
251 var actualAddress = GetActualAddress(address);
253 TraceStart("GET",actualAddress);
255 var actualRetries = (retries == 0) ? Retries : retries;
257 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
259 var task = Retry(() =>
261 var content = base.DownloadString(uriString);
263 if (StatusCode == HttpStatusCode.NoContent)
271 var result = task.Result;
275 catch (AggregateException exc)
277 //If the task fails, propagate the original exception
278 if (exc.InnerException!=null)
279 throw exc.InnerException;
284 public void Head(string address,int retries=0)
286 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
287 RetryWithoutContent(address, retries, "HEAD");
290 public void PutWithRetry(string address, int retries = 0)
292 RetryWithoutContent(address, retries, "PUT");
295 public void DeleteWithRetry(string address,int retries=0)
297 RetryWithoutContent(address, retries, "DELETE");
300 public string GetHeaderValue(string headerName,bool optional=false)
302 if (this.ResponseHeaders==null)
303 throw new InvalidOperationException("ResponseHeaders are null");
304 Contract.EndContractBlock();
306 var values=this.ResponseHeaders.GetValues(headerName);
312 //A required header was not found
313 throw new WebException(String.Format("The {0} header is missing", headerName));
316 public void SetNonEmptyHeaderValue(string headerName, string value)
318 if (String.IsNullOrWhiteSpace(value))
320 Headers.Add(headerName,value);
323 private void RetryWithoutContent(string address, int retries, string method)
326 throw new ArgumentNullException("address");
328 var actualAddress = GetActualAddress(address);
329 var actualRetries = (retries == 0) ? Retries : retries;
331 var task = Retry(() =>
333 var uriString = String.Join("/",BaseAddress ,actualAddress);
334 var uri = new Uri(uriString);
335 var request = GetWebRequest(uri);
336 request.Method = method;
337 if (ResponseHeaders!=null)
338 ResponseHeaders.Clear();
340 TraceStart(method, uriString);
342 request.ContentLength = 0;
344 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
345 //in order to return response headers
346 var response = (HttpWebResponse)GetWebResponse(request);
349 LastModified = response.LastModified;
350 StatusCode = response.StatusCode;
351 StatusDescription = response.StatusDescription;
366 catch (AggregateException ex)
368 var exc = ex.InnerException;
369 if (exc is RetryException)
371 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
375 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
382 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
387 private static void TraceStart(string method, string actualAddress)
389 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
392 private string GetActualAddress(string address)
394 if (Parameters.Count == 0)
396 var addressBuilder=new StringBuilder(address);
399 foreach (var parameter in Parameters)
402 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
404 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
407 return addressBuilder.ToString();
410 public string DownloadStringWithRetry(Uri address,int retries=0)
413 throw new ArgumentNullException("address");
415 var actualRetries = (retries == 0) ? Retries : retries;
416 var task = Retry(() =>
418 var content = base.DownloadString(address);
420 if (StatusCode == HttpStatusCode.NoContent)
426 var result = task.Result;
432 /// Copies headers from another RestClient
434 /// <param name="source">The RestClient from which the headers are copied</param>
435 public void CopyHeaders(RestClient source)
438 throw new ArgumentNullException("source", "source can't be null");
439 Contract.EndContractBlock();
440 //The Headers getter initializes the property, it is never null
441 Contract.Assume(Headers!=null);
443 CopyHeaders(source.Headers,Headers);
447 /// Copies headers from one header collection to another
449 /// <param name="source">The source collection from which the headers are copied</param>
450 /// <param name="target">The target collection to which the headers are copied</param>
451 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
454 throw new ArgumentNullException("source", "source can't be null");
456 throw new ArgumentNullException("target", "target can't be null");
457 Contract.EndContractBlock();
459 for (int i = 0; i < source.Count; i++)
461 target.Add(source.GetKey(i), source[i]);
465 public void AssertStatusOK(string message)
467 if (StatusCode >= HttpStatusCode.BadRequest)
468 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
472 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
475 throw new ArgumentNullException("original");
476 Contract.EndContractBlock();
479 tcs = new TaskCompletionSource<T>();
480 Task.Factory.StartNew(original).ContinueWith(_original =>
482 if (!_original.IsFaulted)
483 tcs.SetFromTask(_original);
486 var e = _original.Exception.InnerException;
487 var we = (e as WebException);
492 var statusCode = GetStatusCode(we);
494 //Return null for 404
495 if (statusCode == HttpStatusCode.NotFound)
496 tcs.SetResult(default(T));
497 //Retry for timeouts and service unavailable
498 else if (we.Status == WebExceptionStatus.Timeout ||
499 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
504 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
505 tcs.SetException(new RetryException("Timed out too many times.", e));
510 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
512 Retry(original, retryCount - 1, tcs);
523 private HttpStatusCode GetStatusCode(WebException we)
526 throw new ArgumentNullException("we");
527 var statusCode = HttpStatusCode.RequestTimeout;
528 if (we.Response != null)
530 statusCode = ((HttpWebResponse) we.Response).StatusCode;
531 this.StatusCode = statusCode;
536 public UriBuilder GetAddressBuilder(string container, string objectName)
538 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
542 public Dictionary<string, string> GetMeta(string metaPrefix)
544 if (String.IsNullOrWhiteSpace(metaPrefix))
545 throw new ArgumentNullException("metaPrefix");
546 Contract.EndContractBlock();
548 var keys = ResponseHeaders.AllKeys.AsQueryable();
549 var dict = (from key in keys
550 where key.StartsWith(metaPrefix)
551 let name = key.Substring(metaPrefix.Length)
552 select new { Name = name, Value = ResponseHeaders[key] })
553 .ToDictionary(t => t.Name, t => t.Value);
558 public class RetryException:Exception
560 public RetryException()
566 public RetryException(string message)
572 public RetryException(string message,Exception innerException)
573 :base(message,innerException)
578 public RetryException(SerializationInfo info,StreamingContext context)