systemd-vaultd-update-secrets: get service name from MAINPID

main
Jörg Thalheim 2 years ago
parent 2fd4e8a5c9
commit f0fd03caca

@ -6,6 +6,7 @@ import (
"log" "log"
"os" "os"
"path" "path"
"strings"
"syscall" "syscall"
"time" "time"
) )
@ -85,14 +86,31 @@ func updateSecrets(serviceName, target string) error {
return nil return nil
} }
func getSystemdServiceName() (string, error) {
mainPid := os.Getenv("MAINPID")
if mainPid == "" {
return "", fmt.Errorf("MAINPID not set")
}
p := fmt.Sprintf("/proc/%s/cgroup", mainPid)
content, err := os.ReadFile(p)
if err != nil {
return "", fmt.Errorf("failed to read cgroup file %s: %w", p, err)
}
line := strings.SplitN(string(content), "\n", 2)[0]
if !strings.HasSuffix(line, ".service") {
return "", fmt.Errorf("cgroup file %s does not end with .service", p)
}
return path.Base(line), nil
}
func main() { func main() {
if len(os.Args) != 2 { if len(os.Args) != 2 {
fmt.Println("Usage: systemd-vaultd-update-secrets <target>") fmt.Println("Usage: systemd-vaultd-update-secrets <target>")
os.Exit(1) os.Exit(1)
} }
serviceName := os.Getenv("SYSTEMD_ACTIVATION_UNIT") serviceName, err := getSystemdServiceName()
if serviceName == "" { if err != nil {
fmt.Println("SYSTEMD_ACTIVATION_UNIT not set") fmt.Println(err)
os.Exit(1) os.Exit(1)
} }

Loading…
Cancel
Save