Repository navigation
Expand file tree
/
Copy pathPackageManager.cs
More file actions
641 lines (562 loc) · 24.8 KB
/
Copy pathPackageManager.cs
File metadata and controls
641 lines (562 loc) · 24.8 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
using System.Diagnostics;
using System.Text;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.SettingsEngine.SecureSettings;
using UniGetUI.Core.Tools;
using UniGetUI.PackageEngine.Classes.Manager;
using UniGetUI.PackageEngine.Classes.Manager.Classes;
using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers;
using UniGetUI.PackageEngine.Classes.Packages;
using UniGetUI.PackageEngine.Interfaces;
using UniGetUI.PackageEngine.Interfaces.ManagerProviders;
using UniGetUI.PackageEngine.ManagerClasses.Classes;
using UniGetUI.PackageEngine.PackageClasses;
namespace UniGetUI.PackageEngine.ManagerClasses.Manager
{
public abstract class PackageManager : IPackageManager
{
private const int PackageListingTaskTimeout = 60;
public ManagerProperties Properties { get; set; } = new(IsDummy: true);
public ManagerCapabilities Capabilities { get; set; } = new(IsDummy: true);
public ManagerStatus Status { get; set; } = new() { Found = false };
public string Id
{
get => string.IsNullOrWhiteSpace(Properties.Id) ? Name : Properties.Id;
}
public string Name
{
get => Properties.Name;
}
public string DisplayName
{
get => Properties.DisplayName ?? Name;
}
public IManagerSource DefaultSource
{
get => Properties.DefaultSource;
}
public IManagerLogger TaskLogger { get; }
public IReadOnlyList<ManagerDependency> Dependencies { get; protected set; } = [];
public IMultiSourceHelper SourcesHelper { get; protected set; } = new NullSourceHelper();
public IPackageDetailsHelper DetailsHelper { get; protected set; } = null!;
public IPackageOperationHelper OperationHelper { get; protected set; } = null!;
public virtual Encoding OutputEncoding => Encoding.UTF8;
public virtual bool InstallerUrlFollowsPackageVersion => false;
public virtual bool CommandLineIsShellInterpreted => false;
public virtual bool IdentifiersAreQuotedOnCommandLine => false;
public virtual int? CompareVersions(string versionA, string versionB)
{
var parsedA = CoreTools.VersionStringToStruct(versionA);
var parsedB = CoreTools.VersionStringToStruct(versionB);
if (parsedA == CoreTools.Version.Null || parsedB == CoreTools.Version.Null)
return null;
return parsedA.CompareTo(parsedB);
}
private readonly bool _baseConstructorCalled;
private bool _ready;
public PackageManager()
{
_baseConstructorCalled = true;
TaskLogger = new ManagerLogger(this);
}
private static void Throw(string message)
{
throw new InvalidDataException(message);
}
protected abstract void _loadManagerExecutableFile(
out bool found,
out string path,
out string callArguments
);
protected abstract void _loadManagerVersion(out string version);
/// <summary>
/// The argument vector that precedes the operation parameters, for managers whose command
/// line must be built with <see cref="System.Diagnostics.ProcessStartInfo.ArgumentList"/>
/// instead of a single concatenated string. An empty vector selects the concatenated
/// <see cref="ManagerStatus.ExecutableCallArgs"/> path.
/// </summary>
protected virtual IReadOnlyList<string> _getOperationCallArgs(
string executablePath,
string callArguments
) => [];
protected virtual void _performPreInitializationSteps() { }
protected virtual void _performExtraLoadingSteps() { }
public virtual void Initialize()
{
try
{
_ready = false;
_ensurePropertlyConstructed();
_performPreInitializationSteps();
if (!IsEnabled())
{ // Do NOT initialise disabled package managers
Status = new() { Version = CoreTools.Translate("{0} is disabled", DisplayName) };
Logger.ImportantInfo($"{Name} is not enabled");
return;
}
// Find package manager executable
_loadManagerExecutableFile(
out bool found,
out string path,
out string callArguments
);
if (_recordDefaultEnabledState(found))
{
Status = new() { Version = CoreTools.Translate("{0} is disabled", DisplayName) };
Logger.ImportantInfo(
$"{Name} was not found on the system and has been disabled by default"
);
return;
}
Status = new ManagerStatus();
Status.Found = found;
Status.ExecutablePath = path;
Status.ExecutableCallArgs = callArguments;
if (!Status.Found)
{ // Do not load version of managers that were not found
Status.Version = CoreTools
.Translate("{pm} was not found!")
.Replace("{pm}", DisplayName)
.Trim('!');
Logger.Error($"{Name} is enabled but was not found on the system!");
return;
}
Logger.ImportantInfo($"{Name} is enabled and was found on {path}");
Status.OperationCallArgs = _getOperationCallArgs(path, callArguments);
// Load manager version
_loadManagerVersion(out string version);
Status.Version = version;
_logManagerInfo();
// Finish initialization
_performExtraLoadingSteps();
_ready = true;
_initializeSources();
}
catch (Exception ex)
{
Logger.Error($"An error occurred while initialising package manager {Name}");
Logger.Error(ex);
}
}
/// <summary>
/// This serves to ensure that the implemented hasn't messed up any crucial
/// details on the implementation
/// </summary>
private void _ensurePropertlyConstructed()
{
if (!_baseConstructorCalled)
Throw($"The Manager {Properties.Name} has not called the base constructor.");
if (Capabilities.IsDummy)
Throw(
$"The current instance of PackageManager with name ${Properties.Name} does not have a valid Capabilities object"
);
if (Properties.IsDummy)
Throw(
$"The current instance of PackageManager with name ${Properties.Name} does not have a valid Properties object"
);
if (OperationHelper is NullPkgOperationHelper)
Throw($"Manager {Name} does not have an OperationProvider");
if (DetailsHelper is NullPkgDetailsHelper)
Throw($"Manager {Name} does not have a valid DetailsHelper");
if (Capabilities.SupportsCustomSources && SourcesHelper is NullSourceHelper)
Throw(
$"Manager {Name} has been declared as SupportsCustomSources but has no helper associated with it"
);
}
/// <summary>
/// Load and prepare manager sources sources
/// </summary>
private void _initializeSources()
{
// Sources that are instantiated before Manager's DisplayName property will have invalid DisplayName
// To prevent loading it on runtime, the string is cached internally and will only be reloaded when needed to
Properties.DefaultSource.RefreshSourceNames();
foreach (var source in Properties.KnownSources)
{
source.RefreshSourceNames();
}
if (Capabilities.SupportsCustomSources)
{
// SourcesHelper.GetSources() will handle saving the found sources to the internal registry
SourcesHelper.GetSources();
}
}
private void _logManagerInfo()
{
string LogData = $"""
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
█▀▀▀▀▀▀▀▀▀▀▀▀▀ MANAGER LOADED ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
█ Name: {DisplayName} (aka {Name})
█ Executable name: "{Properties.ExecutableFriendlyName}"
█ Executable path: "{Status.ExecutablePath}"
█ Call arguments: "{Status.ExecutableCallArgs}"
█ Version: {Status.Version.Trim().Replace("\n", "\n█ ")}
█
█ {DisplayName} is enabled and ready to go.
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
""";
Logger.Info(LogData);
}
/// <summary>
/// Returns a list of paths that could be used for this package manager.
/// For example, if you have three Pythons installed on your system, this would return those three Pythons.
/// </summary>
/// <returns>A tuple containing: a boolean that represents whether the path was found or not; the path to the file if found.</returns>
public abstract IReadOnlyList<string> FindCandidateExecutableFiles();
public Tuple<bool, string> GetExecutableFile()
{
var candidates = FindCandidateExecutableFiles();
// If custom package manager paths are DISABLED, get the first one (as old UniGetUI did) and return it.
if (!SecureSettings.Get(SecureSettings.K.AllowCustomManagerPaths))
{
if (candidates.Count == 0)
{
// No paths were found
return new(false, "");
}
return new(true, candidates[0]);
}
else
{
string? exeSelection = Settings.GetDictionaryItem<string, string>(
Settings.K.ManagerPaths,
Name
);
// If there is no executable selection for this package manager
if (string.IsNullOrEmpty(exeSelection))
{
if (candidates.Count == 0)
{
// No paths were found
return new(false, "");
}
return new(true, candidates[0]);
}
else if (!File.Exists(exeSelection))
{
Logger.Error(
$"The selected executable path {exeSelection} for manager {Name} does not exist, the default one will be used if available..."
);
}
else
{
return new(true, exeSelection);
}
if (candidates.Count == 0)
{
// No paths were found
return new(false, "");
}
return new(true, candidates[0]);
}
}
protected bool IsUserSelectedExecutablePath(string path)
{
if (!SecureSettings.Get(SecureSettings.K.AllowCustomManagerPaths))
{
return false;
}
string? exeSelection = Settings.GetDictionaryItem<string, string>(
Settings.K.ManagerPaths,
Name
);
return !string.IsNullOrEmpty(exeSelection)
&& File.Exists(exeSelection)
&& exeSelection.Equals(path, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Returns true if the manager is enabled, false otherwise
/// </summary>
public bool IsEnabled()
{
return !Settings.GetDictionaryItem<string, bool>(Settings.K.DisabledManagers, Name);
}
private static readonly object _defaultEnabledStateLock = new();
private bool _recordDefaultEnabledState(bool found)
{
lock (_defaultEnabledStateLock)
{
if (Settings.DictionaryContainsKey<string, bool>(Settings.K.DisabledManagers, Name))
return false;
Settings.SetDictionaryItem(Settings.K.DisabledManagers, Name, !found);
return !found;
}
}
/// <summary>
/// Returns true if the manager is enabled and available (the required executable files were found). Returns false otherwise
/// </summary>
public bool IsReady()
{
return _ready && IsEnabled() && Status.Found;
}
// Opt out (override => false) when AttemptFastRepair can't recover a timed-out query (issue #4974).
protected virtual bool RetryListingTasksOnTimeout => true;
// Processes started by the current listing task, so a timeout can kill them instead of orphaning them.
private readonly AsyncLocal<List<Process>?> _listingProcesses = new();
// Lets a listing task register a process for kill-on-timeout. No-op when outside a listing task.
protected void RegisterListingProcess(Process process)
{
List<Process>? processes = _listingProcesses.Value;
if (processes is null)
return;
lock (processes)
processes.Add(process);
}
private static void KillListingProcesses(List<Process> processes)
{
lock (processes)
foreach (Process p in processes)
{
try
{
if (!p.HasExited)
p.Kill(entireProcessTree: true);
}
catch (Exception ex)
{
Logger.Warn($"Could not kill a timed-out process tree: {ex.Message}");
}
}
}
private void RefreshPackageIndexesSafely()
{
try
{
RunListingTaskWithTimeout<object?>(
() =>
{
RefreshPackageIndexes();
return null;
},
"RefreshPackageIndexes",
allowDisablingTimeout: false
);
}
catch (Exception e)
{
while (e is AggregateException)
e = e.InnerException ?? new InvalidOperationException("How did we get here?");
Logger.Warn(
$"Manager {DisplayName} could not refresh its package indexes "
+ $"({e.GetType().Name}: {e.Message}). The available updates will be listed "
+ "with the indexes as they are, which may result in an incomplete list."
);
}
}
private T RunListingTaskWithTimeout<T>(
Func<T> method,
string taskName,
bool allowDisablingTimeout = true
)
{
List<Process> processes = [];
var task = Task.Run(() =>
{
_listingProcesses.Value = processes;
return method();
});
if (!task.Wait(TimeSpan.FromSeconds(PackageListingTaskTimeout)))
{
if (
!allowDisablingTimeout
|| !Settings.Get(Settings.K.DisableTimeoutOnPackageListingTasks)
)
{
KillListingProcesses(processes);
CoreTools.FinalizeDangerousTask(task);
throw new TimeoutException(
$"Task {taskName} for manager {Name} did not finish after "
+ $"{PackageListingTaskTimeout} seconds, aborting."
+ (
allowDisablingTimeout
? " You may disable timeouts from UniGetUI Advanced Settings"
: ""
)
);
}
task.Wait();
}
return task.GetAwaiter().GetResult();
}
/// <summary>
/// Returns an array of Package objects that the manager lists for the given query. Depending on the manager, the list may
/// also include similar results. This method is fail-safe and will return an empty array if an error occurs.
/// </summary>
public IReadOnlyList<IPackage> FindPackages(string query) => _findPackages(query, false);
private IReadOnlyList<IPackage> _findPackages(string query, bool SecondAttempt)
{
if (!IsReady())
{
Logger.Warn($"Manager {Name} is disabled but yet FindPackages was called");
return [];
}
try
{
var packages = RunListingTaskWithTimeout(
() => FindPackages_UnSafe(query),
"_findPackages"
);
Logger.Info(
$"Found {packages.Count} available packages from {Name} with the query {query}"
);
return packages;
}
catch (Exception e)
{
while (e is AggregateException)
e = e.InnerException ?? new InvalidOperationException("How did we get here?");
if (!SecondAttempt && (RetryListingTasksOnTimeout || e is not TimeoutException))
{
Logger.Warn(
$"Manager {DisplayName} failed to find packages with exception {e.GetType().Name}: {e.Message}"
);
Logger.Warn(
$"Since this was the first attempt, {Name}.AttemptFastRepair() will be called and the procedure will be restarted"
);
AttemptFastRepair();
return _findPackages(query, true);
}
Logger.Error("Error finding packages on manager " + Name + " with query " + query);
Logger.Error(e);
return [];
}
}
/// <summary>
/// Returns an array of UpgradablePackage objects that represent the available updates reported by the manager.
/// This method is fail-safe and will return an empty array if an error occurs.
/// </summary>
public bool LastUpdatesListingFailed { get; private set; }
public IReadOnlyList<IPackage> GetAvailableUpdates()
{
LastUpdatesListingFailed = false;
return _getAvailableUpdates(false);
}
private IReadOnlyList<IPackage> _getAvailableUpdates(bool SecondAttempt)
{
if (!IsReady())
{
Logger.Warn($"Manager {Name} is disabled but yet GetAvailableUpdates was called");
return [];
}
try
{
if (!SecondAttempt)
{
RefreshPackageIndexesSafely();
}
var packages = RunListingTaskWithTimeout(
GetAvailableUpdates_UnSafe,
"_getAvailableUpdates"
);
Logger.Info($"Found {packages.Count} available updates from {Name}");
return packages;
}
catch (Exception e)
{
while (e is AggregateException)
e = e.InnerException ?? new InvalidOperationException("How did we get here?");
if (!SecondAttempt && (RetryListingTasksOnTimeout || e is not TimeoutException))
{
Logger.Warn(
$"Manager {DisplayName} failed to list available updates with exception {e.GetType().Name}: {e.Message}"
);
Logger.Warn(
$"Since this was the first attempt, {Name}.AttemptFastRepair() will be called and the procedure will be restarted"
);
AttemptFastRepair();
return _getAvailableUpdates(true);
}
Logger.Error("Error finding updates on manager " + Name);
Logger.Error(e);
LastUpdatesListingFailed = true;
return [];
}
}
/// <summary>
/// Returns an array of Package objects that represent the installed reported by the manager.
/// This method is fail-safe and will return an empty array if an error occurs.
/// </summary>
public bool LastInstalledListingFailed { get; private set; }
private long _installedPackagesGeneration;
public long InstalledPackagesGeneration => Volatile.Read(ref _installedPackagesGeneration);
public void InvalidateInstalledPackages() =>
Interlocked.Increment(ref _installedPackagesGeneration);
public IReadOnlyList<IPackage> GetInstalledPackages()
{
LastInstalledListingFailed = false;
return _getInstalledPackages(false);
}
private IReadOnlyList<IPackage> _getInstalledPackages(bool SecondAttempt)
{
if (!IsReady())
{
Logger.Warn($"Manager {Name} is disabled but yet GetInstalledPackages was called");
return [];
}
try
{
var packages = RunListingTaskWithTimeout(
GetInstalledPackages_UnSafe,
"_getInstalledPackages"
);
Logger.Info($"Found {packages.Count} installed packages from {Name}");
return packages;
}
catch (Exception e)
{
while (e is AggregateException)
e = e.InnerException ?? new InvalidOperationException("How did we get here?");
if (!SecondAttempt && (RetryListingTasksOnTimeout || e is not TimeoutException))
{
Logger.Warn(
$"Manager {DisplayName} failed to list installed packages with exception {e.GetType().Name}: {e.Message}"
);
Logger.Warn(
$"Since this was the first attempt, {Name}.AttemptFastRepair() will be called and the procedure will be restarted"
);
AttemptFastRepair();
return _getInstalledPackages(true);
}
Logger.Error("Error finding installed packages on manager " + Name);
Logger.Error(e);
LastInstalledListingFailed = true;
return [];
}
}
/// <summary>
/// Returns the available packages to install for the given query.
/// Each manager MUST implement this method.
/// </summary>
/// <param name="query">The query string to search for</param>
/// <returns>An array of Package objects</returns>
protected abstract IReadOnlyList<Package> FindPackages_UnSafe(string query);
/// <summary>
/// Returns the available updates reported by the manager.
/// Each manager MUST implement this method.
/// </summary>
/// <returns>An array of UpgradablePackage objects</returns>
protected abstract IReadOnlyList<Package> GetAvailableUpdates_UnSafe();
/// <summary>
/// Returns an array of Package objects containing the installed packages reported by the manager.
/// Each manager MUST implement this method.
/// </summary>
/// <returns>An array of Package objects</returns>
protected abstract IReadOnlyList<Package> GetInstalledPackages_UnSafe();
/// <summary>
/// Refreshes the Package Manager sources/indexes
/// Each manager MUST implement this method.
/// </summary>
public virtual void RefreshPackageIndexes()
{
Logger.Debug($"Manager {Name} has not implemented RefreshPackageIndexes");
}
/// <summary>
/// Attempt a live, fast, repair method when an exception occurs (for example, reconnect to COM Server)
/// </summary>
public virtual void AttemptFastRepair()
{
Logger.Debug($"Manager {Name} has not implemented AttemptFastRepair");
}
}
}