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