using System.IO;
using System.Linq;
using System.Net;
+using System.Reflection;
using System.Security.Cryptography;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pithos.Interfaces;
[Export(typeof(ICloudClient))]
public class CloudFilesClient:ICloudClient
{
+ private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
//CloudFilesClient uses *_baseClient* internally to communicate with the server
//RestClient provides a REST-friendly interface over the standard WebClient.
private RestClient _baseClient;
public bool UsePithos { get; set; }
- private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
public CloudFilesClient(string userName, string apiKey)
{
}
Log.InfoFormat("[AUTHENTICATE] End for {0}", UserName);
-
+ Debug.Assert(_baseClient!=null);
return new AccountInfo {StorageUri = StorageUrl, Token = Token, UserName = UserName,Groups=groups};
using (ThreadContext.Stacks["Share"].Push("List Objects"))
{
if (Log.IsDebugEnabled) Log.DebugFormat("START");
-
+ //'since' is not used here because we need to have ListObjects return a NoChange result
+ //for all shared accounts,containers
+ var accounts = ListSharingAccounts();
+ var items = from account in accounts
+ let containers = ListContainers(account.name)
+ from container in containers
+ select ListObjects(account.name, container.Name,since);
+ var objects=items.SelectMany(r=> r).ToList();
+/*
var objects = new List<ObjectInfo>();
- var accounts = ListSharingAccounts(since);
- foreach (var account in accounts)
+ foreach (var containerObjects in items)
{
- var containers = ListContainers(account.name);
- foreach (var container in containers)
- {
- var containerObjects = ListObjects(account.name, container.Name);
- objects.AddRange(containerObjects);
- }
+ objects.AddRange(containerObjects);
}
+*/
if (Log.IsDebugEnabled) Log.DebugFormat("END");
return objects;
}
client.Headers.Add("X-Object-Public", isPublic);
- var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
- var uri = uriBuilder.Uri;
-
- client.UploadValues(uri,new NameValueCollection());
+ /*var uriBuilder = client.GetAddressBuilder(objectInfo.Container, objectInfo.Name);
+ uriBuilder.Query = "update=";
+ var uri = uriBuilder.Uri.MakeRelativeUri(this.RootAddressUri);*/
+ var address = String.Format("{0}/{1}?update=",objectInfo.Container, objectInfo.Name);
+ client.PostWithRetry(address,"application/xml");
+
+ //client.UploadValues(uri,new NameValueCollection());
client.AssertStatusOK("UpdateMetadata failed");
client.AssertStatusOK("ListObjects failed");
+ if (client.StatusCode==HttpStatusCode.NotModified)
+ return new[]{new NoModificationInfo(account,container)};
//If the result is empty, return an empty list,
var infos = String.IsNullOrWhiteSpace(content)
? new List<ObjectInfo>()
info.Account = account;
info.StorageUri = this.StorageUrl;
}
- if (Log.IsDebugEnabled) Log.DebugFormat("START");
+ if (Log.IsDebugEnabled) Log.DebugFormat("END");
return infos;
}
}
}
-
-
public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
{
if (String.IsNullOrWhiteSpace(container))
var content = client.DownloadStringWithRetry(container, 3);
client.AssertStatusOK("ListObjects failed");
+ if (client.StatusCode==HttpStatusCode.NotModified)
+ return new[]{new NoModificationInfo(account,container,folder)};
+
var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
foreach (var info in infos)
{
Account = account,
Container = container,
Name = objectName,
- Hash = client.GetHeaderValue("ETag"),
+ ETag = client.GetHeaderValue("ETag"),
+ X_Object_Hash = client.GetHeaderValue("X-Object-Hash"),
Content_Type = client.GetHeaderValue("Content-Type"),
Bytes = Convert.ToInt64(client.GetHeaderValue("Content-Length",true)),
Tags = tags,
ContentEncoding=client.GetHeaderValue("Content-Encoding",true),
ContendDisposition = client.GetHeaderValue("Content-Disposition",true),
Manifest=client.GetHeaderValue("X-Object-Manifest",true),
- PublicUrl=client.GetHeaderValue("X-Object-Public",true),
+ PublicUrl=client.GetHeaderValue("X-Object-Public",true),
+ StorageUri=this.StorageUrl,
};
info.SetPermissions(permissions);
return info;
{
Account=account,
Name = container,
+ StorageUrl=this.StorageUrl.ToString(),
Count =
long.Parse(client.GetHeaderValue("X-Container-Object-Count")),
Bytes = long.Parse(client.GetHeaderValue("X-Container-Bytes-Used")),
/// <remarks>This method should have no timeout or a very long one</remarks>
//Asynchronously download the object specified by *objectName* in a specific *container* to
// a local file
- public Task GetObject(string account, string container, string objectName, string fileName)
+ public async Task GetObject(string account, string container, string objectName, string fileName,CancellationToken cancellationToken)
{
if (String.IsNullOrWhiteSpace(container))
throw new ArgumentNullException("container", "The container property can't be empty");
//object to avoid concurrency errors.
//
//Download operations take a long time therefore they have no timeout.
- var client = new RestClient(_baseClient) { Timeout = 0 };
- if (!String.IsNullOrWhiteSpace(account))
- client.BaseAddress = GetAccountUrl(account);
+ using(var client = new RestClient(_baseClient) { Timeout = 0 })
+ {
+ if (!String.IsNullOrWhiteSpace(account))
+ client.BaseAddress = GetAccountUrl(account);
- //The container and objectName are relative names. They are joined with the client's
- //BaseAddress to create the object's absolute address
- var builder = client.GetAddressBuilder(container, objectName);
- var uri = builder.Uri;
+ //The container and objectName are relative names. They are joined with the client's
+ //BaseAddress to create the object's absolute address
+ var builder = client.GetAddressBuilder(container, objectName);
+ var uri = builder.Uri;
- //Download progress is reported to the Trace log
- Log.InfoFormat("[GET] START {0}", objectName);
- client.DownloadProgressChanged += (sender, args) =>
- Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
- fileName, args.ProgressPercentage,
- args.BytesReceived,
- args.TotalBytesToReceive);
+ //Download progress is reported to the Trace log
+ Log.InfoFormat("[GET] START {0}", objectName);
+ client.DownloadProgressChanged += (sender, args) =>
+ Log.InfoFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
+ fileName, args.ProgressPercentage,
+ args.BytesReceived,
+ args.TotalBytesToReceive);
+
+ //Start downloading the object asynchronously
+ await client.DownloadFileTaskAsync(uri, fileName,cancellationToken);
- //Start downloading the object asynchronously
- var downloadTask = client.DownloadFileTask(uri, fileName);
-
- //Once the download completes
- return downloadTask.ContinueWith(download =>
- {
- //Delete the local client object
- client.Dispose();
- //And report failure or completion
- if (download.IsFaulted)
- {
- Log.ErrorFormat("[GET] FAIL for {0} with \r{1}", objectName,
- download.Exception);
- }
- else
- {
- Log.InfoFormat("[GET] END {0}", objectName);
- }
- });
+ //Once the download completes
+ //Delete the local client object
+ }
+ //And report failure or completion
}
catch (Exception exc)
{
- Log.ErrorFormat("[GET] END {0} with {1}", objectName, exc);
+ Log.ErrorFormat("[GET] FAIL {0} with {1}", objectName, exc);
throw;
}
+ Log.InfoFormat("[GET] END {0}", objectName);
}
client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
var jsonHash = hash.ToJson();
var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
-
+ if (Log.IsDebugEnabled)
+ Log.DebugFormat("Hashes:\r\n{0}", jsonHash);
return uploadTask.ContinueWith(t =>
{
{
//In case of 409 the missing parts will be in the response content
using (var stream = response.GetResponseStream())
- using(var reader=new StreamReader(stream))
+ using(var reader=stream.GetLoggedReader(Log))
{
- Debug.Assert(stream.Position == 0);
//We used to have to cleanup the content before returning it because it contains
//error content after the list of hashes
//
//line by line
var serializer = new JsonSerializer();
- var hashes=(List<string>)serializer.Deserialize(reader, typeof (List<string>));
-
+ serializer.Error += (sender, args) => Log.ErrorFormat("Deserialization error at [{0}] [{1}]", args.ErrorContext.Error, args.ErrorContext.Member);
+ var hashes = (List<string>)serializer.Deserialize(reader, typeof(List<string>));
return hashes;
}
}
//Any other status code is unexpected and the exception should be rethrown
+ Log.LogError(response);
throw ex;
}
+
//Any other status code is unexpected but there was no exception. We can probably continue processing
Log.WarnFormat("Unexcpected status code when putting map: {0} - {1}",client.StatusCode,client.StatusDescription);
}
- public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
+
+ public async Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end, CancellationToken cancellationToken)
{
if (String.IsNullOrWhiteSpace(Token))
throw new InvalidOperationException("Invalid Token");
throw new InvalidOperationException("Invalid Storage Url");
if (String.IsNullOrWhiteSpace(container))
throw new ArgumentNullException("container");
- if (relativeUrl== null)
+ if (relativeUrl == null)
throw new ArgumentNullException("relativeUrl");
- if (end.HasValue && end<0)
+ if (end.HasValue && end < 0)
throw new ArgumentOutOfRangeException("end");
- if (start<0)
+ if (start < 0)
throw new ArgumentOutOfRangeException("start");
Contract.EndContractBlock();
-
//Don't use a timeout because putting the hashmap may be a long process
- var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end};
- if (!String.IsNullOrWhiteSpace(account))
- client.BaseAddress = GetAccountUrl(account);
+ using (var client = new RestClient(_baseClient) {Timeout = 0, RangeFrom = start, RangeTo = end})
+ {
+ if (!String.IsNullOrWhiteSpace(account))
+ client.BaseAddress = GetAccountUrl(account);
- var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
- var uri = builder.Uri;
+ var builder = client.GetAddressBuilder(container, relativeUrl.ToString());
+ var uri = builder.Uri;
+
+ client.DownloadProgressChanged += (sender, args) =>
+ Log.DebugFormat("[GET PROGRESS] {0} {1}% {2} of {3}",
+ uri.Segments.Last(), args.ProgressPercentage,
+ args.BytesReceived,
+ args.TotalBytesToReceive);
- return client.DownloadDataTask(uri)
- .ContinueWith(t=>
- {
- client.Dispose();
- return t.Result;
- });
+
+ var result = await client.DownloadDataTaskAsync(uri, cancellationToken);
+ return result;
+ }
}
//Don't use a timeout because putting the hashmap may be a long process
using (var client = new RestClient(_baseClient) { Timeout = 0 })
- {
+ {
if (!String.IsNullOrWhiteSpace(account))
client.BaseAddress = GetAccountUrl(account);
var buffer = new byte[count];
Buffer.BlockCopy(block, offset, buffer, 0, count);
//Send the block
- await client.UploadDataTask(uri, "POST", buffer);
+ await client.UploadDataTaskAsync(uri, "POST", buffer);
Log.InfoFormat("[BLOCK POST] END");
}
}
if (!File.Exists(fileName) && !Directory.Exists(fileName))
throw new FileNotFoundException("The file or directory does not exist",fileName);
*/
- Contract.EndContractBlock();
try
{
{
Log.InfoFormat("Completed {0}", fileName);
}
- };
+ };
if (contentType=="application/directory")
await client.UploadDataTaskAsync(uri, "PUT", new byte[0]);
else
client.Headers.Add("X-Move-From", sourceUrl);
client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
+ Log.InfoFormat("[TRASH] [{0}] to [{1}]",sourceUrl,targetUrl);
client.PutWithRetry(targetUrl, 3);
var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
var directories=this.ListObjects(container.Account, container.Name, "/");
}
*/
+
+ public bool CanUpload(string account, ObjectInfo cloudFile)
+ {
+ Contract.Requires(!String.IsNullOrWhiteSpace(account));
+ Contract.Requires(cloudFile!=null);
+
+ using (var client = new RestClient(_baseClient))
+ {
+ if (!String.IsNullOrWhiteSpace(account))
+ client.BaseAddress = GetAccountUrl(account);
+
+
+ var parts = cloudFile.Name.Split('/');
+ var folder = String.Join("/", parts,0,parts.Length-1);
+
+ var fileUrl=String.Format("{0}/{1}/{2}.pithos.ignore",cloudFile.Container,folder,Guid.NewGuid());
+
+ client.Parameters.Clear();
+ try
+ {
+ client.PutWithRetry(fileUrl, 3, @"application/octet-stream");
+
+ var expectedCodes = new[] { HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created};
+ var result=(expectedCodes.Contains(client.StatusCode));
+ DeleteObject(account, cloudFile.Container, fileUrl);
+ return result;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ }
}
public class ShareAccountInfo