Statistics
| Branch: | Revision:

root / trunk / Pithos.Network / CloudFilesClient.cs @ ff26eb71

History | View | Annotate | Download (51.5 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 SetTags(ObjectInfo target,IDictionary<string,string> tags)
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 (target == null)
276
                throw new ArgumentNullException("target");
277
            Contract.EndContractBlock();
278

    
279
            using (log4net.ThreadContext.Stacks["Share"].Push("Share Object"))
280
            {
281
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
282

    
283
                using (var client = new RestClient(_baseClient))
284
                {
285

    
286
                    client.BaseAddress = GetAccountUrl(target.Account);
287

    
288
                    client.Parameters.Clear();
289
                    client.Parameters.Add("update", "");
290

    
291
                    foreach (var tag in tags)
292
                    {
293
                        var headerTag = String.Format("X-Object-Meta-{0}", tag.Key);
294
                        client.Headers.Add(headerTag, tag.Value);
295
                    }
296
                    
297
                    var content = client.DownloadStringWithRetry(target.Container, 3);
298

    
299
                    
300
                    client.AssertStatusOK("SetTags failed");
301
                    //If the status is NOT ACCEPTED we have a problem
302
                    if (client.StatusCode != HttpStatusCode.Accepted)
303
                    {
304
                        Log.Error("Failed to set tags");
305
                        throw new Exception("Failed to set tags");
306
                    }
307

    
308
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
309
                }
310
            }
311

    
312

    
313
        }
314

    
315
        public void ShareObject(string account, string container, string objectName, string shareTo, bool read, bool write)
316
        {
317
            if (String.IsNullOrWhiteSpace(Token))
318
                throw new InvalidOperationException("The Token is not set");
319
            if (StorageUrl==null)
320
                throw new InvalidOperationException("The StorageUrl is not set");
321
            if (String.IsNullOrWhiteSpace(container))
322
                throw new ArgumentNullException("container");
323
            if (String.IsNullOrWhiteSpace(objectName))
324
                throw new ArgumentNullException("objectName");
325
            if (String.IsNullOrWhiteSpace(account))
326
                throw new ArgumentNullException("account");
327
            if (String.IsNullOrWhiteSpace(shareTo))
328
                throw new ArgumentNullException("shareTo");
329
            Contract.EndContractBlock();
330

    
331
            using (log4net.ThreadContext.Stacks["Share"].Push("Share Object"))
332
            {
333
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
334
                
335
                using (var client = new RestClient(_baseClient))
336
                {
337

    
338
                    client.BaseAddress = GetAccountUrl(account);
339

    
340
                    client.Parameters.Clear();
341
                    client.Parameters.Add("format", "json");
342

    
343
                    string permission = "";
344
                    if (write)
345
                        permission = String.Format("write={0}", shareTo);
346
                    else if (read)
347
                        permission = String.Format("read={0}", shareTo);
348
                    client.Headers.Add("X-Object-Sharing", permission);
349

    
350
                    var content = client.DownloadStringWithRetry(container, 3);
351

    
352
                    client.AssertStatusOK("ShareObject failed");
353

    
354
                    //If the result is empty, return an empty list,
355
                    var infos = String.IsNullOrWhiteSpace(content)
356
                                    ? new List<ObjectInfo>()
357
                                //Otherwise deserialize the object list into a list of ObjectInfos
358
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
359

    
360
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
361
                }
362
            }
363

    
364

    
365
        }
366

    
367
        public AccountInfo GetAccountPolicies(AccountInfo accountInfo)
368
        {
369
            if (accountInfo==null)
370
                throw new ArgumentNullException("accountInfo");
371
            Contract.EndContractBlock();
372

    
373
            using (log4net.ThreadContext.Stacks["Account"].Push("GetPolicies"))
374
            {
375
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
376

    
377
                using (var client = new RestClient(_baseClient))
378
                {
379
                    if (!String.IsNullOrWhiteSpace(accountInfo.UserName))
380
                        client.BaseAddress = GetAccountUrl(accountInfo.UserName);
381

    
382
                    client.Parameters.Clear();
383
                    client.Parameters.Add("format", "json");                    
384
                    client.Head(String.Empty, 3);
385

    
386
                    var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"];
387
                    var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"];
388

    
389
                    long quota, bytes;
390
                    if (long.TryParse(quotaValue, out quota))
391
                        accountInfo.Quota = quota;
392
                    if (long.TryParse(bytesValue, out bytes))
393
                        accountInfo.BytesUsed = bytes;
394
                    
395
                    return accountInfo;
396

    
397
                }
398

    
399
            }
400
        }
