| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Runtime.InteropServices; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.Extensions.Configuration; |
| | | 5 | | using Serilog; |
| | | 6 | | |
| | | 7 | | namespace NLightning.Node.Utilities; |
| | | 8 | | |
| | | 9 | | using Constants; |
| | | 10 | | |
| | | 11 | | public partial class DaemonUtils |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Starts the application as a daemon process if requested |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="args">Command line arguments</param> |
| | | 17 | | /// <param name="configuration">Configuration</param> |
| | | 18 | | /// <param name="pidFilePath">Path where to store the PID file</param> |
| | | 19 | | /// <param name="logger">Logger for startup messages</param> |
| | | 20 | | /// <returns>True if the parent process should exit, false to continue execution</returns> |
| | | 21 | | public static bool StartDaemonIfRequested(string[] args, IConfiguration configuration, string pidFilePath, ILogger l |
| | | 22 | | { |
| | | 23 | | // Check if we're already running as a daemon child process |
| | 0 | 24 | | if (IsRunningAsDaemon()) |
| | | 25 | | { |
| | 0 | 26 | | return false; // Continue execution as daemon child |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | // Check command line args (highest priority) |
| | 0 | 30 | | var isDaemonRequested = Array.Exists(args, arg => |
| | 0 | 31 | | arg.Equals("--daemon", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 32 | | arg.Equals("--daemon=true", StringComparison.OrdinalIgnoreCase)); |
| | | 33 | | |
| | | 34 | | // Check environment variable (middle priority) |
| | 0 | 35 | | if (!isDaemonRequested) |
| | | 36 | | { |
| | 0 | 37 | | var envDaemon = Environment.GetEnvironmentVariable("NLTG_DAEMON"); |
| | 0 | 38 | | isDaemonRequested = !string.IsNullOrEmpty(envDaemon) && |
| | 0 | 39 | | (envDaemon.Equals("true", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 40 | | envDaemon.Equals("1", StringComparison.OrdinalIgnoreCase)); |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | // Check configuration file (lowest priority) |
| | 0 | 44 | | if (!isDaemonRequested) |
| | | 45 | | { |
| | 0 | 46 | | isDaemonRequested = configuration.GetValue<bool>("Node:Daemon"); |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | if (!isDaemonRequested) |
| | | 50 | | { |
| | 0 | 51 | | return false; // Continue normal execution |
| | | 52 | | } |
| | | 53 | | |
| | 0 | 54 | | logger.Information("Daemon mode requested, starting background process"); |
| | | 55 | | |
| | | 56 | | // Platform-specific daemon implementation |
| | 0 | 57 | | return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) |
| | 0 | 58 | | ? StartWindowsDaemon(args, pidFilePath, logger) |
| | 0 | 59 | | : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) |
| | 0 | 60 | | ? StartMacOsDaemon(args, pidFilePath, logger) // Special implementation for macOS to avoid fork() issues |
| | 0 | 61 | | : StartUnixDaemon(pidFilePath, logger); // Linux and other Unix systems |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | private static bool StartWindowsDaemon(string[] args, string pidFilePath, ILogger logger) |
| | | 65 | | { |
| | | 66 | | try |
| | | 67 | | { |
| | | 68 | | // Create a new process info |
| | 0 | 69 | | var startInfo = new ProcessStartInfo |
| | 0 | 70 | | { |
| | 0 | 71 | | FileName = Process.GetCurrentProcess().MainModule?.FileName, |
| | 0 | 72 | | UseShellExecute = true, |
| | 0 | 73 | | CreateNoWindow = true, |
| | 0 | 74 | | WindowStyle = ProcessWindowStyle.Hidden, |
| | 0 | 75 | | WorkingDirectory = Environment.CurrentDirectory |
| | 0 | 76 | | }; |
| | | 77 | | |
| | | 78 | | // Copy all args except --daemon |
| | 0 | 79 | | foreach (var arg in args) |
| | | 80 | | { |
| | 0 | 81 | | if (!arg.StartsWith("--daemon", StringComparison.OrdinalIgnoreCase)) |
| | | 82 | | { |
| | 0 | 83 | | startInfo.ArgumentList.Add(arg); |
| | | 84 | | } |
| | | 85 | | } |
| | | 86 | | |
| | | 87 | | // Add special flag to indicate we're already in daemon mode |
| | 0 | 88 | | startInfo.ArgumentList.Add("--daemon-child"); |
| | | 89 | | |
| | | 90 | | // Start the new process |
| | 0 | 91 | | var process = Process.Start(startInfo); |
| | 0 | 92 | | if (process == null) |
| | | 93 | | { |
| | 0 | 94 | | logger.Error("Failed to start daemon process"); |
| | 0 | 95 | | return false; |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | // Write PID to file |
| | 0 | 99 | | File.WriteAllText(pidFilePath, process.Id.ToString()); |
| | | 100 | | |
| | 0 | 101 | | logger.Information("Daemon started with PID {PID}", process.Id); |
| | 0 | 102 | | return true; // Parent should exit |
| | | 103 | | } |
| | 0 | 104 | | catch (Exception ex) |
| | | 105 | | { |
| | 0 | 106 | | logger.Error(ex, "Error starting daemon process"); |
| | 0 | 107 | | return false; |
| | | 108 | | } |
| | 0 | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Start daemon on macOS - uses a different approach than Linux to avoid fork() issues |
| | | 113 | | /// </summary> |
| | | 114 | | private static bool StartMacOsDaemon(string[] args, string pidFilePath, ILogger logger) |
| | | 115 | | { |
| | | 116 | | try |
| | | 117 | | { |
| | 0 | 118 | | logger.Information("Using macOS-specific daemon startup"); |
| | | 119 | | |
| | | 120 | | // Build the command line |
| | 0 | 121 | | var processPath = Process.GetCurrentProcess().MainModule?.FileName; |
| | 0 | 122 | | var arguments = new StringBuilder(); |
| | | 123 | | |
| | | 124 | | // Add all the original arguments except --daemon |
| | 0 | 125 | | foreach (var arg in args) |
| | | 126 | | { |
| | 0 | 127 | | if (arg.StartsWith("--daemon", StringComparison.OrdinalIgnoreCase)) |
| | | 128 | | { |
| | | 129 | | continue; |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | // Quote the argument if it contains spaces |
| | 0 | 133 | | if (arg.Contains(' ')) |
| | | 134 | | { |
| | 0 | 135 | | arguments.Append($"\"{arg}\" "); |
| | | 136 | | } |
| | | 137 | | else |
| | | 138 | | { |
| | 0 | 139 | | arguments.Append($"{arg} "); |
| | | 140 | | } |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | // Add daemon-child argument |
| | 0 | 144 | | arguments.Append("--daemon-child"); |
| | | 145 | | |
| | | 146 | | // Create a shell script to launch the process and disown it |
| | 0 | 147 | | var scriptPath = Path.Combine(Path.GetTempPath(), $"nltg_daemon_{Guid.NewGuid()}.sh"); |
| | | 148 | | |
| | | 149 | | // Write the shell script |
| | 0 | 150 | | var scriptContent = $""" |
| | 0 | 151 | | #!/bin/bash |
| | 0 | 152 | | # Auto-generated daemon launcher for NLTG |
| | 0 | 153 | | nohup "{processPath}" {arguments} > /dev/null 2>&1 & |
| | 0 | 154 | | echo $! > "{pidFilePath}" |
| | 0 | 155 | | |
| | 0 | 156 | | """; |
| | 0 | 157 | | File.WriteAllText(scriptPath, scriptContent); |
| | | 158 | | |
| | | 159 | | // Make the script executable |
| | 0 | 160 | | var chmodProcess = Process.Start(new ProcessStartInfo |
| | 0 | 161 | | { |
| | 0 | 162 | | FileName = "chmod", |
| | 0 | 163 | | Arguments = $"+x \"{scriptPath}\"", |
| | 0 | 164 | | UseShellExecute = false, |
| | 0 | 165 | | CreateNoWindow = true |
| | 0 | 166 | | }); |
| | 0 | 167 | | chmodProcess?.WaitForExit(); |
| | | 168 | | |
| | | 169 | | // Run the script |
| | 0 | 170 | | var scriptProcess = Process.Start(new ProcessStartInfo |
| | 0 | 171 | | { |
| | 0 | 172 | | FileName = "/bin/bash", |
| | 0 | 173 | | Arguments = $"\"{scriptPath}\"", |
| | 0 | 174 | | UseShellExecute = false, |
| | 0 | 175 | | CreateNoWindow = true |
| | 0 | 176 | | }); |
| | 0 | 177 | | scriptProcess?.WaitForExit(); |
| | | 178 | | |
| | | 179 | | // Clean up the script file |
| | | 180 | | try |
| | | 181 | | { |
| | 0 | 182 | | File.Delete(scriptPath); |
| | 0 | 183 | | } |
| | 0 | 184 | | catch |
| | | 185 | | { |
| | | 186 | | // Ignore cleanup errors |
| | 0 | 187 | | } |
| | | 188 | | |
| | | 189 | | // Verify PID file was created |
| | 0 | 190 | | if (File.Exists(pidFilePath)) |
| | | 191 | | { |
| | 0 | 192 | | var pidContent = File.ReadAllText(pidFilePath).Trim(); |
| | 0 | 193 | | logger.Information("macOS daemon started with PID {PID}", pidContent); |
| | 0 | 194 | | return true; |
| | | 195 | | } |
| | | 196 | | |
| | 0 | 197 | | logger.Warning("PID file not created, daemon may not have started correctly"); |
| | 0 | 198 | | return true; // Parent still exits even if there might be an issue |
| | | 199 | | } |
| | 0 | 200 | | catch (Exception ex) |
| | | 201 | | { |
| | 0 | 202 | | logger.Error(ex, "Error starting macOS daemon process"); |
| | 0 | 203 | | return false; |
| | | 204 | | } |
| | 0 | 205 | | } |
| | | 206 | | |
| | | 207 | | private static bool StartUnixDaemon(string pidFilePath, ILogger logger) |
| | | 208 | | { |
| | | 209 | | try |
| | | 210 | | { |
| | | 211 | | // First fork |
| | 0 | 212 | | var pid = Fork(); |
| | | 213 | | switch (pid) |
| | | 214 | | { |
| | | 215 | | case < 0: |
| | 0 | 216 | | logger.Error("First fork failed"); |
| | 0 | 217 | | return false; |
| | | 218 | | case > 0: |
| | | 219 | | // Parent process exits |
| | 0 | 220 | | logger.Information("Forked first process with PID {PID}", pid); |
| | 0 | 221 | | return true; |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | // Detach from terminal |
| | 0 | 225 | | _ = Setsid(); |
| | | 226 | | |
| | | 227 | | // Second fork |
| | 0 | 228 | | pid = Fork(); |
| | | 229 | | switch (pid) |
| | | 230 | | { |
| | | 231 | | case < 0: |
| | 0 | 232 | | logger.Error("Second fork failed"); |
| | 0 | 233 | | return false; |
| | | 234 | | case > 0: |
| | | 235 | | // Exit the intermediate process |
| | 0 | 236 | | Environment.Exit(0); |
| | | 237 | | break; |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | // Child process continues |
| | | 241 | | // Change working directory |
| | 0 | 242 | | Directory.SetCurrentDirectory("/"); |
| | | 243 | | |
| | | 244 | | // Close standard file descriptors |
| | 0 | 245 | | Console.SetIn(StreamReader.Null); |
| | 0 | 246 | | Console.SetOut(StreamWriter.Null); |
| | 0 | 247 | | Console.SetError(StreamWriter.Null); |
| | | 248 | | |
| | | 249 | | // Write PID file |
| | 0 | 250 | | var currentPid = Environment.ProcessId; |
| | 0 | 251 | | File.WriteAllText(pidFilePath, currentPid.ToString()); |
| | | 252 | | |
| | 0 | 253 | | return false; // Continue execution in the child |
| | | 254 | | } |
| | 0 | 255 | | catch (Exception ex) |
| | | 256 | | { |
| | 0 | 257 | | logger.Error(ex, "Error starting Unix daemon process"); |
| | 0 | 258 | | return false; |
| | | 259 | | } |
| | 0 | 260 | | } |
| | | 261 | | |
| | | 262 | | /// <summary> |
| | | 263 | | /// Checks if this process is already running as daemon |
| | | 264 | | /// </summary> |
| | | 265 | | public static bool IsRunningAsDaemon() |
| | | 266 | | { |
| | 0 | 267 | | return Array.Exists(Environment.GetCommandLineArgs(), |
| | 0 | 268 | | arg => arg.Equals("--daemon-child", StringComparison.OrdinalIgnoreCase)); |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <summary> |
| | | 272 | | /// Gets the path for the PID file |
| | | 273 | | /// </summary> |
| | | 274 | | public static string GetPidFilePath(string network) |
| | | 275 | | { |
| | 0 | 276 | | var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 0 | 277 | | var networkDir = Path.Combine(homeDir, DaemonConstants.DaemonFolder, network); |
| | 0 | 278 | | Directory.CreateDirectory(networkDir); // Ensure directory exists |
| | 0 | 279 | | return Path.Combine(networkDir, DaemonConstants.PidFile); |
| | | 280 | | } |
| | | 281 | | |
| | | 282 | | /// <summary> |
| | | 283 | | /// Stops a running daemon if it exists |
| | | 284 | | /// </summary> |
| | | 285 | | public static bool StopDaemon(string pidFilePath, ILogger logger) |
| | | 286 | | { |
| | | 287 | | try |
| | | 288 | | { |
| | 0 | 289 | | if (!File.Exists(pidFilePath)) |
| | | 290 | | { |
| | 0 | 291 | | logger.Warning("PID file not found, daemon may not be running"); |
| | 0 | 292 | | return false; |
| | | 293 | | } |
| | | 294 | | |
| | 0 | 295 | | var pidText = File.ReadAllText(pidFilePath).Trim(); |
| | 0 | 296 | | if (!int.TryParse(pidText, out var pid)) |
| | | 297 | | { |
| | 0 | 298 | | logger.Error("Invalid PID in file: {PidText}", pidText); |
| | 0 | 299 | | return false; |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | try |
| | | 303 | | { |
| | 0 | 304 | | var process = Process.GetProcessById(pid); |
| | 0 | 305 | | logger.Information("Stopping daemon process with PID {PID}", pid); |
| | | 306 | | |
| | | 307 | | // Send SIGTERM instead of Kill for graceful shutdown |
| | 0 | 308 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 309 | | { |
| | | 310 | | // Windows - send Ctrl+C or use taskkill /PID {pid} /F |
| | 0 | 311 | | SendCtrlEvent(process); |
| | | 312 | | } |
| | | 313 | | else |
| | | 314 | | { |
| | | 315 | | // Unix/macOS - send SIGTERM |
| | 0 | 316 | | SendSignal(pid, 15); // SIGTERM is 15 |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | // Wait for exit |
| | 0 | 320 | | var exited = process.WaitForExit(TimeSpan.FromSeconds(10)); |
| | 0 | 321 | | if (exited) |
| | | 322 | | { |
| | 0 | 323 | | logger.Information("Daemon process stopped successfully"); |
| | 0 | 324 | | File.Delete(pidFilePath); |
| | 0 | 325 | | return true; |
| | | 326 | | } |
| | | 327 | | |
| | | 328 | | // If graceful shutdown fails, force kill as last resort |
| | 0 | 329 | | logger.Warning("Daemon process did not exit gracefully, forcing termination"); |
| | 0 | 330 | | process.Kill(); |
| | 0 | 331 | | exited = process.WaitForExit(5000); |
| | 0 | 332 | | if (exited) |
| | | 333 | | { |
| | 0 | 334 | | File.Delete(pidFilePath); |
| | 0 | 335 | | return true; |
| | | 336 | | } |
| | | 337 | | |
| | 0 | 338 | | return false; |
| | | 339 | | } |
| | 0 | 340 | | catch (ArgumentException) |
| | | 341 | | { |
| | 0 | 342 | | logger.Warning("No process found with PID {PID}, removing stale PID file", pid); |
| | 0 | 343 | | File.Delete(pidFilePath); |
| | 0 | 344 | | return false; |
| | | 345 | | } |
| | | 346 | | } |
| | 0 | 347 | | catch (Exception ex) |
| | | 348 | | { |
| | 0 | 349 | | logger.Error(ex, "Error stopping daemon"); |
| | 0 | 350 | | return false; |
| | | 351 | | } |
| | 0 | 352 | | } |
| | | 353 | | |
| | | 354 | | private static void SendSignal(int pid, int signal) |
| | | 355 | | { |
| | 0 | 356 | | Process.Start("kill", $"-{signal} {pid}").WaitForExit(); |
| | 0 | 357 | | } |
| | | 358 | | |
| | | 359 | | private static void SendCtrlEvent(Process process) |
| | | 360 | | { |
| | 0 | 361 | | Process.Start("taskkill", $"/PID {process.Id}").WaitForExit(); |
| | 0 | 362 | | } |
| | | 363 | | |
| | | 364 | | #region Native Methods |
| | | 365 | | |
| | | 366 | | [LibraryImport("libc")] |
| | | 367 | | private static partial int fork(); |
| | | 368 | | |
| | | 369 | | [LibraryImport("libc")] |
| | | 370 | | private static partial int setsid(); |
| | | 371 | | |
| | | 372 | | private static int Fork() |
| | | 373 | | { |
| | | 374 | | // If not on Unix, simulate fork by returning -1 |
| | 0 | 375 | | if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && |
| | 0 | 376 | | !RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| | | 377 | | { |
| | 0 | 378 | | return -1; |
| | | 379 | | } |
| | | 380 | | |
| | 0 | 381 | | return fork(); |
| | | 382 | | } |
| | | 383 | | |
| | | 384 | | private static int Setsid() |
| | | 385 | | { |
| | | 386 | | // If not on Unix, simulate setsid by returning -1 |
| | 0 | 387 | | if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && |
| | 0 | 388 | | !RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| | | 389 | | { |
| | 0 | 390 | | return -1; |
| | | 391 | | } |
| | | 392 | | |
| | 0 | 393 | | return setsid(); |
| | | 394 | | } |
| | | 395 | | |
| | | 396 | | #endregion |
| | | 397 | | } |