-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor.go
More file actions
696 lines (598 loc) · 17.9 KB
/
monitor.go
File metadata and controls
696 lines (598 loc) · 17.9 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// Copyright 2023 The CortexTheseus Authors
// This file is part of the CortexTheseus library.
//
// The CortexTheseus library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The CortexTheseus library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the CortexTheseus library. If not, see <http://www.gnu.org/licenses/>.
package robot
import (
"context"
"errors"
"math"
//"sort"
"fmt"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/CortexFoundation/CortexTheseus/common"
"github.com/CortexFoundation/CortexTheseus/common/mclock"
"github.com/CortexFoundation/CortexTheseus/log"
"github.com/CortexFoundation/CortexTheseus/rpc"
"github.com/CortexFoundation/torrentfs/params"
"github.com/CortexFoundation/torrentfs/types"
lru "github.com/hashicorp/golang-lru/v2"
ttl "github.com/hashicorp/golang-lru/v2/expirable"
"github.com/ucwong/golang-kv"
"github.com/CortexFoundation/robot/backend"
)
// Monitor observes the data changes on the blockchain and synchronizes.
// cl for ipc/rpc communication, dl for download manager, and fs for data storage.
type Monitor struct {
config *params.Config
cl *rpc.Client
fs *backend.ChainDB
engine kv.Bucket
//dl *backend.TorrentManager
exitCh chan any
srvCh chan int
//exitSyncCh chan any
terminated atomic.Bool
lastNumber atomic.Uint64
startNumber atomic.Uint64
currentNumber atomic.Uint64
scope uint64
wg sync.WaitGroup
rpcWg sync.WaitGroup
taskCh chan *types.Block
errCh chan error
//newTaskHook func(*types.Block)
blockCache *lru.Cache[uint64, string]
//blockCache *lru.LRU[uint64, string]
sizeCache *ttl.LRU[string, uint64]
ckp *params.TrustedCheckpoint
start mclock.AbsTime
local bool
listen bool
startOnce sync.Once
closeOnce sync.Once
mode string
lock sync.RWMutex
callback chan any
srv atomic.Int32
}
// NewMonitor creates a new instance of monitor.
// Once Ipcpath is settle, this method prefers to build socket connection in order to
// get higher communicating performance.
// IpcPath is unavailable on windows.
// func New(flag *params.Config, cache, compress, listen bool, fs *backend.ChainDB, tMana *backend.TorrentManager, callback chan any) (*Monitor, error) {
func New(flag *params.Config, cache, compress, listen bool, callback chan any) (m *Monitor, err error) {
/*fs, fsErr := NewChainDB(flag)
if fsErr != nil {
log.Error("file storage failed", "err", fsErr)
return nil, fsErr
}
log.Info("File storage initialized")
tMana, err := NewTorrentManager(flag, fs.ID(), cache, compress)
if err != nil || tMana == nil {
log.Error("fs manager failed")
return nil, errors.New("fs download manager initialise failed")
}
log.Info("Fs manager initialized")*/
m = &Monitor{
config: flag,
cl: nil,
//fs: fs,
//dl: tMana,
exitCh: make(chan any),
srvCh: make(chan int),
//exitSyncCh: make(chan any),
scope: uint64(math.Max(float64(runtime.NumCPU()*2), float64(8))),
//taskCh: make(chan *types.Block, batch),
//taskCh: make(chan *types.Block, 1),
//start: mclock.Now(),
}
m.errCh = make(chan error, m.scope)
m.taskCh = make(chan *types.Block, m.scope)
// TODO https://github.com/ucwong/golang-kv
if fs_, err := backend.NewChainDB(flag); err != nil {
log.Error("file storage failed", "err", err)
return nil, err
} else {
m.fs = fs_
}
m.fs.Init()
m.lastNumber.Store(0)
m.currentNumber.Store(0)
m.startNumber.Store(0)
m.terminated.Store(false)
//m.blockCache = lru.NewLRU[uint64, string](delay, nil, time.Second*60)
m.blockCache, _ = lru.New[uint64, string](delay)
m.sizeCache = ttl.NewLRU[string, uint64](batch, nil, time.Second*60)
m.listen = listen
m.callback = callback
//if err := m.dl.Start(); err != nil {
// log.Warn("Fs start error")
// return nil, err
//}
m.mode = flag.Mode
m.srv.Store(SRV_MODEL)
m.engine = kv.Pebble(filepath.Join(flag.DataDir, ".srv"))
/*torrents, _ := fs.initTorrents()
if m.mode != params.LAZY {
for k, v := range torrents {
if err := GetStorage().Download(context.Background(), k, v); err != nil {
return nil, err
}
}
}
if len(torrents) == 0 {
log.Warn("Data reloading", "mode", m.mode)
m.indexInit()
}*/
return m, nil
}
func (m *Monitor) CurrentNumber() uint64 {
return m.currentNumber.Load()
}
func (m *Monitor) ID() uint64 {
return m.fs.ID()
}
func (m *Monitor) DB() *backend.ChainDB {
return m.fs
}
func (m *Monitor) Callback() chan any {
return m.callback
}
/*func (m *Monitor) loadHistory() error {
torrents, _ := m.fs.InitTorrents()
if m.mode != params.LAZY {
for k, v := range torrents {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
m.download(ctx, k, v)
}
}
if len(torrents) == 0 {
log.Warn("Data reloading", "mode", m.mode)
if err := m.indexInit(); err != nil {
return err
}
}
return nil
}*/
func (m *Monitor) download(ctx context.Context, k string, v uint64) error {
if m.mode != params.LAZY && m.callback != nil {
select {
case m.callback <- types.NewBitsFlow(k, v):
case <-ctx.Done():
return ctx.Err()
case <-m.exitCh:
return errors.New("terminated")
}
}
return nil
}
func (m *Monitor) indexCheck() error {
log.Info("Loading storage data ... ...", "latest", m.fs.LastListenBlockNumber(), "checkpoint", m.fs.CheckPoint(), "root", m.fs.Root(), "version", m.fs.Version(), "current", m.currentNumber.Load())
genesis, err := m.rpcBlockByNumber(0)
if err != nil {
return err
}
if checkpoint, ok := params.TrustedCheckpoints[genesis.Hash]; ok {
m.ckp = checkpoint
version := m.fs.GetRoot(checkpoint.TfsCheckPoint)
if common.BytesToHash(version) != checkpoint.TfsRoot {
m.lastNumber.Store(0)
m.startNumber.Store(0)
if m.lastNumber.Load() > checkpoint.TfsCheckPoint {
//m.fs.LastListenBlockNumber = 0
m.fs.Anchor(0)
//m.lastNumber = 0
//if err := m.fs.Reset(); err != nil {
// return err
//}
}
log.Warn("Fs storage is reloading ...", "name", m.ckp.Name, "number", checkpoint.TfsCheckPoint, "version", common.BytesToHash(version), "checkpoint", checkpoint.TfsRoot, "blocks", len(m.fs.Blocks()), "files", len(m.fs.Files()), "txs", m.fs.Txs(), "lastNumber", m.lastNumber.Load(), "last", m.fs.LastListenBlockNumber())
} else {
log.Info("Fs storage version check passed", "name", m.ckp.Name, "number", checkpoint.TfsCheckPoint, "version", common.BytesToHash(version), "blocks", len(m.fs.Blocks()), "files", len(m.fs.Files()), "txs", m.fs.Txs())
}
}
return nil
}
func (m *Monitor) indexInit() error {
fileMap := make(map[string]*types.FileInfo, len(m.fs.Files()))
for _, file := range m.fs.Files() {
if f, ok := fileMap[file.Meta.InfoHash]; ok {
if f.LeftSize > file.LeftSize {
fileMap[file.Meta.InfoHash] = file
}
} else {
fileMap[file.Meta.InfoHash] = file
}
}
var (
capcity = uint64(0)
seed = 0
pause = 0
pending = 0
)
for _, file := range fileMap {
var bytesRequested uint64
if file.Meta.RawSize > file.LeftSize {
bytesRequested = file.Meta.RawSize - file.LeftSize
}
capcity += bytesRequested
log.Debug("File storage info", "addr", file.ContractAddr, "ih", file.Meta.InfoHash, "remain", common.StorageSize(file.LeftSize), "raw", common.StorageSize(file.Meta.RawSize), "request", common.StorageSize(bytesRequested))
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := m.download(ctx, file.Meta.InfoHash, bytesRequested); err != nil {
return err
}
if file.LeftSize == 0 {
seed++
} else if file.Meta.RawSize == file.LeftSize && file.LeftSize > 0 {
pending++
} else if file.Meta.RawSize > file.LeftSize && file.LeftSize > 0 {
pause++
}
}
log.Info("Storage current state", "total", len(m.fs.Files()), "dis", len(fileMap), "seed", seed, "pause", pause, "pending", pending, "capcity", common.StorageSize(capcity), "blocks", len(m.fs.Blocks()), "txs", m.fs.Txs())
return nil
}
func (m *Monitor) taskLoop() {
log.Info("Task channel started")
defer m.wg.Done()
for {
select {
case task := <-m.taskCh:
//if m.newTaskHook != nil {
// m.newTaskHook(task)
//}
/*if err := m.solve(task); err != nil {
m.errCh <- err
log.Warn("Block solved failed, try again", "err", err, "num", task.Number, "last", m.lastNumber.Load())
} else {
m.errCh <- nil
}*/
m.errCh <- m.solve(task)
case <-m.exitCh:
log.Info("Monitor task channel closed")
return
}
}
}
/*func (m *Monitor) exit() {
m.closeOnce.Do(func() {
if m.exitCh != nil {
close(m.exitCh)
m.wg.Wait()
m.exitCh = nil
} else {
log.Warn("Listener has already been stopped")
}
})
}
func (m *Monitor) Stop() error {
m.lock.Lock()
defer m.lock.Unlock()
if m.terminated.Swap(true) {
return nil
}
m.exit()
log.Info("Monitor is waiting to be closed")
m.blockCache.Purge()
m.sizeCache.Purge()
//log.Info("Fs client listener synchronizing closing")
//if err := m.dl.Close(); err != nil {
// log.Error("Monitor Fs Manager closed", "error", err)
//}
// TODO dirty statics deal with
if m.engine != nil {
log.Info("Golang-kv engine close", "engine", m.engine.Name())
if err := m.engine.Close(); err != nil {
return err
}
}
if err := m.fs.Close(); err != nil {
log.Error("Monitor File Storage closed", "error", err)
return err
}
log.Info("Fs listener synchronizing closed")
return nil
}*/
func (m *Monitor) exit() {
m.closeOnce.Do(func() {
if m.exitCh != nil {
close(m.exitCh)
m.wg.Wait()
} else {
log.Debug("Listener exit channel already closed")
}
})
}
func (m *Monitor) Stop() error {
m.lock.Lock()
if m.terminated.Swap(true) {
m.lock.Unlock()
return nil
}
m.lock.Unlock()
m.exit()
log.Info("Monitor is waiting to be closed")
var errs []error
m.blockCache.Purge()
m.sizeCache.Purge()
if m.engine != nil {
log.Info("Closing Golang-kv engine", "engine", m.engine.Name())
if err := m.engine.Close(); err != nil {
errs = append(errs, fmt.Errorf("engine close: %w", err))
}
}
if err := m.fs.Close(); err != nil {
errs = append(errs, fmt.Errorf("fs close: %w", err))
}
log.Info("Fs listener synchronizing closed")
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// Start ... start ListenOn on the rpc port of a blockchain full node
func (m *Monitor) Start() error {
//if !m.listen {
//log.Info("Disable listener")
//return nil
//}
m.startOnce.Do(func() {
m.wg.Add(1)
go func() {
defer m.wg.Done()
//m.fs.Init()
if err := m.run(); err != nil {
log.Error("Fs monitor start failed", "err", err)
}
}()
})
return nil
}
func (m *Monitor) run() error {
var ipcpath string
if runtime.GOOS != "windows" && m.config.IpcPath != "" {
ipcpath = m.config.IpcPath
//} else {
// if m.config.RpcURI == "" {
// log.Warn("Fs rpc uri is empty")
// return errors.New("fs RpcURI is empty")
// }
// clientURI = m.config.RpcURI
}
rpcClient, rpcErr := m.buildConnection(ipcpath, m.config.RpcURI)
if rpcErr != nil {
log.Error("Fs rpc client is wrong", "uri", ipcpath, "error", rpcErr, "config", m.config)
return rpcErr
}
m.cl = rpcClient
if m.srv.Load() == SRV_MODEL {
m.lastNumber.Store(m.fs.LastListenBlockNumber())
if err := m.indexCheck(); err != nil {
return err
}
}
m.currentBlock()
m.startNumber.Store(uint64(math.Min(float64(m.fs.LastListenBlockNumber()), float64(m.currentNumber.Load())))) // ? m.currentNumber:m.fs.LastListenBlockNumber
//if err := m.loadHistory(); err != nil {
// return err
//}
m.wg.Add(1)
go m.taskLoop()
m.wg.Add(1)
go m.listenLatestBlock()
m.wg.Add(1)
go m.syncLatestBlock()
return nil
}
func (m *Monitor) listenLatestBlock() {
defer m.wg.Done()
timer := time.NewTimer(time.Second * params.QueryTimeInterval)
defer timer.Stop()
for {
select {
case <-timer.C:
if cur, update, err := m.currentBlock(); err == nil && update {
log.Debug("Blockchain update", "cur", cur)
}
if m.local {
timer.Reset(time.Second * params.QueryTimeInterval)
} else {
timer.Reset(time.Second * params.QueryTimeInterval * 10)
}
case <-m.exitCh:
log.Info("Block listener stopped")
return
}
}
}
func (m *Monitor) syncLatestBlock() {
defer m.wg.Done()
timer := time.NewTimer(time.Second * params.QueryTimeInterval)
defer timer.Stop()
counter := 0
// Helper function to determine the next delay based on sync progress
getNextDelay := func(progress uint64) time.Duration {
if progress >= delay {
return 0 // Trigger immediately
}
if progress > 1 {
return time.Millisecond * 2000
}
if progress == 1 {
return time.Millisecond * 6750
}
// If progress is 0, check for listener and checkpoint status
if !m.listen && ((m.ckp != nil && m.currentNumber.Load() >= m.ckp.TfsCheckPoint) || (m.ckp == nil && m.currentNumber.Load() > 0)) {
// This part seems to have a specific termination or pause logic
// The original code has some commented-out `return`, so I'm assuming it's a "steady state" delay.
return time.Millisecond * 6750
}
return time.Millisecond * 6750 // Default case for other conditions
}
for {
select {
case sv := <-m.srvCh:
if err := m.doSwitch(sv); err != nil {
log.Error("Service switch failed", "srv", sv, "err", err)
}
case <-timer.C:
progress := m.syncLastBlock()
// Determine the next delay and reset the timer
nextDelay := getNextDelay(progress)
timer.Reset(nextDelay)
// Log status periodically
counter += int(progress)
if counter > 65536 {
log.Info("Monitor status", "blocks", progress, "current", m.CurrentNumber(), "latest", m.lastNumber.Load(), "txs", m.fs.Txs(), "ckp", m.fs.CheckPoint(), "last", m.fs.LastListenBlockNumber(), "progress", progress, "root", m.fs.Root())
counter = 0
}
// Always flush at the end of a timer cycle
//m.fs.Anchor(m.lastNumber.Load())
//m.fs.Flush()
case <-m.exitCh:
return
}
}
}
func (m *Monitor) skip(num uint64) (bool, uint64) {
if m.srv.Load() != SRV_MODEL {
return false, 0
}
if len(m.ckp.Skips) == 0 || num > m.ckp.Skips[len(m.ckp.Skips)-1].To || num < m.ckp.Skips[0].From {
return false, 0
}
for _, skip := range m.ckp.Skips {
if num > skip.From && num < skip.To {
return true, skip.To
}
}
return false, 0
}
func (m *Monitor) syncLastBlock() uint64 {
currentNumber := m.currentNumber.Load()
lastNumber := m.lastNumber.Load()
// Step 1: Handle rollback logic if current block number is less than the last processed number.
if currentNumber < lastNumber {
log.Warn("Fs sync rollback detected", "current", currentNumber, "last", lastNumber, "offset", lastNumber-currentNumber)
rollbackNumber := uint64(0)
if currentNumber > 65536 {
rollbackNumber = currentNumber - 65536
}
m.lastNumber.Store(rollbackNumber)
m.startNumber.Store(rollbackNumber)
}
// Step 2: Determine the block range for this sync batch.
minNumber := m.lastNumber.Load() + 1
maxNumber := currentNumber
if currentNumber > delay {
maxNumber = currentNumber - delay
}
// If the last processed block is unexpectedly higher than the current block (after rollback check),
// this indicates a need to sync backward from the last number.
if m.lastNumber.Load() > currentNumber {
minNumber = m.lastNumber.Load() - batch
if m.lastNumber.Load() < batch {
minNumber = 0 // Avoids underflow if lastNumber is smaller than batch
}
}
// Adjust maxNumber to not exceed the batch size.
if maxNumber > minNumber+batch {
maxNumber = minNumber + batch
}
if maxNumber < minNumber {
return 0
}
m.start = mclock.Now()
processedCount := 0
for i := minNumber; i <= maxNumber; {
if m.terminated.Load() {
log.Warn("Fs scan terminated by signal", "lastProcessed", i-1)
m.lastNumber.Store(i - 1)
return 0
}
if m.ckp != nil {
if skip, to := m.skip(i); skip {
i = to
continue
}
}
// Step 3: Fetch blocks in a batch or individually based on remaining scope.
remainingScope := maxNumber - i
if remainingScope >= m.scope {
// Process a batch of blocks
blocks, err := m.rpcBatchBlockByNumber(i, i+m.scope)
if err != nil {
return m.handleSyncError("Batch sync old block failed", err, i-1)
}
// Send blocks to the processing channel
for _, block := range blocks {
m.taskCh <- block
}
// Wait for the processing results for the entire batch
for range blocks {
select {
case err := <-m.errCh:
if err != nil {
return m.handleSyncError("Processing error", err, i-1)
}
case <-m.exitCh:
log.Info("Task checker quit signal received")
m.lastNumber.Store(i - 1)
return 0
}
}
i += uint64(len(blocks))
processedCount += len(blocks)
} else {
// Process a single block
block, err := m.rpcBlockByNumber(i)
if err != nil {
return m.handleSyncError("Sync old block failed", err, i-1)
}
if err := m.solve(block); err != nil {
return m.handleSyncError("solve err", err, i-1)
}
i++
processedCount++
}
}
// Step 4: Finalize the sync operation.
m.lastNumber.Store(maxNumber)
elapsed := time.Duration(mclock.Now()) - time.Duration(m.start)
log.Debug("Chain segment frozen",
"from", minNumber,
"to", maxNumber,
"totalBlocks", uint64(maxNumber-minNumber+1),
"processed", processedCount,
"scope", m.scope,
"current", m.CurrentNumber(),
"last", m.lastNumber.Load(),
"elapsed", common.PrettyDuration(elapsed),
"bps", float64(processedCount)/elapsed.Seconds(),
)
return uint64(maxNumber - minNumber)
}
// handleSyncError is a helper function to log an error, update the last processed block number, and return 0.
func (m *Monitor) handleSyncError(msg string, err error, lastBlock uint64) uint64 {
log.Error(msg, "error", err, "lastProcessed", lastBlock)
m.lastNumber.Store(lastBlock)
return 0
}