401

    
402

    
403
        public IList<ObjectInfo> ListObjects(string account, string container, DateTime? since = null)
404
        {
405
            if (String.IsNullOrWhiteSpace(container))
406
                throw new ArgumentNullException("container");
407
            Contract.EndContractBlock();
408

    
409
            using (log4net.ThreadContext.Stacks["Objects"].Push("List"))
410
            {
411
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
412

    
413
                using (var client = new RestClient(_baseClient))
414
                {
415
                    if (!String.IsNullOrWhiteSpace(account))
416
                        client.BaseAddress = GetAccountUrl(account);
417

    
418
                    client.Parameters.Clear();
419
                    client.Parameters.Add("format", "json");
420
                    client.IfModifiedSince = since;
421
                    var content = client.DownloadStringWithRetry(container, 3);
422

    
423
                    client.AssertStatusOK("ListObjects failed");
424

    
425
                    //If the result is empty, return an empty list,
426
                    var infos = String.IsNullOrWhiteSpace(content)
427
                                    ? new List<ObjectInfo>()
428
                                //Otherwise deserialize the object list into a list of ObjectInfos
429
                                    : JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
430

    
431
                    foreach (var info in infos)
432
                    {
433
                        info.Container = container;
434
                        info.Account = account;
435
                    }
436
                    if (Log.IsDebugEnabled) Log.DebugFormat("START");
437
                    return infos;
438
                }
439
            }
440
        }
441

    
442

    
443

    
444
        public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
445
        {
446
            if (String.IsNullOrWhiteSpace(container))
447
                throw new ArgumentNullException("container");
448
            if (String.IsNullOrWhiteSpace(folder))
449
                throw new ArgumentNullException("folder");
450
            Contract.EndContractBlock();
451

    
452
            using (log4net.ThreadContext.Stacks["Objects"].Push("List"))
453
            {
454
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
455

    
456
                using (var client = new RestClient(_baseClient))
457
                {
458
                    if (!String.IsNullOrWhiteSpace(account))
459
                        client.BaseAddress = GetAccountUrl(account);
460

    
461
                    client.Parameters.Clear();
462
                    client.Parameters.Add("format", "json");
463
                    client.Parameters.Add("path", folder);
464
                    client.IfModifiedSince = since;
465
                    var content = client.DownloadStringWithRetry(container, 3);
466
                    client.AssertStatusOK("ListObjects failed");
467

    
468
                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
469

    
470
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
471
                    return infos;
472
                }
473
            }
474
        }
475

    
476
 
477
        public bool ContainerExists(string account, string container)
478
        {
479
            if (String.IsNullOrWhiteSpace(container))
480
                throw new ArgumentNullException("container", "The container property can't be empty");
481
            Contract.EndContractBlock();
482

    
483
            using (log4net.ThreadContext.Stacks["Containters"].Push("Exists"))
484
            {
485
                if (Log.IsDebugEnabled) Log.DebugFormat("START");
486

    
487
                using (var client = new RestClient(_baseClient))
488
                {
489
                    if (!String.IsNullOrWhiteSpace(account))
490
                        client.BaseAddress = GetAccountUrl(account);
491

    
492
                    client.Parameters.Clear();
493
                    client.Head(container, 3);
494
                                        
495
                    bool result;
496
                    switch (client.StatusCode)
497
                    {
498
                        case HttpStatusCode.OK:
499
                        case HttpStatusCode.NoContent:
500
                            result=true;
501
                            break;
502
                        case HttpStatusCode.NotFound:
503
                            result=false;
504
                            break;
505
                        default:
506
                            throw CreateWebException("ContainerExists", client.StatusCode);
507
                    }
508
                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
509

    
510
                    return result;
511
                }
512
                
513
            }
514
        }
515

    
516
        public bool ObjectExists(string account, string container, string objectName)
