-
Notifications
You must be signed in to change notification settings - Fork 456
/
quaistats.go
1441 lines (1256 loc) · 41.5 KB
/
quaistats.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
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package quaistats implements the network stats reporting service.
package quaistats
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"net/http"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/dominant-strategies/go-quai/consensus/misc"
lru "github.com/hashicorp/golang-lru"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/process"
"os/exec"
"github.com/dominant-strategies/go-quai/common"
"github.com/dominant-strategies/go-quai/consensus"
"github.com/dominant-strategies/go-quai/core"
"github.com/dominant-strategies/go-quai/core/types"
"github.com/dominant-strategies/go-quai/event"
"github.com/dominant-strategies/go-quai/log"
"github.com/dominant-strategies/go-quai/node"
"github.com/dominant-strategies/go-quai/params"
"github.com/dominant-strategies/go-quai/rpc"
)
const (
// chainHeadChanSize is the size of channel listening to ChainHeadEvent.
chainHeadChanSize = 10
// reportInterval is the time interval between two reports.
reportInterval = 15
c_alpha = 8
c_statsErrorValue = int64(-1)
// Max number of stats objects to send in one batch
c_queueBatchSize uint64 = 10
// Number of blocks to include in one batch of transactions
c_txBatchSize uint64 = 10
// Seconds that we want to iterate over (3600s = 1 hr)
c_windowSize uint64 = 3600
// Max number of objects to keep in queue
c_maxQueueSize int = 100
)
var (
chainID9000 = big.NewInt(9000)
chainID12000 = big.NewInt(12000)
chainID15000 = big.NewInt(15000)
chainID17000 = big.NewInt(17000)
chainID1337 = big.NewInt(1337)
)
// backend encompasses the bare-minimum functionality needed for quaistats reporting
type backend interface {
SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription
CurrentHeader() *types.WorkObject
TotalLogS(header *types.WorkObject) *big.Int
HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.WorkObject, error)
Stats() (pending int, queued int)
ChainConfig() *params.ChainConfig
ProcessingState() bool
NodeCtx() int
NodeLocation() common.Location
Logger() *log.Logger
}
// fullNodeBackend encompasses the functionality necessary for a full node
// reporting to quaistats
type fullNodeBackend interface {
backend
BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.WorkObject, error)
BlockByHash(ctx context.Context, hash common.Hash) (*types.WorkObject, error)
CurrentBlock() *types.WorkObject
}
// Service implements an Quai netstats reporting daemon that pushes local
// chain statistics up to a monitoring server.
type Service struct {
backend backend
engine consensus.Engine // Consensus engine to retrieve variadic block fields
node string // Name of the node to display on the monitoring page
pass string // Password to authorize access to the monitoring page
host string // Remote address of the monitoring service
sendfullstats bool // Whether the node is sending full stats or not
pongCh chan struct{} // Pong notifications are fed into this channel
headSub event.Subscription
transactionStatsQueue *StatsQueue
detailStatsQueue *StatsQueue
appendTimeStatsQueue *StatsQueue
// After handling a block and potentially adding to the queues, it will notify the sendStats goroutine
// that stats are ready to be sent
statsReadyCh chan struct{}
blockLookupCache *lru.Cache
chainID *big.Int
instanceDir string // Path to the node's instance directory
}
// StatsQueue is a thread-safe queue designed for managing and processing stats data.
//
// The primary objective of the StatsQueue is to provide a safe mechanism for enqueuing,
// dequeuing, and requeuing stats objects concurrently across multiple goroutines.
//
// Key Features:
// - Enqueue: Allows adding an item to the end of the queue.
// - Dequeue: Removes and returns the item from the front of the queue.
// - RequeueFront: Adds an item back to the front of the queue, useful for failed processing attempts.
//
// Concurrent Access:
// - The internal state of the queue is protected by a mutex to prevent data races and ensure
// that the operations are atomic. As a result, it's safe to use across multiple goroutines
// without external synchronization.
type StatsQueue struct {
data []interface{}
mutex sync.Mutex
}
func NewStatsQueue() *StatsQueue {
return &StatsQueue{
data: make([]interface{}, 0),
}
}
func (q *StatsQueue) Enqueue(item interface{}) {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.data) >= c_maxQueueSize {
q.dequeue()
}
q.data = append(q.data, item)
}
func (q *StatsQueue) Dequeue() interface{} {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.data) == 0 {
return nil
}
return q.dequeue()
}
func (q *StatsQueue) dequeue() interface{} {
item := q.data[0]
q.data = q.data[1:]
return item
}
func (q *StatsQueue) EnqueueFront(item interface{}) {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.data) >= c_maxQueueSize {
q.dequeue()
}
q.data = append([]interface{}{item}, q.data...)
}
func (q *StatsQueue) EnqueueFrontBatch(items []interface{}) {
q.mutex.Lock()
defer q.mutex.Unlock()
// Iterate backwards through the items and add them to the front of the queue
// Going backwards means oldest items are not added in case of overflow
for i := len(items) - 1; i >= 0; i-- {
if len(q.data) >= c_maxQueueSize {
break
}
q.data = append([]interface{}{items[i]}, q.data...)
}
}
func (q *StatsQueue) Size() int {
q.mutex.Lock()
defer q.mutex.Unlock()
return len(q.data)
}
// parseEthstatsURL parses the netstats connection url.
// URL argument should be of the form <nodename:secret@host:port>
// If non-erroring, the returned slice contains 3 elements: [nodename, pass, host]
func parseEthstatsURL(url string) (parts []string, err error) {
err = fmt.Errorf("invalid netstats url: \"%s\", should be nodename:secret@host:port", url)
hostIndex := strings.LastIndex(url, "@")
if hostIndex == -1 || hostIndex == len(url)-1 {
return nil, err
}
preHost, host := url[:hostIndex], url[hostIndex+1:]
passIndex := strings.LastIndex(preHost, ":")
if passIndex == -1 {
return []string{preHost, "", host}, nil
}
nodename, pass := preHost[:passIndex], ""
if passIndex != len(preHost)-1 {
pass = preHost[passIndex+1:]
}
return []string{nodename, pass, host}, nil
}
// New returns a monitoring service ready for stats reporting.
func New(node *node.Node, backend backend, engine consensus.Engine, url string, sendfullstats bool) error {
parts, err := parseEthstatsURL(url)
if err != nil {
return err
}
chainID := backend.ChainConfig().ChainID
var durationLimit *big.Int
switch {
case chainID.Cmp(chainID9000) == 0:
durationLimit = params.DurationLimit
case chainID.Cmp(chainID12000) == 0:
durationLimit = params.GardenDurationLimit
case chainID.Cmp(chainID15000) == 0:
durationLimit = params.OrchardDurationLimit
case chainID.Cmp(chainID17000) == 0:
durationLimit = params.LighthouseDurationLimit
case chainID.Cmp(chainID1337) == 0:
durationLimit = params.LocalDurationLimit
default:
durationLimit = params.DurationLimit
}
durationLimitInt := durationLimit.Uint64()
c_blocksPerWindow := c_windowSize / durationLimitInt
blockLookupCache, _ := lru.New(int(c_blocksPerWindow * 2))
quaistats := &Service{
backend: backend,
engine: engine,
node: parts[0],
pass: parts[1],
host: parts[2],
pongCh: make(chan struct{}),
chainID: backend.ChainConfig().ChainID,
transactionStatsQueue: NewStatsQueue(),
detailStatsQueue: NewStatsQueue(),
appendTimeStatsQueue: NewStatsQueue(),
statsReadyCh: make(chan struct{}, 1),
sendfullstats: sendfullstats,
blockLookupCache: blockLookupCache,
instanceDir: node.InstanceDir(),
}
node.RegisterLifecycle(quaistats)
return nil
}
// Start implements node.Lifecycle, starting up the monitoring and reporting daemon.
func (s *Service) Start() error {
// Subscribe to chain events to execute updates on
chainHeadCh := make(chan core.ChainHeadEvent, chainHeadChanSize)
s.headSub = s.backend.SubscribeChainHeadEvent(chainHeadCh)
go s.loopBlocks(chainHeadCh)
go s.loopSender(s.initializeURLMap())
s.backend.Logger().Info("Stats daemon started")
return nil
}
// Stop implements node.Lifecycle, terminating the monitoring and reporting daemon.
func (s *Service) Stop() error {
s.headSub.Unsubscribe()
s.backend.Logger().Info("Stats daemon stopped")
return nil
}
func (s *Service) loopBlocks(chainHeadCh chan core.ChainHeadEvent) {
defer func() {
if r := recover(); r != nil {
s.backend.Logger().WithFields(log.Fields{"err": r, "stacktrace": string(debug.Stack())}).Error("Stats process crashed")
go s.loopBlocks(chainHeadCh)
}
}()
quitCh := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
s.backend.Logger().WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Error("Go-Quai Panicked")
}
}()
for {
select {
case head := <-chainHeadCh:
// Directly handle the block
go s.handleBlock(head.Block)
case <-s.headSub.Err():
close(quitCh)
return
}
}
}()
// Wait for the goroutine to signal completion or error
<-quitCh
}
// loop keeps trying to connect to the netstats server, reporting chain events
// until termination.
func (s *Service) loopSender(urlMap map[string]string) {
defer func() {
if r := recover(); r != nil {
s.backend.Logger().WithFields(log.Fields{"err": r, "stacktrace": string(debug.Stack())}).Error("Stats process crashed")
go s.loopSender(urlMap)
}
}()
// Start a goroutine that exhausts the subscriptions to avoid events piling up
var (
quitCh = make(chan struct{})
)
nodeStatsMod := 0
errTimer := time.NewTimer(0)
defer errTimer.Stop()
var authJwt = ""
// Loop reporting until termination
for {
select {
case <-quitCh:
return
case <-errTimer.C:
// If we don't have a JWT or it's expired, get a new one
isJwtExpiredResult, jwtIsExpiredErr := s.isJwtExpired(authJwt)
if authJwt == "" || isJwtExpiredResult || jwtIsExpiredErr != nil {
s.backend.Logger().Info("Trying to login to quaistats")
var err error
authJwt, err = s.login2(urlMap["login"])
if err != nil {
s.backend.Logger().WithField("err", err).Warn("Stats login failed")
errTimer.Reset(10 * time.Second)
continue
}
}
errs := make(map[string]error)
// Authenticate the client with the server
for key, url := range urlMap {
switch key {
case "login":
continue
case "nodeStats":
if errs[key] = s.reportNodeStats(url, 0, authJwt); errs[key] != nil {
s.backend.Logger().WithField("err", errs[key]).Warn("Initial stats report failed for " + key)
errTimer.Reset(0)
continue
}
case "blockTransactionStats":
if errs[key] = s.sendTransactionStats(url, authJwt); errs[key] != nil {
s.backend.Logger().WithField("err", errs[key]).Warn("Initial stats report failed for " + key)
errTimer.Reset(0)
continue
}
case "blockDetailStats":
if errs[key] = s.sendDetailStats(url, authJwt); errs[key] != nil {
s.backend.Logger().WithField("err", errs[key]).Warn("Initial stats report failed for " + key)
errTimer.Reset(0)
continue
}
case "blockAppendTime":
if errs[key] = s.sendAppendTimeStats(url, authJwt); errs[key] != nil {
s.backend.Logger().WithField("err", errs[key]).Warn("Initial stats report failed for " + key)
errTimer.Reset(0)
continue
}
}
}
// Keep sending status updates until the connection breaks
fullReport := time.NewTicker(reportInterval * time.Second)
var noErrs = true
for noErrs {
var err error
select {
case <-quitCh:
fullReport.Stop()
return
case <-fullReport.C:
nodeStatsMod ^= 1
if err = s.reportNodeStats(urlMap["nodeStats"], nodeStatsMod, authJwt); err != nil {
noErrs = false
s.backend.Logger().WithField("err", err).Warn("nodeStats full stats report failed")
}
case <-s.statsReadyCh:
if url, ok := urlMap["blockTransactionStats"]; ok {
if err := s.sendTransactionStats(url, authJwt); err != nil {
noErrs = false
errTimer.Reset(0)
s.backend.Logger().Warn("blockTransactionStats stats report failed", "err", err)
}
}
if url, ok := urlMap["blockDetailStats"]; ok {
if err := s.sendDetailStats(url, authJwt); err != nil {
noErrs = false
errTimer.Reset(0)
s.backend.Logger().Warn("blockDetailStats stats report failed", "err", err)
}
}
if url, ok := urlMap["blockAppendTime"]; ok {
if err := s.sendAppendTimeStats(url, authJwt); err != nil {
noErrs = false
errTimer.Reset(0)
s.backend.Logger().Warn("blockAppendTime stats report failed", "err", err)
}
}
}
errTimer.Reset(0)
}
fullReport.Stop()
}
}
}
func (s *Service) initializeURLMap() map[string]string {
return map[string]string{
"blockTransactionStats": fmt.Sprintf("http://%s/stats/blockTransactionStats", s.host),
"blockAppendTime": fmt.Sprintf("http://%s/stats/blockAppendTime", s.host),
"blockDetailStats": fmt.Sprintf("http://%s/stats/blockDetailStats", s.host),
"nodeStats": fmt.Sprintf("http://%s/stats/nodeStats", s.host),
"login": fmt.Sprintf("http://%s/auth/login", s.host),
}
}
func (s *Service) handleBlock(block *types.WorkObject) {
defer func() {
if r := recover(); r != nil {
s.backend.Logger().WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Fatal("Go-Quai Panicked")
}
}()
// Cache Block
s.backend.Logger().WithFields(log.Fields{
"detailsQueueSize": s.detailStatsQueue.Size(),
"appendTimeQueueSize": s.appendTimeStatsQueue.Size(),
"transactionQueueSize": s.transactionStatsQueue.Size(),
"blockNumber": block.NumberU64(s.backend.NodeCtx()),
}).Trace("Handling block")
s.cacheBlock(block)
if s.sendfullstats {
dtlStats := s.assembleBlockDetailStats(block)
if dtlStats != nil {
s.detailStatsQueue.Enqueue(dtlStats)
}
}
appStats := s.assembleBlockAppendTimeStats(block)
if appStats != nil {
s.appendTimeStatsQueue.Enqueue(appStats)
}
if block.NumberU64(s.backend.NodeCtx())%c_txBatchSize == 0 && s.sendfullstats && block.Location().Context() == common.ZONE_CTX {
txStats := s.assembleBlockTransactionStats(block)
if txStats != nil {
s.transactionStatsQueue.Enqueue(txStats)
}
}
// After handling a block and potentially adding to the queues, notify the sendStats goroutine
// that stats are ready to be sent
select {
case s.statsReadyCh <- struct{}{}:
default:
s.backend.Logger().Debug("Stats ready channel is full")
}
}
func (s *Service) reportNodeStats(url string, mod int, authJwt string) error {
if url == "" {
s.backend.Logger().Warn("node stats url is empty")
return errors.New("node stats connection is empty")
}
isRegion := strings.Contains(s.instanceDir, "region")
isPrime := strings.Contains(s.instanceDir, "prime")
if isRegion || isPrime {
s.backend.Logger().Debug("Skipping node stats for region or prime. Filtered out on backend")
return nil
}
// Don't send if dirSize < 1
// Get disk usage (as a percentage)
diskUsage, err := dirSize(s.instanceDir + "/../..")
if err != nil {
s.backend.Logger().WithField("err", err).Warn("Error calculating directory sizes")
diskUsage = c_statsErrorValue
}
diskSize, err := diskTotalSize()
if err != nil {
s.backend.Logger().WithField("err", err).Warn("Error calculating disk size")
diskUsage = c_statsErrorValue
}
diskUsagePercent := float64(c_statsErrorValue)
if diskSize > 0 {
diskUsagePercent = float64(diskUsage) / float64(diskSize)
} else {
s.backend.Logger().Warn("Error calculating disk usage percent: disk size is 0")
}
// Usage in your main function
ramUsage, err := getQuaiRAMUsage()
if err != nil {
s.backend.Logger().WithField("err", err).Warn("Error getting Quai RAM usage")
return err
}
var ramUsagePercent, ramFreePercent, ramAvailablePercent float64
if vmStat, err := mem.VirtualMemory(); err == nil {
ramUsagePercent = float64(ramUsage) / float64(vmStat.Total)
ramFreePercent = float64(vmStat.Free) / float64(vmStat.Total)
ramAvailablePercent = float64(vmStat.Available) / float64(vmStat.Total)
} else {
s.backend.Logger().WithField("err", err).Warn("Error getting RAM stats")
return err
}
// Get CPU usage
cpuUsageQuai, err := getQuaiCPUUsage()
if err != nil {
s.backend.Logger().WithField("err", err).Warn("Error getting Quai CPU usage")
return err
} else {
cpuUsageQuai /= float64(100)
}
var cpuFree float32
if cpuUsageTotal, err := cpu.Percent(0, false); err == nil {
cpuFree = 1 - float32(cpuUsageTotal[0]/float64(100))
} else {
s.backend.Logger().WithField("err", err).Warn("Error getting CPU free")
return err
}
currentHeader := s.backend.CurrentHeader()
if currentHeader == nil {
s.backend.Logger().Warn("Current header is nil")
return errors.New("current header is nil")
}
// Get current block number
currentBlockHeight := currentHeader.NumberArray()
// Get location
location := currentHeader.Location()
// Get the first non-loopback MAC address
var macAddress string
interfaces, err := net.Interfaces()
if err == nil {
for _, interf := range interfaces {
if interf.HardwareAddr != nil && len(interf.HardwareAddr.String()) > 0 && (interf.Flags&net.FlagLoopback) == 0 {
macAddress = interf.HardwareAddr.String()
break
}
}
} else {
s.backend.Logger().WithField("err", err).Warn("Error getting MAC address")
return err
}
// Hash the MAC address
var hashedMAC string
if macAddress != "" {
hash := sha256.Sum256([]byte(macAddress))
hashedMAC = hex.EncodeToString(hash[:])
}
document := map[string]interface{}{
"id": s.node,
"nodeStats": &nodeStats{
Name: s.node,
Timestamp: big.NewInt(time.Now().Unix()), // Current timestamp
RAMUsage: int64(ramUsage),
RAMUsagePercent: float32(ramUsagePercent),
RAMFreePercent: float32(ramFreePercent),
RAMAvailablePercent: float32(ramAvailablePercent),
CPUUsagePercent: float32(cpuUsageQuai),
CPUFree: float32(cpuFree),
DiskUsageValue: int64(diskUsage),
DiskUsagePercent: float32(diskUsagePercent),
CurrentBlockNumber: currentBlockHeight,
RegionLocation: location.Region(),
ZoneLocation: location.Zone(),
NodeStatsMod: mod,
HashedMAC: hashedMAC,
},
}
jsonData, err := json.Marshal(document)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to marshal node stats")
return err
}
// Create a new HTTP request
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to create new HTTP request")
return err
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+authJwt)
// Send the request using the default HTTP client
resp, err := http.DefaultClient.Do(req)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to send node stats")
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to read response body")
return err
}
s.backend.Logger().WithFields(log.Fields{
"status": resp.Status,
"body": string(body),
}).Error("Received non-OK response")
return errors.New("Received non-OK response: " + resp.Status)
}
return nil
}
func (s *Service) sendTransactionStats(url string, authJwt string) error {
if len(s.transactionStatsQueue.data) == 0 {
return nil
}
statsBatch := make([]*blockTransactionStats, 0, c_queueBatchSize)
for i := 0; i < int(c_queueBatchSize) && len(s.transactionStatsQueue.data) > 0; i++ {
stat := s.transactionStatsQueue.Dequeue()
if stat == nil {
break
}
statsBatch = append(statsBatch, stat.(*blockTransactionStats))
}
if len(statsBatch) == 0 {
return nil
}
err := s.report(url, "blockTransactionStats", statsBatch, authJwt)
if err != nil && strings.Contains(err.Error(), "Received non-OK response") {
s.backend.Logger().WithField("err", err).Warn("Failed to send transaction stats, requeuing stats")
// Re-enqueue the failed stats from end to beginning
tempSlice := make([]interface{}, len(statsBatch))
for i, item := range statsBatch {
tempSlice[len(statsBatch)-1-i] = item
}
s.transactionStatsQueue.EnqueueFrontBatch(tempSlice)
return err
} else if err != nil {
s.backend.Logger().WithField("err", err).Warn("Failed to send transaction stats")
return err
}
return nil
}
func (s *Service) sendDetailStats(url string, authJwt string) error {
if len(s.detailStatsQueue.data) == 0 {
return nil
}
statsBatch := make([]*blockDetailStats, 0, c_queueBatchSize)
for i := 0; i < int(c_queueBatchSize) && s.detailStatsQueue.Size() > 0; i++ {
stat := s.detailStatsQueue.Dequeue()
if stat == nil {
break
}
statsBatch = append(statsBatch, stat.(*blockDetailStats))
}
if len(statsBatch) == 0 {
return nil
}
err := s.report(url, "blockDetailStats", statsBatch, authJwt)
if err != nil && strings.Contains(err.Error(), "Received non-OK response") {
s.backend.Logger().WithField("err", err).Warn("Failed to send detail stats, requeuing stats")
// Re-enqueue the failed stats from end to beginning
tempSlice := make([]interface{}, len(statsBatch))
for i, item := range statsBatch {
tempSlice[len(statsBatch)-1-i] = item
}
s.detailStatsQueue.EnqueueFrontBatch(tempSlice)
return err
} else if err != nil {
s.backend.Logger().WithField("err", err).Warn("Failed to send detail stats")
return err
}
return nil
}
func (s *Service) sendAppendTimeStats(url string, authJwt string) error {
if len(s.appendTimeStatsQueue.data) == 0 {
return nil
}
statsBatch := make([]*blockAppendTime, 0, c_queueBatchSize)
for i := 0; i < int(c_queueBatchSize) && s.appendTimeStatsQueue.Size() > 0; i++ {
stat := s.appendTimeStatsQueue.Dequeue()
if stat == nil {
break
}
statsBatch = append(statsBatch, stat.(*blockAppendTime))
}
if len(statsBatch) == 0 {
return nil
}
err := s.report(url, "blockAppendTime", statsBatch, authJwt)
if err != nil && strings.Contains(err.Error(), "Received non-OK response") {
s.backend.Logger().WithField("err", err).Warn("Failed to send append time stats, requeuing stats")
// Re-enqueue the failed stats from end to beginning
tempSlice := make([]interface{}, len(statsBatch))
for i, item := range statsBatch {
tempSlice[len(statsBatch)-1-i] = item
}
s.appendTimeStatsQueue.EnqueueFrontBatch(tempSlice)
return err
} else if err != nil {
s.backend.Logger().WithField("err", err).Warn("Failed to send append time stats")
return err
}
return nil
}
func (s *Service) report(url string, dataType string, stats interface{}, authJwt string) error {
if url == "" {
s.backend.Logger().Warn(dataType + " url is empty")
return errors.New(dataType + " url is empty")
}
if stats == nil {
s.backend.Logger().Warn(dataType + " stats are nil")
return errors.New(dataType + " stats are nil")
}
s.backend.Logger().WithField("datatype", dataType).Trace("Sending stats to quaistats")
document := map[string]interface{}{
"id": s.node,
dataType: stats,
}
jsonData, err := json.Marshal(document)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to marshal " + dataType + " stats")
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to create new request for " + dataType + " stats")
return err
}
// Add headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+authJwt) // Add this line for the Authorization header
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to send " + dataType + " stats")
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to read response body")
return err
}
s.backend.Logger().WithFields(log.Fields{
"status": resp.Status,
"body": string(body),
}).Error("Received non-OK response")
return errors.New("Received non-OK response: " + resp.Status)
}
s.backend.Logger().WithField("datatype", dataType).Trace("Successfully sent stats to quaistats")
return nil
}
type cachedBlock struct {
number uint64
parentHash common.Hash
txCount float64
quaiTxCount float64
qiTxCount float64
extTxCount float64
extTxInCount float64
extTxOutCount float64
time uint64
}
// nodeInfo is the collection of meta information about a node that is displayed
// on the monitoring page.
type nodeInfo struct {
Name string `json:"name"`
Node string `json:"node"`
Port int `json:"port"`
Network string `json:"net"`
Protocol string `json:"protocol"`
API string `json:"api"`
Os string `json:"os"`
OsVer string `json:"os_v"`
Client string `json:"client"`
History bool `json:"canUpdateHistory"`
Chain string `json:"chain"`
ChainID uint64 `json:"chainId"`
}
// authMsg is the authentication infos needed to login to a monitoring server.
type authMsg struct {
ID string `json:"id"`
Info nodeInfo `json:"info"`
Secret loginSecret `json:"secret"`
}
type loginSecret struct {
Name string `json:"name"`
Password string `json:"password"`
}
type Credentials struct {
Name string `json:"name"`
Password string `json:"password"`
}
type AuthResponse struct {
Success bool `json:"success"`
Token string `json:"token"`
}
func (s *Service) login2(url string) (string, error) {
// Substitute with your actual service address and port
var secretUser string
if s.sendfullstats {
secretUser = "admin"
} else {
secretUser = s.node
}
auth := &authMsg{
ID: s.node,
Info: nodeInfo{
Name: s.node,
API: "No",
Os: runtime.GOOS,
OsVer: runtime.GOARCH,
Client: "0.1.1",
History: true,
Chain: s.backend.NodeLocation().Name(),
ChainID: s.chainID.Uint64(),
},
Secret: loginSecret{
Name: secretUser,
Password: s.pass,
},
}
authJson, err := json.Marshal(auth)
if err != nil {
return "", err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(authJson))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
s.backend.Logger().WithField("err", err).Error("Failed to read response body")
return "", err
}
var authResponse AuthResponse
err = json.Unmarshal(body, &authResponse)
if err != nil {
return "", err
}
if authResponse.Success {
return authResponse.Token, nil
}
return "", fmt.Errorf("login failed")
}
// isJwtExpired checks if the JWT token is expired
func (s *Service) isJwtExpired(authJwt string) (bool, error) {
if authJwt == "" {
return false, errors.New("token is nil")
}
parts := strings.Split(authJwt, ".")
if len(parts) != 3 {
return false, errors.New("invalid token")
}
claims := jwt.MapClaims{}
_, _, err := new(jwt.Parser).ParseUnverified(authJwt, claims)
if err != nil {
return false, err
}
if exp, ok := claims["exp"].(float64); ok {
return time.Now().Unix() >= int64(exp), nil
}
return false, errors.New("exp claim not found in token")
}
// Trusted Only
type blockTransactionStats struct {
Timestamp *big.Int `json:"timestamp"`
Tx subTps `json:"tx"`