-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRunner.cs
More file actions
384 lines (335 loc) · 15.8 KB
/
Copy pathRunner.cs
File metadata and controls
384 lines (335 loc) · 15.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using CommandLine;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.EventLog;
using nanoFramework.IoT.TestRunner.Configuration;
using nanoFramework.IoT.TestRunner.Helpers;
using nanoFramework.IoT.TestRunner.TerminalGui;
using nanoFramework.IoT.TestRunner.UsbIp;
using System.Text.Json;
using System.Text.RegularExpressions;
using Terminal.Gui;
namespace nanoFramework.IoT.TestRunner
{
/// <summary>
/// Reprensent the main program.
/// </summary>
public class Runner
{
private static HardwareConfig? _hardwareConfiguration;
private static IHost _host;
/// <summary>
/// Gets or sets the return value.
/// </summary>
public static ErrorCode ErrorCode { get; set; } = ErrorCode.None;
/// <summary>
/// Gets or sets the state of usbipd.
/// </summary>
public static State? State { get; set; }
/// <summary>
/// Gets the overall configuration.
/// </summary>
public static OverallConfiguration? OverallConfiguration { get; internal set; }
/// <summary>
/// Gets the commandline options.
/// </summary>
public static CommandlineOptions Options { get; internal set; }
/// <summary>
/// Gets the logger.
/// </summary>
public static ILogger Logger { get; internal set; }
/// <summary>
/// Main program entry point.
/// </summary>
public static int Main(string[] args)
{
// Get things prepared for the logger and service
var builder = Host.CreateApplicationBuilder(args);
// To be adjusted for the proper level, here mainly for debugging
builder.Logging.AddEventLog(
eventLogSettings =>
{
eventLogSettings.LogName = "Application";
eventLogSettings.SourceName = "TestStream.Runner";
eventLogSettings.Filter = (category, level) =>
{
return level >= LogLevel.Information;
};
});
builder.Services.AddHostedService<Worker>();
LoggerProviderOptions.RegisterProviderOptions<
EventLogSettings, EventLogLoggerProvider>(builder.Services);
_host = builder.Build();
Logger = _host.Services.GetRequiredService<ILogger<Runner>>();
Parser.Default.ParseArguments<CommandlineOptions>(args)
.WithParsed<CommandlineOptions>(RunLogic)
.WithNotParsed(HandleErrors);
return (int)ErrorCode;
}
/// <summary>
/// Run the logic of the app with the given parameters.
/// </summary>
/// <param name="o">Parsed commandline options.</param>
private static void RunLogic(CommandlineOptions o)
{
Options = o;
// Check the configuration
if (!File.Exists(o.ConfigFilePath))
{
// Check if we can use the default configuration file in the same directory
if (File.Exists(Path.Combine(AppContext.BaseDirectory, "agent", "runner-configuration.json")))
{
o.ConfigFilePath = Path.Combine(AppContext.BaseDirectory, "agent", "runner-configuration.json");
}
else
{
Logger.LogError($"Configuration file not found: {o.ConfigFilePath}");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
}
// Check if the path to the hardware configuration file is different than the overall configuration
if (!string.IsNullOrEmpty(o.ConfigHardwareFilePath) && (Path.GetFullPath(o.ConfigFilePath) == Path.GetFullPath(o.ConfigHardwareFilePath)))
{
Logger.LogError("The path to the hardware configuration file is the same as the overall configuration file. You **must** use different path for security reasons.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
// Check the configuration
if (!File.Exists(o.ConfigHardwareFilePath))
{
// Chedck if the path is not empty
if (string.IsNullOrEmpty(o.ConfigHardwareFilePath))
{
// Create a default path in /agent/config
o.ConfigHardwareFilePath = Path.Combine(AppContext.BaseDirectory, "agent", "config", "configuration.json");
}
// Creates any missing directories
Directory.CreateDirectory(Path.GetDirectoryName(o.ConfigHardwareFilePath)!);
}
try
{
string jsonString = File.ReadAllText(o.ConfigHardwareFilePath);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
_hardwareConfiguration = JsonSerializer.Deserialize<HardwareConfig>(jsonString, options);
if (_hardwareConfiguration == null)
{
Logger.LogError("Hardware configuration did not deserialized successfully.");
}
else
{
Logger.LogInformation("Configuration deserialized successfully.");
// Print the capabilities
foreach (var capability in _hardwareConfiguration.Capabilities)
{
Logger.LogDebug($"Key: {capability.Key}, Value: {capability.Value}");
}
}
}
catch (Exception ex)
{
Logger.LogError($"An error occurred while deserializing the JSON file: {ex.Message}");
}
try
{
string jsonString = File.ReadAllText(o.ConfigFilePath);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
OverallConfiguration = JsonSerializer.Deserialize<OverallConfiguration>(jsonString, options);
if (OverallConfiguration != null)
{
Logger.LogInformation("Configuration deserialized successfully.");
}
else
{
Logger.LogError("Configuration is null or not valid.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
if (!o.Setup)
{
// Check that there is a token
if (string.IsNullOrEmpty(OverallConfiguration.Config.Token))
{
Logger.LogError("Token is not set in the configuration file.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
// Check that there is a github id
if (string.IsNullOrEmpty(OverallConfiguration.Config.GithubId))
{
Logger.LogError("GithubId is not set in the configuration file.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
// Check that there is an organization
if (string.IsNullOrEmpty(OverallConfiguration.Config.Org))
{
Logger.LogError("Organization is not set in the configuration file.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
// Check that there is a pool
if (string.IsNullOrEmpty(OverallConfiguration.Config.Pool))
{
Logger.LogError("Pool is not set in the configuration file.");
ErrorCode = ErrorCode.ConfigurationError;
return;
}
}
// Check if the agent name is set
if (string.IsNullOrEmpty(OverallConfiguration.Config.AgentName))
{
OverallConfiguration.Config.AgentName = OverallConfiguration.Config.GithubId;
}
}
catch (Exception ex)
{
Logger.LogError($"An error occurred while deserializing the JSON file: {ex.Message}");
}
if (o.Setup)
{
CreateSetup();
}
else
{
// Get the state of usbipd
State = UsbipProcessor.GetState();
if (State == null)
{
Logger.LogError("Can't get usbipd state. Make sure usbipd is properly installed.");
ErrorCode = ErrorCode.UsbipBindError;
return;
}
_host.Run();
}
}
/// <summary>
/// On parameter errors, we set the returnvalue to 1 to indicated an error.
/// </summary>
/// <param name="errors">List or errors (ignored).</param>
private static void HandleErrors(IEnumerable<Error> errors)
{
ErrorCode = ErrorCode.Other;
}
private static void CreateSetup()
{
Application.Init();
// Stop the service and install it if not
Application.Run<ServiceWindow>();
// Make sure we have the proper OverallConfiguration.Config
ConfigationWindow.OverallConfiguration = OverallConfiguration;
Application.Run<ConfigationWindow>();
// Save the configuration
var options = new JsonSerializerOptions
{
WriteIndented = true
};
OverallConfiguration = ConfigationWindow.OverallConfiguration;
File.WriteAllText(Options.ConfigFilePath, JsonSerializer.Serialize(OverallConfiguration, options));
// Going through the setup for WSL if needed, check with 'wsl -v' if it is installed
var isInWSL = ProcessHelpers.RunCommand("wsl", "-v");
bool isInstalled = false;
if (!string.IsNullOrEmpty(isInWSL))
{
// Check if the version is 2.x.x.x
isInstalled = Regex.IsMatch(isInWSL, @"WSL version: 2\.\d+\.\d+\.\d+");
}
if (!isInstalled)
{
var res = MessageBox.Query("WSL Installation", "WSL is not installed. Do you want to install WSL2 before continuing with Docker and all the needed elements?", "Yes", "No");
if (res == 0)
{
var install = ProcessHelpers.RunCommand("powershell.exe",
$"-ExecutionPolicy Restricted -ExecutionPolicy Bypass -File \"{Path.Combine(AppContext.BaseDirectory, "agent", "install.ps1")}\" -WSLDistribution {OverallConfiguration.Config.WslDistribution}",
outputConsole: true,
useShell: true);
}
}
else
{
// Check if the distribution is installed
var installed = ProcessHelpers.RunCommand("wsl", "-l -q");
if (!installed.Contains(OverallConfiguration.Config.WslDistribution))
{
var res = MessageBox.Query("WSL Distribution Installation", "WSL distribution is not installed. Do you want to install it before continuing with Docker and all the needed elements?", "Yes", "No");
if (res == 0)
{
var install = ProcessHelpers.RunCommand("powershell.exe",
$"-ExecutionPolicy Restricted -ExecutionPolicy Bypass -File \"{Path.Combine(AppContext.BaseDirectory, "agent", "install.ps1")}\" -WSLDistribution {OverallConfiguration.Config.WslDistribution}",
outputConsole: true,
useShell: true);
res = MessageBox.Query("WSL Distribution Installation", "If you saw that the system needs to be rebooted, please click reboot and rerun this setup.", "Reboot", "Continue");
if (res == 0)
{
ProcessHelpers.RunCommand("shutdown", "/r /t 0", useShell: true);
}
}
}
}
// Check if USBIP is installed
var usbipInstalled = ProcessHelpers.RunCommand("usbipd", "--version");
if (!usbipInstalled.StartsWith("4.3.0"))
{
var res = MessageBox.Query("USBIP Installation", "USBIP is not installed. Do you want to install it before continuing with Docker and all the needed elements?", "Yes", "No");
if (res == 0)
{
var install = ProcessHelpers.RunCommand("powershell.exe",
$"-ExecutionPolicy Restricted -ExecutionPolicy Bypass -File \"{Path.Combine(AppContext.BaseDirectory, "agent", "install.ps1")}\" -SkipWSLInstallation -SkipDockerInstallation",
outputConsole: true,
useShell: true);
}
}
// Check if Docker is installed
var dockerInstalled = ProcessHelpers.RunCommand("wsl", "docker --version");
if (string.IsNullOrEmpty(dockerInstalled))
{
var res = MessageBox.Query("Doncker Installation", "Docker is not installed. Do you want to install it before continuing with Docker and all the needed elements?", "Yes", "No");
if (res == 0)
{
var install = ProcessHelpers.RunCommand("powershell.exe",
$"-ExecutionPolicy Restricted -ExecutionPolicy Bypass -File \"{Path.Combine(AppContext.BaseDirectory, "agent", "install.ps1")}\" -SkipWSLInstallation -SkipUSBIPDInstallation",
outputConsole: true,
useShell: true);
}
}
var previousHardware = OverallConfiguration!.Hardware;
Application.Run<DeviceWindow>();
// Save the configuration
File.WriteAllText(Options.ConfigFilePath, JsonSerializer.Serialize(OverallConfiguration,
new JsonSerializerOptions
{
WriteIndented = true
}
));
// Make sure the configuration class is created
if (_hardwareConfiguration == null)
{
_hardwareConfiguration = new HardwareConfig();
_hardwareConfiguration.Capabilities = new Dictionary<string, string>();
}
// Write also the agent configuration capabilities
// We do not override anything as it is possible to setup multiple firmware with the same serial port
// The adjustment will have to be done by the user
if (DeviceWindow.NewHardware is not null)
{
_hardwareConfiguration.Capabilities.Add(DeviceWindow.NewHardware.Firmware, DeviceWindow.NewHardware.Port);
}
File.WriteAllText(Options.ConfigHardwareFilePath, JsonSerializer.Serialize(_hardwareConfiguration, new JsonSerializerOptions
{
WriteIndented = true
}));
Application.Run<DockerBuildWindows>();
Application.Shutdown();
}
}
}