Statistics
| Branch: | Revision:

root / trunk / Pithos.Network / CloudFilesClient.cs @ 42800be8

History | View | Annotate | Download (48.8 kB)

1
// **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
2
//
3
// The class provides methods to upload/download files, delete files, manage containers
4

    
5

    
6
using System;
7
using System.Collections.Generic;
8
using System.ComponentModel.Composition;
9
using System.Diagnostics.Contracts;
10
using System.IO;
11
using System.Linq;
12
using System.Net;
13
using System.Security.Cryptography;
14
using System.Text;
15
using System.Threading.Tasks;
16
using Newtonsoft.Json;
17
using Pithos.Interfaces;
18
using log4net;
19

    
20
namespace Pithos.Network
21
{
22
    [Export(typeof(ICloudClient))]
23
    public class CloudFilesClient:ICloudClient
24
    {
25
        //CloudFilesClient uses *_baseClient* internally to communicate with the server
26
        //RestClient provides a REST-friendly interface over the standard WebClient.
27
        private RestClient _baseClient;
28
        
29

    
30
        //During authentication the client provides a UserName 
31
        public string UserName { get; set; }
32
        
33
        //and and ApiKey to the server
34
        public string ApiKey { get; set; }
35
        
36
        //And receives an authentication Token. This token must be provided in ALL other operations,
37
        //in the X-Auth-Token header
38
        private string _token;
39
        public string Token
40
        {
41
            get { return _token; }
42
            set
43
            {
44
                _token = value;
45
                _baseClient.Headers["X-Auth-Token"] = value;
46
            }
47
        }
48

    
49
        //The client also receives a StorageUrl after authentication. All subsequent operations must
50
        //use this url
51
        public Uri StorageUrl { get; set; }
52

    
53

    
54
        protected Uri RootAddressUri { get; set; }
55

    
56
        private Uri _proxy;
57
        public Uri Proxy
58
        {
59
            get { return _proxy; }
60
            set
61
            {
62
                _proxy = value;
63
                if (_baseClient != null)
64
                    _baseClient.Proxy = new WebProxy(value);                
65
            }
66
        }
67

    
68
        public double DownloadPercentLimit { get; set; }
69
        public double UploadPercentLimit { get; set; }
70

    
71
        public string AuthenticationUrl { get; set; }
72

    
73
 
74
        public string VersionPath
75
        {
76
            get { return UsePithos ? "v1" : "v1.0"; }
77
        }
78

    
79
        public bool UsePithos { get; set; }
80

    
81

    
82
        private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
83

    
84
        public CloudFilesClient(string userName, string apiKey)
85
        {
86
            UserName = userName;
87
            ApiKey = apiKey;
88
        }
89

    
90
        public CloudFilesClient(AccountInfo accountInfo)
91
        {
92
            if (accountInfo==null)
93
                throw new ArgumentNullException("accountInfo");
94
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
95
            Contract.Ensures(StorageUrl != null);
96
            Contract.Ensures(_baseClient != null);
97
            Contract.Ensures(RootAddressUri != null);
98
            Contract.EndContractBlock();
99

    
100
            _baseClient = new RestClient
101
            {
102
                BaseAddress = accountInfo.StorageUri.ToString(),
103
                Timeout = 10000,
104
                Retries = 3
105
            };
106
            StorageUrl = accountInfo.StorageUri;
107
            Token = accountInfo.Token;
108
            UserName = accountInfo.UserName;
109

    
110
            //Get the root address (StorageUrl without the account)
111
            var storageUrl = StorageUrl.AbsoluteUri;
112
            var usernameIndex = storageUrl.LastIndexOf(UserName);
113
            var rootUrl = storageUrl.Substring(0, usernameIndex);
114
            RootAddressUri = new Uri(rootUrl);
115
        }
116

    
117

    
118
        public AccountInfo Authenticate()
119
        {
120
            if (String.IsNullOrWhiteSpace(UserName))
121
                throw new InvalidOperationException("UserName is empty");
122
            if (String.IsNullOrWhiteSpace(ApiKey))
123
                throw new InvalidOperationException("ApiKey is empty");
124
            if (String.IsNullOrWhiteSpace(AuthenticationUrl))
125
                throw new InvalidOperationException("AuthenticationUrl is empty");
126
            Contract.Ensures(!String.IsNullOrWhiteSpace(Token));
127
            Contract.Ensures(StorageUrl != null);
128
            Contract.Ensures(_baseClient != null);
129
            Contract.Ensures(RootAddressUri != null);
130
            Contract.EndContractBlock();
131

    
132

    
133
            Log.InfoFormat("[AUTHENTICATE] Start for {0}", UserName);
134

    
135
            using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
136
            {
137
                if (Proxy != null)
138
                    authClient.Proxy = new WebProxy(Proxy);
139

    
140
                Contract.Assume(authClient.Headers!=null);
141

    
142
                authClient.Headers.Add("X-Auth-User", UserName);
143
                authClient.Headers.Add("X-Auth-Key", ApiKey);
144

    
145
                authClient.DownloadStringWithRetry(VersionPath, 3);
146

    
147
                authClient.AssertStatusOK("Authentication failed");
148

    
149
                var storageUrl = authClient.GetHeaderValue("X-Storage-Url");
150
                if (String.IsNullOrWhiteSpace(storageUrl))
151
                    throw new InvalidOperationException("Failed to obtain storage url");
152
                
153
                _baseClient = new RestClient
154
                {
155
                    BaseAddress = storageUrl,
156
                    Timeout = 10000,
157
                    Retries = 3
158
                };
159

    
160
                StorageUrl = new Uri(storageUrl);
161
                
162
                //Get the root address (StorageUrl without the account)
163
                var usernameIndex=storageUrl.LastIndexOf(UserName);
164
                var rootUrl = storageUrl.Substring(0, usernameIndex);
165
                RootAddressUri = new Uri(rootUrl);
166
                
167
                var token = authClient.GetHeaderValue("X-Auth-Token");
168
                if (String.IsNullOrWhiteSpace(token))
169
                    throw new InvalidOperationException("Failed to obtain token url");
170
                Token = token;
171

    
172
            }
173

    
174
            Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
175
            
176

    
177
            return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName};            
178

    
179
        }
180

    
181

    
182

    
183
        public IList<ContainerInfo> ListContainers(string account)
184
        {
185
            using (var client = new RestClient(_baseClient))
186
            {
187
                if (!String.IsNullOrWhiteSpace(account))
188
                    client.BaseAddress = GetAccountUrl(account);
189
                
190
                client.Parameters.Clear();
191
                client.Parameters.Add("format", "json");
192
                var content = client.DownloadStringWithRetry("", 3);
193
                client.AssertStatusOK("List Containers failed");
194

    
195
                if (client.StatusCode == HttpStatusCode.NoContent)
196
                    return new List<ContainerInfo>();
197
                var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(content);
198
                
199
                foreach (var info in infos)
200
                {
201
                    info.Account = account;
202
                }
203
                return infos;
204
            }
205

    
206
        }
207

    
208
        private string GetAccountUrl(string account)
209
        {
210
            return new Uri(this.RootAddressUri, new Uri(account,UriKind.Relative)).AbsoluteUri;
211
        }
212

    
213
        public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null)
