-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
176 lines (162 loc) · 4.74 KB
/
main.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
package main
import (
"context"
"fmt"
"github.com/fasthttp/router"
"github.com/google/gops/agent"
"github.com/revolution1/jsonrpc-proxy/statistic"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/valyala/fasthttp"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
var debugMode bool
func main() {
rootCmd := cobra.Command{
Use: "jsonrpc-proxy",
Short: "proxy for jsonrpc service",
}
flags := rootCmd.Flags()
printVer := flags.BoolP("version", "v", false, "print version")
path := flags.StringP("config", "c", "proxy.yaml", "the path of config file")
_ = rootCmd.MarkFlagFilename("config", "yaml", "yml")
//_ = cobra.MarkFlagRequired(flags, "config")
//ctx, cancel := context.WithCancel(context.Background())
rootCmd.RunE = func(cmd *cobra.Command, args []string) error {
if *printVer {
fmt.Println(printVersion())
return nil
}
// gops agent
if err := agent.Listen(agent.Options{}); err != nil {
return err
}
log.Infof("Loading config from %s", *path)
log.Infof("Version: %s", printVersion())
config, err := LoadConfig(*path)
if err != nil {
return err
}
config.MustValidate()
initLog(config)
return runMain(config)
}
_ = rootCmd.Execute()
}
func runMain(config *Config) error {
CheckFdLimit()
log.Infof("Build: %s %s %s, PID: %d", runtime.GOOS, runtime.Compiler, runtime.Version(), os.Getpid())
r := router.New()
//if debugMode {
// log.Infof("Debug Mode enabled")
// r.GET("/debug/pprof/{name:*}", pprofhandler.PprofHandler)
//}
p := NewProxy(config)
p.RegisterHandler(r)
serverListen := GetHostFromUrl(config.Listen)
manageListen := GetHostFromUrl(config.Manage.Listen)
if config.Statistic.Enabled {
log.Info("initialize statistic collecting")
statistic.InitStatistic(debugMode)
}
var manageServer *fasthttp.Server
m := NewManage(config, p)
if serverListen == manageListen {
log.Warn("Manage Server listens at the same address with RPC Server")
m.registerHandler(r)
} else {
r := router.New()
m.registerHandler(r)
h := useMiddleWares(r.Handler, panicHandler, Cors, fasthttp.CompressHandler, accessLogMetricHandler("[Manage] ", config))
manageServer = newServer("JSON-RPC Proxy Manage Server", h, log.TraceLevel, config)
}
h := useMiddleWares(r.Handler, panicHandler, Cors, fasthttp.CompressHandler, accessLogMetricHandler("", config))
server := newServer("JSON-RPC Proxy Server", h, log.TraceLevel, config)
ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
wg.Add(1)
go runServer(ctx, server, serverListen, wg)
if manageServer != nil {
wg.Add(1)
go runServer(ctx, manageServer, manageListen, wg)
}
sigCh := make(chan os.Signal)
signal.Notify(sigCh, os.Interrupt, os.Kill, syscall.SIGTERM)
go func() {
sig := <-sigCh
log.Infof("received signal '%s', shutting down server...", strings.ToUpper(sig.String()))
cancel()
}()
wg.Wait()
return nil
}
func initLog(config *Config) {
log.SetOutput(os.Stdout)
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.RFC3339,
QuoteEmptyFields: true,
ForceColors: config.LogForceColors,
})
level, err := log.ParseLevel(strings.ToLower(config.LogLevel))
if err != nil {
log.Fatal("Invalid logLevel")
}
debugMode, err = strconv.ParseBool(os.Getenv("DEBUG"))
if err != nil {
debugMode = config.Debug
}
if debugMode && level < log.DebugLevel {
level = log.DebugLevel
}
log.SetLevel(level)
log.Debugf("LogLevel: %s", log.GetLevel())
}
func newServer(name string, h fasthttp.RequestHandler, level log.Level, config *Config) *fasthttp.Server {
return &fasthttp.Server{
Name: name,
Handler: h,
ErrorHandler: nil,
HeaderReceived: nil,
ContinueHandler: nil,
TCPKeepalive: true,
ReadTimeout: config.ReadTimeout.Duration,
WriteTimeout: config.WriteTimeout.Duration,
IdleTimeout: config.IdleTimeout.Duration,
Concurrency: 0,
DisableKeepalive: false,
ReduceMemoryUsage: false,
LogAllErrors: false,
Logger: LeveledLogger{level: level},
}
}
func runServer(ctx context.Context, server *fasthttp.Server, listen string, wg *sync.WaitGroup) {
defer wg.Done()
if listen == "" {
log.Errorf("empty listen address for %s", server.Name)
}
errCh := make(chan error)
go func() {
defer close(errCh)
log.Infof("%s listening at %s", server.Name, listen)
if err := server.ListenAndServe(listen); err != nil {
errCh <- err
}
}()
select {
case err := <-errCh:
log.Infof("%s exited with error %s...", server.Name, err.Error())
case <-ctx.Done():
if err := server.Shutdown(); err != nil {
log.WithError(err).WithField("name", server.Name).Error("error while shutting down server")
}
log.Infof("shutting down %s...", server.Name)
}
}