-
Notifications
You must be signed in to change notification settings - Fork 10
/
cube.go
90 lines (74 loc) · 2.2 KB
/
cube.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 cube
import (
"os"
"path/filepath"
"syscall"
"github.com/anuvu/cube/component"
"github.com/anuvu/cube/signal"
)
// ServerInit provides the server initialization function type.
// This function is called to customize server initialization.
type ServerInit func(g component.Group) (Invoker, error)
// Invoker provides the invocation function callback. This function is called
// to invoke any custom functions after the server initialization. If the server
// initialization fails this callback may never be called.
type Invoker func() error
// Main is the entrypoint of the server that can be customized by providing a
// ServerInit function. Developers can create custom components and component
// groups in this function.
//
// By default a signal handler is installed to handle SIGINT and SIGTERM for
// graceful shutdown of the server.
func Main(initF ServerInit) {
name := filepath.Base(os.Args[0])
base := component.New(name + "-core")
base.Add(signal.New)
// Install the signal handler
srvGrp := base.New(name)
srvGrp.Add(newShutHandler)
// Initialize all the server components
invoker, err := initF(srvGrp)
if err != nil {
panic(err)
}
// Create the groups
if err := base.Create(); err != nil {
panic(err)
}
// Configure the server
if err := base.Configure(); err != nil {
panic(err)
}
// Start the server
if err := base.Start(); err != nil {
panic(err)
}
if invoker != nil {
if err := invoker(); err != nil {
panic(err)
}
}
// Wait for shutdown sequence to be initiated by someone
base.Invoke(func(ctx component.Context) {
<-ctx.Ctx().Done()
})
// Stop all the components and exit
if err := base.Stop(); err != nil {
panic(err)
}
}
type shutDownHandler struct {
ctx component.Context
router signal.Router
shutFunc component.ServerShutdown
}
func newShutHandler(ctx component.Context, router signal.Router, shutFunc component.ServerShutdown) *shutDownHandler {
s := &shutDownHandler{ctx, router, shutFunc}
s.router.Handle(syscall.SIGINT, s.shut)
s.router.Handle(syscall.SIGTERM, s.shut)
return s
}
func (s *shutDownHandler) shut(sig os.Signal) {
s.ctx.Log().Info().Str("signal", sig.String()).Msg("Attempting a graceful server shutdown.")
s.shutFunc()
}