214
        {
215
            using (log4net.ThreadContext.Stacks["Share"].Push("List Accounts"))
216
            {
217
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
218

    
219
                using (var client = new RestClient(_baseClient))
220
                {
221
                    client.Parameters.Clear();
222
                    client.Parameters.Add("format", "json");
223
                    client.IfModifiedSince = since;
224

    
225
                    //Extract the username from the base address
226
                    client.BaseAddress = RootAddressUri.AbsoluteUri;
227

    
228
                    var content = client.DownloadStringWithRetry(@"", 3);
229

    
230
                    client.AssertStatusOK("ListSharingAccounts failed");
231

    
232
                    //If the result is empty, return an empty list,
233
                    var infos = String.IsNullOrWhiteSpace(content)
234
                                    ? new List<ShareAccountInfo>()
235
                                //Otherwise deserialize the account list into a list of ShareAccountInfos
236
                                    : JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content);
237

    
238
                    Log.DebugFormat("END");
239
                    return infos;
240
                }
241
            }
242
        }
243

    
244
        //Request listing of all objects in a container modified since a specific time.
245
        //If the *since* value is missing, return all objects
246
        public IList<ObjectInfo> ListSharedObjects(DateTime? since = null)
247
        {
248

    
249
            using (log4net.ThreadContext.Stacks["Share"].Push("List Objects"))
250
            {
251
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
252

    
253
                var objects = new List<ObjectInfo>();
254
                var accounts = ListSharingAccounts(since);
255
                foreach (var account in accounts)
256
                {
257
                    var containers = ListContainers(account.name);
258
                    foreach (var container in containers)
259
                    {
260
                        var containerObjects = ListObjects(account.name, container.Name, null);
261
                        objects.AddRange(containerObjects);
262
                    }
263
                }
264
                if (Log.IsDebugEnabled) Log.DebugFormat("END");
265
                return objects;
266
            }
267
        }
268

    
269
        public void ShareObject(string account, string container, string objectName, string shareTo, bool read, bool write)
