github.com/Consensys/quorum@v21.1.0+incompatible/ethstats/ethstats.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package ethstats implements the network stats reporting service. 18 package ethstats 19 20 import ( 21 "context" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 "net/http" 27 "regexp" 28 "runtime" 29 "strconv" 30 "strings" 31 "time" 32 33 "github.com/ethereum/go-ethereum/common" 34 "github.com/ethereum/go-ethereum/common/mclock" 35 "github.com/ethereum/go-ethereum/consensus" 36 "github.com/ethereum/go-ethereum/core" 37 "github.com/ethereum/go-ethereum/core/types" 38 "github.com/ethereum/go-ethereum/eth" 39 "github.com/ethereum/go-ethereum/event" 40 "github.com/ethereum/go-ethereum/les" 41 "github.com/ethereum/go-ethereum/log" 42 "github.com/ethereum/go-ethereum/p2p" 43 "github.com/ethereum/go-ethereum/rpc" 44 "github.com/gorilla/websocket" 45 ) 46 47 const ( 48 // historyUpdateRange is the number of blocks a node should report upon login or 49 // history request. 50 historyUpdateRange = 50 51 52 // txChanSize is the size of channel listening to NewTxsEvent. 53 // The number is referenced from the size of tx pool. 54 txChanSize = 4096 55 // chainHeadChanSize is the size of channel listening to ChainHeadEvent. 56 chainHeadChanSize = 10 57 ) 58 59 type txPool interface { 60 // SubscribeNewTxsEvent should return an event subscription of 61 // NewTxsEvent and send events to the given channel. 62 SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription 63 } 64 65 type blockChain interface { 66 SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription 67 } 68 69 // Service implements an Ethereum netstats reporting daemon that pushes local 70 // chain statistics up to a monitoring server. 71 type Service struct { 72 server *p2p.Server // Peer-to-peer server to retrieve networking infos 73 eth *eth.Ethereum // Full Ethereum service if monitoring a full node 74 les *les.LightEthereum // Light Ethereum service if monitoring a light node 75 engine consensus.Engine // Consensus engine to retrieve variadic block fields 76 77 node string // Name of the node to display on the monitoring page 78 pass string // Password to authorize access to the monitoring page 79 host string // Remote address of the monitoring service 80 81 pongCh chan struct{} // Pong notifications are fed into this channel 82 histCh chan []uint64 // History request block numbers are fed into this channel 83 } 84 85 // New returns a monitoring service ready for stats reporting. 86 func New(url string, ethServ *eth.Ethereum, lesServ *les.LightEthereum) (*Service, error) { 87 // Parse the netstats connection url 88 re := regexp.MustCompile("([^:@]*)(:([^@]*))?@(.+)") 89 parts := re.FindStringSubmatch(url) 90 if len(parts) != 5 { 91 return nil, fmt.Errorf("invalid netstats url: \"%s\", should be nodename:secret@host:port", url) 92 } 93 // Assemble and return the stats service 94 var engine consensus.Engine 95 if ethServ != nil { 96 engine = ethServ.Engine() 97 } else { 98 engine = lesServ.Engine() 99 } 100 return &Service{ 101 eth: ethServ, 102 les: lesServ, 103 engine: engine, 104 node: parts[1], 105 pass: parts[3], 106 host: parts[4], 107 pongCh: make(chan struct{}), 108 histCh: make(chan []uint64, 1), 109 }, nil 110 } 111 112 // Protocols implements node.Service, returning the P2P network protocols used 113 // by the stats service (nil as it doesn't use the devp2p overlay network). 114 func (s *Service) Protocols() []p2p.Protocol { return nil } 115 116 // APIs implements node.Service, returning the RPC API endpoints provided by the 117 // stats service (nil as it doesn't provide any user callable APIs). 118 func (s *Service) APIs() []rpc.API { return nil } 119 120 // Start implements node.Service, starting up the monitoring and reporting daemon. 121 func (s *Service) Start(server *p2p.Server) error { 122 s.server = server 123 go s.loop() 124 125 log.Info("Stats daemon started") 126 return nil 127 } 128 129 // Stop implements node.Service, terminating the monitoring and reporting daemon. 130 func (s *Service) Stop() error { 131 log.Info("Stats daemon stopped") 132 return nil 133 } 134 135 // loop keeps trying to connect to the netstats server, reporting chain events 136 // until termination. 137 func (s *Service) loop() { 138 // Subscribe to chain events to execute updates on 139 var blockchain blockChain 140 var txpool txPool 141 if s.eth != nil { 142 blockchain = s.eth.BlockChain() 143 txpool = s.eth.TxPool() 144 } else { 145 blockchain = s.les.BlockChain() 146 txpool = s.les.TxPool() 147 } 148 149 chainHeadCh := make(chan core.ChainHeadEvent, chainHeadChanSize) 150 headSub := blockchain.SubscribeChainHeadEvent(chainHeadCh) 151 defer headSub.Unsubscribe() 152 153 txEventCh := make(chan core.NewTxsEvent, txChanSize) 154 txSub := txpool.SubscribeNewTxsEvent(txEventCh) 155 defer txSub.Unsubscribe() 156 157 // Start a goroutine that exhausts the subsciptions to avoid events piling up 158 var ( 159 quitCh = make(chan struct{}) 160 headCh = make(chan *types.Block, 1) 161 txCh = make(chan struct{}, 1) 162 ) 163 go func() { 164 var lastTx mclock.AbsTime 165 166 HandleLoop: 167 for { 168 select { 169 // Notify of chain head events, but drop if too frequent 170 case head := <-chainHeadCh: 171 select { 172 case headCh <- head.Block: 173 default: 174 } 175 176 // Notify of new transaction events, but drop if too frequent 177 case <-txEventCh: 178 if time.Duration(mclock.Now()-lastTx) < time.Second { 179 continue 180 } 181 lastTx = mclock.Now() 182 183 select { 184 case txCh <- struct{}{}: 185 default: 186 } 187 188 // node stopped 189 case <-txSub.Err(): 190 break HandleLoop 191 case <-headSub.Err(): 192 break HandleLoop 193 } 194 } 195 close(quitCh) 196 }() 197 // Loop reporting until termination 198 for { 199 // Resolve the URL, defaulting to TLS, but falling back to none too 200 path := fmt.Sprintf("%s/api", s.host) 201 urls := []string{path} 202 203 // url.Parse and url.IsAbs is unsuitable (https://github.com/golang/go/issues/19779) 204 if !strings.Contains(path, "://") { 205 urls = []string{"wss://" + path, "ws://" + path} 206 } 207 // Establish a websocket connection to the server on any supported URL 208 var ( 209 conn *websocket.Conn 210 err error 211 ) 212 dialer := websocket.Dialer{HandshakeTimeout: 5 * time.Second} 213 header := make(http.Header) 214 header.Set("origin", "http://localhost") 215 for _, url := range urls { 216 conn, _, err = dialer.Dial(url, header) 217 if err == nil { 218 break 219 } 220 } 221 if err != nil { 222 log.Warn("Stats server unreachable", "err", err) 223 time.Sleep(10 * time.Second) 224 continue 225 } 226 // Authenticate the client with the server 227 if err = s.login(conn); err != nil { 228 log.Warn("Stats login failed", "err", err) 229 conn.Close() 230 time.Sleep(10 * time.Second) 231 continue 232 } 233 go s.readLoop(conn) 234 235 // Send the initial stats so our node looks decent from the get go 236 if err = s.report(conn); err != nil { 237 log.Warn("Initial stats report failed", "err", err) 238 conn.Close() 239 continue 240 } 241 // Keep sending status updates until the connection breaks 242 fullReport := time.NewTicker(15 * time.Second) 243 244 for err == nil { 245 select { 246 case <-quitCh: 247 conn.Close() 248 return 249 250 case <-fullReport.C: 251 if err = s.report(conn); err != nil { 252 log.Warn("Full stats report failed", "err", err) 253 } 254 case list := <-s.histCh: 255 if err = s.reportHistory(conn, list); err != nil { 256 log.Warn("Requested history report failed", "err", err) 257 } 258 case head := <-headCh: 259 if err = s.reportBlock(conn, head); err != nil { 260 log.Warn("Block stats report failed", "err", err) 261 } 262 if err = s.reportPending(conn); err != nil { 263 log.Warn("Post-block transaction stats report failed", "err", err) 264 } 265 case <-txCh: 266 if err = s.reportPending(conn); err != nil { 267 log.Warn("Transaction stats report failed", "err", err) 268 } 269 } 270 } 271 // Make sure the connection is closed 272 conn.Close() 273 } 274 } 275 276 // readLoop loops as long as the connection is alive and retrieves data packets 277 // from the network socket. If any of them match an active request, it forwards 278 // it, if they themselves are requests it initiates a reply, and lastly it drops 279 // unknown packets. 280 func (s *Service) readLoop(conn *websocket.Conn) { 281 // If the read loop exists, close the connection 282 defer conn.Close() 283 284 for { 285 // Retrieve the next generic network packet and bail out on error 286 var msg map[string][]interface{} 287 if err := conn.ReadJSON(&msg); err != nil { 288 log.Warn("Failed to decode stats server message", "err", err) 289 return 290 } 291 log.Trace("Received message from stats server", "msg", msg) 292 if len(msg["emit"]) == 0 { 293 log.Warn("Stats server sent non-broadcast", "msg", msg) 294 return 295 } 296 command, ok := msg["emit"][0].(string) 297 if !ok { 298 log.Warn("Invalid stats server message type", "type", msg["emit"][0]) 299 return 300 } 301 // If the message is a ping reply, deliver (someone must be listening!) 302 if len(msg["emit"]) == 2 && command == "node-pong" { 303 select { 304 case s.pongCh <- struct{}{}: 305 // Pong delivered, continue listening 306 continue 307 default: 308 // Ping routine dead, abort 309 log.Warn("Stats server pinger seems to have died") 310 return 311 } 312 } 313 // If the message is a history request, forward to the event processor 314 if len(msg["emit"]) == 2 && command == "history" { 315 // Make sure the request is valid and doesn't crash us 316 request, ok := msg["emit"][1].(map[string]interface{}) 317 if !ok { 318 log.Warn("Invalid stats history request", "msg", msg["emit"][1]) 319 s.histCh <- nil 320 continue // Ethstats sometime sends invalid history requests, ignore those 321 } 322 list, ok := request["list"].([]interface{}) 323 if !ok { 324 log.Warn("Invalid stats history block list", "list", request["list"]) 325 return 326 } 327 // Convert the block number list to an integer list 328 numbers := make([]uint64, len(list)) 329 for i, num := range list { 330 n, ok := num.(float64) 331 if !ok { 332 log.Warn("Invalid stats history block number", "number", num) 333 return 334 } 335 numbers[i] = uint64(n) 336 } 337 select { 338 case s.histCh <- numbers: 339 continue 340 default: 341 } 342 } 343 // Report anything else and continue 344 log.Info("Unknown stats message", "msg", msg) 345 } 346 } 347 348 // nodeInfo is the collection of metainformation about a node that is displayed 349 // on the monitoring page. 350 type nodeInfo struct { 351 Name string `json:"name"` 352 Node string `json:"node"` 353 Port int `json:"port"` 354 Network string `json:"net"` 355 Protocol string `json:"protocol"` 356 API string `json:"api"` 357 Os string `json:"os"` 358 OsVer string `json:"os_v"` 359 Client string `json:"client"` 360 History bool `json:"canUpdateHistory"` 361 } 362 363 // authMsg is the authentication infos needed to login to a monitoring server. 364 type authMsg struct { 365 ID string `json:"id"` 366 Info nodeInfo `json:"info"` 367 Secret string `json:"secret"` 368 } 369 370 // login tries to authorize the client at the remote server. 371 func (s *Service) login(conn *websocket.Conn) error { 372 // Construct and send the login authentication 373 infos := s.server.NodeInfo() 374 375 var network, protocol string 376 //must pass engine protocol name for quorum 377 p := s.engine.Protocol() 378 if info := infos.Protocols[p.Name]; info != nil { 379 network = fmt.Sprintf("%d", info.(*eth.NodeInfo).Network) 380 protocol = fmt.Sprintf("eth/%d", eth.ProtocolVersions[0]) 381 } else { 382 network = fmt.Sprintf("%d", infos.Protocols["les"].(*les.NodeInfo).Network) 383 protocol = fmt.Sprintf("les/%d", les.ClientProtocolVersions[0]) 384 } 385 auth := &authMsg{ 386 ID: s.node, 387 Info: nodeInfo{ 388 Name: s.node, 389 Node: infos.Name, 390 Port: infos.Ports.Listener, 391 Network: network, 392 Protocol: protocol, 393 API: "No", 394 Os: runtime.GOOS, 395 OsVer: runtime.GOARCH, 396 Client: "0.1.1", 397 History: true, 398 }, 399 Secret: s.pass, 400 } 401 login := map[string][]interface{}{ 402 "emit": {"hello", auth}, 403 } 404 if err := conn.WriteJSON(login); err != nil { 405 return err 406 } 407 // Retrieve the remote ack or connection termination 408 var ack map[string][]string 409 if err := conn.ReadJSON(&ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" { 410 return errors.New("unauthorized") 411 } 412 return nil 413 } 414 415 // report collects all possible data to report and send it to the stats server. 416 // This should only be used on reconnects or rarely to avoid overloading the 417 // server. Use the individual methods for reporting subscribed events. 418 func (s *Service) report(conn *websocket.Conn) error { 419 if err := s.reportLatency(conn); err != nil { 420 return err 421 } 422 if err := s.reportBlock(conn, nil); err != nil { 423 return err 424 } 425 if err := s.reportPending(conn); err != nil { 426 return err 427 } 428 if err := s.reportStats(conn); err != nil { 429 return err 430 } 431 return nil 432 } 433 434 // reportLatency sends a ping request to the server, measures the RTT time and 435 // finally sends a latency update. 436 func (s *Service) reportLatency(conn *websocket.Conn) error { 437 // Send the current time to the ethstats server 438 start := time.Now() 439 440 ping := map[string][]interface{}{ 441 "emit": {"node-ping", map[string]string{ 442 "id": s.node, 443 "clientTime": start.String(), 444 }}, 445 } 446 if err := conn.WriteJSON(ping); err != nil { 447 return err 448 } 449 // Wait for the pong request to arrive back 450 select { 451 case <-s.pongCh: 452 // Pong delivered, report the latency 453 case <-time.After(5 * time.Second): 454 // Ping timeout, abort 455 return errors.New("ping timed out") 456 } 457 latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)) 458 459 // Send back the measured latency 460 log.Trace("Sending measured latency to ethstats", "latency", latency) 461 462 stats := map[string][]interface{}{ 463 "emit": {"latency", map[string]string{ 464 "id": s.node, 465 "latency": latency, 466 }}, 467 } 468 return conn.WriteJSON(stats) 469 } 470 471 // blockStats is the information to report about individual blocks. 472 type blockStats struct { 473 Number *big.Int `json:"number"` 474 Hash common.Hash `json:"hash"` 475 ParentHash common.Hash `json:"parentHash"` 476 Timestamp *big.Int `json:"timestamp"` 477 Miner common.Address `json:"miner"` 478 GasUsed uint64 `json:"gasUsed"` 479 GasLimit uint64 `json:"gasLimit"` 480 Diff string `json:"difficulty"` 481 TotalDiff string `json:"totalDifficulty"` 482 Txs []txStats `json:"transactions"` 483 TxHash common.Hash `json:"transactionsRoot"` 484 Root common.Hash `json:"stateRoot"` 485 Uncles uncleStats `json:"uncles"` 486 } 487 488 // txStats is the information to report about individual transactions. 489 type txStats struct { 490 Hash common.Hash `json:"hash"` 491 } 492 493 // uncleStats is a custom wrapper around an uncle array to force serializing 494 // empty arrays instead of returning null for them. 495 type uncleStats []*types.Header 496 497 func (s uncleStats) MarshalJSON() ([]byte, error) { 498 if uncles := ([]*types.Header)(s); len(uncles) > 0 { 499 return json.Marshal(uncles) 500 } 501 return []byte("[]"), nil 502 } 503 504 // reportBlock retrieves the current chain head and reports it to the stats server. 505 func (s *Service) reportBlock(conn *websocket.Conn, block *types.Block) error { 506 // Gather the block details from the header or block chain 507 details := s.assembleBlockStats(block) 508 509 // Assemble the block report and send it to the server 510 log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash) 511 512 stats := map[string]interface{}{ 513 "id": s.node, 514 "block": details, 515 } 516 report := map[string][]interface{}{ 517 "emit": {"block", stats}, 518 } 519 return conn.WriteJSON(report) 520 } 521 522 // assembleBlockStats retrieves any required metadata to report a single block 523 // and assembles the block stats. If block is nil, the current head is processed. 524 func (s *Service) assembleBlockStats(block *types.Block) *blockStats { 525 // Gather the block infos from the local blockchain 526 var ( 527 header *types.Header 528 td *big.Int 529 txs []txStats 530 uncles []*types.Header 531 ) 532 if s.eth != nil { 533 // Full nodes have all needed information available 534 if block == nil { 535 block = s.eth.BlockChain().CurrentBlock() 536 } 537 header = block.Header() 538 td = s.eth.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 539 540 txs = make([]txStats, len(block.Transactions())) 541 for i, tx := range block.Transactions() { 542 txs[i].Hash = tx.Hash() 543 } 544 uncles = block.Uncles() 545 } else { 546 // Light nodes would need on-demand lookups for transactions/uncles, skip 547 if block != nil { 548 header = block.Header() 549 } else { 550 header = s.les.BlockChain().CurrentHeader() 551 } 552 td = s.les.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 553 txs = []txStats{} 554 } 555 // Assemble and return the block stats 556 author, _ := s.engine.Author(header) 557 558 return &blockStats{ 559 Number: header.Number, 560 Hash: header.Hash(), 561 ParentHash: header.ParentHash, 562 Timestamp: new(big.Int).SetUint64(header.Time), 563 Miner: author, 564 GasUsed: header.GasUsed, 565 GasLimit: header.GasLimit, 566 Diff: header.Difficulty.String(), 567 TotalDiff: td.String(), 568 Txs: txs, 569 TxHash: header.TxHash, 570 Root: header.Root, 571 Uncles: uncles, 572 } 573 } 574 575 // reportHistory retrieves the most recent batch of blocks and reports it to the 576 // stats server. 577 func (s *Service) reportHistory(conn *websocket.Conn, list []uint64) error { 578 // Figure out the indexes that need reporting 579 indexes := make([]uint64, 0, historyUpdateRange) 580 if len(list) > 0 { 581 // Specific indexes requested, send them back in particular 582 indexes = append(indexes, list...) 583 } else { 584 // No indexes requested, send back the top ones 585 var head int64 586 if s.eth != nil { 587 head = s.eth.BlockChain().CurrentHeader().Number.Int64() 588 } else { 589 head = s.les.BlockChain().CurrentHeader().Number.Int64() 590 } 591 start := head - historyUpdateRange + 1 592 if start < 0 { 593 start = 0 594 } 595 for i := uint64(start); i <= uint64(head); i++ { 596 indexes = append(indexes, i) 597 } 598 } 599 // Gather the batch of blocks to report 600 history := make([]*blockStats, len(indexes)) 601 for i, number := range indexes { 602 // Retrieve the next block if it's known to us 603 var block *types.Block 604 if s.eth != nil { 605 block = s.eth.BlockChain().GetBlockByNumber(number) 606 } else { 607 if header := s.les.BlockChain().GetHeaderByNumber(number); header != nil { 608 block = types.NewBlockWithHeader(header) 609 } 610 } 611 // If we do have the block, add to the history and continue 612 if block != nil { 613 history[len(history)-1-i] = s.assembleBlockStats(block) 614 continue 615 } 616 // Ran out of blocks, cut the report short and send 617 history = history[len(history)-i:] 618 break 619 } 620 // Assemble the history report and send it to the server 621 if len(history) > 0 { 622 log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number) 623 } else { 624 log.Trace("No history to send to stats server") 625 } 626 stats := map[string]interface{}{ 627 "id": s.node, 628 "history": history, 629 } 630 report := map[string][]interface{}{ 631 "emit": {"history", stats}, 632 } 633 return conn.WriteJSON(report) 634 } 635 636 // pendStats is the information to report about pending transactions. 637 type pendStats struct { 638 Pending int `json:"pending"` 639 } 640 641 // reportPending retrieves the current number of pending transactions and reports 642 // it to the stats server. 643 func (s *Service) reportPending(conn *websocket.Conn) error { 644 // Retrieve the pending count from the local blockchain 645 var pending int 646 if s.eth != nil { 647 pending, _ = s.eth.TxPool().Stats() 648 } else { 649 pending = s.les.TxPool().Stats() 650 } 651 // Assemble the transaction stats and send it to the server 652 log.Trace("Sending pending transactions to ethstats", "count", pending) 653 654 stats := map[string]interface{}{ 655 "id": s.node, 656 "stats": &pendStats{ 657 Pending: pending, 658 }, 659 } 660 report := map[string][]interface{}{ 661 "emit": {"pending", stats}, 662 } 663 return conn.WriteJSON(report) 664 } 665 666 // nodeStats is the information to report about the local node. 667 type nodeStats struct { 668 Active bool `json:"active"` 669 Syncing bool `json:"syncing"` 670 Mining bool `json:"mining"` 671 Hashrate int `json:"hashrate"` 672 Peers int `json:"peers"` 673 GasPrice int `json:"gasPrice"` 674 Uptime int `json:"uptime"` 675 } 676 677 // reportPending retrieves various stats about the node at the networking and 678 // mining layer and reports it to the stats server. 679 func (s *Service) reportStats(conn *websocket.Conn) error { 680 // Gather the syncing and mining infos from the local miner instance 681 var ( 682 mining bool 683 hashrate int 684 syncing bool 685 gasprice int 686 ) 687 if s.eth != nil { 688 mining = s.eth.Miner().Mining() 689 hashrate = int(s.eth.Miner().HashRate()) 690 691 sync := s.eth.Downloader().Progress() 692 syncing = s.eth.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 693 694 price, _ := s.eth.APIBackend.SuggestPrice(context.Background()) 695 gasprice = int(price.Uint64()) 696 } else { 697 sync := s.les.Downloader().Progress() 698 syncing = s.les.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 699 } 700 // Assemble the node stats and send it to the server 701 log.Trace("Sending node details to ethstats") 702 703 stats := map[string]interface{}{ 704 "id": s.node, 705 "stats": &nodeStats{ 706 Active: true, 707 Mining: mining, 708 Hashrate: hashrate, 709 Peers: s.server.PeerCount(), 710 GasPrice: gasprice, 711 Syncing: syncing, 712 Uptime: 100, 713 }, 714 } 715 report := map[string][]interface{}{ 716 "emit": {"stats", stats}, 717 } 718 return conn.WriteJSON(report) 719 }