summary refs log tree commit diff
path: root/LibSystemdCli/SystemdExecutor.cs
blob: f252891bee68142165ba3758660e2323bafe9c1e (plain) (blame)
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
using System.Text.Json;
using System.Text.Json.Nodes;
using LibSystemdCli.Models;

namespace LibSystemdCli;

public class SystemdExecutor {
    public static async IAsyncEnumerable<SystemdUnitListItem> GetUnits() {
        var output = await CommandExecutor.ExecuteCommand("systemctl", "list-units --all --no-legend --no-pager --no-legend -o json-pretty");

        List<SystemdUnitListItem>? data;
        try {
            data = JsonSerializer.Deserialize<List<SystemdUnitListItem>>(output);
        }
        catch (Exception ex) {
            Console.WriteLine("Failed to parse systemctl output: " + ex);
            Console.WriteLine("Output was: " + output);
            yield break;
        }

        foreach (var unit in data) {
            try {
                var fragmentOutput = await CommandExecutor.ExecuteCommand("systemctl", $"show -P FragmentPath --no-pager --no-legend -- {unit.Unit} ");
                // Console.WriteLine(fragmentOutput);
                unit.FragmentPaths = fragmentOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
            }
            catch (Exception e) {
                Console.WriteLine("Failed to get fragment path for unit " + unit.Unit + ": " + e);
            }

            yield return unit;
            // await Task.Delay(100);
        }
    }

    public static async IAsyncEnumerable<SystemdJournalLogItem> GetUnitLogs(string serviceName, int contextLines = 100) {
        await foreach (var line in CommandExecutor.ExecuteCommandAsync("journalctl", $"--catalog --all --pager-end --output=json --follow --lines={contextLines} --unit={serviceName}")) {
            yield return JsonSerializer.Deserialize<SystemdJournalLogItem>(line)!;
        }
    }

    public static async Task<SystemdServiceData> GetUnitData(string serviceName) {
        var output = await CommandExecutor.ExecuteCommand("systemctl", $"show --no-pager --no-legend -- {serviceName} ");
        var data = new SystemdServiceData();
        foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) {
            var parts = line.Split('=', 2);
            var key = parts[0];
            var value = parts[1];
            data.AddData(key, value);
        }

        return data;
    }

    private class TypeDef {
        public bool IsList { get; set; }
        public string Type { get; set; } = null!;
    }
}