-
Notifications
You must be signed in to change notification settings - Fork 8
/
machinectl.go
72 lines (60 loc) · 1.48 KB
/
machinectl.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
"github.com/reconquest/executil-go"
"github.com/reconquest/ser-go"
)
func listActiveContainers(
containerSuffix string,
) (map[string]struct{}, error) {
command := exec.Command("machinectl", "--no-legend")
output, _, err := executil.Run(command)
if err != nil {
return nil, err
}
containers := map[string]struct{}{}
rawContainers := strings.Split(string(output), "\n")
for _, rawContainer := range rawContainers {
if rawContainer == "" {
continue
}
fields := strings.Fields(rawContainer)
if len(fields) < 3 {
return nil, fmt.Errorf(
"invalid output from machinectl: %s", rawContainer,
)
}
if strings.HasSuffix(fields[0], containerSuffix) {
nameWithoutSuffix := strings.TrimSuffix(fields[0], containerSuffix)
containers[nameWithoutSuffix] = struct{}{}
}
}
return containers, nil
}
func getContainerLeaderPID(name string) (int, error) {
command := exec.Command("machinectl", "show", name+containerSuffix)
output, _, err := executil.Run(command)
if err != nil {
return 0, err
}
config := strings.Split(string(output), "\n")
for _, line := range config {
if strings.HasPrefix(line, "Leader=") {
pid, err := strconv.Atoi(strings.Split(line, "=")[1])
if err != nil {
return 0, ser.Errorf(
err,
"can't convert Leader value from '%s' to PID",
line,
)
}
return pid, nil
}
}
return 0, fmt.Errorf(
"PID info is not found in machinectl show '%s'", name,
)
}