517
        {
518
            if (String.IsNullOrWhiteSpace(container))
519
                throw new ArgumentNullException("container", "The container property can't be empty");
520
            if (String.IsNullOrWhiteSpace(objectName))
521
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
522
            Contract.EndContractBlock();
523

    
524
            using (var client = new RestClient(_baseClient))
525
            {
526
                if (!String.IsNullOrWhiteSpace(account))
527
                    client.BaseAddress = GetAccountUrl(account);
528

    
529
                client.Parameters.Clear();
530
                client.Head(container + "/" + objectName, 3);
531

    
532
                switch (client.StatusCode)
533
                {
534
                    case HttpStatusCode.OK:
535
                    case HttpStatusCode.NoContent:
536
                        return true;
537
                    case HttpStatusCode.NotFound:
538
                        return false;
539
                    default:
540
                        throw CreateWebException("ObjectExists", client.StatusCode);
541
                }
542
            }
543

    
544
        }
545

    
546
        public ObjectInfo GetObjectInfo(string account, string container, string objectName)
547
        {
548
            if (String.IsNullOrWhiteSpace(container))
549
                throw new ArgumentNullException("container", "The container property can't be empty");
550
            if (String.IsNullOrWhiteSpace(objectName))
551
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
552
            Contract.EndContractBlock();
553

    
554
            using (log4net.ThreadContext.Stacks["Objects"].Push("GetObjectInfo"))
555
            {                
556

    
557
                using (var client = new RestClient(_baseClient))
558
                {
559
                    if (!String.IsNullOrWhiteSpace(account))
560
                        client.BaseAddress = GetAccountUrl(account);
561
                    try
562
                    {
563
                        client.Parameters.Clear();
564

    
565
                        client.Head(container + "/" + objectName, 3);
566

    
567
                        if (client.TimedOut)
568
                            return ObjectInfo.Empty;
569

    
570
                        switch (client.StatusCode)
571
                        {
572
                            case HttpStatusCode.OK:
573
                            case HttpStatusCode.NoContent:
574
                                var keys = client.ResponseHeaders.AllKeys.AsQueryable();
575
                                var tags = (from key in keys
576
                                            where key.StartsWith("X-Object-Meta-")
577
                                            let name = key.Substring(14)
578
                                            select new {Name = name, Value = client.ResponseHeaders[name]})
579
                                    .ToDictionary(t => t.Name, t => t.Value);
580
                                var extensions = (from key in keys
581
                                                  where key.StartsWith("X-Object-") && !key.StartsWith("X-Object-Meta-")
582
                                                  select new {Name = key, Value = client.ResponseHeaders[key]})
583
                                    .ToDictionary(t => t.Name, t => t.Value);
584
                                var info = new ObjectInfo
585
                                               {
586
                                                   Account = account,
587
                                                   Container = container,
588
                                                   Name = objectName,
589
                                                   Hash = client.GetHeaderValue("ETag"),
590
                                                   Content_Type = client.GetHeaderValue("Content-Type"),
591
                                                   Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length")),
592
                                                   Tags = tags,
593
                                                   Last_Modified = client.LastModified,
594
                                                   Extensions = extensions
595
                                               };
596
                                return info;
597
                            case HttpStatusCode.NotFound:
598
                                return ObjectInfo.Empty;
599
                            default:
600
                                throw new WebException(
601
                                    String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
602
                                                  objectName, client.StatusCode));
603
                        }
604

    
605
                    }
606
                    catch (RetryException)
607
                    {
608
                        Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.");
609
                        return ObjectInfo.Empty;
610
                    }
611
                    catch (WebException e)
612
                    {
613
                        Log.Error(
614
                            String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}",
615
                                          objectName, client.StatusCode), e);
616
                        throw;
617
                    }
618
                }                
619
            }
620

    
621
        }
622

    
623
        public void CreateFolder(string account, string container, string folder)
624
        {
625
            if (String.IsNullOrWhiteSpace(container))
626
                throw new ArgumentNullException("container", "The container property can't be empty");
627
            if (String.IsNullOrWhiteSpace(folder))
628
                throw new ArgumentNullException("folder", "The folder property can't be empty");
629
            Contract.EndContractBlock();
630

    
631
            var folderUrl=String.Format("{0}/{1}",container,folder);
632
            using (var client = new RestClient(_baseClient))
633
            {
634
                if (!String.IsNullOrWhiteSpace(account))
635
                    client.BaseAddress = GetAccountUrl(account);
636

    
637
                client.Parameters.Clear();
638
                client.Headers.Add("Content-Type", @"application/directory");
639
                client.Headers.Add("Content-Length", "0");
640
                client.PutWithRetry(folderUrl, 3);
641

    
642
                if (client.StatusCode != HttpStatusCode.Created && client.StatusCode != HttpStatusCode.Accepted)
643
                    throw CreateWebException("CreateFolder", client.StatusCode);
644
            }
645
        }
