-
Notifications
You must be signed in to change notification settings - Fork 453
/
service_runner.go
458 lines (366 loc) · 11.2 KB
/
service_runner.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package system
import (
"context"
"errors"
"fmt"
"log"
"slices"
"sync"
"time"
"github.com/siderolabs/gen/xslices"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime"
"github.com/siderolabs/talos/internal/app/machined/pkg/system/events"
"github.com/siderolabs/talos/internal/app/machined/pkg/system/health"
"github.com/siderolabs/talos/internal/app/machined/pkg/system/runner"
"github.com/siderolabs/talos/pkg/conditions"
machineapi "github.com/siderolabs/talos/pkg/machinery/api/machine"
)
// WaitConditionCheckInterval is time between checking for wait condition
// description changes.
//
// Exposed here for unit-tests to override.
var WaitConditionCheckInterval = time.Second
// ServiceRunner wraps the state of the service (running, stopped, ...).
type ServiceRunner struct {
mu sync.Mutex
runtime runtime.Runtime
service Service
id string
instance *singleton
state events.ServiceState
events events.ServiceEvents
healthState health.State
stateSubscribers map[StateEvent][]chan<- struct{}
stopCh chan struct{}
}
// NewServiceRunner creates new ServiceRunner around Service instance.
func NewServiceRunner(instance *singleton, service Service, runtime runtime.Runtime) *ServiceRunner {
return &ServiceRunner{
service: service,
instance: instance,
runtime: runtime,
id: service.ID(runtime),
state: events.StateInitialized,
stateSubscribers: make(map[StateEvent][]chan<- struct{}),
stopCh: make(chan struct{}, 1),
}
}
// GetState implements events.Recorder.
func (svcrunner *ServiceRunner) GetState() events.ServiceState {
svcrunner.mu.Lock()
defer svcrunner.mu.Unlock()
return svcrunner.state
}
// UpdateState implements events.Recorder.
func (svcrunner *ServiceRunner) UpdateState(ctx context.Context, newstate events.ServiceState, message string, args ...interface{}) {
svcrunner.mu.Lock()
event := events.ServiceEvent{
Message: fmt.Sprintf(message, args...),
State: newstate,
Timestamp: time.Now(),
}
svcrunner.state = newstate
svcrunner.events.Push(event)
log.Printf("service[%s](%s): %s", svcrunner.id, svcrunner.state, event.Message)
isUp := svcrunner.inStateLocked(StateEventUp)
isDown := svcrunner.inStateLocked(StateEventDown)
isFinished := svcrunner.inStateLocked(StateEventFinished)
svcrunner.mu.Unlock()
if svcrunner.runtime != nil {
svcrunner.runtime.Events().Publish(ctx, event.AsProto(svcrunner.id))
}
if isUp {
svcrunner.notifyEvent(StateEventUp)
}
if isDown {
svcrunner.notifyEvent(StateEventDown)
}
if isFinished {
svcrunner.notifyEvent(StateEventFinished)
}
}
func (svcrunner *ServiceRunner) healthUpdate(ctx context.Context, change health.StateChange) {
svcrunner.mu.Lock()
// service not running, suppress event
if svcrunner.state != events.StateRunning {
svcrunner.mu.Unlock()
return
}
var message string
if *change.New.Healthy {
message = "Health check successful"
} else {
message = fmt.Sprintf("Health check failed: %s", change.New.LastMessage)
}
event := events.ServiceEvent{
Message: message,
State: svcrunner.state,
Health: change.New,
Timestamp: time.Now(),
}
svcrunner.events.Push(event)
log.Printf("service[%s](%s): %s", svcrunner.id, svcrunner.state, event.Message)
isUp := svcrunner.inStateLocked(StateEventUp)
svcrunner.mu.Unlock()
if isUp {
svcrunner.notifyEvent(StateEventUp)
}
if svcrunner.runtime != nil {
svcrunner.runtime.Events().Publish(ctx, event.AsProto(svcrunner.id))
}
}
// GetEventHistory returns history of events for this service.
func (svcrunner *ServiceRunner) GetEventHistory(count int) []events.ServiceEvent {
svcrunner.mu.Lock()
defer svcrunner.mu.Unlock()
return svcrunner.events.Get(count)
}
func (svcrunner *ServiceRunner) waitFor(ctx context.Context, condition conditions.Condition) error {
description := condition.String()
svcrunner.UpdateState(ctx, events.StateWaiting, "Waiting for %s", description)
errCh := make(chan error)
go func() {
errCh <- condition.Wait(ctx)
}()
ticker := time.NewTicker(WaitConditionCheckInterval)
defer ticker.Stop()
// update state if condition description changes (some conditions are satisfied)
for {
select {
case err := <-errCh:
return err
case <-ticker.C:
newDescription := condition.String()
if newDescription != description && newDescription != "" {
description = newDescription
svcrunner.UpdateState(ctx, events.StateWaiting, "Waiting for %s", description)
}
}
}
}
// ErrSkip is returned by Run when service is skipped.
var ErrSkip = errors.New("service skipped")
// Run initializes the service and runs it.
//
// Run returns an error when a service stops.
//
// Run should be run in a goroutine.
//
//nolint:gocyclo
func (svcrunner *ServiceRunner) Run(notifyChannels ...chan<- struct{}) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
select {
case <-ctx.Done():
return
case <-svcrunner.stopCh:
cancel()
}
}()
svcrunner.UpdateState(ctx, events.StateStarting, "Starting service")
for _, notifyCh := range notifyChannels {
close(notifyCh)
}
condition := svcrunner.service.Condition(svcrunner.runtime)
dependencies := svcrunner.service.DependsOn(svcrunner.runtime)
if len(dependencies) > 0 {
serviceConditions := xslices.Map(dependencies, func(dep string) conditions.Condition { return waitForService(instance, StateEventUp, dep) })
serviceDependencies := conditions.WaitForAll(serviceConditions...)
if condition != nil {
condition = conditions.WaitForAll(serviceDependencies, condition)
} else {
condition = serviceDependencies
}
}
if condition != nil {
if err := svcrunner.waitFor(ctx, condition); err != nil {
return fmt.Errorf("condition failed: %w", err)
}
}
svcrunner.UpdateState(ctx, events.StatePreparing, "Running pre state")
if err := svcrunner.service.PreFunc(ctx, svcrunner.runtime); err != nil {
return fmt.Errorf("failed to run pre stage: %w", err)
}
svcrunner.UpdateState(ctx, events.StatePreparing, "Creating service runner")
runnr, err := svcrunner.service.Runner(svcrunner.runtime)
if err != nil {
return fmt.Errorf("failed to create runner: %w", err)
}
defer func() {
// PostFunc passes in the state so that we can take actions that depend on the outcome of the run
state := svcrunner.GetState()
if err := svcrunner.service.PostFunc(svcrunner.runtime, state); err != nil {
svcrunner.UpdateState(ctx, events.StateFailed, "Failed to run post stage: %v", err)
}
}()
if runnr == nil {
return ErrSkip
}
if err := svcrunner.run(ctx, runnr); err != nil {
return fmt.Errorf("failed running service: %w", err)
}
return nil
}
//nolint:gocyclo
func (svcrunner *ServiceRunner) run(ctx context.Context, runnr runner.Runner) error {
if runnr == nil {
// special case - run nothing (TODO: we should handle it better, e.g. in PreFunc)
return nil
}
if err := runnr.Open(); err != nil {
return fmt.Errorf("error opening runner: %w", err)
}
//nolint:errcheck
defer runnr.Close()
errCh := make(chan error)
go func() {
errCh <- runnr.Run(func(s events.ServiceState, msg string, args ...interface{}) {
svcrunner.UpdateState(ctx, s, msg, args...)
})
}()
if healthSvc, ok := svcrunner.service.(HealthcheckedService); ok {
var healthWg sync.WaitGroup
defer healthWg.Wait()
healthWg.Add(1)
go func() {
defer healthWg.Done()
//nolint:errcheck
health.Run(
ctx,
healthSvc.HealthSettings(svcrunner.runtime),
&svcrunner.healthState,
healthSvc.HealthFunc(svcrunner.runtime),
)
}()
notifyCh := make(chan health.StateChange, 2)
svcrunner.healthState.Subscribe(notifyCh)
defer svcrunner.healthState.Unsubscribe(notifyCh)
healthWg.Add(1)
go func() {
defer healthWg.Done()
for {
select {
case <-ctx.Done():
return
case change := <-notifyCh:
svcrunner.healthUpdate(ctx, change)
}
}
}()
}
select {
case <-ctx.Done():
err := runnr.Stop()
<-errCh
if err != nil {
return fmt.Errorf("error stopping service: %w", err)
}
case err := <-errCh:
if err != nil {
return fmt.Errorf("error running service: %w", err)
}
}
return nil
}
// Shutdown initiates shutdown of the service runner
//
// Shutdown completes when Start() returns.
func (svcrunner *ServiceRunner) Shutdown() {
select {
case svcrunner.stopCh <- struct{}{}:
default:
}
}
// AsProto returns protobuf struct with the state of the service runner.
func (svcrunner *ServiceRunner) AsProto() *machineapi.ServiceInfo {
svcrunner.mu.Lock()
defer svcrunner.mu.Unlock()
return &machineapi.ServiceInfo{
Id: svcrunner.id,
State: svcrunner.state.String(),
Events: svcrunner.events.AsProto(events.MaxEventsToKeep),
Health: svcrunner.healthState.AsProto(),
}
}
// Subscribe to a specific event for this service.
//
// Channel `ch` should be buffered or it should have listener attached to it,
// as event might be delivered before Subscribe() returns.
func (svcrunner *ServiceRunner) Subscribe(event StateEvent, ch chan<- struct{}) {
svcrunner.mu.Lock()
if svcrunner.inStateLocked(event) {
svcrunner.mu.Unlock()
// svcrunner is already in expected state, notify immediately
select {
case ch <- struct{}{}:
default:
}
return
}
svcrunner.stateSubscribers[event] = append(svcrunner.stateSubscribers[event], ch)
svcrunner.mu.Unlock()
}
// Unsubscribe cancels subscription established with Subscribe.
func (svcrunner *ServiceRunner) Unsubscribe(event StateEvent, ch chan<- struct{}) {
svcrunner.mu.Lock()
defer svcrunner.mu.Unlock()
channels := svcrunner.stateSubscribers[event]
for i := 0; i < len(channels); {
if channels[i] == ch {
channels[i], channels[len(channels)-1] = channels[len(channels)-1], nil
channels = channels[:len(channels)-1]
} else {
i++
}
}
svcrunner.stateSubscribers[event] = channels
}
func (svcrunner *ServiceRunner) notifyEvent(event StateEvent) {
svcrunner.mu.Lock()
channels := slices.Clone(svcrunner.stateSubscribers[event])
svcrunner.mu.Unlock()
for _, ch := range channels {
select {
case ch <- struct{}{}:
default:
}
}
}
func (svcrunner *ServiceRunner) inStateLocked(event StateEvent) bool {
switch event {
case StateEventUp:
// up when:
// a) either skipped or already finished
// b) or running and healthy (if supports health checks)
switch svcrunner.state { //nolint:exhaustive
case events.StateSkipped, events.StateFinished:
return true
case events.StateRunning:
// check if service supports health checks
_, supportsHealth := svcrunner.service.(HealthcheckedService)
health := svcrunner.healthState.Get()
return !supportsHealth || (health.Healthy != nil && *health.Healthy)
default:
return false
}
case StateEventDown:
// down when in any of the terminal states
switch svcrunner.state { //nolint:exhaustive
case events.StateFailed, events.StateFinished, events.StateSkipped:
return true
default:
return false
}
case StateEventFinished:
if svcrunner.state == events.StateFinished {
return true
}
return false
default:
panic("unsupported event")
}
}