270
        {
271
            if (String.IsNullOrWhiteSpace(Token))
272
                throw new InvalidOperationException("The Token is not set");
273
            if (StorageUrl==null)
274
                throw new InvalidOperationException("The StorageUrl is not set");
275
            if (String.IsNullOrWhiteSpace(container))
276
                throw new ArgumentNullException("container");
277
            if (String.IsNullOrWhiteSpace(objectName))
278
                throw new ArgumentNullException("objectName");
279
            if (String.IsNullOrWhiteSpace(account))
280
                throw new ArgumentNullException("account");
281
            if (String.IsNullOrWhiteSpace(shareTo))
282
                throw new ArgumentNullException("shareTo");
283
            Contract.EndContractBlock();
284

    
285
            using (log4net.ThreadContext.Stacks["Share"].Push("Share Object"))
286
            {
287
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
288
                
289
                using (var client = new RestClient(_baseClient))
290
                {
291

    
292
                    client.BaseAddress = GetAccountUrl(account);
293

    
294
                    client.Parameters.Clear();
295
                    client.Parameters.Add("format", "json");
296

    
297
                    string permission = "";
298
                    if (write)
299
                        permission = String.Format("write={0}", shareTo);
300
                    else if (read)
301
                        permission = String.Format("read={0}", shareTo);
302
                    client.Headers.Add("X-Object-Sharing", permission);
303

    
304
                    var content = client.DownloadStringWithRetry(container, 3);
305

    
306
                    client.AssertStatusOK("ShareObject failed");
307

    
308
                    //If the result is empty, return an empty list,
309
                    var infos = String.IsNullOrWhiteSpace(content)
310
                                    ? new List<ObjectInfo>()
311
                                //Otherwise deserialize the object list into a list of ObjectInfos
312
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
313

    
314
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
315
                }
316
            }
317

    
318

    
319
        }
320

    
321
        public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
322
        {
323
            if (accountInfo==null)
324
                throw new ArgumentNullException("accountInfo");
325
            Contract.EndContractBlock();
326

    
327
            using (log4net.ThreadContext.Stacks["Account"].Push("GetPolicies"))
328
            {
329
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
330

    
331
                using (var client = new RestClient(_baseClient))
332
                {
333
                    if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
334
                        client.BaseAddress = GetAccountUrl(accountInfo.UserName);
335

    
336
                    client.Parameters.Clear();
337
                    client.Parameters.Add("format", "json");                    
338
                    client.Head(String.Empty, 3);
339

    
340
                    var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
341
                    var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
342

    
343
                    long quota, bytes;
344
                    if (long.TryParse(quotaValue, out quota))
345
                        accountInfo.Quota = quota;
346
                    if (long.TryParse(bytesValue, out bytes))
347
                        accountInfo.BytesUsed = bytes;
348
                    
349
                    return accountInfo;
350

    
351
                }
352

    
353
            }
354
        }
355

    
356

    
357
        public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
358
        {
359
            if (String.IsNullOrWhiteSpace(container))
360
                throw new ArgumentNullException("container");
361
            Contract.EndContractBlock();
362

    
363
            using (log4net.ThreadContext.Stacks["Objects"].Push("List"))
364
            {
365
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
366

    
367
                using (var client = new RestClient(_baseClient))
368
                {
369
                    if (!String.IsNullOrWhiteSpace(account))
370
                        client.BaseAddress = GetAccountUrl(account);
371

    
372
                    client.Parameters.Clear();
373
                    client.Parameters.Add("format", "json");
374
                    client.IfModifiedSince = since;
375
                    var content = client.DownloadStringWithRetry(container, 3);
376

    
377
                    client.AssertStatusOK("ListObjects failed");
378

    
379
                    //If the result is empty, return an empty list,
380
                    var infos = String.IsNullOrWhiteSpace(content)
381
                                    ? new List<ObjectInfo>()
382
                                //Otherwise deserialize the object list into a list of ObjectInfos
383
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
384

    
385
                    foreach (var info in infos)
386
                    {
387
                        info.Container = container;
388
                        info.Account = account;
389
                    }
390
                    if (Log.IsDebugEnabled) Log.DebugFormat("START");
391
                    return infos;
392
                }
393
            }
394
        }
395

    
396

    
397

    
398
        public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
399
        {
400
            if (String.IsNullOrWhiteSpace(container))
401
                throw new ArgumentNullException("container");
402
            if (String.IsNullOrWhiteSpace(folder))
403
                throw new ArgumentNullException("folder");
404
            Contract.EndContractBlock();
405

    
406
            using (log4net.ThreadContext.Stacks["Objects"].Push("List"))
407
            {
408
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
409

    
410
                using (var client = new RestClient(_baseClient))
411
                {
412
                    if (!String.IsNullOrWhiteSpace(account))
413
                        client.BaseAddress = GetAccountUrl(account);
414

    
415
                    client.Parameters.Clear();
416
                    client.Parameters.Add("format", "json");
417
                    client.Parameters.Add("path", folder);
418
                    client.IfModifiedSince = since;
419
                    var content = client.DownloadStringWithRetry(container, 3);
420
                    client.AssertStatusOK("ListObjects failed");
421

    
422
                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
423

    
424
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
425
                    return infos;
426
                }
427
            }
428
        }
429

    
430
 
431
        public bool ContainerExists(string account, string container)
