Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / Uploader.cs @ 496595a5

History | View | Annotate | Download (17.4 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
                        Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action", fileInfo.FullName);
62
                        return;
63
                    }
64

    
65
                    var latestState = action.FileState;
66

    
67
                    //Do not upload files in conflict
68
                    if (latestState.FileStatus == FileStatus.Conflict)
69
                    {
70
                        Log.InfoFormat("Skipping file in conflict [{0}]", fileInfo.FullName);
71
                        return;
72
                    }
73
                    //Do not upload files when we have no permission
74
                    if (latestState.FileStatus == FileStatus.Forbidden)
75
                    {
76
                        Log.InfoFormat("Skipping forbidden file [{0}]", fileInfo.FullName);
77
                        return;
78
                    }
79

    
80
                    //Are we targeting our own account or a sharer account?
81
                    var relativePath = fileInfo.AsRelativeTo(action.AccountInfo.AccountPath);
82
                    var accountInfo = relativePath.StartsWith(FolderConstants.OthersFolder) 
83
                                                  ? GetSharerAccount(relativePath, action.AccountInfo) 
84
                                                  : action.AccountInfo;
85

    
86

    
87

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

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

    
100
                            var client = new CloudFilesClient(accountInfo);
101

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

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

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

    
128
                            }
129

    
130
                            await UnpauseEvent.WaitAsync();
131

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

    
152
                                var cloudHash = cloudInfo.Hash.ToLower();
153

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

    
162

    
163

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

    
173

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

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

    
181
                                
182

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

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

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

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

    
260

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

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

    
283
                var fullFileName = fileInfo.GetProperCapitalization();
284

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

    
288

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

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

    
301

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

    
308

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

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

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

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

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

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

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

    
358

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

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

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