646

    
647
        public ContainerInfo GetContainerInfo(string account, string container)
648
        {
649
            if (String.IsNullOrWhiteSpace(container))
650
                throw new ArgumentNullException("container", "The container property can't be empty");
651
            Contract.EndContractBlock();
652

    
653
            using (var client = new RestClient(_baseClient))
654
            {
655
                if (!String.IsNullOrWhiteSpace(account))
656
                    client.BaseAddress = GetAccountUrl(account);                
657

    
658
                client.Head(container);
659
                switch (client.StatusCode)
660
                {
661
                    case HttpStatusCode.OK:
662
                    case HttpStatusCode.NoContent:
663
                        var keys = client.ResponseHeaders.AllKeys.AsQueryable();
664
                        var tags = (from key in keys
665
                                    where key.StartsWith("X-Container-Meta-")
666
                                    let name = key.Substring(14)
667
                                    select new { Name = name, Value = client.ResponseHeaders[name] })
668
                                    .ToDictionary(t => t.Name, t => t.Value);
669
                        var policies= (from key in keys
670
                                    where key.StartsWith("X-Container-Policy-")
671
                                    let name = key.Substring(14)
672
                                    select new { Name = name, Value = client.ResponseHeaders[name] })
673
                                    .ToDictionary(t => t.Name, t => t.Value);
674

    
675
                        var containerInfo = new ContainerInfo
676
                                                {
677
                                                    Account=account,
678
                                                    Name = container,
679
                                                    Count =
680
                                                        long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
681
                                                    Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
682
                                                    BlockHash = client.GetHeaderValue("X-Container-Block-Hash"),
683
                                                    BlockSize=int.Parse(client.GetHeaderValue("X-Container-Block-Size")),
684
                                                    Last_Modified=client.LastModified,
685
                                                    Tags=tags,
686
                                                    Policies=policies
687
                                                };
688
                        
689

    
690
                        return containerInfo;
691
                    case HttpStatusCode.NotFound:
692
                        return ContainerInfo.Empty;
693
                    default:
694
                        throw CreateWebException("GetContainerInfo", client.StatusCode);
695
                }
696
            }
697
        }
698

    
699
        public void CreateContainer(string account, string container)
700
        {            
701
            if (String.IsNullOrWhiteSpace(container))
702
                throw new ArgumentNullException("container", "The container property can't be empty");
703
            Contract.EndContractBlock();
704

    
705
            using (var client = new RestClient(_baseClient))
706
            {
707
                if (!String.IsNullOrWhiteSpace(account))
708
                    client.BaseAddress = GetAccountUrl(account);
709

    
710
                client.PutWithRetry(container, 3);
711
                var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK};
712
                if (!expectedCodes.Contains(client.StatusCode))
713
                    throw CreateWebException("CreateContainer", client.StatusCode);
714
            }
715
        }
716

    
717
        public void DeleteContainer(string account, string container)
718
        {
719
            if (String.IsNullOrWhiteSpace(container))
720
                throw new ArgumentNullException("container", "The container property can't be empty");
721
            Contract.EndContractBlock();
722

    
723
            using (var client = new RestClient(_baseClient))
724
            {
725
                if (!String.IsNullOrWhiteSpace(account))
726
                    client.BaseAddress = GetAccountUrl(account);
727

    
728
                client.DeleteWithRetry(container, 3);
729
                var expectedCodes = new[] {HttpStatusCode.NotFound, HttpStatusCode.NoContent};
730
                if (!expectedCodes.Contains(client.StatusCode))
731
                    throw CreateWebException("DeleteContainer", client.StatusCode);
732
            }
733

    
734
        }
735

    
736
        /// <summary>
737
        /// 
738
        /// </summary>
739
        /// <param name="account"></param>
740
        /// <param name="container"></param>
741
        /// <param name="objectName"></param>
742
        /// <param name="fileName"></param>
743
        /// <returns></returns>
744
        /// <remarks>This method should have no timeout or a very long one</remarks>
745
        //Asynchronously download the object specified by *objectName* in a specific *container* to 