432
        {
433
            if (String.IsNullOrWhiteSpace(container))
434
                throw new ArgumentNullException("container", "The container property can't be empty");
435
            Contract.EndContractBlock();
436

    
437
            using (log4net.ThreadContext.Stacks["Containters"].Push("Exists"))
438
            {
439
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
440

    
441
                using (var client = new RestClient(_baseClient))
442
                {
443
                    if (!String.IsNullOrWhiteSpace(account))
444
                        client.BaseAddress = GetAccountUrl(account);
445

    
446
                    client.Parameters.Clear();
447
                    client.Head(container, 3);
448
                                        
449
                    bool result;
450
                    switch (client.StatusCode)
451
                    {
452
                        case HttpStatusCode.OK:
453
                        case HttpStatusCode.NoContent:
454
                            result=true;
455
                            break;
456
                        case HttpStatusCode.NotFound:
457
                            result=false;
458
                            break;
459
                        default:
460
                            throw CreateWebException("ContainerExists", client.StatusCode);
461
                    }
462
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
463

    
464
                    return result;
465
                }
466
                
467
            }
468
        }
469

    
470
        public bool ObjectExists(string account, string container, string objectName)
471
        {
472
            if (String.IsNullOrWhiteSpace(container))
473
                throw new ArgumentNullException("container", "The container property can't be empty");
474
            if (String.IsNullOrWhiteSpace(objectName))
475
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
476
            Contract.EndContractBlock();
477

    
478
            using (var client = new RestClient(_baseClient))
479
            {
480
                if (!String.IsNullOrWhiteSpace(account))
481
                    client.BaseAddress = GetAccountUrl(account);
482

    
483
                client.Parameters.Clear();
484
                client.Head(container + "/" + objectName, 3);
485

    
486
                switch (client.StatusCode)
487
                {
488
                    case HttpStatusCode.OK:
489
                    case HttpStatusCode.NoContent:
490
                        return true;
491
                    case HttpStatusCode.NotFound:
492
                        return false;
493
                    default:
494
                        throw CreateWebException("ObjectExists", client.StatusCode);
495
                }
496
            }
497

    
498
        }
499

    
500
        public ObjectInfo GetObjectInfo(string account, string container, string objectName)
501
        {
502
            if (String.IsNullOrWhiteSpace(container))
503
                throw new ArgumentNullException("container", "The container property can't be empty");
504
            if (String.IsNullOrWhiteSpace(objectName))
505
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
506
            Contract.EndContractBlock();
507

    
508
            using (log4net.ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
509
            {                
510

    
511
                using (var client = new RestClient(_baseClient))
512
                {
513
                    if (!String.IsNullOrWhiteSpace(account))
514
                        client.BaseAddress = GetAccountUrl(account);
515
                    try
516
                    {
517
                        client.Parameters.Clear();
518

    
519
                        client.Head(container + "/" + objectName, 3);
520

    
521
                        if (client.TimedOut)
522
                            return ObjectInfo.Empty;
523

    
524
                        switch (client.StatusCode)
525
                        {
526
                            case HttpStatusCode.OK:
527
                            case HttpStatusCode.NoContent:
528
                                var keys = client.ResponseHeaders.AllKeys.AsQueryable();
529
                                var tags = (from key in keys
530
                                            where key.StartsWith("X-Object-Meta-")
531
                                            let name = key.Substring(14)
532
                                            select new {Name = name, Value = client.ResponseHeaders[name]})
533
                                    .ToDictionary(t => t.Name, t => t.Value);
534
                                var extensions = (from key in keys
535
                                                  where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
536
                                                  select new {Name = key, Value = client.ResponseHeaders[key]})
537
                                    .ToDictionary(t => t.Name, t => t.Value);
538
                                var info = new ObjectInfo
539
                                               {
540
                                                   Account = account,
541
                                                   Container = container,
542
                                                   Name = objectName,
543
                                                   Hash = client.GetHeaderValue("ETag"),
544
                                                   Content_Type = client.GetHeaderValue("Content-Type"),
545
                                                   Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length")),
546
                                                   Tags = tags,
547
                                                   Last_Modified = client.LastModified,
548
                                                   Extensions = extensions
549
                                               };
550
                                return info;
551
                            case HttpStatusCode.NotFound:
552
                                return ObjectInfo.Empty;
553
                            default:
554
                                throw new WebException(
555
                                    String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
556
                                                  objectName, client.StatusCode));
557
                        }
558

    
559
                    }
560
                    catch (RetryException)
561
                    {
562
                        Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.");
563
                        return ObjectInfo.Empty;
564
                    }
565
                    catch (WebException e)
566
                    {
567
                        Log.Error(
568
                            String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
569
                                          objectName, client.StatusCode), e);
570
                        throw;
571
                    }
572
                }                
573
            }
574

    
575
        }
576

    
577
        public void CreateFolder(string account, string container, string folder)
578
        {
579
            if (String.IsNullOrWhiteSpace(container))
580
                throw new ArgumentNullException("container", "The container property can't be empty");
581
            if (String.IsNullOrWhiteSpace(folder))
582
                throw new ArgumentNullException("folder", "The folder property can't be empty");
583
            Contract.EndContractBlock();
584

    
585
            var folderUrl=String.Format("{0}/{1}",container,folder);
586
            using (var client = new RestClient(_baseClient))
587
            {
588
                if (!String.IsNullOrWhiteSpace(account))
589
                    client.BaseAddress = GetAccountUrl(account);
590

    
591
                client.Parameters.Clear();
592
                client.Headers.Add("Content-Type", @"application/directory");
593
                client.Headers.Add("Content-Length", "0");
594
                client.PutWithRetry(folderUrl, 3);
595

    
596
                if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
597
                    throw CreateWebException("CreateFolder", client.StatusCode);
598
            }
599
        }
