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 //Any value above 2^21-1 will result in an empty response.
101 //-1 essentially ignores the maximum length
102 HttpWebRequest.DefaultMaximumErrorResponseLength = -1;
106 public RestClient(RestClient other)
110 throw new ArgumentNullException("other");
111 Contract.EndContractBlock();
113 //The maximum error response must be large because missing server hashes are return as a Conflivt (409) error response
114 //Any value above 2^21-1 will result in an empty response.
115 //-1 essentially ignores the maximum length
116 HttpWebRequest.DefaultMaximumErrorResponseLength = -1;
119 Timeout = other.Timeout;
120 Retries = other.Retries;
121 BaseAddress = other.BaseAddress;
123 foreach (var parameter in other.Parameters)
125 Parameters.Add(parameter.Key,parameter.Value);
128 this.Proxy = other.Proxy;
132 protected override WebRequest GetWebRequest(Uri address)
135 var webRequest = base.GetWebRequest(address);
136 var request = (HttpWebRequest)webRequest;
137 request.ServicePoint.ConnectionLimit = 50;
138 if (IfModifiedSince.HasValue)
139 request.IfModifiedSince = IfModifiedSince.Value;
140 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
142 request.Timeout = Timeout;
144 if (RangeFrom.HasValue)
146 if (RangeTo.HasValue)
147 request.AddRange(RangeFrom.Value, RangeTo.Value);
149 request.AddRange(RangeFrom.Value);
154 public DateTime? IfModifiedSince { get; set; }
156 //Asynchronous version
157 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
159 Log.InfoFormat("[{0}] {1}", request.Method, request.RequestUri);
160 HttpWebResponse response = null;
164 response = (HttpWebResponse)base.GetWebResponse(request, result);
166 catch (WebException exc)
168 if (!TryGetResponse(exc, request,out response))
172 StatusCode = response.StatusCode;
173 LastModified = response.LastModified;
174 StatusDescription = response.StatusDescription;
180 //Synchronous version
181 protected override WebResponse GetWebResponse(WebRequest request)
183 HttpWebResponse response = null;
186 Log.InfoFormat("[{0}] {1}",request.Method,request.RequestUri);
187 response = (HttpWebResponse)base.GetWebResponse(request);
189 catch (WebException exc)
191 if (!TryGetResponse(exc, request,out response))
195 StatusCode = response.StatusCode;
196 LastModified = response.LastModified;
197 StatusDescription = response.StatusDescription;
201 private bool TryGetResponse(WebException exc, WebRequest request,out HttpWebResponse response)
204 //Fail on empty response
205 if (exc.Response == null)
207 Log.WarnFormat("[{0}] {1} {2}", request.Method, exc.Status, request.RequestUri);
211 response = (exc.Response as HttpWebResponse);
212 var statusCode = (int)response.StatusCode;
213 //Succeed on allowed status codes
214 if (AllowedStatusCodes.Contains(response.StatusCode))
216 if (Log.IsDebugEnabled)
217 Log.DebugFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
221 Log.WarnFormat("[{0}] {1} {2}", request.Method, statusCode, request.RequestUri);
223 //Does the response have any content to log?
224 if (exc.Response.ContentLength > 0)
226 var content = LogContent(exc.Response);
227 Log.ErrorFormat(content);
232 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
234 public List<HttpStatusCode> AllowedStatusCodes
238 return _allowedStatusCodes;
242 public DateTime LastModified { get; private set; }
244 private static string LogContent(WebResponse webResponse)
246 if (webResponse == null)
247 throw new ArgumentNullException("webResponse");
248 Contract.EndContractBlock();
250 //The response stream must be copied to avoid affecting other code by disposing of the
251 //original response stream.
252 var stream = webResponse.GetResponseStream();
253 using(var memStream=new MemoryStream())
254 using (var reader = new StreamReader(memStream))
256 stream.CopyTo(memStream);
257 string content = reader.ReadToEnd();
259 stream.Seek(0,SeekOrigin.Begin);
264 public string DownloadStringWithRetry(string address,int retries=0)
268 throw new ArgumentNullException("address");
270 var actualAddress = GetActualAddress(address);
272 TraceStart("GET",actualAddress);
274 var actualRetries = (retries == 0) ? Retries : retries;
276 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
278 var task = Retry(() =>
280 var content = base.DownloadString(uriString);
282 if (StatusCode == HttpStatusCode.NoContent)
290 var result = task.Result;
294 catch (AggregateException exc)
296 //If the task fails, propagate the original exception
297 if (exc.InnerException!=null)
298 throw exc.InnerException;
303 public void Head(string address,int retries=0)
305 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
306 RetryWithoutContent(address, retries, "HEAD");
309 public void PutWithRetry(string address, int retries = 0)
311 RetryWithoutContent(address, retries, "PUT");
314 public void DeleteWithRetry(string address,int retries=0)
316 RetryWithoutContent(address, retries, "DELETE");
319 public string GetHeaderValue(string headerName,bool optional=false)
321 if (this.ResponseHeaders==null)
322 throw new InvalidOperationException("ResponseHeaders are null");
323 Contract.EndContractBlock();
325 var values=this.ResponseHeaders.GetValues(headerName);
331 //A required header was not found
332 throw new WebException(String.Format("The {0} header is missing", headerName));
335 public void SetNonEmptyHeaderValue(string headerName, string value)
337 if (String.IsNullOrWhiteSpace(value))
339 Headers.Add(headerName,value);
342 private void RetryWithoutContent(string address, int retries, string method)
345 throw new ArgumentNullException("address");
347 var actualAddress = GetActualAddress(address);
348 var actualRetries = (retries == 0) ? Retries : retries;
350 var task = Retry(() =>
352 var uriString = String.Join("/",BaseAddress ,actualAddress);
353 var uri = new Uri(uriString);
354 var request = GetWebRequest(uri);
355 request.Method = method;
356 if (ResponseHeaders!=null)
357 ResponseHeaders.Clear();
359 TraceStart(method, uriString);
361 request.ContentLength = 0;
363 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
364 //in order to return response headers
365 var response = (HttpWebResponse)GetWebResponse(request);
368 LastModified = response.LastModified;
369 StatusCode = response.StatusCode;
370 StatusDescription = response.StatusDescription;
385 catch (AggregateException ex)
387 var exc = ex.InnerException;
388 if (exc is RetryException)
390 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
394 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
401 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
406 private static void TraceStart(string method, string actualAddress)
408 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
411 private string GetActualAddress(string address)
413 if (Parameters.Count == 0)
415 var addressBuilder=new StringBuilder(address);
418 foreach (var parameter in Parameters)
421 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
423 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
426 return addressBuilder.ToString();
429 public string DownloadStringWithRetry(Uri address,int retries=0)
432 throw new ArgumentNullException("address");
434 var actualRetries = (retries == 0) ? Retries : retries;
435 var task = Retry(() =>
437 var content = base.DownloadString(address);
439 if (StatusCode == HttpStatusCode.NoContent)
445 var result = task.Result;
451 /// Copies headers from another RestClient
453 /// <param name="source">The RestClient from which the headers are copied</param>
454 public void CopyHeaders(RestClient source)
457 throw new ArgumentNullException("source", "source can't be null");
458 Contract.EndContractBlock();
459 //The Headers getter initializes the property, it is never null
460 Contract.Assume(Headers!=null);
462 CopyHeaders(source.Headers,Headers);
466 /// Copies headers from one header collection to another
468 /// <param name="source">The source collection from which the headers are copied</param>
469 /// <param name="target">The target collection to which the headers are copied</param>
470 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
473 throw new ArgumentNullException("source", "source can't be null");
475 throw new ArgumentNullException("target", "target can't be null");
476 Contract.EndContractBlock();
478 for (int i = 0; i < source.Count; i++)
480 target.Add(source.GetKey(i), source[i]);
484 public void AssertStatusOK(string message)
486 if (StatusCode >= HttpStatusCode.BadRequest)
487 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
491 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
494 throw new ArgumentNullException("original");
495 Contract.EndContractBlock();
498 tcs = new TaskCompletionSource<T>();
499 Task.Factory.StartNew(original).ContinueWith(_original =>
501 if (!_original.IsFaulted)
502 tcs.SetFromTask(_original);
505 var e = _original.Exception.InnerException;
506 var we = (e as WebException);
511 var statusCode = GetStatusCode(we);
513 //Return null for 404
514 if (statusCode == HttpStatusCode.NotFound)
515 tcs.SetResult(default(T));
516 //Retry for timeouts and service unavailable
517 else if (we.Status == WebExceptionStatus.Timeout ||
518 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
523 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
524 tcs.SetException(new RetryException("Timed out too many times.", e));
529 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
531 Retry(original, retryCount - 1, tcs);
542 private HttpStatusCode GetStatusCode(WebException we)
545 throw new ArgumentNullException("we");
546 var statusCode = HttpStatusCode.RequestTimeout;
547 if (we.Response != null)
549 statusCode = ((HttpWebResponse) we.Response).StatusCode;
550 this.StatusCode = statusCode;
555 public UriBuilder GetAddressBuilder(string container, string objectName)
557 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
561 public Dictionary<string, string> GetMeta(string metaPrefix)
563 if (String.IsNullOrWhiteSpace(metaPrefix))
564 throw new ArgumentNullException("metaPrefix");
565 Contract.EndContractBlock();
567 var keys = ResponseHeaders.AllKeys.AsQueryable();
568 var dict = (from key in keys
569 where key.StartsWith(metaPrefix)
570 let name = key.Substring(metaPrefix.Length)
571 select new { Name = name, Value = ResponseHeaders[key] })
572 .ToDictionary(t => t.Name, t => t.Value);
577 public class RetryException:Exception
579 public RetryException()
585 public RetryException(string message)
591 public RetryException(string message,Exception innerException)
592 :base(message,innerException)
597 public RetryException(SerializationInfo info,StreamingContext context)