From: Simon Ruderich Date: Mon, 9 Nov 2026 11:46:43 +0000 (+0100) Subject: First working version X-Git-Url: https://ruderich.org/simon/gitweb/?a=commitdiff_plain;h=refs%2Fheads%2Fmaster;p=monitoring%2Fmustrestart.git First working version --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f3cb5e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/mustrestart diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..8fd3586 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,70 @@ +version: "2" + +linters: + default: none + enable: + # Enabled by default + - errcheck + - govet + - ineffassign + - staticcheck + - unused + # Additional checks + - bodyclose + - containedctx + - contextcheck + - copyloopvar + - durationcheck + - errname + - exhaustive + - exptostd + - gocheckcompilerdirectives + - gocritic + - iface + - importas + - nilerr + - nilnesserr + - nolintlint + - nonamedreturns + - nosprintfhostport + - predeclared + - reassign + - recvcheck + - rowserrcheck + - thelper + - tparallel + - unconvert + - usestdlibvars + - usetesting + - wastedassign + + settings: + exhaustive: + # "default" is good enough to be exhaustive + default-signifies-exhaustive: true + gocritic: + disabled-checks: + - exitAfterDefer + - ifElseChain + - singleCaseSwitch + staticcheck: + checks: + # Defaults + - "all" + - "-ST1000" + - "-ST1003" + - "-ST1016" + - "-ST1020" + - "-ST1021" + - "-ST1022" + # + - "-QF1001" + - "-QF1003" + - "-QF1003" + - "-QF1007" + usestdlibvars: + http-method: false + + +run: + timeout: 10m diff --git a/.punyci.toml b/.punyci.toml new file mode 100644 index 0000000..aa6c54c --- /dev/null +++ b/.punyci.toml @@ -0,0 +1,8 @@ +[[Jobs]] +Image = "golang:1.26" +Script = """ +mkdir -p /punyci-cache/pkg +ln -s /punyci-cache/pkg /go/pkg +./ci/run +""" +Cache = true diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..29498fa --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +all: + go build + go test + go fmt + go vet + +.PHONY: all diff --git a/ci/run b/ci/run new file mode 100755 index 0000000..959cedc --- /dev/null +++ b/ci/run @@ -0,0 +1,21 @@ +#!/bin/sh + +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (C) 2026 Simon Ruderich + +set -eu +set -x + + +# Go + +PATH=$HOME/go/bin:$PATH +export PATH + +make + +# Additional static checks only run in CI +go install golang.org/x/vuln/cmd/govulncheck@1.9.0 +govulncheck ./... +go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 +golangci-lint run diff --git a/config.go b/config.go new file mode 100644 index 0000000..c4cda09 --- /dev/null +++ b/config.go @@ -0,0 +1,64 @@ +// Config parsing + +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Simon Ruderich + +package main + +import ( + "fmt" + "regexp" + + "github.com/BurntSushi/toml" +) + +type Config struct { + IgnoreChecks []ConfigIgnore + + ServicesToRestart []string + ServicesToReload []string +} + +type ConfigIgnore struct { + Exe string // as string, empty to match every program + Paths []string // as regexp + + paths []*regexp.Regexp +} + +func LoadConfig(path string) (*Config, error) { + var cfg Config + md, err := toml.DecodeFile(path, &cfg) + if err != nil { + return nil, err + } + undecoded := md.Undecoded() + if len(undecoded) != 0 { + return nil, fmt.Errorf("%q: invalid fields used: %q", path, undecoded) + } + + err = loadConfigPrepare(&cfg) + if err != nil { + return nil, fmt.Errorf("%q: %v", path, err) + } + + return &cfg, nil +} + +func loadConfigPrepare(cfg *Config) error { + for i, ignore := range cfg.IgnoreChecks { + var rs []*regexp.Regexp + for j, x := range ignore.Paths { + r, err := regexp.Compile(x) + if err != nil { + return fmt.Errorf("IgnoreChecks[%d].Paths[%d]: %v", i, j, err) + } + rs = append(rs, r) + } + cfg.IgnoreChecks[i].paths = rs + cfg.IgnoreChecks[i].Paths = nil // prevent accidental use + } + return nil +} + +// vi: set noet ts=4 sw=4 sts=4: diff --git a/deleted.go b/deleted.go new file mode 100644 index 0000000..9cad133 --- /dev/null +++ b/deleted.go @@ -0,0 +1,148 @@ +// Find binaries which use deleted files + +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Simon Ruderich + +package main + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" +) + +type Deleted struct { + Pid int + Exe string + Service string // systemd system service, can be empty + Paths []string +} + +func DeletedFiles() ([]Deleted, error) { + var res []Deleted + + proc, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } + for _, x := range proc { + // Skip non PID entries + pid, err := strconv.Atoi(x.Name()) + if err != nil { + continue + } + dir := filepath.Join("/proc", x.Name()) + + deleted, err := deletedFilesFromProcMaps(filepath.Join(dir, "maps")) + if err != nil { + if os.IsNotExist(err) { // process exited + continue + } + return nil, err + } + if len(deleted) == 0 { + continue + } + + exe, err := os.Readlink(filepath.Join(dir, "exe")) + if err != nil { + if os.IsNotExist(err) { // process exited + continue + } + return nil, err + } + exe = strings.TrimSuffix(exe, " (deleted)") + + cgroup, err := os.ReadFile(filepath.Join(dir, "cgroup")) + if err != nil { + if os.IsNotExist(err) { // process exited + continue + } + return nil, err + } + + res = append(res, Deleted{ + Pid: pid, + Exe: exe, + Paths: deleted, + Service: cgroupToService(string(cgroup)), + }) + } + + slices.SortFunc(res, func(a, b Deleted) int { + return a.Pid - b.Pid + }) + return res, nil +} + +func deletedFilesFromProcMaps(path string) ([]string, error) { + maps, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + r := regexp.MustCompile(" +") + seen := make(map[string]bool) + + var res []string + for x := range strings.Lines(string(maps)) { + // See man 5 proc_pid_maps + xs := r.Split(x, 6) + + path := strings.TrimSuffix(xs[5], "\n") + // Skip non-file mappings + if path == "" || path[0] == '[' || + path == "/dev/zero (deleted)" || + strings.HasPrefix(path, "/dev/shm/sem.") || // shared memory + strings.HasPrefix(path, "/SYSV") || // shared memory + false { + continue + } + // The suffix check is not foolproof but we care only about system + // files which won't contain "(deleted)" + path, ok := strings.CutSuffix(path, " (deleted)") + if !ok { + continue + } + if seen[path] { + continue + } + seen[path] = true + + res = append(res, path) + } + + slices.Sort(res) + return res, nil +} + +func cgroupToService(cgroup string) string { + cgroup = strings.TrimSuffix(cgroup, "\n") + + x, ok := strings.CutPrefix(cgroup, "0::/system.slice/") + if !ok { + // We care only about system services + return "" + } + + // There should only be one line, abort just in case + if strings.Contains(x, "\n") { + return "" + } + + // Support the following cases: + // - "0::/system.slice/dbus.service" (default) + // - "0::/system.slice/systemd-udevd.service/udev" + // - "0::/system.slice/system-getty.slice/getty@tty2.service" + for _, x := range strings.Split(x, "/") { + if strings.HasSuffix(x, ".service") { + return x + } + } + return "" +} + +// vi: set noet ts=4 sw=4 sts=4: diff --git a/filter.go b/filter.go new file mode 100644 index 0000000..26f9509 --- /dev/null +++ b/filter.go @@ -0,0 +1,88 @@ +// Filter list of deleted binaries/files + +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Simon Ruderich + +package main + +import ( + "maps" + "slices" + "strings" +) + +func DeletedFilesFiltered(cfg *Config) ([]Deleted, error) { + xs, err := DeletedFiles() + if err != nil { + return nil, err + } + return FilterDeleted(cfg, xs), nil +} + +func FilterDeleted(cfg *Config, deleted []Deleted) []Deleted { + if len(cfg.IgnoreChecks) == 0 { + return deleted + } + + var res []Deleted + for _, x := range deleted { + filterDeleted(cfg.IgnoreChecks, &x) + if len(x.Paths) == 0 { + continue + } + res = append(res, x) + } + return res +} + +func filterDeleted(ignores []ConfigIgnore, deleted *Deleted) { + paths := make(map[string]struct{}) + for _, x := range deleted.Paths { + paths[x] = struct{}{} + } + + for _, ignore := range ignores { + if !filterExeMatches(ignore.Exe, deleted.Exe) { + continue + } + + // No paths given: match all paths + if len(ignore.paths) == 0 { + deleted.Paths = nil + return + } + + for _, r := range ignore.paths { + for p := range paths { + if r.MatchString(p) { + delete(paths, p) + } + } + } + } + + deleted.Paths = slices.Sorted(maps.Keys(paths)) +} + +func filterExeMatches(ignore, deleted string) bool { + // Empty matches everything + if ignore == "" { + return true + } + // Full match + if ignore == deleted { + return true + } + + // Match of last path component + if !strings.Contains(ignore, "/") { + xs := strings.Split(deleted, "/") + if xs[len(xs)-1] == ignore { + return true + } + } + + return false +} + +// vi: set noet ts=4 sw=4 sts=4: diff --git a/filter_test.go b/filter_test.go new file mode 100644 index 0000000..da5227e --- /dev/null +++ b/filter_test.go @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Simon Ruderich + +package main + +import ( + "reflect" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestFilterDeleted(t *testing.T) { + deleted := func() []Deleted { + return []Deleted{ + { + Pid: 23, + Exe: "/usr/bin/ls", + Paths: []string{ + "/usr/bin/ls", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + }, + }, + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + } + } + + tests := []struct { + name string + cfg *Config + deleted []Deleted + exp []Deleted + }{ + + { + "empty", + &Config{}, + deleted(), + []Deleted{ + { + Pid: 23, + Exe: "/usr/bin/ls", + Paths: []string{ + "/usr/bin/ls", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + }, + }, + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + }, + }, + + { + "ignore everything", + &Config{ + IgnoreChecks: []ConfigIgnore{ + {}, + }, + }, + deleted(), + nil, + }, + { + "ignore everything II", + &Config{ + IgnoreChecks: []ConfigIgnore{ + { + Exe: "", + Paths: []string{".*"}, + }, + }, + }, + deleted(), + nil, + }, + + { + "ignore one exe", + &Config{ + IgnoreChecks: []ConfigIgnore{ + { + Exe: "/usr/bin/ls", + }, + }, + }, + deleted(), + []Deleted{ + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + }, + }, + + { + "ignore one exe, relative path", + &Config{ + IgnoreChecks: []ConfigIgnore{ + { + Exe: "ls", + }, + }, + }, + deleted(), + []Deleted{ + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + }, + }, + + { + "ignore one path", + &Config{ + IgnoreChecks: []ConfigIgnore{ + { + Exe: "", + Paths: []string{`libc\.so\.\d+`}, + }, + }, + }, + deleted(), + []Deleted{ + { + Pid: 23, + Exe: "/usr/bin/ls", + Paths: []string{ + "/usr/bin/ls", + }, + }, + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + }, + }, + + { + "ignore one path for one exe", + &Config{ + IgnoreChecks: []ConfigIgnore{ + { + Exe: "/usr/bin/ls", + Paths: []string{`libc\.so\.\d+`}, + }, + }, + }, + deleted(), + []Deleted{ + { + Pid: 23, + Exe: "/usr/bin/ls", + Paths: []string{ + "/usr/bin/ls", + }, + }, + { + Pid: 42, + Exe: "/usr/bin/htop", + Paths: []string{ + "/usr/bin/htop", + "/usr/lib/x86_64-linux-gnu/libc.so.6", + "/usr/lib/x86_64-linux-gnu/libncursesw.so.6.6", + }, + }, + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := loadConfigPrepare(tc.cfg) + if err != nil { + t.Fatal(err) + } + + res := FilterDeleted(tc.cfg, tc.deleted) + if !reflect.DeepEqual(res, tc.exp) { + t.Errorf("res: %s", cmp.Diff(tc.exp, res)) + } + }) + } +} + +// vi: set noet ts=4 sw=4 sts=4: diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d92a6a6 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module mustrestart + +go 1.26.0 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/google/go-cmp v0.7.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7d2396d --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= diff --git a/main.go b/main.go new file mode 100644 index 0000000..0e73014 --- /dev/null +++ b/main.go @@ -0,0 +1,190 @@ +// Find binaries which use deleted files and either list or restart them. Only +// explicitly listed binaries are restarted. + +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Simon Ruderich + +package main + +import ( + "bufio" + "flag" + "fmt" + "log" + "os" + "os/exec" + "slices" + "strings" +) + +func main() { + configPath := flag.String("config", "", "path to config file") + dryRun := flag.Bool("dry-run", false, "dry run (only for restart)") + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "usage: %[1]s [options]\n"+ + " %[1]s [options] check\n"+ + " %[1]s [options] restart\n"+ + "\n", + os.Args[0]) + flag.PrintDefaults() + } + flag.Parse() + + usage := func() { + flag.Usage() + os.Exit(1) + } + + args := flag.Args() + + cfg := &Config{} + if *configPath != "" { + x, err := LoadConfig(*configPath) + if err != nil { + log.Fatal(err) + } + cfg = x + } + + // Show verbose output by default + if len(args) == 0 { + deleted, err := DeletedFilesFiltered(cfg) + if err != nil { + log.Fatal(err) + } + + w := bufio.NewWriter(os.Stdout) + for _, x := range deleted { + exe := StripUninterestingPathParts(x.Exe) + _, _ = fmt.Fprintf(w, "%s (%d", exe, x.Pid) + if x.Service != "" { + _, _ = fmt.Fprintf(w, ", %s", x.Service) + } + _, _ = fmt.Fprintf(w, "):") + for _, p := range x.Paths { + p := StripUninterestingPathParts(p) + _, _ = fmt.Fprintf(w, " %s", p) + } + _, _ = fmt.Fprintf(w, "\n") + } + err = w.Flush() + if err != nil { + log.Fatal(err) + } + return + + } else if len(args) != 1 { + usage() + } + + // Abbreviated output for monitoring checks + if args[0] == "check" { + deleted, err := DeletedFilesFiltered(cfg) + if err != nil { + log.Fatal(err) + } + if len(deleted) == 0 { + return + } + + seen := make(map[string]bool) + var exes []string + for _, x := range deleted { + exe := StripUninterestingPathParts(x.Exe) + if seen[exe] { + continue + } + seen[exe] = true + exes = append(exes, exe) + } + slices.Sort(exes) + _, err = os.Stdout.Write([]byte(strings.Join(exes, " ") + "\n")) + if err != nil { + log.Fatal(err) + } + return + + } else if args[0] == "restart" { + deleted, err := DeletedFiles() + if err != nil { + log.Fatal(err) + } + if len(deleted) == 0 { + return + } + + restartMap := make(map[string]bool) + for _, x := range cfg.ServicesToRestart { + restartMap[x] = true + } + reloadMap := make(map[string]bool) + for _, x := range cfg.ServicesToReload { + reloadMap[x] = true + } + done := make(map[string]bool) + + for _, x := range deleted { + if x.Service == "" { + continue + } + restart := restartMap[x.Service] + if !restart && !reloadMap[x.Service] { + continue + } + + // Only restart service once, in case there's more than one binary + if done[x.Service] { + continue + } + done[x.Service] = true + + var extra string + if *dryRun { + extra = " (dry-run)" + } + var msg, action string + if restart { + msg = fmt.Sprintf("Restarting %s%s\n", x.Service, extra) + action = "restart" + } else { + msg = fmt.Sprintf("Reloading %s%s\n", x.Service, extra) + action = "reload" + } + _, _ = os.Stdout.Write([]byte(msg)) + + if *dryRun { + continue + } + + cmd := exec.Command("systemctl", action, x.Service) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + log.Fatal(err) + } + } + + } else { + usage() + } +} + +func StripUninterestingPathParts(path string) string { + for _, prefix := range []string{ + "/usr/bin/", + "/usr/lib/systemd/", + "/usr/lib/x86_64-linux-gnu/", + "/usr/local/bin/", + "/usr/local/sbin/", + "/usr/sbin/", + } { + x, ok := strings.CutPrefix(path, prefix) + if ok { + return x + } + } + return path +} + +// vi: set noet ts=4 sw=4 sts=4: