Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / Uploader.cs @ 1cc1e8c5

History | View | Annotate | Download (17.5 kB)

1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel.Composition;
4
using System.Diagnostics;
5
using System.Diagnostics.Contracts;
6
using System.IO;
7
using System.Linq;
8
using System.Net;
9
using System.Reflection;
10
using System.Security.Cryptography;
11
using System.Threading;
12
using System.Threading.Tasks;
13
using Pithos.Interfaces;
14
using Pithos.Network;
15
using log4net;
16

    
17
namespace Pithos.Core.Agents
18
{
19
    [Export(typeof(Uploader))]
20
    public class Uploader
21
    {
22
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
23

    
24
        [Import]
25
        private IStatusKeeper StatusKeeper { get; set; }
26

    
27
        public IStatusNotification StatusNotification { get; set; }
28

    
29
        
30
        //CancellationTokenSource _cts = new CancellationTokenSource();
31
        /*public void SignalStop()
32
        {
33
            _cts.Cancel();
34
        }*/
35

    
36
        public async Task UploadCloudFile(CloudUploadAction action,CancellationToken cancellationToken)
37
        {
38
            if (action == null)
39
                throw new ArgumentNullException("action");
40
            Contract.EndContractBlock();
41

    
42
            using (ThreadContext.Stacks["Operation"].Push("UploadCloudFile"))
43
            {
44
                try
45
                {
46
                    await UnpauseEvent.WaitAsync();
47

    
48
                    var fileInfo = action.LocalFile;
49

    
50
                    if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
51
                        return;
52

    
53
                    if (!Selectives.IsSelected(action.AccountInfo, fileInfo) && !action.IsCreation)
54
                        return;
55

    
56
                    //Try to load the action's local state, if it is empty
57
                    if (action.FileState == null)
58
                        action.FileState = StatusKeeper.GetStateByFilePath(fileInfo.FullName);
59
                    if (action.FileState != null)
60
                    {
61
                        /*
62
                                                Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action", fileInfo.FullName);
63
                                                return;
64
                        */
65

    
66

    
67
                        var latestState = action.FileState;
68

    
69
                        //Do not upload files in conflict
70
                        if (latestState.FileStatus == FileStatus.Conflict)
71
                        {
72
                            Log.InfoFormat("Skipping file in conflict [{0}]", fileInfo.FullName);
73
                            return;
74
                        }
75
                        //Do not upload files when we have no permission
76
                        if (latestState.FileStatus == FileStatus.Forbidden)
77
                        {
78
                            Log.InfoFormat("Skipping forbidden file [{0}]", fileInfo.FullName);
79
                            return;
80
                        }
81
                    }
82
                    //Are we targeting our own account or a sharer account?
83
                    var relativePath = fileInfo.AsRelativeTo(action.AccountInfo.AccountPath);
84
                    var accountInfo = relativePath.StartsWith(FolderConstants.OthersFolder) 
85
                                                  ? GetSharerAccount(relativePath, action.AccountInfo) 
86
                                                  : action.AccountInfo;
87

    
88

    
89

    
90
                    var fullFileName = fileInfo.GetProperCapitalization();
91
                    using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
92
                    {
93
                        //Abort if the file is already being uploaded or downloaded
94
                        if (gate.Failed)
95
                            return;
96

    
97
                        var cloudFile = action.CloudFile;
98
                        var account = cloudFile.Account ?? accountInfo.UserName;
99
                        try
100
                        {
101

    
102
                            var client = new CloudFilesClient(accountInfo);
103

    
104
                            //Even if GetObjectInfo times out, we can proceed with the upload            
105
                            var cloudInfo = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
106

    
107
                            //If this a shared file
108
                            if (!cloudFile.Account.Equals(action.AccountInfo.UserName,StringComparison.InvariantCultureIgnoreCase))
109
                            {
110
                                
111
/*
112
                                if (!cloudInfo.IsWritable(action.AccountInfo.UserName))
113
                                {
114
                                    MakeFileReadOnly(fullFileName);
115
                                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
116
                                    return;
117
                                }
118
*/
119

    
120
                                //If this is a read-only file, do not upload changes
121
                                if ( !cloudInfo.IsWritable(action.AccountInfo.UserName) ||
122
                                    //If the file is new, but we can't upload it
123
                                    (!cloudInfo.Exists && !client.CanUpload(account, cloudFile)) )
124
                                {
125
                                    MakeFileReadOnly(fullFileName);
126
                                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
127
                                    return;
128
                                }
129

    
130
                            }
131

    
132
                            await UnpauseEvent.WaitAsync();
133

    
134
                            if (fileInfo is DirectoryInfo)
135
                            {
136
                                //If the directory doesn't exist the Hash property will be empty
137
                                if (String.IsNullOrWhiteSpace(cloudInfo.X_Object_Hash))
138
                                    //Go on and create the directory
139
                                    await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName,
140
                                                         String.Empty, "application/directory");
141
                                //If the upload is in response to a Folder create with Selective Sync enabled
142
                                if (action.IsCreation)
143
                                {
144
                                    //Add the folder to the Selected URls
145
                                    var selectiveUri = new Uri(client.RootAddressUri, cloudFile.Uri);
146
                                    Selectives.AddUri(accountInfo, selectiveUri);                                    
147
                                    Selectives.Save(accountInfo);
148
                                }
149
                            }
150
                            else
151
                            {
152

    
153
                                var cloudHash = cloudInfo.X_Object_Hash.ToLower();
154

    
155
                                string topHash;
156
                                TreeHash treeHash;
157
                                using(StatusNotification.GetNotifier("Hashing {0} for Upload", "Finished hashing {0}",fileInfo.Name))
158
                                {
159
                                    treeHash = action.TreeHash.Value;
160
                                    topHash = treeHash.TopHash.ToHashString();
161
                                }
162

    
163

    
164

    
165
                                //If the file hashes match, abort the upload
166
                                if (cloudInfo != ObjectInfo.Empty && (topHash == cloudHash ))
167
                                {
168
                                    //but store any metadata changes 
169
                                    StatusKeeper.StoreInfo(fullFileName, cloudInfo);
170
                                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
171
                                    return;
172
                                }
173

    
174

    
175
                                //Mark the file as modified while we upload it
176
                                await StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
177
                                //And then upload it
178

    
179
                                //Upload even small files using the Hashmap. The server may already contain
180
                                //the relevant block                                
181

    
182
                                
183

    
184
                                await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash,cancellationToken);
185
                            }
186
                            //If everything succeeds, change the file and overlay status to normal
187
                            StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
188
                        }
189
                        catch (WebException exc)
190
                        {
191
                            var response = (exc.Response as HttpWebResponse);
192
                            if (response == null)
193
                                throw;
194
                            if (response.StatusCode == HttpStatusCode.Forbidden)
195
                            {
196
                                StatusKeeper.SetFileState(fileInfo.FullName, FileStatus.Forbidden, FileOverlayStatus.Conflict, "Forbidden");
197
                                MakeFileReadOnly(fullFileName);
198
                            }
199
                            else
200
                                //In any other case, propagate the error
201
                                throw;
202
                        }
203
                    }
204
                    //Notify the Shell to update the overlays
205
                    NativeMethods.RaiseChangeNotification(fullFileName);
206
                    StatusNotification.NotifyChangedFile(fullFileName);
207
                }
208
                catch (AggregateException ex)
209
                {
210
                    var exc = ex.InnerException as WebException;
211
                    if (exc == null)
212
                        throw ex.InnerException;
213
                    if (HandleUploadWebException(action, exc))
214
                        return;
215
                    throw;
216
                }
217
                catch (WebException ex)
218
                {
219
                    if (HandleUploadWebException(action, ex))
220
                        return;
221
                    throw;
222
                }
223
                catch (Exception ex)
224
                {
225
                    Log.Error("Unexpected error while uploading file", ex);
226
                    throw;
227
                }
228
            }
229
        }
