-
-
Notifications
You must be signed in to change notification settings - Fork 551
Expand file tree
/
Copy pathRunningPackageService.cs
More file actions
320 lines (273 loc) · 11 KB
/
RunningPackageService.cs
File metadata and controls
320 lines (273 loc) · 11 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
using System.Collections.Immutable;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using FluentAvalonia.UI.Controls;
using Injectio.Attributes;
using KeyedSemaphores;
using Microsoft.Extensions.Logging;
using Nito.Disposables.Internals;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.ViewModels;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper.Factory;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Avalonia.Services;
[RegisterSingleton<RunningPackageService>]
public partial class RunningPackageService(
ILogger<RunningPackageService> logger,
IPackageFactory packageFactory,
INotificationService notificationService,
ISettingsManager settingsManager,
IPyRunner pyRunner
) : ObservableObject, IDisposable
{
/// <summary>
/// Locks for starting or stopping packages.
/// </summary>
private readonly KeyedSemaphoresDictionary<Guid> packageLocks = new();
// 🤔 what if we put the ConsoleViewModel inside the BasePackage? 🤔
[ObservableProperty]
private ObservableDictionary<Guid, RunningPackageViewModel> runningPackages = [];
public async Task<PackagePair?> StartPackage(
InstalledPackage installedPackage,
string? command = null,
CancellationToken cancellationToken = default
)
{
// Get lock
using var _ = await packageLocks.LockAsync(installedPackage.Id, cancellationToken);
// Ignore if already running after lock
if (RunningPackages.ContainsKey(installedPackage.Id))
{
logger.LogWarning("Skipping StartPackage, already running: {Id}", installedPackage.Id);
return null;
}
var activeInstallName = installedPackage.PackageName;
var basePackage = string.IsNullOrWhiteSpace(activeInstallName)
? null
: packageFactory.GetNewBasePackage(installedPackage);
if (basePackage == null)
{
logger.LogWarning(
"During launch, package name '{PackageName}' did not match a definition",
activeInstallName
);
notificationService.Show(
new Notification(
"Package name invalid",
"Install package name did not match a definition. Please reinstall and let us know about this issue.",
NotificationType.Error
)
);
return null;
}
// Show warning if critical vulnerabilities are found
if (basePackage.HasCriticalVulnerabilities)
{
var vulns = basePackage
.KnownVulnerabilities.Where(v => v.Severity == VulnerabilitySeverity.Critical)
.Select(v =>
$"**{v.Id}**: {v.Title}\n - Severity: {v.Severity}\n - Description: {v.Description}"
)
.ToList();
var message =
$"# ⚠️ Critical Security Vulnerabilities\n\nThis package has critical security vulnerabilities that may put your system at risk:\n\n{string.Join("\n\n", vulns)}";
message +=
"\n\nFor more information, please visit the [GitHub Security Advisory page](https://github.com/LykosAI/StabilityMatrix/security/advisories).";
var dialog = DialogHelper.CreateMarkdownDialog(message, "Security Warning");
dialog.IsPrimaryButtonEnabled = false;
dialog.PrimaryButtonText = "Continue Anyway (3)";
dialog.CloseButtonText = Resources.Action_Cancel;
dialog.DefaultButton = ContentDialogButton.Close;
// Start a timer to enable the button after 3 seconds
var countdown = 3;
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (_, _) =>
{
Dispatcher.UIThread.Post(() =>
{
countdown--;
if (countdown <= 0)
{
dialog.IsPrimaryButtonEnabled = true;
dialog.PrimaryButtonText = "Continue Anyway";
timer.Stop();
timer.Dispose();
}
else
{
dialog.PrimaryButtonText = $"Continue Anyway ({countdown})";
}
});
};
timer.Start();
var result = await dialog.ShowAsync();
if (result != ContentDialogResult.Primary)
{
return null;
}
}
// Show warning if any vulnerabilities are found
else if (basePackage.HasVulnerabilities)
{
var vulns = basePackage
.KnownVulnerabilities.Select(v =>
$"**{v.Id}**: {v.Title}\n - Severity: {v.Severity}\n - Description: {v.Description}"
)
.ToList();
var message =
$"# ⚠️ Security Notice\n\nThis package has known vulnerabilities:\n\n{string.Join("\n\n", vulns)}";
message +=
"\n\nFor more information, please visit the [GitHub Security Advisory page](https://github.com/LykosAI/StabilityMatrix/security/advisories).";
var dialog = DialogHelper.CreateMarkdownDialog(message, "Security Notice");
dialog.IsPrimaryButtonEnabled = false;
dialog.PrimaryButtonText = "Continue Anyway (3)";
dialog.CloseButtonText = Resources.Action_Cancel;
dialog.DefaultButton = ContentDialogButton.Close;
// Start a timer to enable the button after 3 seconds
var countdown = 3;
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (_, _) =>
{
Dispatcher.UIThread.Post(() =>
{
countdown--;
if (countdown <= 0)
{
dialog.IsPrimaryButtonEnabled = true;
dialog.PrimaryButtonText = "Continue Anyway";
timer.Stop();
timer.Dispose();
}
else
{
dialog.PrimaryButtonText = $"Continue Anyway ({countdown})";
}
});
};
timer.Start();
var result = await dialog.ShowAsync();
if (result != ContentDialogResult.Primary)
{
return null;
}
}
// If this is the first launch (LaunchArgs is null),
// load and save a launch options dialog vm
// so that dynamic initial values are saved.
if (installedPackage.LaunchArgs == null)
{
var definitions = basePackage.LaunchOptions;
// Create config cards and save them
var cards = LaunchOptionCard
.FromDefinitions(definitions, Array.Empty<LaunchOption>())
.ToImmutableArray();
var args = cards.SelectMany(c => c.Options).ToList();
logger.LogDebug(
"Setting initial launch args: {Args}",
string.Join(", ", args.Select(o => o.ToArgString()?.ToRepr()))
);
settingsManager.SaveLaunchArgs(installedPackage.Id, args);
}
if (basePackage is not StableSwarm)
{
await pyRunner.Initialize();
}
// Get path from package
var packagePath = new DirectoryPath(settingsManager.LibraryDir, installedPackage.LibraryPath!);
if (basePackage is not StableSwarm)
{
// Unpack sitecustomize.py to venv
await UnpackSiteCustomize(packagePath.JoinDir("venv"));
}
// Clear console and start update processing
var console = new ConsoleViewModel();
console.StartUpdates();
// Update shared folder links (in case library paths changed)
await basePackage.UpdateModelFolders(
packagePath,
installedPackage.PreferredSharedFolderMethod ?? basePackage.RecommendedSharedFolderMethod
);
if (installedPackage.UseSharedOutputFolder)
{
await basePackage.SetupOutputFolderLinks(installedPackage.FullPath!);
}
// Load user launch args from settings
var launchArgStrings = (installedPackage.LaunchArgs ?? [])
.Select(option => option.ToArgString())
.WhereNotNull()
.ToArray();
var launchProcessArgs = ProcessArgs.FromQuoted(launchArgStrings);
var runPackageOptions = new RunPackageOptions { Command = command, Arguments = launchProcessArgs };
// Join with extras, if any
await basePackage.RunPackage(
packagePath,
installedPackage,
runPackageOptions,
console.Post,
cancellationToken
);
var runningPackage = new PackagePair(installedPackage, basePackage);
var viewModel = new RunningPackageViewModel(
settingsManager,
notificationService,
this,
runningPackage,
runPackageOptions,
console
);
RunningPackages.Add(runningPackage.InstalledPackage.Id, viewModel);
return runningPackage;
}
public async Task StopPackage(Guid id, CancellationToken cancellationToken = default)
{
// Get lock
using var _ = await packageLocks.LockAsync(id, cancellationToken);
// Ignore if not running after lock
if (!RunningPackages.TryGetValue(id, out var vm))
{
logger.LogWarning("Skipping StopPackage, not running: {Id}", id);
return;
}
var runningPackage = vm.RunningPackage;
await runningPackage.BasePackage.WaitForShutdown();
await vm.DisposeAsync();
RunningPackages.Remove(id);
}
public RunningPackageViewModel? GetRunningPackageViewModel(Guid id) =>
RunningPackages.TryGetValue(id, out var vm) ? vm : null;
private static async Task UnpackSiteCustomize(DirectoryPath venvPath)
{
var sitePackages = venvPath.JoinDir(PyVenvRunner.RelativeSitePackagesPath);
var file = sitePackages.JoinFile("sitecustomize.py");
file.Directory?.Create();
await Assets.PyScriptSiteCustomize.ExtractTo(file, true);
}
public void Dispose()
{
var exceptions = new List<Exception>();
foreach (var (_, vm) in RunningPackages)
{
try
{
vm.Dispose();
}
catch (Exception e)
{
exceptions.Add(e);
}
}
if (exceptions.Count != 0)
{
throw new AggregateException(exceptions);
}
GC.SuppressFinalize(this);
}
}