-
Notifications
You must be signed in to change notification settings - Fork 645
/
server.go
66 lines (55 loc) · 1.18 KB
/
server.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
package common
import (
"sync"
"sync/atomic"
"github.com/chubaofs/chubaofs/util/config"
)
const (
StateStandby uint32 = iota
StateStart
StateRunning
StateShutdown
StateStopped
)
type Control struct {
state uint32
wg sync.WaitGroup
}
type Server interface {
Start(cfg *config.Config) error
Shutdown()
// Sync will block invoker goroutine until this MetaNode shutdown.
Sync()
}
type DoStartFunc func(s Server, cfg *config.Config) (err error)
type DoShutdownFunc func(s Server)
func (c *Control) Start(s Server, cfg *config.Config, do DoStartFunc) (err error) {
if atomic.CompareAndSwapUint32(&c.state, StateStandby, StateStart) {
defer func() {
var newState uint32
if err != nil {
newState = StateStandby
} else {
newState = StateRunning
}
atomic.StoreUint32(&c.state, newState)
}()
if err = do(s, cfg); err != nil {
return
}
c.wg.Add(1)
}
return
}
func (c *Control) Shutdown(s Server, do DoShutdownFunc) {
if atomic.CompareAndSwapUint32(&c.state, StateRunning, StateShutdown) {
do(s)
c.wg.Done()
atomic.StoreUint32(&c.state, StateStopped)
}
}
func (c *Control) Sync() {
if atomic.LoadUint32(&c.state) == StateRunning {
c.wg.Wait()
}
}