Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / Uploader.cs @ c945b450

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.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 selections = Selectives.SelectiveUris[accountInfo.AccountKey];
146
                                    var selectiveUri = new Uri(client.RootAddressUri, cloudFile.Uri);
147
                                    selections.Add(selectiveUri);
148
                                    Selectives.Save(accountInfo);
149
                                }
150
                            }
151
                            else
152
                            {
153

    
154
                                var cloudHash = cloudInfo.Hash.ToLower();
155

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

    
164

    
165

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

    
175

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

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

    
183
                                
184

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

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

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

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

    
262

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

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

    
285
                var fullFileName = fileInfo.GetProperCapitalization();
286

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

    
290

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

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

    
303

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

    
310

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

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

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

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

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

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

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

    
360

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

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

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