forked from ribasushi/spade
/
main.go
163 lines (139 loc) · 4.22 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
package main
import (
"errors"
"fmt"
"io"
"os"
"time"
"github.com/filecoin-project/evergreen-dealer/common"
fslock "github.com/ipfs/go-fs-lock"
logging "github.com/ipfs/go-log/v2"
"github.com/prometheus/client_golang/prometheus"
prometheuspush "github.com/prometheus/client_golang/prometheus/push"
"github.com/urfave/cli/v2"
)
var log = logging.Logger(fmt.Sprintf("%s-cron(%d)", common.AppName, os.Getpid()))
func main() {
logging.SetLogLevel("*", "INFO") //nolint:errcheck
ctx, cleanup := common.TopContext(nil)
defer cleanup()
// wrap in a defer to always capture endstate/send a metric, even under panic()s
var (
t0 time.Time
err error
currentCmd string
currentCmdLock io.Closer
)
defer func() {
// shared log/metric emitter
// ( lock-contention does not count, see invocation below )
emitEndLogs := func(logSuccess bool) {
took := time.Since(t0).Truncate(time.Millisecond)
cmdFqName := common.NonAlphanumRun.ReplaceAllString(common.AppName+"_cron_"+currentCmd, `_`)
logHdr := fmt.Sprintf("=== FINISH '%s' run", currentCmd)
logArgs := []interface{}{
"success", logSuccess,
"took", took.String(),
}
tookGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: fmt.Sprintf("%s_run_time", cmdFqName),
Help: "How long did the job take (in milliseconds)",
})
tookGauge.Set(float64(took.Milliseconds()))
successGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: fmt.Sprintf("%s_success", cmdFqName),
Help: "Whether the job completed with success(1) or failure(0)",
})
if logSuccess {
log.Infow(logHdr, logArgs...)
successGauge.Set(1)
} else {
log.Warnw(logHdr, logArgs...)
successGauge.Set(0)
}
if common.PromURL != "" {
if promErr := prometheuspush.New(common.PromURL, common.NonAlphanumRun.ReplaceAllString(currentCmd, "_")).
Grouping("instance", common.NonAlphanumRun.ReplaceAllString(common.PromInstance, "_")).
BasicAuth(common.PromUser, common.PromPass).
Collector(tookGauge).
Collector(successGauge).
Push(); promErr != nil {
log.Warnf("push of prometheus metrics to '%s' failed: %s", common.PromURL, promErr)
}
}
}
// a panic condition takes precedence
if r := recover(); r != nil {
if err == nil {
err = fmt.Errorf("panic encountered: %s", r)
} else {
err = fmt.Errorf("panic encountered (in addition to error '%s'): %s", err, r)
}
}
if err != nil {
// if we are not interactive - be quiet on a failed lock
if !common.IsTerm && errors.As(err, new(fslock.LockedError)) {
cleanup()
os.Exit(1)
}
log.Error(err)
if currentCmdLock != nil {
emitEndLogs(false)
}
cleanup()
os.Exit(1)
} else if currentCmdLock != nil {
emitEndLogs(true)
}
}()
t0 = time.Now()
// the function ends after this block, err is examined in the defer above
err = (&cli.App{
Name: common.AppName + "-cron",
Usage: "Misc background processes for " + common.AppName,
Commands: []*cli.Command{
trackDeals,
pushMetrics,
proposePending,
},
Flags: common.CliFlags,
// obtains locks and emits the proper init loglines
Before: func(cctx *cli.Context) error {
if err := common.CliBeforeSetup(cctx); err != nil {
return err
}
// figure out what is the command that was invoked
if len(os.Args) > 1 {
cmdNames := make(map[string]string)
for _, c := range cctx.App.Commands {
cmdNames[c.Name] = c.Name
for _, a := range c.Aliases {
cmdNames[a] = c.Name
}
}
var firstCmdOccurrence string
for i := 1; i < len(os.Args); i++ {
// if we are in help context - no locks and no start/stop timers
if os.Args[i] == `-h` || os.Args[i] == `--help` {
return nil
}
if firstCmdOccurrence != "" {
continue
}
firstCmdOccurrence = cmdNames[os.Args[i]]
}
// help, wrong cmd or something
if firstCmdOccurrence == "" || firstCmdOccurrence == "help" {
return nil
}
currentCmd = firstCmdOccurrence
var err error
if currentCmdLock, err = fslock.Lock(os.TempDir(), "evergreen-cron-"+currentCmd); err != nil {
return err
}
log.Infow(fmt.Sprintf("=== BEGIN '%s' run", currentCmd))
}
return nil
},
}).RunContext(ctx, os.Args)
}