forked from YuraAka/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.cs
889 lines (749 loc) · 30.8 KB
/
core.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
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Security;
using WinSCP;
namespace Core {
using EventPool = List<FileSystemEventArgs>;
using Timer = System.Timers.Timer;
using Changes = WatcherChangeTypes;
using TransmitResult = OperationResultBase;
using System.Threading.Tasks;
public delegate bool Predicate();
class Utils {
public static bool IsDirectory(string path) {
var attrs = TryAttrs(path);
return attrs.HasValue
&& (attrs.Value & FileAttributes.Directory) == FileAttributes.Directory;
}
private static FileAttributes? TryAttrs(string path) {
try {
return File.GetAttributes(path);
} catch (DirectoryNotFoundException) {
return null;
} catch (FileNotFoundException) {
return null;
}
}
public static string ToBashPath(string path) {
var parts = path.Split(':');
return "/mnt/" + parts[0].ToLower() + parts[1].Replace('\\', '/');
}
public static string TryBashExePath() {
string path = @"C:\Windows\sysnative\bash.exe";
if (File.Exists(path)) {
return path;
}
return "";
}
}
interface ILogger {
void Debug(string format, params object[] arg);
void Info(string format, params object[] arg);
void Error(string format, params object[] arg);
};
class CompoundLogger : ILogger {
public ILogger[] Logs { get; set; }
public virtual void Debug(string format, params object[] arg) {
foreach (var log in Logs) {
log.Debug(format, arg);
}
}
public virtual void Info(string format, params object[] arg) {
foreach (var log in Logs) {
log.Info(format, arg);
}
}
public virtual void Error(string format, params object[] arg) {
foreach (var log in Logs) {
log.Error(format, arg);
}
}
}
class EventLogger : ILogger {
private EventLog Log;
public EventLogger() {
try {
if (!EventLog.SourceExists("YSync")) {
EventLog.CreateEventSource("YSync", "YSync");
}
Log = new EventLog("YSync") {
Source = "YSync"
};
} catch (SecurityException) {
Console.WriteLine("ERR: Cannot create event log. Please, run once with administrative priviledges.");
}
}
public virtual void Debug(string format, params object[] arg) {
if (Log != null) {
Log.WriteEntry(String.Format(format, arg), EventLogEntryType.Information, 300, 3);
}
}
public virtual void Info(string format, params object[] arg) {
if (Log != null) {
Log.WriteEntry(String.Format(format, arg), EventLogEntryType.Information, 200, 2);
}
}
public virtual void Error(string format, params object[] arg) {
if (Log != null) {
Log.WriteEntry(String.Format(format, arg), EventLogEntryType.Error, 100, 1);
}
}
}
class ConsoleLogger : ILogger {
public int Verbosity { get; set; } = 0;
public virtual void Debug(string format, params object[] arg) {
if (Verbosity >= 2) {
Console.WriteLine("DBG: " + format, arg);
}
}
public virtual void Info(string format, params object[] arg) {
if (Verbosity >= 1) {
Console.WriteLine("INF: " + format, arg);
}
}
public virtual void Error(string format, params object[] arg) {
Console.WriteLine("ERR: " + format, arg);
}
};
class ChangesMonitor {
private EventPool Events = new EventPool();
private Timer Quantifier;
private ILogger Log;
private FileSystemWatcher Watcher;
private Predicate IsCancel;
private bool FirstChangeInSeries = false;
public string SourcePath { get; set; }
public HashSet<string> Excludes { get; set; }
public event Action OnWait = new Action(() => {});
public event Action OnChangesCollect = new Action(() => { });
public ChangesMonitor(ILogger log) {
Log = log;
Quantifier = new Timer() {
AutoReset = true,
Interval = 100
};
Quantifier.Elapsed += Flush;
}
public void TurnOn() {
IsCancel = null;
Watcher = CreateWatcher();
Log.Info("Ready to monitor filesystem.");
}
public EventPool Wait(Predicate cancelPoller) {
IsCancel = cancelPoller;
EventPool result;
lock (Events) {
if (Events.Count == 0) {
Log.Info("Waiting for changes...");
OnWait();
Monitor.Wait(Events);
FirstChangeInSeries = true;
}
if (IsCancel()) {
return null;
}
result = Events;
Events = new EventPool();
}
return result;
}
private FileSystemWatcher CreateWatcher() {
var watcher = new FileSystemWatcher {
Path = SourcePath,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
InternalBufferSize = 64 * 1024
};
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
return watcher;
}
private void Flush(Object source, System.Timers.ElapsedEventArgs ev) {
lock (Events) {
if (Events.Count > 0 || IsCancel()) {
Monitor.Pulse(Events);
}
}
}
private void OnChanged(object source, FileSystemEventArgs ev) {
Quantifier.Enabled = false;
Quantifier.Enabled = true;
if (TrySkip(ev)) {
return;
}
if (FirstChangeInSeries) {
OnChangesCollect();
FirstChangeInSeries = false;
}
ev = Transform(ev);
lock (Events) {
Events.Add(ev);
if (TryCommitNew(ev)) {
return;
}
if (!TryReduce(ev)) {
Log.Debug("IN: Added, no rule applied: {0}", ev.FullPath);
LogEventsNoLock();
}
}
}
private FileSystemEventArgs Transform(FileSystemEventArgs ev) {
if (ev.ChangeType == Changes.Renamed) {
RenamedEventArgs re = (RenamedEventArgs)ev;
if (re.OldFullPath.Contains("~")) {
ev = new FileSystemEventArgs(Changes.Changed, SourcePath, re.Name);
Log.Debug("IN: Refactor rename to update: {0}", ev.FullPath);
}
}
return ev;
}
private bool TrySkip(FileSystemEventArgs ev) {
if (ev.FullPath.Contains("~")) {
Log.Debug("IN: Skip tilda: {0}", ev.FullPath);
return true;
}
/// todo regexp
foreach (var part in ev.FullPath.Split(Path.DirectorySeparatorChar)) {
if (Excludes.Contains(part)) {
Log.Debug("IN: Skip exclusion: {0}", ev.FullPath);
return true;
}
}
if (ev.ChangeType == Changes.Changed) {
if (Utils.IsDirectory(ev.FullPath)) {
Log.Debug("IN: Skip directory update: {0}", ev.FullPath);
return true;
}
}
return false;
}
private bool TryCommitNew(FileSystemEventArgs ev) {
if (Events.Count == 0) {
Log.Debug("IN: Add first event: {0}", ev.FullPath);
LogEventsNoLock();
return true;
}
var last = Events[Events.Count - 1];
if (last.FullPath != ev.FullPath) {
Log.Debug("IN: Add different events: {0} => {1}", last.FullPath, ev.FullPath);
LogEventsNoLock();
return true;
}
return false;
}
private bool TryReduce(FileSystemEventArgs ev) {
bool applied = false;
var curIdx = Events.Count - 1;
var prevIdx = Events.Count - 2;
while (Events.Count > 1 && Events[prevIdx].FullPath == Events[curIdx].FullPath) {
var prev = Events[prevIdx];
var cur = Events[curIdx];
if (prev.ChangeType == cur.ChangeType) {
Log.Debug("IN: Skip duplicate: {0} => {1}", prev.FullPath, cur.FullPath);
} else if (prev.ChangeType == Changes.Deleted && cur.ChangeType != Changes.Deleted) {
Log.Debug("IN: Rewrite deletion for update: {0} => {1}", prev.FullPath, cur.FullPath);
} else if ((prev.ChangeType & (Changes.Changed | Changes.Created)) != 0) {
if (cur.ChangeType == Changes.Renamed) {
Log.Debug("IN: Rewrite rename for update: {0} => {1}", prev.FullPath, cur.FullPath);
} else if ((cur.ChangeType & (Changes.Changed | Changes.Created)) != 0) {
Log.Debug("IN: Rewrite create for update: {0} => {1}", prev.FullPath, cur.FullPath);
}
} else if (prev.ChangeType != Changes.Deleted && cur.ChangeType == Changes.Deleted) {
Log.Debug("IN: Rewrite update for deletion: {0} => {1}", prev.FullPath, cur.FullPath);
} else {
return false;
}
applied = true;
Events[prevIdx] = Events[curIdx];
Events.RemoveAt(curIdx);
LogEventsNoLock();
if (prevIdx == 0) {
return true;
}
--prevIdx;
--curIdx;
}
return applied;
}
private void LogEventsNoLock() {
var stream = new StringWriter();
stream.Write("Events: ");
foreach (var ev in Events) {
stream.Write(ev.ChangeType.ToString()[0]);
}
stream.Write("\n");
Log.Debug(stream.ToString());
}
};
class ChangesTransmitter {
private Session Session = new Session();
private ILogger Log;
private EventPool LostLifeChanges = new EventPool();
private string BashSourcePath { set; get; }
private string BashExePath { set; get; }
private string SourcePath { set; get; }
private Predicate IsCancel;
public string Host { set; get; }
public string User { set; get; }
public string PrivateKey { set; get; }
public string Passphrase { set; get; }
public string DestinationPath { set; get; }
public bool DryRun { set; get; }
public TimeSpan Timeout { set; get; } = TimeSpan.FromSeconds(30);
public HashSet<string> Excludes { set; get; }
public event Action OnSessionClose = new Action(() => { });
public event Action OnSessionOpen = new Action(() => { });
public event Action OnChangesStart = new Action(() => { });
public event Action OnChangesFinish = new Action(() => { });
public ChangesTransmitter(ILogger log) {
Log = log;
Session.ReconnectTime = TimeSpan.MaxValue;
UnpackWinSCP();
}
public void Stop() {
Session.Abort();
}
public void Resync(string sourcePath) {
SourcePath = sourcePath;
BashSourcePath = Utils.ToBashPath(SourcePath);
BashExePath = Utils.TryBashExePath();
RunBatchTransfer(SourcePath);
}
public void WaitChanges(ChangesMonitor source, Predicate cancelPoller) {
SourcePath = source.SourcePath;
BashSourcePath = Utils.ToBashPath(SourcePath);
BashExePath = Utils.TryBashExePath();
var sessionOptions = CreateSessionOptions();
var transferOptions = CreateTransferOptions();
Session.Timeout = Timeout;
IsCancel = cancelPoller;
while (!IsCancel()) {
try {
OpenSession(sessionOptions);
while (!IsCancel()) {
var changes = RetrieveChanges(source);
OnChangesStart();
if (changes == null) {
return;
}
TransferAll(changes, transferOptions);
OnChangesFinish();
}
} catch (SessionRemoteException err) {
Log.Error("Remote failure: {0}", err);
} catch (TimeoutException) {
Log.Error("Session timeout. Retryng to connect...");
} catch (InvalidOperationException err) {
Log.Error("Remote failure: {0}", err);
} catch (SessionLocalException err) {
Log.Error("Local failure: {0}", err);
} catch (Exception err) {
Log.Error("UNKNOWN EXCEPTION: {0}. Yury, you MUST fix it!", err);
if (LostLifeChanges.Count > 0) {
var first = LostLifeChanges[0];
Log.Debug("Skip problem change: {0} {1}", first.ChangeType, first.FullPath);
LostLifeChanges.RemoveAt(0);
}
Thread.Sleep(1000);
} finally {
CloseSession();
}
}
}
private void OpenSession(SessionOptions options) {
if (DryRun) {
Log.Info("Fake session open");
return;
}
if (options.SshHostKeyFingerprint == null) {
options.SshHostKeyFingerprint = Session.ScanFingerprint(options);
}
if (!Session.Opened) {
Session.Open(options);
OnSessionOpen();
Log.Info("Ready to transmit changes.");
}
}
private void UnpackWinSCP() {
string executableName = "WinSCP.exe";
string executablePath = Path.Combine(Directory.GetCurrentDirectory(), executableName);
if (File.Exists(executablePath)) {
Log.Debug("Using existing winscp {0}", executablePath);
return;
}
try {
Assembly executingAssembly = Assembly.GetExecutingAssembly();
/// todo: potential bug here: we must use namespace name, not assembly name
string resourceName = executingAssembly.GetName().Name + "." + "WinSCP.exe";
using (Stream resource = executingAssembly.GetManifestResourceStream(resourceName))
using (Stream file = new FileStream(executablePath, FileMode.Create, FileAccess.Write)) {
resource.CopyTo(file);
}
} catch (Exception) {
File.Delete(executablePath);
throw;
}
Log.Debug("Unpack winscp {0}", executablePath);
}
private SessionOptions CreateSessionOptions() {
return new SessionOptions {
HostName = Host,
UserName = User,
SshPrivateKeyPath = PrivateKey,
PrivateKeyPassphrase = Passphrase,
Protocol = Protocol.Scp
};
}
private TransferOptions CreateTransferOptions() {
return new TransferOptions {
TransferMode = TransferMode.Binary,
ResumeSupport = new TransferResumeSupport {
State = TransferResumeSupportState.Smart,
Threshold = 4 * 1024
}
};
}
private bool RunBatchTransfer(string root) {
if (BashExePath.Length == 0) {
Log.Info("No bash found in system. Load optimization is disabled");
return false;
}
string localPath = BashSourcePath + "/" + root;
string remotePath = string.Format("{0}:{1}", Host, DestinationPath + "/" + root);
Process pProcess = new Process();
pProcess.StartInfo.FileName = BashExePath;
string excludes = "";
if (Excludes != null) {
foreach (var exclude in Excludes) {
excludes += string.Format("--exclude '{0}' ", exclude);
}
}
string cmd = string.Format("-c \"rsync {0} {1} -a {2} --delete -v\"", localPath, remotePath, excludes);
pProcess.StartInfo.Arguments = cmd;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.RedirectStandardError = true;
pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pProcess.StartInfo.CreateNoWindow = true;
Log.Info("Rsync run: {0} {1}", pProcess.StartInfo.FileName, pProcess.StartInfo.Arguments);
if (!DryRun) {
/// TODO support cancelation: kill in another thread
pProcess.Start();
pProcess.WaitForExit();
Log.Debug("Rsync stdout: {0}", pProcess.StandardOutput.ReadToEnd());
Log.Debug("Rsync stderr: {0}", pProcess.StandardError.ReadToEnd());
}
return true;
}
private HashSet<string> GetChangedRoots(EventPool changes) {
// TODO: get all changes, convert to tree and separate several biggest subtrees,
// then sync only roots with rsync
var result = new HashSet<string>();
foreach (var change in changes) {
var relativePath = change.FullPath.Substring(SourcePath.Length);
var parts = relativePath.Split(
Path.DirectorySeparatorChar.ToString().ToCharArray(),
options: StringSplitOptions.RemoveEmptyEntries
);
var root = parts.Length == 1 ? "" : parts[0] + "/";
result.Add(root);
}
return result;
}
private bool TryBatchTransfer(EventPool changes) {
// TODO: tune threshold for optimal speed
if (true || changes.Count < 100) {
// TODO: run batch sync on the end: measure speed of changes
return false;
}
Log.Info("To many changes. Need to fallback to batch method");
foreach (var root in GetChangedRoots(changes)) {
if (IsCancel()) {
return true;
}
if (!RunBatchTransfer(root)) {
return false;
}
}
return true;
}
private void TransferAll(EventPool changes, TransferOptions options) {
if (TryBatchTransfer(changes)) {
return;
}
Exception lostLifeError = null;
foreach (var change in changes) {
if (IsCancel()) {
return;
}
if (lostLifeError != null) {
LostLifeChanges.Add(change);
continue;
}
try {
TransferOne(change, options);
} catch (SessionRemoteException err) {
Log.Error("Skip change {0} {1} due to {2}", change.ChangeType, change.FullPath, err);
} catch (Exception err) {
Log.Error("Emergency changes save started due to error: {0}", err);
lostLifeError = err;
LostLifeChanges.Add(change);
}
}
if (lostLifeError != null) {
throw lostLifeError;
}
}
private void TransferOne(FileSystemEventArgs change, TransferOptions options) {
if (DryRun) {
Log.Info("Fake transfer " + change.FullPath);
return;
}
change = Transform(change);
if (change == null) {
return;
}
Log.Debug("Transfer change {0} {1}", change.ChangeType, change.FullPath);
switch (change.ChangeType) {
case Changes.Changed:
case Changes.Created:
Update(change.FullPath, options);
break;
case Changes.Deleted:
Delete(change.FullPath);
break;
case Changes.Renamed:
Rename(GetOldPath(change), change.FullPath);
break;
}
}
private string GetOldPath(FileSystemEventArgs change) {
if (change.ChangeType != Changes.Renamed) {
throw new InvalidOperationException("Change is not a rename change");
}
var rename = (RenamedEventArgs)change;
return rename.OldFullPath;
}
private void CreateDirWithParents(string dirPath) {
string relativePath = dirPath.Substring(SourcePath.Length);
var separator = new[] { Path.DirectorySeparatorChar };
var subdirs = relativePath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string readyPath = string.Copy(SourcePath);
foreach (var subdir in subdirs) {
readyPath = Path.Combine(readyPath, subdir) + Path.DirectorySeparatorChar;
var remotePath = AsRemotePath(readyPath);
if (!Session.FileExists(remotePath)) {
Session.CreateDirectory(remotePath);
}
}
}
private void Update(string path, TransferOptions options) {
bool isDir = Utils.IsDirectory(path);
try {
if (isDir) {
UpdateDirectory(path);
} else {
UpdateFile(path, options);
}
} catch (SessionRemoteException err) {
var remotePath = AsRemotePath(path);
Log.Debug("Update {0} failed: {1}", remotePath, err);
var localParentDir = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar;
var remoteParentDir = AsRemotePath(localParentDir);
if (Session.FileExists(remoteParentDir)) {
throw;
}
CreateDirWithParents(localParentDir);
Log.Debug("Retrying after parents creation");
Update(path, options);
}
}
private void UpdateFile(string localPath, TransferOptions options) {
var remotePath = AsRemotePath(localPath);
Session.PutFiles(localPath, remotePath, false, options).Check();
Log.Info("Upload {0} to {1}", localPath, remotePath);
}
private void UpdateDirectory(string localPath) {
var remotePath = AsRemotePath(localPath);
if (Session.FileExists(remotePath)) {
Log.Debug("Remove existing directory {0}", remotePath);
Session.RemoveFiles(remotePath).Check();
}
Session.CreateDirectory(remotePath);
Log.Info("Create directory {0}", remotePath);
}
private void Delete(string localPath) {
var remotePath = AsRemotePath(localPath);
if (Session.FileExists(remotePath)) {
Session.RemoveFiles(remotePath).Check();
Log.Info("Remove {0}", remotePath);
}
}
private void Rename(string fromPath, string toPath) {
if (Utils.IsDirectory(toPath)) {
Delete(toPath);
}
var fromRemotePath = AsRemotePath(fromPath);
var toRemotePath = AsRemotePath(toPath);
Session.MoveFile(fromRemotePath, toRemotePath);
Log.Info("Rename from {0} to {1}", fromRemotePath, toRemotePath);
}
private void LogResult(TransmitResult result) {
if (result.IsSuccess) {
return;
}
StringWriter msg = new StringWriter();
msg.Write("Operation has failed. Suberrors: \n");
foreach (var fail in result.Failures) {
msg.Write("* Error {0}\n", fail);
}
Log.Error(msg.ToString());
}
private FileSystemEventArgs Transform(FileSystemEventArgs change) {
bool exist = File.Exists(change.FullPath) || Directory.Exists(change.FullPath);
if (change.ChangeType == Changes.Deleted && exist) {
Log.Debug("Transform deletion to update {0} due to file exist", change.FullPath);
return new FileSystemEventArgs(Changes.Changed, SourcePath, change.Name);
}
if (change.ChangeType == Changes.Deleted) {
return change;
}
if (!exist) {
Log.Debug("Skip update nonexisting {0} of file {1}", change.ChangeType, change.FullPath);
return null;
}
if (change.ChangeType != Changes.Renamed) {
return change;
}
var rename = (RenamedEventArgs)change;
var remoteOldPath = AsRemotePath(rename.OldFullPath);
if (!Session.FileExists(remoteOldPath)) {
Log.Debug("Transform rename to update {0} due to file does not exist", remoteOldPath);
return new FileSystemEventArgs(Changes.Changed, SourcePath, change.Name);
}
return change;
}
private EventPool RetrieveChanges(ChangesMonitor source) {
if (LostLifeChanges.Count == 0) {
return source.Wait(IsCancel);
}
// we failed last time and there are unprocessed changes
var changes = new EventPool(LostLifeChanges);
LostLifeChanges.Clear();
return changes;
}
private void CloseSession() {
if (DryRun) {
Log.Info("Fake session close");
return;
}
if (Session.Opened) {
OnSessionClose();
Session.Close();
}
}
private string AsRemotePath(string path) {
return Session.TranslateLocalPathToRemote(path, SourcePath, DestinationPath);
}
}
class InteractiveFileChangesSync {
public string User { get; set; }
public string SourcePath { get; set; }
public string DestinationPath { get; set; }
public string Host { get; set; }
public string PrivateKey { get; set; }
public string Passphrase { get; set; }
public HashSet<string> Excludes { get; set; }
public event Action OnChangesProcessed = new Action(() => { });
public event Action OnChangesWait = new Action(() => { });
public event Action OnStop = new Action(() => { });
public void Start(Predicate cancelPoller) {
OnChangesWait();
ILogger logger = new EventLogger();
/// add delegates
ChangesMonitor monitor = new ChangesMonitor(logger) {
SourcePath = SourcePath,
Excludes = Excludes,
};
ChangesTransmitter transmitter = new ChangesTransmitter(logger) {
Host = Host,
User = User,
PrivateKey = PrivateKey,
Passphrase = Passphrase,
DestinationPath = DestinationPath,
Excludes = Excludes,
};
monitor.OnChangesCollect += OnChangesProcessed;
monitor.OnWait += OnChangesWait;
monitor.TurnOn();
var cancelListen = new Task(new Action(() => {
while (!cancelPoller()) {
Thread.Sleep(1000);
}
//monitor.TurnOff();
transmitter.Stop();
}));
cancelListen.Start();
transmitter.WaitChanges(monitor, cancelPoller);
OnStop();
logger.Info("Stopping...");
}
public void Resync() {
ILogger logger = new EventLogger();
ChangesTransmitter transmitter = new ChangesTransmitter(logger) {
Host = Host,
User = User,
PrivateKey = PrivateKey,
Passphrase = Passphrase,
DestinationPath = DestinationPath,
Excludes = Excludes,
};
transmitter.Resync(SourcePath);
OnStop();
logger.Info("Resync stopping...");
}
}
class SimpleFileChangesSync {
public string User { get; set; }
public string SourcePath { get; set; }
public string DestinationPath { get; set; }
public string Host { get; set; }
public string PrivateKey { get; set; }
public string Passphrase { get; set; }
public int Verbosity { get; set; }
public HashSet<string> Excludes { get; set; }
public bool DryRun { get; set; }
public void Run() {
ILogger logger = new CompoundLogger() {
Logs = new ILogger[] {
new EventLogger(),
new ConsoleLogger() {
Verbosity = Verbosity
}
}
};
ChangesMonitor monitor = new ChangesMonitor(logger) {
SourcePath = SourcePath,
Excludes = Excludes
};
ChangesTransmitter transmitter = new ChangesTransmitter(logger) {
Host = Host,
User = User,
PrivateKey = PrivateKey,
Passphrase = Passphrase,
DestinationPath = DestinationPath,
DryRun = DryRun,
Excludes = Excludes,
};
monitor.TurnOn();
transmitter.WaitChanges(monitor, () => false);
}
}
}