-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (80 loc) · 2.03 KB
/
main.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/abiosoft/lineprefix"
)
type Config struct {
Signals map[string]string `json:"signals"`
}
var signalMap = map[string]syscall.Signal{
"USR1": syscall.SIGUSR1,
"USR2": syscall.SIGUSR2,
"INT": syscall.SIGINT,
"ABRT": syscall.SIGABRT,
"ALRM": syscall.SIGALRM,
"BUS": syscall.SIGBUS,
"CHLD": syscall.SIGCHLD,
"CLD": syscall.SIGCLD,
"CONT": syscall.SIGCONT,
"FPE": syscall.SIGFPE,
"HUP": syscall.SIGHUP,
"IO": syscall.SIGIO,
"IOT": syscall.SIGIOT,
}
// handles a single signal
func handleSignal(ctx context.Context, signalName string, command string) {
c := make(chan os.Signal, 3)
signalNumber, ok := signalMap[signalName]
if !ok {
log.Fatalf("failed to find syscall for signal %v\n", signalName)
}
signal.Notify(c, signalNumber)
prefix := lineprefix.Prefix(fmt.Sprintf("[CMD SIG%v]", signalName))
stdoutWrapper := lineprefix.New(prefix, lineprefix.Writer(os.Stdout))
stderrWrapper := lineprefix.New(prefix, lineprefix.Writer(os.Stderr))
outer:
for {
select {
case <-c:
cmd := exec.Command("/bin/bash", "-c", command)
cmd.Stderr = stderrWrapper
cmd.Stdout = stdoutWrapper
if err := cmd.Run(); err != nil {
log.Printf("WARNING: program terminated with error: %v\n", err)
}
case <-ctx.Done():
break outer
}
}
signal.Stop(c)
close(c)
}
// main entry point for the program, loads config file etc.
func main() {
configFile, ok := os.LookupEnv("CONFIG_FILE")
if !ok {
configFile = "/etc/config.json"
}
configBytes, err := os.ReadFile(configFile)
if err != nil {
log.Fatalf("failed to read config file: %v\n", err)
}
config := Config{}
if err := json.Unmarshal(configBytes, &config); err != nil {
log.Fatalf("failed to deserialize config file: %v\n", err)
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer cancel()
for signal, command := range config.Signals {
go handleSignal(ctx, signal, command)
}
<-ctx.Done()
log.Printf("exiting")
}