-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
328 lines (292 loc) · 7.86 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package main
import (
"fmt"
"io"
"os"
"runtime"
"sort"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog"
"github.com/rs/zerolog/diode"
"github.com/urfave/cli/v2"
application "github.com/MindHunter86/addie/app"
"github.com/MindHunter86/addie/utils"
)
var version = "devel" // -ldflags="-X main.version=X.X.X"
var buildtime = "never"
func main() {
retcode := 0
defer func() { os.Exit(retcode) }()
// non-blocking writer
dwr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
fmt.Fprintf(os.Stderr, "diodes dropped %d messages; check your log-rate, please\n", missed)
})
defer dwr.Close()
// logger
log := zerolog.New(zerolog.ConsoleWriter{
Out: dwr,
}).With().Timestamp().Caller().Logger()
// .Hook(SeverityHook{})
zerolog.CallerMarshalFunc = callerMarshalFunc
zerolog.TimeFieldFormat = time.RFC3339Nano
zerolog.SetGlobalLevel(zerolog.DebugLevel)
// application
app := cli.NewApp()
cli.VersionFlag = &cli.BoolFlag{Name: "version", Aliases: []string{"V"}}
app.Name = "addie"
app.Version = fmt.Sprintf("%s\t%s", version, buildtime)
app.Authors = []*cli.Author{
&cli.Author{
Name: "MindHunter86",
Email: "mindhunter86@vkom.cc",
},
}
app.Copyright = "(c) 2022-2023 mindhunter86\nwith love for Anilibria project"
app.Usage = "AniLibria media delivery manager (ADDIE)"
app.Flags = []cli.Flag{
// common flags
&cli.StringFlag{
Name: "log-level",
Aliases: []string{"l"},
Value: "debug",
Usage: "levels: trace, debug, info, warn, err, panic, disabled",
EnvVars: []string{"LOG_LEVEL"},
},
&cli.BoolFlag{
Name: "quite",
Aliases: []string{"q"},
Usage: "Flag is equivalent to --log-level=quite",
},
&cli.StringFlag{
Name: "syslog-server",
Value: "",
EnvVars: []string{"SYSLOG_ADDRESS"},
},
&cli.StringFlag{
Name: "syslog-proto",
Value: "tcp",
},
&cli.StringFlag{
Name: "syslog-tag",
Value: "",
},
// http client settings
&cli.BoolFlag{
Name: "http-client-insecure",
Usage: "Flag for TLS certificate verification disabling",
},
&cli.DurationFlag{
Name: "http-client-timeout",
Usage: "Internal HTTP client connection `TIMEOUT` (format: 1000ms, 1s)",
Value: 3 * time.Second,
},
&cli.DurationFlag{
Name: "http-tcp-timeout",
Usage: "",
Value: 1 * time.Second,
},
&cli.DurationFlag{
Name: "http-tls-handshake-timeout",
Usage: "",
Value: 1 * time.Second,
},
&cli.DurationFlag{
Name: "http-idle-timeout",
Usage: "",
Value: 300 * time.Second,
},
&cli.DurationFlag{
Name: "http-keepalive-timeout",
Usage: "",
Value: 300 * time.Second,
},
&cli.IntFlag{
Name: "http-max-idle-conns",
Usage: "",
Value: 100,
},
&cli.BoolFlag{
Name: "http-debug",
Usage: "",
},
// fiber (http server) settings
&cli.StringFlag{
Name: "http-listen-addr",
Usage: "Ex: 127.0.0.1:8080, :8080",
Value: "127.0.0.1:8080",
},
&cli.StringFlag{
Name: "http-trusted-proxies",
Usage: "Ex: 10.0.0.0/8; Separated by comma",
},
&cli.BoolFlag{
Name: "http-prefork",
Usage: `Enables use of the SO_REUSEPORT socket option;
if enabled, the application will need to be ran
through a shell because prefork mode sets environment variables`,
},
&cli.BoolFlag{
Name: "http-cors",
Usage: "enable cors requests serving",
Value: true,
},
&cli.BoolFlag{
Name: "http-pprof-enable",
Usage: "enable golang http-pprof methods",
},
// limiter settings
&cli.BoolFlag{
Name: "limiter-use-bbolt",
Usage: "use bbolt key\value file database instead of memory database",
},
&cli.IntFlag{
Name: "limiter-max-req",
Value: 200,
},
&cli.DurationFlag{
Name: "limiter-records-duration",
Value: 5 * time.Minute,
},
// balancer
&cli.UintFlag{
Name: "balancer-max-tries",
Usage: "max fails for one request; max value - 10",
Value: 3,
},
// bbolt settings
&cli.StringFlag{
Name: "database-prefix",
Value: ".",
},
// anilibria settings
&cli.StringFlag{
Name: "anilibria-baseurl",
Usage: "",
Value: "https://www.anilibria.tv",
},
&cli.StringFlag{
Name: "anilibria-api-baseurl",
Usage: "",
Value: "https://api.anilibria.tv/v2",
},
// ...
&cli.DurationFlag{
Name: "link-expiration",
Usage: "",
Value: 10 * time.Second,
EnvVars: []string{"LINK_EXPIRATION"},
},
&cli.StringFlag{
Name: "link-secret",
Usage: "",
Value: "TZj3Ts1Lsvk",
EnvVars: []string{"SIGN_SECRET"},
DefaultText: "CHANGE DEFAULT SECRET",
},
// consul settings
&cli.BoolFlag{
Name: "consul-ignore-errors",
},
&cli.StringFlag{
Name: "consul-address",
Usage: "consul API uri",
Value: "http://127.0.0.1:8500",
EnvVars: []string{"CONSUL_ADDRESS"},
},
&cli.StringFlag{
Name: "consul-service-nodes",
Usage: "service name (id) with cache-nodes used for balancing",
Value: "cache-node-internal",
},
&cli.StringFlag{
Name: "consul-service-cloud",
Usage: "service name (id) with cache-clouds used for balancing",
Value: "cache-cloud-ingress",
},
&cli.StringFlag{
Name: "consul-entries-domain",
Usage: "add domain for all service entries",
Value: "libria.fun",
},
&cli.StringFlag{
Name: "consul-kv-prefix",
Value: fmt.Sprintf("anilibria/%s", app.Name),
},
}
app.Action = func(c *cli.Context) (e error) {
var lvl zerolog.Level
if lvl, e = zerolog.ParseLevel(c.String("log-level")); e != nil {
log.Fatal().Err(e).Msg("")
}
zerolog.SetGlobalLevel(lvl)
if c.Bool("quite") {
zerolog.SetGlobalLevel(zerolog.Disabled)
}
var syslogWriter = io.Discard
if len(c.String("syslog-server")) != 0 {
if runtime.GOOS == "windows" {
log.Error().Msg("sorry, but syslog is not worked for windows; golang does not support syslog for win systems")
return os.ErrProcessDone
}
log.Debug().Msg("connecting to syslog server ...")
if syslogWriter, e = utils.SetUpSyslogWriter(c); e != nil {
return
}
log.Debug().Msg("syslog connection established; reset zerolog for MultiLevelWriter set ...")
log = zerolog.New(zerolog.MultiLevelWriter(
zerolog.ConsoleWriter{Out: dwr},
syslogWriter,
)).With().Timestamp().Caller().Logger()
log.Info().Msg("zerolog reinitialized; starting app...")
}
if !fiber.IsChild() {
log.Info().Msgf("system cpu count %d", runtime.NumCPU())
log.Info().Msgf("cmdline - %v", os.Args)
log.Debug().Msgf("environment - %v", os.Environ())
} else {
log.Info().Msgf("system cpu count %d", runtime.NumCPU())
log.Info().Msgf("old cpu count %d", runtime.GOMAXPROCS(1))
log.Info().Msgf("new cpu count %d", runtime.GOMAXPROCS(1))
}
log.Debug().Msgf("%s (%s) builded %s now is ready...", app.Name, version, buildtime)
return application.NewApp(c, &log, syslogWriter).Bootstrap()
}
// TODO sort.Sort of Flags uses too much allocs; temporary disabled
// sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
if e := app.Run(os.Args); e != nil {
log.WithLevel(zerolog.FatalLevel).Msg(e.Error())
retcode = 1
}
// fucking diode was no `wait` method, so we need to use this `250` shit
log.Debug().Msg("waiting for diode buf")
time.Sleep(250 * time.Millisecond)
}
// type SeverityHook struct{}
// func (SeverityHook) Run(e *zerolog.Event, level zerolog.Level, _ string) {
// if level > zerolog.DebugLevel || version != "devel" {
// return
// }
// rfn := "unknown"
// pcs := make([]uintptr, 1)
// if runtime.Callers(4, pcs) != 0 {
// if fun := runtime.FuncForPC(pcs[0] - 1); fun != nil {
// rfn = fun.Name()
// }
// }
// fn := strings.Split(rfn, "/")
// e.Str("func", fn[len(fn)-1:][0])
// }
func callerMarshalFunc(_ uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}