-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
293 lines (260 loc) · 6.95 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
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
package main
import (
"fmt"
"io"
"net/http"
_ "net/http/pprof"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v3"
)
type HostIp struct {
Name string
Ip string
}
type ProxyConfig struct {
Name string
DialogTimeout int `yaml:"dialogTimeout,omitempty"`
KeepNextHopRoute string `yaml:"keepNextHopRoute,omitempty"`
Listens []struct {
Address string
UDPPort int `yaml:"udp-port,omitempty"`
TCPPort int `yaml:"tcp-port,omitempty"`
Backends []string `yaml:",omitempty"`
Dests []string `yaml:",omitempty"`
NoReceived bool `yaml:"no-received,omitempty"`
defRoute bool `yaml:"def-route,omitempty"`
// True if the route must be recorded in the route header
// False: no record-route will be added to the header if there is any record-route in the header
// If not specified, the route must be recorded in the route header
MustRecordRoute bool `yaml:"must-record-route,omitempty"`
}
Route []struct {
Dests []string
Protocol string
NextHop string
}
Hosts []HostIp
}
type ProxiesConfigure struct {
Admin struct {
Addr string
}
Proxies []ProxyConfig
Hosts []HostIp
}
func init() {
}
func initLog(logFile string, logLevel string, logFormat string, logSize int, backups int) {
var logEncoder zapcore.Encoder
if strings.ToLower(logFormat) == "json" {
logEncoder = zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
} else {
logEncoder = zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
}
level := zapcore.DebugLevel
level.Set(logLevel)
highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= level
})
var out io.Writer = os.Stdout
if len(logFile) > 0 {
out = &lumberjack.Logger{Filename: logFile,
LocalTime: true,
MaxSize: logSize,
MaxBackups: backups}
}
core := zapcore.NewCore(logEncoder, zapcore.AddSync(out), highPriority)
logger := zap.New(core)
zap.ReplaceGlobals(logger)
}
func startProfiling(port int) {
if port > 0 {
go http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
}
func loadConfigFromReader(reader io.Reader) (*ProxiesConfigure, error) {
r := &ProxiesConfigure{}
decoder := yaml.NewDecoder(reader)
err := decoder.Decode(r)
if err != nil {
return nil, err
}
return r, nil
}
func loadConfig(fileName string) (*ProxiesConfigure, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
return loadConfigFromReader(f)
}
func toKeepNextHopRoute(s string) bool {
possibleTrueValues := []string{"true", "yes", "1", "on", "t", "y"}
if s == "" {
s = os.Getenv("KEEP_NEXT_HOP_ROUTE")
}
return slices.Contains(possibleTrueValues, strings.ToLower(s))
}
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")
logSize := c.Int("log-size")
backups := c.Int("log-backups")
logFormat := c.String("log-format")
profilingPort := c.Int("profiling-port")
initLog(fileName, strLevel, logFormat, logSize, backups)
startProfiling(profilingPort)
b, _ := yaml.Marshal(config)
zap.L().Debug("Success load configuration file", zap.String("config", string(b)))
for _, proxy := range config.Proxies {
preConfigRoute := createPreConfigRoute(proxy)
resolver := createPreConfigHostResolver(config.Hosts, proxy)
zap.L().Info("start sip proxy", zap.String("name", proxy.Name))
err = startProxy(proxy, preConfigRoute, resolver)
if err != nil {
return err
}
}
for {
time.Sleep(time.Duration(5 * time.Second))
}
}
func getDefaultDialogTimeout() int {
expire, ok := os.LookupEnv("DEFAULT_DIALOG_TIMEOUT")
if !ok {
return 1200
}
if val, err := strconv.Atoi(expire); err == nil {
return val
}
return 1200
}
func startProxy(config ProxyConfig, preConfigRoute *PreConfigRoute, resolver *PreConfigHostResolver) error {
selfLearnRoute := NewSelfLearnRoute()
dialogTimeout := config.DialogTimeout
if dialogTimeout <= 0 {
dialogTimeout = getDefaultDialogTimeout()
}
proxies := make([]*Proxy, 0)
//proxy := NewProxy(config.Name, int64(dialogTimeout), toKeepNextHopRoute(config.KeepNextHopRoute), preConfigRoute, resolver, selfLearnRoute)
for _, listen := range config.Listens {
proxy := NewProxy(config.Name,
int64(dialogTimeout),
toKeepNextHopRoute(config.KeepNextHopRoute),
preConfigRoute,
resolver,
selfLearnRoute,
!listen.NoReceived,
listen.MustRecordRoute)
item, err := NewProxyItem(listen.Address,
listen.UDPPort,
listen.TCPPort,
listen.Backends,
listen.Dests,
listen.defRoute,
!listen.NoReceived,
proxy,
selfLearnRoute,
proxy)
if err != nil {
zap.L().Error("Fail to start proxy with error", zap.String("error", err.Error()))
return err
}
proxy.AddItem(item)
proxies = append(proxies, proxy)
}
failed_proxies := 0
for _, proxy := range proxies {
err := proxy.Start()
if err == nil {
zap.L().Info("Succeed to start proxy", zap.String("name", config.Name))
} else {
failed_proxies += 1
zap.L().Error("Fail to start proxy", zap.String("name", config.Name))
}
}
if failed_proxies > 0 {
return fmt.Errorf("failed to start %d proxies", failed_proxies)
} else {
return nil
}
}
func createPreConfigRoute(config ProxyConfig) *PreConfigRoute {
preConfigRoute := NewPreConfigRoute()
for _, routeItem := range config.Route {
for _, dest := range routeItem.Dests {
preConfigRoute.AddRouteItem(routeItem.Protocol, dest, routeItem.NextHop)
}
}
return preConfigRoute
}
func createPreConfigHostResolver(globalHostIPs []HostIp, config ProxyConfig) *PreConfigHostResolver {
resolver := NewPreConfigHostResolver()
for _, hostInfo := range globalHostIPs {
resolver.AddHostIP(hostInfo.Name, hostInfo.Ip)
}
for _, hostInfo := range config.Hosts {
resolver.AddHostIP(hostInfo.Name, hostInfo.Ip)
}
return resolver
}
func main() {
app := &cli.App{
Name: "sipproxy",
Usage: "a sip proxy in golang",
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-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,
},
&cli.StringFlag{
Name: "log-format",
Usage: "must be one of: json, text",
Value: "text",
},
&cli.IntFlag{
Name: "profiling-port",
Usage: "the profiling port number",
Value: 0,
},
},
Action: startProxies,
}
err := app.Run(os.Args)
if err != nil {
zap.L().Error("Fail to start application", zap.String("error", err.Error()))
}
}