github.com/googgoog/go-ethereum@v1.9.7/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 if info := infos.Protocols["eth"]; info != nil { 377 network = fmt.Sprintf("%d", info.(*eth.NodeInfo).Network) 378 protocol = fmt.Sprintf("eth/%d", eth.ProtocolVersions[0]) 379 } else { 380 network = fmt.Sprintf("%d", infos.Protocols["les"].(*les.NodeInfo).Network) 381 protocol = fmt.Sprintf("les/%d", les.ClientProtocolVersions[0]) 382 } 383 auth := &authMsg{ 384 ID: s.node, 385 Info: nodeInfo{ 386 Name: s.node, 387 Node: infos.Name, 388 Port: infos.Ports.Listener, 389 Network: network, 390 Protocol: protocol, 391 API: "No", 392 Os: runtime.GOOS, 393 OsVer: runtime.GOARCH, 394 Client: "0.1.1", 395 History: true, 396 }, 397 Secret: s.pass, 398 } 399 login := map[string][]interface{}{ 400 "emit": {"hello", auth}, 401 } 402 if err := conn.WriteJSON(login); err != nil { 403 return err 404 } 405 // Retrieve the remote ack or connection termination 406 var ack map[string][]string 407 if err := conn.ReadJSON(&ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" { 408 return errors.New("unauthorized") 409 } 410 return nil 411 } 412 413 // report collects all possible data to report and send it to the stats server. 414 // This should only be used on reconnects or rarely to avoid overloading the 415 // server. Use the individual methods for reporting subscribed events. 416 func (s *Service) report(conn *websocket.Conn) error { 417 if err := s.reportLatency(conn); err != nil { 418 return err 419 } 420 if err := s.reportBlock(conn, nil); err != nil { 421 return err 422 } 423 if err := s.reportPending(conn); err != nil { 424 return err 425 } 426 if err := s.reportStats(conn); err != nil { 427 return err 428 } 429 return nil 430 } 431 432 // reportLatency sends a ping request to the server, measures the RTT time and 433 // finally sends a latency update. 434 func (s *Service) reportLatency(conn *websocket.Conn) error { 435 // Send the current time to the ethstats server 436 start := time.Now() 437 438 ping := map[string][]interface{}{ 439 "emit": {"node-ping", map[string]string{ 440 "id": s.node, 441 "clientTime": start.String(), 442 }}, 443 } 444 if err := conn.WriteJSON(ping); err != nil { 445 return err 446 } 447 // Wait for the pong request to arrive back 448 select { 449 case <-s.pongCh: 450 // Pong delivered, report the latency 451 case <-time.After(5 * time.Second): 452 // Ping timeout, abort 453 return errors.New("ping timed out") 454 } 455 latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)) 456 457 // Send back the measured latency 458 log.Trace("Sending measured latency to ethstats", "latency", latency) 459 460 stats := map[string][]interface{}{ 461 "emit": {"latency", map[string]string{ 462 "id": s.node, 463 "latency": latency, 464 }}, 465 } 466 return conn.WriteJSON(stats) 467 } 468 469 // blockStats is the information to report about individual blocks. 470 type blockStats struct { 471 Number *big.Int `json:"number"` 472 Hash common.Hash `json:"hash"` 473 ParentHash common.Hash `json:"parentHash"` 474 Timestamp *big.Int `json:"timestamp"` 475 Miner common.Address `json:"miner"` 476 GasUsed uint64 `json:"gasUsed"` 477 GasLimit uint64 `json:"gasLimit"` 478 Diff string `json:"difficulty"` 479 TotalDiff string `json:"totalDifficulty"` 480 Txs []txStats `json:"transactions"` 481 TxHash common.Hash `json:"transactionsRoot"` 482 Root common.Hash `json:"stateRoot"` 483 Uncles uncleStats `json:"uncles"` 484 } 485 486 // txStats is the information to report about individual transactions. 487 type txStats struct { 488 Hash common.Hash `json:"hash"` 489 } 490 491 // uncleStats is a custom wrapper around an uncle array to force serializing 492 // empty arrays instead of returning null for them. 493 type uncleStats []*types.Header 494 495 func (s uncleStats) MarshalJSON() ([]byte, error) { 496 if uncles := ([]*types.Header)(s); len(uncles) > 0 { 497 return json.Marshal(uncles) 498 } 499 return []byte("[]"), nil 500 } 501 502 // reportBlock retrieves the current chain head and reports it to the stats server. 503 func (s *Service) reportBlock(conn *websocket.Conn, block *types.Block) error { 504 // Gather the block details from the header or block chain 505 details := s.assembleBlockStats(block) 506 507 // Assemble the block report and send it to the server 508 log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash) 509 510 stats := map[string]interface{}{ 511 "id": s.node, 512 "block": details, 513 } 514 report := map[string][]interface{}{ 515 "emit": {"block", stats}, 516 } 517 return conn.WriteJSON(report) 518 } 519 520 // assembleBlockStats retrieves any required metadata to report a single block 521 // and assembles the block stats. If block is nil, the current head is processed. 522 func (s *Service) assembleBlockStats(block *types.Block) *blockStats { 523 // Gather the block infos from the local blockchain 524 var ( 525 header *types.Header 526 td *big.Int 527 txs []txStats 528 uncles []*types.Header 529 ) 530 if s.eth != nil { 531 // Full nodes have all needed information available 532 if block == nil { 533 block = s.eth.BlockChain().CurrentBlock() 534 } 535 header = block.Header() 536 td = s.eth.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 537 538 txs = make([]txStats, len(block.Transactions())) 539 for i, tx := range block.Transactions() { 540 txs[i].Hash = tx.Hash() 541 } 542 uncles = block.Uncles() 543 } else { 544 // Light nodes would need on-demand lookups for transactions/uncles, skip 545 if block != nil { 546 header = block.Header() 547 } else { 548 header = s.les.BlockChain().CurrentHeader() 549 } 550 td = s.les.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 551 txs = []txStats{} 552 } 553 // Assemble and return the block stats 554 author, _ := s.engine.Author(header) 555 556 return &blockStats{ 557 Number: header.Number, 558 Hash: header.Hash(), 559 ParentHash: header.ParentHash, 560 Timestamp: new(big.Int).SetUint64(header.Time), 561 Miner: author, 562 GasUsed: header.GasUsed, 563 GasLimit: header.GasLimit, 564 Diff: header.Difficulty.String(), 565 TotalDiff: td.String(), 566 Txs: txs, 567 TxHash: header.TxHash, 568 Root: header.Root, 569 Uncles: uncles, 570 } 571 } 572 573 // reportHistory retrieves the most recent batch of blocks and reports it to the 574 // stats server. 575 func (s *Service) reportHistory(conn *websocket.Conn, list []uint64) error { 576 // Figure out the indexes that need reporting 577 indexes := make([]uint64, 0, historyUpdateRange) 578 if len(list) > 0 { 579 // Specific indexes requested, send them back in particular 580 indexes = append(indexes, list...) 581 } else { 582 // No indexes requested, send back the top ones 583 var head int64 584 if s.eth != nil { 585 head = s.eth.BlockChain().CurrentHeader().Number.Int64() 586 } else { 587 head = s.les.BlockChain().CurrentHeader().Number.Int64() 588 } 589 start := head - historyUpdateRange + 1 590 if start < 0 { 591 start = 0 592 } 593 for i := uint64(start); i <= uint64(head); i++ { 594 indexes = append(indexes, i) 595 } 596 } 597 // Gather the batch of blocks to report 598 history := make([]*blockStats, len(indexes)) 599 for i, number := range indexes { 600 // Retrieve the next block if it's known to us 601 var block *types.Block 602 if s.eth != nil { 603 block = s.eth.BlockChain().GetBlockByNumber(number) 604 } else { 605 if header := s.les.BlockChain().GetHeaderByNumber(number); header != nil { 606 block = types.NewBlockWithHeader(header) 607 } 608 } 609 // If we do have the block, add to the history and continue 610 if block != nil { 611 history[len(history)-1-i] = s.assembleBlockStats(block) 612 continue 613 } 614 // Ran out of blocks, cut the report short and send 615 history = history[len(history)-i:] 616 break 617 } 618 // Assemble the history report and send it to the server 619 if len(history) > 0 { 620 log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number) 621 } else { 622 log.Trace("No history to send to stats server") 623 } 624 stats := map[string]interface{}{ 625 "id": s.node, 626 "history": history, 627 } 628 report := map[string][]interface{}{ 629 "emit": {"history", stats}, 630 } 631 return conn.WriteJSON(report) 632 } 633 634 // pendStats is the information to report about pending transactions. 635 type pendStats struct { 636 Pending int `json:"pending"` 637 } 638 639 // reportPending retrieves the current number of pending transactions and reports 640 // it to the stats server. 641 func (s *Service) reportPending(conn *websocket.Conn) error { 642 // Retrieve the pending count from the local blockchain 643 var pending int 644 if s.eth != nil { 645 pending, _ = s.eth.TxPool().Stats() 646 } else { 647 pending = s.les.TxPool().Stats() 648 } 649 // Assemble the transaction stats and send it to the server 650 log.Trace("Sending pending transactions to ethstats", "count", pending) 651 652 stats := map[string]interface{}{ 653 "id": s.node, 654 "stats": &pendStats{ 655 Pending: pending, 656 }, 657 } 658 report := map[string][]interface{}{ 659 "emit": {"pending", stats}, 660 } 661 return conn.WriteJSON(report) 662 } 663 664 // nodeStats is the information to report about the local node. 665 type nodeStats struct { 666 Active bool `json:"active"` 667 Syncing bool `json:"syncing"` 668 Mining bool `json:"mining"` 669 Hashrate int `json:"hashrate"` 670 Peers int `json:"peers"` 671 GasPrice int `json:"gasPrice"` 672 Uptime int `json:"uptime"` 673 } 674 675 // reportPending retrieves various stats about the node at the networking and 676 // mining layer and reports it to the stats server. 677 func (s *Service) reportStats(conn *websocket.Conn) error { 678 // Gather the syncing and mining infos from the local miner instance 679 var ( 680 mining bool 681 hashrate int 682 syncing bool 683 gasprice int 684 ) 685 if s.eth != nil { 686 mining = s.eth.Miner().Mining() 687 hashrate = int(s.eth.Miner().HashRate()) 688 689 sync := s.eth.Downloader().Progress() 690 syncing = s.eth.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 691 692 price, _ := s.eth.APIBackend.SuggestPrice(context.Background()) 693 gasprice = int(price.Uint64()) 694 } else { 695 sync := s.les.Downloader().Progress() 696 syncing = s.les.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 697 } 698 // Assemble the node stats and send it to the server 699 log.Trace("Sending node details to ethstats") 700 701 stats := map[string]interface{}{ 702 "id": s.node, 703 "stats": &nodeStats{ 704 Active: true, 705 Mining: mining, 706 Hashrate: hashrate, 707 Peers: s.server.PeerCount(), 708 GasPrice: gasprice, 709 Syncing: syncing, 710 Uptime: 100, 711 }, 712 } 713 report := map[string][]interface{}{ 714 "emit": {"stats", stats}, 715 } 716 return conn.WriteJSON(report) 717 }