-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
225 lines (185 loc) · 6.24 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"github.com/piraeusdatastore/drbd-shutdown-guard/pkg/vars"
)
const (
ServiceRuntimeDirectory = "/run/drbd-shutdown-guard"
ServiceBinaryName = "drbd-shutdown-guard"
DrbdSetupBinaryName = "drbdsetup"
SystemdRuntimeDirectory = "/run/systemd/system"
SystemdServiceName = "drbd-shutdown-guard.service"
DrbdSetupEnv = "DRBDSETUP_LOCATION"
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
cmd := cobra.Command{
Use: ServiceBinaryName,
Version: vars.Version,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
log.Printf("Running %s version %s\n", ServiceBinaryName, vars.Version)
},
}
cmd.AddCommand(install())
cmd.AddCommand(execute())
err := cmd.ExecuteContext(ctx)
if err != nil {
log.Fatalf("failed: %s", err.Error())
}
}
func install() *cobra.Command {
return &cobra.Command{
Use: "install",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
log.Printf("Creating service directory '%s'\n", ServiceRuntimeDirectory)
err := os.MkdirAll(ServiceRuntimeDirectory, os.FileMode(0755))
if err != nil {
return fmt.Errorf("failed to create systemd runtime unit directory '%s': %w", SystemdRuntimeDirectory, err)
}
log.Printf("Copying drbdsetup to service directory\n")
err = atomicCreateFile(path.Join(ServiceRuntimeDirectory, DrbdSetupBinaryName), os.FileMode(0755), copyBinary(os.Getenv(DrbdSetupEnv)))
if err != nil {
return fmt.Errorf("failed to copy drbdsetup: %w", err)
}
log.Printf("Copying %s to service directory\n", ServiceBinaryName)
self, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to look up currently running binary: %w", err)
}
err = atomicCreateFile(path.Join(ServiceRuntimeDirectory, ServiceBinaryName), os.FileMode(0755), copyBinary(self))
if err != nil {
return fmt.Errorf("failed to copy drbdsetup: %w", err)
}
log.Printf("Optionally: relabel service directory for SELinux")
err = exec.CommandContext(ctx, "chcon", "--recursive", "system_u:object_r:bin_t:s0", ServiceRuntimeDirectory).Run()
if err != nil {
log.Printf("ignoring error when setting selinux label: %s", err)
}
log.Printf("Creating systemd unit %s in %s\n", SystemdServiceName, SystemdRuntimeDirectory)
err = os.MkdirAll(SystemdRuntimeDirectory, os.FileMode(0755))
if err != nil {
return fmt.Errorf("failed to create systemd runtime unit directory '%s': %w", SystemdRuntimeDirectory, err)
}
err = atomicCreateFile(path.Join(SystemdRuntimeDirectory, SystemdServiceName), os.FileMode(0644), writeShutdownServiceUnit)
if err != nil {
return fmt.Errorf("failed to write service unit '%s': %w", ServiceRuntimeDirectory, err)
}
log.Printf("Reloading systemd\n")
err = exec.CommandContext(ctx, "systemctl", "daemon-reload").Run()
if err != nil {
return fmt.Errorf("failed to reload systemd")
}
log.Printf("Starting systemd unit %s\n", SystemdServiceName)
err = exec.CommandContext(ctx, "systemctl", "start", SystemdServiceName).Run()
if err != nil {
return fmt.Errorf("failed to start systemd service '%s': %w", SystemdServiceName, err)
}
log.Printf("Install successful\n")
return nil
},
}
}
type DrbdStatusEntry struct {
Name string `json:"name"`
}
func execute() *cobra.Command {
return &cobra.Command{
Use: "execute",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
drbdSetupPath := os.Getenv(DrbdSetupEnv)
log.Printf("Running 'drbdsetup status --json' to get current resources\n")
out, err := exec.CommandContext(ctx, drbdSetupPath, "status", "--json").Output()
if err != nil {
return fmt.Errorf("failed to run 'drbdsetup status --json': %w", err)
}
var resources []DrbdStatusEntry
err = json.Unmarshal(out, &resources)
if err != nil {
return fmt.Errorf("failed to parse output of 'drbdsetup status --json': %w", err)
}
var errg errgroup.Group
for i := range resources {
name := resources[i].Name
errg.Go(func() error {
log.Printf("Running 'drbdsetup secondary --force %s'\n", name)
err := exec.CommandContext(ctx, drbdSetupPath, "secondary", "--force", name).Run()
if err != nil {
return fmt.Errorf("failed to run 'drbdsetup secondary --force %s': %w", name, err)
}
return nil
})
}
return errg.Wait()
},
}
}
func writeShutdownServiceUnit(f *os.File) error {
_, err := f.WriteString(fmt.Sprintf(`[Unit]
Description=Ensure that DRBD devices with suspended IO are resumed (with potential IO errors) during shutdown.
# Ensure the stop action only runs after normal container shut down
Before=kubelet.service
# Ensure we get stopped during shutdown
Conflicts=umount.target
[Service]
Type=oneshot
RemainAfterExit=yes
Environment=DRBDSETUP_LOCATION=%s
ExecStop=%s execute
`, path.Join(ServiceRuntimeDirectory, DrbdSetupBinaryName), path.Join(ServiceRuntimeDirectory, ServiceBinaryName)))
if err != nil {
return fmt.Errorf("failed to write unit file: %w", err)
}
return nil
}
func copyBinary(p string) func(f *os.File) error {
return func(f *os.File) error {
src, err := os.Open(p)
if err != nil {
return fmt.Errorf("failed to open copy source '%s': %w", p, err)
}
_, err = io.Copy(f, src)
if err != nil {
return fmt.Errorf("failed to copy '%s' to '%s': %w", p, f.Name(), err)
}
return nil
}
}
func atomicCreateFile(p string, perm os.FileMode, write func(f *os.File) error) error {
tf, err := os.CreateTemp(path.Dir(p), path.Base(p))
if err != nil {
return fmt.Errorf("failed to create temporary file for '%s': %w", p, err)
}
err = tf.Chmod(perm)
if err != nil {
return fmt.Errorf("failed to update temporary file permissions for '%s': %w", p, err)
}
err = write(tf)
if err != nil {
_ = tf.Close()
return err
}
err = tf.Close()
if err != nil {
return fmt.Errorf("failed to close temporary file for '%s': %w", p, err)
}
err = os.Rename(tf.Name(), p)
if err != nil {
return fmt.Errorf("failed to move temporary file to final location '%s': %w", p, err)
}
return nil
}