746
        // a local file
747
        public Task GetObject(string account, string container, string objectName, string fileName)
748
        {
749
            if (String.IsNullOrWhiteSpace(container))
750
                throw new ArgumentNullException("container", "The container property can't be empty");
751
            if (String.IsNullOrWhiteSpace(objectName))
752
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");            
753
            Contract.EndContractBlock();
754

    
755
            try
756
            {
757
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
758
                //object to avoid concurrency errors.
759
                //
760
                //Download operations take a long time therefore they have no timeout.
761
                var client = new RestClient(_baseClient) { Timeout = 0 };
762
                if (!String.IsNullOrWhiteSpace(account))
763
                    client.BaseAddress = GetAccountUrl(account);
764

    
765
                //The container and objectName are relative names. They are joined with the client's
766
                //BaseAddress to create the object's absolute address
767
                var builder = client.GetAddressBuilder(container, objectName);
768
                var uri = builder.Uri;
769

    
770
                //Download progress is reported to the Trace log
771
                Log.InfoFormat("[GET] START {0}", objectName);
772
                client.DownloadProgressChanged += (sender, args) => 
773
                    Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
774
                                    fileName, args.ProgressPercentage,
775
                                    args.BytesReceived,
776
                                    args.TotalBytesToReceive);                                
777

    
778

    
779
                //Start downloading the object asynchronously
780
                var downloadTask = client.DownloadFileTask(uri, fileName);
781
                
782
                //Once the download completes
783
                return downloadTask.ContinueWith(download =>
784
                                      {
785
                                          //Delete the local client object
786
                                          client.Dispose();
787
                                          //And report failure or completion
788
                                          if (download.IsFaulted)
789
                                          {
790
                                              Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
791
                                                               download.Exception);
792
                                          }
793
                                          else
794
                                          {
795
                                              Log.InfoFormat("[GET] END {0}", objectName);                                             
796
                                          }
797
                                      });
798
            }
799
            catch (Exception exc)
800
            {
801
                Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
802
                throw;
803
            }
804

    
805

    
806

    
807
        }
808

    
809
        public Task<IList<string>> PutHashMap(string account, string container, string objectName, TreeHash hash)
810
        {
811
            if (String.IsNullOrWhiteSpace(container))
812
                throw new ArgumentNullException("container");
813
            if (String.IsNullOrWhiteSpace(objectName))
814
                throw new ArgumentNullException("objectName");
815
            if (hash==null)
816
                throw new ArgumentNullException("hash");
817
            if (String.IsNullOrWhiteSpace(Token))
818
                throw new InvalidOperationException("Invalid Token");
819
            if (StorageUrl == null)
820
                throw new InvalidOperationException("Invalid Storage Url");
821
            Contract.EndContractBlock();
822

    
823

    
824
            //Don't use a timeout because putting the hashmap may be a long process
825
            var client = new RestClient(_baseClient) { Timeout = 0 };
826
            if (!String.IsNullOrWhiteSpace(account))
827
                client.BaseAddress = GetAccountUrl(account);
828

    
829
            //The container and objectName are relative names. They are joined with the client's
830
            //BaseAddress to create the object's absolute address
831
            var builder = client.GetAddressBuilder(container, objectName);
832
            builder.Query = "format=json&hashmap";
833
            var uri = builder.Uri;
834

    
835

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

    
840
            
841
            return uploadTask.ContinueWith(t =>
842
            {
843

    
844
                var empty = (IList<string>)new List<string>();
845
                
846

    
847
                //The server will respond either with 201-created if all blocks were already on the server
848
                if (client.StatusCode == HttpStatusCode.Created)                    
849
                {
850
                    //in which case we return an empty hash list
851
                    return empty;
852
                }
853
                //or with a 409-conflict and return the list of missing parts
854
                //A 409 will cause an exception so we need to check t.IsFaulted to avoid propagating the exception                
855
                if (t.IsFaulted)
856
                {
857
                    var ex = t.Exception.InnerException;
858
                    var we = ex as WebException;
859
                    var response = we.Response as HttpWebResponse;
860
                    if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
861
                    {
862
                        //In case of 409 the missing parts will be in the response content                        
863
                        using (var stream = response.GetResponseStream())
864
                        using(var reader=new StreamReader(stream))
865
                        {
866
                            //We need to cleanup the content before returning it because it contains
867
                            //error content after the list of hashes
868
                            var hashes = new List<string>();
869
                            string line=null;
870
                            //All lines up to the first empty line are hashes
871
                            while(!String.IsNullOrWhiteSpace(line=reader.ReadLine()))
872
                            {
873
                                hashes.Add(line);
874
                            }
875

    
876
                            return hashes;
877
                        }                        
878
                    }
879
                    else
880
                        //Any other status code is unexpected and the exception should be rethrown
881
                        throw ex;
882
                    
883
                }
884
                //Any other status code is unexpected but there was no exception. We can probably continue processing
885
                else
886
                {
887
                    Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);                    
888
                }
889
                return empty;
890
            });
