-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
110 lines (99 loc) · 2.53 KB
/
server.go
File metadata and controls
110 lines (99 loc) · 2.53 KB
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
107
108
109
110
package main
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"github.com/labstack/echo/v4"
"github.com/urfave/cli/v3"
"github.com/openUC2/device-admin/internal/app/server"
"github.com/openUC2/device-admin/internal/app/server/conf"
)
const (
defaultPort = 3001
defaultShutdownTimeout = 5 * time.Second
)
var serverCmd = &cli.Command{
Name: "server",
Action: serverMain,
Flags: []cli.Flag{
// HTTP server
&cli.IntFlag{
Name: "http-port",
Value: defaultPort,
Usage: "port for HTTP server",
Sources: cli.EnvVars("HTTP_PORT"),
},
&cli.StringFlag{
Name: "http-base-path",
Value: "/",
Usage: "base path for HTTP routes",
Sources: cli.EnvVars("HTTP_BASEPATH"),
},
&cli.IntFlag{
Name: "http-gzip-level",
Value: 1,
Usage: "port for HTTP server",
Sources: cli.EnvVars("HTTP_GZIPLEVEL"),
},
&cli.DurationFlag{
Name: "http-shutdown-timeout",
Value: defaultShutdownTimeout,
Usage: "timeout for graceful shutdown before hard shutdown",
Sources: cli.EnvVars("SHUTDOWNTIMEOUT"),
},
// Sidecar
&cli.StringFlag{
Name: "sidecar-address",
Value: "tcp:127.0.0.1:2312",
Usage: "address of varlink service",
Sources: cli.EnvVars("SIDECAR_ADDRESS"),
},
},
}
func serverMain(ctx context.Context, cmd *cli.Command) error {
e := echo.New()
// Get config
config, err := conf.GetConfig()
if err != nil {
return err
}
config.HTTP.Port = cmd.Int("http-port")
config.HTTP.BasePath = cmd.String("http-base-path")
config.HTTP.GzipLevel = cmd.Int("http-gzip-level")
config.Sidecar.Address = cmd.String("sidecar-address")
// Prepare server
s, err := server.New(config, e.Logger)
if err != nil {
return err
}
if err = s.Register(e); err != nil {
return err
}
// Run server
ctxRun, cancelRun := signal.NotifyContext(
ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT,
)
go func() {
if err = s.Run(e); err != nil {
e.Logger.Error(err)
}
cancelRun()
}()
<-ctxRun.Done()
cancelRun()
// Shut down server
shutdownTimeout := cmd.Duration("http-shutdown-timeout")
ctxShutdown, cancelShutdown := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancelShutdown()
e.Logger.Infof("attempting to shut down gracefully within %.1f sec", shutdownTimeout.Seconds())
if err := s.Shutdown(ctxShutdown, e); err != nil {
e.Logger.Warn("forcibly closing http server due to failure of graceful shutdown")
if closeErr := s.Close(e); closeErr != nil {
return closeErr
}
}
e.Logger.Info("finished shutdown")
return nil
}