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()
\r
99 HttpWebRequest.DefaultMaximumErrorResponseLength = 67108864;
\r
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("[{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, request,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 Log.InfoFormat("[{0}] {1}",request.Method,request.RequestUri);
179 response = (HttpWebResponse)base.GetWebResponse(request);
181 catch (WebException exc)
183 if (!TryGetResponse(exc, request,out response))
187 StatusCode = response.StatusCode;
188 LastModified = response.LastModified;
189 StatusDescription = response.StatusDescription;
193 private bool TryGetResponse(WebException exc, WebRequest request,out HttpWebResponse response)
196 //Fail on empty response
197 if (exc.Response == null)
199 Log.WarnFormat("[{0}] {1} {2}", request.Method, exc.Status, request.RequestUri);
203 response = (exc.Response as HttpWebResponse);
204 var statusCode = (int)response.StatusCode;
205 //Succeed on allowed status codes
206 if (AllowedStatusCodes.Contains(response.StatusCode))
208 if (Log.IsDebugEnabled)
209 Log.DebugFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
213 Log.WarnFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
215 //Does the response have any content to log?
216 if (exc.Response.ContentLength > 0)
218 var content = LogContent(exc.Response);
219 Log.ErrorFormat(content);
224 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
226 public List<HttpStatusCode> AllowedStatusCodes
230 return _allowedStatusCodes;
234 public DateTime LastModified { get; private set; }
236 private static string LogContent(WebResponse webResponse)
238 if (webResponse == null)
239 throw new ArgumentNullException("webResponse");
240 Contract.EndContractBlock();
242 //The response stream must be copied to avoid affecting other code by disposing of the
243 //original response stream.
244 var stream = webResponse.GetResponseStream();
245 using(var memStream=new MemoryStream())
246 using (var reader = new StreamReader(memStream))
248 stream.CopyTo(memStream);
249 string content = reader.ReadToEnd();
251 stream.Seek(0,SeekOrigin.Begin);
256 public string DownloadStringWithRetry(string address,int retries=0)
260 throw new ArgumentNullException("address");
262 var actualAddress = GetActualAddress(address);
264 TraceStart("GET",actualAddress);
266 var actualRetries = (retries == 0) ? Retries : retries;
268 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
270 var task = Retry(() =>
272 var content = base.DownloadString(uriString);
274 if (StatusCode == HttpStatusCode.NoContent)
282 var result = task.Result;
286 catch (AggregateException exc)
288 //If the task fails, propagate the original exception
289 if (exc.InnerException!=null)
290 throw exc.InnerException;
295 public void Head(string address,int retries=0)
297 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
298 RetryWithoutContent(address, retries, "HEAD");
301 public void PutWithRetry(string address, int retries = 0)
303 RetryWithoutContent(address, retries, "PUT");
306 public void DeleteWithRetry(string address,int retries=0)
308 RetryWithoutContent(address, retries, "DELETE");
311 public string GetHeaderValue(string headerName,bool optional=false)
313 if (this.ResponseHeaders==null)
314 throw new InvalidOperationException("ResponseHeaders are null");
315 Contract.EndContractBlock();
317 var values=this.ResponseHeaders.GetValues(headerName);
323 //A required header was not found
324 throw new WebException(String.Format("The {0} header is missing", headerName));
327 public void SetNonEmptyHeaderValue(string headerName, string value)
329 if (String.IsNullOrWhiteSpace(value))
331 Headers.Add(headerName,value);
334 private void RetryWithoutContent(string address, int retries, string method)
337 throw new ArgumentNullException("address");
339 var actualAddress = GetActualAddress(address);
340 var actualRetries = (retries == 0) ? Retries : retries;
342 var task = Retry(() =>
344 var uriString = String.Join("/",BaseAddress ,actualAddress);
345 var uri = new Uri(uriString);
346 var request = GetWebRequest(uri);
347 request.Method = method;
348 if (ResponseHeaders!=null)
349 ResponseHeaders.Clear();
351 TraceStart(method, uriString);
353 request.ContentLength = 0;
355 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
356 //in order to return response headers
357 var response = (HttpWebResponse)GetWebResponse(request);
360 LastModified = response.LastModified;
361 StatusCode = response.StatusCode;
362 StatusDescription = response.StatusDescription;
377 catch (AggregateException ex)
379 var exc = ex.InnerException;
380 if (exc is RetryException)
382 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
386 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
393 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
398 private static void TraceStart(string method, string actualAddress)
400 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
403 private string GetActualAddress(string address)
405 if (Parameters.Count == 0)
407 var addressBuilder=new StringBuilder(address);
410 foreach (var parameter in Parameters)
413 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
415 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
418 return addressBuilder.ToString();
421 public string DownloadStringWithRetry(Uri address,int retries=0)
424 throw new ArgumentNullException("address");
426 var actualRetries = (retries == 0) ? Retries : retries;
427 var task = Retry(() =>
429 var content = base.DownloadString(address);
431 if (StatusCode == HttpStatusCode.NoContent)
437 var result = task.Result;
443 /// Copies headers from another RestClient
445 /// <param name="source">The RestClient from which the headers are copied</param>
446 public void CopyHeaders(RestClient source)
449 throw new ArgumentNullException("source", "source can't be null");
450 Contract.EndContractBlock();
451 //The Headers getter initializes the property, it is never null
452 Contract.Assume(Headers!=null);
454 CopyHeaders(source.Headers,Headers);
458 /// Copies headers from one header collection to another
460 /// <param name="source">The source collection from which the headers are copied</param>
461 /// <param name="target">The target collection to which the headers are copied</param>
462 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
465 throw new ArgumentNullException("source", "source can't be null");
467 throw new ArgumentNullException("target", "target can't be null");
468 Contract.EndContractBlock();
470 for (int i = 0; i < source.Count; i++)
472 target.Add(source.GetKey(i), source[i]);
476 public void AssertStatusOK(string message)
478 if (StatusCode >= HttpStatusCode.BadRequest)
479 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
483 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
486 throw new ArgumentNullException("original");
487 Contract.EndContractBlock();
490 tcs = new TaskCompletionSource<T>();
491 Task.Factory.StartNew(original).ContinueWith(_original =>
493 if (!_original.IsFaulted)
494 tcs.SetFromTask(_original);
497 var e = _original.Exception.InnerException;
498 var we = (e as WebException);
503 var statusCode = GetStatusCode(we);
505 //Return null for 404
506 if (statusCode == HttpStatusCode.NotFound)
507 tcs.SetResult(default(T));
508 //Retry for timeouts and service unavailable
509 else if (we.Status == WebExceptionStatus.Timeout ||
510 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
515 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
516 tcs.SetException(new RetryException("Timed out too many times.", e));
521 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
523 Retry(original, retryCount - 1, tcs);
534 private HttpStatusCode GetStatusCode(WebException we)
537 throw new ArgumentNullException("we");
538 var statusCode = HttpStatusCode.RequestTimeout;
539 if (we.Response != null)
541 statusCode = ((HttpWebResponse) we.Response).StatusCode;
542 this.StatusCode = statusCode;
547 public UriBuilder GetAddressBuilder(string container, string objectName)
549 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
553 public Dictionary<string, string> GetMeta(string metaPrefix)
555 if (String.IsNullOrWhiteSpace(metaPrefix))
556 throw new ArgumentNullException("metaPrefix");
557 Contract.EndContractBlock();
559 var keys = ResponseHeaders.AllKeys.AsQueryable();
560 var dict = (from key in keys
561 where key.StartsWith(metaPrefix)
562 let name = key.Substring(metaPrefix.Length)
563 select new { Name = name, Value = ResponseHeaders[key] })
564 .ToDictionary(t => t.Name, t => t.Value);
569 public class RetryException:Exception
571 public RetryException()
577 public RetryException(string message)
583 public RetryException(string message,Exception innerException)
584 :base(message,innerException)
589 public RetryException(SerializationInfo info,StreamingContext context)