-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
230 lines (206 loc) · 6.24 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package server
import (
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"time"
authz "github.com/CHESSComputing/golib/authz"
srvConfig "github.com/CHESSComputing/golib/config"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
logging "github.com/vkuznet/http-logging"
)
var _routes gin.RoutesInfo
var metricsPrefix string
// StartTime represents initial time when we started the server
var StartTime time.Time
// Route represents routes structure
type Route struct {
Method string
Path string
Scope string
Authorized bool
Handler gin.HandlerFunc
}
// StartServer starts HTTP(s) server
func StartServer(r *gin.Engine, webServer srvConfig.WebServer) {
sport := fmt.Sprintf(":%d", webServer.Port)
if webServer.ServerKey != "" {
certFile := webServer.ServerCrt
ckeyFile := webServer.ServerKey
log.Println("Start HTTPs server on port", sport)
r.RunTLS(sport, certFile, ckeyFile)
} else {
log.Println("Start HTTP server on port", sport)
r.Run(sport)
}
}
// InitServer provides server initialization
func InitServer(webServer srvConfig.WebServer) {
StartTime = time.Now()
// setup log options
rotateLogs(webServer.LogFile)
// setup log options
log.SetFlags(log.LstdFlags | log.Lshortfile)
if webServer.LogLongFile {
log.SetFlags(log.LstdFlags | log.Llongfile)
}
// setup limiter
if webServer.LimiterPeriod == "" {
// default 100 request per second
webServer.LimiterPeriod = "100-S"
}
initLimiter(webServer.LimiterPeriod, webServer.LimiterHeader)
metricsPrefix = webServer.MetricsPrefix
// setup gin options
if webServer.GinOptions.DisableConsoleColor {
// Disable Console Color
gin.DisableConsoleColor()
}
// set gin mode of operation
if webServer.GinOptions.Mode == "release" {
gin.SetMode(gin.ReleaseMode)
} else if webServer.GinOptions.Mode == "debug" {
gin.SetMode(gin.DebugMode)
} else if webServer.GinOptions.Mode == "test" {
gin.SetMode(gin.TestMode)
}
// use production flag to overwrite gin mode
if webServer.GinOptions.Production {
gin.SetMode(gin.ReleaseMode)
}
log.Printf("webServer configuration:\n%s", webServer.String())
}
// Router provids server router, it takes two maps:
// one for non-authorized routes and anotehr for authorized ones
func Router(routes []Route, fsys fs.FS, static string, webServer srvConfig.WebServer) *gin.Engine {
base := webServer.Base
verbose := webServer.Verbose
InitServer(webServer)
// setup gin router
r := gin.New()
// initialize cookie store (used by authz module and oauth)
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("server_session", store))
// GET routes
r.GET("/apis", ApisHandler)
r.GET("/metrics", MetricsHandler)
// loop over routes and creates necessary router structure
var authGroup bool
var readRoutes, writeRoutes []Route
for _, route := range routes {
if route.Authorized {
authGroup = true
if route.Scope == "write" {
writeRoutes = append(writeRoutes, route)
} else {
readRoutes = append(readRoutes, route)
}
continue
}
log.Printf("method %s path %s auth %v scope '%s'", route.Method, route.Path, route.Authorized, route.Scope)
if route.Method == "GET" {
r.GET(route.Path, route.Handler)
} else if route.Method == "POST" {
r.POST(route.Path, route.Handler)
} else if route.Method == "PUT" {
r.PUT(route.Path, route.Handler)
} else if route.Method == "DELETE" {
r.DELETE(route.Path, route.Handler)
}
}
// all authorized routes
if authGroup {
authorizedRead := r.Group("/")
// authorizedRead.Use(authz.TokenMiddleware(srvConfig.Config.Authz.ClientID, verbose))
authorizedRead.Use(authz.ScopeTokenMiddleware("read", srvConfig.Config.Authz.ClientID, verbose))
{
for _, route := range readRoutes {
if !route.Authorized {
continue
}
log.Printf("method %s path %s auth %v scope '%s'", route.Method, route.Path, route.Authorized, route.Scope)
if route.Method == "GET" {
authorizedRead.GET(route.Path, route.Handler)
} else if route.Method == "POST" {
authorizedRead.POST(route.Path, route.Handler)
} else if route.Method == "PUT" {
authorizedRead.PUT(route.Path, route.Handler)
} else if route.Method == "DELETE" {
authorizedRead.DELETE(route.Path, route.Handler)
}
}
}
authorizedWrite := r.Group("/")
authorizedWrite.Use(authz.ScopeTokenMiddleware("write", srvConfig.Config.Authz.ClientID, verbose))
{
for _, route := range writeRoutes {
if !route.Authorized {
continue
}
log.Printf("method %s path %s auth %v scope '%s'", route.Method, route.Path, route.Authorized, route.Scope)
if route.Method == "GET" {
authorizedWrite.GET(route.Path, route.Handler)
} else if route.Method == "POST" {
authorizedWrite.POST(route.Path, route.Handler)
} else if route.Method == "PUT" {
authorizedWrite.PUT(route.Path, route.Handler)
} else if route.Method == "DELETE" {
authorizedWrite.DELETE(route.Path, route.Handler)
}
}
}
}
// static files
if fsys != nil {
if entries, err := os.ReadDir(static); err == nil {
for _, e := range entries {
dir := e.Name()
filesFS, err := fs.Sub(fsys, filepath.Join(static, dir))
if err != nil {
panic(err)
}
m := fmt.Sprintf("%s/%s", base, dir)
r.StaticFS(m, http.FS(filesFS))
}
}
}
_routes = r.Routes()
// use common middlewares
r.Use(CounterMiddleware())
r.Use(LimiterMiddleware)
r.Use(HeaderMiddleware(webServer))
return r
}
// helper function to rotate logs
func rotateLogs(srvLogName string) {
if srvLogName != "" {
log.SetOutput(new(logging.LogWriter))
rl, err := rotatelogs.New(logName(srvLogName))
if err == nil {
rotlogs := logging.RotateLogWriter{RotateLogs: rl}
log.SetOutput(rotlogs)
}
}
}
// logName returns proper log name based on Config LogFile and either
// hostname or pod name (used in k8s environment).
func logName(srvLogName string) string {
hostname, err := os.Hostname()
if err != nil {
log.Println("unable to get hostname", err)
}
if os.Getenv("MY_POD_NAME") != "" {
hostname = os.Getenv("MY_POD_NAME")
}
logName := srvLogName + "_%Y%m%d"
if hostname != "" {
logName = fmt.Sprintf("%s_%s", srvLogName, hostname) + "_%Y%m%d"
}
return logName
}