-
Notifications
You must be signed in to change notification settings - Fork 20
/
state_machine_handler.go
375 lines (293 loc) · 10.6 KB
/
state_machine_handler.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
package assets
import (
"math"
"time"
"github.com/Filecoin-Titan/titan/api/types"
"github.com/Filecoin-Titan/titan/node/scheduler/node"
"github.com/alecthomas/units"
"github.com/filecoin-project/go-statemachine"
"golang.org/x/xerrors"
)
var (
// MinRetryTime defines the minimum time duration between retries
MinRetryTime = 1 * time.Minute
// MaxRetryCount defines the maximum number of retries allowed
MaxRetryCount = 3
)
// failedCoolDown is called when a retry needs to be attempted and waits for the specified time duration
func failedCoolDown(ctx statemachine.Context, info AssetPullingInfo) error {
retryStart := time.Now().Add(MinRetryTime)
if time.Now().Before(retryStart) {
log.Debugf("%s(%s), waiting %s before retrying", info.State, info.Hash, time.Until(retryStart))
select {
case <-time.After(time.Until(retryStart)):
case <-ctx.Context().Done():
return ctx.Context().Err()
}
}
return nil
}
// handleSeedSelect handles the selection of seed nodes for asset pull
func (m *Manager) handleSeedSelect(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle select seed: %s", info.CID)
if len(info.CandidateReplicaSucceeds) >= seedReplicaCount {
// The number of candidate node replicas has reached the requirement
return ctx.Send(SkipStep{})
}
// find nodes
nodes, str := m.chooseCandidateNodes(seedReplicaCount, info.CandidateReplicaSucceeds)
if len(nodes) < 1 {
return ctx.Send(SelectFailed{error: xerrors.Errorf("node not found; %s", str)})
}
// save to db
err := m.saveReplicaInformation(nodes, info.Hash.String(), true)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
m.startAssetTimeoutCounting(info.Hash.String(), 0)
// send a cache request to the node
go func() {
for _, node := range nodes {
err := node.PullAsset(ctx.Context(), info.CID, nil)
if err != nil {
log.Errorf("%s pull asset err:%s", node.NodeID, err.Error())
continue
}
}
}()
return ctx.Send(PullRequestSent{})
}
// handleSeedPulling handles the asset pulling process of seed nodes
func (m *Manager) handleSeedPulling(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle seed pulling, %s", info.CID)
if len(info.CandidateReplicaSucceeds) >= seedReplicaCount {
return ctx.Send(PullSucceed{})
}
if info.CandidateWaitings == 0 {
return ctx.Send(PullFailed{error: xerrors.New("node pull failed")})
}
return nil
}
// handleUploadInit handles the upload init
func (m *Manager) handleUploadInit(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle upload init: %s, nodeID: %s", info.CID, info.SeedNodeID)
if len(info.CandidateReplicaSucceeds) >= seedReplicaCount {
// The number of candidate node replicas has reached the requirement
return ctx.Send(SkipStep{})
}
cNode := m.nodeMgr.GetCandidateNode(info.SeedNodeID)
if cNode == nil {
return ctx.Send(SelectFailed{})
}
nodes := map[string]*node.Node{
cNode.NodeID: cNode,
}
// save to db
err := m.saveReplicaInformation(nodes, info.Hash.String(), true)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
m.startAssetTimeoutCounting(info.Hash.String(), 0)
return ctx.Send(PullRequestSent{})
}
// handleSeedUploading handles the asset upload process of seed nodes
func (m *Manager) handleSeedUploading(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle seed upload, %s", info.CID)
if len(info.CandidateReplicaSucceeds) >= seedReplicaCount {
return ctx.Send(PullSucceed{})
}
if info.CandidateWaitings == 0 {
return ctx.Send(PullFailed{error: xerrors.New("user upload failed")})
}
return nil
}
// handleCandidatesSelect handles the selection of candidate nodes for asset pull
func (m *Manager) handleCandidatesSelect(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle candidates select, %s", info.CID)
sources := m.getDownloadSources(info.Hash.String())
if len(sources) < 1 {
return ctx.Send(SelectFailed{error: xerrors.New("source node not found")})
}
needCount := info.CandidateReplicas - int64(len(info.CandidateReplicaSucceeds))
if needCount < 1 {
err := m.DeleteReplenishBackup(info.Hash.String())
if err != nil {
log.Errorf("%s handle candidates DeleteReplenishBackup err, %s", info.Hash.String(), err.Error())
}
// The number of candidate node replicas has reached the requirement
return ctx.Send(SkipStep{})
}
// find nodes
nodes, str := m.chooseCandidateNodes(int(needCount), info.CandidateReplicaSucceeds)
if len(nodes) < 1 {
return ctx.Send(SelectFailed{error: xerrors.Errorf("node not found; %s", str)})
}
downloadSources, payloads, err := m.GenerateToken(info.CID, sources, nodes)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
err = m.SaveTokenPayload(payloads)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
// save to db
err = m.saveReplicaInformation(nodes, info.Hash.String(), true)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
m.startAssetTimeoutCounting(info.Hash.String(), 0)
// send a pull request to the node
go func() {
for _, node := range nodes {
err := node.PullAsset(ctx.Context(), info.CID, downloadSources[node.NodeID])
if err != nil {
log.Errorf("%s pull asset err:%s", node.NodeID, err.Error())
continue
}
}
}()
return ctx.Send(PullRequestSent{})
}
// handleCandidatesPulling handles the asset pulling process of candidate nodes
func (m *Manager) handleCandidatesPulling(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle candidates pulling,cid: %s, hash:%s", info.CID, info.Hash.String())
if int64(len(info.CandidateReplicaSucceeds)) >= info.CandidateReplicas {
err := m.DeleteReplenishBackup(info.Hash.String())
if err != nil {
log.Errorf("%s handle candidates DeleteReplenishBackup err, %s", info.Hash.String(), err.Error())
}
return ctx.Send(PullSucceed{})
}
if info.CandidateWaitings == 0 {
return ctx.Send(PullFailed{error: xerrors.New("node pull failed")})
}
return nil
}
func (m *Manager) getCurBandwidthUp(nodes []string) int64 {
bandwidthUp := int64(0)
for _, nodeID := range nodes {
node := m.nodeMgr.GetEdgeNode(nodeID)
if node != nil {
bandwidthUp += node.BandwidthUp
}
}
// B to MiB
v := int64(math.Ceil(float64(bandwidthUp) / float64(units.MiB)))
return v
}
// handleEdgesSelect handles the selection of edge nodes for asset pull
func (m *Manager) handleEdgesSelect(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle edges select , %s", info.CID)
needCount := info.EdgeReplicas - int64(len(info.EdgeReplicaSucceeds))
if info.ReplenishReplicas > 0 {
// Check to node offline while replenishing the temporary replica
needCount = info.ReplenishReplicas
}
needBandwidth := info.Bandwidth - m.getCurBandwidthUp(info.EdgeReplicaSucceeds)
if needCount < 1 && needBandwidth <= 0 {
// The number of edge node replications and the total downlink bandwidth are met
return ctx.Send(SkipStep{})
}
sources := m.getDownloadSources(info.Hash.String())
if len(sources) < 1 {
return ctx.Send(SelectFailed{error: xerrors.New("source node not found")})
}
// find nodes
nodes, str := m.chooseEdgeNodes(int(needCount), needBandwidth, info.EdgeReplicaSucceeds, float64(info.Size))
if len(nodes) < 1 {
return ctx.Send(SelectFailed{error: xerrors.Errorf("node not found; %s", str)})
}
downloadSources, payloads, err := m.GenerateToken(info.CID, sources, nodes)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
err = m.SaveTokenPayload(payloads)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
// save to db
err = m.saveReplicaInformation(nodes, info.Hash.String(), false)
if err != nil {
return ctx.Send(SelectFailed{error: err})
}
m.startAssetTimeoutCounting(info.Hash.String(), 0)
// send a pull request to the node
go func() {
for _, node := range nodes {
err := node.PullAsset(ctx.Context(), info.CID, downloadSources[node.NodeID])
if err != nil {
log.Errorf("%s pull asset err:%s", node.NodeID, err.Error())
continue
}
}
}()
return ctx.Send(PullRequestSent{})
}
// handleEdgesPulling handles the asset pulling process of edge nodes
func (m *Manager) handleEdgesPulling(ctx statemachine.Context, info AssetPullingInfo) error {
log.Debugf("handle edges pulling, %s", info.CID)
needBandwidth := info.Bandwidth - m.getCurBandwidthUp(info.EdgeReplicaSucceeds)
if int64(len(info.EdgeReplicaSucceeds)) >= info.EdgeReplicas && needBandwidth <= 0 {
return ctx.Send(PullSucceed{})
}
if info.EdgeWaitings == 0 {
return ctx.Send(PullFailed{error: xerrors.New("node pull failed")})
}
return nil
}
// handleServicing asset pull completed and in service status
func (m *Manager) handleServicing(ctx statemachine.Context, info AssetPullingInfo) error {
log.Infof("handle servicing: %s", info.CID)
m.stopAssetTimeoutCounting(info.Hash.String())
// remove fail replicas
return m.DeleteUnfinishedReplicas(info.Hash.String())
}
// handlePullsFailed handles the failed state of asset pulling and retries if necessary
func (m *Manager) handlePullsFailed(ctx statemachine.Context, info AssetPullingInfo) error {
m.stopAssetTimeoutCounting(info.Hash.String())
if info.RetryCount >= int64(MaxRetryCount) {
log.Infof("handle pulls failed: %s, retry count: %d", info.CID, info.RetryCount)
err := m.DeleteReplenishBackup(info.Hash.String())
if err != nil {
log.Errorf("%s handle candidates DeleteReplenishBackup err, %s", info.Hash.String(), err.Error())
}
return nil
}
log.Debugf("handle pulls failed: %s, retries: %d", info.CID, info.RetryCount)
if err := failedCoolDown(ctx, info); err != nil {
return err
}
return ctx.Send(AssetRePull{})
}
func (m *Manager) handleUploadFailed(ctx statemachine.Context, info AssetPullingInfo) error {
log.Infof("handle upload fail: %s", info.CID)
m.stopAssetTimeoutCounting(info.Hash.String())
return nil
}
func (m *Manager) handleRemove(ctx statemachine.Context, info AssetPullingInfo) error {
log.Infof("handle remove: %s", info.CID)
m.stopAssetTimeoutCounting(info.Hash.String())
defer m.AssetRemoveDone(info.Hash.String())
hash := info.Hash.String()
cid := info.CID
cInfos, err := m.LoadReplicasByStatus(hash, types.ReplicaStatusAll)
if err != nil {
return xerrors.Errorf("RemoveAsset %s LoadAssetReplicas err:%s", info.CID, err.Error())
}
// node info
for _, cInfo := range cInfos {
err = m.RemoveReplica(cid, hash, cInfo.NodeID)
if err != nil {
return xerrors.Errorf("RemoveAsset %s RemoveReplica err: %s", hash, err.Error())
}
}
// remove user asset
users, err := m.ListUsersForAsset(hash)
for _, user := range users {
err = m.DeleteAssetUser(hash, user)
if err != nil {
log.Errorf("DeleteAssetUser: %s", info.CID)
}
}
return nil
}