891

    
892
        }
893

    
894
        public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
895
        {
896
            if (String.IsNullOrWhiteSpace(Token))
897
                throw new InvalidOperationException("Invalid Token");
898
            if (StorageUrl == null)
899
                throw new InvalidOperationException("Invalid Storage Url");
900
            if (String.IsNullOrWhiteSpace(container))
901
                throw new ArgumentNullException("container");
902
            if (relativeUrl== null)
903
                throw new ArgumentNullException("relativeUrl");
904
            if (end.HasValue && end<0)
905
                throw new ArgumentOutOfRangeException("end");
906
            if (start<0)
907
                throw new ArgumentOutOfRangeException("start");
908
            Contract.EndContractBlock();
909

    
910

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

    
916
            var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
917
            var uri = builder.Uri;
918

    
919
            return client.DownloadDataTask(uri)
920
                .ContinueWith(t=>
921
                                  {
922
                                      client.Dispose();
923
                                      return t.Result;
924
                                  });
925
        }
926

    
927

    
928
        public Task PostBlock(string account, string container, byte[] block, int offset, int count)
929
        {
930
            if (String.IsNullOrWhiteSpace(container))
931
                throw new ArgumentNullException("container");
932
            if (block == null)
933
                throw new ArgumentNullException("block");
934
            if (offset < 0 || offset >= block.Length)
935
                throw new ArgumentOutOfRangeException("offset");
936
            if (count < 0 || count > block.Length)
937
                throw new ArgumentOutOfRangeException("count");
938
            if (String.IsNullOrWhiteSpace(Token))
939
                throw new InvalidOperationException("Invalid Token");
940
            if (StorageUrl == null)
941
                throw new InvalidOperationException("Invalid Storage Url");                        
942
            Contract.EndContractBlock();
943

    
944
                        
945
            //Don't use a timeout because putting the hashmap may be a long process
946
            var client = new RestClient(_baseClient) { Timeout = 0 };
947
            if (!String.IsNullOrWhiteSpace(account))
948
                client.BaseAddress = GetAccountUrl(account);
949

    
950
            var builder = client.GetAddressBuilder(container, "");
951
            //We are doing an update
952
            builder.Query = "update";
953
            var uri = builder.Uri;
954

    
955
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
956

    
957
            Log.InfoFormat("[BLOCK POST] START");
958

    
959
            client.UploadProgressChanged += (sender, args) => 
960
                Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}",
961
                                    args.ProgressPercentage, args.BytesSent,
962
                                    args.TotalBytesToSend);
963
            client.UploadFileCompleted += (sender, args) => 
964
                Log.InfoFormat("[BLOCK POST PROGRESS] Completed ");
965

    
966
            
967
            //Send the block
968
            var uploadTask = client.UploadDataTask(uri, "POST", block)
969
            .ContinueWith(upload =>
970
            {
971
                client.Dispose();
972

    
973
                if (upload.IsFaulted)
974
                {
975
                    var exception = upload.Exception.InnerException;
976
                    Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exception);                        
977
                    throw exception;
978
                }
979
                    
980
                Log.InfoFormat("[BLOCK POST] END");
981
            });
982
            return uploadTask;            
983
        }
984

    
985

    
986
        public Task<TreeHash> GetHashMap(string account, string container, string objectName)
