forked from akash-network/provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
253 lines (209 loc) · 5.99 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
package bidengine
import (
"context"
"errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/boz/go-lifecycle"
sdkquery "github.com/cosmos/cosmos-sdk/types/query"
mtypes "github.com/akash-network/akash-api/go/node/market/v1beta4"
"github.com/akash-network/node/pubsub"
mquery "github.com/akash-network/node/x/market/query"
"github.com/akash-network/provider/cluster"
"github.com/akash-network/provider/operator/waiter"
"github.com/akash-network/provider/session"
)
var (
ordersCounter = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "provider_order_handler",
Help: "The total number of orders created",
}, []string{"action"})
)
// ErrNotRunning declares new error with message "not running"
var ErrNotRunning = errors.New("not running")
// StatusClient interface predefined with Status method
type StatusClient interface {
Status(context.Context) (*Status, error)
}
var (
orderManagerGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "provider_order_manager",
Help: "",
ConstLabels: nil,
})
)
// Service handles bidding on orders.
type Service interface {
StatusClient
Close() error
Done() <-chan struct{}
}
// NewService creates new service instance and returns error in case of failure
func NewService(ctx context.Context, session session.Session, cluster cluster.Cluster, bus pubsub.Bus, waiter waiter.OperatorWaiter, cfg Config) (Service, error) {
session = session.ForModule("bidengine-service")
existingOrders, err := queryExistingOrders(ctx, session)
if err != nil {
session.Log().Error("finding existing orders", "err", err)
return nil, err
}
sub, err := bus.Subscribe()
if err != nil {
return nil, err
}
session.Log().Info("found orders", "count", len(existingOrders))
providerAttrService, err := newProviderAttrSignatureService(session, bus)
if err != nil {
return nil, err
}
s := &service{
session: session,
cluster: cluster,
bus: bus,
sub: sub,
statusch: make(chan chan<- *Status),
orders: make(map[string]*order),
drainch: make(chan *order),
lc: lifecycle.New(),
cfg: cfg,
pass: providerAttrService,
waiter: waiter,
}
go s.lc.WatchContext(ctx)
go s.run(ctx, existingOrders)
return s, nil
}
type service struct {
session session.Session
cluster cluster.Cluster
cfg Config
bus pubsub.Bus
sub pubsub.Subscriber
statusch chan chan<- *Status
orders map[string]*order
drainch chan *order
lc lifecycle.Lifecycle
pass *providerAttrSignatureService
waiter waiter.OperatorWaiter
}
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) 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) updateOrderManagerGauge() {
orderManagerGauge.Set(float64(len(s.orders)))
}
func (s *service) run(ctx context.Context, existingOrders []mtypes.OrderID) {
defer s.lc.ShutdownCompleted()
defer s.sub.Close()
s.updateOrderManagerGauge()
// wait for configured operators to be online & responsive before proceeding
err := s.waiter.WaitForAll(ctx)
if err != nil {
s.lc.ShutdownInitiated(err)
return
}
for _, orderID := range existingOrders {
key := mquery.OrderPath(orderID)
s.session.Log().Debug("creating catchup order", "order", key)
order, err := newOrder(s, orderID, s.cfg, s.pass, true)
if err != nil {
s.session.Log().Error("creating catchup order", "order", key, "err", err)
continue
}
s.orders[key] = order
s.updateOrderManagerGauge()
}
loop:
for {
select {
case <-s.lc.ShutdownRequest():
s.lc.ShutdownInitiated(nil)
break loop
case ev := <-s.sub.Events():
switch ev := ev.(type) { // nolint: gocritic
case mtypes.EventOrderCreated:
// new order
key := mquery.OrderPath(ev.ID)
s.session.Log().Info("order detected", "order", key)
if order := s.orders[key]; order != nil {
s.session.Log().Debug("existing order", "order", key)
break
}
// create an order object for managing the bid process and order lifecycle
order, err := newOrder(s, ev.ID, s.cfg, s.pass, false)
if err != nil {
s.session.Log().Error("handling order", "order", key, "err", err)
break
}
ordersCounter.WithLabelValues("start").Inc()
s.orders[key] = order
}
case ch := <-s.statusch:
ch <- &Status{
Orders: uint32(len(s.orders)),
}
case order := <-s.drainch:
// child done
key := mquery.OrderPath(order.orderID)
delete(s.orders, key)
ordersCounter.WithLabelValues("stop").Inc()
}
s.updateOrderManagerGauge()
}
s.pass.lc.ShutdownAsync(nil)
s.session.Log().Info("draining order monitors", "qty", len(s.orders))
// drain: wait for all order monitors to complete.
for len(s.orders) > 0 {
key := mquery.OrderPath((<-s.drainch).orderID)
delete(s.orders, key)
s.updateOrderManagerGauge()
}
s.session.Log().Debug("waiting on provider attributes service")
<-s.pass.lc.Done()
s.session.Log().Info("shutdown complete")
}
func queryExistingOrders(ctx context.Context, session session.Session) ([]mtypes.OrderID, error) {
params := &mtypes.QueryOrdersRequest{
Filters: mtypes.OrderFilters{},
Pagination: &sdkquery.PageRequest{
Limit: 10000,
},
}
res, err := session.Client().Query().Orders(ctx, params)
if err != nil {
session.Log().Error("error querying open orders:", "err", err)
return nil, err
}
orders := res.Orders
existingOrders := make([]mtypes.OrderID, 0)
for i := range orders {
pOrder := &orders[i]
// Only check existing orders that are open
if pOrder.State != mtypes.OrderOpen {
continue
}
existingOrders = append(existingOrders, pOrder.OrderID)
}
return existingOrders, nil
}