summary refs log tree commit diff
path: root/LibSystemdCli/SystemdExecutor.cs
blob: 06c9538cb957cd15a0696c69fb94017dd466dc6d (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
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");
        
        var data = JsonSerializer.Deserialize<List<SystemdUnitListItem>>(output);
        
        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
            {
            }

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

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