600

    
601
        public ContainerInfo GetContainerInfo(string account, string container)
602
        {
603
            if (String.IsNullOrWhiteSpace(container))
604
                throw new ArgumentNullException("container", "The container property can't be empty");
605
            Contract.EndContractBlock();
606

    
607
            using (var client = new RestClient(_baseClient))
608
            {
609
                if (!String.IsNullOrWhiteSpace(account))
610
                    client.BaseAddress = GetAccountUrl(account);                
611

    
612
                client.Head(container);
613
                switch (client.StatusCode)
614
                {
615
                    case HttpStatusCode.OK:
616
                    case HttpStatusCode.NoContent:
617
                        var containerInfo = new ContainerInfo
618
                                                {
619
                                                    Account=account,
620
                                                    Name = container,
621
                                                    Count =
622
                                                        long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
623
                                                    Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
624
                                                    BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
625
                                                    BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
626
                                                    Last_Modified=client.LastModified
627
                                                };
628
                        return containerInfo;
629
                    case HttpStatusCode.NotFound:
630
                        return ContainerInfo.Empty;
631
                    default:
632
                        throw CreateWebException("GetContainerInfo", client.StatusCode);
633
                }
634
            }
635
        }
636

    
637
        public void CreateContainer(string account, string container)
638
        {            
639
            if (String.IsNullOrWhiteSpace(container))
640
                throw new ArgumentNullException("container", "The container property can't be empty");
641
            Contract.EndContractBlock();
642

    
643
            using (var client = new RestClient(_baseClient))
644
            {
645
                if (!String.IsNullOrWhiteSpace(account))
646
                    client.BaseAddress = GetAccountUrl(account);
647

    
648
                client.PutWithRetry(container, 3);
649
                var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
650
                if (!expectedCodes.Contains(client.StatusCode))
651
                    throw CreateWebException("CreateContainer", client.StatusCode);
652
            }
653
        }
654

    
655
        public void DeleteContainer(string account, string container)
656
        {
657
            if (String.IsNullOrWhiteSpace(container))
658
                throw new ArgumentNullException("container", "The container property can't be empty");
659
            Contract.EndContractBlock();
660

    
661
            using (var client = new RestClient(_baseClient))
662
            {
663
                if (!String.IsNullOrWhiteSpace(account))
664
                    client.BaseAddress = GetAccountUrl(account);
665

    
666
                client.DeleteWithRetry(container, 3);
667
                var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
668
                if (!expectedCodes.Contains(client.StatusCode))
669
                    throw CreateWebException("DeleteContainer", client.StatusCode);
670
            }
671

    
672
        }
673

    
674
        /// <summary>
675
        /// 
676
        /// </summary>
677
        /// <param name="account"></param>
678
        /// <param name="container"></param>
679
        /// <param name="objectName"></param>
680
        /// <param name="fileName"></param>
681
        /// <returns></returns>
682
        /// <remarks>This method should have no timeout or a very long one</remarks>
683
        //Asynchronously download the object specified by *objectName* in a specific *container* to 
684
        // a local file
685
        public Task GetObject(string account, string container, string objectName, string fileName)
686
        {
687
            if (String.IsNullOrWhiteSpace(container))
688
                throw new ArgumentNullException("container", "The container property can't be empty");
689
            if (String.IsNullOrWhiteSpace(objectName))
690
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");            
691
            Contract.EndContractBlock();
692

    
693
            try
694
            {
695
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
696
                //object to avoid concurrency errors.
697
                //
698
                //Download operations take a long time therefore they have no timeout.
699
                var client = new RestClient(_baseClient) { Timeout = 0 };
700
                if (!String.IsNullOrWhiteSpace(account))
701
                    client.BaseAddress = GetAccountUrl(account);
702

    
703
                //The container and objectName are relative names. They are joined with the client's
704
                //BaseAddress to create the object's absolute address
705
                var builder = client.GetAddressBuilder(container, objectName);
706
                var uri = builder.Uri;
707

    
708
                //Download progress is reported to the Trace log
709
                Log.InfoFormat("[GET] START {0}", objectName);
710
                client.DownloadProgressChanged += (sender, args) => 
711
                    Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
712
                                    fileName, args.ProgressPercentage,
713
                                    args.BytesReceived,
714
                                    args.TotalBytesToReceive);                                
715

    
716

    
717
                //Start downloading the object asynchronously
718
                var downloadTask = client.DownloadFileTask(uri, fileName);
719
                
720
                //Once the download completes
721
                return downloadTask.ContinueWith(download =>
722
                                      {
723
                                          //Delete the local client object
724
                                          client.Dispose();
725
                                          //And report failure or completion
726
                                          if (download.IsFaulted)
727
                                          {
728
                                              Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
729
                                                               download.Exception);
730
                                          }
731
                                          else
732
                                          {
733
                                              Log.InfoFormat("[GET] END {0}", objectName);                                             
734
                                          }
735
                                      });
