forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
359 lines (307 loc) · 9.43 KB
/
service.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package nodetasks
import (
"encoding/json"
"fmt"
"github.com/golang/glog"
"io/ioutil"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/nodeup/cloudinit"
"k8s.io/kops/upup/pkg/fi/nodeup/local"
"k8s.io/kops/upup/pkg/fi/nodeup/tags"
"k8s.io/kops/upup/pkg/fi/utils"
"os"
"os/exec"
"path"
"reflect"
"strings"
"time"
)
const (
debianSystemdSystemPath = "/lib/systemd/system"
// TODO: Generally only repo packages write to /usr/lib/systemd/system on _rhel_family
// But we use it in two ways: we update the docker manifest, and we install our own
// package (protokube, kubelet). Maybe we should have the idea of a "system" package.
centosSystemdSystemPath = "/usr/lib/systemd/system"
)
type Service struct {
Name string
Definition *string
Running *bool
// Enabled configures the service to start at boot (or not start at boot)
Enabled *bool
ManageState *bool `json:"manageState"`
SmartRestart *bool `json:"smartRestart"`
}
var _ fi.HasDependencies = &Service{}
func (p *Service) GetDependencies(tasks map[string]fi.Task) []fi.Task {
var deps []fi.Task
for _, v := range tasks {
// We assume that services depend on basically everything
typeName := utils.BuildTypeName(reflect.TypeOf(v))
switch typeName {
case "*CopyAssetTask", "*File", "*Package", "*Sysctl", "*UpdatePackages", "*UserTask", "*Disk":
deps = append(deps, v)
case "*Service":
// ignore
default:
glog.Warningf("Unhandled type name in Service::GetDependencies: %q", typeName)
deps = append(deps, v)
}
}
return deps
}
func (s *Service) String() string {
return fmt.Sprintf("Service: %s", s.Name)
}
func NewService(name string, contents string, meta string) (fi.Task, error) {
s := &Service{Name: name}
s.Definition = fi.String(contents)
if meta != "" {
err := json.Unmarshal([]byte(meta), s)
if err != nil {
return nil, fmt.Errorf("error parsing json for service %q: %v", name, err)
}
}
// Default some values to true: Running, SmartRestart, ManageState
if s.Running == nil {
s.Running = fi.Bool(true)
}
if s.SmartRestart == nil {
s.SmartRestart = fi.Bool(true)
}
if s.ManageState == nil {
s.ManageState = fi.Bool(true)
}
// Default Enabled to be the same as running
if s.Enabled == nil {
s.Enabled = s.Running
}
return s, nil
}
func getSystemdStatus(name string) (map[string]string, error) {
glog.V(2).Infof("querying state of service %q", name)
cmd := exec.Command("systemctl", "show", "--all", name)
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error doing systemd show %s: %v\nOutput: %s", name, err, output)
}
properties := make(map[string]string)
for _, line := range strings.Split(string(output), "\n") {
if line == "" {
continue
}
tokens := strings.SplitN(line, "=", 2)
if len(tokens) != 2 {
glog.Warningf("Ignoring line in systemd show output: %q", line)
continue
}
properties[tokens[0]] = tokens[1]
}
return properties, nil
}
func (e *Service) systemdSystemPath(target tags.HasTags) (string, error) {
if target.HasTag(tags.TagOSFamilyDebian) {
return debianSystemdSystemPath, nil
} else if target.HasTag(tags.TagOSFamilyRHEL) {
return centosSystemdSystemPath, nil
} else {
return "", fmt.Errorf("unsupported systemd system")
}
}
func (e *Service) Find(c *fi.Context) (*Service, error) {
systemdSystemPath, err := e.systemdSystemPath(c.Target.(tags.HasTags))
if err != nil {
return nil, err
}
servicePath := path.Join(systemdSystemPath, e.Name)
d, err := ioutil.ReadFile(servicePath)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("Error reading systemd file %q: %v", servicePath, err)
}
// Not found
return &Service{
Name: e.Name,
Definition: nil,
Running: fi.Bool(false),
}, nil
}
actual := &Service{
Name: e.Name,
Definition: fi.String(string(d)),
// Avoid spurious changes
ManageState: e.ManageState,
SmartRestart: e.SmartRestart,
}
properties, err := getSystemdStatus(e.Name)
if err != nil {
return nil, err
}
activeState := properties["ActiveState"]
switch activeState {
case "active":
actual.Running = fi.Bool(true)
case "failed", "inactive":
actual.Running = fi.Bool(false)
default:
glog.Warningf("Unknown ActiveState=%q; will treat as not running", activeState)
actual.Running = fi.Bool(false)
}
wantedBy := properties["WantedBy"]
switch wantedBy {
case "":
actual.Enabled = fi.Bool(false)
// TODO: Can probably do better here!
case "multi-user.target", "graphical.target multi-user.target":
actual.Enabled = fi.Bool(true)
default:
glog.Warningf("Unknown WantedBy=%q; will treat as not enabled", wantedBy)
actual.Enabled = fi.Bool(false)
}
return actual, nil
}
// Parse the systemd unit file to extract obvious dependencies
func getSystemdDependencies(serviceName string, definition string) ([]string, error) {
var dependencies []string
for _, line := range strings.Split(definition, "\n") {
line = strings.TrimSpace(line)
tokens := strings.SplitN(line, "=", 2)
if len(tokens) != 2 {
continue
}
k := strings.TrimSpace(tokens[0])
v := strings.TrimSpace(tokens[1])
switch k {
case "EnvironmentFile":
dependencies = append(dependencies, v)
case "ExecStart":
// ExecStart=/usr/local/bin/kubelet "$DAEMON_ARGS"
// We extract the first argument (only)
tokens := strings.SplitN(v, " ", 2)
dependencies = append(dependencies, tokens[0])
glog.V(2).Infof("extracted depdendency from %q: %q", line, tokens[0])
}
}
return dependencies, nil
}
func (e *Service) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (s *Service) CheckChanges(a, e, changes *Service) error {
return nil
}
func (_ *Service) RenderLocal(t *local.LocalTarget, a, e, changes *Service) error {
systemdSystemPath, err := e.systemdSystemPath(t)
if err != nil {
return err
}
serviceName := e.Name
action := ""
if changes.Running != nil && fi.BoolValue(e.ManageState) {
if fi.BoolValue(e.Running) {
action = "restart"
} else {
action = "stop"
}
}
if changes.Definition != nil {
servicePath := path.Join(systemdSystemPath, serviceName)
err := fi.WriteFile(servicePath, fi.NewStringResource(*e.Definition), 0644, 0755)
if err != nil {
return fmt.Errorf("error writing systemd service file: %v", err)
}
glog.Infof("Reloading systemd configuration")
cmd := exec.Command("systemctl", "daemon-reload")
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error doing systemd daemon-reload: %v\nOutput: %s", err, output)
}
}
// "SmartRestart" - look at the obvious dependencies in the systemd service, restart if start time older
if fi.BoolValue(e.ManageState) && fi.BoolValue(e.SmartRestart) {
definition := fi.StringValue(e.Definition)
if definition == "" && a != nil {
definition = fi.StringValue(a.Definition)
}
if action == "" && fi.BoolValue(e.Running) && definition != "" {
dependencies, err := getSystemdDependencies(serviceName, definition)
if err != nil {
return err
}
var newest time.Time
for _, dependency := range dependencies {
stat, err := os.Stat(dependency)
if err != nil {
glog.Infof("Ignoring error checking service dependency %q: %v", dependency, err)
continue
}
modTime := stat.ModTime()
if newest.IsZero() || newest.Before(modTime) {
newest = modTime
}
}
if !newest.IsZero() {
properties, err := getSystemdStatus(e.Name)
if err != nil {
return err
}
startedAt := properties["ExecMainStartTimestamp"]
if startedAt == "" {
glog.Warningf("service was running, but did not have ExecMainStartTimestamp: %q", serviceName)
} else {
startedAtTime, err := time.Parse("Mon 2006-01-02 15:04:05 MST", startedAt)
if err != nil {
return fmt.Errorf("unable to parse service ExecMainStartTimestamp: %q", startedAt)
}
if startedAtTime.Before(newest) {
glog.V(2).Infof("will restart service %q because dependency changed after service start", serviceName)
action = "restart"
} else {
glog.V(2).Infof("will not restart service %q - started after dependencies", serviceName)
}
}
}
}
}
if action != "" && fi.BoolValue(e.ManageState) {
glog.Infof("Restarting service %q", serviceName)
cmd := exec.Command("systemctl", action, serviceName)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error doing systemd %s %s: %v\nOutput: %s", action, serviceName, err, output)
}
}
if changes.Enabled != nil && fi.BoolValue(e.ManageState) {
var args []string
if fi.BoolValue(e.Enabled) {
glog.Infof("Enabling service %q", serviceName)
args = []string{"enable", serviceName}
} else {
glog.Infof("Disabling service %q", serviceName)
args = []string{"disable", serviceName}
}
cmd := exec.Command("systemctl", args...)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error doing 'systemctl %v': %v\nOutput: %s", args, err, output)
}
}
return nil
}
func (_ *Service) RenderCloudInit(t *cloudinit.CloudInitTarget, a, e, changes *Service) error {
systemdSystemPath, err := e.systemdSystemPath(t)
if err != nil {
return err
}
serviceName := e.Name
servicePath := path.Join(systemdSystemPath, serviceName)
err = t.WriteFile(servicePath, fi.NewStringResource(*e.Definition), 0644, 0755)
if err != nil {
return err
}
if fi.BoolValue(e.ManageState) {
t.AddCommand(cloudinit.Once, "systemctl", "daemon-reload")
t.AddCommand(cloudinit.Once, "systemctl", "start", "--no-block", serviceName)
}
return nil
}