-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatusManager.cs
More file actions
392 lines (348 loc) · 15.1 KB
/
StatusManager.cs
File metadata and controls
392 lines (348 loc) · 15.1 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.Win32;
namespace BootstrapMate
{
public enum InstallationStage
{
Starting,
Running,
Completed,
Failed,
Skipped
}
public enum InstallationPhase
{
SetupAssistant,
Userland
}
public class InstallationStatus
{
public InstallationStage Stage { get; set; }
public string StartTime { get; set; } = "";
public string CompletionTime { get; set; } = "";
public int ExitCode { get; set; }
public string Version { get; set; } = "2025.08.30.1300";
public InstallationPhase Phase { get; set; }
public string Architecture { get; set; } = "";
public string BootstrapUrl { get; set; } = "";
public string LastError { get; set; } = "";
public string RunId { get; set; } = "";
}
public static class StatusManager
{
private const string BASE_REGISTRY_PATH = @"SOFTWARE\Cimian\BootstrapMate\Status";
private const string VERSION_REGISTRY_PATH = @"SOFTWARE\Cimian\BootstrapMate";
private const string STATUS_FILE_PATH = @"C:\ProgramData\ManagedBootstrap\status.json";
private static string _currentRunId = Guid.NewGuid().ToString();
private static string _bootstrapUrl = "";
private static string _version = "1.0.0"; // Default fallback version
public static void Initialize(string bootstrapUrl = "", string version = "1.0.0")
{
_bootstrapUrl = bootstrapUrl;
_version = version;
_currentRunId = Guid.NewGuid().ToString();
// Ensure status directory exists
var statusDir = Path.GetDirectoryName(STATUS_FILE_PATH);
if (statusDir != null && !Directory.Exists(statusDir))
{
Directory.CreateDirectory(statusDir);
}
// Don't write version to registry here - only write it after successful completion
}
public static string GetCurrentRunId()
{
return _currentRunId;
}
public static void SetPhaseStatus(InstallationPhase phase, InstallationStage stage, string errorMessage = "", int exitCode = 0)
{
try
{
var status = new InstallationStatus
{
Stage = stage,
Version = _version,
Phase = phase,
Architecture = GetArchitecture(),
BootstrapUrl = _bootstrapUrl,
RunId = _currentRunId,
ExitCode = exitCode,
LastError = errorMessage
};
// Set timestamps based on stage
switch (stage)
{
case InstallationStage.Starting:
case InstallationStage.Running:
status.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
break;
case InstallationStage.Completed:
case InstallationStage.Failed:
case InstallationStage.Skipped:
if (string.IsNullOrEmpty(status.StartTime))
{
status.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
status.CompletionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
break;
}
// Write to both registry views (64-bit and 32-bit)
WriteRegistryStatus(phase, status);
// Write status file for troubleshooting
WriteStatusFile(phase, status);
WriteLog($"Status updated: {phase} = {stage}" +
(exitCode != 0 ? $" (ExitCode: {exitCode})" : "") +
(!string.IsNullOrEmpty(errorMessage) ? $" - {errorMessage}" : ""));
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to update status for {phase}: {ex.Message}");
// Don't throw - status tracking failure shouldn't break the main process
}
}
public static void WriteSuccessfulCompletionRegistry()
{
try
{
var values = new Dictionary<string, object>
{
{ "LastRunVersion", _version }
};
// Write to both 64-bit and 32-bit registry views
WriteRegistryBothViews(VERSION_REGISTRY_PATH, values);
WriteLog($"Successful completion: LastRunVersion {_version} written to registry");
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to write completion status to registry: {ex.Message}");
}
}
private static void WriteVersionToRegistry(string version)
{
try
{
var values = new Dictionary<string, object>
{
{ "Version", version },
{ "LastUpdated", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
{ "Architecture", GetArchitecture() }
};
// Write to both 64-bit and 32-bit registry views
WriteRegistryBothViews(VERSION_REGISTRY_PATH, values);
WriteLog($"Version {version} written to registry");
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to write version to registry: {ex.Message}");
}
}
private static void WriteRegistryStatus(InstallationPhase phase, InstallationStatus status)
{
var phaseName = phase.ToString();
var subKey = $@"{BASE_REGISTRY_PATH}\{phaseName}";
var values = new Dictionary<string, object>
{
{ "Stage", status.Stage.ToString() },
{ "StartTime", status.StartTime },
{ "CompletionTime", status.CompletionTime },
{ "ExitCode", status.ExitCode },
{ "Phase", status.Phase.ToString().ToLowerInvariant() },
{ "Architecture", status.Architecture },
{ "BootstrapUrl", status.BootstrapUrl },
{ "LastError", status.LastError },
{ "RunId", status.RunId }
};
// Write to both 64-bit and 32-bit registry views
WriteRegistryBothViews(subKey, values);
}
private static void WriteRegistryBothViews(string subKey, Dictionary<string, object> values)
{
var views = new[] { RegistryView.Registry64, RegistryView.Registry32 };
foreach (var view in views)
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
using var key = baseKey.CreateSubKey(subKey, true);
if (key != null)
{
foreach (var kv in values)
{
if (kv.Value is int intValue)
{
key.SetValue(kv.Key, intValue, RegistryValueKind.DWord);
}
else
{
key.SetValue(kv.Key, kv.Value?.ToString() ?? "", RegistryValueKind.String);
}
}
}
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to write to {view} registry: {ex.Message}");
}
}
}
private static void WriteStatusFile(InstallationPhase phase, InstallationStatus status)
{
try
{
// Read existing status file or create new structure
var statusData = new Dictionary<string, InstallationStatus>();
if (File.Exists(STATUS_FILE_PATH))
{
var json = File.ReadAllText(STATUS_FILE_PATH);
var existing = JsonSerializer.Deserialize<Dictionary<string, InstallationStatus>>(json);
if (existing != null)
{
statusData = existing;
}
}
// Update the specific phase
statusData[phase.ToString()] = status;
// Write back to file
var options = new JsonSerializerOptions { WriteIndented = true };
var updatedJson = JsonSerializer.Serialize(statusData, options);
File.WriteAllText(STATUS_FILE_PATH, updatedJson);
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to write status file: {ex.Message}");
}
}
private static string GetArchitecture()
{
// Use OSArchitecture so the x64 binary running under ARM64 emulation reports ARM64
return RuntimeInformation.OSArchitecture.ToString().ToUpperInvariant();
}
public static InstallationStatus GetPhaseStatus(InstallationPhase phase)
{
try
{
var phaseName = phase.ToString();
var subKey = $@"{BASE_REGISTRY_PATH}\{phaseName}";
// Try 64-bit view first, then 32-bit
var views = new[] { RegistryView.Registry64, RegistryView.Registry32 };
foreach (var view in views)
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
using var key = baseKey.OpenSubKey(subKey);
if (key != null)
{
var status = new InstallationStatus
{
Stage = Enum.TryParse<InstallationStage>(key.GetValue("Stage")?.ToString() ?? "", out var stage) ? stage : InstallationStage.Starting,
StartTime = key.GetValue("StartTime")?.ToString() ?? "",
CompletionTime = key.GetValue("CompletionTime")?.ToString() ?? "",
ExitCode = (int)(key.GetValue("ExitCode") ?? 0),
Version = _version, // Use current version instead of stored version
Phase = Enum.TryParse<InstallationPhase>(key.GetValue("Phase")?.ToString() ?? "", true, out var phaseValue) ? phaseValue : phase,
Architecture = key.GetValue("Architecture")?.ToString() ?? "",
BootstrapUrl = key.GetValue("BootstrapUrl")?.ToString() ?? "",
LastError = key.GetValue("LastError")?.ToString() ?? "",
RunId = key.GetValue("RunId")?.ToString() ?? ""
};
return status;
}
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to read from {view} registry: {ex.Message}");
}
}
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to get status for {phase}: {ex.Message}");
}
// Return default status if not found
return new InstallationStatus
{
Stage = InstallationStage.Starting,
Phase = phase,
Architecture = GetArchitecture()
};
}
public static void CleanupOldStatuses(TimeSpan maxAge)
{
try
{
// Only clean up statuses that are older than maxAge and not "Running"
foreach (InstallationPhase phase in Enum.GetValues<InstallationPhase>())
{
var status = GetPhaseStatus(phase);
if (status.Stage != InstallationStage.Running &&
!string.IsNullOrEmpty(status.CompletionTime) &&
DateTime.TryParse(status.CompletionTime, out var completionTime) &&
DateTime.Now - completionTime > maxAge)
{
// Clean up this old status
DeletePhaseStatus(phase);
WriteLog($"Cleaned up old status for {phase} (completed: {completionTime})");
}
}
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to cleanup old statuses: {ex.Message}");
}
}
private static void DeletePhaseStatus(InstallationPhase phase)
{
try
{
var phaseName = phase.ToString();
var subKey = $@"{BASE_REGISTRY_PATH}\{phaseName}";
var views = new[] { RegistryView.Registry64, RegistryView.Registry32 };
foreach (var view in views)
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
baseKey.DeleteSubKeyTree(subKey, false);
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to delete {view} registry key: {ex.Message}");
}
}
}
catch (Exception ex)
{
WriteLog($"Warning: Failed to delete status for {phase}: {ex.Message}");
}
}
// Helper method to integrate with existing logging
private static void WriteLog(string message)
{
try
{
// Try to use the existing WriteLog method if available through reflection
var programType = typeof(Program);
var writeLogMethod = programType.GetMethod("WriteLog",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (writeLogMethod != null)
{
writeLogMethod.Invoke(null, new object[] { $"[StatusManager] {message}" });
}
else
{
// Fallback to console if WriteLog method not found
Console.WriteLine($"[StatusManager] {message}");
}
}
catch
{
// Silent fallback to console
Console.WriteLine($"[StatusManager] {message}");
}
}
}
}