/
run.go
107 lines (90 loc) · 2.35 KB
/
run.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
package app
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"github.com/fatih/color"
"github.com/kilnfi/near-validator-watcher/pkg/metrics"
"github.com/kilnfi/near-validator-watcher/pkg/near"
"github.com/kilnfi/near-validator-watcher/pkg/watcher"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"golang.org/x/sync/errgroup"
)
func RunFunc(cCtx *cli.Context) error {
var (
ctx = cCtx.Context
// Config flags
httpAddr = cCtx.String("http-addr")
logLevel = cCtx.String("log-level")
namespace = cCtx.String("namespace")
noColor = cCtx.Bool("no-color")
node = cCtx.String("node")
refreshRate = cCtx.Duration("refresh-rate")
validators = cCtx.StringSlice("validator")
)
//
// Setup
//
// Logger setup
logrus.SetOutput(os.Stdout)
logrus.SetLevel(logLevelFromString(logLevel))
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: noColor,
})
// Disable colored output if requested
color.NoColor = noColor
// Handle signals via context
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Create errgroup to manage all goroutines
errg, ctx := errgroup.WithContext(ctx)
//
// Validator Watcher
//
logrus.Infof("connecting to node %s", node)
client := near.NewClient(node)
registry := prometheus.NewRegistry()
metrics := metrics.New(namespace)
metrics.Register(registry)
watcher := watcher.New(client, metrics, &watcher.Config{
Writer: os.Stdout,
TrackedAccounts: validators,
RefreshRate: refreshRate,
})
errg.Go(func() error {
return watcher.Start(ctx)
})
//
// HTTP server
//
logrus.Infof("starting HTTP server on %s", httpAddr)
readyProbe := watcher.IsSynced
httpServer := NewHTTPServer(
httpAddr,
WithReadyProbe(readyProbe),
WithLiveProbe(upProbe),
WithMetrics(registry),
)
errg.Go(func() error {
return httpServer.Run()
})
//
// Wait for context to be cancelled (via signals or error from errgroup)
//
<-ctx.Done()
logrus.Info("shutting down")
//
// Stop all watchers and exporter
//
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
logrus.WithError(err).Errorf("failed to stop http server")
}
// Wait for all goroutines to finish
return errg.Wait()
}