/
Backup.cs
1576 lines (1469 loc) · 45.3 KB
/
Backup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2008,2009,2010,2011 Chris Capon.
This file is part of KeepBack.
KeepBack is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KeepBack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with KeepBack. If not, see <http://www.gnu.org/licenses/>.
*/
/*
When compiling under Mono - include reference to Mono.Posix
*/
#if true //tracking a bug in history processing
#define CHECK_HISTORY_BUG
#endif
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
namespace KeepBack
{
public class Backup
{
//--- define ----------------------------
const int Maximum_Items_In_Queue = 999; //maximum # of files and folders waiting to be updated at a time
const string ExMethod = "Backup.Method";
const string ExArchiveRoot = "Backup.Archive.Root";
const string ExCurrentRoot = "Backup.Current.Root";
const string ExCurrentPath = "Backup.Current.Path";
const string ExCurrentFilename = "Backup.Current.Filename";
const string ExHistoryRoot = "Backup.History.Root";
const string ExHistoryPath = "Backup.History.Path";
const string ExHistoryFilename = "Backup.History.Filename";
const string ExFolderName = "Backup.Folder.Name";
const string ExFolderRoot = "Backup.Folder.Root";
const string ExFolderPath = "Backup.Folder.Path";
const string ExFolderFilename = "Backup.Folder.Filename";
const string ExPath = "Backup.Path";
const string ExFilename = "Backup.Filename";
const string ExUpdateAction = "Backup.Update.Action";
const string ExUpdatePath = "Backup.Update.Path";
const string ExUpdateFilename = "Backup.Update.Filename";
public enum Operation
{
Merge,
Backup,
}
enum ActionType
{
None = 0,
Copy,
Delete,
}
enum StatusType : int
{
Created = 0,
Modified = 1,
Deleted = 2,
Skipped = 3,
}
class FolderInfo
{
string name;
string root;
MatchSet filters = null;
public string Name { get { return name; } }
public string Root { get { return root; } }
public FolderInfo( string name, string root )
{
this.name = name;
this.root = root;
}
public FolderInfo( CtrlFolder f, bool isCaseSensitive ) : this( f.Name, f.Path )
{
filters = new MatchSet( f.Filters, isCaseSensitive );
}
public bool IsHistoryFolder ( string path ) { return (filters != null) ? filters.IsHistoryFolder ( path ) : true; }
public bool IsHistoryFile ( string path ) { return (filters != null) ? filters.IsHistoryFile ( path ) : true; }
public bool IsIncludedFolder( string path ) { return (filters != null) ? filters.IsIncludedFolder( path ) : true; }
public bool IsIncludedFile ( string path ) { return (filters != null) ? filters.IsIncludedFile ( path ) : true; }
}
struct UpdateRequest
{
public ActionType action;
public FolderInfo folder;
public string path;
public string filename;
public UpdateRequest( ActionType action, FolderInfo folder, string path, string filename )
{
this.action = action;
this.folder = folder;
this.path = path;
this.filename = filename;
}
}
public class BackupStatus
{
public struct Merge
{
public string current;
}
public struct Scan
{
public string current;
public long folders;
public long files;
}
public struct Update
{
public string current;
public long created;
public long modified;
public long deleted;
public long skipped;
}
public Merge merge;
public Scan scan;
public Update update;
public string ToString( long val )
{
return (val <= 0) ? string.Empty : val.ToString( "N0" );
}
}
public delegate void MessageDelegate( string msg );
//--- field -----------------------------
char[] InvalidFilenameCharacters = System.IO.Path.GetInvalidFileNameChars();
char[] InvalidPathCharacters = System.IO.Path.GetInvalidPathChars();
MessageDelegate message;
Ctrl ctrl = null;
bool debug = false;
BlockingCollection<string> logging = null;
BackupStatus status = null;
CancellationTokenSource cancel = null;
ManualResetEvent pause = new ManualResetEvent( true );
DateTime start = DateTime.MinValue;
BlockingCollection<UpdateRequest> queue = null;
string current = null;
string history = null;
Thread log = null;
Thread merge = null;
Thread scan = null;
Thread update = null;
//--- property --------------------------
public TimeSpan Elapsed { get { return DateTime.Now - start; } }
public BackupStatus Status { get { return status; } }
public int Pending { get { return (queue != null) ? queue.Count : 0; } }
public int LogCount { get { return logging.Count; } }
public bool IsLogAlive { get { return (log != null) && log .IsAlive; } }
public bool IsMergeAlive { get { return (merge != null) && merge .IsAlive; } }
public bool IsScanAlive { get { return (scan != null) && scan .IsAlive; } }
public bool IsUpdateAlive { get { return (update != null) && update.IsAlive; } }
public bool IsMergeWorking { get { return (IsMergeAlive && ! merge .ThreadState.HasFlag( ThreadState.WaitSleepJoin )); } }
public bool IsScanWorking { get { return (IsScanAlive && ! scan .ThreadState.HasFlag( ThreadState.WaitSleepJoin )); } }
public bool IsUpdateWorking { get { return (IsUpdateAlive && ! update.ThreadState.HasFlag( ThreadState.WaitSleepJoin )); } }
public ThreadState MergeState { get { return (merge != null) ? merge .ThreadState : ThreadState.Unstarted; } }
public ThreadState ScanState { get { return (scan != null) ? scan .ThreadState : ThreadState.Unstarted; } }
public ThreadState UpdateState { get { return (update != null) ? update.ThreadState : ThreadState.Unstarted; } }
public bool IsPaused { get { return ! pause.WaitOne( 0 ); } }
bool IsCancelRequested { get { pause.WaitOne(); return cancel.IsCancellationRequested; } }
public bool IsRunning
{
get
{
if( ! IsMergeAlive && ! IsScanAlive && ! IsUpdateAlive )
{
if( (logging != null) && ! logging.IsAddingCompleted )
{
logging.CompleteAdding();
}
if( ! IsLogAlive )
{
return false;
}
}
return true;
}
}
//--- constructor -----------------------
public Backup( MessageDelegate message )
{
this.message = message;
}
//--- backup ----------------------------
public void Process( Operation operation, Ctrl ctrl, bool debug )
{
try
{
this.ctrl = ctrl;
this.debug = debug;
this.logging = new BlockingCollection<string>( Maximum_Items_In_Queue );
this.status = new BackupStatus();
this.cancel = new CancellationTokenSource();
pause.Set();
this.start = DateTime.Now;
this.queue = new BlockingCollection<UpdateRequest>( Maximum_Items_In_Queue );
this.current = null;
this.history = null;
this.log = new Thread( new ThreadStart( LogHandler ) );
this.log.Name = "Log";
this.log.Priority = ThreadPriority.BelowNormal;
this.log.Start();
switch( operation )
{
case Operation.Merge:
{
this.merge = new Thread( new ThreadStart( MergeHandler ) );
this.merge.Name = "Update";
this.merge.Priority = ThreadPriority.BelowNormal;
this.merge.Start();
break;
}
case Operation.Backup:
{
this.scan = new Thread( new ThreadStart( ScanHandler ) );
this.scan .Name = "Scan";
this.scan .Priority = ThreadPriority.BelowNormal;
this.scan .Start();
this.update = new Thread( new ThreadStart( UpdateHandler ) );
this.update.Name = "Update";
this.update.Priority = ThreadPriority.BelowNormal;
this.update.Start();
break;
}
}
}
catch( Exception ex )
{
Msg( "Process: {0}", Except.ToString( ex, debug ) );
}
}
public void Pause()
{
if( cancel != null )
{
lock( cancel )
{
if( ! cancel.IsCancellationRequested )
{
if( pause.WaitOne( 0 ) )
{
pause.Reset();
}
else
{
pause.Set();
}
}
}
}
}
public void Cancel()
{
try
{
if( cancel != null )
{
bool b = false;
lock( cancel )
{
if( ! cancel.IsCancellationRequested )
{
cancel.Cancel();
pause.Set();
b = true;
}
}
if( b )
{
if( IsScanAlive ) { scan .Abort(); }
if( IsUpdateAlive ) { update.Abort(); }
if( IsMergeAlive ) { merge .Abort(); }
Msg( "..operation cancelled" );
}
}
}
catch( Exception ex )
{
Msg( "Cancel: {0}", Except.ToString( ex, debug ) );
}
}
//--- logging ---------------------------
void LogHandler()
{
try
{
Msg( "Log: begins" );
using( StreamWriter sw = ctrl.CreateLogFile( start ) )
{
try
{
foreach( string msg in logging.GetConsumingEnumerable() )
{
sw.WriteLine( msg );
}
}
catch( Exception ex )
{
logging.CompleteAdding();
sw.WriteLine( "Log: {0}", Except.ToString( ex, debug ) );
}
sw.WriteLine();
sw.WriteLine( "{0} - Elapsed", Ctrl.FormatTimeSpan( Elapsed ) );
sw.WriteLine( "Scanned {0:N0} folders, {1:N0} files", status.scan.folders, status.scan.files );
sw.WriteLine( "Updated {0:N0} created, {1:N0} modified, {2:N0} deleted, {3:N0} skipped", status.update.created, status.update.modified, status.update.deleted, status.update.skipped );
}
}
catch( Exception ex )
{
logging.CompleteAdding();
Msg( "Log: {0}", Except.ToString( ex, debug ) );
Cancel();
}
finally
{
Msg( "Log: complete" );
}
}
//--- backup scanner --------------------
void ScanHandler()
{
try
{
Msg( "Scan: begins" );
Scan();
}
catch( Exception ex )
{
Msg( "Scan: {0}", Except.ToString( ex, debug ) );
Cancel();
}
finally
{
queue.CompleteAdding();
Msg( "Scan: {0}", cancel.IsCancellationRequested ? "cancelled" : "complete" );
}
}
void Scan()
{
try
{
Msg( "Archive: {0}", ctrl.Path );
//..check the archive path's drive properties
ctrl.TestArchiveDriveProperties();
//..create a date/time based folder name for this backup
current = Ctrl.DateFolder( start, Ctrl.DateFolderLevel.Second );
{
//..find the most recent date/time backup history folder
string[] a = ctrl.HistoryFolders();
//..if none exist, invent one for a time 1 second prior to our current folder
history = (a.Length > 0) ? a[a.Length -1] : Ctrl.DateFolder( start.AddSeconds( -1.0 ), Ctrl.DateFolderLevel.Second );
//..make sure the new backup folder is more recent than the last one
if( string.Compare( current, history ) <= 0 )
{
throw new Exception( "Scan: current folder is not newer than history folder" );
}
}
Msg( "History: {0}", history );
Msg( "Current: {0}", current );
current = ctrl.HistoryFullPath( current );
history = ctrl.HistoryFullPath( history );
if( debug )
{
Log( ".s.current folder [{0}]", current );
Log( ".s.history folder [{0}]", history );
}
if( DirectoryExists( history ) )
{
try
{
if( debug ) { Log( ".s.move history to current" ); }
DirectoryMove( history, current );
}
catch( Exception ex )
{
throw new Exception( "Scan: can not rename history folder to current", ex );
}
}
//..check Archive.keep for changes, submit a copy request if changed.
try
{
string n = PathFilename( ctrl.Filename );
FileInfo fi = new FileInfo( ctrl.Filename );
FileInfo ci = new FileInfo( PathCombine( current, n ) );
if( debug ) { Log( ".s.check if control file has been updated [{0}]", fi.FullName ); }
if( ! ci.Exists || ! ctrl.FileDateMatches( fi.LastWriteTimeUtc, ci.LastWriteTimeUtc ) || (fi.Length != ci.Length) )
{
if( debug ) { Log( ".s.control file changed" ); }
FolderInfo fo = new FolderInfo( string.Empty, ctrl.Path );
ScanQueue( ActionType.Copy, fo, string.Empty, n );
}
}
catch( Exception ex )
{
ex.Data[ExCurrentRoot] = current;
ex.Data[ExFilename] = ctrl.Filename;
throw new Exception( "Scan: failed while checking archive control file", ex );
}
CtrlArchive archive = ctrl.Archive;
if( archive != null )
{
bool b = true;
//..backup each folder in archive set
if( debug ) { Log( ".s.build list of existing folders in current" ); }
List<string> a = DirectoryExists( current ) ? Ctrl.ListDirectories( current ) : new List<string>();
if( archive.Folders != null )
{
foreach( CtrlFolder f in archive.Folders )
{
try
{
Scan( f );
ListFilenameRemove( a, f.Name );
}
catch( Exception ex )
{
string s = string.Format( "Scan: {0}", Except.ToString( ex, debug ) );
Msg( s );
b = false;
}
}
}
//..move folders which are no longer part of the backup folder set to history
if( b && ! IsCancelRequested && (a.Count > 0) )
{
if( debug ) { Log( ".s.remove folders from current which are not part of backup set" ); }
foreach( string n in a )
{
if( debug ) { Log( " .s.remove [{0}]", n ); }
FolderInfo f = new FolderInfo( n, null );
Log( string.Empty );
Msg( "Folder: {0}", f.Name );
//..delete/archive folders which are no longer part of the backup set
ScanQueue( ActionType.Delete, f, string.Empty, null );
}
}
}
}
catch( Exception ex )
{
ex.Data[ExArchiveRoot] = ctrl.Path;
ex.Data[ExCurrentRoot] = current;
ex.Data[ExHistoryRoot] = history;
throw;
}
finally
{
status.scan.current = string.Empty;
ctrl.HistoryFolders(); // This is here to make sure our last accessed folder doesn't lock one of the history directories
}
}
void Scan( CtrlFolder folder )
{
try
{
FolderInfo f = new FolderInfo( folder, ctrl.IsCaseSensitive );
Log( string.Empty );
Msg( "Folder: {0} : {1}", f.Name, f.Root );
if( string.IsNullOrEmpty( f.Name ) )
{
throw new Exception( "Folder name is empty." );
}
if( f.Name.IndexOfAny( InvalidFilenameCharacters ) >= 0 )
{
throw new Exception( "Folder name contains invalid characters." );
}
if( string.IsNullOrEmpty( f.Root ) )
{
throw new Exception( "Folder path is empty." );
}
if( f.Root.IndexOfAny( InvalidPathCharacters ) >= 0 )
{
throw new Exception( "Folder path contains invalid characters." );
}
ScanFolder( f, string.Empty );
}
catch( Exception ex )
{
ex.Data[ExArchiveRoot] = ctrl.Path;
ex.Data[ExCurrentRoot] = current;
ex.Data[ExHistoryRoot] = history;
ex.Data[ExFolderName] = folder.Name;
ex.Data[ExFolderRoot] = folder.Path;
throw;
}
}
void ScanFolder( FolderInfo folder, string path )
{
try
{
//..record current location
string s = MatchPath.AbsoluteDirectoryPath( path ?? string.Empty );
status.scan.current = folder.Name + ":" + s;
if( debug ) { Log( ".s.scan path [{0}]", s ); }
Interlocked.Increment( ref status.scan.folders );
//..check if cancelled
if( IsCancelRequested ) { throw new Exception( "Scan cancelled." ); }
if( ! folder.IsIncludedFolder( path ) )
{
if( debug ) { Log( " .s.not included" ); }
return;
}
//..find out if folder path exists
string fp = PathCombine( folder.Root, path );
if( debug ) { Log( ".s.folder path [{0}]", fp ); }
try
{
#if __MonoCS__
{
Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fp );
if( ! i.Exists || ! i.IsDirectory )
{
return;
}
}
#endif
if( ! DirectoryExists( fp ) )
{
throw new DirectoryNotFoundException( "Folder path does not exist." );
}
//..find out if path exists in current
string cp = PathCombine( current, folder.Name, path );
if( debug ) { Log( ".s.current path [{0}]", cp ); }
try
{
if( ! DirectoryExists( cp ) )
{
if( debug ) { Log( ".s.current path absent, copy everything" ); }
//..when the folder does not exist in current, copy everything without comparing
ScanQueue( ActionType.Copy, folder, path, null );
return;
}
List<string> a;
//..scan files first
if( debug ) { Log( ".s.-----> files [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); }
a = new List<string>( Ctrl.ListFiles( cp ) );
foreach( string n in Ctrl.ListFiles( fp ) )
{
try
{
if( IsCancelRequested )
{
throw new Exception( "Scan cancelled." );
}
Interlocked.Increment( ref status.scan.files );
string pn = PathCombine( path, n );
if( debug ) { Log( ".s.file [{0}]", pn ); }
if( folder.IsIncludedFile( pn ) )
{
if( debug ) { Log( ".s.is included" ); }
string fpn = PathCombine( fp, n );
try
{
#if __MonoCS__
Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fpn );
if( i.Exists && i.IsRegularFile )
#endif
{
string cpn = PathCombine( cp, n );
try
{
FileInfo fi = new FileInfo( fpn );
FileInfo ci = new FileInfo( cpn );
if( debug ) { Log( ".s.compare folder file [{0}]\n with current [{1}]", fpn, cpn ); }
if( ! ci.Exists || ! ctrl.FileDateMatches( fi.LastWriteTimeUtc, ci.LastWriteTimeUtc ) || (fi.Length != ci.Length) )
{
if( debug ) { Log( ".s.file has changed" ); }
ScanQueue( ActionType.Copy, folder, path, n );
}
ListFilenameRemove( a, n );
}
catch( Exception ex )
{
ex.Data[ExFolderFilename ] = fpn;
ex.Data[ExCurrentFilename] = cpn;
Log( "Scan {0}", Except.ToString( ex, debug ) );
Interlocked.Increment( ref status.update.skipped );
LogStatus( StatusType.Skipped, folder.Name, path, n );
}
}
}
catch( Exception ex )
{
ex.Data[ExFolderFilename] = fpn;
throw;
}
}
}
catch( Exception ex )
{
ex.Data[ExFilename] = n;
throw;
}
}
if( a.Count > 0 )
{
if( debug ) { Log( ".s.flag deleted files for removal" ); }
foreach( string n in a )
{
if( debug ) { Log( ".s.deleted file [{0}]", n ); }
ScanQueue( ActionType.Delete, folder, path, n );
}
}
//..scan folders second
if( debug ) { Log( ".s.-----> directories [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); }
a = new List<string>( Ctrl.ListDirectories( cp ) );
foreach( string n in Ctrl.ListDirectories( fp ) )
{
if( IsCancelRequested )
{
throw new Exception( "Scan cancelled." );
}
string pn = PathCombine( path, n );
if( debug ) { Log( ".s.directory [{0}]", pn ); }
ScanFolder( folder, pn );
ListFilenameRemove( a, n );
}
if( a.Count > 0 )
{
if( debug ) { Log( ".s.flag deleted directories for removal" ); }
foreach( string n in a )
{
if( debug ) { Log( ".s.deleted directory [{0}]", n ); }
ScanQueue( ActionType.Delete, folder, PathCombine( path, n ), null );
}
}
}
catch( Exception ex )
{
ex.Data[ExCurrentPath] = cp;
throw;
}
}
catch( Exception ex )
{
ex.Data[ExFolderPath] = fp;
throw;
}
}
catch( Exception ex )
{
ex.Data[ExPath] = path;
Msg( "Scan: {0}", Except.ToString( ex, debug ) );
}
}
void ScanQueue( ActionType action, FolderInfo folder, string path, string filename )
{
queue.Add( new UpdateRequest( action, folder, path, filename ), cancel.Token );
}
//--- backup update ---------------------
void UpdateHandler()
{
try
{
Msg( "Update: waiting" );
foreach( UpdateRequest ur in queue.GetConsumingEnumerable( cancel.Token ) )
{
try
{
Update( ur );
}
catch( Exception ex )
{
ex.Data[ExArchiveRoot] = ctrl.Path;
ex.Data[ExCurrentRoot] = current;
ex.Data[ExHistoryRoot] = history;
Msg( "Update: {0}", Except.ToString( ex, debug ) );
}
pause.WaitOne();
}
}
catch( OperationCanceledException ex )
{
Msg( "Update: {0}", Except.ToString( ex, debug ) );
}
catch( Exception ex )
{
Msg( "Update: {0}", Except.ToString( ex, debug ) );
Cancel();
}
finally
{
if( ! string.IsNullOrEmpty( history ) && DirectoryExists( history ) )
{
if( debug ) { Log( ".u.remove empty history folders [{0}]", history ); }
RemoveEmptyHistoryFolder( string.Empty );
}
status.update.current = string.Empty;
Msg( "Update: {0}", (cancel.IsCancellationRequested || ! queue.IsCompleted) ? "cancelled" : "complete" );
}
}
void Update( UpdateRequest ur )
{
try
{
FolderInfo folder = ur.folder;
status.update.current = folder.Name + ":" + MatchPath.AbsoluteDirectoryPath( ur.path ?? string.Empty ) + (ur.filename ?? string.Empty);
if( debug ) { Log( ".u.update operation: {0} [{1}:{2}] [{3}{4}]", ur.action, ur.folder.Name ?? string.Empty, ur.folder.Root ?? string.Empty, MatchPath.AbsoluteDirectoryPath( ur.path ?? string.Empty ), ur.filename ?? string.Empty ); }
string cp = PathCombine( current, folder.Name, ur.path );
string hp = PathCombine( history, folder.Name, ur.path );
if( debug )
{
Log( ".u.current path [{0}]", cp );
Log( ".u.history path [{0}]", hp );
}
try
{
bool bc = Directory.Exists( cp );
if( string.IsNullOrEmpty( ur.filename ) )
{
//..process folder
if( bc )
{
string p = PathDirectory( hp );
if( debug ) { Log( ".u.create history folder" ); }
DirectoryCreate( p );
if( DirectoryExists( hp ) )
{
if( debug ) { Log( ".u.delete history folder" ); }
DirectoryDelete( hp, true );
}
if( debug ) { Log( ".u.move current to history" ); }
DirectoryMove( cp, hp );
}
switch( ur.action )
{
case ActionType.Copy:
{
if( debug ) { Log( ".u.recursive copy [{0}:{1}] path [{2}] to current.", folder.Name, folder.Root, ur.path ); }
RecursiveCopy( folder, ur.path );
break;
}
case ActionType.Delete:
{
if( bc )
{
if( debug ) { Log( ".u.recursive delete history [{0}]", hp ); }
RecursiveDelete( folder, ur.path );
}
break;
}
}
if( bc && ! folder.IsHistoryFolder( ur.path ) )
{
if( debug ) { Log( ".u.delete history folder" ); }
DirectoryDelete( hp, true );
}
}
else
{
//..process file
string cpn = PathCombine( cp, ur.filename );
string hpn = PathCombine( hp, ur.filename );
if( debug ) { Log( ".u.current file [{0}]", cpn ); }
if( debug ) { Log( ".u.history file [{0}]", hpn ); }
try
{
bool bcf = false;
if( bc )
{
bcf = FileExists( cpn );
if( bcf )
{
if( debug ) { Log( ".u.create history folder" ); }
DirectoryCreate( hp );
if( debug ) { Log( " .u.delete history file" ); }
FileDelete( hpn );
if( debug ) { Log( " .u.move current to history" ); }
FileMove( cpn, hpn );
}
}
switch( ur.action )
{
case ActionType.Copy:
{
if( ! bc )
{
if( debug ) { Log( ".u.create current folder" ); }
DirectoryCreate( cp );
}
string n = PathCombine( folder.Root, ur.path, ur.filename );
if( debug ) { Log( " .u.copy file to current" ); }
try
{
FileCopy( n, cpn );
if( bcf )
{
Interlocked.Increment( ref status.update.modified );
LogStatus( StatusType.Modified, folder.Name, ur.path, ur.filename );
}
else
{
Interlocked.Increment( ref status.update.created );
LogStatus( StatusType.Created, folder.Name, ur.path, ur.filename );
}
}
catch( Exception ex )
{
Log( "Update {0}", Except.ToString( ex, debug ) );
Interlocked.Increment( ref status.update.skipped );
LogStatus( StatusType.Skipped, folder.Name, ur.path, ur.filename );
}
break;
}
case ActionType.Delete:
{
if( bcf )
{
Interlocked.Increment( ref status.update.deleted );
LogStatus( StatusType.Deleted, folder.Name, ur.path, ur.filename );
}
break;
}
}
if( bcf && ! folder.IsHistoryFile( PathCombine( ur.path, ur.filename ) ) )
{
if( debug ) { Log( ".u.delete history" ); }
FileDelete( hpn );
}
}
catch( Exception ex )
{
ex.Data[ExCurrentFilename] = cpn;
ex.Data[ExHistoryFilename] = hpn;
throw;
}
}
}
catch( Exception ex )
{
ex.Data[ExCurrentPath] = cp;
ex.Data[ExHistoryPath] = hp;
throw;
}
}
catch( Exception ex )
{
if( ur.action != ActionType.None )
{
ex.Data[ExUpdateAction] = ur.action;
ex.Data[ExUpdatePath] = ur.path;
ex.Data[ExUpdateFilename] = ur.filename;
if( ur.folder != null )
{
ex.Data[ExFolderName] = ur.folder.Name;
ex.Data[ExFolderRoot] = ur.folder.Root;
}
}
throw;
}
}
void RemoveEmptyHistoryFolder( string path )
{
try
{
if( debug ) { Log( ".u.check folder [{0}]", path ); }
string fp = PathCombine( history, path );
foreach( string s in Ctrl.ListDirectories( fp ) )
{
RemoveEmptyHistoryFolder( PathCombine( path, s ) );
}
DirectoryInfo di = new DirectoryInfo( fp );
if( di.GetFileSystemInfos().Length <= 0 )
{
if( debug ) { Log( ".u.folder [{0}] is empty", path ); }
di.Delete();
}
}
catch( Exception ex )
{
ex.Data[ExHistoryRoot] = history;
ex.Data[ExPath] = path;
Msg( "Update: remove empty folders: {0}", Except.ToString( ex, debug ) );
}
}
void RecursiveCopy( FolderInfo folder, string path )
{
try
{
string s = folder.Name + ":" + MatchPath.AbsoluteDirectoryPath( path ?? string.Empty );
status.update.current = s;
if( debug ) { Log( ".u.recursive copy [{0}]", s ); }
//..check if cancelled
if( IsCancelRequested )
{
throw new Exception( "Update cancelled." );
}
if( ! folder.IsIncludedFolder( path ) )
{
if( debug ) { Log( ".u.not included", path ); }
return;
}
string fp = PathCombine( folder.Root, path );
if( debug ) { Log( ".u.folder path [{0}]", fp ); }
try
{
#if __MonoCS__
{
Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fp );
if( ! i.Exists || ! i.IsDirectory )
{
return;
}
}
#endif
if( ! DirectoryExists( fp ) )
{
throw new Exception( "Folder path does not exist." );
}
string cp = PathCombine( current, folder.Name, path );
if( debug ) { Log( ".u.current path [{0}]", cp ); }
try
{
if( debug ) { Log( ".u.create current directory" ); }
DirectoryCreate( cp );