736
            }
737
            catch (Exception exc)
738
            {
739
                Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
740
                throw;
741
            }
742

    
743

    
744

    
745
        }
746

    
747
        public Task<IList<string>> PutHashMap(string account, string container, string objectName, TreeHash hash)
748
        {
749
            if (String.IsNullOrWhiteSpace(container))
750
                throw new ArgumentNullException("container");
751
            if (String.IsNullOrWhiteSpace(objectName))
752
                throw new ArgumentNullException("objectName");
753
            if (hash==null)
754
                throw new ArgumentNullException("hash");
755
            if (String.IsNullOrWhiteSpace(Token))
756
                throw new InvalidOperationException("Invalid Token");
757
            if (StorageUrl == null)
758
                throw new InvalidOperationException("Invalid Storage Url");
759
            Contract.EndContractBlock();
760

    
761

    
762
            //Don't use a timeout because putting the hashmap may be a long process
763
            var client = new RestClient(_baseClient) { Timeout = 0 };
764
            if (!String.IsNullOrWhiteSpace(account))
765
                client.BaseAddress = GetAccountUrl(account);
766

    
767
            //The container and objectName are relative names. They are joined with the client's
768
            //BaseAddress to create the object's absolute address
769
            var builder = client.GetAddressBuilder(container, objectName);
770
            builder.Query = "format=json&hashmap";
771
            var uri = builder.Uri;
772

    
773

    
774
            //Send the tree hash as Json to the server            
775
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
776
            var uploadTask=client.UploadStringTask(uri, "PUT", hash.ToJson());
777

    
778
            
779
            return uploadTask.ContinueWith(t =>
780
            {
781

    
782
                var empty = (IList<string>)new List<string>();
783
                
784

    
785
                //The server will respond either with 201-created if all blocks were already on the server
786
                if (client.StatusCode == HttpStatusCode.Created)                    
787
                {
788
                    //in which case we return an empty hash list
789
                    return empty;
790
                }
791
                //or with a 409-conflict and return the list of missing parts
792
                //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception                
793
                if (t.IsFaulted)
794
                {
795
                    var ex = t.Exception.InnerException;
796
                    var we = ex as WebException;
797
                    var response = we.Response as HttpWebResponse;
798
                    if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
799
                    {
800
                        //In case of 409 the missing parts will be in the response content                        
801
                        using (var stream = response.GetResponseStream())
802
                        using(var reader=new StreamReader(stream))
803
                        {
804
                            //We need to cleanup the content before returning it because it contains
805
                            //error content after the list of hashes
806
                            var hashes = new List<string>();
807
                            string line=null;
808
                            //All lines up to the first empty line are hashes
809
                            while(!String.IsNullOrWhiteSpace(line=reader.ReadLine()))
810
                            {
811
                                hashes.Add(line);
812
                            }
813

    
814
                            return hashes;
815
                        }                        
816
                    }
817
                    else
818
                        //Any other status code is unexpected and the exception should be rethrown
819
                        throw ex;
820
                    
821
                }
822
                //Any other status code is unexpected but there was no exception. We can probably continue processing
823
                else
824
                {
825
                    Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
826
                }
827
                return empty;
828
            });
829

    
830
        }
831

    
832
        public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
833
        {
834
            if (String.IsNullOrWhiteSpace(Token))
835
                throw new InvalidOperationException("Invalid Token");
836
            if (StorageUrl == null)
837
                throw new InvalidOperationException("Invalid Storage Url");
838
            if (String.IsNullOrWhiteSpace(container))
839
                throw new ArgumentNullException("container");
840
            if (relativeUrl== null)
841
                throw new ArgumentNullException("relativeUrl");
842
            if (end.HasValue && end<0)
843
                throw new ArgumentOutOfRangeException("end");
844
            if (start<0)
845
                throw new ArgumentOutOfRangeException("start");
846
            Contract.EndContractBlock();
847

    
848

    
849
            //Don't use a timeout because putting the hashmap may be a long process
850
            var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end};
851
            if (!String.IsNullOrWhiteSpace(account))
852
                client.BaseAddress = GetAccountUrl(account);
853

    
854
            var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
855
            var uri = builder.Uri;
856

    
857
            return client.DownloadDataTask(uri)
858
                .ContinueWith(t=>
859
                                  {
860
                                      client.Dispose();
861
                                      return t.Result;
862
                                  });
863
        }
864

    
865

    
866
        public Task PostBlock(string account, string container, byte[] block, int offset, int count)
