-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
196 lines (175 loc) · 4.27 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package main
import (
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v3"
"net/http"
"os"
"runtime"
"time"
)
func createJSONFormatter() *log.JSONFormatter {
return &log.JSONFormatter{
FieldMap: log.FieldMap{
log.FieldKeyTime: "timestamp",
log.FieldKeyLevel: "level",
log.FieldKeyMsg: "message",
},
}
}
func getLogFormat(logFormat string) string {
if len(logFormat) > 0 {
return logFormat
}
t := os.Getenv("LOG_FORMAT")
if len(t) > 0 {
return t
}
return logFormat
}
func init() {
initLog("", getLogFormat(""), "Info", 50*1024*1024, 10)
}
func initLog(logFile string, logFormat string, strLevel string, logSize int, backups int) {
level, err := log.ParseLevel(strLevel)
if err != nil {
level = log.InfoLevel
}
if logFormat == "json" {
log.SetFormatter(createJSONFormatter())
} else {
if runtime.GOOS == "windows" {
log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true})
} else {
log.SetFormatter(&log.TextFormatter{DisableColors: false, FullTimestamp: true})
}
}
log.SetLevel(level)
if len(logFile) <= 0 {
log.SetOutput(os.Stdout)
} else {
log.SetOutput(&lumberjack.Logger{Filename: logFile,
MaxSize: logSize,
MaxBackups: backups})
}
}
type ReadinessConf struct {
Protocol string
Port int
Path string `yaml:"path,omitempty"`
}
type CircuitbreakConf struct {
SuccessiveFailures int `yaml:"successiveFailures"`
PauseTime string `yaml:"pauseTime"`
}
type BackendInfo struct {
Addr string
Readiness *ReadinessConf `yaml:"readiness,omitempty"`
CircuitBreaker *CircuitbreakConf `yaml:"circuitBreaker,omitempty"`
}
type ProxiesConfigure struct {
Admin struct {
Addr string
}
Metrics struct {
Addr string
}
Proxies []struct {
Name string
Listen string
RequestTimeout string `yaml:"requestTimeout,omitempty"`
Backends []BackendInfo
}
}
func loadConfig(fileName string) (*ProxiesConfigure, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
r := &ProxiesConfigure{}
decoder := yaml.NewDecoder(f)
err = decoder.Decode(r)
if err != nil {
return nil, err
}
return r, nil
}
func startMetrics(addr string) {
var server http.Server
server.Addr = addr
router := mux.NewRouter()
router.Handle("/metrics", promhttp.Handler())
server.Handler = router
go server.ListenAndServe()
}
func startProxies(c *cli.Context) error {
config, err := loadConfig(c.String("config"))
if err != nil {
return err
}
strLevel := c.String("log-level")
fileName := c.String("log-file")
logFormat := getLogFormat(c.String("log-format"))
logSize := c.Int("log-size")
backups := c.Int("log-backups")
initLog(fileName, logFormat, strLevel, logSize, backups)
proxyMgr := NewProxyMgr()
admin := NewAdmin(config.Admin.Addr, proxyMgr)
defTimeout := time.Duration(60) * time.Second
for _, proxy := range config.Proxies {
roundRobin := NewRoundrobin()
for _, backend := range proxy.Backends {
roundRobin.AddBackend(&backend)
}
proxyMgr.AddProxy(NewProxy(proxy.Name, proxy.Listen, convertDuration(proxy.RequestTimeout, defTimeout), roundRobin))
}
admin.Start()
startMetrics(config.Metrics.Addr)
proxyMgr.Run()
return nil
}
func main() {
app := &cli.App{
Name: "thriftproxy",
Usage: "a proxy between thrift client and thrift backend servers",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Required: true,
Usage: "Load configuration from `FILE`",
},
&cli.StringFlag{
Name: "log-file",
Usage: "log file name",
},
&cli.StringFlag{
Name: "log-format",
Usage: "log file format: text, json",
},
&cli.StringFlag{
Name: "log-level",
Usage: "one of following level: Trace, Debug, Info, Warn, Error, Fatal, Panic",
},
&cli.IntFlag{
Name: "log-size",
Usage: "size of log file in Megabytes",
Value: 50,
},
&cli.IntFlag{
Name: "log-backups",
Usage: "number of log rotate files",
Value: 10,
},
},
Action: startProxies,
}
err := app.Run(os.Args)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("Fail to start application")
}
}