-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
92 lines (80 loc) · 2.22 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
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
package server
import (
"context"
"io/ioutil"
"net/http"
"time"
"github.com/YLonely/sysdig-monitor/server/controller/prometheus"
"github.com/YLonely/sysdig-monitor/server/controller"
"github.com/gin-gonic/gin"
"github.com/YLonely/sysdig-monitor/log"
"github.com/YLonely/sysdig-monitor/server/controller/container"
)
// Config containes params to start a server, only port now
type Config struct {
Port string
}
// Server is the interface of a monitor server
type Server interface {
Start() chan error
Shutdown() error
}
type server struct {
conf Config
httpServer *http.Server
cancle context.CancelFunc
ctx context.Context
controllers []controller.Controller
}
func NewServer(ctx context.Context, conf Config) Server {
res := &server{conf: conf}
ctx, cancle := context.WithCancel(ctx)
res.cancle = cancle
res.ctx = ctx
return res
}
func (s *server) Start() chan error {
errch := make(chan error, 1)
//TODO: may be use plugin method to registry and manage all the controllers?
containerController, err := container.NewController(s.ctx)
if err != nil {
errch <- err
return errch
}
promController, err := prometheus.NewController(s.ctx)
if err != nil {
errch <- err
return errch
}
s.controllers = append(s.controllers, containerController, promController)
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = ioutil.Discard
ginServer := gin.Default()
initRoutes(ginServer, s.controllers...) // may be more controller?
s.httpServer = &http.Server{Addr: s.conf.Port, Handler: ginServer}
go func() {
if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errch <- err
}
}()
log.L.Info("web server start. Listening on port " + s.conf.Port)
return errch
}
func (s *server) Shutdown() error {
ctx, cancel := context.WithTimeout(s.ctx, time.Second*3)
defer cancel()
err := s.httpServer.Shutdown(ctx)
s.cancle()
for _, c := range s.controllers {
c.Release()
}
return err
}
func initRoutes(ginServer *gin.Engine, controllers ...controller.Controller) {
for _, controller := range controllers {
routes := controller.BindedRoutes()
for _, route := range routes {
ginServer.Handle(route.Method(), route.Path(), gin.HandlerFunc(route.Handler()))
}
}
}