867
        {
868
            if (String.IsNullOrWhiteSpace(container))
869
                throw new ArgumentNullException("container");
870
            if (block == null)
871
                throw new ArgumentNullException("block");
872
            if (offset < 0 || offset >= block.Length)
873
                throw new ArgumentOutOfRangeException("offset");
874
            if (count < 0 || count > block.Length)
875
                throw new ArgumentOutOfRangeException("count");
876
            if (String.IsNullOrWhiteSpace(Token))
877
                throw new InvalidOperationException("Invalid Token");
878
            if (StorageUrl == null)
879
                throw new InvalidOperationException("Invalid Storage Url");                        
880
            Contract.EndContractBlock();
881

    
882
                        
883
            //Don't use a timeout because putting the hashmap may be a long process
884
            var client = new RestClient(_baseClient) { Timeout = 0 };
885
            if (!String.IsNullOrWhiteSpace(account))
886
                client.BaseAddress = GetAccountUrl(account);
887

    
888
            var builder = client.GetAddressBuilder(container, "");
889
            //We are doing an update
890
            builder.Query = "update";
891
            var uri = builder.Uri;
892

    
893
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
894

    
895
            Log.InfoFormat("[BLOCK POST] START");
896

    
897
            client.UploadProgressChanged += (sender, args) => 
898
                Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
899
                                    args.ProgressPercentage, args.BytesSent,
900
                                    args.TotalBytesToSend);
901
            client.UploadFileCompleted += (sender, args) => 
902
                Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
903

    
904
            
905
            //Send the block
906
            var uploadTask = client.UploadDataTask(uri, "POST", block)
907
            .ContinueWith(upload =>
908
            {
909
                client.Dispose();
910

    
911
                if (upload.IsFaulted)
912
                {
913
                    var exception = upload.Exception.InnerException;
914
                    Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exception);                        
915
                    throw exception;
916
                }
917
                    
918
                Log.InfoFormat("[BLOCK POST] END");
919
            });
920
            return uploadTask;            
921
        }
922

    
923

    
924
        public Task<TreeHash> GetHashMap(string account, string container, string objectName)
925
        {
926
            if (String.IsNullOrWhiteSpace(container))
927
                throw new ArgumentNullException("container");
928
            if (String.IsNullOrWhiteSpace(objectName))
929
                throw new ArgumentNullException("objectName");
930
            if (String.IsNullOrWhiteSpace(Token))
931
                throw new InvalidOperationException("Invalid Token");
932
            if (StorageUrl == null)
933
                throw new InvalidOperationException("Invalid Storage Url");
934
            Contract.EndContractBlock();
935

    
936
            try
937
            {
938
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
939
                //object to avoid concurrency errors.
940
                //
941
                //Download operations take a long time therefore they have no timeout.
942
                //TODO: Do we really? this is a hashmap operation, not a download
943
                var client = new RestClient(_baseClient) { Timeout = 0 };
944
                if (!String.IsNullOrWhiteSpace(account))
945
                    client.BaseAddress = GetAccountUrl(account);
946

    
947

    
948
                //The container and objectName are relative names. They are joined with the client's
949
                //BaseAddress to create the object's absolute address
950
                var builder = client.GetAddressBuilder(container, objectName);
951
                builder.Query = "format=json&hashmap";
952
                var uri = builder.Uri;
953
                
954
                //Start downloading the object asynchronously
955
                var downloadTask = client.DownloadStringTask(uri);
956
                
957
                //Once the download completes
958
                return downloadTask.ContinueWith(download =>
959
                {
960
                    //Delete the local client object
961
                    client.Dispose();
962
                    //And report failure or completion
963
                    if (download.IsFaulted)
964
                    {
965
                        Log.ErrorFormat("[GET HASH] FAIL for {0} with \r{1}", objectName,
966
                                        download.Exception);
967
                        throw download.Exception;
968
                    }
969
                                          
970
                    //The server will return an empty string if the file is empty
971
                    var json = download.Result;
972
                    var treeHash = TreeHash.Parse(json);
973
                    Log.InfoFormat("[GET HASH] END {0}", objectName);                                             
974
                    return treeHash;
975
                });
976
            }
977
            catch (Exception exc)
978
            {
979
                Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
980
                throw;
981
            }
982

    
983

    
984

    
985
        }
986

    
987

    
988
        /// <summary>
989
        /// 
990
        /// </summary>
991
        /// <param name="account"></param>
992
        /// <param name="container"></param>
993
        /// <param name="objectName"></param>
994
        /// <param name="fileName"></param>
995
        /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
996
        /// <remarks>>This method should have no timeout or a very long one</remarks>
997
        public Task PutObject(string account, string container, string objectName, string fileName, string hash = null)