230

    
231
        private static void MakeFileReadOnly(string fullFileName)
232
        {
233
            var attributes = File.GetAttributes(fullFileName);
234
            //Do not make any modifications if not necessary
235
            if (attributes.HasFlag(FileAttributes.ReadOnly))
236
                return;
237
            File.SetAttributes(fullFileName, attributes | FileAttributes.ReadOnly);            
238
        }
239

    
240
        private static AccountInfo GetSharerAccount(string relativePath, AccountInfo accountInfo)
241
        {
242
            var parts = relativePath.Split('\\');
243
            var accountName = parts[1];
244
            var oldName = accountInfo.UserName;
245
            var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
246
            var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
247
            var root = absoluteUri.Substring(0, nameIndex);
248

    
249
            accountInfo = new AccountInfo
250
                              {
251
                                  UserName = accountName,
252
                                  AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
253
                                  StorageUri = new Uri(root + accountName),
254
                                  BlockHash = accountInfo.BlockHash,
255
                                  BlockSize = accountInfo.BlockSize,
256
                                  Token = accountInfo.Token
257
                              };
258
            return accountInfo;
259
        }
260

    
261

    
262
        public async Task UploadWithHashMap(AccountInfo accountInfo, ObjectInfo cloudFile, FileInfo fileInfo, string url, TreeHash treeHash, CancellationToken token)
