-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice.go
90 lines (73 loc) · 1.95 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
package tinytcp
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
var shutdownSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}
// Service represents concurrent job, that is expected to run in background for the whole lifetime of the process.
type Service interface {
// Start is expected to start execution of the service and block.
// If the execution cannot be started, or it fails abruptly, it should return a non-nil error.
Start() error
// Stop is expected to stop the running service gracefully and unblock the thread used by Start function.
Stop() error
}
// StartAndBlock starts all passed services in their designated goroutines and then blocks the current thread.
// Thread is unblocked when the process receives SIGINT or SIGTERM signals or one of the Start() functions returns an error.
// When exiting, StartAndBlock gracefully stops all the services by calling their Stop() functions and waiting for them to exit.
func StartAndBlock(services ...Service) (err error) {
errorChannel := make(chan error)
for _, service := range services {
s := service
go func() {
defer func() {
if r := recover(); r != nil {
select {
case errorChannel <- fmt.Errorf("%v", r):
default:
}
}
}()
if err := s.Start(); err != nil {
select {
case errorChannel <- err:
default:
}
}
}()
}
defer func() {
wg := &sync.WaitGroup{}
wg.Add(len(services))
for _, service := range services {
s := service
go func() {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
wg.Done()
}()
err = s.Stop()
}()
}
wg.Wait()
}()
err = blockThread(errorChannel)
return
}
func blockThread(errorChannel <-chan error) error {
shutdownSignalsChannel := make(chan os.Signal)
signal.Notify(shutdownSignalsChannel, shutdownSignals...)
for {
select {
case err := <-errorChannel:
return err
case <-shutdownSignalsChannel:
return nil
}
}
}