-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.go
348 lines (298 loc) · 10.1 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"net/http/pprof"
"os"
"strings"
"time"
"github.com/brancz/locutus/client"
"github.com/brancz/locutus/config"
"github.com/brancz/locutus/db"
"github.com/brancz/locutus/render/file"
"github.com/brancz/locutus/render/jsonnet"
"github.com/brancz/locutus/rollout"
"github.com/brancz/locutus/rollout/checks"
"github.com/brancz/locutus/source"
"github.com/brancz/locutus/trigger"
"github.com/brancz/locutus/trigger/database"
"github.com/brancz/locutus/trigger/interval"
"github.com/brancz/locutus/trigger/oneoff"
"github.com/brancz/locutus/trigger/resource"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/oklog/run"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
logLevelAll = "all"
logLevelDebug = "debug"
logLevelInfo = "info"
logLevelWarn = "warn"
logLevelError = "error"
logLevelNone = "none"
)
var (
availableLogLevels = []string{
logLevelAll,
logLevelDebug,
logLevelInfo,
logLevelWarn,
logLevelError,
logLevelNone,
}
)
type stringList []string
func (l *stringList) String() string {
return strings.Join(*l, ",")
}
func (l *stringList) Set(value string) error {
*l = append(*l, value)
return nil
}
func Main() int {
var (
logLevel string
masterURL string
kubeconfig string
qps int
burst int
renderProviderName string
writeStatus bool
configFile string
renderOnly bool
oneOff bool
rendererFileDirectory string
rendererFileRollout string
rendererJsonnetJpaths stringList
rendererJsonnetEntrypoint string
rendererJsonnetExtStrs stringList
databaseConnectionsFile string
sourceDatabaseFile string
triggerIntervalDuration time.Duration
triggerResourceConfig string
triggerDatabaseConfig string
)
s := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
s.StringVar(&logLevel, "log-level", logLevelInfo, "Log level to use.")
s.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
s.IntVar(&qps, "qps", 5, "QPS to use while talking with kubernetes API.")
s.IntVar(&burst, "burst", 10, "Burst to use while talking with kubernetes API.")
s.StringVar(&masterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
s.StringVar(&renderProviderName, "renderer", "", "The provider to use for rendering manifests.")
s.StringVar(&configFile, "config-file", "", "The config file whose content to pass to the render provider.")
s.BoolVar(&renderOnly, "render-only", false, "Only render manifests to be rolled out and print to STDOUT.")
s.BoolVar(&oneOff, "one-off", false, "Only render and rollout once, then exit.")
s.StringVar(&databaseConnectionsFile, "database-connections-file", "", "File to read database connections from.")
s.StringVar(&rendererFileDirectory, "renderer.file.dir", "manifests/", "Directory to read files from.")
s.StringVar(&rendererFileRollout, "renderer.file.rollout", "rollout.yaml", "Plain rollout spec to read.")
s.StringVar(&rendererJsonnetEntrypoint, "renderer.jsonnet.entrypoint", "jsonnet/main.jsonnet", "Jsonnet file to execute to render.")
s.Var(&rendererJsonnetExtStrs, "renderer.jsonnet.ext-str", "Jsonnet ext-str to pass to the jsonnet VM.")
s.Var(&rendererJsonnetJpaths, "renderer.jsonnet.jpaths", "Jsonnet jpaths to pass to the jsonnet VM.")
s.StringVar(&sourceDatabaseFile, "source.database.file", "", "File to read database queries from as sources.")
s.DurationVar(&triggerIntervalDuration, "trigger.interval.duration", time.Duration(0), "Duration of interval in which to trigger.")
s.StringVar(&triggerResourceConfig, "trigger.resource.config", "", "Path to configuration of resource triggers.")
s.StringVar(&triggerDatabaseConfig, "trigger.database.config", "", "Path to configuration of database triggers.")
s.BoolVar(&writeStatus, "trigger.resource.write-status", true, "Whether to write status back to the originating resource.")
if err := s.Parse(os.Args[1:]); err != nil {
return 1
}
logger, err := logger(logLevel)
if err != nil {
fmt.Println(err)
return 1
}
reg := prometheus.NewRegistry()
reg.MustRegister(prometheus.NewGoCollector())
reg.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
var cl *client.Client
{
konfig, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
if err != nil {
logger.Log("msg", "error building kubeconfig", "err", err)
return 1
}
konfig.QPS = float32(qps)
konfig.Burst = burst
klient, err := kubernetes.NewForConfig(konfig)
if err != nil {
logger.Log("msg", "error building kubernetes clientset", "err", err)
return 1
}
cl = client.NewClient(konfig, klient)
cl.WithLogger(log.With(logger, "component", "client"))
cl.SetUpdatePreparations(client.DefaultUpdatePreparations)
cl.SetUpdateChecks(client.DefaultUpdateChecks)
}
ctx := context.Background()
sources := map[string]func(context.Context) ([]byte, error){}
triggers := []trigger.Trigger{}
if triggerResourceConfig != "" {
t, err := resource.NewTrigger(ctx, logger, cl, triggerResourceConfig, writeStatus)
if err != nil {
logger.Log("msg", "failed to create resource trigger", "err", err)
return 1
}
triggerSources := t.InputSources()
for name, sourceFunc := range triggerSources {
level.Debug(logger).Log("msg", "adding dynamic import", "source", name)
sources[name] = sourceFunc
}
triggers = append(triggers, t)
}
if triggerIntervalDuration > 0 {
triggers = append(triggers, interval.NewTrigger(logger, triggerIntervalDuration))
}
var databaseConnections *db.Connections
if databaseConnectionsFile != "" {
databaseConnections, err = db.FromFile(ctx, reg, databaseConnectionsFile)
if err != nil {
logger.Log("msg", "failed to read database connections", "err", err)
return 1
}
}
if sourceDatabaseFile != "" {
s, err := source.NewDatabaseSources(
logger,
databaseConnections,
sourceDatabaseFile,
)
if err != nil {
logger.Log("msg", "failed to create cockroachdb source", "err", err)
return 1
}
databaseSources, err := s.InputSources()
if err != nil {
logger.Log("msg", "failed to create cockroachdb source", "err", err)
return 1
}
for name, sourceFunc := range databaseSources {
level.Debug(logger).Log("msg", "adding dynamic import", "source", name)
sources[name] = sourceFunc
}
}
if triggerDatabaseConfig != "" {
t, err := database.NewTrigger(
logger,
databaseConnections,
triggerDatabaseConfig,
)
if err != nil {
logger.Log("msg", "failed to create resource trigger", "err", err)
return 1
}
triggers = append(triggers, t)
}
if oneOff {
triggers = []trigger.Trigger{oneoff.NewTrigger(logger)}
}
if len(triggers) == 0 {
logger.Log("msg", "no triggers configured")
return 1
}
var renderer rollout.Renderer
{
switch renderProviderName {
case "jsonnet":
renderer, err = jsonnet.NewRenderer(
logger,
rendererJsonnetEntrypoint,
sources,
[]string(rendererJsonnetExtStrs),
[]string(rendererJsonnetJpaths),
)
if err != nil {
logger.Log("msg", "failed to create jsonnet renderer", "err", err)
return 1
}
case "file":
renderer = file.NewRenderer(logger, rendererFileDirectory, rendererFileRollout)
default:
logger.Log("msg", "failed to find render provider")
return 1
}
}
c, err := checks.NewChecks(logger, cl, databaseConnections, checks.DefaultChecks)
if err != nil {
logger.Log("msg", "failed to create checks", "err", err)
return 1
}
runner := rollout.NewRunner(reg, log.With(logger, "component", "rollout-runner"), cl, renderer, c, renderOnly)
runner.SetObjectActions(rollout.DefaultObjectActions)
for _, trigger := range triggers {
trigger.Register(config.NewFileConfigPasser(configFile, runner))
}
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.InstrumentMetricHandler(reg, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})))
mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
srv := &http.Server{Handler: mux}
var g run.Group
{
l, err := net.Listen("tcp", ":8080")
if err != nil {
logger.Log("msg", "listening port 8080 failed", "err", err)
return 1
}
g.Add(func() error {
return srv.Serve(l)
}, func(err error) {
l.Close()
})
}
for _, trigger := range triggers {
ctx, cancel := context.WithCancel(ctx)
g.Add(func() error {
level.Info(logger).Log("msg", "starting trigger...", "trigger", fmt.Sprintf("%T", trigger))
if err := trigger.Run(ctx); err != nil {
return fmt.Errorf("failed to run trigger: %w", err)
}
return nil
}, func(err error) {
cancel()
})
}
{
g.Add(run.SignalHandler(context.Background(), os.Interrupt))
}
level.Info(logger).Log("msg", "running", "renderer", renderProviderName)
if err := g.Run(); err != nil {
logger.Log("msg", "Unhandled error received. Exiting...", "err", err)
return 1
}
return 0
}
func logger(logLevel string) (log.Logger, error) {
logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
switch logLevel {
case logLevelAll:
logger = level.NewFilter(logger, level.AllowAll())
case logLevelDebug:
logger = level.NewFilter(logger, level.AllowDebug())
case logLevelInfo:
logger = level.NewFilter(logger, level.AllowInfo())
case logLevelWarn:
logger = level.NewFilter(logger, level.AllowWarn())
case logLevelError:
logger = level.NewFilter(logger, level.AllowError())
case logLevelNone:
logger = level.NewFilter(logger, level.AllowNone())
default:
return nil, fmt.Errorf("log level %v unknown, %v are possible values", logLevel, availableLogLevels)
}
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
logger = log.With(logger, "caller", log.DefaultCaller)
return logger, nil
}
func main() {
os.Exit(Main())
}