-
Notifications
You must be signed in to change notification settings - Fork 129
/
startup.go
149 lines (129 loc) · 3.99 KB
/
startup.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
package common
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/weaveworks/promrus"
commonconfig "github.com/armadaproject/armada/internal/common/config"
"github.com/armadaproject/armada/internal/common/logging"
)
const baseConfigFileName = "config"
func BindCommandlineArguments() {
err := viper.BindPFlags(pflag.CommandLine)
if err != nil {
log.Error()
os.Exit(-1)
}
}
// TODO Move code relating to config out of common into a new package internal/serverconfig
func LoadConfig(config interface{}, defaultPath string, overrideConfigs []string) *viper.Viper {
v := viper.NewWithOptions(viper.KeyDelimiter("::"))
v.SetConfigName(baseConfigFileName)
v.AddConfigPath(defaultPath)
if err := v.ReadInConfig(); err != nil {
log.Errorf("Error reading base config path=%s name=%s: %v", defaultPath, baseConfigFileName, err)
os.Exit(-1)
}
log.Infof("Read base config from %s", v.ConfigFileUsed())
for _, overrideConfig := range overrideConfigs {
v.SetConfigFile(overrideConfig)
err := v.MergeInConfig()
if err != nil {
log.Errorf("Error reading config from %s: %v", overrideConfig, err)
os.Exit(-1)
}
log.Infof("Read config from %s", v.ConfigFileUsed())
}
v.SetEnvKeyReplacer(strings.NewReplacer("::", "_"))
v.SetEnvPrefix("ARMADA")
v.AutomaticEnv()
err := v.Unmarshal(config, commonconfig.CustomHooks...)
if err != nil {
log.Error(err)
os.Exit(-1)
}
return v
}
func UnmarshalKey(v *viper.Viper, key string, item interface{}) error {
return v.UnmarshalKey(key, item, commonconfig.CustomHooks...)
}
// TODO Move logging-related code out of common into a new package internal/logging
func ConfigureCommandLineLogging() {
commandLineFormatter := new(logging.CommandLineFormatter)
log.SetFormatter(commandLineFormatter)
log.SetOutput(os.Stdout)
}
func ConfigureLogging() {
log.SetLevel(readEnvironmentLogLevel())
log.SetFormatter(readEnvironmentLogFormat())
log.SetOutput(os.Stdout)
}
func readEnvironmentLogLevel() log.Level {
level, ok := os.LookupEnv("LOG_LEVEL")
if ok {
logLevel, err := log.ParseLevel(level)
if err == nil {
return logLevel
}
}
return log.InfoLevel
}
func readEnvironmentLogFormat() log.Formatter {
formatStr, ok := os.LookupEnv("LOG_FORMAT")
if !ok {
formatStr = "colourful"
}
switch strings.ToLower(formatStr) {
case "json":
return &log.JSONFormatter{}
case "colourful":
return &log.TextFormatter{ForceColors: true, FullTimestamp: true}
case "text":
return &log.TextFormatter{DisableColors: true, FullTimestamp: true}
default:
println(os.Stderr, fmt.Sprintf("Unknown log format %s, defaulting to colourful format", formatStr))
return &log.TextFormatter{ForceColors: true, FullTimestamp: true}
}
}
func ServeMetrics(port uint16) (shutdown func()) {
return ServeMetricsFor(port, prometheus.DefaultGatherer)
}
func ServeMetricsFor(port uint16, gatherer prometheus.Gatherer) (shutdown func()) {
hook := promrus.MustNewPrometheusHook()
log.AddHook(hook)
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{}))
return ServeHttp(port, mux)
}
// ServeHttp starts an HTTP server listening on the given port.
func ServeHttp(port uint16, mux http.Handler) (shutdown func()) {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
}
go func() {
log.Printf("Starting http server listening on %d", port)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
panic(err) // TODO Don't panic, return an error
}
}()
// TODO There's no need for this function to panic, since the main goroutine will exit.
// Instead, just log an error.
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
log.Printf("Stopping http server listening on %d", port)
e := srv.Shutdown(ctx)
if e != nil {
panic(e)
}
}
}