2 /* -----------------------------------------------------------------------
\r
3 * <copyright file="CloudFilesClient.cs" company="GRNet">
\r
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
\r
7 * Redistribution and use in source and binary forms, with or
\r
8 * without modification, are permitted provided that the following
\r
9 * conditions are met:
\r
11 * 1. Redistributions of source code must retain the above
\r
12 * copyright notice, this list of conditions and the following
\r
15 * 2. Redistributions in binary form must reproduce the above
\r
16 * copyright notice, this list of conditions and the following
\r
17 * disclaimer in the documentation and/or other materials
\r
18 * provided with the distribution.
\r
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
\r
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
\r
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
\r
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
\r
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
\r
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
\r
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
\r
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
\r
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
\r
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
\r
32 * POSSIBILITY OF SUCH DAMAGE.
\r
34 * The views and conclusions contained in the software and
\r
35 * documentation are those of the authors and should not be
\r
36 * interpreted as representing official policies, either expressed
\r
37 * or implied, of GRNET S.A.
\r
39 * -----------------------------------------------------------------------
\r
43 // **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
\r
45 // The class provides methods to upload/download files, delete files, manage containers
\r
49 using System.Collections.Generic;
\r
50 using System.Collections.Specialized;
\r
51 using System.ComponentModel.Composition;
\r
52 using System.Diagnostics;
\r
53 using System.Diagnostics.Contracts;
\r
56 using System.Net.Http;
\r
57 using System.Reflection;
\r
58 using System.Threading;
\r
59 using System.Threading.Tasks;
\r
60 using Newtonsoft.Json;
\r
61 using Pithos.Interfaces;
\r
64 namespace Pithos.Network
\r
66 [Export(typeof(ICloudClient))]
\r
67 public class CloudFilesClient:ICloudClient
\r
69 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
\r
71 //CloudFilesClient uses *_baseClient* internally to communicate with the server
\r
72 //RestClient provides a REST-friendly interface over the standard WebClient.
\r
73 private RestClient _baseClient;
\r
75 private HttpClient _baseHttpClient;
\r
78 //During authentication the client provides a UserName
\r
79 public string UserName { get; set; }
\r
81 //and and ApiKey to the server
\r
82 public string ApiKey { get; set; }
\r
84 //And receives an authentication Token. This token must be provided in ALL other operations,
\r
85 //in the X-Auth-Token header
\r
86 private string _token;
\r
87 private readonly string _emptyGuid = Guid.Empty.ToString();
\r
88 private readonly Uri _emptyUri = new Uri("",UriKind.Relative);
\r
93 get { return _token; }
\r
97 _baseClient.Headers["X-Auth-Token"] = value;
\r
101 //The client also receives a StorageUrl after authentication. All subsequent operations must
\r
103 public Uri StorageUrl { get; set; }
\r
106 public Uri RootAddressUri { get; set; }
\r
108 /* private WebProxy _proxy;
\r
109 public WebProxy Proxy
\r
111 get { return _proxy; }
\r
115 if (_baseClient != null)
\r
116 _baseClient.Proxy = value;
\r
121 /* private Uri _proxy;
\r
124 get { return _proxy; }
\r
128 if (_baseClient != null)
\r
129 _baseClient.Proxy = new WebProxy(value);
\r
133 public double DownloadPercentLimit { get; set; }
\r
134 public double UploadPercentLimit { get; set; }
\r
136 public string AuthenticationUrl { get; set; }
\r
139 public string VersionPath
\r
141 get { return UsePithos ? "v1" : "v1.0"; }
\r
144 public bool UsePithos { get; set; }
\r
148 public CloudFilesClient(string userName, string apiKey)
\r
150 UserName = userName;
\r
154 public CloudFilesClient(AccountInfo accountInfo)
\r
156 if (accountInfo==null)
\r
157 throw new ArgumentNullException("accountInfo");
\r
158 Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
\r
159 Contract.Ensures(StorageUrl != null);
\r
160 Contract.Ensures(_baseClient != null);
\r
161 Contract.Ensures(RootAddressUri != null);
\r
162 Contract.EndContractBlock();
\r
164 _baseClient = new RestClient
\r
166 BaseAddress = accountInfo.StorageUri.ToString(),
\r
170 StorageUrl = accountInfo.StorageUri;
\r
171 Token = accountInfo.Token;
\r
172 UserName = accountInfo.UserName;
\r
174 //Get the root address (StorageUrl without the account)
\r
175 var storageUrl = StorageUrl.AbsoluteUri;
\r
176 var usernameIndex = storageUrl.LastIndexOf(UserName);
\r
177 var rootUrl = storageUrl.Substring(0, usernameIndex);
\r
178 RootAddressUri = new Uri(rootUrl);
\r
180 var httpClientHandler = new HttpClientHandler
\r
182 AllowAutoRedirect = true,
\r
183 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
\r
188 _baseHttpClient = new HttpClient(httpClientHandler)
\r
190 BaseAddress = StorageUrl,
\r
191 Timeout = TimeSpan.FromSeconds(30)
\r
193 _baseHttpClient.DefaultRequestHeaders.Add("X-Auth-Token", Token);
\r
199 private static void AssertStatusOK(HttpResponseMessage response, string message)
\r
201 var statusCode = response.StatusCode;
\r
202 if (statusCode >= HttpStatusCode.BadRequest)
\r
203 throw new WebException(String.Format("{0} with code {1} - {2}", message, statusCode, response.ReasonPhrase));
\r
206 public AccountInfo Authenticate()
\r
208 if (String.IsNullOrWhiteSpace(UserName))
\r
209 throw new InvalidOperationException("UserName is empty");
\r
210 if (String.IsNullOrWhiteSpace(ApiKey))
\r
211 throw new InvalidOperationException("ApiKey is empty");
\r
212 if (String.IsNullOrWhiteSpace(AuthenticationUrl))
\r
213 throw new InvalidOperationException("AuthenticationUrl is empty");
\r
214 Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
\r
215 Contract.Ensures(StorageUrl != null);
\r
216 Contract.Ensures(_baseClient != null);
\r
217 Contract.Ensures(RootAddressUri != null);
\r
218 Contract.EndContractBlock();
\r
221 Log.InfoFormat("[AUTHENTICATE] Start for {0}", UserName);
\r
223 var groups = new List<Group>();
\r
225 var httpClientHandler = new HttpClientHandler
\r
227 AllowAutoRedirect = true,
\r
228 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
\r
229 UseCookies = true,
\r
232 using (var authClient = new HttpClient(httpClientHandler){ BaseAddress = new Uri(AuthenticationUrl),Timeout=TimeSpan.FromSeconds(30) })
\r
233 //using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
\r
235 /* if (Proxy != null)
\r
236 authClient.Proxy = Proxy;*/
\r
238 //Contract.Assume(authClient.DefaultRequestHeaders != null);
\r
240 authClient.DefaultRequestHeaders.Add("X-Auth-User", UserName);
\r
241 authClient.DefaultRequestHeaders.Add("X-Auth-Key", ApiKey);
\r
243 //Func<Task<HttpResponseMessage>> call = () => ;
\r
247 using (var response = authClient.GetAsyncWithRetries(new Uri(VersionPath, UriKind.Relative),3).Result) // .DownloadStringWithRetryRelative(new Uri(VersionPath, UriKind.Relative), 3);
\r
249 AssertStatusOK(response,"Authentication failed");
\r
251 storageUrl = response.Headers.GetValues("X-Storage-Url").First();
\r
252 if (String.IsNullOrWhiteSpace(storageUrl))
\r
253 throw new InvalidOperationException("Failed to obtain storage url");
\r
255 token = response.Headers.GetValues("X-Auth-Token").First();
\r
256 if (String.IsNullOrWhiteSpace(token))
\r
257 throw new InvalidOperationException("Failed to obtain token url");
\r
262 _baseClient = new RestClient
\r
264 BaseAddress = storageUrl,
\r
270 StorageUrl = new Uri(storageUrl);
\r
276 //Get the root address (StorageUrl without the account)
\r
277 var usernameIndex=storageUrl.LastIndexOf(UserName);
\r
278 var rootUrl = storageUrl.Substring(0, usernameIndex);
\r
279 RootAddressUri = new Uri(rootUrl);
\r
282 _baseHttpClient = new HttpClient(httpClientHandler)
\r
284 BaseAddress = StorageUrl,
\r
285 Timeout = TimeSpan.FromSeconds(30)
\r
287 _baseHttpClient.DefaultRequestHeaders.Add("X-Auth-Token", token);
\r
289 /* var keys = authClient.ResponseHeaders.AllKeys.AsQueryable();
\r
290 groups = (from key in keys
\r
291 where key.StartsWith("X-Account-Group-")
\r
292 let name = key.Substring(16)
\r
293 select new Group(name, authClient.ResponseHeaders[key]))
\r
299 Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
\r
300 Debug.Assert(_baseClient!=null);
\r
302 return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};
\r
306 private static void TraceStart(string method, Uri actualAddress)
\r
308 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
\r
311 private async Task<string> GetString(Uri targetUri, string errorMessage,DateTime? since=null)
\r
313 TraceStart("GET",targetUri);
\r
314 var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
\r
315 if (since.HasValue)
\r
317 request.Headers.IfModifiedSince = since.Value;
\r
319 //Func<Task<HttpResponseMessage>> call = () => _baseHttpClient.SendAsync(request);
\r
320 using (var response = await _baseHttpClient.SendAsyncWithRetries(request,3))
\r
322 AssertStatusOK(response, errorMessage);
\r
324 if (response.StatusCode == HttpStatusCode.NoContent)
\r
325 return String.Empty;
\r
327 var content = await response.Content.ReadAsStringAsync();
\r
332 public IList<ContainerInfo> ListContainers(string account)
\r
335 var targetUrl = GetTargetUrl(account);
\r
336 var targetUri=new Uri(String.Format("{0}?format=json",targetUrl));
\r
337 var result = GetString(targetUri, "List Containers failed").Result;
\r
338 if (String.IsNullOrWhiteSpace(result))
\r
339 return new List<ContainerInfo>();
\r
340 var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(result);
\r
341 foreach (var info in infos)
\r
343 info.Account = account;
\r
346 /* using (var client = new RestClient(_baseClient))
\r
348 if (!String.IsNullOrWhiteSpace(account))
\r
349 client.BaseAddress = GetAccountUrl(account);
\r
351 client.Parameters.Clear();
\r
352 client.Parameters.Add("format", "json");
\r
353 var content = client.DownloadStringWithRetryRelative(_emptyUri, 3);
\r
354 client.AssertStatusOK("List Containers failed");
\r
356 if (client.StatusCode == HttpStatusCode.NoContent)
\r
357 return new List<ContainerInfo>();
\r
358 var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(content);
\r
360 foreach (var info in infos)
\r
362 info.Account = account;
\r
369 private string GetAccountUrl(string account)
\r
371 return RootAddressUri.Combine(account).AbsoluteUri;
\r
374 public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null)
\r
376 using (ThreadContext.Stacks["Share"].Push("List Accounts"))
\r
378 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
380 var targetUri = new Uri(String.Format("{0}?format=json", RootAddressUri), UriKind.Absolute);
\r
381 var content=GetString(targetUri, "ListSharingAccounts failed", since).Result;
\r
383 //If the result is empty, return an empty list,
\r
384 var infos = String.IsNullOrWhiteSpace(content)
\r
385 ? new List<ShareAccountInfo>()
\r
386 //Otherwise deserialize the account list into a list of ShareAccountInfos
\r
387 : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
\r
389 Log.DebugFormat("END");
\r
392 using (var client = new RestClient(_baseClient))
\r
394 client.Parameters.Clear();
\r
395 client.Parameters.Add("format", "json");
\r
396 client.IfModifiedSince = since;
\r
398 //Extract the username from the base address
\r
399 client.BaseAddress = RootAddressUri.AbsoluteUri;
\r
401 var content = client.DownloadStringWithRetryRelative(_emptyUri, 3);
\r
403 client.AssertStatusOK("ListSharingAccounts failed");
\r
405 //If the result is empty, return an empty list,
\r
406 var infos = String.IsNullOrWhiteSpace(content)
\r
407 ? new List<ShareAccountInfo>()
\r
408 //Otherwise deserialize the account list into a list of ShareAccountInfos
\r
409 : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
\r
411 Log.DebugFormat("END");
\r
420 /// Request listing of all objects in a container modified since a specific time.
\r
421 /// If the *since* value is missing, return all objects
\r
423 /// <param name="knownContainers">Use the since variable only for the containers listed in knownContainers. Unknown containers are considered new
\r
424 /// and should be polled anyway
\r
426 /// <param name="since"></param>
\r
427 /// <returns></returns>
\r
428 public IList<ObjectInfo> ListSharedObjects(HashSet<string> knownContainers,DateTime? since = null )
\r
431 using (ThreadContext.Stacks["Share"].Push("List Objects"))
\r
433 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
434 //'since' is not used here because we need to have ListObjects return a NoChange result
\r
435 //for all shared accounts,containers
\r
437 Func<ContainerInfo, string> getKey = c => String.Format("{0}\\{1}", c.Account, c.Name);
\r
439 var accounts = ListSharingAccounts();
\r
440 var containers = (from account in accounts
\r
441 let conts = ListContainers(account.name)
\r
442 from container in conts
\r
443 select container).ToList();
\r
444 var items = from container in containers
\r
445 let actualSince=knownContainers.Contains(getKey(container))?since:null
\r
446 select ListObjects(container.Account , container.Name, actualSince);
\r
447 var objects=items.SelectMany(r=> r).ToList();
\r
450 //Check parents recursively up to (but not including) the container.
\r
451 //If parents are missing, add them to the list
\r
452 //Need function to calculate all parent URLs
\r
453 objects = AddMissingParents(objects);
\r
455 //Store any new containers
\r
456 foreach (var container in containers)
\r
458 knownContainers.Add(getKey(container));
\r
463 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
468 private List<ObjectInfo> AddMissingParents(List<ObjectInfo> objects)
\r
470 //TODO: Remove short-circuit when we decide to use Missing Parents functionality
\r
473 var existingUris = objects.ToDictionary(o => o.Uri, o => o);
\r
474 foreach (var objectInfo in objects)
\r
476 //Can be null when retrieving objects to show in selective sync
\r
477 if (objectInfo.Name == null)
\r
480 //No need to unescape here, the parts will be used to create new ObjectInfos
\r
481 var parts = objectInfo.Name.ToString().Split(new[]{'/'},StringSplitOptions.RemoveEmptyEntries);
\r
482 //If there is no parent, skip
\r
483 if (parts.Length == 1)
\r
485 var baseParts = new[]
\r
487 objectInfo.Uri.Host, objectInfo.Uri.Segments[1].TrimEnd('/'),objectInfo.Account,objectInfo.Container.ToString()
\r
489 for (var partIdx = 0; partIdx < parts.Length - 1; partIdx++)
\r
491 var nameparts = parts.Range(0, partIdx).ToArray();
\r
492 var parentName= String.Join("/", nameparts);
\r
494 var parentParts = baseParts.Concat(nameparts);
\r
495 var parentUrl = objectInfo.Uri.Scheme+ "://" + String.Join("/", parentParts);
\r
497 var parentUri = new Uri(parentUrl, UriKind.Absolute);
\r
499 ObjectInfo existingInfo;
\r
500 if (!existingUris.TryGetValue(parentUri,out existingInfo))
\r
502 var h = parentUrl.GetHashCode();
\r
503 var reverse = new string(parentUrl.Reverse().ToArray());
\r
504 var rh = reverse.GetHashCode();
\r
505 var b1 = BitConverter.GetBytes(h);
\r
506 var b2 = BitConverter.GetBytes(rh);
\r
507 var g = new Guid(0,0,0,b1.Concat(b2).ToArray());
\r
510 existingUris[parentUri] = new ObjectInfo
\r
512 Account = objectInfo.Account,
\r
513 Container = objectInfo.Container,
\r
514 Content_Type = ObjectInfo.CONTENT_TYPE_DIRECTORY,
\r
515 ETag = Signature.MERKLE_EMPTY,
\r
516 X_Object_Hash = Signature.MERKLE_EMPTY,
\r
517 Name=new Uri(parentName,UriKind.Relative),
\r
518 StorageUri=objectInfo.StorageUri,
\r
520 UUID=g.ToString(),
\r
525 return existingUris.Values.ToList();
\r
528 public void SetTags(ObjectInfo target,IDictionary<string,string> tags)
\r
530 if (String.IsNullOrWhiteSpace(Token))
\r
531 throw new InvalidOperationException("The Token is not set");
\r
532 if (StorageUrl == null)
\r
533 throw new InvalidOperationException("The StorageUrl is not set");
\r
534 if (target == null)
\r
535 throw new ArgumentNullException("target");
\r
536 Contract.EndContractBlock();
\r
538 using (ThreadContext.Stacks["Share"].Push("Share Object"))
\r
540 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
542 using (var client = new RestClient(_baseClient))
\r
545 client.BaseAddress = GetAccountUrl(target.Account);
\r
547 client.Parameters.Clear();
\r
548 client.Parameters.Add("update", "");
\r
550 foreach (var tag in tags)
\r
552 var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
\r
553 client.Headers.Add(headerTag, tag.Value);
\r
556 client.DownloadStringWithRetryRelative(target.Container, 3);
\r
559 client.AssertStatusOK("SetTags failed");
\r
560 //If the status is NOT ACCEPTED we have a problem
\r
561 if (client.StatusCode != HttpStatusCode.Accepted)
\r
563 Log.Error("Failed to set tags");
\r
564 throw new Exception("Failed to set tags");
\r
567 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
574 public void ShareObject(string account, Uri container, Uri objectName, string shareTo, bool read, bool write)
\r
576 if (String.IsNullOrWhiteSpace(Token))
\r
577 throw new InvalidOperationException("The Token is not set");
\r
578 if (StorageUrl==null)
\r
579 throw new InvalidOperationException("The StorageUrl is not set");
\r
580 if (container==null)
\r
581 throw new ArgumentNullException("container");
\r
582 if (container.IsAbsoluteUri)
\r
583 throw new ArgumentException("container");
\r
584 if (objectName==null)
\r
585 throw new ArgumentNullException("objectName");
\r
586 if (objectName.IsAbsoluteUri)
\r
587 throw new ArgumentException("objectName");
\r
588 if (String.IsNullOrWhiteSpace(account))
\r
589 throw new ArgumentNullException("account");
\r
590 if (String.IsNullOrWhiteSpace(shareTo))
\r
591 throw new ArgumentNullException("shareTo");
\r
592 Contract.EndContractBlock();
\r
594 using (ThreadContext.Stacks["Share"].Push("Share Object"))
\r
596 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
598 using (var client = new RestClient(_baseClient))
\r
601 client.BaseAddress = GetAccountUrl(account);
\r
603 client.Parameters.Clear();
\r
604 client.Parameters.Add("format", "json");
\r
606 string permission = "";
\r
608 permission = String.Format("write={0}", shareTo);
\r
610 permission = String.Format("read={0}", shareTo);
\r
611 client.Headers.Add("X-Object-Sharing", permission);
\r
613 var content = client.DownloadStringWithRetryRelative(container, 3);
\r
615 client.AssertStatusOK("ShareObject failed");
\r
617 //If the result is empty, return an empty list,
\r
618 var infos = String.IsNullOrWhiteSpace(content)
\r
619 ? new List<ObjectInfo>()
\r
620 //Otherwise deserialize the object list into a list of ObjectInfos
\r
621 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
\r
623 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
630 public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
\r
632 if (accountInfo==null)
\r
633 throw new ArgumentNullException("accountInfo");
\r
634 Contract.EndContractBlock();
\r
636 using (ThreadContext.Stacks["Account"].Push("GetPolicies"))
\r
638 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
640 if (_baseClient == null)
\r
642 _baseClient = new RestClient
\r
644 BaseAddress = accountInfo.StorageUri.ToString(),
\r
650 using (var client = new RestClient(_baseClient))
\r
652 if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
\r
653 client.BaseAddress = GetAccountUrl(accountInfo.UserName);
\r
655 client.Parameters.Clear();
\r
656 client.Parameters.Add("format", "json");
\r
657 client.Head(_emptyUri, 3);
\r
659 var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
\r
660 var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
\r
663 if (long.TryParse(quotaValue, out quota))
\r
664 accountInfo.Quota = quota;
\r
665 if (long.TryParse(bytesValue, out bytes))
\r
666 accountInfo.BytesUsed = bytes;
\r
668 return accountInfo;
\r
675 public void UpdateMetadata(ObjectInfo objectInfo)
\r
677 if (objectInfo == null)
\r
678 throw new ArgumentNullException("objectInfo");
\r
679 Contract.EndContractBlock();
\r
681 using (ThreadContext.Stacks["Objects"].Push("UpdateMetadata"))
\r
683 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
686 using(var client=new RestClient(_baseClient))
\r
689 client.BaseAddress = GetAccountUrl(objectInfo.Account);
\r
691 client.Parameters.Clear();
\r
695 foreach (var tag in objectInfo.Tags)
\r
697 var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
\r
698 client.Headers.Add(headerTag, tag.Value);
\r
703 var permissions=objectInfo.GetPermissionString();
\r
704 client.SetNonEmptyHeaderValue("X-Object-Sharing",permissions);
\r
706 client.SetNonEmptyHeaderValue("Content-Disposition",objectInfo.ContendDisposition);
\r
707 client.SetNonEmptyHeaderValue("Content-Encoding",objectInfo.ContentEncoding);
\r
708 client.SetNonEmptyHeaderValue("X-Object-Manifest",objectInfo.Manifest);
\r
709 var isPublic = objectInfo.IsPublic.ToString().ToLower();
\r
710 client.Headers.Add("X-Object-Public", isPublic);
\r
713 /*var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
\r
714 uriBuilder.Query = "update=";
\r
715 var uri = uriBuilder.Uri.MakeRelativeUri(this.RootAddressUri);*/
\r
716 var address = String.Format("{0}/{1}?update=",objectInfo.Container, objectInfo.Name);
\r
717 client.PostWithRetry(new Uri(address,UriKind.Relative),"application/xml");
\r
719 //client.UploadValues(uri,new NameValueCollection());
\r
722 client.AssertStatusOK("UpdateMetadata failed");
\r
723 //If the status is NOT ACCEPTED or OK we have a problem
\r
724 if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
\r
726 Log.Error("Failed to update metadata");
\r
727 throw new Exception("Failed to update metadata");
\r
730 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
736 public void UpdateMetadata(ContainerInfo containerInfo)
\r
738 if (containerInfo == null)
\r
739 throw new ArgumentNullException("containerInfo");
\r
740 Contract.EndContractBlock();
\r
742 using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata"))
\r
744 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
747 using(var client=new RestClient(_baseClient))
\r
750 client.BaseAddress = GetAccountUrl(containerInfo.Account);
\r
752 client.Parameters.Clear();
\r
756 foreach (var tag in containerInfo.Tags)
\r
758 var headerTag = String.Format("X-Container-Meta-{0}", tag.Key);
\r
759 client.Headers.Add(headerTag, tag.Value);
\r
764 foreach (var policy in containerInfo.Policies)
\r
766 var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key);
\r
767 client.Headers.Add(headerPolicy, policy.Value);
\r
771 var uriBuilder = client.GetAddressBuilder(containerInfo.Name,_emptyUri);
\r
772 var uri = uriBuilder.Uri;
\r
774 client.UploadValues(uri,new NameValueCollection());
\r
777 client.AssertStatusOK("UpdateMetadata failed");
\r
778 //If the status is NOT ACCEPTED or OK we have a problem
\r
779 if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
\r
781 Log.Error("Failed to update metadata");
\r
782 throw new Exception("Failed to update metadata");
\r
785 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
794 public IList<ObjectInfo> ListObjects(string account, Uri container, DateTime? since = null)
\r
796 if (container==null)
\r
797 throw new ArgumentNullException("container");
\r
798 if (container.IsAbsoluteUri)
\r
799 throw new ArgumentException("container");
\r
800 Contract.EndContractBlock();
\r
802 using (ThreadContext.Stacks["Objects"].Push("List"))
\r
804 /*if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
806 var targetUrl = String.IsNullOrWhiteSpace(account)
\r
807 ? _baseHttpClient.BaseAddress.ToString()
\r
808 : GetAccountUrl(account);
\r
809 var targetUri = new Uri(String.Format("{0}?format=json", targetUrl));
\r
810 var result = GetString(targetUri, "ListObjects failed",since).Result;
\r
812 if (String.IsNullOrWhiteSpace(result))
\r
813 return new[]{new NoModificationInfo(account,container)};
\r
814 //If the result is empty, return an empty list,
\r
815 var infos = String.IsNullOrWhiteSpace(result)
\r
816 ? new List<ObjectInfo>()
\r
817 //Otherwise deserialize the object list into a list of ObjectInfos
\r
818 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(result);
\r
820 foreach (var info in infos)
\r
822 info.Container = container;
\r
823 info.Account = account;
\r
824 info.StorageUri = StorageUrl;
\r
826 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
829 var containerUri = GetTargetUri(account).Combine(container);
\r
830 var targetUri = new Uri(String.Format("{0}?format=json", containerUri), UriKind.Absolute);
\r
831 var content = GetString(targetUri, "ListObjects failed", since).Result;
\r
833 //304 will result in an empty string. Empty containers return an empty json array
\r
834 if (String.IsNullOrWhiteSpace(content))
\r
835 return new[] {new NoModificationInfo(account, container)};
\r
837 //If the result is empty, return an empty list,
\r
838 var infos = String.IsNullOrWhiteSpace(content)
\r
839 ? new List<ObjectInfo>()
\r
840 //Otherwise deserialize the object list into a list of ObjectInfos
\r
841 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
\r
843 foreach (var info in infos)
\r
845 info.Container = container;
\r
846 info.Account = account;
\r
847 info.StorageUri = StorageUrl;
\r
849 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
852 using (var client = new RestClient(_baseClient))
\r
854 if (!String.IsNullOrWhiteSpace(account))
\r
855 client.BaseAddress = GetAccountUrl(account);
\r
857 client.Parameters.Clear();
\r
858 client.Parameters.Add("format", "json");
\r
859 client.IfModifiedSince = since;
\r
860 var content = client.DownloadStringWithRetryRelative(container, 3);
\r
862 client.AssertStatusOK("ListObjects failed");
\r
864 if (client.StatusCode == HttpStatusCode.NotModified)
\r
865 return new[] {new NoModificationInfo(account, container)};
\r
866 //If the result is empty, return an empty list,
\r
867 var infos = String.IsNullOrWhiteSpace(content)
\r
868 ? new List<ObjectInfo>()
\r
869 //Otherwise deserialize the object list into a list of ObjectInfos
\r
870 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
\r
872 foreach (var info in infos)
\r
874 info.Container = container;
\r
875 info.Account = account;
\r
876 info.StorageUri = StorageUrl;
\r
878 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
885 public IList<ObjectInfo> ListObjects(string account, Uri container, Uri folder, DateTime? since = null)
\r
887 if (container==null)
\r
888 throw new ArgumentNullException("container");
\r
889 if (container.IsAbsoluteUri)
\r
890 throw new ArgumentException("container");
\r
892 if (String.IsNullOrWhiteSpace(folder))
\r
893 throw new ArgumentNullException("folder");
\r
895 Contract.EndContractBlock();
\r
897 using (ThreadContext.Stacks["Objects"].Push("List"))
\r
899 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
901 var containerUri = GetTargetUri(account).Combine(container);
\r
902 var targetUri = new Uri(String.Format("{0}?format=json&path={1}", containerUri,folder), UriKind.Absolute);
\r
903 var content = GetString(targetUri, "ListObjects failed", since).Result;
\r
905 //304 will result in an empty string. Empty containers return an empty json array
\r
906 if (String.IsNullOrWhiteSpace(content))
\r
907 return new[] { new NoModificationInfo(account, container) };
\r
910 var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
\r
911 foreach (var info in infos)
\r
913 info.Account = account;
\r
914 if (info.Container == null)
\r
915 info.Container = container;
\r
916 info.StorageUri = StorageUrl;
\r
918 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
921 using (var client = new RestClient(_baseClient))
\r
923 if (!String.IsNullOrWhiteSpace(account))
\r
924 client.BaseAddress = GetAccountUrl(account);
\r
926 client.Parameters.Clear();
\r
927 client.Parameters.Add("format", "json");
\r
928 client.Parameters.Add("path", folder.ToString());
\r
929 client.IfModifiedSince = since;
\r
930 var content = client.DownloadStringWithRetryRelative(container, 3);
\r
931 client.AssertStatusOK("ListObjects failed");
\r
933 if (client.StatusCode==HttpStatusCode.NotModified)
\r
934 return new[]{new NoModificationInfo(account,container,folder)};
\r
936 var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
\r
937 foreach (var info in infos)
\r
939 info.Account = account;
\r
940 if (info.Container == null)
\r
941 info.Container = container;
\r
942 info.StorageUri = StorageUrl;
\r
944 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
952 public bool ContainerExists(string account, Uri container)
\r
954 if (container==null)
\r
955 throw new ArgumentNullException("container", "The container property can't be empty");
\r
956 if (container.IsAbsoluteUri)
\r
957 throw new ArgumentException( "The container must be relative","container");
\r
958 Contract.EndContractBlock();
\r
960 using (ThreadContext.Stacks["Containters"].Push("Exists"))
\r
962 if (Log.IsDebugEnabled) Log.DebugFormat("START");
\r
964 var targetUri = GetTargetUri(account).Combine(container);
\r
966 using (var response = _baseHttpClient.HeadAsyncWithRetries(targetUri, 3).Result)
\r
970 switch (response.StatusCode)
\r
972 case HttpStatusCode.OK:
\r
973 case HttpStatusCode.NoContent:
\r
976 case HttpStatusCode.NotFound:
\r
980 throw CreateWebException("ContainerExists", response.StatusCode);
\r
982 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
987 using (var client = new RestClient(_baseClient))
\r
989 if (!String.IsNullOrWhiteSpace(account))
\r
990 client.BaseAddress = GetAccountUrl(account);
\r
992 client.Parameters.Clear();
\r
993 client.Head(container, 3);
\r
996 switch (client.StatusCode)
\r
998 case HttpStatusCode.OK:
\r
999 case HttpStatusCode.NoContent:
\r
1002 case HttpStatusCode.NotFound:
\r
1006 throw CreateWebException("ContainerExists", client.StatusCode);
\r
1008 if (Log.IsDebugEnabled) Log.DebugFormat("END");
\r
1017 private Uri GetTargetUri(string account)
\r
1019 return new Uri(GetTargetUrl(account),UriKind.Absolute);
\r
1022 private string GetTargetUrl(string account)
\r
1024 return String.IsNullOrWhiteSpace(account)
\r
1025 ? _baseHttpClient.BaseAddress.ToString()
\r
1026 : GetAccountUrl(account);
\r
1029 public bool ObjectExists(string account, Uri container, Uri objectName)
\r
1031 if (container == null)
\r
1032 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1033 if (container.IsAbsoluteUri)
\r
1034 throw new ArgumentException("The container must be relative","container");
\r
1035 if (objectName == null)
\r
1036 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1037 if (objectName.IsAbsoluteUri)
\r
1038 throw new ArgumentException("The objectName must be relative","objectName");
\r
1039 Contract.EndContractBlock();
\r
1041 var targetUri=GetTargetUri(account).Combine(container).Combine(objectName);
\r
1043 using (var response = _baseHttpClient.HeadAsyncWithRetries(targetUri, 3).Result)
\r
1045 switch (response.StatusCode)
\r
1047 case HttpStatusCode.OK:
\r
1048 case HttpStatusCode.NoContent:
\r
1050 case HttpStatusCode.NotFound:
\r
1053 throw CreateWebException("ObjectExists", response.StatusCode);
\r
1058 using (var client = new RestClient(_baseClient))
\r
1060 if (!String.IsNullOrWhiteSpace(account))
\r
1061 client.BaseAddress = GetAccountUrl(account);
\r
1063 client.Parameters.Clear();
\r
1064 client.Head(container.Combine(objectName), 3);
\r
1066 switch (client.StatusCode)
\r
1068 case HttpStatusCode.OK:
\r
1069 case HttpStatusCode.NoContent:
\r
1071 case HttpStatusCode.NotFound:
\r
1074 throw CreateWebException("ObjectExists", client.StatusCode);
\r
1081 public ObjectInfo GetObjectInfo(string account, Uri container, Uri objectName)
\r
1083 if (container == null)
\r
1084 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1085 if (container.IsAbsoluteUri)
\r
1086 throw new ArgumentException("The container must be relative","container");
\r
1087 if (objectName == null)
\r
1088 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1089 if (objectName.IsAbsoluteUri)
\r
1090 throw new ArgumentException("The objectName must be relative","objectName");
\r
1091 Contract.EndContractBlock();
\r
1093 using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
\r
1096 using (var client = new RestClient(_baseClient))
\r
1098 if (!String.IsNullOrWhiteSpace(account))
\r
1099 client.BaseAddress = GetAccountUrl(account);
\r
1102 client.Parameters.Clear();
\r
1104 client.Head(container.Combine(objectName), 3);
\r
1106 if (client.TimedOut)
\r
1107 return ObjectInfo.Empty;
\r
1109 switch (client.StatusCode)
\r
1111 case HttpStatusCode.OK:
\r
1112 case HttpStatusCode.NoContent:
\r
1113 var keys = client.ResponseHeaders.AllKeys.AsQueryable();
\r
1114 var tags = client.GetMeta("X-Object-Meta-");
\r
1115 var extensions = (from key in keys
\r
1116 where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
\r
1117 select new {Name = key, Value = client.ResponseHeaders[key]})
\r
1118 .ToDictionary(t => t.Name, t => t.Value);
\r
1120 var permissions=client.GetHeaderValue("X-Object-Sharing", true);
\r
1123 var info = new ObjectInfo
\r
1125 Account = account,
\r
1126 Container = container,
\r
1127 Name = objectName,
\r
1128 ETag = client.GetHeaderValue("ETag"),
\r
1129 UUID=client.GetHeaderValue("X-Object-UUID"),
\r
1130 X_Object_Hash = client.GetHeaderValue("X-Object-Hash"),
\r
1131 Content_Type = client.GetHeaderValue("Content-Type"),
\r
1132 Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
\r
1134 Last_Modified = client.LastModified,
\r
1135 Extensions = extensions,
\r
1136 ContentEncoding=client.GetHeaderValue("Content-Encoding",true),
\r
1137 ContendDisposition = client.GetHeaderValue("Content-Disposition",true),
\r
1138 Manifest=client.GetHeaderValue("X-Object-Manifest",true),
\r
1139 PublicUrl=client.GetHeaderValue("X-Object-Public",true),
\r
1140 StorageUri=StorageUrl,
\r
1142 info.SetPermissions(permissions);
\r
1144 case HttpStatusCode.NotFound:
\r
1145 return ObjectInfo.Empty;
\r
1147 throw new WebException(
\r
1148 String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
\r
1149 objectName, client.StatusCode));
\r
1153 catch (RetryException)
\r
1155 Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.",objectName);
\r
1156 return ObjectInfo.Empty;
\r
1158 catch (WebException e)
\r
1161 String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
\r
1162 objectName, client.StatusCode), e);
\r
1172 public void CreateFolder(string account, Uri container, Uri folder)
\r
1174 if (container == null)
\r
1175 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1176 if (container.IsAbsoluteUri)
\r
1177 throw new ArgumentException("The container must be relative","container");
\r
1178 if (folder == null)
\r
1179 throw new ArgumentNullException("folder", "The objectName property can't be empty");
\r
1180 if (folder.IsAbsoluteUri)
\r
1181 throw new ArgumentException("The objectName must be relative","folder");
\r
1182 Contract.EndContractBlock();
\r
1184 var folderUri=container.Combine(folder);
\r
1185 var targetUri = GetTargetUri(account).Combine(folderUri);
\r
1186 var message = new HttpRequestMessage(HttpMethod.Put, targetUri);
\r
1188 message.Headers.Add("Content-Type", ObjectInfo.CONTENT_TYPE_DIRECTORY);
\r
1189 message.Headers.Add("Content-Length", "0");
\r
1190 using (var response = _baseHttpClient.SendAsyncWithRetries(message, 3).Result)
\r
1192 if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.Accepted)
\r
1193 throw CreateWebException("CreateFolder", response.StatusCode);
\r
1196 using (var client = new RestClient(_baseClient))
\r
1198 if (!String.IsNullOrWhiteSpace(account))
\r
1199 client.BaseAddress = GetAccountUrl(account);
\r
1201 client.Parameters.Clear();
\r
1202 client.Headers.Add("Content-Type", ObjectInfo.CONTENT_TYPE_DIRECTORY);
\r
1203 client.Headers.Add("Content-Length", "0");
\r
1204 client.PutWithRetry(folderUri, 3);
\r
1206 if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
\r
1207 throw CreateWebException("CreateFolder", client.StatusCode);
\r
1214 public ContainerInfo GetContainerInfo(string account, Uri container)
\r
1216 if (container == null)
\r
1217 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1218 if (container.IsAbsoluteUri)
\r
1219 throw new ArgumentException("The container must be relative","container");
\r
1220 Contract.EndContractBlock();
\r
1222 using (var client = new RestClient(_baseClient))
\r
1224 if (!String.IsNullOrWhiteSpace(account))
\r
1225 client.BaseAddress = GetAccountUrl(account);
\r
1227 client.Head(container);
\r
1228 switch (client.StatusCode)
\r
1230 case HttpStatusCode.OK:
\r
1231 case HttpStatusCode.NoContent:
\r
1232 var tags = client.GetMeta("X-Container-Meta-");
\r
1233 var policies = client.GetMeta("X-Container-Policy-");
\r
1235 var containerInfo = new ContainerInfo
\r
1239 StorageUrl=StorageUrl.ToString(),
\r
1241 long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
\r
1242 Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
\r
1243 BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
\r
1244 BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
\r
1245 Last_Modified=client.LastModified,
\r
1251 return containerInfo;
\r
1252 case HttpStatusCode.NotFound:
\r
1253 return ContainerInfo.Empty;
\r
1255 throw CreateWebException("GetContainerInfo", client.StatusCode);
\r
1260 public void CreateContainer(string account, Uri container)
\r
1262 if (container == null)
\r
1263 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1264 if (container.IsAbsoluteUri)
\r
1265 throw new ArgumentException("The container must be relative","container");
\r
1266 Contract.EndContractBlock();
\r
1268 var targetUri=GetTargetUri(account).Combine(container);
\r
1269 var message = new HttpRequestMessage(HttpMethod.Put, targetUri);
\r
1270 message.Headers.Add("Content-Length", "0");
\r
1271 using (var response = _baseHttpClient.SendAsyncWithRetries(message, 3).Result)
\r
1273 var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
\r
1274 if (!expectedCodes.Contains(response.StatusCode))
\r
1275 throw CreateWebException("CreateContainer", response.StatusCode);
\r
1278 using (var client = new RestClient(_baseClient))
\r
1280 if (!String.IsNullOrWhiteSpace(account))
\r
1281 client.BaseAddress = GetAccountUrl(account);
\r
1283 client.PutWithRetry(container, 3);
\r
1284 var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
\r
1285 if (!expectedCodes.Contains(client.StatusCode))
\r
1286 throw CreateWebException("CreateContainer", client.StatusCode);
\r
1291 public void DeleteContainer(string account, Uri container)
\r
1293 if (container == null)
\r
1294 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1295 if (container.IsAbsoluteUri)
\r
1296 throw new ArgumentException("The container must be relative","container");
\r
1297 Contract.EndContractBlock();
\r
1299 var targetUri = GetTargetUri(account).Combine(container);
\r
1300 var message = new HttpRequestMessage(HttpMethod.Delete, targetUri);
\r
1301 using (var response = _baseHttpClient.SendAsyncWithRetries(message, 3).Result)
\r
1303 var expectedCodes = new[] { HttpStatusCode.NotFound, HttpStatusCode.NoContent };
\r
1304 if (!expectedCodes.Contains(response.StatusCode))
\r
1305 throw CreateWebException("DeleteContainer", response.StatusCode);
\r
1308 using (var client = new RestClient(_baseClient))
\r
1310 if (!String.IsNullOrWhiteSpace(account))
\r
1311 client.BaseAddress = GetAccountUrl(account);
\r
1313 client.DeleteWithRetry(container, 3);
\r
1314 var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
\r
1315 if (!expectedCodes.Contains(client.StatusCode))
\r
1316 throw CreateWebException("DeleteContainer", client.StatusCode);
\r
1325 /// <param name="account"></param>
\r
1326 /// <param name="container"></param>
\r
1327 /// <param name="objectName"></param>
\r
1328 /// <param name="fileName"></param>
\r
1329 /// <param name="cancellationToken"> </param>
\r
1330 /// <returns></returns>
\r
1331 /// <remarks>This method should have no timeout or a very long one</remarks>
\r
1332 //Asynchronously download the object specified by *objectName* in a specific *container* to
\r
1334 public async Task GetObject(string account, Uri container, Uri objectName, string fileName,CancellationToken cancellationToken)
\r
1336 if (container == null)
\r
1337 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1338 if (container.IsAbsoluteUri)
\r
1339 throw new ArgumentException("The container must be relative","container");
\r
1340 if (objectName == null)
\r
1341 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1342 if (objectName.IsAbsoluteUri)
\r
1343 throw new ArgumentException("The objectName must be relative","objectName");
\r
1344 Contract.EndContractBlock();
\r
1349 //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
\r
1350 //object to avoid concurrency errors.
\r
1352 //Download operations take a long time therefore they have no timeout.
\r
1353 using(var client = new RestClient(_baseClient) { Timeout = 0 })
\r
1355 if (!String.IsNullOrWhiteSpace(account))
\r
1356 client.BaseAddress = GetAccountUrl(account);
\r
1358 //The container and objectName are relative names. They are joined with the client's
\r
1359 //BaseAddress to create the object's absolute address
\r
1360 var builder = client.GetAddressBuilder(container, objectName);
\r
1361 var uri = builder.Uri;
\r
1363 //Download progress is reported to the Trace log
\r
1364 Log.InfoFormat("[GET] START {0}", objectName);
\r
1365 /*client.DownloadProgressChanged += (sender, args) =>
\r
1366 Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
\r
1367 fileName, args.ProgressPercentage,
\r
1368 args.BytesReceived,
\r
1369 args.TotalBytesToReceive);*/
\r
1370 var progress = new Progress<DownloadProgressChangedEventArgs>(args =>
\r
1372 Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
\r
1373 fileName, args.ProgressPercentage,
\r
1374 args.BytesReceived,
\r
1375 args.TotalBytesToReceive);
\r
1376 if (DownloadProgressChanged!=null)
\r
1377 DownloadProgressChanged(this, args);
\r
1380 //Start downloading the object asynchronously
\r
1381 await client.DownloadFileTaskAsync(uri, fileName, cancellationToken,progress).ConfigureAwait(false);
\r
1383 //Once the download completes
\r
1384 //Delete the local client object
\r
1386 //And report failure or completion
\r
1388 catch (Exception exc)
\r
1390 Log.ErrorFormat("[GET] FAIL {0} with {1}", objectName, exc);
\r
1394 Log.InfoFormat("[GET] END {0}", objectName);
\r
1399 public Task<IList<string>> PutHashMap(string account, Uri container, Uri objectName, TreeHash hash)
\r
1401 if (container == null)
\r
1402 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1403 if (container.IsAbsoluteUri)
\r
1404 throw new ArgumentException("The container must be relative","container");
\r
1405 if (objectName == null)
\r
1406 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1407 if (objectName.IsAbsoluteUri)
\r
1408 throw new ArgumentException("The objectName must be relative","objectName");
\r
1410 throw new ArgumentNullException("hash");
\r
1411 if (String.IsNullOrWhiteSpace(Token))
\r
1412 throw new InvalidOperationException("Invalid Token");
\r
1413 if (StorageUrl == null)
\r
1414 throw new InvalidOperationException("Invalid Storage Url");
\r
1415 Contract.EndContractBlock();
\r
1419 //Don't use a timeout because putting the hashmap may be a long process
\r
1420 var client = new RestClient(_baseClient) { Timeout = 0 };
\r
1421 if (!String.IsNullOrWhiteSpace(account))
\r
1422 client.BaseAddress = GetAccountUrl(account);
\r
1424 //The container and objectName are relative names. They are joined with the client's
\r
1425 //BaseAddress to create the object's absolute address
\r
1426 var builder = client.GetAddressBuilder(container, objectName);
\r
1427 builder.Query = "format=json&hashmap";
\r
1428 var uri = builder.Uri;
\r
1431 //Send the tree hash as Json to the server
\r
1432 client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
\r
1433 var jsonHash = hash.ToJson();
\r
1435 client.Headers.Add("ETag",hash.TopHash.ToHashString());
\r
1436 var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
\r
1437 if (Log.IsDebugEnabled)
\r
1438 Log.DebugFormat("Hashes:\r\n{0}", jsonHash);
\r
1439 return uploadTask.ContinueWith(t =>
\r
1442 var empty = (IList<string>)new List<string>();
\r
1445 //The server will respond either with 201-created if all blocks were already on the server
\r
1446 if (client.StatusCode == HttpStatusCode.Created)
\r
1448 //in which case we return an empty hash list
\r
1451 //or with a 409-conflict and return the list of missing parts
\r
1452 //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception
\r
1455 var ex = t.Exception.InnerException;
\r
1456 var we = ex as WebException;
\r
1457 var response = we.Response as HttpWebResponse;
\r
1458 if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
\r
1460 //In case of 409 the missing parts will be in the response content
\r
1461 using (var stream = response.GetResponseStream())
\r
1462 using(var reader=stream.GetLoggedReader(Log))
\r
1464 //We used to have to cleanup the content before returning it because it contains
\r
1465 //error content after the list of hashes
\r
1467 //As of 30/1/2012, the result is a proper Json array so we don't need to read the content
\r
1470 var serializer = new JsonSerializer();
\r
1471 serializer.Error += (sender, args) => Log.ErrorFormat("Deserialization error at [{0}] [{1}]", args.ErrorContext.Error, args.ErrorContext.Member);
\r
1472 var hashes = (List<string>)serializer.Deserialize(reader, typeof(List<string>));
\r
1476 //Any other status code is unexpected and the exception should be rethrown
\r
1477 Log.LogError(response);
\r
1482 //Any other status code is unexpected but there was no exception. We can probably continue processing
\r
1483 Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);
\r
1491 public async Task<byte[]> GetBlock(string account, Uri container, Uri relativeUrl, long start, long? end, CancellationToken cancellationToken)
\r
1493 if (String.IsNullOrWhiteSpace(Token))
\r
1494 throw new InvalidOperationException("Invalid Token");
\r
1495 if (StorageUrl == null)
\r
1496 throw new InvalidOperationException("Invalid Storage Url");
\r
1497 if (container == null)
\r
1498 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1499 if (container.IsAbsoluteUri)
\r
1500 throw new ArgumentException("The container must be relative","container");
\r
1501 if (relativeUrl == null)
\r
1502 throw new ArgumentNullException("relativeUrl");
\r
1503 if (end.HasValue && end < 0)
\r
1504 throw new ArgumentOutOfRangeException("end");
\r
1506 throw new ArgumentOutOfRangeException("start");
\r
1507 Contract.EndContractBlock();
\r
1509 //Don't use a timeout because putting the hashmap may be a long process
\r
1510 using (var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end})
\r
1512 if (!String.IsNullOrWhiteSpace(account))
\r
1513 client.BaseAddress = GetAccountUrl(account);
\r
1515 var builder = client.GetAddressBuilder(container, relativeUrl);
\r
1516 var uri = builder.Uri;
\r
1518 /* client.DownloadProgressChanged += (sender, args) =>
\r
1520 Log.DebugFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
\r
1521 uri.Segments.Last(), args.ProgressPercentage,
\r
1522 args.BytesReceived,
\r
1523 args.TotalBytesToReceive);
\r
1524 DownloadProgressChanged(sender, args);
\r
1526 var progress = new Progress<DownloadProgressChangedEventArgs>(args =>
\r
1528 Log.DebugFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
\r
1529 uri.Segments.Last(), args.ProgressPercentage,
\r
1530 args.BytesReceived,
\r
1531 args.TotalBytesToReceive);
\r
1532 if (DownloadProgressChanged!=null)
\r
1533 DownloadProgressChanged(this, args);
\r
1537 var result = await client.DownloadDataTaskAsync(uri, cancellationToken,progress).ConfigureAwait(false);
\r
1542 public event UploadProgressChangedEventHandler UploadProgressChanged;
\r
1543 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
\r
1545 public async Task PostBlock(string account, Uri container, byte[] block, int offset, int count,CancellationToken token)
\r
1547 if (container == null)
\r
1548 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1549 if (container.IsAbsoluteUri)
\r
1550 throw new ArgumentException("The container must be relative","container");
\r
1551 if (block == null)
\r
1552 throw new ArgumentNullException("block");
\r
1553 if (offset < 0 || offset >= block.Length)
\r
1554 throw new ArgumentOutOfRangeException("offset");
\r
1555 if (count < 0 || count > block.Length)
\r
1556 throw new ArgumentOutOfRangeException("count");
\r
1557 if (String.IsNullOrWhiteSpace(Token))
\r
1558 throw new InvalidOperationException("Invalid Token");
\r
1559 if (StorageUrl == null)
\r
1560 throw new InvalidOperationException("Invalid Storage Url");
\r
1561 Contract.EndContractBlock();
\r
1567 //Don't use a timeout because putting the hashmap may be a long process
\r
1568 using (var client = new RestClient(_baseClient) { Timeout = 0 })
\r
1570 if (!String.IsNullOrWhiteSpace(account))
\r
1571 client.BaseAddress = GetAccountUrl(account);
\r
1573 var builder = client.GetAddressBuilder(container, _emptyUri);
\r
1574 //We are doing an update
\r
1575 builder.Query = "update";
\r
1576 var uri = builder.Uri;
\r
1578 client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
\r
1580 Log.InfoFormat("[BLOCK POST] START");
\r
1583 client.UploadProgressChanged += (sender, args) =>
\r
1585 Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
\r
1586 args.ProgressPercentage, args.BytesSent,
\r
1587 args.TotalBytesToSend);
\r
1588 UploadProgressChanged(sender, args);
\r
1591 client.UploadFileCompleted += (sender, args) =>
\r
1592 Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
\r
1594 var progress=new Progress<UploadProgressChangedEventArgs>(args=>
\r
1596 Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
\r
1597 args.ProgressPercentage, args.BytesSent,
\r
1598 args.TotalBytesToSend);
\r
1599 if (UploadProgressChanged!=null)
\r
1600 UploadProgressChanged(this, args);
\r
1602 var buffer = new byte[count];
\r
1603 Buffer.BlockCopy(block, offset, buffer, 0, count);
\r
1605 await client.UploadDataTaskAsync(uri, "POST", buffer,token,progress).ConfigureAwait(false);
\r
1606 Log.InfoFormat("[BLOCK POST] END");
\r
1609 catch (TaskCanceledException )
\r
1611 Log.Info("Aborting block");
\r
1614 catch (Exception exc)
\r
1616 Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc);
\r
1622 public async Task<TreeHash> GetHashMap(string account, Uri container, Uri objectName)
\r
1624 if (container == null)
\r
1625 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1626 if (container.IsAbsoluteUri)
\r
1627 throw new ArgumentException("The container must be relative","container");
\r
1628 if (objectName == null)
\r
1629 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1630 if (objectName.IsAbsoluteUri)
\r
1631 throw new ArgumentException("The objectName must be relative","objectName");
\r
1632 if (String.IsNullOrWhiteSpace(Token))
\r
1633 throw new InvalidOperationException("Invalid Token");
\r
1634 if (StorageUrl == null)
\r
1635 throw new InvalidOperationException("Invalid Storage Url");
\r
1636 Contract.EndContractBlock();
\r
1640 //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
\r
1641 //object to avoid concurrency errors.
\r
1643 //Download operations take a long time therefore they have no timeout.
\r
1644 //TODO: Do they really? this is a hashmap operation, not a download
\r
1646 //Start downloading the object asynchronously
\r
1647 using (var client = new RestClient(_baseClient) { Timeout = 0 })
\r
1649 if (!String.IsNullOrWhiteSpace(account))
\r
1650 client.BaseAddress = GetAccountUrl(account);
\r
1652 //The container and objectName are relative names. They are joined with the client's
\r
1653 //BaseAddress to create the object's absolute address
\r
1655 var builder = client.GetAddressBuilder(container, objectName);
\r
1656 builder.Query = "format=json&hashmap";
\r
1657 var uri = builder.Uri;
\r
1660 var json = await client.DownloadStringTaskAsync(uri).ConfigureAwait(false);
\r
1661 var treeHash = TreeHash.Parse(json);
\r
1662 Log.InfoFormat("[GET HASH] END {0}", objectName);
\r
1666 catch (Exception exc)
\r
1668 Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
\r
1678 /// <param name="account"></param>
\r
1679 /// <param name="container"></param>
\r
1680 /// <param name="objectName"></param>
\r
1681 /// <param name="fileName"></param>
\r
1682 /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
\r
1683 /// <param name="contentType"> </param>
\r
1684 /// <remarks>>This method should have no timeout or a very long one</remarks>
\r
1685 public async Task PutObject(string account, Uri container, Uri objectName, string fileName, string hash = Signature.MERKLE_EMPTY, string contentType = "application/octet-stream")
\r
1687 if (container == null)
\r
1688 throw new ArgumentNullException("container", "The container property can't be empty");
\r
1689 if (container.IsAbsoluteUri)
\r
1690 throw new ArgumentException("The container must be relative","container");
\r
1691 if (objectName == null)
\r
1692 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1693 if (objectName.IsAbsoluteUri)
\r
1694 throw new ArgumentException("The objectName must be relative","objectName");
\r
1695 if (String.IsNullOrWhiteSpace(fileName))
\r
1696 throw new ArgumentNullException("fileName", "The fileName property can't be empty");
\r
1698 if (!File.Exists(fileName) && !Directory.Exists(fileName))
\r
1699 throw new FileNotFoundException("The file or directory does not exist",fileName);
\r
1705 using (var client = new RestClient(_baseClient) { Timeout = 0 })
\r
1707 if (!String.IsNullOrWhiteSpace(account))
\r
1708 client.BaseAddress = GetAccountUrl(account);
\r
1710 var builder = client.GetAddressBuilder(container, objectName);
\r
1711 var uri = builder.Uri;
\r
1713 string etag = hash ;
\r
1715 client.Headers.Add("Content-Type", contentType);
\r
1716 if (contentType!=ObjectInfo.CONTENT_TYPE_DIRECTORY)
\r
1717 client.Headers.Add("ETag", etag);
\r
1720 Log.InfoFormat("[PUT] START {0}", objectName);
\r
1721 client.UploadProgressChanged += (sender, args) =>
\r
1723 using (ThreadContext.Stacks["PUT"].Push("Progress"))
\r
1725 Log.InfoFormat("{0} {1}% {2} of {3}", fileName,
\r
1726 args.ProgressPercentage,
\r
1727 args.BytesSent, args.TotalBytesToSend);
\r
1731 client.UploadFileCompleted += (sender, args) =>
\r
1733 using (ThreadContext.Stacks["PUT"].Push("Progress"))
\r
1735 Log.InfoFormat("Completed {0}", fileName);
\r
1739 if (contentType==ObjectInfo.CONTENT_TYPE_DIRECTORY)
\r
1740 await client.UploadDataTaskAsync(uri, "PUT", new byte[0]).ConfigureAwait(false);
\r
1742 await client.UploadFileTaskAsync(uri, "PUT", fileName).ConfigureAwait(false);
\r
1745 Log.InfoFormat("[PUT] END {0}", objectName);
\r
1747 catch (Exception exc)
\r
1749 Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
\r
1757 private static string CalculateHash(string fileName)
\r
1759 Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
\r
1760 Contract.EndContractBlock();
\r
1763 using (var hasher = MD5.Create())
\r
1764 using(var stream=File.OpenRead(fileName))
\r
1766 var hashBuilder=new StringBuilder();
\r
1767 foreach (byte b in hasher.ComputeHash(stream))
\r
1768 hashBuilder.Append(b.ToString("x2").ToLower());
\r
1769 hash = hashBuilder.ToString();
\r
1776 public void MoveObject(string account, Uri sourceContainer, Uri oldObjectName, Uri targetContainer, Uri newObjectName)
\r
1778 if (sourceContainer == null)
\r
1779 throw new ArgumentNullException("sourceContainer", "The sourceContainer property can't be empty");
\r
1780 if (sourceContainer.IsAbsoluteUri)
\r
1781 throw new ArgumentException("The sourceContainer must be relative","sourceContainer");
\r
1782 if (oldObjectName == null)
\r
1783 throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
\r
1784 if (oldObjectName.IsAbsoluteUri)
\r
1785 throw new ArgumentException("The oldObjectName must be relative","oldObjectName");
\r
1786 if (targetContainer == null)
\r
1787 throw new ArgumentNullException("targetContainer", "The targetContainer property can't be empty");
\r
1788 if (targetContainer.IsAbsoluteUri)
\r
1789 throw new ArgumentException("The targetContainer must be relative","targetContainer");
\r
1790 if (newObjectName == null)
\r
1791 throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
\r
1792 if (newObjectName.IsAbsoluteUri)
\r
1793 throw new ArgumentException("The newObjectName must be relative","newObjectName");
\r
1794 Contract.EndContractBlock();
\r
1796 var baseUri = GetTargetUri(account);
\r
1797 var targetUri = baseUri.Combine(targetContainer).Combine(newObjectName);
\r
1798 var sourceUri = new Uri(String.Format("/{0}/{1}", sourceContainer, oldObjectName),UriKind.Relative);
\r
1800 var message = new HttpRequestMessage(HttpMethod.Put, targetUri);
\r
1801 message.Headers.Add("X-Move-From", sourceUri.ToString());
\r
1802 using (var response = _baseHttpClient.SendAsyncWithRetries(message, 3).Result)
\r
1804 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
\r
1805 if (!expectedCodes.Contains(response.StatusCode))
\r
1806 throw CreateWebException("MoveObject", response.StatusCode);
\r
1809 using (var client = new RestClient(_baseClient))
\r
1811 if (!String.IsNullOrWhiteSpace(account))
\r
1812 client.BaseAddress = GetAccountUrl(account);
\r
1814 client.Headers.Add("X-Move-From", sourceUri.ToString());
\r
1815 client.PutWithRetry(targetUri, 3);
\r
1817 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
\r
1818 if (!expectedCodes.Contains(client.StatusCode))
\r
1819 throw CreateWebException("MoveObject", client.StatusCode);
\r
1824 public void DeleteObject(string account, Uri sourceContainer, Uri objectName, bool isDirectory)
\r
1826 if (sourceContainer == null)
\r
1827 throw new ArgumentNullException("sourceContainer", "The sourceContainer property can't be empty");
\r
1828 if (sourceContainer.IsAbsoluteUri)
\r
1829 throw new ArgumentException("The sourceContainer must be relative","sourceContainer");
\r
1830 if (objectName == null)
\r
1831 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
\r
1832 if (objectName.IsAbsoluteUri)
\r
1833 throw new ArgumentException("The objectName must be relative","objectName");
\r
1834 Contract.EndContractBlock();
\r
1836 var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
\r
1839 targetUrl = targetUrl + "?delimiter=/";
\r
1842 var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
\r
1844 using (var client = new RestClient(_baseClient))
\r
1846 if (!String.IsNullOrWhiteSpace(account))
\r
1847 client.BaseAddress = GetAccountUrl(account);
\r
1849 client.Headers.Add("X-Move-From", sourceUrl);
\r
1850 client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
\r
1851 Log.InfoFormat("[TRASH] [{0}] to [{1}]",sourceUrl,targetUrl);
\r
1852 client.PutWithRetry(new Uri(targetUrl,UriKind.Relative), 3);
\r
1854 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
\r
1855 if (!expectedCodes.Contains(client.StatusCode))
\r
1856 throw CreateWebException("DeleteObject", client.StatusCode);
\r
1861 private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
\r
1863 return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
\r
1868 public IEnumerable<ObjectInfo> ListDirectories(ContainerInfo container)
\r
1870 var directories=this.ListObjects(container.Account, container.Name, "/");
\r
1874 public bool CanUpload(string account, ObjectInfo cloudFile)
\r
1876 Contract.Requires(!String.IsNullOrWhiteSpace(account));
\r
1877 Contract.Requires(cloudFile!=null);
\r
1879 using (var client = new RestClient(_baseClient))
\r
1881 if (!String.IsNullOrWhiteSpace(account))
\r
1882 client.BaseAddress = GetAccountUrl(account);
\r
1885 var parts = cloudFile.Name.ToString().Split('/');
\r
1886 var folder = String.Join("/", parts,0,parts.Length-1);
\r
1888 var fileName = String.Format("{0}/{1}.pithos.ignore", folder, Guid.NewGuid());
\r
1889 var fileUri=fileName.ToEscapedUri();
\r
1891 client.Parameters.Clear();
\r
1894 var relativeUri = cloudFile.Container.Combine(fileUri);
\r
1895 client.PutWithRetry(relativeUri, 3, @"application/octet-stream");
\r
1897 var expectedCodes = new[] { HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
\r
1898 var result=(expectedCodes.Contains(client.StatusCode));
\r
1899 DeleteObject(account, cloudFile.Container, fileUri, cloudFile.IsDirectory);
\r
1910 public class ShareAccountInfo
\r
1912 public DateTime? last_modified { get; set; }
\r
1913 public string name { get; set; }
\r