-
Notifications
You must be signed in to change notification settings - Fork 25
/
monitor.go
239 lines (191 loc) · 5.74 KB
/
monitor.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
package cluster
import (
"context"
"math/rand"
"time"
aclient "github.com/akash-network/akash-api/go/node/client/v1beta2"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/boz/go-lifecycle"
"github.com/tendermint/tendermint/libs/log"
mtypes "github.com/akash-network/akash-api/go/node/market/v1beta4"
"github.com/akash-network/node/pubsub"
"github.com/akash-network/node/util/runner"
ctypes "github.com/akash-network/provider/cluster/types/v1beta3"
"github.com/akash-network/provider/event"
"github.com/akash-network/provider/session"
"github.com/akash-network/provider/tools/fromctx"
)
const (
monitorMaxRetries = 40
monitorRetryPeriodMin = time.Second * 4 // nolint revive
monitorRetryPeriodJitter = time.Second * 15
monitorHealthcheckPeriodMin = time.Second * 10 // nolint revive
monitorHealthcheckPeriodJitter = time.Second * 5
)
var (
deploymentHealthCheckCounter = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "provider_deployment_monitor_health",
}, []string{"state"})
)
type deploymentMonitor struct {
bus pubsub.Bus
session session.Session
client Client
deployment ctypes.IDeployment
attempts int
log log.Logger
lc lifecycle.Lifecycle
clusterSettings map[interface{}]interface{}
}
func newDeploymentMonitor(dm *deploymentManager) *deploymentMonitor {
m := &deploymentMonitor{
bus: dm.bus,
session: dm.session,
client: dm.client,
deployment: dm.deployment,
log: dm.log.With("cmp", "deployment-monitor"),
lc: lifecycle.New(),
clusterSettings: dm.config.ClusterSettings,
}
go m.lc.WatchChannel(dm.lc.ShuttingDown())
go m.run()
return m
}
func (m *deploymentMonitor) shutdown() {
m.lc.ShutdownAsync(nil)
}
func (m *deploymentMonitor) done() <-chan struct{} {
return m.lc.Done()
}
func (m *deploymentMonitor) run() {
defer m.lc.ShutdownCompleted()
ctx, cancel := context.WithCancel(context.Background())
var (
runch <-chan runner.Result
closech <-chan runner.Result
)
tickch := m.scheduleRetry()
loop:
for {
select {
case err := <-m.lc.ShutdownRequest():
m.log.Debug("shutting down")
m.lc.ShutdownInitiated(err)
break loop
case <-tickch:
tickch = nil
runch = m.runCheck(ctx)
case result := <-runch:
runch = nil
if err := result.Error(); err != nil {
deploymentHealthCheckCounter.WithLabelValues("err").Inc()
m.log.Error("monitor check", "err", err)
}
ok := result.Value().(bool)
m.log.Info("check result", "ok", ok, "attempt", m.attempts)
if ok {
// healthy
m.attempts = 0
tickch = m.scheduleHealthcheck()
m.publishStatus(event.ClusterDeploymentDeployed)
deploymentHealthCheckCounter.WithLabelValues("up").Inc()
break
} else {
deploymentHealthCheckCounter.WithLabelValues("down").Inc()
}
m.publishStatus(event.ClusterDeploymentPending)
if m.attempts <= monitorMaxRetries {
// unhealthy. retry
tickch = m.scheduleRetry()
break
}
m.log.Error("deployment failed. closing lease.")
deploymentHealthCheckCounter.WithLabelValues("failed").Inc()
closech = m.runCloseLease(ctx)
case <-closech:
closech = nil
}
}
cancel()
if runch != nil {
m.log.Debug("read runch")
<-runch
}
if closech != nil {
m.log.Debug("read closech")
<-closech
}
// TODO
// Check that we got here
m.log.Debug("shutdown complete")
}
func (m *deploymentMonitor) runCheck(ctx context.Context) <-chan runner.Result {
m.attempts++
m.log.Debug("running check", "attempt", m.attempts)
return runner.Do(func() runner.Result {
return runner.NewResult(m.doCheck(ctx))
})
}
func (m *deploymentMonitor) doCheck(ctx context.Context) (bool, error) {
ctx = fromctx.ApplyToContext(ctx, m.clusterSettings)
status, err := m.client.LeaseStatus(ctx, m.deployment.LeaseID())
if err != nil {
m.log.Error("lease status", "err", err)
return false, err
}
badsvc := 0
for _, spec := range m.deployment.ManifestGroup().Services {
service, foundService := status[spec.Name]
if foundService {
if uint32(service.Available) < spec.Count {
badsvc++
m.log.Debug("service available replicas below target",
"service", spec.Name,
"available", service.Available,
"target", spec.Count,
)
}
}
if !foundService {
badsvc++
m.log.Debug("service status not found", "service", spec.Name)
}
}
return badsvc == 0, nil
}
func (m *deploymentMonitor) runCloseLease(ctx context.Context) <-chan runner.Result {
return runner.Do(func() runner.Result {
// TODO: retry, timeout
msg := &mtypes.MsgCloseBid{
BidID: m.deployment.LeaseID().BidID(),
}
res, err := m.session.Client().Tx().Broadcast(ctx, []sdk.Msg{msg}, aclient.WithResultCodeAsError())
if err != nil {
m.log.Error("closing deployment", "err", err)
} else {
m.log.Info("bidding on lease closed")
}
return runner.NewResult(res, err)
})
}
func (m *deploymentMonitor) publishStatus(status event.ClusterDeploymentStatus) {
if err := m.bus.Publish(event.ClusterDeployment{
LeaseID: m.deployment.LeaseID(),
Group: m.deployment.ManifestGroup(),
Status: status,
}); err != nil {
m.log.Error("publishing manifest group deployed event", "err", err, "status", status)
}
}
func (m *deploymentMonitor) scheduleRetry() <-chan time.Time {
return m.schedule(monitorRetryPeriodMin, monitorRetryPeriodJitter)
}
func (m *deploymentMonitor) scheduleHealthcheck() <-chan time.Time {
return m.schedule(monitorHealthcheckPeriodMin, monitorHealthcheckPeriodJitter)
}
func (m *deploymentMonitor) schedule(min, jitter time.Duration) <-chan time.Time {
period := min + time.Duration(rand.Int63n(int64(jitter))) // nolint: gosec
return time.After(period)
}