root / trunk / Pithos.Core / Agents / PollAgent.cs @ d21f3c77
History | View | Annotate | Download (32.2 kB)
1 |
#region |
---|---|
2 |
/* ----------------------------------------------------------------------- |
3 |
* <copyright file="PollAgent.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 |
using System.Collections.Concurrent; |
44 |
using System.ComponentModel.Composition; |
45 |
using System.Diagnostics; |
46 |
using System.Diagnostics.Contracts; |
47 |
using System.IO; |
48 |
using System.Reflection; |
49 |
using System.Threading; |
50 |
using System.Threading.Tasks; |
51 |
using Castle.ActiveRecord; |
52 |
using Pithos.Interfaces; |
53 |
using Pithos.Network; |
54 |
using log4net; |
55 |
|
56 |
namespace Pithos.Core.Agents |
57 |
{ |
58 |
using System; |
59 |
using System.Collections.Generic; |
60 |
using System.Linq; |
61 |
|
62 |
/// <summary> |
63 |
/// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all |
64 |
/// objects and compares it with a previously cached version to detect differences. |
65 |
/// New files are downloaded, missing files are deleted from the local file system and common files are compared |
66 |
/// to determine the appropriate action |
67 |
/// </summary> |
68 |
[Export] |
69 |
public class PollAgent |
70 |
{ |
71 |
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); |
72 |
|
73 |
[System.ComponentModel.Composition.Import] |
74 |
public IStatusKeeper StatusKeeper { get; set; } |
75 |
|
76 |
[System.ComponentModel.Composition.Import] |
77 |
public IPithosSettings Settings { get; set; } |
78 |
|
79 |
[System.ComponentModel.Composition.Import] |
80 |
public NetworkAgent NetworkAgent { get; set; } |
81 |
|
82 |
[System.ComponentModel.Composition.Import] |
83 |
public Selectives Selectives { get; set; } |
84 |
|
85 |
public IStatusNotification StatusNotification { get; set; } |
86 |
|
87 |
public bool Pause |
88 |
{ |
89 |
get { |
90 |
return _pause; |
91 |
} |
92 |
set { |
93 |
_pause = value; |
94 |
if (!_pause) |
95 |
_unPauseEvent.Set(); |
96 |
else |
97 |
{ |
98 |
_unPauseEvent.Reset(); |
99 |
} |
100 |
} |
101 |
} |
102 |
|
103 |
private bool _firstPoll = true; |
104 |
|
105 |
//The Sync Event signals a manual synchronisation |
106 |
private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent(); |
107 |
|
108 |
private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true); |
109 |
|
110 |
private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>(); |
111 |
private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>(); |
112 |
|
113 |
|
114 |
/// <summary> |
115 |
/// Start a manual synchronization |
116 |
/// </summary> |
117 |
public void SynchNow() |
118 |
{ |
119 |
_syncEvent.Set(); |
120 |
} |
121 |
|
122 |
/// <summary> |
123 |
/// Remote files are polled periodically. Any changes are processed |
124 |
/// </summary> |
125 |
/// <param name="since"></param> |
126 |
/// <returns></returns> |
127 |
public async Task PollRemoteFiles(DateTime? since = null) |
128 |
{ |
129 |
if (Log.IsDebugEnabled) |
130 |
Log.DebugFormat("Polling changes after [{0}]",since); |
131 |
|
132 |
Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!"); |
133 |
|
134 |
|
135 |
using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts")) |
136 |
{ |
137 |
//If this poll fails, we will retry with the same since value |
138 |
var nextSince = since; |
139 |
try |
140 |
{ |
141 |
await _unPauseEvent.WaitAsync(); |
142 |
UpdateStatus(PithosStatus.PollSyncing); |
143 |
|
144 |
var tasks = from accountInfo in _accounts.Values |
145 |
select ProcessAccountFiles(accountInfo, since); |
146 |
|
147 |
var nextTimes=await TaskEx.WhenAll(tasks.ToList()); |
148 |
|
149 |
_firstPoll = false; |
150 |
//Reschedule the poll with the current timestamp as a "since" value |
151 |
|
152 |
if (nextTimes.Length>0) |
153 |
nextSince = nextTimes.Min(); |
154 |
if (Log.IsDebugEnabled) |
155 |
Log.DebugFormat("Next Poll at [{0}]",nextSince); |
156 |
} |
157 |
catch (Exception ex) |
158 |
{ |
159 |
Log.ErrorFormat("Error while processing accounts\r\n{0}", ex); |
160 |
//In case of failure retry with the same "since" value |
161 |
} |
162 |
|
163 |
UpdateStatus(PithosStatus.PollComplete); |
164 |
//The multiple try blocks are required because we can't have an await call |
165 |
//inside a finally block |
166 |
//TODO: Find a more elegant solution for reschedulling in the event of an exception |
167 |
try |
168 |
{ |
169 |
//Wait for the polling interval to pass or the Sync event to be signalled |
170 |
nextSince = await WaitForScheduledOrManualPoll(nextSince); |
171 |
} |
172 |
finally |
173 |
{ |
174 |
//Ensure polling is scheduled even in case of error |
175 |
TaskEx.Run(() => PollRemoteFiles(nextSince)); |
176 |
} |
177 |
} |
178 |
} |
179 |
|
180 |
/// <summary> |
181 |
/// Wait for the polling period to expire or a manual sync request |
182 |
/// </summary> |
183 |
/// <param name="since"></param> |
184 |
/// <returns></returns> |
185 |
private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since) |
186 |
{ |
187 |
var sync = _syncEvent.WaitAsync(); |
188 |
var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken); |
189 |
|
190 |
var signaledTask = await TaskEx.WhenAny(sync, wait); |
191 |
|
192 |
//Pausing takes precedence over manual sync or awaiting |
193 |
_unPauseEvent.Wait(); |
194 |
|
195 |
//Wait for network processing to finish before polling |
196 |
var pauseTask=NetworkAgent.ProceedEvent.WaitAsync(); |
197 |
await TaskEx.WhenAll(signaledTask, pauseTask); |
198 |
|
199 |
//If polling is signalled by SynchNow, ignore the since tag |
200 |
if (sync.IsCompleted) |
201 |
{ |
202 |
//TODO: Must convert to AutoReset |
203 |
_syncEvent.Reset(); |
204 |
return null; |
205 |
} |
206 |
return since; |
207 |
} |
208 |
|
209 |
public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null) |
210 |
{ |
211 |
if (accountInfo == null) |
212 |
throw new ArgumentNullException("accountInfo"); |
213 |
if (String.IsNullOrWhiteSpace(accountInfo.AccountPath)) |
214 |
throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo"); |
215 |
Contract.EndContractBlock(); |
216 |
|
217 |
|
218 |
using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName)) |
219 |
{ |
220 |
|
221 |
await NetworkAgent.GetDeleteAwaiter(); |
222 |
|
223 |
Log.Info("Scheduled"); |
224 |
var client = new CloudFilesClient(accountInfo); |
225 |
|
226 |
//We don't need to check the trash container |
227 |
var containers = client.ListContainers(accountInfo.UserName) |
228 |
.Where(c=>c.Name!="trash") |
229 |
.ToList(); |
230 |
|
231 |
|
232 |
CreateContainerFolders(accountInfo, containers); |
233 |
|
234 |
//The nextSince time fallback time is the same as the current. |
235 |
//If polling succeeds, the next Since time will be the smallest of the maximum modification times |
236 |
//of the shared and account objects |
237 |
var nextSince = since; |
238 |
|
239 |
try |
240 |
{ |
241 |
//Wait for any deletions to finish |
242 |
await NetworkAgent.GetDeleteAwaiter(); |
243 |
//Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted |
244 |
//than delete a file that was created while we were executing the poll |
245 |
|
246 |
//Get the list of server objects changed since the last check |
247 |
//The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step |
248 |
var listObjects = (from container in containers |
249 |
select Task<IList<ObjectInfo>>.Factory.StartNew(_ => |
250 |
client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList(); |
251 |
|
252 |
var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => |
253 |
client.ListSharedObjects(since), "shared"); |
254 |
listObjects.Add(listShared); |
255 |
var listTasks = await Task.Factory.WhenAll(listObjects.ToArray()); |
256 |
|
257 |
using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results")) |
258 |
{ |
259 |
var dict = listTasks.ToDictionary(t => t.AsyncState); |
260 |
|
261 |
//Get all non-trash objects. Remember, the container name is stored in AsyncState |
262 |
var remoteObjects = (from objectList in listTasks |
263 |
where (string)objectList.AsyncState != "trash" |
264 |
from obj in objectList.Result |
265 |
select obj).ToList(); |
266 |
|
267 |
//Get the latest remote object modification date, only if it is after |
268 |
//the original since date |
269 |
nextSince = GetLatestDateAfter(nextSince, remoteObjects); |
270 |
|
271 |
var sharedObjects = dict["shared"].Result; |
272 |
nextSince = GetLatestDateBefore(nextSince, sharedObjects); |
273 |
|
274 |
//DON'T process trashed files |
275 |
//If some files are deleted and added again to a folder, they will be deleted |
276 |
//even though they are new. |
277 |
//We would have to check file dates and hashes to ensure that a trashed file |
278 |
//can be deleted safely from the local hard drive. |
279 |
/* |
280 |
//Items with the same name, hash may be both in the container and the trash |
281 |
//Don't delete items that exist in the container |
282 |
var realTrash = from trash in trashObjects |
283 |
where |
284 |
!remoteObjects.Any( |
285 |
info => info.Name == trash.Name && info.Hash == trash.Hash) |
286 |
select trash; |
287 |
ProcessTrashedFiles(accountInfo, realTrash); |
288 |
*/ |
289 |
|
290 |
var cleanRemotes = (from info in remoteObjects.Union(sharedObjects) |
291 |
let name = info.Name??"" |
292 |
where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) && |
293 |
!name.StartsWith(FolderConstants.CacheFolder + "/", |
294 |
StringComparison.InvariantCultureIgnoreCase) |
295 |
select info).ToList(); |
296 |
|
297 |
if (_firstPoll) |
298 |
StatusKeeper.CleanupOrphanStates(); |
299 |
StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes); |
300 |
|
301 |
var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes); |
302 |
|
303 |
var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey]; |
304 |
|
305 |
ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris)); |
306 |
|
307 |
// @@@ NEED To add previous state here as well, To compare with previous hash |
308 |
|
309 |
|
310 |
|
311 |
//Create a list of actions from the remote files |
312 |
|
313 |
var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris)) |
314 |
.Union( |
315 |
ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris))) |
316 |
.Union( |
317 |
CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris))); |
318 |
|
319 |
//And remove those that are already being processed by the agent |
320 |
var distinctActions = allActions |
321 |
.Except(NetworkAgent.GetEnumerable(), new LocalFileComparer()) |
322 |
.ToList(); |
323 |
|
324 |
await _unPauseEvent.WaitAsync(); |
325 |
//Queue all the actions |
326 |
foreach (var message in distinctActions) |
327 |
{ |
328 |
NetworkAgent.Post(message); |
329 |
} |
330 |
|
331 |
Log.Info("[LISTENER] End Processing"); |
332 |
} |
333 |
} |
334 |
catch (Exception ex) |
335 |
{ |
336 |
Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex); |
337 |
return nextSince; |
338 |
} |
339 |
|
340 |
Log.Info("[LISTENER] Finished"); |
341 |
return nextSince; |
342 |
} |
343 |
} |
344 |
|
345 |
/// <summary> |
346 |
/// Returns the latest LastModified date from the list of objects, but only if it is before |
347 |
/// than the threshold value |
348 |
/// </summary> |
349 |
/// <param name="threshold"></param> |
350 |
/// <param name="cloudObjects"></param> |
351 |
/// <returns></returns> |
352 |
private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects) |
353 |
{ |
354 |
DateTime? maxDate = null; |
355 |
if (cloudObjects!=null && cloudObjects.Count > 0) |
356 |
maxDate = cloudObjects.Max(obj => obj.Last_Modified); |
357 |
if (maxDate == null || maxDate == DateTime.MinValue) |
358 |
return threshold; |
359 |
if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate) |
360 |
return maxDate; |
361 |
return threshold; |
362 |
} |
363 |
|
364 |
/// <summary> |
365 |
/// Returns the latest LastModified date from the list of objects, but only if it is after |
366 |
/// the threshold value |
367 |
/// </summary> |
368 |
/// <param name="threshold"></param> |
369 |
/// <param name="cloudObjects"></param> |
370 |
/// <returns></returns> |
371 |
private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects) |
372 |
{ |
373 |
DateTime? maxDate = null; |
374 |
if (cloudObjects!=null && cloudObjects.Count > 0) |
375 |
maxDate = cloudObjects.Max(obj => obj.Last_Modified); |
376 |
if (maxDate == null || maxDate == DateTime.MinValue) |
377 |
return threshold; |
378 |
if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate) |
379 |
return maxDate; |
380 |
return threshold; |
381 |
} |
382 |
|
383 |
readonly AccountsDifferencer _differencer = new AccountsDifferencer(); |
384 |
private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>(); |
385 |
private bool _pause; |
386 |
|
387 |
/// <summary> |
388 |
/// Deletes local files that are not found in the list of cloud files |
389 |
/// </summary> |
390 |
/// <param name="accountInfo"></param> |
391 |
/// <param name="cloudFiles"></param> |
392 |
private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles) |
393 |
{ |
394 |
if (accountInfo == null) |
395 |
throw new ArgumentNullException("accountInfo"); |
396 |
if (String.IsNullOrWhiteSpace(accountInfo.AccountPath)) |
397 |
throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo"); |
398 |
if (cloudFiles == null) |
399 |
throw new ArgumentNullException("cloudFiles"); |
400 |
Contract.EndContractBlock(); |
401 |
|
402 |
//On the first run |
403 |
if (_firstPoll) |
404 |
{ |
405 |
//Only consider files that are not being modified, ie they are in the Unchanged state |
406 |
var deleteCandidates = FileState.Queryable.Where(state => |
407 |
state.FilePath.StartsWith(accountInfo.AccountPath) |
408 |
&& state.FileStatus == FileStatus.Unchanged).ToList(); |
409 |
|
410 |
|
411 |
//TODO: filesToDelete must take into account the Others container |
412 |
var filesToDelete = (from deleteCandidate in deleteCandidates |
413 |
let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath) |
414 |
let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath) |
415 |
where |
416 |
!cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath) |
417 |
select localFile).ToList(); |
418 |
|
419 |
|
420 |
|
421 |
//Set the status of missing files to Conflict |
422 |
foreach (var item in filesToDelete) |
423 |
{ |
424 |
//Try to acquire a gate on the file, to take into account files that have been dequeued |
425 |
//and are being processed |
426 |
using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting)) |
427 |
{ |
428 |
if (gate.Failed) |
429 |
continue; |
430 |
StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,"Local file missing from server"); |
431 |
} |
432 |
} |
433 |
UpdateStatus(PithosStatus.HasConflicts); |
434 |
StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count)); |
435 |
StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info); |
436 |
} |
437 |
else |
438 |
{ |
439 |
var deletedFiles = new List<FileSystemInfo>(); |
440 |
foreach (var objectInfo in cloudFiles) |
441 |
{ |
442 |
if (Log.IsDebugEnabled) |
443 |
Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri); |
444 |
var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName); |
445 |
var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath); |
446 |
if (Log.IsDebugEnabled) |
447 |
Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri); |
448 |
if (item.Exists) |
449 |
{ |
450 |
if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) |
451 |
{ |
452 |
item.Attributes = item.Attributes & ~FileAttributes.ReadOnly; |
453 |
|
454 |
} |
455 |
|
456 |
|
457 |
Log.DebugFormat("Deleting {0}", item.FullName); |
458 |
|
459 |
var directory = item as DirectoryInfo; |
460 |
if (directory!=null) |
461 |
directory.Delete(true); |
462 |
else |
463 |
item.Delete(); |
464 |
Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri); |
465 |
DateTime lastDate; |
466 |
_lastSeen.TryRemove(item.FullName, out lastDate); |
467 |
deletedFiles.Add(item); |
468 |
} |
469 |
StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted"); |
470 |
} |
471 |
Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count); |
472 |
StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info); |
473 |
} |
474 |
|
475 |
} |
476 |
|
477 |
/// <summary> |
478 |
/// Creates a Sync action for each changed server file |
479 |
/// </summary> |
480 |
/// <param name="accountInfo"></param> |
481 |
/// <param name="changes"></param> |
482 |
/// <returns></returns> |
483 |
private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes) |
484 |
{ |
485 |
if (changes == null) |
486 |
throw new ArgumentNullException(); |
487 |
Contract.EndContractBlock(); |
488 |
var fileAgent = FileAgent.GetFileAgent(accountInfo); |
489 |
|
490 |
//In order to avoid multiple iterations over the files, we iterate only once |
491 |
//over the remote files |
492 |
foreach (var objectInfo in changes) |
493 |
{ |
494 |
var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName); |
495 |
//If a directory object already exists, we may need to sync it |
496 |
if (fileAgent.Exists(relativePath)) |
497 |
{ |
498 |
var localFile = fileAgent.GetFileSystemInfo(relativePath); |
499 |
//We don't need to sync directories |
500 |
if (objectInfo.IsDirectory && localFile is DirectoryInfo) |
501 |
continue; |
502 |
using (new SessionScope(FlushAction.Never)) |
503 |
{ |
504 |
var state = StatusKeeper.GetStateByFilePath(localFile.FullName); |
505 |
_lastSeen[localFile.FullName] = DateTime.Now; |
506 |
//Common files should be checked on a per-case basis to detect differences, which is newer |
507 |
|
508 |
yield return new CloudAction(accountInfo, CloudActionType.MustSynch, |
509 |
localFile, objectInfo, state, accountInfo.BlockSize, |
510 |
accountInfo.BlockHash); |
511 |
} |
512 |
} |
513 |
else |
514 |
{ |
515 |
//Remote files should be downloaded |
516 |
yield return new CloudDownloadAction(accountInfo, objectInfo); |
517 |
} |
518 |
} |
519 |
} |
520 |
|
521 |
/// <summary> |
522 |
/// Creates a Local Move action for each moved server file |
523 |
/// </summary> |
524 |
/// <param name="accountInfo"></param> |
525 |
/// <param name="moves"></param> |
526 |
/// <returns></returns> |
527 |
private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves) |
528 |
{ |
529 |
if (moves == null) |
530 |
throw new ArgumentNullException(); |
531 |
Contract.EndContractBlock(); |
532 |
var fileAgent = FileAgent.GetFileAgent(accountInfo); |
533 |
|
534 |
//In order to avoid multiple iterations over the files, we iterate only once |
535 |
//over the remote files |
536 |
foreach (var objectInfo in moves) |
537 |
{ |
538 |
var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName); |
539 |
//If the previous file already exists, we can execute a Move operation |
540 |
if (fileAgent.Exists(previousRelativepath)) |
541 |
{ |
542 |
var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath); |
543 |
using (new SessionScope(FlushAction.Never)) |
544 |
{ |
545 |
var state = StatusKeeper.GetStateByFilePath(previousFile.FullName); |
546 |
_lastSeen[previousFile.FullName] = DateTime.Now; |
547 |
|
548 |
//For each moved object we need to move both the local file and update |
549 |
yield return new CloudAction(accountInfo, CloudActionType.RenameLocal, |
550 |
previousFile, objectInfo, state, accountInfo.BlockSize, |
551 |
accountInfo.BlockHash); |
552 |
//For modified files, we need to download the changes as well |
553 |
if (objectInfo.Hash!=objectInfo.PreviousHash) |
554 |
yield return new CloudDownloadAction(accountInfo,objectInfo); |
555 |
} |
556 |
} |
557 |
//If the previous file does not exist, we need to download it in the new location |
558 |
else |
559 |
{ |
560 |
//Remote files should be downloaded |
561 |
yield return new CloudDownloadAction(accountInfo, objectInfo); |
562 |
} |
563 |
} |
564 |
} |
565 |
|
566 |
|
567 |
/// <summary> |
568 |
/// Creates a download action for each new server file |
569 |
/// </summary> |
570 |
/// <param name="accountInfo"></param> |
571 |
/// <param name="creates"></param> |
572 |
/// <returns></returns> |
573 |
private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates) |
574 |
{ |
575 |
if (creates == null) |
576 |
throw new ArgumentNullException(); |
577 |
Contract.EndContractBlock(); |
578 |
var fileAgent = FileAgent.GetFileAgent(accountInfo); |
579 |
|
580 |
//In order to avoid multiple iterations over the files, we iterate only once |
581 |
//over the remote files |
582 |
foreach (var objectInfo in creates) |
583 |
{ |
584 |
if (Log.IsDebugEnabled) |
585 |
Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri); |
586 |
|
587 |
var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName); |
588 |
|
589 |
//If the object already exists, we should check before uploading or downloading |
590 |
if (fileAgent.Exists(relativePath)) |
591 |
{ |
592 |
var localFile= fileAgent.GetFileSystemInfo(relativePath); |
593 |
var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName); |
594 |
yield return new CloudAction(accountInfo, CloudActionType.MustSynch, |
595 |
localFile, objectInfo, state, accountInfo.BlockSize, |
596 |
accountInfo.BlockHash); |
597 |
} |
598 |
else |
599 |
{ |
600 |
//Remote files should be downloaded |
601 |
yield return new CloudDownloadAction(accountInfo, objectInfo); |
602 |
} |
603 |
|
604 |
} |
605 |
} |
606 |
|
607 |
/// <summary> |
608 |
/// Notify the UI to update the visual status |
609 |
/// </summary> |
610 |
/// <param name="status"></param> |
611 |
private void UpdateStatus(PithosStatus status) |
612 |
{ |
613 |
try |
614 |
{ |
615 |
StatusNotification.SetPithosStatus(status); |
616 |
//StatusNotification.Notify(new Notification()); |
617 |
} |
618 |
catch (Exception exc) |
619 |
{ |
620 |
//Failure is not critical, just log it |
621 |
Log.Warn("Error while updating status", exc); |
622 |
} |
623 |
} |
624 |
|
625 |
private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers) |
626 |
{ |
627 |
var containerPaths = from container in containers |
628 |
let containerPath = Path.Combine(accountInfo.AccountPath, container.Name) |
629 |
where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath) |
630 |
select containerPath; |
631 |
|
632 |
foreach (var path in containerPaths) |
633 |
{ |
634 |
Directory.CreateDirectory(path); |
635 |
} |
636 |
} |
637 |
|
638 |
public void AddAccount(AccountInfo accountInfo) |
639 |
{ |
640 |
//Avoid adding a duplicate accountInfo |
641 |
_accounts.TryAdd(accountInfo.AccountKey, accountInfo); |
642 |
} |
643 |
|
644 |
public void RemoveAccount(AccountInfo accountInfo) |
645 |
{ |
646 |
AccountInfo account; |
647 |
_accounts.TryRemove(accountInfo.AccountKey, out account); |
648 |
SnapshotDifferencer differencer; |
649 |
_differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer); |
650 |
} |
651 |
|
652 |
public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed) |
653 |
{ |
654 |
AbortRemovedPaths(accountInfo,removed); |
655 |
DownloadNewPaths(accountInfo,added); |
656 |
} |
657 |
|
658 |
private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added) |
659 |
{ |
660 |
var client = new CloudFilesClient(accountInfo); |
661 |
foreach (var folderUri in added) |
662 |
{ |
663 |
try |
664 |
{ |
665 |
|
666 |
string account; |
667 |
string container; |
668 |
var segmentsCount = folderUri.Segments.Length; |
669 |
if (segmentsCount < 3) |
670 |
continue; |
671 |
if (segmentsCount == 3) |
672 |
{ |
673 |
account = folderUri.Segments[1].TrimEnd('/'); |
674 |
container = folderUri.Segments[2].TrimEnd('/'); |
675 |
} |
676 |
else |
677 |
{ |
678 |
account = folderUri.Segments[2].TrimEnd('/'); |
679 |
container = folderUri.Segments[3].TrimEnd('/'); |
680 |
} |
681 |
IList<ObjectInfo> items; |
682 |
if (segmentsCount > 3) |
683 |
{ |
684 |
var folder = String.Join("", folderUri.Segments.Splice(4)); |
685 |
items = client.ListObjects(account, container, folder); |
686 |
} |
687 |
else |
688 |
{ |
689 |
items = client.ListObjects(account, container); |
690 |
} |
691 |
var actions = CreatesToActions(accountInfo, items); |
692 |
foreach (var action in actions) |
693 |
{ |
694 |
NetworkAgent.Post(action); |
695 |
} |
696 |
} |
697 |
catch (Exception exc) |
698 |
{ |
699 |
Log.WarnFormat("Listing of new selective path [{0}] failed with \r\n{1}", folderUri, exc); |
700 |
} |
701 |
} |
702 |
|
703 |
//Need to get a listing of each of the URLs, then post them to the NetworkAgent |
704 |
//CreatesToActions(accountInfo,) |
705 |
|
706 |
/* NetworkAgent.Post();*/ |
707 |
} |
708 |
|
709 |
private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed) |
710 |
{ |
711 |
/*this.NetworkAgent.*/ |
712 |
} |
713 |
} |
714 |
} |