998
        {
999
            if (String.IsNullOrWhiteSpace(container))
1000
                throw new ArgumentNullException("container", "The container property can't be empty");
1001
            if (String.IsNullOrWhiteSpace(objectName))
1002
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1003
            if (String.IsNullOrWhiteSpace(fileName))
1004
                throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1005
            if (!File.Exists(fileName))
1006
                throw new FileNotFoundException("The file does not exist",fileName);
1007
            Contract.EndContractBlock();
1008
            
1009
            try
1010
            {
1011

    
1012
                var client = new RestClient(_baseClient){Timeout=0};
1013
                if (!String.IsNullOrWhiteSpace(account))
1014
                    client.BaseAddress = GetAccountUrl(account);
1015

    
1016
                var builder = client.GetAddressBuilder(container, objectName);
1017
                var uri = builder.Uri;
1018

    
1019
                string etag = hash ?? CalculateHash(fileName);
1020

    
1021
                client.Headers.Add("Content-Type", "application/octet-stream");
1022
                client.Headers.Add("ETag", etag);
1023

    
1024

    
1025
                Log.InfoFormat("[PUT] START {0}", objectName);
1026
                client.UploadProgressChanged += (sender, args) =>
1027
                {
1028
                    using (log4net.ThreadContext.Stacks["PUT"].Push("Progress"))
1029
                    {
1030
                        Log.InfoFormat("{0} {1}% {2} of {3}", fileName, args.ProgressPercentage,
1031
                                       args.BytesSent, args.TotalBytesToSend);
1032
                    }
1033
                };
1034

    
1035
                client.UploadFileCompleted += (sender, args) =>
1036
                {
1037
                    using (log4net.ThreadContext.Stacks["PUT"].Push("Progress"))
1038
                    {
1039
                        Log.InfoFormat("Completed {0}", fileName);
1040
                    }
1041
                };
1042
                return client.UploadFileTask(uri, "PUT", fileName)
1043
                    .ContinueWith(upload=>
1044
                                      {
1045
                                          client.Dispose();
1046

    
1047
                                          if (upload.IsFaulted)
1048
                                          {
1049
                                              var exc = upload.Exception.InnerException;
1050
                                              Log.ErrorFormat("[PUT] FAIL for {0} with \r{1}",objectName,exc);
1051
                                              throw exc;
1052
                                          }
1053
                                          else
1054
                                            Log.InfoFormat("[PUT] END {0}", objectName);
1055
                                      });
1056
            }
1057
            catch (Exception exc)
1058
            {
1059
                Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1060
                throw;
1061
            }                
1062

    
1063
        }
1064
       
1065
        
1066
        private static string CalculateHash(string fileName)
1067
        {
1068
            Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1069
            Contract.EndContractBlock();
1070

    
1071
            string hash;
1072
            using (var hasher = MD5.Create())
1073
            using(var stream=File.OpenRead(fileName))
1074
            {
1075
                var hashBuilder=new StringBuilder();
1076
                foreach (byte b in hasher.ComputeHash(stream))
1077
                    hashBuilder.Append(b.ToString("x2").ToLower());
1078
                hash = hashBuilder.ToString();                
1079
            }
1080
            return hash;
1081
        }
1082
        
1083
        public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1084
        {
1085
            if (String.IsNullOrWhiteSpace(sourceContainer))
1086
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1087
            if (String.IsNullOrWhiteSpace(oldObjectName))
1088
                throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1089
            if (String.IsNullOrWhiteSpace(targetContainer))
1090
                throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1091
            if (String.IsNullOrWhiteSpace(newObjectName))
1092
                throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1093
            Contract.EndContractBlock();
1094

    
1095
            var targetUrl = targetContainer + "/" + newObjectName;
1096
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1097

    
1098
            using (var client = new RestClient(_baseClient))
1099
            {
1100
                if (!String.IsNullOrWhiteSpace(account))
1101
                    client.BaseAddress = GetAccountUrl(account);
1102

    
1103
                client.Headers.Add("X-Move-From", sourceUrl);
1104
                client.PutWithRetry(targetUrl, 3);
1105

    
1106
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1107
                if (!expectedCodes.Contains(client.StatusCode))
1108
                    throw CreateWebException("MoveObject", client.StatusCode);
1109
            }
1110
        }
1111

    
1112
        public void DeleteObject(string account, string sourceContainer, string objectName)
1113
        {            
1114
            if (String.IsNullOrWhiteSpace(sourceContainer))
1115
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1116
            if (String.IsNullOrWhiteSpace(objectName))
1117
                throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1118
            Contract.EndContractBlock();
1119

    
1120
            var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1121
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1122

    
1123
            using (var client = new RestClient(_baseClient))
1124
            {
1125
                if (!String.IsNullOrWhiteSpace(account))
1126
                    client.BaseAddress = GetAccountUrl(account);
1127

    
1128
                client.Headers.Add("X-Move-From", sourceUrl);
1129
                client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1130
                client.PutWithRetry(targetUrl, 3);
1131

    
1132
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1133
                if (!expectedCodes.Contains(client.StatusCode))
1134
                    throw CreateWebException("DeleteObject", client.StatusCode);
1135
            }
1136
        }
1137

    
1138
      
1139
        private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1140
        {
1141
            return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1142
        }
1143

    
1144
        
1145
    }
1146

    
1147
    public class ShareAccountInfo
1148
    {
1149
        public DateTime? last_modified { get; set; }
1150
        public string name { get; set; }
1151
    }
1152
}