-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathRunCommand.cs
More file actions
287 lines (245 loc) · 12.2 KB
/
RunCommand.cs
File metadata and controls
287 lines (245 loc) · 12.2 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
using System.CommandLine;
using DeveloperCli.Installation;
using DeveloperCli.Utilities;
using Spectre.Console;
namespace DeveloperCli.Commands;
/// <summary>
/// Command to manage Aspire AppHost lifecycle - start, stop, and monitor the application host.
/// </summary>
public class RunCommand : Command
{
private const int AspirePort = 9001;
private const int DashboardPort = 9097;
private const int ResourceServicePort = 9098;
public RunCommand() : base("run", "Runs Aspire AppHost (use --watch for hot reload)")
{
var watchOption = new Option<bool>("--watch", "-w") { Description = "Enable watch mode for hot reload" };
var forceOption = new Option<bool>("--force") { Description = "Force start a fresh Aspire AppHost instance, stopping any existing one" };
var stopOption = new Option<bool>("--stop") { Description = "Stop any running Aspire AppHost instance without starting a new one" };
var attachOption = new Option<bool>("--attach", "-a") { Description = "Keep the CLI process attached to the Aspire process" };
var detachOption = new Option<bool>("--detach", "-d") { Description = "Run the Aspire process in detached mode (background)" };
var publicUrlOption = new Option<string?>("--public-url") { Description = "Set the PUBLIC_URL environment variable for the app (e.g., https://example.ngrok-free.app)" };
Options.Add(watchOption);
Options.Add(forceOption);
Options.Add(stopOption);
Options.Add(attachOption);
Options.Add(detachOption);
Options.Add(publicUrlOption);
SetAction(parseResult => Execute(
parseResult.GetValue(watchOption),
parseResult.GetValue(forceOption),
parseResult.GetValue(stopOption),
parseResult.GetValue(attachOption),
parseResult.GetValue(detachOption),
parseResult.GetValue(publicUrlOption)
)
);
}
private static void Execute(bool watch, bool force, bool stop, bool attach, bool detach, string? publicUrl)
{
Prerequisite.Ensure(Prerequisite.Dotnet, Prerequisite.Node, Prerequisite.Docker);
var isRunning = IsAspireRunning();
if (stop)
{
StopAspire();
return;
}
// Validate that either --attach or --detach is specified (but not both)
if (attach == detach)
{
AnsiConsole.MarkupLine("[red]You must specify either --attach (-a) or --detach (-d) mode.[/]");
Environment.Exit(1);
}
if (isRunning)
{
if (!force)
{
AnsiConsole.MarkupLine($"[yellow]Aspire AppHost is already running on port {AspirePort}. Use --force to force a fresh start or --stop to stop it.[/]");
Environment.Exit(1);
}
StopAspire();
}
StartAspireAppHost(watch, attach, publicUrl);
}
private static bool IsAspireRunning()
{
// Check the main Aspire port
if (Configuration.IsWindows)
{
// Windows: Check all Aspire ports
var aspirePortsToCheck = new[] { AspirePort, DashboardPort, ResourceServicePort };
foreach (var port in aspirePortsToCheck)
{
var portCheckCommand = $"""powershell -Command "Get-NetTCPConnection -LocalPort {port} -State Listen -ErrorAction SilentlyContinue" """;
var result = ProcessHelper.StartProcess(portCheckCommand, redirectOutput: true, exitOnError: false);
if (!string.IsNullOrWhiteSpace(result))
{
return true;
}
}
}
else
{
// macOS/Linux: Original logic - only check main port
var portCheckCommand = $"lsof -i :{AspirePort} -sTCP:LISTEN -t";
var result = ProcessHelper.StartProcess(portCheckCommand, redirectOutput: true, exitOnError: false);
if (!string.IsNullOrWhiteSpace(result))
{
return true;
}
}
// Also check if there are any dotnet processes running AppHost (both run and watch modes)
if (Configuration.IsWindows)
{
// Check if any dotnet.exe processes are running with AppHost in the command line
var appHostProcesses = ProcessHelper.StartProcess("""powershell -Command "Get-Process dotnet -ErrorAction SilentlyContinue | Where-Object {$_.CommandLine -like '*AppHost*'} | Select-Object Id" """, redirectOutput: true, exitOnError: false);
return !string.IsNullOrWhiteSpace(appHostProcesses) && appHostProcesses.Contains("Id");
}
else
{
var appHostProcesses = ProcessHelper.StartProcess("pgrep -f dotnet.*AppHost", redirectOutput: true, exitOnError: false);
return !string.IsNullOrWhiteSpace(appHostProcesses);
}
}
private static void StopAspire()
{
AnsiConsole.MarkupLine("[blue]Stopping Aspire AppHost and all related services...[/]");
if (Configuration.IsWindows)
{
// Kill all dotnet and rsbuild-node processes on ports 9000-9999
var netstatOutput = ProcessHelper.StartProcess("""cmd /c "netstat -ano | findstr LISTENING" """, redirectOutput: true, exitOnError: false);
if (!string.IsNullOrWhiteSpace(netstatOutput))
{
var processedPids = new HashSet<string>();
foreach (var line in netstatOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 5) continue;
var address = parts[1];
var portIndex = address.LastIndexOf(':');
if (portIndex == -1) continue;
if (!int.TryParse(address[(portIndex + 1)..], out var port) || port < 9000 || port > 9999) continue;
var pid = parts[^1];
if (!processedPids.Add(pid)) continue;
var processName = ProcessHelper.StartProcess($"""wmic process where ProcessId={pid} get Name /format:list""", redirectOutput: true, exitOnError: false);
if (processName.Contains("dotnet", StringComparison.OrdinalIgnoreCase) ||
processName.Contains("rsbuild-node", StringComparison.OrdinalIgnoreCase))
{
ProcessHelper.StartProcess($"taskkill /F /PID {pid}", redirectOutput: true, exitOnError: false);
}
}
}
// Kill specific Aspire-related processes
var processesToKill = new[] { "Aspire.Dashboard", "dcp", "dcpproc" };
foreach (var processName in processesToKill)
{
ProcessHelper.StartProcess($"taskkill /F /IM {processName}.exe", redirectOutput: true, exitOnError: false);
}
}
else
{
// Kill all processes on ports 9000-9999 that belong to our application
var pidsOutput = ProcessHelper.StartProcess("lsof -i :9000-9999 -sTCP:LISTEN -t", redirectOutput: true, exitOnError: false);
if (!string.IsNullOrWhiteSpace(pidsOutput))
{
foreach (var pid in pidsOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
// Use full command line (args) since comm= truncates names on Linux
var commandLine = ProcessHelper.StartProcess($"ps -p {pid} -o args=", redirectOutput: true, exitOnError: false).Trim();
if (string.IsNullOrWhiteSpace(commandLine)) continue;
if (commandLine.Contains(Configuration.SourceCodeFolder, StringComparison.OrdinalIgnoreCase))
{
ProcessHelper.StartProcess($"kill -9 {pid}", redirectOutput: true, exitOnError: false);
}
}
}
}
// Wait a moment for processes to terminate
Thread.Sleep(TimeSpan.FromSeconds(2));
AnsiConsole.MarkupLine("[green]Aspire AppHost stopped successfully.[/]");
}
private static void StartAspireAppHost(bool watch, bool attach, string? publicUrl)
{
var mode = watch ? "watch" : "run";
AnsiConsole.MarkupLine($"[blue]Starting Aspire AppHost in {mode} mode ({(attach ? "attached" : "detached")})...[/]");
if (publicUrl is not null)
{
AnsiConsole.MarkupLine($"[blue]Using PUBLIC_URL: {publicUrl}[/]");
// Check if this is an ngrok URL and start ngrok if needed
if (publicUrl.Contains(".ngrok-free.app", StringComparison.OrdinalIgnoreCase) ||
publicUrl.Contains(".ngrok.io", StringComparison.OrdinalIgnoreCase))
{
StartNgrokIfNeeded(publicUrl);
}
}
var appHostProjectPath = Path.Combine(Configuration.ApplicationFolder, "AppHost", "AppHost.csproj");
var command = watch
? $"dotnet watch --non-interactive --project {appHostProjectPath}"
: $"dotnet run --project {appHostProjectPath}";
if (!attach && Configuration.IsWindows)
{
// For Windows in detached mode, use "start" command to truly detach
var detachedCommand = $"cmd /c start \"Aspire AppHost\" /min {command}";
ProcessHelper.StartProcess(
publicUrl is not null ? $"{detachedCommand} --environment PUBLIC_URL={publicUrl}" : detachedCommand,
Configuration.ApplicationFolder,
waitForExit: false
);
// Give it a moment to start
Thread.Sleep(2000);
AnsiConsole.MarkupLine("[green]Aspire AppHost started in detached mode.[/]");
}
else
{
// Attached mode or non-Windows
if (publicUrl is not null)
{
ProcessHelper.StartProcess(command, Configuration.ApplicationFolder, waitForExit: attach, environmentVariables: ("PUBLIC_URL", publicUrl));
}
else
{
ProcessHelper.StartProcess(command, Configuration.ApplicationFolder, waitForExit: attach);
}
}
}
private static void StartNgrokIfNeeded(string publicUrl)
{
// First check if ngrok is installed
var ngrokVersion = ProcessHelper.StartProcess("ngrok version", redirectOutput: true, exitOnError: false);
if (!ngrokVersion.Contains("ngrok version", StringComparison.OrdinalIgnoreCase))
{
AnsiConsole.MarkupLine("[yellow]Ngrok is not installed. Please install ngrok from https://ngrok.com/download[/]");
AnsiConsole.MarkupLine("[yellow]Continuing without ngrok tunnel...[/]");
return;
}
// Extract the subdomain from the URL
var uri = new Uri(publicUrl);
var subdomain = uri.Host.Split('.')[0];
// Check if ngrok is already running
bool isNgrokRunning;
if (Configuration.IsWindows)
{
var ngrokProcesses = ProcessHelper.StartProcess("""tasklist /FI "IMAGENAME eq ngrok.exe" """, redirectOutput: true, exitOnError: false);
isNgrokRunning = ngrokProcesses.Contains("ngrok.exe");
}
else
{
var ngrokProcesses = ProcessHelper.StartProcess("pgrep -f ngrok", redirectOutput: true, exitOnError: false);
isNgrokRunning = !string.IsNullOrEmpty(ngrokProcesses);
}
if (isNgrokRunning)
{
AnsiConsole.MarkupLine("[yellow]Ngrok is already running.[/]");
return;
}
AnsiConsole.MarkupLine("[blue]Starting ngrok tunnel...[/]");
// Start ngrok in detached mode
var ngrokCommand = $"ngrok http --url={subdomain}.ngrok-free.app https://localhost:9000";
// Use shell to handle backgrounding properly on macOS/Linux
ProcessHelper.StartProcess(
Configuration.IsWindows ? $"start /B {ngrokCommand}" : $"sh -c \"{ngrokCommand} > /dev/null 2>&1 &\"",
waitForExit: false
);
AnsiConsole.MarkupLine("[green]Ngrok tunnel started successfully.[/]");
}
}