-
Notifications
You must be signed in to change notification settings - Fork 25
/
service.go
468 lines (387 loc) · 12.3 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package cluster
import (
"context"
"github.com/boz/go-lifecycle"
sdktypes "github.com/cosmos/cosmos-sdk/types"
tpubsub "github.com/troian/pubsub"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/tendermint/tendermint/libs/log"
dtypes "github.com/akash-network/akash-api/go/node/deployment/v1beta3"
mtypes "github.com/akash-network/akash-api/go/node/market/v1beta4"
provider "github.com/akash-network/akash-api/go/provider/v1"
"github.com/akash-network/node/pubsub"
ctypes "github.com/akash-network/provider/cluster/types/v1beta3"
"github.com/akash-network/provider/event"
"github.com/akash-network/provider/operator/waiter"
crd "github.com/akash-network/provider/pkg/apis/akash.network/v2beta2"
"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")
ErrInvalidResource = errors.New("invalid resource")
errNoManifestGroup = errors.New("no manifest group could be found")
)
var (
deploymentManagerGauge = promauto.NewGauge(prometheus.GaugeOpts{
// fixme provider_deployment_manager
Name: "provider_deployment_manager",
Help: "",
ConstLabels: nil,
})
)
type service struct {
session session.Session
client Client
bus pubsub.Bus
sub pubsub.Subscriber
inventory *inventoryService
hostnames *hostnameService
checkDeploymentExistsRequestCh chan checkDeploymentExistsRequest
statusch chan chan<- *ctypes.Status
statusV1ch chan chan<- uint32
managers map[mtypes.LeaseID]*deploymentManager
managerch chan *deploymentManager
log log.Logger
lc lifecycle.Lifecycle
waiter waiter.OperatorWaiter
config Config
}
type checkDeploymentExistsRequest struct {
owner sdktypes.Address
dseq uint64
gseq uint32
responseCh chan<- mtypes.LeaseID
}
// Cluster is the interface that wraps Reserve and Unreserve methods
//
//go:generate mockery --name Cluster
type Cluster interface {
Reserve(mtypes.OrderID, dtypes.ResourceGroup) (ctypes.Reservation, error)
Unreserve(mtypes.OrderID) error
}
// StatusClient is the interface which includes status of service
type StatusClient interface {
Status(context.Context) (*ctypes.Status, error)
StatusV1(context.Context) (*provider.ClusterStatus, error)
FindActiveLease(ctx context.Context, owner sdktypes.Address, dseq uint64, gseq uint32) (bool, mtypes.LeaseID, crd.ManifestGroup, error)
}
// Service manage compute cluster for the provider. Will eventually integrate with kubernetes, etc...
//
//go:generate mockery --name Service
type Service interface {
StatusClient
Cluster
Close() error
Ready() <-chan struct{}
Done() <-chan struct{}
HostnameService() ctypes.HostnameServiceClient
TransferHostname(ctx context.Context, leaseID mtypes.LeaseID, hostname string, serviceName string, externalPort uint32) error
}
// NewService returns new Service instance
func NewService(ctx context.Context, session session.Session, bus pubsub.Bus, client Client, waiter waiter.OperatorWaiter, cfg Config) (Service, error) {
log := session.Log().With("module", "provider-cluster", "cmp", "service")
lc := lifecycle.New()
sub, err := bus.Subscribe()
if err != nil {
return nil, err
}
deployments, err := findDeployments(ctx, log, client, session)
if err != nil {
sub.Close()
return nil, err
}
inventory, err := newInventoryService(ctx, cfg, log, sub, client, waiter, deployments)
if err != nil {
sub.Close()
return nil, err
}
allHostnames, err := client.AllHostnames(ctx)
if err != nil {
sub.Close()
return nil, err
}
// Note: one side effect of this code is to add reservations for auto generated hostnames
// This is not normally done, but also doesn't cause any problems
activeHostnames := make(map[string]mtypes.LeaseID, len(allHostnames))
for _, v := range allHostnames {
activeHostnames[v.Hostname] = v.ID
log.Debug("found existing hostname", "hostname", v.Hostname, "id", v.ID)
}
hostnames, err := newHostnameService(ctx, cfg, activeHostnames)
if err != nil {
return nil, err
}
s := &service{
session: session,
client: client,
hostnames: hostnames,
bus: bus,
sub: sub,
inventory: inventory,
statusch: make(chan chan<- *ctypes.Status),
statusV1ch: make(chan chan<- uint32),
managers: make(map[mtypes.LeaseID]*deploymentManager),
managerch: make(chan *deploymentManager),
checkDeploymentExistsRequestCh: make(chan checkDeploymentExistsRequest),
log: log,
lc: lc,
config: cfg,
waiter: waiter,
}
go s.lc.WatchContext(ctx)
go s.run(ctx, deployments)
return s, nil
}
func (s *service) FindActiveLease(ctx context.Context, owner sdktypes.Address, dseq uint64, gseq uint32) (bool, mtypes.LeaseID, crd.ManifestGroup, error) {
response := make(chan mtypes.LeaseID, 1)
req := checkDeploymentExistsRequest{
responseCh: response,
dseq: dseq,
gseq: gseq,
owner: owner,
}
select {
case s.checkDeploymentExistsRequestCh <- req:
case <-ctx.Done():
return false, mtypes.LeaseID{}, crd.ManifestGroup{}, ctx.Err()
}
var leaseID mtypes.LeaseID
var ok bool
select {
case leaseID, ok = <-response:
if !ok {
return false, mtypes.LeaseID{}, crd.ManifestGroup{}, nil
}
case <-ctx.Done():
return false, mtypes.LeaseID{}, crd.ManifestGroup{}, ctx.Err()
}
found, mgroup, err := s.client.GetManifestGroup(ctx, leaseID)
if err != nil {
return false, mtypes.LeaseID{}, crd.ManifestGroup{}, err
}
if !found {
return false, mtypes.LeaseID{}, crd.ManifestGroup{}, errNoManifestGroup
}
return true, leaseID, mgroup, nil
}
func (s *service) Close() error {
s.lc.Shutdown(nil)
return s.lc.Error()
}
func (s *service) Done() <-chan struct{} {
return s.lc.Done()
}
func (s *service) Ready() <-chan struct{} {
return s.inventory.ready()
}
func (s *service) Reserve(order mtypes.OrderID, resources dtypes.ResourceGroup) (ctypes.Reservation, error) {
return s.inventory.reserve(order, resources)
}
func (s *service) Unreserve(order mtypes.OrderID) error {
return s.inventory.unreserve(order)
}
func (s *service) HostnameService() ctypes.HostnameServiceClient {
return s.hostnames
}
func (s *service) TransferHostname(ctx context.Context, leaseID mtypes.LeaseID, hostname string, serviceName string, externalPort uint32) error {
return s.client.DeclareHostname(ctx, leaseID, hostname, serviceName, externalPort)
}
func (s *service) Status(ctx context.Context) (*ctypes.Status, error) {
istatus, err := s.inventory.status(ctx)
if err != nil {
return nil, err
}
ch := make(chan *ctypes.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:
result.Inventory = istatus
return result, nil
}
}
func (s *service) StatusV1(ctx context.Context) (*provider.ClusterStatus, error) {
istatus, err := s.inventory.statusV1(ctx)
if err != nil {
return nil, err
}
ch := make(chan uint32, 1)
select {
case <-s.lc.Done():
return nil, ErrNotRunning
case <-ctx.Done():
return nil, ctx.Err()
case s.statusV1ch <- ch:
}
select {
case <-s.lc.Done():
return nil, ErrNotRunning
case <-ctx.Done():
return nil, ctx.Err()
case result := <-ch:
res := &provider.ClusterStatus{
Leases: provider.Leases{
Active: result,
},
Inventory: *istatus,
}
return res, nil
}
}
func (s *service) updateDeploymentManagerGauge() {
deploymentManagerGauge.Set(float64(len(s.managers)))
}
func (s *service) run(ctx context.Context, deployments []ctypes.IDeployment) {
defer s.lc.ShutdownCompleted()
defer s.sub.Close()
s.updateDeploymentManagerGauge()
// wait for configured operators to be online & responsive before proceeding
err := s.waiter.WaitForAll(ctx)
if err != nil {
s.lc.ShutdownInitiated(err)
return
}
bus := fromctx.MustPubSubFromCtx(ctx)
inventorych := bus.Sub(ptypes.PubSubTopicInventoryStatus)
for _, deployment := range deployments {
s.managers[deployment.LeaseID()] = newDeploymentManager(s, deployment, false)
s.updateDeploymentManagerGauge()
}
signalch := make(chan struct{}, 1)
trySignal := func() {
select {
case signalch <- struct{}{}:
case <-ctx.Done():
default:
}
}
trySignal()
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.ManifestReceived:
s.log.Info("manifest received", "lease", ev.LeaseID)
mgroup := ev.ManifestGroup()
if mgroup == nil {
s.log.Error("indeterminate manifest group", "lease", ev.LeaseID, "group-name", ev.Group.GroupSpec.Name)
break
}
reservation, err := s.inventory.lookup(ev.LeaseID.OrderID(), mgroup)
if err != nil {
s.log.Error("error looking up manifest", "err", err, "lease", ev.LeaseID, "group-name", mgroup.Name)
break
}
deployment := &ctypes.Deployment{
Lid: ev.LeaseID,
MGroup: mgroup,
CParams: reservation.ClusterParams(),
}
key := ev.LeaseID
if manager := s.managers[key]; manager != nil {
if err := manager.update(deployment); err != nil {
s.log.Error("updating deployment", "err", err, "lease", ev.LeaseID, "group-name", mgroup.Name)
}
break
}
s.managers[key] = newDeploymentManager(s, deployment, true)
trySignal()
case mtypes.EventLeaseClosed:
_ = s.bus.Publish(event.LeaseRemoveFundsMonitor{LeaseID: ev.ID})
s.teardownLease(ev.ID)
}
case ch := <-s.statusch:
ch <- &ctypes.Status{
Leases: uint32(len(s.managers)),
}
case ch := <-s.statusV1ch:
ch <- uint32(len(s.managers))
case <-signalch:
istatus, _ := s.inventory.statusV1(ctx)
if istatus == nil {
continue
}
msg := provider.ClusterStatus{
Leases: provider.Leases{Active: uint32(len(s.managers))},
Inventory: *istatus,
}
bus.Pub(msg, []string{ptypes.PubSubTopicClusterStatus}, tpubsub.WithRetain())
case <-inventorych:
trySignal()
case dm := <-s.managerch:
s.log.Info("manager done", "lease", dm.deployment.LeaseID())
// unreserve resources
if err := s.inventory.unreserve(dm.deployment.LeaseID().OrderID()); err != nil {
s.log.Error("unreserving inventory",
"err", err,
"lease", dm.deployment.LeaseID())
}
delete(s.managers, dm.deployment.LeaseID())
trySignal()
case req := <-s.checkDeploymentExistsRequestCh:
s.doCheckDeploymentExists(req)
}
s.updateDeploymentManagerGauge()
}
s.log.Debug("draining deployment managers...", "qty", len(s.managers))
for _, manager := range s.managers {
if manager != nil {
manager := <-s.managerch
s.log.Debug("manager done", "lease", manager.deployment.LeaseID())
}
}
<-s.inventory.done()
s.session.Log().Info("shutdown complete")
}
func (s *service) doCheckDeploymentExists(req checkDeploymentExistsRequest) {
for leaseID := range s.managers {
// Check for a match
if leaseID.GSeq == req.gseq && leaseID.DSeq == req.dseq && leaseID.Owner == req.owner.String() {
req.responseCh <- leaseID
return
}
}
close(req.responseCh)
}
func (s *service) teardownLease(lid mtypes.LeaseID) {
if manager := s.managers[lid]; manager != nil {
if err := manager.teardown(); err != nil {
s.log.Error("tearing down lease deployment", "err", err, "lease", lid)
}
return
}
// unreserve resources if no manager present yet.
if lid.Provider == s.session.Provider().Owner {
s.log.Info("unreserving unmanaged order", "lease", lid)
err := s.inventory.unreserve(lid.OrderID())
if err != nil && !errors.Is(errReservationNotFound, err) {
s.log.Error("unreserve failed", "lease", lid, "err", err)
}
}
}
func findDeployments(ctx context.Context, log log.Logger, client Client, _ session.Session) ([]ctypes.IDeployment, error) {
deployments, err := client.Deployments(ctx)
if err != nil {
log.Error("fetching deployments", "err", err)
return nil, err
}
return deployments, nil
}