263
        {
264
            if (accountInfo == null)
265
                throw new ArgumentNullException("accountInfo");
266
            if (cloudFile == null)
267
                throw new ArgumentNullException("cloudFile");
268
            if (fileInfo == null)
269
                throw new ArgumentNullException("fileInfo");
270
            if (String.IsNullOrWhiteSpace(url))
271
                throw new ArgumentNullException(url);
272
            if (treeHash == null)
273
                throw new ArgumentNullException("treeHash");
274
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
275
                throw new ArgumentException("Invalid container", "cloudFile");
276
            Contract.EndContractBlock();
277

    
278
           
279
            using (StatusNotification.GetNotifier("Uploading {0}", "Finished Uploading {0}", fileInfo.Name))
280
            {
281
                if (await WaitOrAbort(accountInfo,cloudFile, token)) 
282
                    return;
283

    
284
                var fullFileName = fileInfo.GetProperCapitalization();
285

    
286
                var account = cloudFile.Account ?? accountInfo.UserName;
287
                var container = cloudFile.Container;
288

    
289

    
290
                var client = new CloudFilesClient(accountInfo);
291
                //Send the hashmap to the server            
292
                var missingHashes = await client.PutHashMap(account, container, url, treeHash);
293
                int block = 0;
294
                ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
295
                //If the server returns no missing hashes, we are done
296
                while (missingHashes.Count > 0)
297
                {
298

    
299
                    if (await WaitOrAbort(accountInfo,cloudFile, token))
300
                        return;
301

    
302

    
303
                    var buffer = new byte[accountInfo.BlockSize];
304
                    foreach (var missingHash in missingHashes)
305
                    {
306
                        if (await WaitOrAbort(accountInfo,cloudFile, token))
307
                            return;
308

    
309

    
310
                        //Find the proper block
311
                        var blockIndex = treeHash.HashDictionary[missingHash];
312
                        long offset = blockIndex*accountInfo.BlockSize;
313

    
314
                        var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
315

    
316
                        try
317
                        {
318
                            //And upload the block                
319
                            await client.PostBlock(account, container, buffer, 0, read, token);
320
                            Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
321
                        }
322
                        catch (TaskCanceledException exc)
323
                        {
324
                            throw new OperationCanceledException(token);
325
                        }
326
                        catch (Exception exc)
327
                        {
328
                            Log.Error(String.Format("Uploading block {0} of {1}", blockIndex, fullFileName), exc);
329
                        }
330
                        ReportUploadProgress(fileInfo.Name, block++, missingHashes.Count, fileInfo.Length);
331
                    }
332

    
333
                    token.ThrowIfCancellationRequested();
334
                    //Repeat until there are no more missing hashes                
335
                    missingHashes = await client.PutHashMap(account, container, url, treeHash);
336
                }
337

    
338
                ReportUploadProgress(fileInfo.Name, missingHashes.Count, missingHashes.Count, fileInfo.Length);
339
            }
340
        }
341

    
342
        private async Task<bool> WaitOrAbort(AccountInfo account,ObjectInfo cloudFile, CancellationToken token)
343
        {
344
            token.ThrowIfCancellationRequested();
345
            await UnpauseEvent.WaitAsync();
346
            var shouldAbort = !Selectives.IsSelected(account,cloudFile);
347
            if (shouldAbort)
348
                Log.InfoFormat("Aborting [{0}]",cloudFile.Uri);
349
            return shouldAbort;
350
        }
351

    
352
        private void ReportUploadProgress(string fileName, int block, int totalBlocks, long fileSize)
353
        {
354
            StatusNotification.Notify(totalBlocks == 0
355
                                          ? new ProgressNotification(fileName, "Uploading", 1, 1, fileSize)
356
                                          : new ProgressNotification(fileName, "Uploading", block, totalBlocks, fileSize));
357
        }
358

    
359

    
360
        private bool HandleUploadWebException(CloudAction action, WebException exc)
361
        {
362
            var response = exc.Response as HttpWebResponse;
363
            if (response == null)
364
                throw exc;
365
            if (response.StatusCode == HttpStatusCode.Unauthorized)
366
            {
367
                Log.Error("Not allowed to upload file", exc);
368
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
369
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal, "");
370
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
371
                return true;
372
            }
373
            return false;
374
        }
375

    
376
        [Import]
377
        public Selectives Selectives { get; set; }
378

    
379
        public AsyncManualResetEvent UnpauseEvent { get; set; }
380
    }
381
}