forked from atlassian/gostatsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gostatsd.go
168 lines (143 loc) · 4.29 KB
/
gostatsd.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
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"github.com/atlassian/gostatsd/statsd"
log "github.com/Sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"golang.org/x/net/context"
)
var (
// BuildDate is the date when the binary was built.
BuildDate string
// GitCommit is the commit hash when the binary was built.
GitCommit string
// Version is the version of the binary.
Version string
)
const (
// ParamVerbose enables verbose logging.
ParamVerbose = "verbose"
// ParamJSON makes logger log in JSON format.
ParamJSON = "json"
// ParamConfigPath provides file with configuration.
ParamConfigPath = "config-path"
// ParamVersion makes program output its version.
ParamVersion = "version"
)
// EnvPrefix is the prefix of the inspected environment variables.
const EnvPrefix = "GSD" //Go Stats D
func main() {
v, version, err := setupConfiguration()
if err != nil {
if err == pflag.ErrHelp {
return
}
log.Fatalf("Error while parsing configuration: %v", err)
}
if version {
fmt.Printf("Version: %s - Commit: %s - Date: %s\n", Version, GitCommit, BuildDate)
return
}
var exitErr error
defer func() {
if exitErr != nil {
log.Fatalf("%v", exitErr)
}
}()
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
cancelOnInterrupt(ctx, cancelFunc)
log.Info("Starting server")
s := statsd.Server{
Backends: toSlice(v.GetString(statsd.ParamBackends)),
ConsoleAddr: v.GetString(statsd.ParamConsoleAddr),
CloudProvider: v.GetString(statsd.ParamCloudProvider),
DefaultTags: toSlice(v.GetString(statsd.ParamDefaultTags)),
ExpiryInterval: v.GetDuration(statsd.ParamExpiryInterval),
FlushInterval: v.GetDuration(statsd.ParamFlushInterval),
MaxReaders: v.GetInt(statsd.ParamMaxReaders),
MaxWorkers: v.GetInt(statsd.ParamMaxWorkers),
MetricsAddr: v.GetString(statsd.ParamMetricsAddr),
Namespace: v.GetString(statsd.ParamNamespace),
PercentThreshold: toSlice(v.GetString(statsd.ParamPercentThreshold)),
WebConsoleAddr: v.GetString(statsd.ParamWebAddr),
Viper: v,
}
if err := s.Run(ctx); err != nil && err != context.Canceled {
augmentErr(&exitErr, fmt.Errorf("Server error: %v", err))
}
}
// augmentErr updates exitErr to point to newErr if exitErr is nil, otherwise logs newErr.
// The idea is to log all errors and fail the program with the first one.
func augmentErr(exitErr *error, newErr error) {
if *exitErr == nil {
*exitErr = newErr
} else {
log.Errorf("%v", newErr)
}
}
func toSlice(s string) []string {
//TODO Remove workaround when https://github.com/spf13/viper/issues/112 is fixed
if s == "" {
return nil
}
return strings.Split(s, ",")
}
// cancelOnInterrupt calls f when os.Interrupt or SIGTERM is received.
func cancelOnInterrupt(ctx context.Context, f context.CancelFunc) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
select {
case <-c:
f()
case <-ctx.Done():
}
}()
}
func setupConfiguration() (*viper.Viper, bool, error) {
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.SetEnvPrefix(EnvPrefix)
v.SetTypeByDefaultValue(true)
v.AutomaticEnv()
var version bool
cmd := pflag.NewFlagSet(os.Args[0], pflag.ContinueOnError)
cmd.BoolVar(&version, ParamVersion, false, "Print the version and exit")
cmd.Bool(ParamVerbose, false, "Verbose")
cmd.Bool(ParamJSON, false, "Log in JSON format")
cmd.String(ParamConfigPath, "", "Path to the configuration file")
statsd.AddFlags(cmd)
cmd.VisitAll(func(flag *pflag.Flag) {
if err := v.BindPFlag(flag.Name, flag); err != nil {
panic(err) // Should never happen
}
})
setupLogger(v) // setup logger from environment vars and flag defaults
if err := cmd.Parse(os.Args[1:]); err != nil {
return nil, false, err
}
setupLogger(v) // update logger with config from command line flags
configPath := v.GetString(ParamConfigPath)
if configPath != "" {
v.SetConfigFile(configPath)
if err := v.ReadInConfig(); err != nil {
return nil, false, err
}
}
setupLogger(v) // finally update logger with vars from config
return v, version, nil
}
func setupLogger(v *viper.Viper) {
if v.GetBool(ParamVerbose) {
log.SetLevel(log.DebugLevel)
}
if v.GetBool(ParamJSON) {
log.SetFormatter(&log.JSONFormatter{})
}
}