-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathservice.go
368 lines (312 loc) · 9.67 KB
/
service.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package manifest
import (
"context"
"errors"
"time"
provider "github.com/akash-network/akash-api/go/provider/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
tpubsub "github.com/troian/pubsub"
"github.com/boz/go-lifecycle"
manifest "github.com/akash-network/akash-api/go/manifest/v2beta2"
dtypes "github.com/akash-network/akash-api/go/node/deployment/v1beta3"
mtypes "github.com/akash-network/akash-api/go/node/market/v1beta4"
"github.com/akash-network/node/pubsub"
dquery "github.com/akash-network/node/x/deployment/query"
clustertypes "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"
ptypes "github.com/akash-network/provider/types"
)
// ErrNotRunning is the error when service is not running
var ErrNotRunning = errors.New("not running")
var (
manifestManagerGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "provider_manifest_manager",
Help: "",
ConstLabels: nil,
})
manifestWatchdogGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "provider_order_watchdog",
Help: "",
ConstLabels: nil,
})
)
// StatusClient is the interface which includes status of service
//
//go:generate mockery --name StatusClient
type StatusClient interface {
Status(context.Context) (*Status, error)
StatusV1(context.Context) (*provider.ManifestStatus, error)
}
// Client is the interface that wraps HandleManifest method
//
//go:generate mockery --name Client
type Client interface {
Submit(context.Context, dtypes.DeploymentID, manifest.Manifest) error
IsActive(context.Context, dtypes.DeploymentID) (bool, error)
}
// Service is the interface that includes StatusClient and Handler interfaces. It also wraps Done method
type Service interface {
StatusClient
Client
Done() <-chan struct{}
}
// NewService creates and returns new Service instance
// Manage incoming leases and manifests and pair the two together to construct and emit a ManifestReceived event.
func NewService(ctx context.Context, session session.Session, bus pubsub.Bus, hostnameService clustertypes.HostnameServiceClient, cfg ServiceConfig) (Service, error) {
session = session.ForModule("provider-manifest")
sub, err := bus.Subscribe()
if err != nil {
return nil, err
}
s := &service{
ctx: ctx,
session: session,
bus: bus,
sub: sub,
statusch: make(chan chan<- *Status),
mreqch: make(chan manifestRequest),
activeCheckCh: make(chan isActiveCheck),
managers: make(map[string]*manager),
managerch: make(chan *manager),
lc: lifecycle.New(),
hostnameService: hostnameService,
config: cfg,
watchdogch: make(chan dtypes.DeploymentID),
watchdogs: make(map[dtypes.DeploymentID]*watchdog),
}
go s.lc.WatchContext(ctx)
go s.run()
return s, nil
}
type service struct {
ctx context.Context
config ServiceConfig
session session.Session
bus pubsub.Bus
sub pubsub.Subscriber
lc lifecycle.Lifecycle
statusch chan chan<- *Status
mreqch chan manifestRequest
activeCheckCh chan isActiveCheck
managers map[string]*manager
managerch chan *manager
hostnameService clustertypes.HostnameServiceClient
watchdogs map[dtypes.DeploymentID]*watchdog
watchdogch chan dtypes.DeploymentID
}
type manifestRequest struct {
value *submitRequest
ch chan<- error
ctx context.Context
}
func (s *service) updateGauges() {
manifestManagerGauge.Set(float64(len(s.managers)))
manifestWatchdogGauge.Set(float64(len(s.managers)))
}
type isActiveCheck struct {
ch chan<- bool
Deployment dtypes.DeploymentID
}
func (s *service) IsActive(ctx context.Context, dID dtypes.DeploymentID) (bool, error) {
ch := make(chan bool, 1)
req := isActiveCheck{
Deployment: dID,
ch: ch,
}
select {
case <-ctx.Done():
return false, ctx.Err()
case s.activeCheckCh <- req:
case <-s.lc.ShuttingDown():
return false, ErrNotRunning
case <-s.lc.Done():
return false, ErrNotRunning
}
select {
case <-ctx.Done():
return false, ctx.Err()
case <-s.lc.Done():
return false, ErrNotRunning
case result := <-ch:
return result, nil
}
}
// Submit incoming manifest request.
func (s *service) Submit(ctx context.Context, did dtypes.DeploymentID, mani manifest.Manifest) error {
// This needs to be buffered because the goroutine writing to this may get the result
// after the context has returned an error
ch := make(chan error, 1)
req := manifestRequest{
value: &submitRequest{
Deployment: did,
Manifest: mani,
},
ch: ch,
ctx: ctx,
}
select {
case <-ctx.Done():
return ctx.Err()
case s.mreqch <- req:
case <-s.lc.ShuttingDown():
return ErrNotRunning
case <-s.lc.Done():
return ErrNotRunning
}
select {
case <-ctx.Done():
return ctx.Err()
case <-s.lc.Done():
return ErrNotRunning
case result := <-ch:
return result
}
}
func (s *service) Done() <-chan struct{} {
return s.lc.Done()
}
func (s *service) Status(ctx context.Context) (*Status, error) {
ch := make(chan *Status, 1)
select {
case <-s.lc.Done():
return nil, ErrNotRunning
case <-ctx.Done():
return nil, ctx.Err()
case s.statusch <- ch:
}
select {
case <-s.lc.Done():
return nil, ErrNotRunning
case <-ctx.Done():
return nil, ctx.Err()
case result := <-ch:
return result, nil
}
}
func (s *service) StatusV1(ctx context.Context) (*provider.ManifestStatus, error) {
res, err := s.Status(ctx)
if err != nil {
return nil, err
}
return &provider.ManifestStatus{Deployments: res.Deployments}, nil
}
func (s *service) run() {
defer s.lc.ShutdownCompleted()
defer s.sub.Close()
bus := fromctx.MustPubSubFromCtx(s.ctx)
s.updateGauges()
signalch := make(chan struct{}, 1)
trySignal := func() {
select {
case signalch <- struct{}{}:
case <-s.lc.ShutdownRequest():
default:
}
}
loop:
for {
select {
case err := <-s.lc.ShutdownRequest():
s.lc.ShutdownInitiated(err)
break loop
case ev := <-s.sub.Events():
switch ev := ev.(type) {
case event.LeaseWon:
if ev.LeaseID.GetProvider() != s.session.Provider().Address().String() {
continue
}
s.session.Log().Info("lease won", "lease", ev.LeaseID)
s.handleLease(ev, true)
case dtypes.EventDeploymentUpdated:
s.session.Log().Info("update received", "deployment", ev.ID, "version", ev.Version)
key := dquery.DeploymentPath(ev.ID)
if manager := s.managers[key]; manager != nil {
s.session.Log().Info("deployment updated", "deployment", ev.ID, "version", ev.Version)
manager.handleUpdate(ev.Version)
}
case dtypes.EventDeploymentClosed:
key := dquery.DeploymentPath(ev.ID)
if manager := s.managers[key]; manager != nil {
s.session.Log().Info("deployment closed", "deployment", ev.ID)
manager.stop()
}
case mtypes.EventLeaseClosed:
if ev.ID.GetProvider() != s.session.Provider().Address().String() {
continue
}
key := dquery.DeploymentPath(ev.ID.DeploymentID())
if manager := s.managers[key]; manager != nil {
s.session.Log().Info("lease closed", "lease", ev.ID)
manager.removeLease(ev.ID)
}
}
case check := <-s.activeCheckCh:
_, ok := s.managers[dquery.DeploymentPath(check.Deployment)]
check.ch <- ok
case req := <-s.mreqch:
// Cancel the watchdog (if it exists), since a manifest has been received
s.maybeRemoveWatchdog(req.value.Deployment)
manager := s.ensureManager(req.value.Deployment)
// The manager is responsible for putting a result in req.ch
manager.handleManifest(req)
trySignal()
case ch := <-s.statusch:
ch <- &Status{
Deployments: uint32(len(s.managers)), // nolint: gosec
}
case <-signalch:
bus.Pub(provider.ManifestStatus{Deployments: uint32(len(s.managers))}, []string{ptypes.PubSubTopicManifestStatus}, tpubsub.WithRetain()) // nolint: gosec
case manager := <-s.managerch:
s.session.Log().Info("manager done", "deployment", manager.daddr)
delete(s.managers, dquery.DeploymentPath(manager.daddr))
// Cancel the watchdog (if it exists) since the manager has stopped as well
s.maybeRemoveWatchdog(manager.daddr)
trySignal()
case leaseID := <-s.watchdogch:
s.session.Log().Info("watchdog done", "lease", leaseID)
delete(s.watchdogs, leaseID)
}
s.updateGauges()
}
for len(s.managers) > 0 {
manager := <-s.managerch
delete(s.managers, dquery.DeploymentPath(manager.daddr))
s.updateGauges()
}
s.session.Log().Debug("draining watchdogs", "qty", len(s.watchdogs))
for _, watchdog := range s.watchdogs {
if watchdog != nil {
leaseID := <-s.watchdogch
s.session.Log().Info("watchdog done", "lease", leaseID)
}
}
s.session.Log().Info("shutdown complete")
}
func (s *service) maybeRemoveWatchdog(deploymentID dtypes.DeploymentID) {
if watchdog := s.watchdogs[deploymentID]; watchdog != nil {
watchdog.stop()
}
}
func (s *service) handleLease(ev event.LeaseWon, isNew bool) {
// Only run this if configured to do so
if isNew && s.config.ManifestTimeout > time.Duration(0) {
// Create watchdog if it does not exist AND a manifest has not been received yet
if watchdog := s.watchdogs[ev.LeaseID.DeploymentID()]; watchdog == nil {
watchdog = newWatchdog(s.session, s.lc.ShuttingDown(), s.watchdogch, ev.LeaseID, s.config.ManifestTimeout)
s.watchdogs[ev.LeaseID.DeploymentID()] = watchdog
}
}
manager := s.ensureManager(ev.LeaseID.DeploymentID())
manager.handleLease(ev)
}
func (s *service) ensureManager(did dtypes.DeploymentID) (manager *manager) {
manager = s.managers[dquery.DeploymentPath(did)]
if manager == nil {
manager = newManager(s, did)
s.managers[dquery.DeploymentPath(did)] = manager
}
return manager
}