1 // -----------------------------------------------------------------------
2 // <copyright file="CloudFilesClient.cs" company="GRNET">
3 // Copyright 2011-2012 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 // -----------------------------------------------------------------------
39 // **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
41 // The class provides methods to upload/download files, delete files, manage containers
45 using System.Collections.Generic;
46 using System.Collections.Specialized;
47 using System.ComponentModel.Composition;
48 using System.Diagnostics;
49 using System.Diagnostics.Contracts;
53 using System.Security.Cryptography;
55 using System.Threading.Tasks;
56 using Newtonsoft.Json;
57 using Pithos.Interfaces;
60 namespace Pithos.Network
62 [Export(typeof(ICloudClient))]
63 public class CloudFilesClient:ICloudClient
65 //CloudFilesClient uses *_baseClient* internally to communicate with the server
66 //RestClient provides a REST-friendly interface over the standard WebClient.
67 private RestClient _baseClient;
70 //During authentication the client provides a UserName
71 public string UserName { get; set; }
73 //and and ApiKey to the server
74 public string ApiKey { get; set; }
76 //And receives an authentication Token. This token must be provided in ALL other operations,
77 //in the X-Auth-Token header
78 private string _token;
81 get { return _token; }
85 _baseClient.Headers["X-Auth-Token"] = value;
89 //The client also receives a StorageUrl after authentication. All subsequent operations must
91 public Uri StorageUrl { get; set; }
94 protected Uri RootAddressUri { get; set; }
96 /* private WebProxy _proxy;
99 get { return _proxy; }
103 if (_baseClient != null)
104 _baseClient.Proxy = value;
109 /* private Uri _proxy;
112 get { return _proxy; }
116 if (_baseClient != null)
117 _baseClient.Proxy = new WebProxy(value);
121 public double DownloadPercentLimit { get; set; }
122 public double UploadPercentLimit { get; set; }
124 public string AuthenticationUrl { get; set; }
127 public string VersionPath
129 get { return UsePithos ? "v1" : "v1.0"; }
132 public bool UsePithos { get; set; }
135 private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
137 public CloudFilesClient(string userName, string apiKey)
143 public CloudFilesClient(AccountInfo accountInfo)
145 if (accountInfo==null)
146 throw new ArgumentNullException("accountInfo");
147 Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
148 Contract.Ensures(StorageUrl != null);
149 Contract.Ensures(_baseClient != null);
150 Contract.Ensures(RootAddressUri != null);
151 Contract.EndContractBlock();
153 _baseClient = new RestClient
155 BaseAddress = accountInfo.StorageUri.ToString(),
159 StorageUrl = accountInfo.StorageUri;
160 Token = accountInfo.Token;
161 UserName = accountInfo.UserName;
163 //Get the root address (StorageUrl without the account)
164 var storageUrl = StorageUrl.AbsoluteUri;
165 var usernameIndex = storageUrl.LastIndexOf(UserName);
166 var rootUrl = storageUrl.Substring(0, usernameIndex);
167 RootAddressUri = new Uri(rootUrl);
171 public AccountInfo Authenticate()
173 if (String.IsNullOrWhiteSpace(UserName))
174 throw new InvalidOperationException("UserName is empty");
175 if (String.IsNullOrWhiteSpace(ApiKey))
176 throw new InvalidOperationException("ApiKey is empty");
177 if (String.IsNullOrWhiteSpace(AuthenticationUrl))
178 throw new InvalidOperationException("AuthenticationUrl is empty");
179 Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
180 Contract.Ensures(StorageUrl != null);
181 Contract.Ensures(_baseClient != null);
182 Contract.Ensures(RootAddressUri != null);
183 Contract.EndContractBlock();
186 Log.InfoFormat("[AUTHENTICATE] Start for {0}", UserName);
188 var groups = new List<Group>();
190 using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
192 /* if (Proxy != null)
193 authClient.Proxy = Proxy;*/
195 Contract.Assume(authClient.Headers!=null);
197 authClient.Headers.Add("X-Auth-User", UserName);
198 authClient.Headers.Add("X-Auth-Key", ApiKey);
200 authClient.DownloadStringWithRetry(VersionPath, 3);
202 authClient.AssertStatusOK("Authentication failed");
204 var storageUrl = authClient.GetHeaderValue("X-Storage-Url");
205 if (String.IsNullOrWhiteSpace(storageUrl))
206 throw new InvalidOperationException("Failed to obtain storage url");
208 _baseClient = new RestClient
210 BaseAddress = storageUrl,
216 StorageUrl = new Uri(storageUrl);
218 //Get the root address (StorageUrl without the account)
219 var usernameIndex=storageUrl.LastIndexOf(UserName);
220 var rootUrl = storageUrl.Substring(0, usernameIndex);
221 RootAddressUri = new Uri(rootUrl);
223 var token = authClient.GetHeaderValue("X-Auth-Token");
224 if (String.IsNullOrWhiteSpace(token))
225 throw new InvalidOperationException("Failed to obtain token url");
228 /* var keys = authClient.ResponseHeaders.AllKeys.AsQueryable();
229 groups = (from key in keys
230 where key.StartsWith("X-Account-Group-")
231 let name = key.Substring(16)
232 select new Group(name, authClient.ResponseHeaders[key]))
238 Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
241 return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};
247 public IList<ContainerInfo> ListContainers(string account)
249 using (var client = new RestClient(_baseClient))
251 if (!String.IsNullOrWhiteSpace(account))
252 client.BaseAddress = GetAccountUrl(account);
254 client.Parameters.Clear();
255 client.Parameters.Add("format", "json");
256 var content = client.DownloadStringWithRetry("", 3);
257 client.AssertStatusOK("List Containers failed");
259 if (client.StatusCode == HttpStatusCode.NoContent)
260 return new List<ContainerInfo>();
261 var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(content);
263 foreach (var info in infos)
265 info.Account = account;
272 private string GetAccountUrl(string account)
274 return new Uri(RootAddressUri, new Uri(account,UriKind.Relative)).AbsoluteUri;
277 public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null)
279 using (ThreadContext.Stacks["Share"].Push("List Accounts"))
281 if (Log.IsDebugEnabled) Log.DebugFormat("START");
283 using (var client = new RestClient(_baseClient))
285 client.Parameters.Clear();
286 client.Parameters.Add("format", "json");
287 client.IfModifiedSince = since;
289 //Extract the username from the base address
290 client.BaseAddress = RootAddressUri.AbsoluteUri;
292 var content = client.DownloadStringWithRetry(@"", 3);
294 client.AssertStatusOK("ListSharingAccounts failed");
296 //If the result is empty, return an empty list,
297 var infos = String.IsNullOrWhiteSpace(content)
298 ? new List<ShareAccountInfo>()
299 //Otherwise deserialize the account list into a list of ShareAccountInfos
300 : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
302 Log.DebugFormat("END");
308 //Request listing of all objects in a container modified since a specific time.
309 //If the *since* value is missing, return all objects
310 public IList<ObjectInfo> ListSharedObjects(DateTime? since = null)
313 using (ThreadContext.Stacks["Share"].Push("List Objects"))
315 if (Log.IsDebugEnabled) Log.DebugFormat("START");
317 var objects = new List<ObjectInfo>();
318 var accounts = ListSharingAccounts(since);
319 foreach (var account in accounts)
321 var containers = ListContainers(account.name);
322 foreach (var container in containers)
324 var containerObjects = ListObjects(account.name, container.Name);
325 objects.AddRange(containerObjects);
328 if (Log.IsDebugEnabled) Log.DebugFormat("END");
333 public void SetTags(ObjectInfo target,IDictionary<string,string> tags)
335 if (String.IsNullOrWhiteSpace(Token))
336 throw new InvalidOperationException("The Token is not set");
337 if (StorageUrl == null)
338 throw new InvalidOperationException("The StorageUrl is not set");
340 throw new ArgumentNullException("target");
341 Contract.EndContractBlock();
343 using (ThreadContext.Stacks["Share"].Push("Share Object"))
345 if (Log.IsDebugEnabled) Log.DebugFormat("START");
347 using (var client = new RestClient(_baseClient))
350 client.BaseAddress = GetAccountUrl(target.Account);
352 client.Parameters.Clear();
353 client.Parameters.Add("update", "");
355 foreach (var tag in tags)
357 var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
358 client.Headers.Add(headerTag, tag.Value);
361 client.DownloadStringWithRetry(target.Container, 3);
364 client.AssertStatusOK("SetTags failed");
365 //If the status is NOT ACCEPTED we have a problem
366 if (client.StatusCode != HttpStatusCode.Accepted)
368 Log.Error("Failed to set tags");
369 throw new Exception("Failed to set tags");
372 if (Log.IsDebugEnabled) Log.DebugFormat("END");
379 public void ShareObject(string account, string container, string objectName, string shareTo, bool read, bool write)
381 if (String.IsNullOrWhiteSpace(Token))
382 throw new InvalidOperationException("The Token is not set");
383 if (StorageUrl==null)
384 throw new InvalidOperationException("The StorageUrl is not set");
385 if (String.IsNullOrWhiteSpace(container))
386 throw new ArgumentNullException("container");
387 if (String.IsNullOrWhiteSpace(objectName))
388 throw new ArgumentNullException("objectName");
389 if (String.IsNullOrWhiteSpace(account))
390 throw new ArgumentNullException("account");
391 if (String.IsNullOrWhiteSpace(shareTo))
392 throw new ArgumentNullException("shareTo");
393 Contract.EndContractBlock();
395 using (ThreadContext.Stacks["Share"].Push("Share Object"))
397 if (Log.IsDebugEnabled) Log.DebugFormat("START");
399 using (var client = new RestClient(_baseClient))
402 client.BaseAddress = GetAccountUrl(account);
404 client.Parameters.Clear();
405 client.Parameters.Add("format", "json");
407 string permission = "";
409 permission = String.Format("write={0}", shareTo);
411 permission = String.Format("read={0}", shareTo);
412 client.Headers.Add("X-Object-Sharing", permission);
414 var content = client.DownloadStringWithRetry(container, 3);
416 client.AssertStatusOK("ShareObject failed");
418 //If the result is empty, return an empty list,
419 var infos = String.IsNullOrWhiteSpace(content)
420 ? new List<ObjectInfo>()
421 //Otherwise deserialize the object list into a list of ObjectInfos
422 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
424 if (Log.IsDebugEnabled) Log.DebugFormat("END");
431 public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
433 if (accountInfo==null)
434 throw new ArgumentNullException("accountInfo");
435 Contract.EndContractBlock();
437 using (ThreadContext.Stacks["Account"].Push("GetPolicies"))
439 if (Log.IsDebugEnabled) Log.DebugFormat("START");
441 using (var client = new RestClient(_baseClient))
443 if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
444 client.BaseAddress = GetAccountUrl(accountInfo.UserName);
446 client.Parameters.Clear();
447 client.Parameters.Add("format", "json");
448 client.Head(String.Empty, 3);
450 var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
451 var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
454 if (long.TryParse(quotaValue, out quota))
455 accountInfo.Quota = quota;
456 if (long.TryParse(bytesValue, out bytes))
457 accountInfo.BytesUsed = bytes;
466 public void UpdateMetadata(ObjectInfo objectInfo)
468 if (objectInfo == null)
469 throw new ArgumentNullException("objectInfo");
470 Contract.EndContractBlock();
472 using (ThreadContext.Stacks["Objects"].Push("UpdateMetadata"))
474 if (Log.IsDebugEnabled) Log.DebugFormat("START");
477 using(var client=new RestClient(_baseClient))
480 client.BaseAddress = GetAccountUrl(objectInfo.Account);
482 client.Parameters.Clear();
486 foreach (var tag in objectInfo.Tags)
488 var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
489 client.Headers.Add(headerTag, tag.Value);
494 var permissions=objectInfo.GetPermissionString();
495 client.SetNonEmptyHeaderValue("X-Object-Sharing",permissions);
497 client.SetNonEmptyHeaderValue("Content-Disposition",objectInfo.ContendDisposition);
498 client.SetNonEmptyHeaderValue("Content-Encoding",objectInfo.ContentEncoding);
499 client.SetNonEmptyHeaderValue("X-Object-Manifest",objectInfo.Manifest);
500 var isPublic = objectInfo.IsPublic.ToString().ToLower();
501 client.Headers.Add("X-Object-Public", isPublic);
504 var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
505 var uri = uriBuilder.Uri;
507 client.UploadValues(uri,new NameValueCollection());
510 client.AssertStatusOK("UpdateMetadata failed");
511 //If the status is NOT ACCEPTED or OK we have a problem
512 if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
514 Log.Error("Failed to update metadata");
515 throw new Exception("Failed to update metadata");
518 if (Log.IsDebugEnabled) Log.DebugFormat("END");
524 public void UpdateMetadata(ContainerInfo containerInfo)
526 if (containerInfo == null)
527 throw new ArgumentNullException("containerInfo");
528 Contract.EndContractBlock();
530 using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata"))
532 if (Log.IsDebugEnabled) Log.DebugFormat("START");
535 using(var client=new RestClient(_baseClient))
538 client.BaseAddress = GetAccountUrl(containerInfo.Account);
540 client.Parameters.Clear();
544 foreach (var tag in containerInfo.Tags)
546 var headerTag = String.Format("X-Container-Meta-{0}", tag.Key);
547 client.Headers.Add(headerTag, tag.Value);
552 foreach (var policy in containerInfo.Policies)
554 var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key);
555 client.Headers.Add(headerPolicy, policy.Value);
559 var uriBuilder = client.GetAddressBuilder(containerInfo.Name,"");
560 var uri = uriBuilder.Uri;
562 client.UploadValues(uri,new NameValueCollection());
565 client.AssertStatusOK("UpdateMetadata failed");
566 //If the status is NOT ACCEPTED or OK we have a problem
567 if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK))
569 Log.Error("Failed to update metadata");
570 throw new Exception("Failed to update metadata");
573 if (Log.IsDebugEnabled) Log.DebugFormat("END");
580 public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
582 if (String.IsNullOrWhiteSpace(container))
583 throw new ArgumentNullException("container");
584 Contract.EndContractBlock();
586 using (ThreadContext.Stacks["Objects"].Push("List"))
588 if (Log.IsDebugEnabled) Log.DebugFormat("START");
590 using (var client = new RestClient(_baseClient))
592 if (!String.IsNullOrWhiteSpace(account))
593 client.BaseAddress = GetAccountUrl(account);
595 client.Parameters.Clear();
596 client.Parameters.Add("format", "json");
597 client.IfModifiedSince = since;
598 var content = client.DownloadStringWithRetry(container, 3);
600 client.AssertStatusOK("ListObjects failed");
602 //If the result is empty, return an empty list,
603 var infos = String.IsNullOrWhiteSpace(content)
604 ? new List<ObjectInfo>()
605 //Otherwise deserialize the object list into a list of ObjectInfos
606 : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
608 foreach (var info in infos)
610 info.Container = container;
611 info.Account = account;
613 if (Log.IsDebugEnabled) Log.DebugFormat("START");
621 public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
623 if (String.IsNullOrWhiteSpace(container))
624 throw new ArgumentNullException("container");
625 if (String.IsNullOrWhiteSpace(folder))
626 throw new ArgumentNullException("folder");
627 Contract.EndContractBlock();
629 using (ThreadContext.Stacks["Objects"].Push("List"))
631 if (Log.IsDebugEnabled) Log.DebugFormat("START");
633 using (var client = new RestClient(_baseClient))
635 if (!String.IsNullOrWhiteSpace(account))
636 client.BaseAddress = GetAccountUrl(account);
638 client.Parameters.Clear();
639 client.Parameters.Add("format", "json");
640 client.Parameters.Add("path", folder);
641 client.IfModifiedSince = since;
642 var content = client.DownloadStringWithRetry(container, 3);
643 client.AssertStatusOK("ListObjects failed");
645 var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
647 if (Log.IsDebugEnabled) Log.DebugFormat("END");
654 public bool ContainerExists(string account, string container)
656 if (String.IsNullOrWhiteSpace(container))
657 throw new ArgumentNullException("container", "The container property can't be empty");
658 Contract.EndContractBlock();
660 using (ThreadContext.Stacks["Containters"].Push("Exists"))
662 if (Log.IsDebugEnabled) Log.DebugFormat("START");
664 using (var client = new RestClient(_baseClient))
666 if (!String.IsNullOrWhiteSpace(account))
667 client.BaseAddress = GetAccountUrl(account);
669 client.Parameters.Clear();
670 client.Head(container, 3);
673 switch (client.StatusCode)
675 case HttpStatusCode.OK:
676 case HttpStatusCode.NoContent:
679 case HttpStatusCode.NotFound:
683 throw CreateWebException("ContainerExists", client.StatusCode);
685 if (Log.IsDebugEnabled) Log.DebugFormat("END");
693 public bool ObjectExists(string account, string container, string objectName)
695 if (String.IsNullOrWhiteSpace(container))
696 throw new ArgumentNullException("container", "The container property can't be empty");
697 if (String.IsNullOrWhiteSpace(objectName))
698 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
699 Contract.EndContractBlock();
701 using (var client = new RestClient(_baseClient))
703 if (!String.IsNullOrWhiteSpace(account))
704 client.BaseAddress = GetAccountUrl(account);
706 client.Parameters.Clear();
707 client.Head(container + "/" + objectName, 3);
709 switch (client.StatusCode)
711 case HttpStatusCode.OK:
712 case HttpStatusCode.NoContent:
714 case HttpStatusCode.NotFound:
717 throw CreateWebException("ObjectExists", client.StatusCode);
723 public ObjectInfo GetObjectInfo(string account, string container, string objectName)
725 if (String.IsNullOrWhiteSpace(container))
726 throw new ArgumentNullException("container", "The container property can't be empty");
727 if (String.IsNullOrWhiteSpace(objectName))
728 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
729 Contract.EndContractBlock();
731 using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
734 using (var client = new RestClient(_baseClient))
736 if (!String.IsNullOrWhiteSpace(account))
737 client.BaseAddress = GetAccountUrl(account);
740 client.Parameters.Clear();
742 client.Head(container + "/" + objectName, 3);
745 return ObjectInfo.Empty;
747 switch (client.StatusCode)
749 case HttpStatusCode.OK:
750 case HttpStatusCode.NoContent:
751 var keys = client.ResponseHeaders.AllKeys.AsQueryable();
752 var tags = client.GetMeta("X-Object-Meta-");
753 var extensions = (from key in keys
754 where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
755 select new {Name = key, Value = client.ResponseHeaders[key]})
756 .ToDictionary(t => t.Name, t => t.Value);
758 var permissions=client.GetHeaderValue("X-Object-Sharing", true);
761 var info = new ObjectInfo
764 Container = container,
766 Hash = client.GetHeaderValue("ETag"),
767 Content_Type = client.GetHeaderValue("Content-Type"),
768 Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
770 Last_Modified = client.LastModified,
771 Extensions = extensions,
772 ContentEncoding=client.GetHeaderValue("Content-Encoding",true),
773 ContendDisposition = client.GetHeaderValue("Content-Disposition",true),
774 Manifest=client.GetHeaderValue("X-Object-Manifest",true),
775 PublicUrl=client.GetHeaderValue("X-Object-Public",true),
777 info.SetPermissions(permissions);
779 case HttpStatusCode.NotFound:
780 return ObjectInfo.Empty;
782 throw new WebException(
783 String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
784 objectName, client.StatusCode));
788 catch (RetryException)
790 Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.",objectName);
791 return ObjectInfo.Empty;
793 catch (WebException e)
796 String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
797 objectName, client.StatusCode), e);
805 public void CreateFolder(string account, string container, string folder)
807 if (String.IsNullOrWhiteSpace(container))
808 throw new ArgumentNullException("container", "The container property can't be empty");
809 if (String.IsNullOrWhiteSpace(folder))
810 throw new ArgumentNullException("folder", "The folder property can't be empty");
811 Contract.EndContractBlock();
813 var folderUrl=String.Format("{0}/{1}",container,folder);
814 using (var client = new RestClient(_baseClient))
816 if (!String.IsNullOrWhiteSpace(account))
817 client.BaseAddress = GetAccountUrl(account);
819 client.Parameters.Clear();
820 client.Headers.Add("Content-Type", @"application/directory");
821 client.Headers.Add("Content-Length", "0");
822 client.PutWithRetry(folderUrl, 3);
824 if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
825 throw CreateWebException("CreateFolder", client.StatusCode);
831 public ContainerInfo GetContainerInfo(string account, string container)
833 if (String.IsNullOrWhiteSpace(container))
834 throw new ArgumentNullException("container", "The container property can't be empty");
835 Contract.EndContractBlock();
837 using (var client = new RestClient(_baseClient))
839 if (!String.IsNullOrWhiteSpace(account))
840 client.BaseAddress = GetAccountUrl(account);
842 client.Head(container);
843 switch (client.StatusCode)
845 case HttpStatusCode.OK:
846 case HttpStatusCode.NoContent:
847 var tags = client.GetMeta("X-Container-Meta-");
848 var policies = client.GetMeta("X-Container-Policy-");
850 var containerInfo = new ContainerInfo
855 long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
856 Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
857 BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
858 BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
859 Last_Modified=client.LastModified,
865 return containerInfo;
866 case HttpStatusCode.NotFound:
867 return ContainerInfo.Empty;
869 throw CreateWebException("GetContainerInfo", client.StatusCode);
874 public void CreateContainer(string account, string container)
876 if (String.IsNullOrWhiteSpace(account))
877 throw new ArgumentNullException("account");
878 if (String.IsNullOrWhiteSpace(container))
879 throw new ArgumentNullException("container");
880 Contract.EndContractBlock();
882 using (var client = new RestClient(_baseClient))
884 if (!String.IsNullOrWhiteSpace(account))
885 client.BaseAddress = GetAccountUrl(account);
887 client.PutWithRetry(container, 3);
888 var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
889 if (!expectedCodes.Contains(client.StatusCode))
890 throw CreateWebException("CreateContainer", client.StatusCode);
894 public void DeleteContainer(string account, string container)
896 if (String.IsNullOrWhiteSpace(container))
897 throw new ArgumentNullException("container", "The container property can't be empty");
898 Contract.EndContractBlock();
900 using (var client = new RestClient(_baseClient))
902 if (!String.IsNullOrWhiteSpace(account))
903 client.BaseAddress = GetAccountUrl(account);
905 client.DeleteWithRetry(container, 3);
906 var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
907 if (!expectedCodes.Contains(client.StatusCode))
908 throw CreateWebException("DeleteContainer", client.StatusCode);
916 /// <param name="account"></param>
917 /// <param name="container"></param>
918 /// <param name="objectName"></param>
919 /// <param name="fileName"></param>
920 /// <returns></returns>
921 /// <remarks>This method should have no timeout or a very long one</remarks>
922 //Asynchronously download the object specified by *objectName* in a specific *container* to
924 public Task GetObject(string account, string container, string objectName, string fileName)
926 if (String.IsNullOrWhiteSpace(container))
927 throw new ArgumentNullException("container", "The container property can't be empty");
928 if (String.IsNullOrWhiteSpace(objectName))
929 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
930 Contract.EndContractBlock();
934 //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
935 //object to avoid concurrency errors.
937 //Download operations take a long time therefore they have no timeout.
938 var client = new RestClient(_baseClient) { Timeout = 0 };
939 if (!String.IsNullOrWhiteSpace(account))
940 client.BaseAddress = GetAccountUrl(account);
942 //The container and objectName are relative names. They are joined with the client's
943 //BaseAddress to create the object's absolute address
944 var builder = client.GetAddressBuilder(container, objectName);
945 var uri = builder.Uri;
947 //Download progress is reported to the Trace log
948 Log.InfoFormat("[GET] START {0}", objectName);
949 client.DownloadProgressChanged += (sender, args) =>
950 Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
951 fileName, args.ProgressPercentage,
953 args.TotalBytesToReceive);
956 //Start downloading the object asynchronously
957 var downloadTask = client.DownloadFileTask(uri, fileName);
959 //Once the download completes
960 return downloadTask.ContinueWith(download =>
962 //Delete the local client object
964 //And report failure or completion
965 if (download.IsFaulted)
967 Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
972 Log.InfoFormat("[GET] END {0}", objectName);
976 catch (Exception exc)
978 Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
986 public Task<IList<string>> PutHashMap(string account, string container, string objectName, TreeHash hash)
988 if (String.IsNullOrWhiteSpace(container))
989 throw new ArgumentNullException("container");
990 if (String.IsNullOrWhiteSpace(objectName))
991 throw new ArgumentNullException("objectName");
993 throw new ArgumentNullException("hash");
994 if (String.IsNullOrWhiteSpace(Token))
995 throw new InvalidOperationException("Invalid Token");
996 if (StorageUrl == null)
997 throw new InvalidOperationException("Invalid Storage Url");
998 Contract.EndContractBlock();
1001 //Don't use a timeout because putting the hashmap may be a long process
1002 var client = new RestClient(_baseClient) { Timeout = 0 };
1003 if (!String.IsNullOrWhiteSpace(account))
1004 client.BaseAddress = GetAccountUrl(account);
1006 //The container and objectName are relative names. They are joined with the client's
1007 //BaseAddress to create the object's absolute address
1008 var builder = client.GetAddressBuilder(container, objectName);
1009 builder.Query = "format=json&hashmap";
1010 var uri = builder.Uri;
1013 //Send the tree hash as Json to the server
1014 client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1015 var jsonHash = hash.ToJson();
1016 var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
1018 return uploadTask.ContinueWith(t =>
1021 var empty = (IList<string>)new List<string>();
1024 //The server will respond either with 201-created if all blocks were already on the server
1025 if (client.StatusCode == HttpStatusCode.Created)
1027 //in which case we return an empty hash list
1030 //or with a 409-conflict and return the list of missing parts
1031 //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception
1034 var ex = t.Exception.InnerException;
1035 var we = ex as WebException;
1036 var response = we.Response as HttpWebResponse;
1037 if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
1039 //In case of 409 the missing parts will be in the response content
1040 using (var stream = response.GetResponseStream())
1041 using(var reader=new StreamReader(stream))
1043 Debug.Assert(stream.Position == 0);
1044 //We used to have to cleanup the content before returning it because it contains
1045 //error content after the list of hashes
1047 //As of 30/1/2012, the result is a proper Json array so we don't need to read the content
1050 var serializer = new JsonSerializer();
1051 var hashes=(List<string>)serializer.Deserialize(reader, typeof (List<string>));
1056 //Any other status code is unexpected and the exception should be rethrown
1060 //Any other status code is unexpected but there was no exception. We can probably continue processing
1061 Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);
1068 public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
1070 if (String.IsNullOrWhiteSpace(Token))
1071 throw new InvalidOperationException("Invalid Token");
1072 if (StorageUrl == null)
1073 throw new InvalidOperationException("Invalid Storage Url");
1074 if (String.IsNullOrWhiteSpace(container))
1075 throw new ArgumentNullException("container");
1076 if (relativeUrl== null)
1077 throw new ArgumentNullException("relativeUrl");
1078 if (end.HasValue && end<0)
1079 throw new ArgumentOutOfRangeException("end");
1081 throw new ArgumentOutOfRangeException("start");
1082 Contract.EndContractBlock();
1085 //Don't use a timeout because putting the hashmap may be a long process
1086 var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end};
1087 if (!String.IsNullOrWhiteSpace(account))
1088 client.BaseAddress = GetAccountUrl(account);
1090 var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
1091 var uri = builder.Uri;
1093 return client.DownloadDataTask(uri)
1102 public async Task PostBlock(string account, string container, byte[] block, int offset, int count)
1104 if (String.IsNullOrWhiteSpace(container))
1105 throw new ArgumentNullException("container");
1107 throw new ArgumentNullException("block");
1108 if (offset < 0 || offset >= block.Length)
1109 throw new ArgumentOutOfRangeException("offset");
1110 if (count < 0 || count > block.Length)
1111 throw new ArgumentOutOfRangeException("count");
1112 if (String.IsNullOrWhiteSpace(Token))
1113 throw new InvalidOperationException("Invalid Token");
1114 if (StorageUrl == null)
1115 throw new InvalidOperationException("Invalid Storage Url");
1116 Contract.EndContractBlock();
1122 //Don't use a timeout because putting the hashmap may be a long process
1123 using (var client = new RestClient(_baseClient) { Timeout = 0 })
1125 if (!String.IsNullOrWhiteSpace(account))
1126 client.BaseAddress = GetAccountUrl(account);
1128 var builder = client.GetAddressBuilder(container, "");
1129 //We are doing an update
1130 builder.Query = "update";
1131 var uri = builder.Uri;
1133 client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
1135 Log.InfoFormat("[BLOCK POST] START");
1137 client.UploadProgressChanged += (sender, args) =>
1138 Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
1139 args.ProgressPercentage, args.BytesSent,
1140 args.TotalBytesToSend);
1141 client.UploadFileCompleted += (sender, args) =>
1142 Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
1144 var buffer = new byte[count];
1145 Buffer.BlockCopy(block, offset, buffer, 0, count);
1147 await client.UploadDataTask(uri, "POST", buffer);
1148 Log.InfoFormat("[BLOCK POST] END");
1151 catch (Exception exc)
1153 Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc);
1159 public async Task<TreeHash> GetHashMap(string account, string container, string objectName)
1161 if (String.IsNullOrWhiteSpace(container))
1162 throw new ArgumentNullException("container");
1163 if (String.IsNullOrWhiteSpace(objectName))
1164 throw new ArgumentNullException("objectName");
1165 if (String.IsNullOrWhiteSpace(Token))
1166 throw new InvalidOperationException("Invalid Token");
1167 if (StorageUrl == null)
1168 throw new InvalidOperationException("Invalid Storage Url");
1169 Contract.EndContractBlock();
1173 //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
1174 //object to avoid concurrency errors.
1176 //Download operations take a long time therefore they have no timeout.
1177 //TODO: Do they really? this is a hashmap operation, not a download
1179 //Start downloading the object asynchronously
1180 using (var client = new RestClient(_baseClient) { Timeout = 0 })
1182 if (!String.IsNullOrWhiteSpace(account))
1183 client.BaseAddress = GetAccountUrl(account);
1185 //The container and objectName are relative names. They are joined with the client's
1186 //BaseAddress to create the object's absolute address
1187 var builder = client.GetAddressBuilder(container, objectName);
1188 builder.Query = "format=json&hashmap";
1189 var uri = builder.Uri;
1192 var json = await client.DownloadStringTaskAsync(uri);
1193 var treeHash = TreeHash.Parse(json);
1194 Log.InfoFormat("[GET HASH] END {0}", objectName);
1198 catch (Exception exc)
1200 Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
1210 /// <param name="account"></param>
1211 /// <param name="container"></param>
1212 /// <param name="objectName"></param>
1213 /// <param name="fileName"></param>
1214 /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
1215 /// <remarks>>This method should have no timeout or a very long one</remarks>
1216 public async Task PutObject(string account, string container, string objectName, string fileName, string hash = null, string contentType = "application/octet-stream")
1218 if (String.IsNullOrWhiteSpace(container))
1219 throw new ArgumentNullException("container", "The container property can't be empty");
1220 if (String.IsNullOrWhiteSpace(objectName))
1221 throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1222 if (String.IsNullOrWhiteSpace(fileName))
1223 throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1225 if (!File.Exists(fileName) && !Directory.Exists(fileName))
1226 throw new FileNotFoundException("The file or directory does not exist",fileName);
1228 Contract.EndContractBlock();
1233 using (var client = new RestClient(_baseClient) { Timeout = 0 })
1235 if (!String.IsNullOrWhiteSpace(account))
1236 client.BaseAddress = GetAccountUrl(account);
1238 var builder = client.GetAddressBuilder(container, objectName);
1239 var uri = builder.Uri;
1241 string etag = hash ?? CalculateHash(fileName);
1243 client.Headers.Add("Content-Type", contentType);
1244 client.Headers.Add("ETag", etag);
1247 Log.InfoFormat("[PUT] START {0}", objectName);
1248 client.UploadProgressChanged += (sender, args) =>
1250 using (ThreadContext.Stacks["PUT"].Push("Progress"))
1252 Log.InfoFormat("{0} {1}% {2} of {3}", fileName,
1253 args.ProgressPercentage,
1254 args.BytesSent, args.TotalBytesToSend);
1258 client.UploadFileCompleted += (sender, args) =>
1260 using (ThreadContext.Stacks["PUT"].Push("Progress"))
1262 Log.InfoFormat("Completed {0}", fileName);
1265 if (contentType=="application/directory")
1266 await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
1268 await client.UploadFileTaskAsync(uri, "PUT", fileName);
1271 Log.InfoFormat("[PUT] END {0}", objectName);
1273 catch (Exception exc)
1275 Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1282 private static string CalculateHash(string fileName)
1284 Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1285 Contract.EndContractBlock();
1288 using (var hasher = MD5.Create())
1289 using(var stream=File.OpenRead(fileName))
1291 var hashBuilder=new StringBuilder();
1292 foreach (byte b in hasher.ComputeHash(stream))
1293 hashBuilder.Append(b.ToString("x2").ToLower());
1294 hash = hashBuilder.ToString();
1299 public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1301 if (String.IsNullOrWhiteSpace(sourceContainer))
1302 throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1303 if (String.IsNullOrWhiteSpace(oldObjectName))
1304 throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1305 if (String.IsNullOrWhiteSpace(targetContainer))
1306 throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1307 if (String.IsNullOrWhiteSpace(newObjectName))
1308 throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1309 Contract.EndContractBlock();
1311 var targetUrl = targetContainer + "/" + newObjectName;
1312 var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1314 using (var client = new RestClient(_baseClient))
1316 if (!String.IsNullOrWhiteSpace(account))
1317 client.BaseAddress = GetAccountUrl(account);
1319 client.Headers.Add("X-Move-From", sourceUrl);
1320 client.PutWithRetry(targetUrl, 3);
1322 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1323 if (!expectedCodes.Contains(client.StatusCode))
1324 throw CreateWebException("MoveObject", client.StatusCode);
1328 public void DeleteObject(string account, string sourceContainer, string objectName)
1330 if (String.IsNullOrWhiteSpace(sourceContainer))
1331 throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1332 if (String.IsNullOrWhiteSpace(objectName))
1333 throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1334 Contract.EndContractBlock();
1336 var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1337 var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1339 using (var client = new RestClient(_baseClient))
1341 if (!String.IsNullOrWhiteSpace(account))
1342 client.BaseAddress = GetAccountUrl(account);
1344 client.Headers.Add("X-Move-From", sourceUrl);
1345 client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1346 client.PutWithRetry(targetUrl, 3);
1348 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1349 if (!expectedCodes.Contains(client.StatusCode))
1350 throw CreateWebException("DeleteObject", client.StatusCode);
1355 private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1357 return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1363 public class ShareAccountInfo
1365 public DateTime? last_modified { get; set; }
1366 public string name { get; set; }