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()
99 //The maximum error response must be large because missing server hashes are return as a Conflivt (409) error response
100 HttpWebRequest.DefaultMaximumErrorResponseLength = 16*1024*1024;
104 public RestClient(RestClient other)
108 throw new ArgumentNullException("other");
109 Contract.EndContractBlock();
111 HttpWebRequest.DefaultMaximumErrorResponseLength = 16 * 1024 * 1024;
114 Timeout = other.Timeout;
115 Retries = other.Retries;
116 BaseAddress = other.BaseAddress;
118 foreach (var parameter in other.Parameters)
120 Parameters.Add(parameter.Key,parameter.Value);
123 this.Proxy = other.Proxy;
127 protected override WebRequest GetWebRequest(Uri address)
130 var webRequest = base.GetWebRequest(address);
131 var request = (HttpWebRequest)webRequest;
132 request.ServicePoint.ConnectionLimit = 50;
133 if (IfModifiedSince.HasValue)
134 request.IfModifiedSince = IfModifiedSince.Value;
135 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
137 request.Timeout = Timeout;
139 if (RangeFrom.HasValue)
141 if (RangeTo.HasValue)
142 request.AddRange(RangeFrom.Value, RangeTo.Value);
144 request.AddRange(RangeFrom.Value);
149 public DateTime? IfModifiedSince { get; set; }
151 //Asynchronous version
152 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
154 Log.InfoFormat("[{0}] {1}", request.Method, request.RequestUri);
155 HttpWebResponse response = null;
159 response = (HttpWebResponse)base.GetWebResponse(request, result);
161 catch (WebException exc)
163 if (!TryGetResponse(exc, request,out response))
167 StatusCode = response.StatusCode;
168 LastModified = response.LastModified;
169 StatusDescription = response.StatusDescription;
175 //Synchronous version
176 protected override WebResponse GetWebResponse(WebRequest request)
178 HttpWebResponse response = null;
181 Log.InfoFormat("[{0}] {1}",request.Method,request.RequestUri);
182 response = (HttpWebResponse)base.GetWebResponse(request);
184 catch (WebException exc)
186 if (!TryGetResponse(exc, request,out response))
190 StatusCode = response.StatusCode;
191 LastModified = response.LastModified;
192 StatusDescription = response.StatusDescription;
196 private bool TryGetResponse(WebException exc, WebRequest request,out HttpWebResponse response)
199 //Fail on empty response
200 if (exc.Response == null)
202 Log.WarnFormat("[{0}] {1} {2}", request.Method, exc.Status, request.RequestUri);
206 response = (exc.Response as HttpWebResponse);
207 var statusCode = (int)response.StatusCode;
208 //Succeed on allowed status codes
209 if (AllowedStatusCodes.Contains(response.StatusCode))
211 if (Log.IsDebugEnabled)
212 Log.DebugFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
216 Log.WarnFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
218 //Does the response have any content to log?
219 if (exc.Response.ContentLength > 0)
221 var content = LogContent(exc.Response);
222 Log.ErrorFormat(content);
227 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
229 public List<HttpStatusCode> AllowedStatusCodes
233 return _allowedStatusCodes;
237 public DateTime LastModified { get; private set; }
239 private static string LogContent(WebResponse webResponse)
241 if (webResponse == null)
242 throw new ArgumentNullException("webResponse");
243 Contract.EndContractBlock();
245 //The response stream must be copied to avoid affecting other code by disposing of the
246 //original response stream.
247 var stream = webResponse.GetResponseStream();
248 using(var memStream=new MemoryStream())
249 using (var reader = new StreamReader(memStream))
251 stream.CopyTo(memStream);
252 string content = reader.ReadToEnd();
254 stream.Seek(0,SeekOrigin.Begin);
259 public string DownloadStringWithRetry(string address,int retries=0)
263 throw new ArgumentNullException("address");
265 var actualAddress = GetActualAddress(address);
267 TraceStart("GET",actualAddress);
269 var actualRetries = (retries == 0) ? Retries : retries;
271 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
273 var task = Retry(() =>
275 var content = base.DownloadString(uriString);
277 if (StatusCode == HttpStatusCode.NoContent)
285 var result = task.Result;
289 catch (AggregateException exc)
291 //If the task fails, propagate the original exception
292 if (exc.InnerException!=null)
293 throw exc.InnerException;
298 public void Head(string address,int retries=0)
300 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
301 RetryWithoutContent(address, retries, "HEAD");
304 public void PutWithRetry(string address, int retries = 0)
306 RetryWithoutContent(address, retries, "PUT");
309 public void DeleteWithRetry(string address,int retries=0)
311 RetryWithoutContent(address, retries, "DELETE");
314 public string GetHeaderValue(string headerName,bool optional=false)
316 if (this.ResponseHeaders==null)
317 throw new InvalidOperationException("ResponseHeaders are null");
318 Contract.EndContractBlock();
320 var values=this.ResponseHeaders.GetValues(headerName);
326 //A required header was not found
327 throw new WebException(String.Format("The {0} header is missing", headerName));
330 public void SetNonEmptyHeaderValue(string headerName, string value)
332 if (String.IsNullOrWhiteSpace(value))
334 Headers.Add(headerName,value);
337 private void RetryWithoutContent(string address, int retries, string method)
340 throw new ArgumentNullException("address");
342 var actualAddress = GetActualAddress(address);
343 var actualRetries = (retries == 0) ? Retries : retries;
345 var task = Retry(() =>
347 var uriString = String.Join("/",BaseAddress ,actualAddress);
348 var uri = new Uri(uriString);
349 var request = GetWebRequest(uri);
350 request.Method = method;
351 if (ResponseHeaders!=null)
352 ResponseHeaders.Clear();
354 TraceStart(method, uriString);
356 request.ContentLength = 0;
358 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
359 //in order to return response headers
360 var response = (HttpWebResponse)GetWebResponse(request);
363 LastModified = response.LastModified;
364 StatusCode = response.StatusCode;
365 StatusDescription = response.StatusDescription;
380 catch (AggregateException ex)
382 var exc = ex.InnerException;
383 if (exc is RetryException)
385 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
389 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
396 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
401 private static void TraceStart(string method, string actualAddress)
403 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
406 private string GetActualAddress(string address)
408 if (Parameters.Count == 0)
410 var addressBuilder=new StringBuilder(address);
413 foreach (var parameter in Parameters)
416 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
418 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
421 return addressBuilder.ToString();
424 public string DownloadStringWithRetry(Uri address,int retries=0)
427 throw new ArgumentNullException("address");
429 var actualRetries = (retries == 0) ? Retries : retries;
430 var task = Retry(() =>
432 var content = base.DownloadString(address);
434 if (StatusCode == HttpStatusCode.NoContent)
440 var result = task.Result;
446 /// Copies headers from another RestClient
448 /// <param name="source">The RestClient from which the headers are copied</param>
449 public void CopyHeaders(RestClient source)
452 throw new ArgumentNullException("source", "source can't be null");
453 Contract.EndContractBlock();
454 //The Headers getter initializes the property, it is never null
455 Contract.Assume(Headers!=null);
457 CopyHeaders(source.Headers,Headers);
461 /// Copies headers from one header collection to another
463 /// <param name="source">The source collection from which the headers are copied</param>
464 /// <param name="target">The target collection to which the headers are copied</param>
465 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
468 throw new ArgumentNullException("source", "source can't be null");
470 throw new ArgumentNullException("target", "target can't be null");
471 Contract.EndContractBlock();
473 for (int i = 0; i < source.Count; i++)
475 target.Add(source.GetKey(i), source[i]);
479 public void AssertStatusOK(string message)
481 if (StatusCode >= HttpStatusCode.BadRequest)
482 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
486 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
489 throw new ArgumentNullException("original");
490 Contract.EndContractBlock();
493 tcs = new TaskCompletionSource<T>();
494 Task.Factory.StartNew(original).ContinueWith(_original =>
496 if (!_original.IsFaulted)
497 tcs.SetFromTask(_original);
500 var e = _original.Exception.InnerException;
501 var we = (e as WebException);
506 var statusCode = GetStatusCode(we);
508 //Return null for 404
509 if (statusCode == HttpStatusCode.NotFound)
510 tcs.SetResult(default(T));
511 //Retry for timeouts and service unavailable
512 else if (we.Status == WebExceptionStatus.Timeout ||
513 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
518 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
519 tcs.SetException(new RetryException("Timed out too many times.", e));
524 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
526 Retry(original, retryCount - 1, tcs);
537 private HttpStatusCode GetStatusCode(WebException we)
540 throw new ArgumentNullException("we");
541 var statusCode = HttpStatusCode.RequestTimeout;
542 if (we.Response != null)
544 statusCode = ((HttpWebResponse) we.Response).StatusCode;
545 this.StatusCode = statusCode;
550 public UriBuilder GetAddressBuilder(string container, string objectName)
552 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
556 public Dictionary<string, string> GetMeta(string metaPrefix)
558 if (String.IsNullOrWhiteSpace(metaPrefix))
559 throw new ArgumentNullException("metaPrefix");
560 Contract.EndContractBlock();
562 var keys = ResponseHeaders.AllKeys.AsQueryable();
563 var dict = (from key in keys
564 where key.StartsWith(metaPrefix)
565 let name = key.Substring(metaPrefix.Length)
566 select new { Name = name, Value = ResponseHeaders[key] })
567 .ToDictionary(t => t.Name, t => t.Value);
572 public class RetryException:Exception
574 public RetryException()
580 public RetryException(string message)
586 public RetryException(string message,Exception innerException)
587 :base(message,innerException)
592 public RetryException(SerializationInfo info,StreamingContext context)