-
Notifications
You must be signed in to change notification settings - Fork 200
/
main.go
163 lines (130 loc) · 5.43 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
// MIT License
// Copyright (c) [2022] [Bohdan Ivashko (https://github.com/Arriven)]
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"context"
"flag"
"math/rand"
"net/http"
pprofhttp "net/http/pprof"
"os"
"strings"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/Arriven/db1000n/src/job"
"github.com/Arriven/db1000n/src/job/config"
"github.com/Arriven/db1000n/src/utils"
"github.com/Arriven/db1000n/src/utils/metrics"
"github.com/Arriven/db1000n/src/utils/ota"
)
const simpleLogFormat = "simple"
func main() {
runnerConfigOptions := job.NewConfigOptionsWithFlags()
jobsGlobalConfig := job.NewGlobalConfigWithFlags()
otaConfig := ota.NewConfigWithFlags()
countryCheckerConfig := utils.NewCountryCheckerConfigWithFlags()
updaterMode, destinationPath := config.NewUpdaterOptionsWithFlags()
prometheusOn, prometheusListenAddress := metrics.NewOptionsWithFlags()
pprof := flag.String("pprof", utils.GetEnvStringDefault("GO_PPROF_ENDPOINT", ""), "enable pprof")
help := flag.Bool("h", false, "print help message and exit")
version := flag.Bool("version", false, "print version and exit")
debug := flag.Bool("debug", utils.GetEnvBoolDefault("DEBUG", false), "enable debug level logging and features")
logLevel := flag.String("log-level", utils.GetEnvStringDefault("LOG_LEVEL", "none"), "log level override for zap, leave empty to use default")
logFormat := flag.String("log-format", utils.GetEnvStringDefault("LOG_FORMAT", simpleLogFormat), "overrides the default (simple) log output format,\n"+
"possible values are: json, console, simple\n"+
"simple is the most human readable format if you only look at the output in your terminal")
flag.Parse()
logger, err := newZapLogger(*debug, *logLevel, *logFormat)
if err != nil {
panic(err)
}
logger.Info("running db1000n", zap.String("version", ota.Version), zap.Int("pid", os.Getpid()))
switch {
case *help:
flag.CommandLine.Usage()
return
case *version:
return
case *updaterMode:
config.UpdateLocal(logger, *destinationPath, strings.Split(runnerConfigOptions.PathsCSV, ","), []byte(runnerConfigOptions.BackupConfig))
return
}
err = utils.UpdateRLimit()
if err != nil {
logger.Warn("failed to increase rlimit", zap.Error(err))
}
go ota.WatchUpdates(logger, otaConfig)
setUpPprof(logger, *pprof, *debug)
rand.Seed(time.Now().UnixNano())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
country := utils.CheckCountryOrFail(ctx, logger, countryCheckerConfig, jobsGlobalConfig.GetProxyParams(logger, nil))
metrics.InitOrFail(ctx, logger, *prometheusOn, *prometheusListenAddress, jobsGlobalConfig.ClientID, country)
reporter := newReporter(*logFormat, logger)
job.NewRunner(runnerConfigOptions, jobsGlobalConfig, reporter).Run(ctx, logger)
}
func newZapLogger(debug bool, logLevel string, logFormat string) (*zap.Logger, error) {
cfg := zap.NewProductionConfig()
if debug {
cfg = zap.NewDevelopmentConfig()
}
if logFormat == simpleLogFormat {
// turn off all output except the message itself and log level
cfg.Encoding = "console"
cfg.EncoderConfig.TimeKey = ""
cfg.EncoderConfig.NameKey = ""
// turning these off for debug output would be undesirable
if !debug {
cfg.EncoderConfig.CallerKey = ""
cfg.EncoderConfig.StacktraceKey = ""
}
} else if logFormat != "" {
cfg.Encoding = logFormat
if logFormat == "console" {
cfg.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
}
}
level, err := zap.ParseAtomicLevel(logLevel)
if err == nil {
cfg.Level = level
}
return cfg.Build()
}
func setUpPprof(logger *zap.Logger, pprof string, debug bool) {
switch {
case debug && pprof == "":
pprof = ":8080"
case pprof == "":
return
}
mux := http.NewServeMux()
mux.Handle("/debug/pprof/", http.HandlerFunc(pprofhttp.Index))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprofhttp.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprofhttp.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprofhttp.Symbol))
mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprofhttp.Trace))
// this has to be wrapped into a lambda bc otherwise it blocks when evaluating argument for zap.Error
go func() { logger.Warn("pprof server", zap.Error(http.ListenAndServe(pprof, mux))) }()
}
func newReporter(logFormat string, logger *zap.Logger) metrics.Reporter {
if logFormat == simpleLogFormat {
return metrics.NewConsoleReporter(os.Stdout)
}
return metrics.NewZapReporter(logger)
}