-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
service.go
106 lines (94 loc) · 1.89 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
package service
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"github.com/hashicorp/go-multierror"
"github.com/plgd-dev/hub/v2/pkg/fn"
"go.uber.org/atomic"
)
type Service struct {
services []APIService
done chan struct{}
sigs chan os.Signal
closeFn fn.FuncList
serving atomic.Bool
}
type APIService interface {
Serve() error
Close() error
}
func New(services ...APIService) *Service {
return &Service{
sigs: make(chan os.Signal, 1),
done: make(chan struct{}),
services: services,
}
}
// Add adds other API services. This needs to be called before Serve.
func (s *Service) Add(services ...APIService) {
s.services = append(s.services, services...)
}
func (s *Service) Serve() error {
if !s.serving.CompareAndSwap(false, true) {
return fmt.Errorf("already serving")
}
defer close(s.done)
var wg sync.WaitGroup
errCh := make(chan error, len(s.services)*2)
wg.Add(len(s.services))
for _, apiService := range s.services {
go func(serve func() error) {
defer wg.Done()
err := serve()
errCh <- err
}(apiService.Serve)
}
signal.Notify(s.sigs,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
<-s.sigs
for _, apiService := range s.services {
err := apiService.Close()
errCh <- err
}
wg.Wait()
s.closeFn.Execute()
var errors *multierror.Error
for {
select {
case err := <-errCh:
if err != nil {
errors = multierror.Append(errors, err)
}
default:
return errors.ErrorOrNil()
}
}
}
func (s *Service) Signal(sig os.Signal) {
select {
case s.sigs <- sig:
default:
}
}
func (s *Service) SigTerm() {
s.Signal(syscall.SIGTERM)
}
// Shutdown turn off server.
func (s *Service) Close() error {
s.SigTerm()
if !s.serving.Load() {
return nil
}
<-s.done
return nil
}
// AddCloseFunc adds a function to be called when the server is closed
func (s *Service) AddCloseFunc(f func()) {
s.closeFn.AddFunc(f)
}