-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
106 lines (85 loc) · 2 KB
/
run.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
package daemon
import (
"context"
"fmt"
"os"
"os/signal"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
)
var started int32
// IsStarted returns true when daemon.Run() is started and false otherwise.
func IsStarted() bool {
return atomic.CompareAndSwapInt32(&started, 1, 1)
}
// Run starts required goroutines for jobs are specified through the options
// and then blocks execution until termination signal will received from OS
// or any job will return an error or all jobs will done.
func Run(ctx context.Context, options ...Option) error {
if !atomic.CompareAndSwapInt32(&started, 0, 1) {
return fmt.Errorf("already started")
}
defer func() {
resetOptions()
atomic.CompareAndSwapInt32(&started, 1, 0)
}()
if err := applyOptions(options...); err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx)
runner, background := errgroup.WithContext(ctx)
for _, job := range jobs {
if job == nil {
continue
}
job := job
runner.Go(func() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("job failure: %v", r)
}
}()
return job(background)
})
}
waitSignal(background)
cancel()
return release(standstill, runner.Wait)
}
var signals = make(chan os.Signal, 1)
func waitSignal(ctx context.Context) {
signal.Notify(signals) // all available os signals
defer func() {
signal.Stop(signals)
signal.Reset()
}()
for {
select {
case <-ctx.Done():
return
case sig := <-signals:
if _, ok := stops[sig]; ok {
return
}
if action := actions[sig]; action != nil {
go action(ctx)
}
}
}
}
// release runs wait-function in separate goroutine and returns its result
// or error after specified time is expired.
func release(after time.Duration, wait func() error) error {
done := make(chan error, 1)
go func() {
defer close(done)
done <- wait()
}()
select {
case err := <-done:
return err
case <-time.After(after):
return fmt.Errorf("forced release: awaiting period (%s) has expired", after)
}
}