Repository navigation
Expand file tree
/
Copy pathPackageOperations.cs
More file actions
1762 lines (1584 loc) · 73.3 KB
/
Copy pathPackageOperations.cs
File metadata and controls
1762 lines (1584 loc) · 73.3 KB
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
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using UniGetUI.Core.Classes;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.Tools;
using UniGetUI.Interface.Enums;
using UniGetUI.PackageEngine.AgentBroker;
using UniGetUI.PackageEngine.Classes.Packages.Classes;
using UniGetUI.PackageEngine.Enums;
using UniGetUI.PackageEngine.Interfaces;
using UniGetUI.PackageEngine.Operations.Reboot;
using UniGetUI.PackageEngine.PackageClasses;
using UniGetUI.PackageEngine.PackageLoader;
using UniGetUI.PackageEngine.Serializable;
using UniGetUI.PackageOperations;
using BrokerClient = Devolutions.Now.Policy.Client.BrokerClient;
using BrokerClientErrorKind = Devolutions.Now.Policy.Client.BrokerClientErrorKind;
using BrokerClientException = Devolutions.Now.Policy.Client.BrokerClientException;
using BrokerDecision = Devolutions.Now.Policy.Api.Decision;
using BrokerElevation = Devolutions.Now.Policy.Api.Elevation;
using BrokerEventFrame = Devolutions.Now.Policy.Api.EventFrame;
using BrokerEventFrameException = Devolutions.Now.Policy.Api.EventFrameException;
using BrokerExecutionResponse = Devolutions.Now.Policy.Api.ExecutionResponse;
using BrokerOperationEventChannel = Devolutions.Now.Policy.Client.OperationEventChannel;
using BrokerOperationStatus = Devolutions.Now.Policy.Api.OperationStatus;
using BrokerStatusResponse = Devolutions.Now.Policy.Api.StatusResponse;
using OperationCancelQuery = Devolutions.Now.Policy.Client.OperationCancelQuery;
using OperationStatusQuery = Devolutions.Now.Policy.Client.OperationStatusQuery;
using PackageOperationRequest = Devolutions.Now.Policy.Client.PackageOperationRequest;
#if WINDOWS
using UniGetUI.PackageEngine.Managers.WingetManager;
#endif
namespace UniGetUI.PackageEngine.Operations
{
public abstract class PackageOperation : AbstractProcessOperation
{
/// <summary>
/// Raised when an operation that must be routed through the Devolutions Agent broker
/// cannot proceed because the broker is not available, or does not accept this client.
/// The payload is the user-facing title and message. The UI layer subscribes to this to
/// show an error message box.
/// </summary>
public static event EventHandler<BrokerFailureDescription>? BrokerUnavailable;
/// <summary>
/// Test seam: substitutes the transport used to reach the agent broker so tests can
/// simulate broker outages without a real named pipe. Always null in production.
/// </summary>
internal static Func<Devolutions.Now.Policy.Client.IBrokerTransport>? BrokerTransportFactory;
/// <summary>
/// Interval between broker operation status polls. Internal so tests can shorten it.
/// </summary>
internal static int BrokerStatusPollIntervalMs = 500;
/// <summary>
/// Maximum time to wait for the broker to accept a cancel request.
/// </summary>
internal static TimeSpan BrokerCancelRequestTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// Maximum time to wait for a canceled broker operation to reach a terminal status.
/// </summary>
internal static TimeSpan BrokerCancelConfirmTimeout = TimeSpan.FromSeconds(30);
/// <summary>
/// Upper bound for a brokered operation to reach a terminal status before the
/// operation is reported as failed. Protects against a broker that keeps
/// reporting a non-terminal status indefinitely.
/// </summary>
internal static TimeSpan BrokerOperationTimeout = TimeSpan.FromHours(1);
protected List<string> DesktopShortcutsBeforeStart = [];
protected List<string>? StartMenuShortcutsBeforeStart;
public readonly IPackage Package;
public readonly InstallOptions Options;
public readonly OperationType Role;
public bool FailedBecauseApplicationRunning { get; private set; }
private IReadOnlyList<string> _closeRunningAppProcessNames = [];
private readonly List<string> _brokerKillBeforeOperationAdded = [];
protected abstract Task HandleSuccess();
protected abstract Task HandleFailure();
protected abstract void Initialize();
protected void SnapshotStartMenuShortcutsOnStart()
{
OperationStarting += (_, _) =>
{
if (StartMenuShortcutsBeforeStart is not null)
return;
if (StartMenuShortcutsDatabase.ShouldTrackShortcuts(Package))
StartMenuShortcutsBeforeStart =
StartMenuShortcutsDatabase.GetShortcutsOnDisk();
};
}
public PackageOperation(
IPackage package,
InstallOptions options,
OperationType role,
bool IgnoreParallelInstalls = false,
AbstractOperation? req = null
)
: base(
!IgnoreParallelInstalls,
_getPreInstallOps(package, options, role, req),
_getPostInstallOps(package, options, role)
)
{
Package = package;
Options = options;
Role = role;
Initialize();
Enqueued += (_, _) =>
{
ApplyCapabilities(
RequiresAdminRights(),
Options.InteractiveInstallation,
(Options.SkipHashCheck && Role is not OperationType.Uninstall),
Package.OverridenOptions.Scope ?? Options.InstallationScope
);
Package.SetTag(PackageTag.OnQueue);
};
StatusChanged += (_, status) =>
{
if (status is OperationStatus.Canceled)
Package.SetTag(PackageTag.Default);
};
OperationSucceeded += (_, _) => RecordPendingRebootState();
OperationSucceeded += (_, _) => HandleSuccess();
OperationFailed += (_, _) => HandleFailure();
}
private void RecordPendingRebootState()
{
try
{
if (SystemRestartRequired)
PendingRebootStore.Record(Package, Role);
else if (Role is OperationType.Uninstall)
PendingRebootStore.Clear(Package.Manager.Id, Package.Id);
}
catch (Exception ex)
{
Logger.Warn("Failed to update the pending-reboot store");
Logger.Warn(ex);
}
}
public static bool HasPendingOperation(IPackage package, OperationType role)
{
if (package.Tag is not (PackageTag.OnQueue or PackageTag.BeingProcessed))
return false;
Logger.Warn(
$"Skipping {role} of {package.Id} because an operation for this package is already queued or running"
);
return true;
}
private bool RequiresAdminRights() =>
BrokerRequestValidator.RequestsElevation(Package, Options);
private volatile int _ranElevated = -1;
public virtual bool WillRunElevated =>
_ranElevated switch
{
1 => true,
0 => false,
_ => CoreTools.IsAdministrator() || RequiresAdminRights(),
};
public static bool CanRetrySkippingIntegrityChecks(
IPackageManager manager,
InstallOptions options,
OperationType role,
bool willRunElevated
)
{
if (!manager.Capabilities.CanSkipIntegrityChecks || options.SkipHashCheck)
return false;
return IntegrityCheckSkipIsHonored(manager, role, willRunElevated);
}
private static bool IntegrityCheckSkipIsHonored(
IPackageManager manager,
OperationType role,
bool willRunElevated
)
{
#if WINDOWS
if (manager is WinGet winget)
return role is not OperationType.Uninstall
&& (!willRunElevated || winget.HonorsIntegrityCheckSkipWhenElevated);
#endif
return true;
}
protected override void ApplyRetryAction(string retryMode)
{
ClearCloseRunningAppAttempt();
switch (retryMode)
{
case RetryMode.Retry_AsAdmin:
Options.RunAsAdministrator = true;
break;
case RetryMode.Retry_Interactive:
Options.InteractiveInstallation = true;
break;
case RetryMode.Retry_SkipIntegrity:
Options.SkipHashCheck = true;
break;
case RetryMode.Retry_CloseRunningApp:
QueueCloseRunningAppAttempt();
break;
case RetryMode.Retry:
break;
default:
throw new InvalidOperationException(
$"Retry mode {retryMode} is not supported in this context"
);
}
Metadata.OperationInformation =
"Retried package operation for Package="
+ Package.Id
+ " with Manager="
+ Package.Manager.Name
+ "\nUpdated installation options: "
+ Options.ToString()
+ "\nOverriden options: "
+ Package.OverridenOptions.ToString();
}
protected sealed override void PrepareProcessStartInfo()
{
bool IsAdmin = CoreTools.IsAdministrator();
Package.SetTag(PackageTag.OnQueue);
var operationParameters = Package.Manager.OperationHelper.GetParameters(
Package,
Options,
Role
);
var callVector = Package.Manager.Status.OperationCallArgs;
if (RequiresAdminRights() && IsAdmin is false)
{
IsAdmin = true;
if (
OperatingSystem.IsLinux()
|| Settings.Get(Settings.K.DoCacheAdminRights)
|| Settings.Get(Settings.K.DoCacheAdminRightsForBatches)
)
{
RequestCachingOfUACPrompt();
}
process.StartInfo.FileName = CoreData.ElevatorPath;
if (callVector.Count > 0)
{
SetArgumentVector(
[
.. ElevatorArgumentPrefix(),
Package.Manager.Status.ExecutablePath,
.. callVector,
.. operationParameters,
]
);
}
else
{
process.StartInfo.Arguments =
$"{CoreData.ElevatorArgs} \"{Package.Manager.Status.ExecutablePath}\" {Package.Manager.Status.ExecutableCallArgs} {string.Join(" ", operationParameters)}".TrimStart();
}
}
else
{
process.StartInfo.FileName = Package.Manager.Status.ExecutablePath;
if (callVector.Count > 0)
{
SetArgumentVector([.. callVector, .. operationParameters]);
}
else
{
process.StartInfo.Arguments =
$"{Package.Manager.Status.ExecutableCallArgs} {string.Join(" ", operationParameters)}";
}
}
if (IsAdmin && IsWinGetManager(Package.Manager))
{
RedirectWinGetTempFolder();
}
process.StartInfo.StandardOutputEncoding = Package.Manager.OutputEncoding;
process.StartInfo.StandardErrorEncoding = Package.Manager.OutputEncoding;
_ranElevated = IsAdmin ? 1 : 0;
ApplyCapabilities(
IsAdmin,
Options.InteractiveInstallation,
(Options.SkipHashCheck && Role is not OperationType.Uninstall),
Package.OverridenOptions.Scope ?? Options.InstallationScope
);
}
/// <summary>
/// Override to intercept operations and route through the Devolutions Agent broker
/// when the UseAgentBroker setting is enabled and the manager is supported by the
/// broker protocol. Falls back to process-based execution otherwise.
/// </summary>
protected override async Task<OperationVeredict> PerformOperation()
{
// Observational stage marker only: structured progress starts as indeterminate
// with the role's stage label (e.g. "Installing..."). Re-reported on every
// attempt, so AutoRetry restarts also reset any previous speed. This changes
// nothing about execution, retries, elevation, proxy, or result handling.
ReportProgress(
Role switch
{
OperationType.Install => OperationProgress.ForStage(
OperationProgressStage.Installing
),
OperationType.Update => OperationProgress.ForStage(
OperationProgressStage.Updating
),
OperationType.Uninstall => OperationProgress.ForStage(
OperationProgressStage.Uninstalling
),
_ => OperationProgress.Unknown,
}
);
if (!ShouldUseAgentBroker())
{
if (!Package.Manager.Capabilities.SerializesOperations)
return await base.PerformOperation();
SemaphoreSlim gate = ManagerOperationGates.GetOrAdd(
Package.Manager.Name,
_ => new SemaphoreSlim(1, 1)
);
if (!await gate.WaitAsync(0))
{
Line(
CoreTools.Translate(
"Waiting for another {0} operation to finish...",
Package.Manager.DisplayName
),
LineType.ProgressIndicator
);
IsWaitingForManager = true;
try
{
await gate.WaitAsync(CancellationToken);
}
catch (OperationCanceledException)
{
return OperationVeredict.Canceled;
}
finally
{
IsWaitingForManager = false;
}
}
try
{
return await base.PerformOperation();
}
finally
{
gate.Release();
}
}
return await PerformBrokerOperation();
}
private static readonly ConcurrentDictionary<string, SemaphoreSlim> ManagerOperationGates =
new();
/// <summary>
/// Determines whether this operation should be routed through the agent broker.
/// </summary>
private bool ShouldUseAgentBroker()
{
// NOTE: Change this condition to enable agent broker by default when ready.
// Currently opt-in via settings.
bool eligible = IsBrokerEligible(Package);
Logger.Info($"[AgentBroker] ShouldUseAgentBroker check: eligible={eligible}, manager={Package.Manager.Name}, virtualSource={Package.Source.IsVirtualManager}");
return eligible;
}
/// <summary>
/// Whether a package operation is eligible for broker routing. The manager must be
/// mappable to a broker protocol manager, and virtual/local sources are excluded:
/// the agent command builder always emits --source from the request, while the local
/// path deliberately omits it for virtual sources (e.g. the Local PC source).
/// </summary>
private static bool IsBrokerEligible(IPackage package) =>
Settings.Get(Settings.K.UseAgentBroker)
&& BrokerRequestBuilder.SupportsManager(package.Manager.Name)
&& !package.Source.IsVirtualManager;
/// <summary>
/// Raw process output streamed over the event channel of the current brokered
/// run, in emission order. Null when no streamed output was captured (no event
/// channel, or streaming failed); result parsers then receive an empty list.
/// </summary>
private List<string>? _brokerStreamedOutput;
/// <summary>
/// Perform the package operation through the Devolutions Agent broker.
/// Sends the request over named pipe and interprets the response.
/// </summary>
private async Task<OperationVeredict> PerformBrokerOperation()
{
_brokerStreamedOutput = null;
Line("Routing operation through Devolutions Agent broker...", LineType.Information);
if (BrokerRequestBuilder.IsUnsupportedAllowClobberRetry(Package, Role))
{
Line("The module conflicts with commands that are already installed; the broker cannot retry with -AllowClobber.", LineType.Error);
return FailWith(new BrokerFailureDescription(
CoreTools.Translate("The module conflicts with installed commands"),
CoreTools.Translate(
"{0} provides commands that another installed module already provides. Installing it anyway requires the -AllowClobber option, which cannot be used through the Devolutions Agent.",
Package.Name)));
}
// Apply manager-specific elevation requirements (e.g. WinGet's detection of
// machine-scope or elevation-requiring installers) before deciding the requested
// elevation, mirroring the local execution path where this runs as part of
// building the process parameters.
Package.Manager.OperationHelper.ApplyElevationRequirements(Package, Options, Role);
bool requestElevated = RequiresAdminRights();
_ranElevated = requestElevated ? 1 : 0;
using var client = CreateBrokerClient(requestElevated);
// Check broker availability. Brokered operations must not fall back to local
// execution: policy evaluation and kill/pre/post actions are owned by the broker.
if (!await client.IsAvailable(CancellationToken))
{
return HandleBrokerUnavailable();
}
// Fetch the capabilities up front: the broker requires an authenticated client for
// them, so this is where an unsigned or modified build is turned away. The client
// caches the response for the request below.
if (await ProbeBrokerCapabilities(client) is { } capabilitiesFailure)
{
return capabilitiesFailure;
}
// Resolve the install location the same way the local WinGet path does, so the
// portable-install safeguard (registry-detected location) is not bypassed.
string? effectiveInstallLocation = GetBrokerEffectiveInstallLocation();
// Build the broker request.
PackageOperationRequest request;
try
{
request = BrokerRequestBuilder.Build(Package, Options, Role, effectiveInstallLocation);
}
catch (BrokerRequestValidationException ex)
{
foreach (string issue in ex.Issues)
{
Line(issue, LineType.Error);
}
Logger.Warn($"[AgentBroker] Request for {Package.Id} not sent: {ex.Message}");
return FailWith(BrokerFailureDescriber.DescribeValidation(ex.Issues));
}
catch (InvalidOperationException ex)
{
// A value that would be read as a command-line option or split into further
// arguments; the broker would reject it as well.
Line(ex.Message, LineType.Error);
Logger.Warn($"[AgentBroker] Request for {Package.Id} not sent: {ex.Message}");
return FailWith(BrokerFailureDescriber.DescribeValidation([ex.Message]));
}
Line($"Sending request to broker: {request.RequestId}", LineType.VerboseDetails);
Line($" Package: {request.Package.Id} ({request.Operation})", LineType.VerboseDetails);
Line($" Manager: {request.Manager}", LineType.VerboseDetails);
Line($" User: {GetEffectiveUser()}", LineType.VerboseDetails);
Line($" Elevation: {(requestElevated ? "Elevated" : "Standard")}", LineType.VerboseDetails);
try
{
// Submit the operation explicitly (instead of ExecuteAndWait) so the
// operation id is available for broker-side cancellation.
var execution = await client.Execute(request, CancellationToken);
if (execution.Decision.Decision != BrokerDecision.Allow)
{
Line(
$"Operation denied by policy: rule={execution.Decision.RuleId}, reason={execution.Decision.Reason}",
LineType.Error);
return FailWith(BrokerFailureDescriber.DescribeDenial(execution.Decision));
}
if (execution.Operation is null)
{
Line("Broker allowed the operation but did not return an operation submission.", LineType.Error);
Metadata.FailureTitle = CoreTools.Translate("Operation failed via broker");
Metadata.FailureMessage = CoreTools.Translate(
"The broker accepted the request but did not report an operation to track.");
return OperationVeredict.Failure;
}
string operationId = execution.Operation.OperationId;
Line($"Broker accepted operation: {operationId}", LineType.VerboseDetails);
// Bound the whole tracking phase (streaming or polling) so a broker that
// never reports a terminal status cannot hang the operation forever.
using var operationTimeout = new CancellationTokenSource(BrokerOperationTimeout);
using var tracking = CancellationTokenSource.CreateLinkedTokenSource(
CancellationToken, operationTimeout.Token);
try
{
// Prefer live status/output streaming over the per-operation event channel
// when the broker advertises one; otherwise (or if streaming breaks) fall
// back to plain status polling without live output.
if (execution.Operation.EventChannel is not null)
{
OperationVeredict? streamed = await StreamBrokerOperationEvents(
client, execution, operationId, tracking.Token);
if (streamed is not null)
{
return streamed.Value;
}
}
else
{
Logger.Info("[AgentBroker] The broker did not advertise an event channel; using status polling without live output.");
}
BrokerStatusResponse status = await WaitForBrokerTerminalStatus(client, operationId, tracking.Token);
return await InterpretBrokerTerminalStatus(status);
}
catch (OperationCanceledException) when (CancellationToken.IsCancellationRequested)
{
return await CancelBrokerOperation(client, operationId);
}
catch (OperationCanceledException) when (operationTimeout.IsCancellationRequested)
{
string timeoutMessage = CoreTools.Translate(
"The operation did not finish within the allotted time. It may still be running on the agent.");
Line($"Broker operation timed out after {BrokerOperationTimeout}.", LineType.Error);
Logger.Error($"[AgentBroker] Operation {operationId} did not reach a terminal status within {BrokerOperationTimeout}");
Metadata.FailureTitle = CoreTools.Translate("Operation failed via broker");
Metadata.FailureMessage = timeoutMessage;
return OperationVeredict.Failure;
}
}
catch (OperationCanceledException)
{
Line("Broker operation was canceled.", LineType.Information);
return OperationVeredict.Canceled;
}
catch (BrokerClientException ex) when (ex.Kind is BrokerClientErrorKind.BrokerUnavailable)
{
// The broker can stop between the availability probe and the request itself;
// route this through the same unavailable handling as a failed probe.
Logger.Error($"[AgentBroker] Broker became unavailable during the operation: {ex}");
return HandleBrokerUnavailable();
}
catch (BrokerClientException ex)
{
Line($"Broker operation failed: {ex.Message}", LineType.Error);
Logger.Error($"[AgentBroker] Broker operation failed: {ex}");
return FailWith(BrokerFailureDescriber.Describe(ex));
}
}
/// <summary>
/// Fetches the broker capabilities before the request is built. Returns the failure
/// veredict when the broker cannot be used, or null to continue.
/// </summary>
private async Task<OperationVeredict?> ProbeBrokerCapabilities(BrokerClient client)
{
try
{
await client.GetCapabilities(CancellationToken);
return null;
}
catch (OperationCanceledException) when (CancellationToken.IsCancellationRequested)
{
Line("Broker operation was canceled.", LineType.Information);
return OperationVeredict.Canceled;
}
catch (BrokerClientException ex) when (BrokerFailureDescriber.DescribeCapabilitiesAccessFailure(ex) is { } accessFailure)
{
// The broker is running but does not accept this client: report it as
// unavailable for this copy of UniGetUI, with the reason, instead of a
// generic failure on the operation request.
Line($"The agent broker did not accept this client: {ex.Message}", LineType.Error);
Logger.Error($"[AgentBroker] Capabilities request was refused (HTTP {ex.StatusCode}, {ex.BrokerError?.Code}): {ex.Message}");
FailWith(accessFailure);
BrokerUnavailable?.Invoke(this, accessFailure);
return OperationVeredict.Failure;
}
catch (BrokerClientException ex) when (ex.Kind is BrokerClientErrorKind.BrokerUnavailable)
{
Logger.Error($"[AgentBroker] Broker became unavailable while reading its capabilities: {ex}");
return HandleBrokerUnavailable();
}
catch (BrokerClientException ex)
{
Line($"Could not read the broker capabilities: {ex.Message}", LineType.Error);
Logger.Error($"[AgentBroker] Capabilities request failed: {ex}");
return FailWith(BrokerFailureDescriber.Describe(ex));
}
}
private OperationVeredict FailWith(BrokerFailureDescription description)
{
Metadata.FailureTitle = description.Title;
Metadata.FailureMessage = description.Message;
return OperationVeredict.Failure;
}
/// <summary>
/// Consumes the per-operation event channel advertised by the broker, emitting
/// live stdout/stderr output and reacting to status-change hints. Returns the
/// final operation veredict, or <c>null</c> when streaming could not be used and
/// the caller should fall back to plain status polling. The supplied token combines
/// user cancellation with the overall operation timeout; timeout-induced
/// cancellations propagate to the caller as <see cref="OperationCanceledException"/>.
/// </summary>
private async Task<OperationVeredict?> StreamBrokerOperationEvents(
BrokerClient client,
BrokerExecutionResponse execution,
string operationId,
CancellationToken trackingToken)
{
BrokerOperationEventChannel channel;
try
{
channel = await client.OpenEventChannel(execution, trackingToken);
}
catch (OperationCanceledException) when (CancellationToken.IsCancellationRequested)
{
return await CancelBrokerOperation(client, operationId);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger.Warn($"[AgentBroker] Could not open the operation event channel; falling back to status polling: {ex}");
Line("Live output is not available for this operation; progress will be tracked via status polling.", LineType.Information);
return null;
}
Line("Live output streaming enabled via broker event channel.", LineType.VerboseDetails);
var capturedOutput = new List<string>();
_brokerStreamedOutput = capturedOutput;
var stdout = new StreamedOutputLineBuffer(this, LineType.Information, capturedOutput);
var stderr = new StreamedOutputLineBuffer(this, LineType.Error, capturedOutput);
await using (channel.ConfigureAwait(false))
{
try
{
BrokerOperationStatus? lastReportedStatus = null;
await foreach (var frame in channel.ReadEvents(trackingToken))
{
switch (frame)
{
case BrokerEventFrame.Stdout frameData:
stdout.Append(frameData.Data);
break;
case BrokerEventFrame.Stderr frameData:
stderr.Append(frameData.Data);
break;
case BrokerEventFrame.StdoutOverflow overflow:
Line($"Warning: {overflow.BytesSkipped} bytes of process output were skipped by the broker.", LineType.Information);
break;
case BrokerEventFrame.StderrOverflow overflow:
Line($"Warning: {overflow.BytesSkipped} bytes of process error output were skipped by the broker.", LineType.Information);
break;
case BrokerEventFrame.StatusUpdated:
var updated = await client.QueryStatus(
new OperationStatusQuery { OperationId = operationId },
trackingToken);
if (updated.Status != lastReportedStatus)
{
lastReportedStatus = updated.Status;
Line($"Broker operation status: {updated.Status}", LineType.VerboseDetails);
}
break;
// Hello and Finish frames need no handling here: the channel
// validates the handshake, and Finish ends the enumeration.
}
}
}
catch (OperationCanceledException) when (CancellationToken.IsCancellationRequested)
{
return await CancelBrokerOperationWhileStreaming(client, channel, operationId, stdout, stderr);
}
catch (OperationCanceledException)
{
// Operation-timeout cancellation: surface any buffered output before
// letting the caller report the timeout failure.
stdout.Flush();
stderr.Flush();
throw;
}
catch (Exception ex) when (ex is BrokerEventFrameException or IOException)
{
// The frame stream is corrupt or the transport failed; the operation
// itself is still running on the broker. Fall back to status polling.
stdout.Flush();
stderr.Flush();
Logger.Warn($"[AgentBroker] The operation event channel failed mid-stream; falling back to status polling: {ex}");
Line("Live output streaming was interrupted; progress will be tracked via status polling.", LineType.Information);
return null;
}
stdout.Flush();
stderr.Flush();
}
BrokerStatusResponse status;
try
{
status = await QueryBrokerTerminalStatus(client, operationId, trackingToken);
}
catch (OperationCanceledException) when (CancellationToken.IsCancellationRequested)
{
return await CancelBrokerOperation(client, operationId);
}
return await InterpretBrokerTerminalStatus(status);
}
/// <summary>
/// Queries the broker for the operation status, and keeps polling until a
/// terminal status is reported. Unlike <see cref="WaitForBrokerTerminalStatus"/>,
/// the first query happens immediately (no initial delay).
/// </summary>
private static async Task<BrokerStatusResponse> QueryBrokerTerminalStatus(
BrokerClient client,
string operationId,
CancellationToken cancellationToken)
{
var status = await client.QueryStatus(
new OperationStatusQuery { OperationId = operationId },
cancellationToken);
if (status.Status is BrokerOperationStatus.Completed
or BrokerOperationStatus.Failed
or BrokerOperationStatus.Canceled)
{
return status;
}
return await WaitForBrokerTerminalStatus(client, operationId, cancellationToken);
}
/// <summary>
/// Polls the broker until the operation reaches a terminal status
/// (Completed, Failed or Canceled).
/// </summary>
private static async Task<BrokerStatusResponse> WaitForBrokerTerminalStatus(
BrokerClient client,
string operationId,
CancellationToken cancellationToken)
{
while (true)
{
await Task.Delay(BrokerStatusPollIntervalMs, cancellationToken);
var status = await client.QueryStatus(
new OperationStatusQuery { OperationId = operationId },
cancellationToken);
if (status.Status is BrokerOperationStatus.Completed
or BrokerOperationStatus.Failed
or BrokerOperationStatus.Canceled)
{
return status;
}
}
}
/// <summary>
/// Requests broker-side cancellation of a running operation, then waits (bounded)
/// for the operation to reach a terminal status. The remote process may win the
/// race and complete or fail before the cancel takes effect; in that case the
/// terminal status is honored instead of reporting a cancellation.
/// </summary>
private async Task<OperationVeredict> CancelBrokerOperation(BrokerClient client, string operationId)
{
await RequestBrokerCancel(client, operationId);
return await ConfirmBrokerCancellation(client, operationId);
}
/// <summary>
/// Cancellation flow used while consuming the event channel: after asking the
/// broker to cancel, keeps draining the channel (bounded) so the tail of the
/// process output and the Finish frame are honored, then confirms the terminal
/// status over the regular status endpoint. If draining fails, falls back to
/// the plain poll-based confirmation.
/// </summary>
private async Task<OperationVeredict> CancelBrokerOperationWhileStreaming(
BrokerClient client,
BrokerOperationEventChannel channel,
string operationId,
StreamedOutputLineBuffer stdout,
StreamedOutputLineBuffer stderr)
{
await RequestBrokerCancel(client, operationId);
try
{
using var drainTimeout = new CancellationTokenSource(BrokerCancelConfirmTimeout);
await foreach (var frame in channel.ReadEvents(drainTimeout.Token))
{
switch (frame)
{
case BrokerEventFrame.Stdout frameData:
stdout.Append(frameData.Data);
break;
case BrokerEventFrame.Stderr frameData:
stderr.Append(frameData.Data);
break;
}
}
}
catch (Exception ex)
{
Logger.Warn($"[AgentBroker] Could not drain the event channel of canceled operation {operationId}: {ex}");
}
finally
{
stdout.Flush();
stderr.Flush();
}
return await ConfirmBrokerCancellation(client, operationId);
}
/// <summary>
/// Best-effort broker-side cancel request, bounded by
/// <see cref="BrokerCancelRequestTimeout"/>. Failures are logged but not
/// surfaced: the cancel request is idempotent, and the operation may already
/// have reached a terminal state.
/// </summary>
private async Task RequestBrokerCancel(BrokerClient client, string operationId)
{
Line("Cancellation requested; asking broker to cancel the remote operation...", LineType.Information);
try
{
using var cancelTimeout = new CancellationTokenSource(BrokerCancelRequestTimeout);
var cancelResponse = await client.Cancel(
new OperationCancelQuery { OperationId = operationId },
cancelTimeout.Token);
Line($"Broker acknowledged cancel request: {cancelResponse.Status}", LineType.VerboseDetails);
}
catch (Exception ex)
{
Logger.Warn($"[AgentBroker] Cancel request for operation {operationId} failed: {ex}");
Line("Broker cancel request failed; checking final operation status...", LineType.Information);
}
}
/// <summary>
/// Waits (bounded) for a canceled operation to reach a terminal status. The
/// remote process may win the race and complete or fail before the cancel takes
/// effect; in that case the terminal status is honored instead of reporting a
/// cancellation.
/// </summary>
private async Task<OperationVeredict> ConfirmBrokerCancellation(BrokerClient client, string operationId)
{
try
{
using var confirmTimeout = new CancellationTokenSource(BrokerCancelConfirmTimeout);
var status = await QueryBrokerTerminalStatus(client, operationId, confirmTimeout.Token);
if (status.Status is not BrokerOperationStatus.Canceled)
{
// The remote process finished before the cancel took effect.
Line($"Broker operation finished before cancellation took effect: {status.Status}", LineType.Information);
return await InterpretBrokerTerminalStatus(status);
}
}
catch (Exception ex)
{
// The user asked for cancellation; do not surface polling failures as errors.
Logger.Warn($"[AgentBroker] Could not confirm terminal status of canceled operation {operationId}: {ex}");
}
Line("Broker operation was canceled.", LineType.Information);
return OperationVeredict.Canceled;
}
/// <summary>
/// Maps a terminal broker status response to an operation veredict, setting
/// failure metadata where appropriate.
/// </summary>
private async Task<OperationVeredict> InterpretBrokerTerminalStatus(BrokerStatusResponse status)
{
Line($"Broker status: {status.Status}, exitCode={status.ExitCode}", LineType.Information);
if (!string.IsNullOrWhiteSpace(status.Message))
{
Line($" Message: {status.Message}", LineType.Information);
}
if (status.Status is BrokerOperationStatus.Canceled)
{
Line("Broker operation was canceled.", LineType.Information);
return OperationVeredict.Canceled;
}
if (status.Status is BrokerOperationStatus.Completed)
{
// Feed the process output streamed over the event channel (if any) to
// the manager's result parser, like the local process path does. Only
// real process output is passed; internal informational lines are not.
var veredict = await GetProcessVeredict(status.ExitCode ?? -1, _brokerStreamedOutput ?? []);
if (veredict is OperationVeredict.Success or OperationVeredict.RestartRequired)
{
Line("Operation completed successfully via agent broker.", LineType.Information);
}
else if (!string.IsNullOrWhiteSpace(status.Message))
{
Metadata.FailureMessage = status.Message;
}
return veredict;
}
// Operation failed — surface a user-visible error.
string reason = string.IsNullOrWhiteSpace(status.Message)
? CoreTools.Translate(
"The package manager run by the Devolutions Agent reported an error (exit code {0}).",
status.ExitCode?.ToString() ?? "?")
: status.Message;
Line($"Operation failed via broker: {reason}", LineType.Error);
Metadata.FailureTitle = CoreTools.Translate("Operation failed via broker");
Metadata.FailureMessage = reason;
return OperationVeredict.Failure;
}
/// <summary>
/// Fails the operation because the agent broker is unreachable: brokered operations
/// must not fall back to local execution, since policy evaluation and kill/pre/post
/// actions are owned by the broker. Sets the failure metadata and raises
/// <see cref="BrokerUnavailable"/> so the UI can notify the user.
/// </summary>
private OperationVeredict HandleBrokerUnavailable()
{
Line("Agent broker is not available. The operation cannot continue.", LineType.Error);
Logger.Error("[AgentBroker] Broker not available, aborting operation");
string message = CoreTools.Translate(
"The Devolutions Agent broker is not available. The operation cannot be performed. Please ensure the Devolutions Agent is installed and running.");
Metadata.FailureTitle = CoreTools.Translate("Agent broker unavailable");
Metadata.FailureMessage = message;
BrokerUnavailable?.Invoke(this, new BrokerFailureDescription(Metadata.FailureTitle, message));
return OperationVeredict.Failure;
}
/// <summary>
/// Buffers streamed process output and emits it line by line through
/// <see cref="AbstractOperation.Line"/>, mirroring the local process reader:
/// LF-terminated text is emitted with the configured line type, while
/// CR-terminated text (progress bars) is emitted as a progress indicator and
/// promoted to a regular line when followed by a bare LF. Regular (non-progress)
/// lines are also recorded in <paramref name="capturedOutput"/> so the manager's
/// result parser receives only real process output.
/// </summary>
private sealed class StreamedOutputLineBuffer(
PackageOperation owner,
LineType lineType,
List<string> capturedOutput)
{
private readonly StringBuilder _pending = new();
private string? _lastLineBeforeLF;
public void Append(string data)
{
ReadOnlySpan<char> remaining = data;
while (!remaining.IsEmpty)
{