1 // -----------------------------------------------------------------------
2 // <copyright file="RestClient.cs" company="GRNet">
3 // Copyright 2011 GRNET S.A. All rights reserved.
5 // Redistribution and use in source and binary forms, with or
6 // without modification, are permitted provided that the following
9 // 1. Redistributions of source code must retain the above
10 // copyright notice, this list of conditions and the following
13 // 2. Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following
15 // disclaimer in the documentation and/or other materials
16 // provided with the distribution.
18 // THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 // POSSIBILITY OF SUCH DAMAGE.
31 // The views and conclusions contained in the software and
32 // documentation are those of the authors and should not be
33 // interpreted as representing official policies, either expressed
34 // or implied, of GRNET S.A.
36 // -----------------------------------------------------------------------
38 using System.Collections.Specialized;
39 using System.Diagnostics;
40 using System.Diagnostics.Contracts;
43 using System.Runtime.Serialization;
44 using System.Threading.Tasks;
48 namespace Pithos.Network
51 using System.Collections.Generic;
56 /// TODO: Update summary.
58 public class RestClient:WebClient
60 public int Timeout { get; set; }
62 public bool TimedOut { get; set; }
64 public HttpStatusCode StatusCode { get; private set; }
66 public string StatusDescription { get; set; }
68 public long? RangeFrom { get; set; }
69 public long? RangeTo { get; set; }
71 public int Retries { get; set; }
73 private readonly Dictionary<string, string> _parameters=new Dictionary<string, string>();
74 public Dictionary<string, string> Parameters
78 Contract.Ensures(_parameters!=null);
83 private static readonly ILog Log = LogManager.GetLogger("RestClient");
86 [ContractInvariantMethod]
87 private void Invariants()
89 Contract.Invariant(Headers!=null);
92 public RestClient():base()
98 public RestClient(RestClient other)
102 throw new ArgumentNullException("other");
103 Contract.EndContractBlock();
106 Timeout = other.Timeout;
107 Retries = other.Retries;
108 BaseAddress = other.BaseAddress;
110 foreach (var parameter in other.Parameters)
112 Parameters.Add(parameter.Key,parameter.Value);
115 this.Proxy = other.Proxy;
119 protected override WebRequest GetWebRequest(Uri address)
122 var webRequest = base.GetWebRequest(address);
123 var request = (HttpWebRequest)webRequest;
124 request.ServicePoint.ConnectionLimit = 10;
125 if (IfModifiedSince.HasValue)
126 request.IfModifiedSince = IfModifiedSince.Value;
127 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
129 request.Timeout = Timeout;
131 if (RangeFrom.HasValue)
133 if (RangeTo.HasValue)
134 request.AddRange(RangeFrom.Value, RangeTo.Value);
136 request.AddRange(RangeFrom.Value);
141 public DateTime? IfModifiedSince { get; set; }
143 //Asynchronous version
144 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
146 Log.InfoFormat("ASYNC [{0}] {1}",request.Method, request.RequestUri);
147 HttpWebResponse response = null;
151 response = (HttpWebResponse)base.GetWebResponse(request, result);
153 catch (WebException exc)
155 if (!TryGetResponse(exc, out response))
159 StatusCode = response.StatusCode;
160 LastModified = response.LastModified;
161 StatusDescription = response.StatusDescription;
167 //Synchronous version
168 protected override WebResponse GetWebResponse(WebRequest request)
170 HttpWebResponse response = null;
173 response = (HttpWebResponse)base.GetWebResponse(request);
175 catch (WebException exc)
177 if (!TryGetResponse(exc, out response))
181 StatusCode = response.StatusCode;
182 LastModified = response.LastModified;
183 StatusDescription = response.StatusDescription;
187 private bool TryGetResponse(WebException exc, out HttpWebResponse response)
190 //Fail on empty response
191 if (exc.Response == null)
194 response = (exc.Response as HttpWebResponse);
195 //Succeed on allowed status codes
196 if (AllowedStatusCodes.Contains(response.StatusCode))
199 //Does the response have any content to log?
200 if (exc.Response.ContentLength > 0)
202 var content = LogContent(exc.Response);
203 Log.ErrorFormat(content);
208 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
210 public List<HttpStatusCode> AllowedStatusCodes
214 return _allowedStatusCodes;
218 public DateTime LastModified { get; private set; }
220 private static string LogContent(WebResponse webResponse)
222 if (webResponse == null)
223 throw new ArgumentNullException("webResponse");
224 Contract.EndContractBlock();
226 //The response stream must be copied to avoid affecting other code by disposing of the
227 //original response stream.
228 var stream = webResponse.GetResponseStream();
229 using(var memStream=new MemoryStream((int) stream.Length))
230 using (var reader = new StreamReader(memStream))
232 stream.CopyTo(memStream);
233 string content = reader.ReadToEnd();
235 stream.Seek(0,SeekOrigin.Begin);
240 public string DownloadStringWithRetry(string address,int retries=0)
244 throw new ArgumentNullException("address");
246 var actualAddress = GetActualAddress(address);
248 TraceStart("GET",actualAddress);
250 var actualRetries = (retries == 0) ? Retries : retries;
252 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
254 var task = Retry(() =>
256 var content = base.DownloadString(uriString);
258 if (StatusCode == HttpStatusCode.NoContent)
264 var result = task.Result;
268 public void Head(string address,int retries=0)
270 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
271 RetryWithoutContent(address, retries, "HEAD");
274 public void PutWithRetry(string address, int retries = 0)
276 RetryWithoutContent(address, retries, "PUT");
279 public void DeleteWithRetry(string address,int retries=0)
281 RetryWithoutContent(address, retries, "DELETE");
284 public string GetHeaderValue(string headerName,bool optional=false)
286 if (this.ResponseHeaders==null)
287 throw new InvalidOperationException("ResponseHeaders are null");
288 Contract.EndContractBlock();
290 var values=this.ResponseHeaders.GetValues(headerName);
296 //A required header was not found
297 throw new WebException(String.Format("The {0} header is missing", headerName));
300 public void SetNonEmptyHeaderValue(string headerName, string value)
302 if (String.IsNullOrWhiteSpace(value))
304 Headers.Add(headerName,value);
307 private void RetryWithoutContent(string address, int retries, string method)
310 throw new ArgumentNullException("address");
312 var actualAddress = GetActualAddress(address);
313 var actualRetries = (retries == 0) ? Retries : retries;
315 var task = Retry(() =>
317 var uriString = String.Join("/",BaseAddress ,actualAddress);
318 var uri = new Uri(uriString);
319 var request = GetWebRequest(uri);
320 request.Method = method;
321 if (ResponseHeaders!=null)
322 ResponseHeaders.Clear();
324 TraceStart(method, uriString);
326 request.ContentLength = 0;
328 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
329 //in order to return response headers
330 var response = (HttpWebResponse)GetWebResponse(request);
333 LastModified = response.LastModified;
334 StatusCode = response.StatusCode;
335 StatusDescription = response.StatusDescription;
350 catch (AggregateException ex)
352 var exc = ex.InnerException;
353 if (exc is RetryException)
355 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
359 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
366 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
371 private static void TraceStart(string method, string actualAddress)
373 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
376 private string GetActualAddress(string address)
378 if (Parameters.Count == 0)
380 var addressBuilder=new StringBuilder(address);
383 foreach (var parameter in Parameters)
386 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
388 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
391 return addressBuilder.ToString();
394 public string DownloadStringWithRetry(Uri address,int retries=0)
397 throw new ArgumentNullException("address");
399 var actualRetries = (retries == 0) ? Retries : retries;
400 var task = Retry(() =>
402 var content = base.DownloadString(address);
404 if (StatusCode == HttpStatusCode.NoContent)
410 var result = task.Result;
416 /// Copies headers from another RestClient
418 /// <param name="source">The RestClient from which the headers are copied</param>
419 public void CopyHeaders(RestClient source)
422 throw new ArgumentNullException("source", "source can't be null");
423 Contract.EndContractBlock();
424 //The Headers getter initializes the property, it is never null
425 Contract.Assume(Headers!=null);
427 CopyHeaders(source.Headers,Headers);
431 /// Copies headers from one header collection to another
433 /// <param name="source">The source collection from which the headers are copied</param>
434 /// <param name="target">The target collection to which the headers are copied</param>
435 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
438 throw new ArgumentNullException("source", "source can't be null");
440 throw new ArgumentNullException("target", "target can't be null");
441 Contract.EndContractBlock();
443 for (int i = 0; i < source.Count; i++)
445 target.Add(source.GetKey(i), source[i]);
449 public void AssertStatusOK(string message)
451 if (StatusCode >= HttpStatusCode.BadRequest)
452 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
456 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
459 throw new ArgumentNullException("original");
460 Contract.EndContractBlock();
463 tcs = new TaskCompletionSource<T>();
464 Task.Factory.StartNew(original).ContinueWith(_original =>
466 if (!_original.IsFaulted)
467 tcs.SetFromTask(_original);
470 var e = _original.Exception.InnerException;
471 var we = (e as WebException);
476 var statusCode = GetStatusCode(we);
478 //Return null for 404
479 if (statusCode == HttpStatusCode.NotFound)
480 tcs.SetResult(default(T));
481 //Retry for timeouts and service unavailable
482 else if (we.Status == WebExceptionStatus.Timeout ||
483 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
488 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
489 tcs.SetException(new RetryException("Timed out too many times.", e));
494 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
496 Retry(original, retryCount - 1, tcs);
507 private HttpStatusCode GetStatusCode(WebException we)
510 throw new ArgumentNullException("we");
511 var statusCode = HttpStatusCode.RequestTimeout;
512 if (we.Response != null)
514 statusCode = ((HttpWebResponse) we.Response).StatusCode;
515 this.StatusCode = statusCode;
520 public UriBuilder GetAddressBuilder(string container, string objectName)
522 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
526 public Dictionary<string, string> GetMeta(string metaPrefix)
528 if (String.IsNullOrWhiteSpace(metaPrefix))
529 throw new ArgumentNullException("metaPrefix");
530 Contract.EndContractBlock();
532 var keys = ResponseHeaders.AllKeys.AsQueryable();
533 var dict = (from key in keys
534 where key.StartsWith(metaPrefix)
535 let name = key.Substring(metaPrefix.Length)
536 select new { Name = name, Value = ResponseHeaders[key] })
537 .ToDictionary(t => t.Name, t => t.Value);
542 public class RetryException:Exception
544 public RetryException()
550 public RetryException(string message)
556 public RetryException(string message,Exception innerException)
557 :base(message,innerException)
562 public RetryException(SerializationInfo info,StreamingContext context)