root / trunk / Pithos.Network / RestClient.cs @ 6bcdd8e2
History | View | Annotate | Download (20 kB)
1 |
#region |
---|---|
2 |
/* ----------------------------------------------------------------------- |
3 |
* <copyright file="RestClient.cs" company="GRNet"> |
4 |
* |
5 |
* Copyright 2011-2012 GRNET S.A. All rights reserved. |
6 |
* |
7 |
* Redistribution and use in source and binary forms, with or |
8 |
* without modification, are permitted provided that the following |
9 |
* conditions are met: |
10 |
* |
11 |
* 1. Redistributions of source code must retain the above |
12 |
* copyright notice, this list of conditions and the following |
13 |
* disclaimer. |
14 |
* |
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. |
19 |
* |
20 |
* |
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. |
33 |
* |
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. |
38 |
* </copyright> |
39 |
* ----------------------------------------------------------------------- |
40 |
*/ |
41 |
#endregion |
42 |
using System.Collections.Specialized; |
43 |
using System.Diagnostics; |
44 |
using System.Diagnostics.Contracts; |
45 |
using System.IO; |
46 |
using System.Net; |
47 |
using System.Reflection; |
48 |
using System.Runtime.Serialization; |
49 |
using System.Threading.Tasks; |
50 |
using log4net; |
51 |
|
52 |
|
53 |
namespace Pithos.Network |
54 |
{ |
55 |
using System; |
56 |
using System.Collections.Generic; |
57 |
using System.Linq; |
58 |
using System.Text; |
59 |
|
60 |
/// <summary> |
61 |
/// TODO: Update summary. |
62 |
/// </summary> |
63 |
public class RestClient:WebClient |
64 |
{ |
65 |
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); |
66 |
|
67 |
public int Timeout { get; set; } |
68 |
|
69 |
public bool TimedOut { get; set; } |
70 |
|
71 |
public HttpStatusCode StatusCode { get; private set; } |
72 |
|
73 |
public string StatusDescription { get; set; } |
74 |
|
75 |
public long? RangeFrom { get; set; } |
76 |
public long? RangeTo { get; set; } |
77 |
|
78 |
public int Retries { get; set; } |
79 |
|
80 |
private readonly Dictionary<string, string> _parameters=new Dictionary<string, string>(); |
81 |
public Dictionary<string, string> Parameters |
82 |
{ |
83 |
get |
84 |
{ |
85 |
Contract.Ensures(_parameters!=null); |
86 |
return _parameters; |
87 |
} |
88 |
} |
89 |
|
90 |
|
91 |
[ContractInvariantMethod] |
92 |
private void Invariants() |
93 |
{ |
94 |
Contract.Invariant(Headers!=null); |
95 |
} |
96 |
|
97 |
public RestClient():base() |
98 |
{ |
99 |
|
100 |
} |
101 |
|
102 |
|
103 |
public RestClient(RestClient other) |
104 |
: base() |
105 |
{ |
106 |
if (other==null) |
107 |
throw new ArgumentNullException("other"); |
108 |
Contract.EndContractBlock(); |
109 |
|
110 |
CopyHeaders(other); |
111 |
Timeout = other.Timeout; |
112 |
Retries = other.Retries; |
113 |
BaseAddress = other.BaseAddress; |
114 |
|
115 |
foreach (var parameter in other.Parameters) |
116 |
{ |
117 |
Parameters.Add(parameter.Key,parameter.Value); |
118 |
} |
119 |
|
120 |
this.Proxy = other.Proxy; |
121 |
} |
122 |
|
123 |
|
124 |
protected override WebRequest GetWebRequest(Uri address) |
125 |
{ |
126 |
TimedOut = false; |
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; |
133 |
if(Timeout>0) |
134 |
request.Timeout = Timeout; |
135 |
|
136 |
if (RangeFrom.HasValue) |
137 |
{ |
138 |
if (RangeTo.HasValue) |
139 |
request.AddRange(RangeFrom.Value, RangeTo.Value); |
140 |
else |
141 |
request.AddRange(RangeFrom.Value); |
142 |
} |
143 |
return request; |
144 |
} |
145 |
|
146 |
public DateTime? IfModifiedSince { get; set; } |
147 |
|
148 |
//Asynchronous version |
149 |
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) |
150 |
{ |
151 |
Log.InfoFormat("[{0}] {1}", request.Method, request.RequestUri); |
152 |
HttpWebResponse response = null; |
153 |
|
154 |
try |
155 |
{ |
156 |
response = (HttpWebResponse)base.GetWebResponse(request, result); |
157 |
} |
158 |
catch (WebException exc) |
159 |
{ |
160 |
Log.WarnFormat("[{0}] {1} {2}", request.Method, exc.Status, request.RequestUri); |
161 |
if (!TryGetResponse(exc, out response)) |
162 |
throw; |
163 |
} |
164 |
|
165 |
StatusCode = response.StatusCode; |
166 |
LastModified = response.LastModified; |
167 |
StatusDescription = response.StatusDescription; |
168 |
return response; |
169 |
|
170 |
} |
171 |
|
172 |
|
173 |
//Synchronous version |
174 |
protected override WebResponse GetWebResponse(WebRequest request) |
175 |
{ |
176 |
HttpWebResponse response = null; |
177 |
try |
178 |
{ |
179 |
Log.InfoFormat("[{0}] {1}",request.Method,request.RequestUri); |
180 |
response = (HttpWebResponse)base.GetWebResponse(request); |
181 |
} |
182 |
catch (WebException exc) |
183 |
{ |
184 |
Log.WarnFormat("[{0}] {1} {2}", request.Method, exc.Status, request.RequestUri); |
185 |
if (!TryGetResponse(exc, out response)) |
186 |
throw; |
187 |
} |
188 |
|
189 |
StatusCode = response.StatusCode; |
190 |
LastModified = response.LastModified; |
191 |
StatusDescription = response.StatusDescription; |
192 |
return response; |
193 |
} |
194 |
|
195 |
private bool TryGetResponse(WebException exc, out HttpWebResponse response) |
196 |
{ |
197 |
response = null; |
198 |
//Fail on empty response |
199 |
if (exc.Response == null) |
200 |
return false; |
201 |
|
202 |
response = (exc.Response as HttpWebResponse); |
203 |
//Succeed on allowed status codes |
204 |
if (AllowedStatusCodes.Contains(response.StatusCode)) |
205 |
return true; |
206 |
|
207 |
//Does the response have any content to log? |
208 |
if (exc.Response.ContentLength > 0) |
209 |
{ |
210 |
var content = LogContent(exc.Response); |
211 |
Log.ErrorFormat(content); |
212 |
} |
213 |
return false; |
214 |
} |
215 |
|
216 |
private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified}; |
217 |
|
218 |
public List<HttpStatusCode> AllowedStatusCodes |
219 |
{ |
220 |
get |
221 |
{ |
222 |
return _allowedStatusCodes; |
223 |
} |
224 |
} |
225 |
|
226 |
public DateTime LastModified { get; private set; } |
227 |
|
228 |
private static string LogContent(WebResponse webResponse) |
229 |
{ |
230 |
if (webResponse == null) |
231 |
throw new ArgumentNullException("webResponse"); |
232 |
Contract.EndContractBlock(); |
233 |
|
234 |
//The response stream must be copied to avoid affecting other code by disposing of the |
235 |
//original response stream. |
236 |
var stream = webResponse.GetResponseStream(); |
237 |
using(var memStream=new MemoryStream()) |
238 |
using (var reader = new StreamReader(memStream)) |
239 |
{ |
240 |
stream.CopyTo(memStream); |
241 |
string content = reader.ReadToEnd(); |
242 |
|
243 |
stream.Seek(0,SeekOrigin.Begin); |
244 |
return content; |
245 |
} |
246 |
} |
247 |
|
248 |
public string DownloadStringWithRetry(string address,int retries=0) |
249 |
{ |
250 |
|
251 |
if (address == null) |
252 |
throw new ArgumentNullException("address"); |
253 |
|
254 |
var actualAddress = GetActualAddress(address); |
255 |
|
256 |
TraceStart("GET",actualAddress); |
257 |
|
258 |
var actualRetries = (retries == 0) ? Retries : retries; |
259 |
|
260 |
var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress); |
261 |
|
262 |
var task = Retry(() => |
263 |
{ |
264 |
var content = base.DownloadString(uriString); |
265 |
|
266 |
if (StatusCode == HttpStatusCode.NoContent) |
267 |
return String.Empty; |
268 |
return content; |
269 |
|
270 |
}, actualRetries); |
271 |
|
272 |
try |
273 |
{ |
274 |
var result = task.Result; |
275 |
return result; |
276 |
|
277 |
} |
278 |
catch (AggregateException exc) |
279 |
{ |
280 |
//If the task fails, propagate the original exception |
281 |
if (exc.InnerException!=null) |
282 |
throw exc.InnerException; |
283 |
throw; |
284 |
} |
285 |
} |
286 |
|
287 |
public void Head(string address,int retries=0) |
288 |
{ |
289 |
AllowedStatusCodes.Add(HttpStatusCode.NotFound); |
290 |
RetryWithoutContent(address, retries, "HEAD"); |
291 |
} |
292 |
|
293 |
public void PutWithRetry(string address, int retries = 0) |
294 |
{ |
295 |
RetryWithoutContent(address, retries, "PUT"); |
296 |
} |
297 |
|
298 |
public void DeleteWithRetry(string address,int retries=0) |
299 |
{ |
300 |
RetryWithoutContent(address, retries, "DELETE"); |
301 |
} |
302 |
|
303 |
public string GetHeaderValue(string headerName,bool optional=false) |
304 |
{ |
305 |
if (this.ResponseHeaders==null) |
306 |
throw new InvalidOperationException("ResponseHeaders are null"); |
307 |
Contract.EndContractBlock(); |
308 |
|
309 |
var values=this.ResponseHeaders.GetValues(headerName); |
310 |
if (values != null) |
311 |
return values[0]; |
312 |
|
313 |
if (optional) |
314 |
return null; |
315 |
//A required header was not found |
316 |
throw new WebException(String.Format("The {0} header is missing", headerName)); |
317 |
} |
318 |
|
319 |
public void SetNonEmptyHeaderValue(string headerName, string value) |
320 |
{ |
321 |
if (String.IsNullOrWhiteSpace(value)) |
322 |
return; |
323 |
Headers.Add(headerName,value); |
324 |
} |
325 |
|
326 |
private void RetryWithoutContent(string address, int retries, string method) |
327 |
{ |
328 |
if (address == null) |
329 |
throw new ArgumentNullException("address"); |
330 |
|
331 |
var actualAddress = GetActualAddress(address); |
332 |
var actualRetries = (retries == 0) ? Retries : retries; |
333 |
|
334 |
var task = Retry(() => |
335 |
{ |
336 |
var uriString = String.Join("/",BaseAddress ,actualAddress); |
337 |
var uri = new Uri(uriString); |
338 |
var request = GetWebRequest(uri); |
339 |
request.Method = method; |
340 |
if (ResponseHeaders!=null) |
341 |
ResponseHeaders.Clear(); |
342 |
|
343 |
TraceStart(method, uriString); |
344 |
if (method == "PUT") |
345 |
request.ContentLength = 0; |
346 |
|
347 |
//Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object |
348 |
//in order to return response headers |
349 |
var response = (HttpWebResponse)GetWebResponse(request); |
350 |
try |
351 |
{ |
352 |
LastModified = response.LastModified; |
353 |
StatusCode = response.StatusCode; |
354 |
StatusDescription = response.StatusDescription; |
355 |
} |
356 |
finally |
357 |
{ |
358 |
response.Close(); |
359 |
} |
360 |
|
361 |
|
362 |
return 0; |
363 |
}, actualRetries); |
364 |
|
365 |
try |
366 |
{ |
367 |
task.Wait(); |
368 |
} |
369 |
catch (AggregateException ex) |
370 |
{ |
371 |
var exc = ex.InnerException; |
372 |
if (exc is RetryException) |
373 |
{ |
374 |
Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries); |
375 |
} |
376 |
else |
377 |
{ |
378 |
Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc); |
379 |
} |
380 |
throw exc; |
381 |
|
382 |
} |
383 |
catch(Exception ex) |
384 |
{ |
385 |
Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex); |
386 |
throw; |
387 |
} |
388 |
} |
389 |
|
390 |
private static void TraceStart(string method, string actualAddress) |
391 |
{ |
392 |
Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress); |
393 |
} |
394 |
|
395 |
private string GetActualAddress(string address) |
396 |
{ |
397 |
if (Parameters.Count == 0) |
398 |
return address; |
399 |
var addressBuilder=new StringBuilder(address); |
400 |
|
401 |
bool isFirst = true; |
402 |
foreach (var parameter in Parameters) |
403 |
{ |
404 |
if(isFirst) |
405 |
addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value); |
406 |
else |
407 |
addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value); |
408 |
isFirst = false; |
409 |
} |
410 |
return addressBuilder.ToString(); |
411 |
} |
412 |
|
413 |
public string DownloadStringWithRetry(Uri address,int retries=0) |
414 |
{ |
415 |
if (address == null) |
416 |
throw new ArgumentNullException("address"); |
417 |
|
418 |
var actualRetries = (retries == 0) ? Retries : retries; |
419 |
var task = Retry(() => |
420 |
{ |
421 |
var content = base.DownloadString(address); |
422 |
|
423 |
if (StatusCode == HttpStatusCode.NoContent) |
424 |
return String.Empty; |
425 |
return content; |
426 |
|
427 |
}, actualRetries); |
428 |
|
429 |
var result = task.Result; |
430 |
return result; |
431 |
} |
432 |
|
433 |
|
434 |
/// <summary> |
435 |
/// Copies headers from another RestClient |
436 |
/// </summary> |
437 |
/// <param name="source">The RestClient from which the headers are copied</param> |
438 |
public void CopyHeaders(RestClient source) |
439 |
{ |
440 |
if (source == null) |
441 |
throw new ArgumentNullException("source", "source can't be null"); |
442 |
Contract.EndContractBlock(); |
443 |
//The Headers getter initializes the property, it is never null |
444 |
Contract.Assume(Headers!=null); |
445 |
|
446 |
CopyHeaders(source.Headers,Headers); |
447 |
} |
448 |
|
449 |
/// <summary> |
450 |
/// Copies headers from one header collection to another |
451 |
/// </summary> |
452 |
/// <param name="source">The source collection from which the headers are copied</param> |
453 |
/// <param name="target">The target collection to which the headers are copied</param> |
454 |
public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target) |
455 |
{ |
456 |
if (source == null) |
457 |
throw new ArgumentNullException("source", "source can't be null"); |
458 |
if (target == null) |
459 |
throw new ArgumentNullException("target", "target can't be null"); |
460 |
Contract.EndContractBlock(); |
461 |
|
462 |
for (int i = 0; i < source.Count; i++) |
463 |
{ |
464 |
target.Add(source.GetKey(i), source[i]); |
465 |
} |
466 |
} |
467 |
|
468 |
public void AssertStatusOK(string message) |
469 |
{ |
470 |
if (StatusCode >= HttpStatusCode.BadRequest) |
471 |
throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription)); |
472 |
} |
473 |
|
474 |
|
475 |
private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null) |
476 |
{ |
477 |
if (original==null) |
478 |
throw new ArgumentNullException("original"); |
479 |
Contract.EndContractBlock(); |
480 |
|
481 |
if (tcs == null) |
482 |
tcs = new TaskCompletionSource<T>(); |
483 |
Task.Factory.StartNew(original).ContinueWith(_original => |
484 |
{ |
485 |
if (!_original.IsFaulted) |
486 |
tcs.SetFromTask(_original); |
487 |
else |
488 |
{ |
489 |
var e = _original.Exception.InnerException; |
490 |
var we = (e as WebException); |
491 |
if (we==null) |
492 |
tcs.SetException(e); |
493 |
else |
494 |
{ |
495 |
var statusCode = GetStatusCode(we); |
496 |
|
497 |
//Return null for 404 |
498 |
if (statusCode == HttpStatusCode.NotFound) |
499 |
tcs.SetResult(default(T)); |
500 |
//Retry for timeouts and service unavailable |
501 |
else if (we.Status == WebExceptionStatus.Timeout || |
502 |
(we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable)) |
503 |
{ |
504 |
TimedOut = true; |
505 |
if (retryCount == 0) |
506 |
{ |
507 |
Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e); |
508 |
tcs.SetException(new RetryException("Timed out too many times.", e)); |
509 |
} |
510 |
else |
511 |
{ |
512 |
Log.ErrorFormat( |
513 |
"[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout, |
514 |
retryCount, e); |
515 |
Retry(original, retryCount - 1, tcs); |
516 |
} |
517 |
} |
518 |
else |
519 |
tcs.SetException(e); |
520 |
} |
521 |
}; |
522 |
}); |
523 |
return tcs.Task; |
524 |
} |
525 |
|
526 |
private HttpStatusCode GetStatusCode(WebException we) |
527 |
{ |
528 |
if (we==null) |
529 |
throw new ArgumentNullException("we"); |
530 |
var statusCode = HttpStatusCode.RequestTimeout; |
531 |
if (we.Response != null) |
532 |
{ |
533 |
statusCode = ((HttpWebResponse) we.Response).StatusCode; |
534 |
this.StatusCode = statusCode; |
535 |
} |
536 |
return statusCode; |
537 |
} |
538 |
|
539 |
public UriBuilder GetAddressBuilder(string container, string objectName) |
540 |
{ |
541 |
var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName)); |
542 |
return builder; |
543 |
} |
544 |
|
545 |
public Dictionary<string, string> GetMeta(string metaPrefix) |
546 |
{ |
547 |
if (String.IsNullOrWhiteSpace(metaPrefix)) |
548 |
throw new ArgumentNullException("metaPrefix"); |
549 |
Contract.EndContractBlock(); |
550 |
|
551 |
var keys = ResponseHeaders.AllKeys.AsQueryable(); |
552 |
var dict = (from key in keys |
553 |
where key.StartsWith(metaPrefix) |
554 |
let name = key.Substring(metaPrefix.Length) |
555 |
select new { Name = name, Value = ResponseHeaders[key] }) |
556 |
.ToDictionary(t => t.Name, t => t.Value); |
557 |
return dict; |
558 |
} |
559 |
} |
560 |
|
561 |
public class RetryException:Exception |
562 |
{ |
563 |
public RetryException() |
564 |
:base() |
565 |
{ |
566 |
|
567 |
} |
568 |
|
569 |
public RetryException(string message) |
570 |
:base(message) |
571 |
{ |
572 |
|
573 |
} |
574 |
|
575 |
public RetryException(string message,Exception innerException) |
576 |
:base(message,innerException) |
577 |
{ |
578 |
|
579 |
} |
580 |
|
581 |
public RetryException(SerializationInfo info,StreamingContext context) |
582 |
:base(info,context) |
583 |
{ |
584 |
|
585 |
} |
586 |
} |
587 |
} |