forked from dobyte/due
-
Notifications
You must be signed in to change notification settings - Fork 1
/
container.go
83 lines (65 loc) · 1.64 KB
/
container.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
package due
import (
"fmt"
"github.com/symsimmy/due/component"
"github.com/symsimmy/due/config"
"github.com/symsimmy/due/eventbus"
"github.com/symsimmy/due/log"
"github.com/symsimmy/due/task"
"github.com/symsimmy/due/utils/xfile"
"os"
"os/signal"
"runtime"
"strconv"
"syscall"
)
type Container struct {
sig chan os.Signal
components []component.Component
}
// NewContainer 创建一个容器
func NewContainer() *Container {
return &Container{sig: make(chan os.Signal)}
}
// Add 添加组件
func (c *Container) Add(components ...component.Component) {
c.components = append(c.components, components...)
}
// Serve 启动容器
func (c *Container) Serve() {
log.Debug(fmt.Sprintf("Welcome to the due framework %s, Learn more at %s", Version, Website))
for _, comp := range c.components {
comp.Init()
}
for _, comp := range c.components {
comp.Start()
}
c.doSavePID()
switch runtime.GOOS {
case `windows`:
signal.Notify(c.sig, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)
default:
signal.Notify(c.sig, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGKILL, syscall.SIGTERM)
}
sig := <-c.sig
log.Warnf("process got signal %v, container will close", sig)
signal.Stop(c.sig)
for _, comp := range c.components {
comp.Destroy()
}
if err := eventbus.Close(); err != nil {
log.Errorf("eventbus close failed: %v", err)
}
task.Release()
config.Close()
}
func (c *Container) doSavePID() {
filename := config.Get("config.pid").String()
if filename == "" {
return
}
err := xfile.WriteFile(filename, []byte(strconv.Itoa(syscall.Getpid())))
if err != nil {
log.Fatalf("pid save failed: %v", err)
}
}