Last active
January 15, 2022 04:34
-
-
Save rgwood/ede13b8324e4c63855f9b016d8104634 to your computer and use it in GitHub Desktop.
Helper to install the current executable as a Systemd service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using CliWrap; | |
| using Spectre.Console; | |
| using System.Diagnostics; | |
| namespace SystemdTemplate; | |
| public static class Systemd | |
| { | |
| /// <summary> | |
| /// Attempt to install the current process as a systemd service | |
| /// </summary> | |
| /// <returns>bool indicating whether the operation succeeded</returns> | |
| public static async Task<bool> InstallServiceAsync(string? name = null, string description = "") | |
| { | |
| string processPath = Environment.ProcessPath!; | |
| string processFileName = Path.GetFileName(processPath); | |
| string serviceName = name ?? processFileName; | |
| AnsiConsole.WriteLine($"Installing {processFileName} as a systemd service..."); | |
| string unitFileContents = @$" | |
| [Unit] | |
| Description={description} | |
| [Service] | |
| # change type to `notify` if using Microsoft.Extensions.Hosting.Systemd | |
| Type=simple | |
| ExecStart={processPath} | |
| [Install] | |
| WantedBy=multi-user.target"; | |
| string unitFilePath = $"/etc/systemd/system/{serviceName}.service"; | |
| try | |
| { | |
| AnsiConsole.WriteLine("Writing unit file..."); | |
| File.WriteAllText(unitFilePath, unitFileContents); | |
| } | |
| catch (Exception ex) | |
| { | |
| AnsiConsole.MarkupLine($"[red]Error:[/] write failed to {unitFilePath}. Did you forget to use sudo?"); | |
| AnsiConsole.WriteException(ex.Demystify()); | |
| return false; | |
| } | |
| try | |
| { | |
| AnsiConsole.WriteLine("Enabling service..."); | |
| await (Cli.Wrap("systemctl").WithArguments($"enable {serviceName}") | | |
| (Console.WriteLine, Console.Error.WriteLine)).ExecuteAsync(); | |
| AnsiConsole.WriteLine("Starting service..."); | |
| await (Cli.Wrap("systemctl").WithArguments($"start {serviceName}") | | |
| (Console.WriteLine, Console.Error.WriteLine)).ExecuteAsync(); | |
| } | |
| catch (Exception ex) | |
| { | |
| AnsiConsole.MarkupLine($"[red]Error:[/] failed to enable+start service"); | |
| AnsiConsole.WriteException(ex.Demystify()); | |
| return false; | |
| } | |
| AnsiConsole.MarkupLine($"[green]Done! Install succeeded.[/]"); | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment