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