-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMutagenController.cs
739 lines (652 loc) · 25.7 KB
/
MutagenController.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
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Coder.Desktop.App.Models;
using Coder.Desktop.MutagenSdk;
using Coder.Desktop.MutagenSdk.Proto.Selection;
using Coder.Desktop.MutagenSdk.Proto.Service.Daemon;
using Coder.Desktop.MutagenSdk.Proto.Service.Prompting;
using Coder.Desktop.MutagenSdk.Proto.Service.Synchronization;
using Coder.Desktop.MutagenSdk.Proto.Synchronization;
using Coder.Desktop.MutagenSdk.Proto.Url;
using Coder.Desktop.Vpn.Utilities;
using Grpc.Core;
using Microsoft.Extensions.Options;
using DaemonTerminateRequest = Coder.Desktop.MutagenSdk.Proto.Service.Daemon.TerminateRequest;
using MutagenProtocol = Coder.Desktop.MutagenSdk.Proto.Url.Protocol;
using SynchronizationTerminateRequest = Coder.Desktop.MutagenSdk.Proto.Service.Synchronization.TerminateRequest;
namespace Coder.Desktop.App.Services;
public class CreateSyncSessionRequest
{
public required Endpoint Alpha { get; init; }
public required Endpoint Beta { get; init; }
public class Endpoint
{
public enum ProtocolKind
{
Local,
Ssh,
}
public required ProtocolKind Protocol { get; init; }
public string User { get; init; } = "";
public string Host { get; init; } = "";
public uint Port { get; init; } = 0;
public string Path { get; init; } = "";
public URL MutagenUrl
{
get
{
var protocol = Protocol switch
{
ProtocolKind.Local => MutagenProtocol.Local,
ProtocolKind.Ssh => MutagenProtocol.Ssh,
_ => throw new ArgumentException($"Invalid protocol '{Protocol}'", nameof(Protocol)),
};
return new URL
{
Kind = Kind.Synchronization,
Protocol = protocol,
User = User,
Host = Host,
Port = Port,
Path = Path,
};
}
}
}
}
public interface ISyncSessionController : IAsyncDisposable
{
public event EventHandler<SyncSessionControllerStateModel> StateChanged;
/// <summary>
/// Gets the current state of the controller.
/// </summary>
SyncSessionControllerStateModel GetState();
// All the following methods will raise a StateChanged event *BEFORE* they return.
/// <summary>
/// Starts the daemon (if it's not running) and fully refreshes the state of the controller. This should be
/// called at startup and after any unexpected daemon crashes to attempt to retry.
/// Additionally, the first call to RefreshState will start a background task to keep the state up-to-date while
/// the daemon is running.
/// </summary>
Task<SyncSessionControllerStateModel> RefreshState(CancellationToken ct = default);
Task<SyncSessionModel> CreateSyncSession(CreateSyncSessionRequest req, Action<string> progressCallback, CancellationToken ct = default);
Task<SyncSessionModel> PauseSyncSession(string identifier, CancellationToken ct = default);
Task<SyncSessionModel> ResumeSyncSession(string identifier, CancellationToken ct = default);
Task TerminateSyncSession(string identifier, CancellationToken ct = default);
}
// These values are the config option names used in the registry. Any option
// here can be configured with `(Debug)?AppMutagenController:OptionName` in the registry.
//
// They should not be changed without backwards compatibility considerations.
// If changed here, they should also be changed in the installer.
public class MutagenControllerConfig
{
// This is set to "[INSTALLFOLDER]\vpn\mutagen.exe" by the installer.
[Required] public string MutagenExecutablePath { get; set; } = @"c:\mutagen.exe";
}
/// <summary>
/// A file synchronization controller based on the Mutagen Daemon.
/// </summary>
public sealed class MutagenController : ISyncSessionController
{
// Protects all private non-readonly class members.
private readonly RaiiSemaphoreSlim _lock = new(1, 1);
private readonly CancellationTokenSource _stateUpdateCts = new();
private Task? _stateUpdateTask;
// _state is the current state of the controller. It is updated
// continuously while the daemon is running and after most operations.
private SyncSessionControllerStateModel? _state;
// _daemonProcess is non-null while the daemon is running, starting, or
// in the process of stopping.
private Process? _daemonProcess;
private LogWriter? _logWriter;
// holds a client connected to the running mutagen daemon, if the daemon is running.
private MutagenClient? _mutagenClient;
// set to true if we are disposing the controller. Prevents the daemon from being
// restarted.
private bool _disposing;
private readonly string _mutagenExecutablePath;
private readonly string _mutagenDataDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CoderDesktop",
"mutagen");
private string MutagenDaemonLog => Path.Combine(_mutagenDataDirectory, "daemon.log");
public MutagenController(IOptions<MutagenControllerConfig> config)
{
_mutagenExecutablePath = config.Value.MutagenExecutablePath;
}
public MutagenController(string executablePath, string dataDirectory)
{
_mutagenExecutablePath = executablePath;
_mutagenDataDirectory = dataDirectory;
}
public event EventHandler<SyncSessionControllerStateModel>? StateChanged;
public async ValueTask DisposeAsync()
{
using var _ = await _lock.LockAsync(CancellationToken.None);
_disposing = true;
await _stateUpdateCts.CancelAsync();
if (_stateUpdateTask != null)
try
{
await _stateUpdateTask;
}
catch
{
// ignored
}
_stateUpdateCts.Dispose();
using var stopCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await StopDaemon(stopCts.Token);
GC.SuppressFinalize(this);
}
public SyncSessionControllerStateModel GetState()
{
// No lock required to read the reference.
var state = _state;
// No clone needed as the model is immutable.
if (state != null) return state;
return new SyncSessionControllerStateModel
{
Lifecycle = SyncSessionControllerLifecycle.Uninitialized,
DaemonError = null,
DaemonLogFilePath = MutagenDaemonLog,
SyncSessions = [],
};
}
public async Task<SyncSessionControllerStateModel> RefreshState(CancellationToken ct = default)
{
using var _ = await _lock.LockAsync(ct);
var client = await EnsureDaemon(ct);
var state = await UpdateState(client, ct);
_stateUpdateTask ??= UpdateLoop(_stateUpdateCts.Token);
return state;
}
public async Task<SyncSessionModel> CreateSyncSession(CreateSyncSessionRequest req, Action<string>? progressCallback = null, CancellationToken ct = default)
{
using var _ = await _lock.LockAsync(ct);
var client = await EnsureDaemon(ct);
await using var prompter = await Prompter.Create(client, true, ct);
if (progressCallback != null)
prompter.OnProgress += (_, progress) => progressCallback(progress);
var createRes = await client.Synchronization.CreateAsync(new CreateRequest
{
Prompter = prompter.Identifier,
Specification = new CreationSpecification
{
Alpha = req.Alpha.MutagenUrl,
Beta = req.Beta.MutagenUrl,
// TODO: probably should set these at some point
Configuration = new Configuration(),
ConfigurationAlpha = new Configuration(),
ConfigurationBeta = new Configuration(),
},
}, cancellationToken: ct);
if (createRes == null) throw new InvalidOperationException("CreateAsync returned null");
var session = await GetSyncSession(client, createRes.Session, ct);
await UpdateState(client, ct);
return session;
}
public async Task<SyncSessionModel> PauseSyncSession(string identifier, CancellationToken ct = default)
{
using var _ = await _lock.LockAsync(ct);
var client = await EnsureDaemon(ct);
// Pausing sessions doesn't require prompting as seen in the mutagen CLI.
await using var prompter = await Prompter.Create(client, false, ct);
await client.Synchronization.PauseAsync(new PauseRequest
{
Prompter = prompter.Identifier,
Selection = new Selection
{
Specifications = { identifier },
},
}, cancellationToken: ct);
var session = await GetSyncSession(client, identifier, ct);
await UpdateState(client, ct);
return session;
}
public async Task<SyncSessionModel> ResumeSyncSession(string identifier, CancellationToken ct = default)
{
using var _ = await _lock.LockAsync(ct);
var client = await EnsureDaemon(ct);
await using var prompter = await Prompter.Create(client, true, ct);
await client.Synchronization.ResumeAsync(new ResumeRequest
{
Prompter = prompter.Identifier,
Selection = new Selection
{
Specifications = { identifier },
},
}, cancellationToken: ct);
var session = await GetSyncSession(client, identifier, ct);
await UpdateState(client, ct);
return session;
}
public async Task TerminateSyncSession(string identifier, CancellationToken ct = default)
{
using var _ = await _lock.LockAsync(ct);
var client = await EnsureDaemon(ct);
// Terminating sessions doesn't require prompting as seen in the mutagen CLI.
await using var prompter = await Prompter.Create(client, true, ct);
await client.Synchronization.TerminateAsync(new SynchronizationTerminateRequest
{
Prompter = prompter.Identifier,
Selection = new Selection
{
Specifications = { identifier },
},
}, cancellationToken: ct);
await UpdateState(client, ct);
}
private async Task UpdateLoop(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(2), ct); // 2s matches macOS app
try
{
// We use a zero timeout here to avoid waiting. If another
// operation is holding the lock, it will update the state once
// it completes anyway.
var locker = await _lock.LockAsync(TimeSpan.Zero, ct);
if (locker == null) continue;
using (locker)
{
if (_mutagenClient == null) continue;
await UpdateState(_mutagenClient, ct);
}
}
catch
{
// ignore
}
}
}
private static async Task<SyncSessionModel> GetSyncSession(MutagenClient client, string identifier,
CancellationToken ct)
{
var listRes = await client.Synchronization.ListAsync(new ListRequest
{
Selection = new Selection
{
Specifications = { identifier },
},
}, cancellationToken: ct);
if (listRes == null) throw new InvalidOperationException("ListAsync returned null");
if (listRes.SessionStates.Count != 1)
throw new InvalidOperationException("ListAsync returned wrong number of sessions");
return new SyncSessionModel(listRes.SessionStates[0]);
}
private void ReplaceState(SyncSessionControllerStateModel state)
{
_state = state;
// Since the event handlers could block (or call back the
// SyncSessionController and deadlock), we run these in a new task.
var stateChanged = StateChanged;
if (stateChanged == null) return;
Task.Run(() => stateChanged.Invoke(this, state));
}
/// <summary>
/// Refreshes state and potentially stops the daemon if there are no sessions. The client must not be used after
/// this method is called.
/// Must be called AND awaited with the lock held.
/// </summary>
private async Task<SyncSessionControllerStateModel> UpdateState(MutagenClient client,
CancellationToken ct = default)
{
ListResponse listResponse;
try
{
listResponse = await client.Synchronization.ListAsync(new ListRequest
{
Selection = new Selection { All = true },
}, cancellationToken: ct);
if (listResponse == null)
throw new InvalidOperationException("ListAsync returned null");
}
catch (Exception e)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var error = $"Failed to UpdateState: ListAsync: {e}";
try
{
await StopDaemon(cts.Token);
}
catch (Exception e2)
{
error = $"Failed to UpdateState: StopDaemon failed after failed ListAsync call: {e2}";
}
ReplaceState(new SyncSessionControllerStateModel
{
Lifecycle = SyncSessionControllerLifecycle.Stopped,
DaemonError = error,
DaemonLogFilePath = MutagenDaemonLog,
SyncSessions = [],
});
throw;
}
var lifecycle = SyncSessionControllerLifecycle.Running;
if (listResponse.SessionStates.Count == 0)
{
lifecycle = SyncSessionControllerLifecycle.Stopped;
try
{
await StopDaemon(ct);
}
catch (Exception e)
{
ReplaceState(new SyncSessionControllerStateModel
{
Lifecycle = SyncSessionControllerLifecycle.Stopped,
DaemonError = $"Failed to stop daemon after no sessions: {e}",
DaemonLogFilePath = MutagenDaemonLog,
SyncSessions = [],
});
throw new InvalidOperationException("Failed to stop daemon after no sessions", e);
}
}
var sessions = listResponse.SessionStates
.Select(s => new SyncSessionModel(s))
.ToList();
sessions.Sort((a, b) => a.CreatedAt < b.CreatedAt ? -1 : 1);
var state = new SyncSessionControllerStateModel
{
Lifecycle = lifecycle,
DaemonError = null,
DaemonLogFilePath = MutagenDaemonLog,
SyncSessions = sessions,
};
ReplaceState(state);
return state;
}
/// <summary>
/// Starts the daemon if it's not running and returns a client to it.
/// Must be called AND awaited with the lock held.
/// </summary>
private async Task<MutagenClient> EnsureDaemon(CancellationToken ct)
{
ObjectDisposedException.ThrowIf(_disposing, typeof(MutagenController));
if (_mutagenClient != null && _daemonProcess != null)
return _mutagenClient;
try
{
return await StartDaemon(ct);
}
catch (Exception e)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
await StopDaemon(cts.Token);
}
catch
{
// ignored
}
ReplaceState(new SyncSessionControllerStateModel
{
Lifecycle = SyncSessionControllerLifecycle.Stopped,
DaemonError = $"Failed to start daemon: {e}",
DaemonLogFilePath = MutagenDaemonLog,
SyncSessions = [],
});
throw;
}
}
/// <summary>
/// Starts the daemon and returns a client to it.
/// Must be called AND awaited with the lock held.
/// </summary>
private async Task<MutagenClient> StartDaemon(CancellationToken ct)
{
// Stop the running daemon
if (_daemonProcess != null) await StopDaemon(ct);
// Attempt to stop any orphaned daemon
try
{
var client = new MutagenClient(_mutagenDataDirectory);
await client.Daemon.TerminateAsync(new DaemonTerminateRequest(), cancellationToken: ct);
}
catch (FileNotFoundException)
{
// Mainline; no daemon running.
}
catch (InvalidOperationException)
{
// Mainline; no daemon running.
}
// If we get some failure while creating the log file or starting the process, we'll retry
// it up to 5 times x 100ms. Those issues should resolve themselves quickly if they are
// going to at all.
const int maxAttempts = 5;
for (var attempts = 1; attempts <= maxAttempts; attempts++)
{
ct.ThrowIfCancellationRequested();
try
{
StartDaemonProcess();
}
catch (Exception e) when (e is not OperationCanceledException)
{
if (attempts == maxAttempts)
throw;
// back off a little and try again.
await Task.Delay(100, ct);
continue;
}
break;
}
// Wait for the RPC to be available.
while (true)
{
ct.ThrowIfCancellationRequested();
try
{
var client = new MutagenClient(_mutagenDataDirectory);
_ = await client.Daemon.VersionAsync(new VersionRequest(), cancellationToken: ct);
_mutagenClient = client;
return client;
}
catch (Exception e) when
(e is not OperationCanceledException) // TODO: Are there other permanent errors we can detect?
{
// just wait a little longer for the daemon to come up
await Task.Delay(100, ct);
}
}
}
/// <summary>
/// Starts the daemon process.
/// Must be called AND awaited with the lock held.
/// </summary>
private void StartDaemonProcess()
{
if (_daemonProcess != null)
throw new InvalidOperationException("StartDaemonProcess called when _daemonProcess already present");
// create the log file first, so ensure we have permissions
Directory.CreateDirectory(_mutagenDataDirectory);
var logPath = Path.Combine(_mutagenDataDirectory, "daemon.log");
var logStream = new StreamWriter(logPath, true);
_daemonProcess = new Process();
_daemonProcess.StartInfo.FileName = _mutagenExecutablePath;
_daemonProcess.StartInfo.Arguments = "daemon run";
_daemonProcess.StartInfo.Environment.Add("MUTAGEN_DATA_DIRECTORY", _mutagenDataDirectory);
// hide the console window
_daemonProcess.StartInfo.CreateNoWindow = true;
// shell needs to be disabled since we set the environment
// https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.environment?view=net-8.0
_daemonProcess.StartInfo.UseShellExecute = false;
_daemonProcess.StartInfo.RedirectStandardError = true;
// TODO: log exited process
// _daemonProcess.Exited += ...
if (!_daemonProcess.Start())
throw new InvalidOperationException("Failed to start mutagen daemon process, Start returned false");
var writer = new LogWriter(_daemonProcess.StandardError, logStream);
Task.Run(() => { _ = writer.Run(); });
_logWriter = writer;
}
/// <summary>
/// Stops the daemon process.
/// Must be called AND awaited with the lock held.
/// </summary>
private async Task StopDaemon(CancellationToken ct)
{
var process = _daemonProcess;
var client = _mutagenClient;
var writer = _logWriter;
_daemonProcess = null;
_mutagenClient = null;
_logWriter = null;
try
{
if (client == null)
{
if (process == null) return;
process.Kill(true);
}
else
{
try
{
await client.Daemon.TerminateAsync(new DaemonTerminateRequest(), cancellationToken: ct);
}
catch
{
if (process == null) return;
process.Kill(true);
}
}
if (process == null) return;
var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
await process.WaitForExitAsync(cts.Token);
}
finally
{
client?.Dispose();
process?.Dispose();
writer?.Dispose();
}
}
private class Prompter : IAsyncDisposable
{
public event EventHandler<string>? OnProgress;
private readonly AsyncDuplexStreamingCall<HostRequest, HostResponse> _dup;
private readonly CancellationTokenSource _cts;
private readonly Task _handleRequestsTask;
public string Identifier { get; }
private Prompter(string identifier, AsyncDuplexStreamingCall<HostRequest, HostResponse> dup,
CancellationToken ct)
{
Identifier = identifier;
_dup = dup;
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_handleRequestsTask = HandleRequests(_cts.Token);
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
try
{
await _handleRequestsTask;
}
catch
{
// ignored
}
_cts.Dispose();
GC.SuppressFinalize(this);
}
public static async Task<Prompter> Create(MutagenClient client, bool allowPrompts = false,
CancellationToken ct = default)
{
var dup = client.Prompting.Host(cancellationToken: ct);
if (dup == null) throw new InvalidOperationException("Prompting.Host returned null");
try
{
// Write first request.
await dup.RequestStream.WriteAsync(new HostRequest
{
AllowPrompts = allowPrompts,
}, ct);
// Read initial response.
if (!await dup.ResponseStream.MoveNext(ct))
throw new InvalidOperationException("Prompting.Host response stream ended early");
var response = dup.ResponseStream.Current;
if (response == null)
throw new InvalidOperationException("Prompting.Host response stream returned null");
if (string.IsNullOrEmpty(response.Identifier))
throw new InvalidOperationException("Prompting.Host response stream returned empty identifier");
return new Prompter(response.Identifier, dup, ct);
}
catch
{
await dup.RequestStream.CompleteAsync();
dup.Dispose();
throw;
}
}
private async Task HandleRequests(CancellationToken ct)
{
try
{
while (true)
{
ct.ThrowIfCancellationRequested();
// Read next request and validate it.
if (!await _dup.ResponseStream.MoveNext(ct))
throw new InvalidOperationException("Prompting.Host response stream ended early");
var response = _dup.ResponseStream.Current;
if (response == null)
throw new InvalidOperationException("Prompting.Host response stream returned null");
if (response.Message == null)
throw new InvalidOperationException("Prompting.Host response stream returned a null message");
if (!response.IsPrompt)
OnProgress?.Invoke(this, response.Message);
// Currently we only reply to SSH fingerprint messages with
// "yes" and send an empty reply for everything else.
var reply = "";
if (response.IsPrompt && response.Message.Contains("yes/no/[fingerprint]")) reply = "yes";
await _dup.RequestStream.WriteAsync(new HostRequest
{
Response = reply,
}, ct);
}
}
catch
{
await _dup.RequestStream.CompleteAsync();
// TODO: log?
}
}
}
private class LogWriter(StreamReader reader, StreamWriter writer) : IDisposable
{
public void Dispose()
{
reader.Dispose();
writer.Dispose();
GC.SuppressFinalize(this);
}
public async Task Run()
{
try
{
while (await reader.ReadLineAsync() is { } line) await writer.WriteLineAsync(line);
}
catch
{
// TODO: Log?
}
finally
{
Dispose();
}
}
}
}