987
        {
988
            if (String.IsNullOrWhiteSpace(container))
989
                throw new ArgumentNullException("container");
990
            if (String.IsNullOrWhiteSpace(objectName))
991
                throw new ArgumentNullException("objectName");
992
            if (String.IsNullOrWhiteSpace(Token))
993
                throw new InvalidOperationException("Invalid Token");
994
            if (StorageUrl == null)
995
                throw new InvalidOperationException("Invalid Storage Url");
996
            Contract.EndContractBlock();
997

    
998
            try
999
            {
1000
                //WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient
1001
                //object to avoid concurrency errors.
1002
                //
1003
                //Download operations take a long time therefore they have no timeout.
1004
                //TODO: Do we really? this is a hashmap operation, not a download
1005
                var client = new RestClient(_baseClient) { Timeout = 0 };
1006
                if (!String.IsNullOrWhiteSpace(account))
1007
                    client.BaseAddress = GetAccountUrl(account);
1008

    
1009

    
1010
                //The container and objectName are relative names. They are joined with the client's
1011
                //BaseAddress to create the object's absolute address
1012
                var builder = client.GetAddressBuilder(container, objectName);
1013
                builder.Query = "format=json&hashmap";
1014
                var uri = builder.Uri;
1015
                
1016
                //Start downloading the object asynchronously
1017
                var downloadTask = client.DownloadStringTask(uri);
1018
                
1019
                //Once the download completes
1020
                return downloadTask.ContinueWith(download =>
1021
                {
1022
                    //Delete the local client object
1023
                    client.Dispose();
1024
                    //And report failure or completion
1025
                    if (download.IsFaulted)
1026
                    {
1027
                        Log.ErrorFormat("[GET HASH] FAIL for {0} with \r{1}", objectName,
1028
                                        download.Exception);
1029
                        throw download.Exception;
1030
                    }
1031
                                          
1032
                    //The server will return an empty string if the file is empty
1033
                    var json = download.Result;
1034
                    var treeHash = TreeHash.Parse(json);
1035
                    Log.InfoFormat("[GET HASH] END {0}", objectName);                                             
1036
                    return treeHash;
1037
                });
1038
            }
1039
            catch (Exception exc)
1040
            {
1041
                Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc);
1042
                throw;
1043
            }
1044

    
1045

    
1046

    
1047
        }
1048

    
1049

    
1050
        /// <summary>
1051
        /// 
1052
        /// </summary>
1053
        /// <param name="account"></param>
1054
        /// <param name="container"></param>
1055
        /// <param name="objectName"></param>
1056
        /// <param name="fileName"></param>
1057
        /// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param>
1058
        /// <remarks>>This method should have no timeout or a very long one</remarks>
1059
        public Task PutObject(string account, string container, string objectName, string fileName, string hash = null)
1060
        {
1061
            if (String.IsNullOrWhiteSpace(container))
1062
                throw new ArgumentNullException("container", "The container property can't be empty");
1063
            if (String.IsNullOrWhiteSpace(objectName))
1064
                throw new ArgumentNullException("objectName", "The objectName property can't be empty");
1065
            if (String.IsNullOrWhiteSpace(fileName))
1066
                throw new ArgumentNullException("fileName", "The fileName property can't be empty");
1067
            if (!File.Exists(fileName))
1068
                throw new FileNotFoundException("The file does not exist",fileName);
1069
            Contract.EndContractBlock();
1070
            
1071
            try
1072
            {
1073

    
1074
                var client = new RestClient(_baseClient){Timeout=0};
1075
                if (!String.IsNullOrWhiteSpace(account))
1076
                    client.BaseAddress = GetAccountUrl(account);
1077

    
1078
                var builder = client.GetAddressBuilder(container, objectName);
1079
                var uri = builder.Uri;
1080

    
1081
                string etag = hash ?? CalculateHash(fileName);
1082

    
1083
                client.Headers.Add("Content-Type", "application/octet-stream");
1084
                client.Headers.Add("ETag", etag);
1085

    
1086

    
1087
                Log.InfoFormat("[PUT] START {0}", objectName);
1088
                client.UploadProgressChanged += (sender, args) =>
1089
                {
1090
                    using (log4net.ThreadContext.Stacks["PUT"].Push("Progress"))
1091
                    {
1092
                        Log.InfoFormat("{0} {1}% {2} of {3}", fileName, args.ProgressPercentage,
1093
                                       args.BytesSent, args.TotalBytesToSend);
1094
                    }
1095
                };
1096

    
1097
                client.UploadFileCompleted += (sender, args) =>
1098
                {
1099
                    using (log4net.ThreadContext.Stacks["PUT"].Push("Progress"))
1100
                    {
1101
                        Log.InfoFormat("Completed {0}", fileName);
1102
                    }
1103
                };
1104
                return client.UploadFileTask(uri, "PUT", fileName)
1105
                    .ContinueWith(upload=>
1106
                                      {
1107
                                          client.Dispose();
1108

    
1109
                                          if (upload.IsFaulted)
1110
                                          {
1111
                                              var exc = upload.Exception.InnerException;
1112
                                              Log.ErrorFormat("[PUT] FAIL for {0} with \r{1}",objectName,exc);
1113
                                              throw exc;
1114
                                          }
1115
                                          else
1116
                                            Log.InfoFormat("[PUT] END {0}", objectName);
1117
                                      });
1118
            }
1119
            catch (Exception exc)
1120
            {
1121
                Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc);
1122
                throw;
1123
            }                
