-
Notifications
You must be signed in to change notification settings - Fork 0
/
servecmd.go
303 lines (258 loc) · 7.41 KB
/
servecmd.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package cmd
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/chutommy/eetgateway/pkg/ca"
"github.com/chutommy/eetgateway/pkg/fscr"
"github.com/chutommy/eetgateway/pkg/gateway"
"github.com/chutommy/eetgateway/pkg/keystore"
"github.com/chutommy/eetgateway/pkg/server"
"github.com/fsnotify/fsnotify"
"github.com/go-redis/redis/v8"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
configPathFlag = "config"
)
func initServeCmd() {
configDir, err := osConfigDir()
if err != nil {
panic(err)
}
configPath := filepath.Join(configDir, configFile)
serveCmd.Flags().StringP(configPathFlag, "c", configPath, "path to config file")
}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Initialize the EET Gateway server",
Long: "Serve initializes all services required to properly run EET Gateway server.",
Args: cobra.NoArgs,
RunE: serveCmdRunE,
}
func serveCmdRunE(cmd *cobra.Command, _ []string) error {
configPath, err := cmd.Flags().GetString(configPathFlag)
if err != nil {
return fmt.Errorf("retrieve 'path' flag: %w", err)
}
configSetDefault()
err = configLoadFromFile(configPath)
if err != nil {
return fmt.Errorf("load config from file: %w", err)
}
setupLogger()
log.Info().
Str("entity", "EET Gateway").
Str("action", "initiating").
Send()
defer log.Info().
Str("entity", "EET Gateway").
Str("action", "exiting").
Send()
log.Info().
Str("entity", "Config Service").
Str("action", "loading config file").
Str("status", "config file located").
Str("path", configPath).
Send()
configWatch()
configLoadFromENV()
caSvc, err := newCASvc()
if err != nil {
return fmt.Errorf("start CA service: %w", err)
}
client, err := newFSCRClient()
if err != nil {
return fmt.Errorf("start FSCR client: %w", err)
}
ks := newKeystoreSvc()
// EET Gateway service
log.Info().
Str("entity", "HTTP Server").
Str("action", "starting").
Str("addr", viper.GetString(serverAddr)).
Dur("idleTimeout", viper.GetDuration(serverIdleTimeout)).
Dur("writeTimeout", viper.GetDuration(serverWriteTimeout)).
Dur("readTimeout", viper.GetDuration(serverReadTimeout)).
Dur("readHeaderTimeout", viper.GetDuration(serverReadHeaderTimeout)).
Int("maxHeaderBytes", viper.GetInt(serverMaxHeaderBytes)).
Send()
gSvc := gateway.NewService(client, caSvc, ks)
h := server.NewHTTPHandler(gSvc)
srv := server.NewService(&http.Server{
Addr: viper.GetString(serverAddr),
ReadTimeout: viper.GetDuration(serverReadTimeout),
ReadHeaderTimeout: viper.GetDuration(serverReadHeaderTimeout),
WriteTimeout: viper.GetDuration(serverWriteTimeout),
IdleTimeout: viper.GetDuration(serverIdleTimeout),
MaxHeaderBytes: viper.GetInt(serverMaxHeaderBytes),
Handler: h.HTTPHandler(),
// TLSConfig: &tls.Config{
// ServerName: "",
// Certificates: nil,
// RootCAs: nil,
// ClientCAs: nil,
// MinVersion: tls.VersionTLS13,
// },
})
// HTTP server
log.Info().
Str("entity", "HTTP Server").
Str("action", "listening").
Str("status", "online").
Dur("shutdownTimeout", viper.GetDuration(serverShutdownTimeout)).
Send()
err = srv.ListenAndServe(viper.GetDuration(serverShutdownTimeout))
log.Info().
Str("entity", "HTTP Server").
Str("action", "shutting down").
Str("status", "offline").
Err(err).
Send()
return nil
}
func newKeystoreSvc() keystore.Service {
log.Info().
Str("entity", "KeyStore Client").
Str("action", "starting").
Str("network", viper.GetString(redisNetwork)).
Str("addr", viper.GetString(redisAddr)).
Int("db", viper.GetInt(redisDB)).
Int("minIdleConns", viper.GetInt(redisMinIdleConns)).
Send()
ks := keystore.NewRedisService(redis.NewClient(&redis.Options{
Network: viper.GetString(redisNetwork),
Addr: viper.GetString(redisAddr),
Username: viper.GetString(redisUsername),
Password: viper.GetString(redisPassword),
DB: viper.GetInt(redisDB),
PoolSize: viper.GetInt(redisPoolSize),
MinIdleConns: viper.GetInt(redisMinIdleConns),
IdleTimeout: viper.GetDuration(redisIdleTimeout),
DialTimeout: viper.GetDuration(redisDialTimeout),
ReadTimeout: viper.GetDuration(redisReadTimeout),
WriteTimeout: viper.GetDuration(redisWriteTimeout),
PoolTimeout: viper.GetDuration(redisPoolTimeout),
IdleCheckFrequency: viper.GetDuration(redisIdleCheckFrequency),
// TLSConfig: &tls.Config{
// ServerName: "",
// Certificates: nil,
// RootCAs: nil,
// ClientCAs: nil,
// MinVersion: tls.VersionTLS13,
// },
}))
return ks
}
func newFSCRClient() (fscr.Client, error) {
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("retrieve system certificate pool: %w", err)
}
url, mode := fscrURL()
log.Info().
Str("entity", "FSCR Client").
Str("action", "starting").
Str("url", url).
Str("mode", mode).
Send()
c := fscr.NewClient(&http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
// ServerName: "",
// Certificates: nil,
RootCAs: certPool,
// ClientCAs: nil,
MinVersion: tls.VersionTLS13,
},
},
}, url)
return c, nil
}
func fscrURL() (string, string) {
url := fscr.PlaygroundURL
mode := "playground"
if viper.GetBool(eetProductionMode) {
url = fscr.ProductionURL
mode = "production"
}
return url, mode
}
func newCASvc() (fscr.CAService, error) {
mode, roots, err := getCARoots()
if err != nil {
return nil, fmt.Errorf("fetch CA roots and mode")
}
dsigPool := x509.NewCertPool()
if ok := dsigPool.AppendCertsFromPEM(ca.ICACertificate); !ok {
return nil, fmt.Errorf("append to dsig certificate pool")
}
log.Info().
Str("entity", "Certificate Authority Service").
Str("action", "starting").
Str("mode", mode).
Send()
return fscr.NewCAService(roots, dsigPool), nil
}
func getCARoots() (string, []*x509.Certificate, error) {
mode := "playground"
roots, err := ca.PlaygroundRoots()
if err != nil {
return "", nil, fmt.Errorf("retrieve playground roots: %w", err)
}
if viper.GetBool(eetProductionMode) {
mode = "production"
roots, err = ca.ProductionRoots()
if err != nil {
return "", nil, fmt.Errorf("retrieve production roots: %w", err)
}
}
return mode, roots, nil
}
func configLoadFromFile(path string) error {
ext := filepath.Ext(path)
name := strings.TrimSuffix(filepath.Base(path), ext)
dir := filepath.Dir(path)
viper.SetConfigName(name)
viper.SetConfigType(ext[1:])
viper.AddConfigPath(dir)
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("read config file: %w", err)
}
return nil
}
func configLoadFromENV() {
viper.SetEnvPrefix("EETG")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
}
func configWatch() {
viper.OnConfigChange(func(e fsnotify.Event) {
log.Info().
Str("entity", "Config Service").
Str("action", "watching config file").
Str("status", "config file changed").
Str("operation", e.Op.String()).
Str("path", e.Name).
Str("note", "restart server to take effect").
Send()
})
viper.WatchConfig()
}
func setupLogger() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
zerolog.DurationFieldUnit = time.Second
if viper.GetBool(apiQuietMode) {
log.Logger = zerolog.Nop()
} else {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
}