root / trunk / Pithos.Network / CloudFilesClient.cs @ 2115e2a5
History | View | Annotate | Download (86 kB)
1 |
#region |
---|---|
2 |
/* ----------------------------------------------------------------------- |
3 |
* <copyright file="CloudFilesClient.cs" company="GRNet"> |
4 |
* |
5 |
* Copyright 2011-2012 GRNET S.A. All rights reserved. |
6 |
* |
7 |
* Redistribution and use in source and binary forms, with or |
8 |
* without modification, are permitted provided that the following |
9 |
* conditions are met: |
10 |
* |
11 |
* 1. Redistributions of source code must retain the above |
12 |
* copyright notice, this list of conditions and the following |
13 |
* disclaimer. |
14 |
* |
15 |
* 2. Redistributions in binary form must reproduce the above |
16 |
* copyright notice, this list of conditions and the following |
17 |
* disclaimer in the documentation and/or other materials |
18 |
* provided with the distribution. |
19 |
* |
20 |
* |
21 |
* THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS |
22 |
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
23 |
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
24 |
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR |
25 |
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
26 |
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
27 |
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF |
28 |
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
29 |
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
30 |
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
31 |
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
32 |
* POSSIBILITY OF SUCH DAMAGE. |
33 |
* |
34 |
* The views and conclusions contained in the software and |
35 |
* documentation are those of the authors and should not be |
36 |
* interpreted as representing official policies, either expressed |
37 |
* or implied, of GRNET S.A. |
38 |
* </copyright> |
39 |
* ----------------------------------------------------------------------- |
40 |
*/ |
41 |
#endregion |
42 |
|
43 |
// **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos |
44 |
// |
45 |
// The class provides methods to upload/download files, delete files, manage containers |
46 |
|
47 |
|
48 |
using System; |
49 |
using System.Collections.Generic; |
50 |
using System.Collections.Specialized; |
51 |
using System.ComponentModel.Composition; |
52 |
using System.Diagnostics; |
53 |
using System.Diagnostics.Contracts; |
54 |
using System.IO; |
55 |
using System.Linq; |
56 |
using System.Net; |
57 |
using System.Net.Http; |
58 |
using System.Net.Http.Headers; |
59 |
using System.Reflection; |
60 |
using System.ServiceModel.Channels; |
61 |
using System.Text; |
62 |
using System.Threading; |
63 |
using System.Threading.Tasks; |
64 |
using Newtonsoft.Json; |
65 |
using Newtonsoft.Json.Linq; |
66 |
using Pithos.Interfaces; |
67 |
using Pithos.Network; |
68 |
using log4net; |
69 |
|
70 |
namespace Pithos.Network |
71 |
{ |
72 |
|
73 |
[Export(typeof(ICloudClient))] |
74 |
public class CloudFilesClient:ICloudClient,IDisposable |
75 |
{ |
76 |
private const string TOKEN_HEADER = "X-Auth-Token"; |
77 |
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); |
78 |
|
79 |
//CloudFilesClient uses *_baseClient* internally to communicate with the server |
80 |
//RestClient provides a REST-friendly interface over the standard WebClient. |
81 |
private RestClient _baseClient; |
82 |
|
83 |
private HttpClient _baseHttpClient; |
84 |
private HttpClient _baseHttpClientNoTimeout; |
85 |
|
86 |
|
87 |
//During authentication the client provides a UserName |
88 |
public string UserName { get; set; } |
89 |
|
90 |
//and and ApiKey to the server |
91 |
public string ApiKey { get; set; } |
92 |
|
93 |
//And receives an authentication Token. This token must be provided in ALL other operations, |
94 |
//in the X-Auth-Token header |
95 |
private string _token; |
96 |
private readonly string _emptyGuid = Guid.Empty.ToString(); |
97 |
private readonly Uri _emptyUri = new Uri("",UriKind.Relative); |
98 |
|
99 |
private HttpClientHandler _httpClientHandler = new HttpClientHandler |
100 |
{ |
101 |
AllowAutoRedirect = true, |
102 |
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, |
103 |
UseCookies = true, |
104 |
}; |
105 |
|
106 |
|
107 |
public string Token |
108 |
{ |
109 |
get { return _token; } |
110 |
set |
111 |
{ |
112 |
_token = value; |
113 |
_baseClient.Headers[TOKEN_HEADER] = value; |
114 |
} |
115 |
} |
116 |
|
117 |
//The client also receives a StorageUrl after authentication. All subsequent operations must |
118 |
//use this url |
119 |
public Uri StorageUrl { get; set; } |
120 |
|
121 |
|
122 |
public Uri RootAddressUri { get; set; } |
123 |
|
124 |
|
125 |
public double DownloadPercentLimit { get; set; } |
126 |
public double UploadPercentLimit { get; set; } |
127 |
|
128 |
public string AuthenticationUrl { get; set; } |
129 |
|
130 |
|
131 |
public string VersionPath |
132 |
{ |
133 |
get { return UsePithos ? "v1" : "v1.0"; } |
134 |
} |
135 |
|
136 |
public bool UsePithos { get; set; } |
137 |
|
138 |
|
139 |
BufferManager _bufferManager=BufferManager.CreateBufferManager(TreeHash.DEFAULT_BLOCK_SIZE*4,(int)TreeHash.DEFAULT_BLOCK_SIZE); |
140 |
private string _userCatalogUrl; |
141 |
|
142 |
public CloudFilesClient(string userName, string apiKey) |
143 |
{ |
144 |
UserName = userName; |
145 |
ApiKey = apiKey; |
146 |
_userCatalogUrl = "https://pithos.okeanos.io/user_catalogs"; |
147 |
} |
148 |
|
149 |
public CloudFilesClient(AccountInfo accountInfo) |
150 |
{ |
151 |
Contract.Requires<ArgumentNullException>(accountInfo!=null,"accountInfo is null"); |
152 |
Contract.Ensures(!String.IsNullOrWhiteSpace(Token)); |
153 |
Contract.Ensures(StorageUrl != null); |
154 |
Contract.Ensures(_baseClient != null); |
155 |
Contract.Ensures(RootAddressUri != null); |
156 |
Contract.EndContractBlock(); |
157 |
|
158 |
_baseClient = new RestClient |
159 |
{ |
160 |
BaseAddress = accountInfo.StorageUri.ToString(), |
161 |
Timeout = 30000, |
162 |
Retries = 3, |
163 |
}; |
164 |
StorageUrl = accountInfo.StorageUri; |
165 |
Token = accountInfo.Token; |
166 |
UserName = accountInfo.UserName; |
167 |
_userCatalogUrl = "https://pithos.okeanos.io/user_catalogs"; |
168 |
//Get the root address (StorageUrl without the account) |
169 |
var storageUrl = StorageUrl.AbsoluteUri; |
170 |
var usernameIndex = storageUrl.LastIndexOf(UserName); |
171 |
var rootUrl = storageUrl.Substring(0, usernameIndex); |
172 |
RootAddressUri = new Uri(rootUrl); |
173 |
|
174 |
var httpClientHandler = new HttpClientHandler |
175 |
{ |
176 |
AllowAutoRedirect = true, |
177 |
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, |
178 |
UseCookies = true, |
179 |
}; |
180 |
|
181 |
|
182 |
_baseHttpClient = new HttpClient(httpClientHandler) |
183 |
{ |
184 |
BaseAddress = StorageUrl, |
185 |
Timeout = TimeSpan.FromSeconds(30) |
186 |
}; |
187 |
_baseHttpClient.DefaultRequestHeaders.Add(TOKEN_HEADER, Token); |
188 |
|
189 |
_baseHttpClientNoTimeout = new HttpClient(httpClientHandler) |
190 |
{ |
191 |
BaseAddress = StorageUrl, |
192 |
Timeout = TimeSpan.FromMilliseconds(-1) |
193 |
}; |
194 |
_baseHttpClientNoTimeout.DefaultRequestHeaders.Add(TOKEN_HEADER, Token); |
195 |
|
196 |
|
197 |
} |
198 |
|
199 |
|
200 |
private static void AssertStatusOK(HttpResponseMessage response, string message) |
201 |
{ |
202 |
var statusCode = response.StatusCode; |
203 |
if (statusCode >= HttpStatusCode.BadRequest) |
204 |
throw new WebException(String.Format("{0} with code {1} - {2}", message, statusCode, response.ReasonPhrase)); |
205 |
} |
206 |
|
207 |
public async Task<AccountInfo> Authenticate() |
208 |
{ |
209 |
if (String.IsNullOrWhiteSpace(UserName)) |
210 |
throw new InvalidOperationException("UserName is empty"); |
211 |
if (String.IsNullOrWhiteSpace(ApiKey)) |
212 |
throw new InvalidOperationException("ApiKey is empty"); |
213 |
if (String.IsNullOrWhiteSpace(AuthenticationUrl)) |
214 |
throw new InvalidOperationException("AuthenticationUrl is empty"); |
215 |
Contract.Ensures(!String.IsNullOrWhiteSpace(Token)); |
216 |
Contract.Ensures(StorageUrl != null); |
217 |
Contract.Ensures(_baseClient != null); |
218 |
Contract.Ensures(RootAddressUri != null); |
219 |
Contract.EndContractBlock(); |
220 |
|
221 |
|
222 |
Log.InfoFormat("[AUTHENTICATE] Start for {0}", UserName); |
223 |
|
224 |
var groups = new List<Group>(); |
225 |
|
226 |
using (var authClient = new HttpClient(_httpClientHandler,false){ BaseAddress = new Uri(AuthenticationUrl),Timeout=TimeSpan.FromSeconds(30) }) |
227 |
{ |
228 |
|
229 |
authClient.DefaultRequestHeaders.Add("X-Auth-User", UserName); |
230 |
authClient.DefaultRequestHeaders.Add("X-Auth-Key", ApiKey); |
231 |
|
232 |
string storageUrl; |
233 |
string token; |
234 |
|
235 |
using (var response = await authClient.GetAsyncWithRetries(new Uri(VersionPath, UriKind.Relative),3).ConfigureAwait(false)) // .DownloadStringWithRetryRelative(new Uri(VersionPath, UriKind.Relative), 3); |
236 |
{ |
237 |
AssertStatusOK(response,"Authentication failed"); |
238 |
|
239 |
storageUrl = response.Headers.GetFirstValue("X-Storage-Url"); |
240 |
if (String.IsNullOrWhiteSpace(storageUrl)) |
241 |
throw new InvalidOperationException("Failed to obtain storage url"); |
242 |
|
243 |
token = response.Headers.GetFirstValue(TOKEN_HEADER); |
244 |
if (String.IsNullOrWhiteSpace(token)) |
245 |
throw new InvalidOperationException("Failed to obtain token url"); |
246 |
|
247 |
} |
248 |
|
249 |
|
250 |
_baseClient = new RestClient |
251 |
{ |
252 |
BaseAddress = storageUrl, |
253 |
Timeout = 30000, |
254 |
Retries = 3, |
255 |
}; |
256 |
|
257 |
StorageUrl = new Uri(storageUrl); |
258 |
Token = token; |
259 |
|
260 |
|
261 |
|
262 |
|
263 |
//Get the root address (StorageUrl without the account) |
264 |
var usernameIndex=storageUrl.LastIndexOf(UserName); |
265 |
var rootUrl = storageUrl.Substring(0, usernameIndex); |
266 |
RootAddressUri = new Uri(rootUrl); |
267 |
|
268 |
|
269 |
_baseHttpClient = new HttpClient(_httpClientHandler,false) |
270 |
{ |
271 |
BaseAddress = StorageUrl, |
272 |
Timeout = TimeSpan.FromSeconds(30) |
273 |
}; |
274 |
_baseHttpClient.DefaultRequestHeaders.Add(TOKEN_HEADER, token); |
275 |
|
276 |
_baseHttpClientNoTimeout = new HttpClient(_httpClientHandler,false) |
277 |
{ |
278 |
BaseAddress = StorageUrl, |
279 |
Timeout = TimeSpan.FromMilliseconds(-1) |
280 |
}; |
281 |
_baseHttpClientNoTimeout.DefaultRequestHeaders.Add(TOKEN_HEADER, token); |
282 |
|
283 |
/* var keys = authClient.ResponseHeaders.AllKeys.AsQueryable(); |
284 |
groups = (from key in keys |
285 |
where key.StartsWith("X-Account-Group-") |
286 |
let name = key.Substring(16) |
287 |
select new Group(name, authClient.ResponseHeaders[key])) |
288 |
.ToList(); |
289 |
|
290 |
*/ |
291 |
} |
292 |
|
293 |
Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName); |
294 |
Debug.Assert(_baseClient!=null); |
295 |
var displayName = UserName; |
296 |
Guid uuid; |
297 |
if (Guid.TryParse(UserName, out uuid)) |
298 |
{ |
299 |
displayName = await ResolveName(uuid); |
300 |
} |
301 |
return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,DisplayName=displayName,Groups=groups}; |
302 |
|
303 |
} |
304 |
|
305 |
private static void TraceStart(string method, Uri actualAddress) |
306 |
{ |
307 |
Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress); |
308 |
} |
309 |
|
310 |
private async Task<string> GetStringAsync(Uri targetUri, string errorMessage,DateTimeOffset? since=null) |
311 |
{ |
312 |
TraceStart("GET",targetUri); |
313 |
var request = new HttpRequestMessage(HttpMethod.Get, targetUri); |
314 |
if (since.HasValue) |
315 |
{ |
316 |
request.Headers.IfModifiedSince = since.Value; |
317 |
} |
318 |
using (var response = await _baseHttpClient.SendAsyncWithRetries(request,3).ConfigureAwait(false)) |
319 |
{ |
320 |
AssertStatusOK(response, errorMessage); |
321 |
|
322 |
if (response.StatusCode == HttpStatusCode.NoContent) |
323 |
return String.Empty; |
324 |
|
325 |
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
326 |
return content; |
327 |
} |
328 |
} |
329 |
|
330 |
public async Task<IList<ContainerInfo>> ListContainers(string account) |
331 |
{ |
332 |
|
333 |
var targetUrl = GetTargetUrl(account); |
334 |
var targetUri = new Uri(String.Format("{0}?format=json", targetUrl)); |
335 |
var result = await GetStringAsync(targetUri, "List Containers failed").ConfigureAwait(false); |
336 |
if (String.IsNullOrWhiteSpace(result)) |
337 |
return new List<ContainerInfo>(); |
338 |
var infos = JsonConvert.DeserializeObject<IList<ContainerInfo>>(result); |
339 |
foreach (var info in infos) |
340 |
{ |
341 |
info.Account = account; |
342 |
} |
343 |
return infos; |
344 |
} |
345 |
|
346 |
|
347 |
private string GetAccountUrl(string account) |
348 |
{ |
349 |
return RootAddressUri.Combine(account).AbsoluteUri; |
350 |
} |
351 |
|
352 |
public IList<ShareAccountInfo> ListSharingAccounts(DateTime? since=null) |
353 |
{ |
354 |
using (ThreadContext.Stacks["Share"].Push("List Accounts")) |
355 |
{ |
356 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
357 |
|
358 |
var targetUri = new Uri(String.Format("{0}?format=json", RootAddressUri), UriKind.Absolute); |
359 |
var content=TaskEx.Run(async ()=>await GetStringAsync(targetUri, "ListSharingAccounts failed", since).ConfigureAwait(false)).Result; |
360 |
|
361 |
//If the result is empty, return an empty list, |
362 |
var infos = String.IsNullOrWhiteSpace(content) |
363 |
? new List<ShareAccountInfo>() |
364 |
//Otherwise deserialize the account list into a list of ShareAccountInfos |
365 |
: JsonConvert.DeserializeObject<IList<ShareAccountInfo>>(content); |
366 |
|
367 |
Log.DebugFormat("END"); |
368 |
return infos; |
369 |
} |
370 |
} |
371 |
|
372 |
|
373 |
/// <summary> |
374 |
/// Request listing of all objects in a container modified since a specific time. |
375 |
/// If the *since* value is missing, return all objects |
376 |
/// </summary> |
377 |
/// <param name="knownContainers">Use the since variable only for the containers listed in knownContainers. Unknown containers are considered new |
378 |
/// and should be polled anyway |
379 |
/// </param> |
380 |
/// <param name="since"></param> |
381 |
/// <returns></returns> |
382 |
public IList<ObjectInfo> ListSharedObjects(HashSet<string> knownContainers, DateTimeOffset? since) |
383 |
{ |
384 |
|
385 |
using (ThreadContext.Stacks["Share"].Push("List Objects")) |
386 |
{ |
387 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
388 |
//'since' is not used here because we need to have ListObjects return a NoChange result |
389 |
//for all shared accounts,containers |
390 |
|
391 |
Func<ContainerInfo, string> getKey = c => String.Format("{0}\\{1}", c.Account, c.Name); |
392 |
|
393 |
var containers = (from account in ListSharingAccounts() |
394 |
let conts = TaskEx.Run(async ()=>await ListContainers(account.name).ConfigureAwait(false)).Result |
395 |
from container in conts |
396 |
select container).ToList(); |
397 |
var items = from container in containers |
398 |
let actualSince=knownContainers.Contains(getKey(container))?since:null |
399 |
select ListObjects(container.Account , container.Name, actualSince); |
400 |
var objects=items.SelectMany(r=> r).ToList(); |
401 |
|
402 |
//For each object |
403 |
//Check parents recursively up to (but not including) the container. |
404 |
//If parents are missing, add them to the list |
405 |
//Need function to calculate all parent URLs |
406 |
objects = AddMissingParents(objects); |
407 |
|
408 |
//Store any new containers |
409 |
foreach (var container in containers) |
410 |
{ |
411 |
knownContainers.Add(getKey(container)); |
412 |
} |
413 |
|
414 |
|
415 |
|
416 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
417 |
return objects; |
418 |
} |
419 |
} |
420 |
|
421 |
private List<ObjectInfo> AddMissingParents(List<ObjectInfo> objects) |
422 |
{ |
423 |
//TODO: Remove short-circuit when we decide to use Missing Parents functionality |
424 |
//return objects; |
425 |
|
426 |
var existingUris = objects.ToDictionary(o => o.Uri, o => o); |
427 |
foreach (var objectInfo in objects) |
428 |
{ |
429 |
//Can be null when retrieving objects to show in selective sync |
430 |
if (objectInfo.Name == null) |
431 |
continue; |
432 |
|
433 |
//No need to unescape here, the parts will be used to create new ObjectInfos |
434 |
var parts = objectInfo.Name.ToString().Split(new[]{'/'},StringSplitOptions.RemoveEmptyEntries); |
435 |
//If there is no parent, skip |
436 |
if (parts.Length == 1) |
437 |
continue; |
438 |
var baseParts = new[] |
439 |
{ |
440 |
objectInfo.Uri.Host, objectInfo.Uri.Segments[1].TrimEnd('/'),objectInfo.Account,objectInfo.Container.ToString() |
441 |
}; |
442 |
for (var partIdx = 0; partIdx < parts.Length - 1; partIdx++) |
443 |
{ |
444 |
var nameparts = parts.Range(0, partIdx).ToArray(); |
445 |
var parentName= String.Join("/", nameparts); |
446 |
|
447 |
var parentParts = baseParts.Concat(nameparts); |
448 |
var parentUrl = objectInfo.Uri.Scheme+ "://" + String.Join("/", parentParts); |
449 |
|
450 |
var parentUri = new Uri(parentUrl, UriKind.Absolute); |
451 |
|
452 |
ObjectInfo existingInfo; |
453 |
if (!existingUris.TryGetValue(parentUri,out existingInfo)) |
454 |
{ |
455 |
var h = parentUrl.GetHashCode(); |
456 |
var reverse = new string(parentUrl.Reverse().ToArray()); |
457 |
var rh = reverse.GetHashCode(); |
458 |
var b1 = BitConverter.GetBytes(h); |
459 |
var b2 = BitConverter.GetBytes(rh); |
460 |
var g = new Guid(0,0,0,b1.Concat(b2).ToArray()); |
461 |
|
462 |
|
463 |
existingUris[parentUri] = new ObjectInfo |
464 |
{ |
465 |
Account = objectInfo.Account, |
466 |
Container = objectInfo.Container, |
467 |
Content_Type = ObjectInfo.CONTENT_TYPE_DIRECTORY, |
468 |
ETag = Signature.MERKLE_EMPTY, |
469 |
X_Object_Hash = Signature.MERKLE_EMPTY, |
470 |
Name=new Uri(parentName,UriKind.Relative), |
471 |
StorageUri=objectInfo.StorageUri, |
472 |
Bytes = 0, |
473 |
UUID=g.ToString(), |
474 |
}; |
475 |
} |
476 |
} |
477 |
} |
478 |
return existingUris.Values.ToList(); |
479 |
} |
480 |
|
481 |
public void SetTags(ObjectInfo target,IDictionary<string,string> tags) |
482 |
{ |
483 |
Contract.Requires<InvalidOperationException>(!String.IsNullOrWhiteSpace(Token),"The Token is not set"); |
484 |
Contract.Requires<InvalidOperationException>(StorageUrl != null,"The StorageUrl is not set"); |
485 |
Contract.Requires<ArgumentNullException>(target != null,"target is null"); |
486 |
Contract.EndContractBlock(); |
487 |
|
488 |
using (ThreadContext.Stacks["Share"].Push("Share Object")) |
489 |
{ |
490 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
491 |
|
492 |
using (var client = new RestClient(_baseClient)) |
493 |
{ |
494 |
|
495 |
client.BaseAddress = GetAccountUrl(target.Account); |
496 |
|
497 |
client.Parameters.Clear(); |
498 |
client.Parameters.Add("update", ""); |
499 |
|
500 |
foreach (var tag in tags) |
501 |
{ |
502 |
var headerTag = String.Format("X-Object-Meta-{0}", tag.Key); |
503 |
client.Headers.Add(headerTag, tag.Value); |
504 |
} |
505 |
|
506 |
client.DownloadStringWithRetryRelative(target.Container, 3); |
507 |
|
508 |
|
509 |
client.AssertStatusOK("SetTags failed"); |
510 |
//If the status is NOT ACCEPTED we have a problem |
511 |
if (client.StatusCode != HttpStatusCode.Accepted) |
512 |
{ |
513 |
Log.Error("Failed to set tags"); |
514 |
throw new Exception("Failed to set tags"); |
515 |
} |
516 |
|
517 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
518 |
} |
519 |
} |
520 |
|
521 |
|
522 |
} |
523 |
|
524 |
public void ShareObject(string account, Uri container, Uri objectName, string shareTo, bool read, bool write) |
525 |
{ |
526 |
|
527 |
Contract.Requires<InvalidOperationException>(!String.IsNullOrWhiteSpace(Token), "The Token is not set"); |
528 |
Contract.Requires<InvalidOperationException>(StorageUrl != null, "The StorageUrl is not set"); |
529 |
Contract.Requires<ArgumentNullException>(container != null, "container is null"); |
530 |
Contract.Requires<ArgumentException>(!container.IsAbsoluteUri, "container is absolute"); |
531 |
Contract.Requires<ArgumentNullException>(objectName != null, "objectName is null"); |
532 |
Contract.Requires<ArgumentException>(!objectName.IsAbsoluteUri, "objectName is absolute"); |
533 |
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(account), "account is not set"); |
534 |
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(shareTo), "shareTo is not set"); |
535 |
Contract.EndContractBlock(); |
536 |
|
537 |
using (ThreadContext.Stacks["Share"].Push("Share Object")) |
538 |
{ |
539 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
540 |
|
541 |
using (var client = new RestClient(_baseClient)) |
542 |
{ |
543 |
|
544 |
client.BaseAddress = GetAccountUrl(account); |
545 |
|
546 |
client.Parameters.Clear(); |
547 |
client.Parameters.Add("format", "json"); |
548 |
|
549 |
string permission = ""; |
550 |
if (write) |
551 |
permission = String.Format("write={0}", shareTo); |
552 |
else if (read) |
553 |
permission = String.Format("read={0}", shareTo); |
554 |
client.Headers.Add("X-Object-Sharing", permission); |
555 |
|
556 |
var content = client.DownloadStringWithRetryRelative(container, 3); |
557 |
|
558 |
client.AssertStatusOK("ShareObject failed"); |
559 |
|
560 |
//If the result is empty, return an empty list, |
561 |
var infos = String.IsNullOrWhiteSpace(content) |
562 |
? new List<ObjectInfo>() |
563 |
//Otherwise deserialize the object list into a list of ObjectInfos |
564 |
: JsonConvert.DeserializeObject<IList<ObjectInfo>>(content); |
565 |
|
566 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
567 |
} |
568 |
} |
569 |
|
570 |
|
571 |
} |
572 |
|
573 |
public async Task<AccountInfo> GetAccountPolicies(AccountInfo accountInfo) |
574 |
{ |
575 |
if (accountInfo==null) |
576 |
throw new ArgumentNullException("accountInfo"); |
577 |
Contract.EndContractBlock(); |
578 |
|
579 |
using (ThreadContext.Stacks["Account"].Push("GetPolicies")) |
580 |
{ |
581 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
582 |
|
583 |
/* |
584 |
if (_baseClient == null) |
585 |
{ |
586 |
_baseClient = new RestClient |
587 |
{ |
588 |
BaseAddress = accountInfo.StorageUri.ToString(), |
589 |
Timeout = 30000, |
590 |
Retries = 3, |
591 |
}; |
592 |
} |
593 |
|
594 |
*/ |
595 |
var containerUri = GetTargetUri(accountInfo.UserName); |
596 |
var targetUri = new Uri(String.Format("{0}?format=json", containerUri), UriKind.Absolute); |
597 |
using(var response=await _baseHttpClient.HeadAsyncWithRetries(targetUri,3).ConfigureAwait(false)) |
598 |
{ |
599 |
|
600 |
var quotaValue=response.Headers.GetFirstValue("X-Account-Policy-Quota"); |
601 |
var bytesValue = response.Headers.GetFirstValue("X-Account-Bytes-Used"); |
602 |
long quota, bytes; |
603 |
if (long.TryParse(quotaValue, out quota)) |
604 |
accountInfo.Quota = quota; |
605 |
if (long.TryParse(bytesValue, out bytes)) |
606 |
accountInfo.BytesUsed = bytes; |
607 |
|
608 |
return accountInfo; |
609 |
} |
610 |
|
611 |
|
612 |
//using (var client = new RestClient(_baseClient)) |
613 |
//{ |
614 |
// if (!String.IsNullOrWhiteSpace(accountInfo.UserName)) |
615 |
// client.BaseAddress = GetAccountUrl(accountInfo.UserName); |
616 |
|
617 |
// client.Parameters.Clear(); |
618 |
// client.Parameters.Add("format", "json"); |
619 |
// client.Head(_emptyUri, 3); |
620 |
|
621 |
// var quotaValue=client.ResponseHeaders["X-Account-Policy-Quota"]; |
622 |
// var bytesValue= client.ResponseHeaders["X-Account-Bytes-Used"]; |
623 |
|
624 |
// long quota, bytes; |
625 |
// if (long.TryParse(quotaValue, out quota)) |
626 |
// accountInfo.Quota = quota; |
627 |
// if (long.TryParse(bytesValue, out bytes)) |
628 |
// accountInfo.BytesUsed = bytes; |
629 |
|
630 |
// return accountInfo; |
631 |
|
632 |
//} |
633 |
|
634 |
} |
635 |
} |
636 |
|
637 |
public void UpdateMetadata(ObjectInfo objectInfo) |
638 |
{ |
639 |
Contract.Requires<ArgumentNullException>(objectInfo != null,"objectInfo is null"); |
640 |
Contract.EndContractBlock(); |
641 |
|
642 |
using (ThreadContext.Stacks["Objects"].Push("UpdateMetadata")) |
643 |
{ |
644 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
645 |
|
646 |
|
647 |
using(var client=new RestClient(_baseClient)) |
648 |
{ |
649 |
|
650 |
client.BaseAddress = GetAccountUrl(objectInfo.Account); |
651 |
|
652 |
client.Parameters.Clear(); |
653 |
|
654 |
|
655 |
//Set Tags |
656 |
foreach (var tag in objectInfo.Tags) |
657 |
{ |
658 |
var headerTag = String.Format("X-Object-Meta-{0}", tag.Key); |
659 |
client.Headers.Add(headerTag, tag.Value); |
660 |
} |
661 |
|
662 |
//Set Permissions |
663 |
|
664 |
var permissions=objectInfo.GetPermissionString(); |
665 |
client.SetNonEmptyHeaderValue("X-Object-Sharing",permissions); |
666 |
|
667 |
client.SetNonEmptyHeaderValue("Content-Disposition",objectInfo.ContendDisposition); |
668 |
client.SetNonEmptyHeaderValue("Content-Encoding",objectInfo.ContentEncoding); |
669 |
client.SetNonEmptyHeaderValue("X-Object-Manifest",objectInfo.Manifest); |
670 |
var isPublic = objectInfo.IsPublic.ToString().ToLower(); |
671 |
client.Headers.Add("X-Object-Public", isPublic); |
672 |
|
673 |
|
674 |
var address = String.Format("{0}/{1}?update=",objectInfo.Container, objectInfo.Name); |
675 |
client.PostWithRetry(new Uri(address,UriKind.Relative),"application/xml"); |
676 |
|
677 |
client.AssertStatusOK("UpdateMetadata failed"); |
678 |
//If the status is NOT ACCEPTED or OK we have a problem |
679 |
if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK)) |
680 |
{ |
681 |
Log.Error("Failed to update metadata"); |
682 |
throw new Exception("Failed to update metadata"); |
683 |
} |
684 |
|
685 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
686 |
} |
687 |
} |
688 |
|
689 |
} |
690 |
|
691 |
public void UpdateMetadata(ContainerInfo containerInfo) |
692 |
{ |
693 |
if (containerInfo == null) |
694 |
throw new ArgumentNullException("containerInfo"); |
695 |
Contract.EndContractBlock(); |
696 |
|
697 |
using (ThreadContext.Stacks["Containers"].Push("UpdateMetadata")) |
698 |
{ |
699 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
700 |
|
701 |
|
702 |
using(var client=new RestClient(_baseClient)) |
703 |
{ |
704 |
|
705 |
client.BaseAddress = GetAccountUrl(containerInfo.Account); |
706 |
|
707 |
client.Parameters.Clear(); |
708 |
|
709 |
|
710 |
//Set Tags |
711 |
foreach (var tag in containerInfo.Tags) |
712 |
{ |
713 |
var headerTag = String.Format("X-Container-Meta-{0}", tag.Key); |
714 |
client.Headers.Add(headerTag, tag.Value); |
715 |
} |
716 |
|
717 |
|
718 |
//Set Policies |
719 |
foreach (var policy in containerInfo.Policies) |
720 |
{ |
721 |
var headerPolicy = String.Format("X-Container-Policy-{0}", policy.Key); |
722 |
client.Headers.Add(headerPolicy, policy.Value); |
723 |
} |
724 |
|
725 |
|
726 |
var uriBuilder = client.GetAddressBuilder(containerInfo.Name,_emptyUri); |
727 |
var uri = uriBuilder.Uri; |
728 |
|
729 |
client.UploadValues(uri,new NameValueCollection()); |
730 |
|
731 |
|
732 |
client.AssertStatusOK("UpdateMetadata failed"); |
733 |
//If the status is NOT ACCEPTED or OK we have a problem |
734 |
if (!(client.StatusCode == HttpStatusCode.Accepted || client.StatusCode == HttpStatusCode.OK)) |
735 |
{ |
736 |
Log.Error("Failed to update metadata"); |
737 |
throw new Exception("Failed to update metadata"); |
738 |
} |
739 |
|
740 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
741 |
} |
742 |
} |
743 |
|
744 |
} |
745 |
|
746 |
|
747 |
|
748 |
|
749 |
public IList<ObjectInfo> ListObjects(string account, Uri container, DateTimeOffset? since = null) |
750 |
{ |
751 |
/* |
752 |
if (container==null) |
753 |
throw new ArgumentNullException("container"); |
754 |
if (container.IsAbsoluteUri) |
755 |
throw new ArgumentException("container"); |
756 |
Contract.EndContractBlock(); |
757 |
*/ |
758 |
|
759 |
using (ThreadContext.Stacks["Objects"].Push("List")) |
760 |
{ |
761 |
|
762 |
var containerUri = GetTargetUri(account).Combine(container); |
763 |
var targetUri = new Uri(String.Format("{0}?format=json", containerUri), UriKind.Absolute); |
764 |
|
765 |
var content =TaskEx.Run(async ()=>await GetStringAsync(targetUri, "ListObjects failed", since).ConfigureAwait(false)).Result; |
766 |
|
767 |
//304 will result in an empty string. Empty containers return an empty json array |
768 |
if (String.IsNullOrWhiteSpace(content)) |
769 |
return new[] {new NoModificationInfo(account, container)}; |
770 |
|
771 |
//If the result is empty, return an empty list, |
772 |
var infos = String.IsNullOrWhiteSpace(content) |
773 |
? new List<ObjectInfo>() |
774 |
//Otherwise deserialize the object list into a list of ObjectInfos |
775 |
: JsonConvert.DeserializeObject<IList<ObjectInfo>>(content); |
776 |
|
777 |
foreach (var info in infos) |
778 |
{ |
779 |
info.Container = container; |
780 |
info.Account = account; |
781 |
info.StorageUri = StorageUrl; |
782 |
} |
783 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
784 |
return infos; |
785 |
} |
786 |
} |
787 |
|
788 |
public IList<ObjectInfo> ListObjects(string account, Uri container, Uri folder, DateTimeOffset? since = null) |
789 |
{ |
790 |
/* if (container==null) |
791 |
throw new ArgumentNullException("container"); |
792 |
if (container.IsAbsoluteUri) |
793 |
throw new ArgumentException("container"); |
794 |
Contract.EndContractBlock();*/ |
795 |
|
796 |
using (ThreadContext.Stacks["Objects"].Push("List")) |
797 |
{ |
798 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
799 |
|
800 |
var containerUri = GetTargetUri(account).Combine(container); |
801 |
var targetUri = new Uri(String.Format("{0}?format=json&path={1}", containerUri,folder), UriKind.Absolute); |
802 |
var content = TaskEx.Run(async ()=>await GetStringAsync(targetUri, "ListObjects failed", since).ConfigureAwait(false)).Result; |
803 |
|
804 |
//304 will result in an empty string. Empty containers return an empty json array |
805 |
if (String.IsNullOrWhiteSpace(content)) |
806 |
return new[] { new NoModificationInfo(account, container) }; |
807 |
|
808 |
|
809 |
var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content); |
810 |
foreach (var info in infos) |
811 |
{ |
812 |
info.Account = account; |
813 |
if (info.Container == null) |
814 |
info.Container = container; |
815 |
info.StorageUri = StorageUrl; |
816 |
} |
817 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
818 |
return infos; |
819 |
/* |
820 |
using (var client = new RestClient(_baseClient)) |
821 |
{ |
822 |
if (!String.IsNullOrWhiteSpace(account)) |
823 |
client.BaseAddress = GetAccountUrl(account); |
824 |
|
825 |
client.Parameters.Clear(); |
826 |
client.Parameters.Add("format", "json"); |
827 |
client.Parameters.Add("path", folder.ToString()); |
828 |
client.IfModifiedSince = since; |
829 |
var content = client.DownloadStringWithRetryRelative(container, 3); |
830 |
client.AssertStatusOK("ListObjects failed"); |
831 |
|
832 |
if (client.StatusCode==HttpStatusCode.NotModified) |
833 |
return new[]{new NoModificationInfo(account,container,folder)}; |
834 |
|
835 |
var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content); |
836 |
foreach (var info in infos) |
837 |
{ |
838 |
info.Account = account; |
839 |
if (info.Container == null) |
840 |
info.Container = container; |
841 |
info.StorageUri = StorageUrl; |
842 |
} |
843 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
844 |
return infos; |
845 |
} |
846 |
*/ |
847 |
} |
848 |
} |
849 |
|
850 |
|
851 |
public async Task<bool> ContainerExists(string account, Uri container) |
852 |
{ |
853 |
if (container==null) |
854 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
855 |
if (container.IsAbsoluteUri) |
856 |
throw new ArgumentException( "The container must be relative","container"); |
857 |
Contract.EndContractBlock(); |
858 |
|
859 |
using (ThreadContext.Stacks["Containters"].Push("Exists")) |
860 |
{ |
861 |
if (Log.IsDebugEnabled) Log.DebugFormat("START"); |
862 |
|
863 |
var targetUri = GetTargetUri(account).Combine(container); |
864 |
|
865 |
using (var response =await _baseHttpClient.HeadAsyncWithRetries(targetUri, 3)) |
866 |
{ |
867 |
|
868 |
bool result; |
869 |
switch (response.StatusCode) |
870 |
{ |
871 |
case HttpStatusCode.OK: |
872 |
case HttpStatusCode.NoContent: |
873 |
result = true; |
874 |
break; |
875 |
case HttpStatusCode.NotFound: |
876 |
result = false; |
877 |
break; |
878 |
default: |
879 |
throw CreateWebException("ContainerExists", response.StatusCode); |
880 |
} |
881 |
if (Log.IsDebugEnabled) Log.DebugFormat("END"); |
882 |
|
883 |
return result; |
884 |
} |
885 |
|
886 |
} |
887 |
} |
888 |
|
889 |
private Uri GetTargetUri(string account) |
890 |
{ |
891 |
return new Uri(GetTargetUrl(account),UriKind.Absolute); |
892 |
} |
893 |
|
894 |
private string GetTargetUrl(string account) |
895 |
{ |
896 |
return String.IsNullOrWhiteSpace(account) |
897 |
? _baseHttpClient.BaseAddress.ToString() |
898 |
: GetAccountUrl(account); |
899 |
} |
900 |
|
901 |
public async Task<bool> ObjectExists(string account, Uri container, Uri objectName) |
902 |
{ |
903 |
if (container == null) |
904 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
905 |
if (container.IsAbsoluteUri) |
906 |
throw new ArgumentException("The container must be relative","container"); |
907 |
if (objectName == null) |
908 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
909 |
if (objectName.IsAbsoluteUri) |
910 |
throw new ArgumentException("The objectName must be relative","objectName"); |
911 |
Contract.EndContractBlock(); |
912 |
|
913 |
var targetUri=GetTargetUri(account).Combine(container).Combine(objectName); |
914 |
|
915 |
using (var response = await _baseHttpClient.HeadAsyncWithRetries(targetUri, 3).ConfigureAwait(false)) |
916 |
{ |
917 |
switch (response.StatusCode) |
918 |
{ |
919 |
case HttpStatusCode.OK: |
920 |
case HttpStatusCode.NoContent: |
921 |
return true; |
922 |
case HttpStatusCode.NotFound: |
923 |
return false; |
924 |
default: |
925 |
throw CreateWebException("ObjectExists", response.StatusCode); |
926 |
} |
927 |
} |
928 |
} |
929 |
|
930 |
public async Task<ObjectInfo> GetObjectInfo(string account, Uri container, Uri objectName) |
931 |
{ |
932 |
if (container == null) |
933 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
934 |
if (container.IsAbsoluteUri) |
935 |
throw new ArgumentException("The container must be relative", "container"); |
936 |
if (objectName == null) |
937 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
938 |
if (objectName.IsAbsoluteUri) |
939 |
throw new ArgumentException("The objectName must be relative", "objectName"); |
940 |
Contract.EndContractBlock(); |
941 |
|
942 |
using (ThreadContext.Stacks["Objects"].Push("GetObjectInfo")) |
943 |
{ |
944 |
|
945 |
var targetUri = GetTargetUri(account).Combine(container).Combine(objectName); |
946 |
try |
947 |
{ |
948 |
using (var response = await _baseHttpClient.HeadAsyncWithRetries(targetUri, 3,true)) |
949 |
{ |
950 |
switch (response.StatusCode) |
951 |
{ |
952 |
case HttpStatusCode.OK: |
953 |
case HttpStatusCode.NoContent: |
954 |
var tags = response.Headers.GetMeta("X-Object-Meta-"); |
955 |
var extensions = (from header in response.Headers |
956 |
where |
957 |
header.Key.StartsWith("X-Object-") && |
958 |
!header.Key.StartsWith("X-Object-Meta-") |
959 |
select new {Name = header.Key, Value = header.Value.FirstOrDefault()}) |
960 |
.ToDictionary(t => t.Name, t => t.Value); |
961 |
|
962 |
var permissions = response.Headers.GetFirstValue("X-Object-Sharing"); |
963 |
|
964 |
|
965 |
var info = new ObjectInfo |
966 |
{ |
967 |
Account = account, |
968 |
Container = container, |
969 |
Name = objectName, |
970 |
ETag = response.Headers.ETag.NullSafe(e=>e.Tag), |
971 |
UUID = response.Headers.GetFirstValue("X-Object-UUID"), |
972 |
X_Object_Hash = response.Headers.GetFirstValue("X-Object-Hash"), |
973 |
Content_Type = response.Headers.GetFirstValue("Content-Type"), |
974 |
Bytes = Convert.ToInt64(response.Content.Headers.ContentLength), |
975 |
Tags = tags, |
976 |
Last_Modified = response.Content.Headers.LastModified, |
977 |
Extensions = extensions, |
978 |
ContentEncoding = |
979 |
response.Content.Headers.ContentEncoding.FirstOrDefault(), |
980 |
ContendDisposition = |
981 |
response.Content.Headers.ContentDisposition.NullSafe(c=>c.ToString()), |
982 |
Manifest = response.Headers.GetFirstValue("X-Object-Manifest"), |
983 |
PublicUrl = response.Headers.GetFirstValue("X-Object-Public"), |
984 |
StorageUri = StorageUrl, |
985 |
}; |
986 |
info.SetPermissions(permissions); |
987 |
return info; |
988 |
case HttpStatusCode.NotFound: |
989 |
return ObjectInfo.Empty; |
990 |
default: |
991 |
throw new WebException( |
992 |
String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status code {1}", |
993 |
objectName, response.StatusCode)); |
994 |
} |
995 |
} |
996 |
} |
997 |
catch (RetryException) |
998 |
{ |
999 |
Log.WarnFormat("[RETRY FAIL] GetObjectInfo for {0} failed.", objectName); |
1000 |
return ObjectInfo.Empty; |
1001 |
} |
1002 |
catch (WebException e) |
1003 |
{ |
1004 |
Log.Error( |
1005 |
String.Format("[FAIL] GetObjectInfo for {0} failed with unexpected status {1}", |
1006 |
objectName, e.Status), e); |
1007 |
throw; |
1008 |
} |
1009 |
} |
1010 |
} |
1011 |
|
1012 |
|
1013 |
|
1014 |
public async Task CreateFolder(string account, Uri container, Uri folder) |
1015 |
{ |
1016 |
if (container == null) |
1017 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1018 |
if (container.IsAbsoluteUri) |
1019 |
throw new ArgumentException("The container must be relative","container"); |
1020 |
if (folder == null) |
1021 |
throw new ArgumentNullException("folder", "The objectName property can't be empty"); |
1022 |
if (folder.IsAbsoluteUri) |
1023 |
throw new ArgumentException("The objectName must be relative","folder"); |
1024 |
Contract.EndContractBlock(); |
1025 |
|
1026 |
var folderUri=container.Combine(folder); |
1027 |
var targetUri = GetTargetUri(account).Combine(folderUri); |
1028 |
var message = new HttpRequestMessage(HttpMethod.Put, targetUri); |
1029 |
message.Content=new StringContent(""); |
1030 |
message.Content.Headers.ContentType = new MediaTypeHeaderValue(ObjectInfo.CONTENT_TYPE_DIRECTORY); |
1031 |
//message.Headers.Add("Content-Length", "0"); |
1032 |
using (var response = await _baseHttpClient.SendAsyncWithRetries(message, 3).ConfigureAwait(false)) |
1033 |
{ |
1034 |
if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.Accepted) |
1035 |
throw CreateWebException("CreateFolder", response.StatusCode); |
1036 |
} |
1037 |
} |
1038 |
|
1039 |
private Dictionary<string, string> GetMeta(HttpResponseMessage response,string metaPrefix) |
1040 |
{ |
1041 |
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(metaPrefix), "metaPrefix is empty"); |
1042 |
Contract.EndContractBlock(); |
1043 |
|
1044 |
var dict = (from header in response.Headers |
1045 |
where header.Key.StartsWith(metaPrefix) |
1046 |
select new { Name = header.Key, Value = String.Join(",", header.Value) }) |
1047 |
.ToDictionary(t => t.Name, t => t.Value); |
1048 |
|
1049 |
|
1050 |
return dict; |
1051 |
} |
1052 |
|
1053 |
|
1054 |
public async Task<ContainerInfo> GetContainerInfo(string account, Uri container) |
1055 |
{ |
1056 |
if (container == null) |
1057 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1058 |
if (container.IsAbsoluteUri) |
1059 |
throw new ArgumentException("The container must be relative","container"); |
1060 |
Contract.EndContractBlock(); |
1061 |
|
1062 |
var targetUri = GetTargetUri(account).Combine(container); |
1063 |
using (var response = await _baseHttpClient.HeadAsyncWithRetries(targetUri, 3,true).ConfigureAwait(false)) |
1064 |
{ |
1065 |
if (Log.IsDebugEnabled) |
1066 |
Log.DebugFormat("ContainerInfo data: {0}\n{1}",response,await response.Content.ReadAsStringAsync().ConfigureAwait(false)); |
1067 |
switch (response.StatusCode) |
1068 |
{ |
1069 |
case HttpStatusCode.OK: |
1070 |
case HttpStatusCode.NoContent: |
1071 |
var tags = GetMeta(response,"X-Container-Meta-"); |
1072 |
var policies = GetMeta(response,"X-Container-Policy-"); |
1073 |
|
1074 |
var containerInfo = new ContainerInfo |
1075 |
{ |
1076 |
Account = account, |
1077 |
Name = container, |
1078 |
StorageUrl = StorageUrl.ToString(), |
1079 |
Count =long.Parse(response.Headers.GetFirstValue("X-Container-Object-Count")), |
1080 |
Bytes = long.Parse(response.Headers.GetFirstValue("X-Container-Bytes-Used")), |
1081 |
BlockHash = response.Headers.GetFirstValue("X-Container-Block-Hash"), |
1082 |
BlockSize = |
1083 |
int.Parse(response.Headers.GetFirstValue("X-Container-Block-Size")), |
1084 |
Last_Modified = response.Content.Headers.LastModified, |
1085 |
Tags = tags, |
1086 |
Policies = policies |
1087 |
}; |
1088 |
|
1089 |
|
1090 |
return containerInfo; |
1091 |
case HttpStatusCode.NotFound: |
1092 |
return ContainerInfo.Empty; |
1093 |
default: |
1094 |
throw CreateWebException("GetContainerInfo", response.StatusCode); |
1095 |
} |
1096 |
} |
1097 |
} |
1098 |
|
1099 |
public async Task CreateContainer(string account, Uri container) |
1100 |
{ |
1101 |
if (container == null) |
1102 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1103 |
if (container.IsAbsoluteUri) |
1104 |
throw new ArgumentException("The container must be relative","container"); |
1105 |
Contract.EndContractBlock(); |
1106 |
|
1107 |
var targetUri=GetTargetUri(account).Combine(container); |
1108 |
var message = new HttpRequestMessage(HttpMethod.Put, targetUri); |
1109 |
|
1110 |
//message.Content.Headers.ContentLength = 0; |
1111 |
using (var response =await _baseHttpClient.SendAsyncWithRetries(message, 3).ConfigureAwait(false)) |
1112 |
{ |
1113 |
var expectedCodes = new[] {HttpStatusCode.Created, HttpStatusCode.Accepted, HttpStatusCode.OK}; |
1114 |
if (!expectedCodes.Contains(response.StatusCode)) |
1115 |
throw CreateWebException("CreateContainer", response.StatusCode); |
1116 |
} |
1117 |
} |
1118 |
|
1119 |
public async Task WipeContainer(string account, Uri container) |
1120 |
{ |
1121 |
if (container == null) |
1122 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1123 |
if (container.IsAbsoluteUri) |
1124 |
throw new ArgumentException("The container must be relative", "container"); |
1125 |
Contract.EndContractBlock(); |
1126 |
|
1127 |
await DeleteContainer(account, new Uri(String.Format("{0}?delimiter=/", container), UriKind.Relative)).ConfigureAwait(false); |
1128 |
} |
1129 |
|
1130 |
|
1131 |
public async Task DeleteContainer(string account, Uri container) |
1132 |
{ |
1133 |
if (container == null) |
1134 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1135 |
if (container.IsAbsoluteUri) |
1136 |
throw new ArgumentException("The container must be relative","container"); |
1137 |
Contract.EndContractBlock(); |
1138 |
|
1139 |
var targetUri = GetTargetUri(account).Combine(container); |
1140 |
var message = new HttpRequestMessage(HttpMethod.Delete, targetUri); |
1141 |
using (var response = await _baseHttpClient.SendAsyncWithRetries(message, 3).ConfigureAwait(false)) |
1142 |
{ |
1143 |
var expectedCodes = new[] { HttpStatusCode.NotFound, HttpStatusCode.NoContent }; |
1144 |
if (!expectedCodes.Contains(response.StatusCode)) |
1145 |
throw CreateWebException("DeleteContainer", response.StatusCode); |
1146 |
} |
1147 |
|
1148 |
} |
1149 |
|
1150 |
/// <summary> |
1151 |
/// |
1152 |
/// </summary> |
1153 |
/// <param name="account"></param> |
1154 |
/// <param name="container"></param> |
1155 |
/// <param name="objectName"></param> |
1156 |
/// <param name="fileName"></param> |
1157 |
/// <param name="cancellationToken"> </param> |
1158 |
/// <returns></returns> |
1159 |
/// <remarks>This method should have no timeout or a very long one</remarks> |
1160 |
//Asynchronously download the object specified by *objectName* in a specific *container* to |
1161 |
// a local file |
1162 |
public async Task GetObject(string account, Uri container, Uri objectName, string fileName,CancellationToken cancellationToken) |
1163 |
{ |
1164 |
if (container == null) |
1165 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1166 |
if (container.IsAbsoluteUri) |
1167 |
throw new ArgumentException("The container must be relative","container"); |
1168 |
if (objectName == null) |
1169 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
1170 |
if (objectName.IsAbsoluteUri) |
1171 |
throw new ArgumentException("The objectName must be relative","objectName"); |
1172 |
Contract.EndContractBlock(); |
1173 |
|
1174 |
|
1175 |
try |
1176 |
{ |
1177 |
//WebClient, and by extension RestClient, are not thread-safe. Create a new RestClient |
1178 |
//object to avoid concurrency errors. |
1179 |
// |
1180 |
//Download operations take a long time therefore they have no timeout. |
1181 |
using(var client = new RestClient(_baseClient) { Timeout = 0 }) |
1182 |
{ |
1183 |
if (!String.IsNullOrWhiteSpace(account)) |
1184 |
client.BaseAddress = GetAccountUrl(account); |
1185 |
|
1186 |
//The container and objectName are relative names. They are joined with the client's |
1187 |
//BaseAddress to create the object's absolute address |
1188 |
var builder = client.GetAddressBuilder(container, objectName); |
1189 |
var uri = builder.Uri; |
1190 |
|
1191 |
//Download progress is reported to the Trace log |
1192 |
Log.InfoFormat("[GET] START {0}", objectName); |
1193 |
/*client.DownloadProgressChanged += (sender, args) => |
1194 |
Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}", |
1195 |
fileName, args.ProgressPercentage, |
1196 |
args.BytesReceived, |
1197 |
args.TotalBytesToReceive);*/ |
1198 |
var progress = new Progress<DownloadProgressChangedEventArgs>(args => |
1199 |
{ |
1200 |
Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}", |
1201 |
fileName, args.ProgressPercentage, |
1202 |
args.BytesReceived, |
1203 |
args.TotalBytesToReceive); |
1204 |
if (DownloadProgressChanged!=null) |
1205 |
DownloadProgressChanged(this, new DownloadArgs(args)); |
1206 |
}); |
1207 |
|
1208 |
//Start downloading the object asynchronously |
1209 |
await client.DownloadFileTaskAsync(uri, fileName, cancellationToken,progress).ConfigureAwait(false); |
1210 |
|
1211 |
//Once the download completes |
1212 |
//Delete the local client object |
1213 |
} |
1214 |
//And report failure or completion |
1215 |
} |
1216 |
catch (Exception exc) |
1217 |
{ |
1218 |
Log.ErrorFormat("[GET] FAIL {0} with {1}", objectName, exc); |
1219 |
throw; |
1220 |
} |
1221 |
|
1222 |
Log.InfoFormat("[GET] END {0}", objectName); |
1223 |
|
1224 |
|
1225 |
} |
1226 |
|
1227 |
public async Task<IList<string>> PutHashMap(string account, Uri container, Uri objectName, TreeHash hash) |
1228 |
{ |
1229 |
if (container == null) |
1230 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1231 |
if (container.IsAbsoluteUri) |
1232 |
throw new ArgumentException("The container must be relative","container"); |
1233 |
if (objectName == null) |
1234 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
1235 |
if (objectName.IsAbsoluteUri) |
1236 |
throw new ArgumentException("The objectName must be relative","objectName"); |
1237 |
if (hash == null) |
1238 |
throw new ArgumentNullException("hash"); |
1239 |
if (String.IsNullOrWhiteSpace(Token)) |
1240 |
throw new InvalidOperationException("Invalid Token"); |
1241 |
if (StorageUrl == null) |
1242 |
throw new InvalidOperationException("Invalid Storage Url"); |
1243 |
Contract.EndContractBlock(); |
1244 |
|
1245 |
|
1246 |
|
1247 |
//The container and objectName are relative names. They are joined with the client's |
1248 |
//BaseAddress to create the object's absolute address |
1249 |
|
1250 |
var targetUri = GetTargetUri(account).Combine(container).Combine(objectName); |
1251 |
|
1252 |
|
1253 |
var uri = new Uri(String.Format("{0}?format=json&hashmap",targetUri),UriKind.Absolute); |
1254 |
|
1255 |
|
1256 |
//Send the tree hash as Json to the server |
1257 |
var jsonHash = hash.ToJson(); |
1258 |
if (Log.IsDebugEnabled) |
1259 |
Log.DebugFormat("Hashes:\r\n{0}", jsonHash); |
1260 |
|
1261 |
var mimeType = objectName.GetMimeType(); |
1262 |
|
1263 |
var message = new HttpRequestMessage(HttpMethod.Put, uri) |
1264 |
{ |
1265 |
Content = new StringContent(jsonHash) |
1266 |
}; |
1267 |
message.Content.Headers.ContentType = mimeType; |
1268 |
message.Headers.Add("ETag",hash.TopHash.ToHashString()); |
1269 |
|
1270 |
|
1271 |
//Don't use a timeout because putting the hashmap may be a long process |
1272 |
|
1273 |
using (var response = await _baseHttpClientNoTimeout.SendAsyncWithRetries(message, 3).ConfigureAwait(false)) |
1274 |
{ |
1275 |
var empty = (IList<string>)new List<string>(); |
1276 |
|
1277 |
switch (response.StatusCode) |
1278 |
{ |
1279 |
case HttpStatusCode.Created: |
1280 |
//The server will respond either with 201-created if all blocks were already on the server |
1281 |
return empty; |
1282 |
case HttpStatusCode.Conflict: |
1283 |
//or with a 409-conflict and return the list of missing parts |
1284 |
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) |
1285 |
using(var reader=stream.GetLoggedReader(Log)) |
1286 |
{ |
1287 |
var serializer = new JsonSerializer(); |
1288 |
serializer.Error += (sender, args) => Log.ErrorFormat("Deserialization error at [{0}] [{1}]", args.ErrorContext.Error, args.ErrorContext.Member); |
1289 |
var hashes = (List<string>)serializer.Deserialize(reader, typeof(List<string>)); |
1290 |
return hashes; |
1291 |
} |
1292 |
default: |
1293 |
//All other cases are unexpected |
1294 |
//Ensure that failure codes raise exceptions |
1295 |
response.EnsureSuccessStatusCode(); |
1296 |
//And log any other codes as warngings, but continute processing |
1297 |
Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",response.StatusCode,response.ReasonPhrase); |
1298 |
return empty; |
1299 |
} |
1300 |
} |
1301 |
|
1302 |
} |
1303 |
|
1304 |
|
1305 |
public async Task<byte[]> GetBlock(string account, Uri container, Uri relativeUrl, long start, long? end, CancellationToken cancellationToken) |
1306 |
{ |
1307 |
if (String.IsNullOrWhiteSpace(Token)) |
1308 |
throw new InvalidOperationException("Invalid Token"); |
1309 |
if (StorageUrl == null) |
1310 |
throw new InvalidOperationException("Invalid Storage Url"); |
1311 |
if (container == null) |
1312 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1313 |
if (container.IsAbsoluteUri) |
1314 |
throw new ArgumentException("The container must be relative","container"); |
1315 |
if (relativeUrl == null) |
1316 |
throw new ArgumentNullException("relativeUrl"); |
1317 |
if (end.HasValue && end < 0) |
1318 |
throw new ArgumentOutOfRangeException("end"); |
1319 |
if (start < 0) |
1320 |
throw new ArgumentOutOfRangeException("start"); |
1321 |
Contract.EndContractBlock(); |
1322 |
|
1323 |
|
1324 |
var targetUri = GetTargetUri(account).Combine(container).Combine(relativeUrl); |
1325 |
var message = new HttpRequestMessage(HttpMethod.Get, targetUri); |
1326 |
//Don't add a range if start=0, end=null (empty files) |
1327 |
if (start!=0 || end!=null) |
1328 |
message.Headers.Range=new RangeHeaderValue(start,end); |
1329 |
|
1330 |
//Don't use a timeout because putting the hashmap may be a long process |
1331 |
|
1332 |
IProgress<DownloadArgs> progress = new Progress<DownloadArgs>(args => |
1333 |
{ |
1334 |
Log.DebugFormat("[GET PROGRESS] {0} {1}% {2} of {3}", |
1335 |
targetUri.Segments.Last(), args.ProgressPercentage, |
1336 |
args.BytesReceived, |
1337 |
args.TotalBytesToReceive); |
1338 |
|
1339 |
if (DownloadProgressChanged!=null) |
1340 |
DownloadProgressChanged(this, args); |
1341 |
}); |
1342 |
|
1343 |
|
1344 |
using (var response = await _baseHttpClientNoTimeout.SendAsyncWithRetries(message, 3, false,HttpCompletionOption.ResponseHeadersRead, |
1345 |
cancellationToken).ConfigureAwait(false)) |
1346 |
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) |
1347 |
{ |
1348 |
long totalSize = response.Content.Headers.ContentLength ?? 0; |
1349 |
byte[] buffer,streambuf; |
1350 |
lock (_bufferManager) |
1351 |
{ |
1352 |
buffer = _bufferManager.TakeBuffer(65536); |
1353 |
streambuf = _bufferManager.TakeBuffer((int)totalSize); |
1354 |
} |
1355 |
|
1356 |
using (var targetStream = new MemoryStream(streambuf)) |
1357 |
{ |
1358 |
|
1359 |
long total = 0; |
1360 |
try |
1361 |
{ |
1362 |
|
1363 |
int read; |
1364 |
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0) |
1365 |
{ |
1366 |
total += read; |
1367 |
progress.Report(new DownloadArgs(total, totalSize)); |
1368 |
await targetStream.WriteAsync(buffer, 0, read).ConfigureAwait(false); |
1369 |
} |
1370 |
} |
1371 |
finally |
1372 |
{ |
1373 |
lock (_bufferManager) |
1374 |
{ |
1375 |
_bufferManager.ReturnBuffer(buffer); |
1376 |
_bufferManager.ReturnBuffer(streambuf); |
1377 |
} |
1378 |
} |
1379 |
var result = targetStream.ToArray(); |
1380 |
return result; |
1381 |
} |
1382 |
} |
1383 |
|
1384 |
} |
1385 |
|
1386 |
public event EventHandler<UploadArgs> UploadProgressChanged; |
1387 |
public event EventHandler<DownloadArgs> DownloadProgressChanged; |
1388 |
|
1389 |
|
1390 |
public async Task PostBlock(string account, Uri container, byte[] block, int offset, int count,string blockHash,CancellationToken token) |
1391 |
{ |
1392 |
if (container == null) |
1393 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1394 |
if (container.IsAbsoluteUri) |
1395 |
throw new ArgumentException("The container must be relative","container"); |
1396 |
if (block == null) |
1397 |
throw new ArgumentNullException("block"); |
1398 |
if (offset < 0 || offset >= block.Length) |
1399 |
throw new ArgumentOutOfRangeException("offset"); |
1400 |
if (count < 0 || count > block.Length) |
1401 |
throw new ArgumentOutOfRangeException("count"); |
1402 |
if (String.IsNullOrWhiteSpace(Token)) |
1403 |
throw new InvalidOperationException("Invalid Token"); |
1404 |
if (StorageUrl == null) |
1405 |
throw new InvalidOperationException("Invalid Storage Url"); |
1406 |
Contract.EndContractBlock(); |
1407 |
|
1408 |
|
1409 |
try |
1410 |
{ |
1411 |
var containerUri = GetTargetUri(account).Combine(container); |
1412 |
var targetUri = new Uri(String.Format("{0}?update", containerUri)); |
1413 |
|
1414 |
|
1415 |
//Don't use a timeout because putting the hashmap may be a long process |
1416 |
|
1417 |
|
1418 |
Log.InfoFormat("[BLOCK POST] START"); |
1419 |
|
1420 |
|
1421 |
var progress = new Progress<UploadArgs>(args => |
1422 |
{ |
1423 |
Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2}", |
1424 |
args.ProgressPercentage, |
1425 |
args.BytesSent, |
1426 |
args.TotalBytesToSend); |
1427 |
if (UploadProgressChanged != null) |
1428 |
UploadProgressChanged(this,args); |
1429 |
}); |
1430 |
|
1431 |
var message = new HttpRequestMessage(HttpMethod.Post, targetUri) |
1432 |
{ |
1433 |
Content = new ByteArrayContentWithProgress(block, offset, count,progress) |
1434 |
}; |
1435 |
message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(@"application/octet-stream"); |
1436 |
|
1437 |
//Send the block |
1438 |
using (var response = await _baseHttpClientNoTimeout.SendAsyncWithRetries(message, 3,false,HttpCompletionOption.ResponseContentRead,token).ConfigureAwait(false)) |
1439 |
{ |
1440 |
Log.InfoFormat("[BLOCK POST PROGRESS] Completed "); |
1441 |
response.EnsureSuccessStatusCode(); |
1442 |
var responseHash = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
1443 |
var cleanHash = responseHash.TrimEnd(); |
1444 |
Debug.Assert(blockHash==cleanHash); |
1445 |
if (!blockHash.Equals(cleanHash, StringComparison.OrdinalIgnoreCase)) |
1446 |
Log.ErrorFormat("Block hash mismatch posting to [{0}]:[{1}], expected [{2}] but was [{3}]", account, container, blockHash, cleanHash); |
1447 |
} |
1448 |
Log.InfoFormat("[BLOCK POST] END"); |
1449 |
} |
1450 |
catch (TaskCanceledException ) |
1451 |
{ |
1452 |
Log.Info("Aborting block"); |
1453 |
throw; |
1454 |
} |
1455 |
catch (Exception exc) |
1456 |
{ |
1457 |
Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc); |
1458 |
throw; |
1459 |
} |
1460 |
} |
1461 |
|
1462 |
public async Task PostBlock(string account, Uri container, string filePath, long offset, int count, string blockHash, CancellationToken token) |
1463 |
{ |
1464 |
if (container == null) |
1465 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1466 |
if (container.IsAbsoluteUri) |
1467 |
throw new ArgumentException("The container must be relative", "container"); |
1468 |
if (String.IsNullOrWhiteSpace(filePath)) |
1469 |
throw new ArgumentNullException("filePath"); |
1470 |
if (!File.Exists(filePath)) |
1471 |
throw new FileNotFoundException("Missing file","filePath"); |
1472 |
if (String.IsNullOrWhiteSpace(Token)) |
1473 |
throw new InvalidOperationException("Invalid Token"); |
1474 |
if (StorageUrl == null) |
1475 |
throw new InvalidOperationException("Invalid Storage Url"); |
1476 |
Contract.EndContractBlock(); |
1477 |
|
1478 |
|
1479 |
try |
1480 |
{ |
1481 |
var containerUri = GetTargetUri(account).Combine(container); |
1482 |
var targetUri = new Uri(String.Format("{0}?update", containerUri)); |
1483 |
|
1484 |
|
1485 |
//Don't use a timeout because putting the hashmap may be a long process |
1486 |
|
1487 |
|
1488 |
Log.InfoFormat("[BLOCK POST] START"); |
1489 |
|
1490 |
|
1491 |
var progress = new Progress<UploadArgs>(args => |
1492 |
{ |
1493 |
Log.InfoFormat("[BLOCK POST PROGRESS] {0}% {1} of {2} at {3:###,} Kbps ", |
1494 |
args.ProgressPercentage, |
1495 |
args.BytesSent, |
1496 |
args.TotalBytesToSend,args.Speed); |
1497 |
if (UploadProgressChanged != null) |
1498 |
UploadProgressChanged(this, args); |
1499 |
}); |
1500 |
|
1501 |
var message = new HttpRequestMessage(HttpMethod.Post, targetUri) |
1502 |
{ |
1503 |
Content = new FileBlockContent(filePath, offset, count, progress) |
1504 |
}; |
1505 |
message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(@"application/octet-stream"); |
1506 |
|
1507 |
//Send the block |
1508 |
using (var response = await _baseHttpClientNoTimeout.SendAsyncWithRetries(message, 3, false, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false)) |
1509 |
{ |
1510 |
Log.InfoFormat("[BLOCK POST PROGRESS] Completed "); |
1511 |
response.EnsureSuccessStatusCode(); |
1512 |
var responseHash = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
1513 |
var cleanHash = responseHash.TrimEnd(); |
1514 |
Debug.Assert(blockHash == cleanHash); |
1515 |
if (!blockHash.Equals(cleanHash, StringComparison.OrdinalIgnoreCase)) |
1516 |
Log.ErrorFormat("Block hash mismatch posting to [{0}]:[{1}], expected [{2}] but was [{3}]", account, container, blockHash, cleanHash); |
1517 |
} |
1518 |
Log.InfoFormat("[BLOCK POST] END"); |
1519 |
} |
1520 |
catch (TaskCanceledException) |
1521 |
{ |
1522 |
Log.Info("Aborting block"); |
1523 |
throw; |
1524 |
} |
1525 |
catch (Exception exc) |
1526 |
{ |
1527 |
Log.ErrorFormat("[BLOCK POST] FAIL with \r{0}", exc); |
1528 |
throw; |
1529 |
} |
1530 |
} |
1531 |
|
1532 |
|
1533 |
public async Task<TreeHash> GetHashMap(string account, Uri container, Uri objectName) |
1534 |
{ |
1535 |
if (container == null) |
1536 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1537 |
if (container.IsAbsoluteUri) |
1538 |
throw new ArgumentException("The container must be relative","container"); |
1539 |
if (objectName == null) |
1540 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
1541 |
if (objectName.IsAbsoluteUri) |
1542 |
throw new ArgumentException("The objectName must be relative","objectName"); |
1543 |
if (String.IsNullOrWhiteSpace(Token)) |
1544 |
throw new InvalidOperationException("Invalid Token"); |
1545 |
if (StorageUrl == null) |
1546 |
throw new InvalidOperationException("Invalid Storage Url"); |
1547 |
Contract.EndContractBlock(); |
1548 |
|
1549 |
try |
1550 |
{ |
1551 |
|
1552 |
var objectUri = GetTargetUri(account).Combine(container).Combine(objectName); |
1553 |
var targetUri = new Uri(String.Format("{0}?format=json&hashmap", objectUri)); |
1554 |
|
1555 |
//Start downloading the object asynchronously |
1556 |
var json = await GetStringAsync(targetUri, "").ConfigureAwait(false); |
1557 |
var treeHash = TreeHash.Parse(json); |
1558 |
Log.InfoFormat("[GET HASH] END {0}", objectName); |
1559 |
return treeHash; |
1560 |
|
1561 |
} |
1562 |
catch (Exception exc) |
1563 |
{ |
1564 |
Log.ErrorFormat("[GET HASH] END {0} with {1}", objectName, exc); |
1565 |
throw; |
1566 |
} |
1567 |
|
1568 |
} |
1569 |
|
1570 |
|
1571 |
/// <summary> |
1572 |
/// |
1573 |
/// </summary> |
1574 |
/// <param name="account"></param> |
1575 |
/// <param name="container"></param> |
1576 |
/// <param name="objectName"></param> |
1577 |
/// <param name="fileName"></param> |
1578 |
/// <param name="hash">Optional hash value for the file. If no hash is provided, the method calculates a new hash</param> |
1579 |
/// <param name="contentType"> </param> |
1580 |
/// <remarks>>This method should have no timeout or a very long one</remarks> |
1581 |
public async Task PutObject(string account, Uri container, Uri objectName, string fileName, string hash = Signature.MERKLE_EMPTY, string contentType = "application/octet-stream") |
1582 |
{ |
1583 |
if (container == null) |
1584 |
throw new ArgumentNullException("container", "The container property can't be empty"); |
1585 |
if (container.IsAbsoluteUri) |
1586 |
throw new ArgumentException("The container must be relative","container"); |
1587 |
if (objectName == null) |
1588 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
1589 |
if (objectName.IsAbsoluteUri) |
1590 |
throw new ArgumentException("The objectName must be relative","objectName"); |
1591 |
if (String.IsNullOrWhiteSpace(fileName)) |
1592 |
throw new ArgumentNullException("fileName", "The fileName property can't be empty"); |
1593 |
try |
1594 |
{ |
1595 |
|
1596 |
using (var client = new RestClient(_baseClient) { Timeout = 0 }) |
1597 |
{ |
1598 |
if (!String.IsNullOrWhiteSpace(account)) |
1599 |
client.BaseAddress = GetAccountUrl(account); |
1600 |
|
1601 |
var builder = client.GetAddressBuilder(container, objectName); |
1602 |
var uri = builder.Uri; |
1603 |
|
1604 |
string etag = hash ; |
1605 |
|
1606 |
client.Headers.Add("Content-Type", contentType); |
1607 |
if (contentType!=ObjectInfo.CONTENT_TYPE_DIRECTORY) |
1608 |
client.Headers.Add("ETag", etag); |
1609 |
|
1610 |
|
1611 |
Log.InfoFormat("[PUT] START {0}", objectName); |
1612 |
client.UploadProgressChanged += (sender, args) => |
1613 |
{ |
1614 |
using (ThreadContext.Stacks["PUT"].Push("Progress")) |
1615 |
{ |
1616 |
Log.InfoFormat("{0} {1}% {2} of {3}", fileName, |
1617 |
args.ProgressPercentage, |
1618 |
args.BytesSent, args.TotalBytesToSend); |
1619 |
} |
1620 |
}; |
1621 |
|
1622 |
client.UploadFileCompleted += (sender, args) => |
1623 |
{ |
1624 |
using (ThreadContext.Stacks["PUT"].Push("Progress")) |
1625 |
{ |
1626 |
Log.InfoFormat("Completed {0}", fileName); |
1627 |
} |
1628 |
}; |
1629 |
|
1630 |
if (contentType==ObjectInfo.CONTENT_TYPE_DIRECTORY) |
1631 |
await client.UploadDataTaskAsync(uri, "PUT", new byte[0]).ConfigureAwait(false); |
1632 |
else |
1633 |
await client.UploadFileTaskAsync(uri, "PUT", fileName).ConfigureAwait(false); |
1634 |
} |
1635 |
|
1636 |
Log.InfoFormat("[PUT] END {0}", objectName); |
1637 |
} |
1638 |
catch (Exception exc) |
1639 |
{ |
1640 |
Log.ErrorFormat("[PUT] END {0} with {1}", objectName, exc); |
1641 |
throw; |
1642 |
} |
1643 |
|
1644 |
} |
1645 |
|
1646 |
public async Task MoveObject(string account, Uri sourceContainer, Uri oldObjectName, Uri targetContainer, Uri newObjectName) |
1647 |
{ |
1648 |
if (sourceContainer == null) |
1649 |
throw new ArgumentNullException("sourceContainer", "The sourceContainer property can't be empty"); |
1650 |
if (sourceContainer.IsAbsoluteUri) |
1651 |
throw new ArgumentException("The sourceContainer must be relative","sourceContainer"); |
1652 |
if (oldObjectName == null) |
1653 |
throw new ArgumentNullException("oldObjectName", "The oldObjectName property can't be empty"); |
1654 |
if (oldObjectName.IsAbsoluteUri) |
1655 |
throw new ArgumentException("The oldObjectName must be relative","oldObjectName"); |
1656 |
if (targetContainer == null) |
1657 |
throw new ArgumentNullException("targetContainer", "The targetContainer property can't be empty"); |
1658 |
if (targetContainer.IsAbsoluteUri) |
1659 |
throw new ArgumentException("The targetContainer must be relative","targetContainer"); |
1660 |
if (newObjectName == null) |
1661 |
throw new ArgumentNullException("newObjectName", "The newObjectName property can't be empty"); |
1662 |
if (newObjectName.IsAbsoluteUri) |
1663 |
throw new ArgumentException("The newObjectName must be relative","newObjectName"); |
1664 |
Contract.EndContractBlock(); |
1665 |
|
1666 |
var baseUri = GetTargetUri(account); |
1667 |
var targetUri = baseUri.Combine(targetContainer).Combine(newObjectName); |
1668 |
var sourceUri = new Uri(String.Format("/{0}/{1}", sourceContainer, oldObjectName),UriKind.Relative); |
1669 |
|
1670 |
var message = new HttpRequestMessage(HttpMethod.Put, targetUri); |
1671 |
message.Headers.Add("X-Move-From", sourceUri.ToString()); |
1672 |
using (var response = await _baseHttpClient.SendAsyncWithRetries(message, 3).ConfigureAwait(false)) |
1673 |
{ |
1674 |
var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created}; |
1675 |
if (!expectedCodes.Contains(response.StatusCode)) |
1676 |
throw CreateWebException("MoveObject", response.StatusCode); |
1677 |
} |
1678 |
} |
1679 |
|
1680 |
public async Task DeleteObject(string account, Uri sourceContainer, Uri objectName, bool isDirectory) |
1681 |
{ |
1682 |
if (sourceContainer == null) |
1683 |
throw new ArgumentNullException("sourceContainer", "The sourceContainer property can't be empty"); |
1684 |
if (sourceContainer.IsAbsoluteUri) |
1685 |
throw new ArgumentException("The sourceContainer must be relative","sourceContainer"); |
1686 |
if (objectName == null) |
1687 |
throw new ArgumentNullException("objectName", "The objectName property can't be empty"); |
1688 |
if (objectName.IsAbsoluteUri) |
1689 |
throw new ArgumentException("The objectName must be relative","objectName"); |
1690 |
Contract.EndContractBlock(); |
1691 |
|
1692 |
|
1693 |
|
1694 |
var sourceUri = new Uri(String.Format("/{0}/{1}", sourceContainer, objectName),UriKind.Relative); |
1695 |
|
1696 |
|
1697 |
if (objectName.OriginalString.EndsWith(".ignore")) |
1698 |
using(var response = await _baseHttpClient.DeleteAsync(sourceUri)){} |
1699 |
else |
1700 |
{ |
1701 |
var relativeUri = new Uri(String.Format("{0}/{1}", FolderConstants.TrashContainer, objectName), |
1702 |
UriKind.Relative); |
1703 |
|
1704 |
/* |
1705 |
var relativeUri = isDirectory |
1706 |
? new Uri( |
1707 |
String.Format("{0}/{1}?delimiter=/", FolderConstants.TrashContainer, |
1708 |
objectName), UriKind.Relative) |
1709 |
: new Uri(String.Format("{0}/{1}", FolderConstants.TrashContainer, objectName), |
1710 |
UriKind.Relative); |
1711 |
|
1712 |
*/ |
1713 |
var targetUri = GetTargetUri(account).Combine(relativeUri); |
1714 |
|
1715 |
|
1716 |
var message = new HttpRequestMessage(HttpMethod.Put, targetUri); |
1717 |
message.Headers.Add("X-Move-From", sourceUri.ToString()); |
1718 |
|
1719 |
Log.InfoFormat("[TRASH] [{0}] to [{1}]", sourceUri, targetUri); |
1720 |
using (var response = await _baseHttpClient.SendAsyncWithRetries(message, 3)) |
1721 |
{ |
1722 |
var expectedCodes = new[] |
1723 |
{ |
1724 |
HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created, |
1725 |
HttpStatusCode.NotFound |
1726 |
}; |
1727 |
if (!expectedCodes.Contains(response.StatusCode)) |
1728 |
throw CreateWebException("DeleteObject", response.StatusCode); |
1729 |
} |
1730 |
} |
1731 |
/* |
1732 |
|
1733 |
|
1734 |
var targetUrl = FolderConstants.TrashContainer + "/" + objectName; |
1735 |
/* |
1736 |
if (isDirectory) |
1737 |
targetUrl = targetUrl + "?delimiter=/"; |
1738 |
#1# |
1739 |
|
1740 |
var sourceUrl = String.Format("/{0}/{1}", sourceContainer, objectName); |
1741 |
|
1742 |
using (var client = new RestClient(_baseClient)) |
1743 |
{ |
1744 |
if (!String.IsNullOrWhiteSpace(account)) |
1745 |
client.BaseAddress = GetAccountUrl(account); |
1746 |
|
1747 |
client.Headers.Add("X-Move-From", sourceUrl); |
1748 |
client.AllowedStatusCodes.Add(HttpStatusCode.NotFound); |
1749 |
Log.InfoFormat("[TRASH] [{0}] to [{1}]",sourceUrl,targetUrl); |
1750 |
client.PutWithRetry(new Uri(targetUrl,UriKind.Relative), 3); |
1751 |
|
1752 |
var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound}; |
1753 |
if (!expectedCodes.Contains(client.StatusCode)) |
1754 |
throw CreateWebException("DeleteObject", client.StatusCode); |
1755 |
} |
1756 |
*/ |
1757 |
} |
1758 |
|
1759 |
|
1760 |
private static WebException CreateWebException(string operation, HttpStatusCode statusCode) |
1761 |
{ |
1762 |
return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode)); |
1763 |
} |
1764 |
|
1765 |
|
1766 |
public async Task<bool> CanUpload(string account, ObjectInfo cloudFile) |
1767 |
{ |
1768 |
Contract.Requires(!String.IsNullOrWhiteSpace(account)); |
1769 |
Contract.Requires(cloudFile!=null); |
1770 |
|
1771 |
var parts = cloudFile.Name.ToString().Split('/'); |
1772 |
var folder = String.Join("/", parts,0,parts.Length-1); |
1773 |
|
1774 |
var fileName = String.Format("{0}/{1}.pithos.ignore", folder, Guid.NewGuid()); |
1775 |
var fileUri=fileName.ToEscapedUri(); |
1776 |
|
1777 |
try |
1778 |
{ |
1779 |
var relativeUri = cloudFile.Container.Combine(fileUri); |
1780 |
var targetUri = GetTargetUri(account).Combine(relativeUri); |
1781 |
var message = new HttpRequestMessage(HttpMethod.Put, targetUri); |
1782 |
message.Content.Headers.ContentType =new MediaTypeHeaderValue("application/octet-stream"); |
1783 |
var response=await _baseHttpClient.SendAsyncWithRetries(message, 3); |
1784 |
var expectedCodes = new[] { HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created}; |
1785 |
var result=(expectedCodes.Contains(response.StatusCode)); |
1786 |
await DeleteObject(account, cloudFile.Container, fileUri, cloudFile.IsDirectory); |
1787 |
return result; |
1788 |
} |
1789 |
catch |
1790 |
{ |
1791 |
return false; |
1792 |
} |
1793 |
|
1794 |
} |
1795 |
|
1796 |
~CloudFilesClient() |
1797 |
{ |
1798 |
Dispose(false); |
1799 |
} |
1800 |
|
1801 |
public void Dispose() |
1802 |
{ |
1803 |
Dispose(true); |
1804 |
GC.SuppressFinalize(this); |
1805 |
} |
1806 |
|
1807 |
protected virtual void Dispose(bool disposing) |
1808 |
{ |
1809 |
if (disposing) |
1810 |
{ |
1811 |
if (_httpClientHandler!=null) |
1812 |
_httpClientHandler.Dispose(); |
1813 |
if (_baseClient!=null) |
1814 |
_baseClient.Dispose(); |
1815 |
if(_baseHttpClient!=null) |
1816 |
_baseHttpClient.Dispose(); |
1817 |
if (_baseHttpClientNoTimeout!=null) |
1818 |
_baseHttpClientNoTimeout.Dispose(); |
1819 |
} |
1820 |
_httpClientHandler = null; |
1821 |
_baseClient = null; |
1822 |
_baseHttpClient = null; |
1823 |
_baseHttpClientNoTimeout = null; |
1824 |
} |
1825 |
|
1826 |
public async Task<string> ResolveName(Guid accountToken) |
1827 |
{ |
1828 |
string format = string.Format("{{\"uuids\":[\"{0}\"]}}", accountToken); |
1829 |
var content = new StringContent(format,Encoding.UTF8); |
1830 |
//content.Headers.ContentType=new MediaTypeHeaderValue("text/html; charset=utf-8"); |
1831 |
string catalogEntry; |
1832 |
var catalogUrl = new Uri(_baseHttpClient.BaseAddress.Scheme + "://" +_baseHttpClient.BaseAddress.Host,UriKind.Absolute).Combine("user_catalogs"); |
1833 |
using (var response = await _baseHttpClient.PostAsync(catalogUrl, content).ConfigureAwait(false)) |
1834 |
{ |
1835 |
catalogEntry=await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
1836 |
} |
1837 |
|
1838 |
var entry = (JContainer)JsonConvert.DeserializeObject(catalogEntry); |
1839 |
string key = accountToken.ToString(); |
1840 |
return (string)entry["uuid_catalog"][key]; |
1841 |
|
1842 |
} |
1843 |
|
1844 |
public async Task<Guid> ResolveToken(string displayName) |
1845 |
{ |
1846 |
string format = string.Format("{{\"displaynames\":[\"{0}\"]}}", displayName); |
1847 |
var content = new StringContent(format,Encoding.UTF8); |
1848 |
//content.Headers.ContentType=new MediaTypeHeaderValue("text/html; charset=utf-8"); |
1849 |
string catalogEntry; |
1850 |
var catalogUrl = new Uri(_baseHttpClient.BaseAddress.Scheme + "://" +_baseHttpClient.BaseAddress.Host,UriKind.Absolute).Combine("user_catalogs"); |
1851 |
using (var response = await _baseHttpClient.PostAsync(catalogUrl, content).ConfigureAwait(false)) |
1852 |
{ |
1853 |
catalogEntry=await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
1854 |
} |
1855 |
|
1856 |
var entry = (JContainer)JsonConvert.DeserializeObject(catalogEntry); |
1857 |
return new Guid((string)entry["displayname_catalog"][displayName]); |
1858 |
|
1859 |
} |
1860 |
} |
1861 |
|
1862 |
public class ShareAccountInfo |
1863 |
{ |
1864 |
public DateTime? last_modified { get; set; } |
1865 |
public string name { get; set; } |
1866 |
} |
1867 |
} |