1124

    
1125
        }
1126
       
1127
        
1128
        private static string CalculateHash(string fileName)
1129
        {
1130
            Contract.Requires(!String.IsNullOrWhiteSpace(fileName));
1131
            Contract.EndContractBlock();
1132

    
1133
            string hash;
1134
            using (var hasher = MD5.Create())
1135
            using(var stream=File.OpenRead(fileName))
1136
            {
1137
                var hashBuilder=new StringBuilder();
1138
                foreach (byte b in hasher.ComputeHash(stream))
1139
                    hashBuilder.Append(b.ToString("x2").ToLower());
1140
                hash = hashBuilder.ToString();                
1141
            }
1142
            return hash;
1143
        }
1144
        
1145
        public void MoveObject(string account, string sourceContainer, string oldObjectName, string targetContainer, string newObjectName)
1146
        {
1147
            if (String.IsNullOrWhiteSpace(sourceContainer))
1148
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1149
            if (String.IsNullOrWhiteSpace(oldObjectName))
1150
                throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty");
1151
            if (String.IsNullOrWhiteSpace(targetContainer))
1152
                throw new ArgumentNullException("targetContainer", "The container property can't be empty");
1153
            if (String.IsNullOrWhiteSpace(newObjectName))
1154
                throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty");
1155
            Contract.EndContractBlock();
1156

    
1157
            var targetUrl = targetContainer + "/" + newObjectName;
1158
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, oldObjectName);
1159

    
1160
            using (var client = new RestClient(_baseClient))
1161
            {
1162
                if (!String.IsNullOrWhiteSpace(account))
1163
                    client.BaseAddress = GetAccountUrl(account);
1164

    
1165
                client.Headers.Add("X-Move-From", sourceUrl);
1166
                client.PutWithRetry(targetUrl, 3);
1167

    
1168
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
1169
                if (!expectedCodes.Contains(client.StatusCode))
1170
                    throw CreateWebException("MoveObject", client.StatusCode);
1171
            }
1172
        }
1173

    
1174
        public void DeleteObject(string account, string sourceContainer, string objectName)
1175
        {            
1176
            if (String.IsNullOrWhiteSpace(sourceContainer))
1177
                throw new ArgumentNullException("sourceContainer", "The container property can't be empty");
1178
            if (String.IsNullOrWhiteSpace(objectName))
1179
                throw new ArgumentNullException("objectName", "The oldObjectName property can't be empty");
1180
            Contract.EndContractBlock();
1181

    
1182
            var targetUrl = FolderConstants.TrashContainer + "/" + objectName;
1183
            var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName);
1184

    
1185
            using (var client = new RestClient(_baseClient))
1186
            {
1187
                if (!String.IsNullOrWhiteSpace(account))
1188
                    client.BaseAddress = GetAccountUrl(account);
1189

    
1190
                client.Headers.Add("X-Move-From", sourceUrl);
1191
                client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
1192
                client.PutWithRetry(targetUrl, 3);
1193

    
1194
                var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
1195
                if (!expectedCodes.Contains(client.StatusCode))
1196
                    throw CreateWebException("DeleteObject", client.StatusCode);
1197
            }
1198
        }
1199

    
1200
      
1201
        private static WebException CreateWebException(string operation, HttpStatusCode statusCode)
1202
        {
1203
            return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
1204
        }
1205

    
1206
        
1207
    }
1208

    
1209
    public class ShareAccountInfo
1210
    {
1211
        public DateTime? last_modified { get; set; }
1212
        public string name { get; set; }
1213
    }
1214
}