github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/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" 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 "golang.org/x/net/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 TxPreEvent. 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 // SubscribeTxPreEvent should return an event subscription of 61 // TxPreEvent and send events to the given channel. 62 SubscribeTxPreEvent(chan<- core.TxPreEvent) 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.TxPreEvent, txChanSize) 154 txSub := txpool.SubscribeTxPreEvent(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 return 197 }() 198 // Loop reporting until termination 199 for { 200 // Resolve the URL, defaulting to TLS, but falling back to none too 201 path := fmt.Sprintf("%s/api", s.host) 202 urls := []string{path} 203 204 if !strings.Contains(path, "://") { // url.Parse and url.IsAbs is unsuitable (https://github.com/golang/go/issues/19779) 205 urls = []string{"wss://" + path, "ws://" + path} 206 } 207 // Establish a websocket connection to the server on any supported URL 208 var ( 209 conf *websocket.Config 210 conn *websocket.Conn 211 err error 212 ) 213 for _, url := range urls { 214 if conf, err = websocket.NewConfig(url, "http://localhost/"); err != nil { 215 continue 216 } 217 conf.Dialer = &net.Dialer{Timeout: 5 * time.Second} 218 if conn, err = websocket.DialConfig(conf); err == nil { 219 break 220 } 221 } 222 if err != nil { 223 log.Warn("Stats server unreachable", "err", err) 224 time.Sleep(10 * time.Second) 225 continue 226 } 227 // Authenticate the client with the server 228 if err = s.login(conn); err != nil { 229 log.Warn("Stats login failed", "err", err) 230 conn.Close() 231 time.Sleep(10 * time.Second) 232 continue 233 } 234 go s.readLoop(conn) 235 236 // Send the initial stats so our node looks decent from the get go 237 if err = s.report(conn); err != nil { 238 log.Warn("Initial stats report failed", "err", err) 239 conn.Close() 240 continue 241 } 242 // Keep sending status updates until the connection breaks 243 fullReport := time.NewTicker(15 * time.Second) 244 245 for err == nil { 246 select { 247 case <-quitCh: 248 conn.Close() 249 return 250 251 case <-fullReport.C: 252 if err = s.report(conn); err != nil { 253 log.Warn("Full stats report failed", "err", err) 254 } 255 case list := <-s.histCh: 256 if err = s.reportHistory(conn, list); err != nil { 257 log.Warn("Requested history report failed", "err", err) 258 } 259 case head := <-headCh: 260 if err = s.reportBlock(conn, head); err != nil { 261 log.Warn("Block stats report failed", "err", err) 262 } 263 if err = s.reportPending(conn); err != nil { 264 log.Warn("Post-block transaction stats report failed", "err", err) 265 } 266 case <-txCh: 267 if err = s.reportPending(conn); err != nil { 268 log.Warn("Transaction stats report failed", "err", err) 269 } 270 } 271 } 272 // Make sure the connection is closed 273 conn.Close() 274 } 275 } 276 277 // readLoop loops as long as the connection is alive and retrieves data packets 278 // from the network socket. If any of them match an active request, it forwards 279 // it, if they themselves are requests it initiates a reply, and lastly it drops 280 // unknown packets. 281 func (s *Service) readLoop(conn *websocket.Conn) { 282 // If the read loop exists, close the connection 283 defer conn.Close() 284 285 for { 286 // Retrieve the next generic network packet and bail out on error 287 var msg map[string][]interface{} 288 if err := websocket.JSON.Receive(conn, &msg); err != nil { 289 log.Warn("Failed to decode stats server message", "err", err) 290 return 291 } 292 log.Trace("Received message from stats server", "msg", msg) 293 if len(msg["emit"]) == 0 { 294 log.Warn("Stats server sent non-broadcast", "msg", msg) 295 return 296 } 297 command, ok := msg["emit"][0].(string) 298 if !ok { 299 log.Warn("Invalid stats server message type", "type", msg["emit"][0]) 300 return 301 } 302 // If the message is a ping reply, deliver (someone must be listening!) 303 if len(msg["emit"]) == 2 && command == "node-pong" { 304 select { 305 case s.pongCh <- struct{}{}: 306 // Pong delivered, continue listening 307 continue 308 default: 309 // Ping routine dead, abort 310 log.Warn("Stats server pinger seems to have died") 311 return 312 } 313 } 314 // If the message is a history request, forward to the event processor 315 if len(msg["emit"]) == 2 && command == "history" { 316 // Make sure the request is valid and doesn't crash us 317 request, ok := msg["emit"][1].(map[string]interface{}) 318 if !ok { 319 log.Warn("Invalid stats history request", "msg", msg["emit"][1]) 320 s.histCh <- nil 321 continue // Ethstats sometime sends invalid history requests, ignore those 322 } 323 list, ok := request["list"].([]interface{}) 324 if !ok { 325 log.Warn("Invalid stats history block list", "list", request["list"]) 326 return 327 } 328 // Convert the block number list to an integer list 329 numbers := make([]uint64, len(list)) 330 for i, num := range list { 331 n, ok := num.(float64) 332 if !ok { 333 log.Warn("Invalid stats history block number", "number", num) 334 return 335 } 336 numbers[i] = uint64(n) 337 } 338 select { 339 case s.histCh <- numbers: 340 continue 341 default: 342 } 343 } 344 // Report anything else and continue 345 log.Info("Unknown stats message", "msg", msg) 346 } 347 } 348 349 // nodeInfo is the collection of metainformation about a node that is displayed 350 // on the monitoring page. 351 type nodeInfo struct { 352 Name string `json:"name"` 353 Node string `json:"node"` 354 Port int `json:"port"` 355 Network string `json:"net"` 356 Protocol string `json:"protocol"` 357 API string `json:"api"` 358 Os string `json:"os"` 359 OsVer string `json:"os_v"` 360 Client string `json:"client"` 361 History bool `json:"canUpdateHistory"` 362 } 363 364 // authMsg is the authentication infos needed to login to a monitoring server. 365 type authMsg struct { 366 Id string `json:"id"` 367 Info nodeInfo `json:"info"` 368 Secret string `json:"secret"` 369 } 370 371 // login tries to authorize the client at the remote server. 372 func (s *Service) login(conn *websocket.Conn) error { 373 // Construct and send the login authentication 374 infos := s.server.NodeInfo() 375 376 var network, protocol string 377 if info := infos.Protocols["eth"]; info != nil { 378 network = fmt.Sprintf("%d", info.(*eth.EthNodeInfo).Network) 379 protocol = fmt.Sprintf("eth/%d", eth.ProtocolVersions[0]) 380 } else { 381 network = fmt.Sprintf("%d", infos.Protocols["les"].(*eth.EthNodeInfo).Network) 382 protocol = fmt.Sprintf("les/%d", les.ClientProtocolVersions[0]) 383 } 384 auth := &authMsg{ 385 Id: s.node, 386 Info: nodeInfo{ 387 Name: s.node, 388 Node: infos.Name, 389 Port: infos.Ports.Listener, 390 Network: network, 391 Protocol: protocol, 392 API: "No", 393 Os: runtime.GOOS, 394 OsVer: runtime.GOARCH, 395 Client: "0.1.1", 396 History: true, 397 }, 398 Secret: s.pass, 399 } 400 login := map[string][]interface{}{ 401 "emit": {"hello", auth}, 402 } 403 if err := websocket.JSON.Send(conn, login); err != nil { 404 return err 405 } 406 // Retrieve the remote ack or connection termination 407 var ack map[string][]string 408 if err := websocket.JSON.Receive(conn, &ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" { 409 return errors.New("unauthorized") 410 } 411 return nil 412 } 413 414 // report collects all possible data to report and send it to the stats server. 415 // This should only be used on reconnects or rarely to avoid overloading the 416 // server. Use the individual methods for reporting subscribed events. 417 func (s *Service) report(conn *websocket.Conn) error { 418 if err := s.reportLatency(conn); err != nil { 419 return err 420 } 421 if err := s.reportBlock(conn, nil); err != nil { 422 return err 423 } 424 if err := s.reportPending(conn); err != nil { 425 return err 426 } 427 if err := s.reportStats(conn); err != nil { 428 return err 429 } 430 return nil 431 } 432 433 // reportLatency sends a ping request to the server, measures the RTT time and 434 // finally sends a latency update. 435 func (s *Service) reportLatency(conn *websocket.Conn) error { 436 // Send the current time to the ethstats server 437 start := time.Now() 438 439 ping := map[string][]interface{}{ 440 "emit": {"node-ping", map[string]string{ 441 "id": s.node, 442 "clientTime": start.String(), 443 }}, 444 } 445 if err := websocket.JSON.Send(conn, ping); err != nil { 446 return err 447 } 448 // Wait for the pong request to arrive back 449 select { 450 case <-s.pongCh: 451 // Pong delivered, report the latency 452 case <-time.After(5 * time.Second): 453 // Ping timeout, abort 454 return errors.New("ping timed out") 455 } 456 latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)) 457 458 // Send back the measured latency 459 log.Trace("Sending measured latency to ethstats", "latency", latency) 460 461 stats := map[string][]interface{}{ 462 "emit": {"latency", map[string]string{ 463 "id": s.node, 464 "latency": latency, 465 }}, 466 } 467 return websocket.JSON.Send(conn, stats) 468 } 469 470 // blockStats is the information to report about individual blocks. 471 type blockStats struct { 472 Number *big.Int `json:"number"` 473 Hash common.Hash `json:"hash"` 474 ParentHash common.Hash `json:"parentHash"` 475 Timestamp *big.Int `json:"timestamp"` 476 Miner common.Address `json:"miner"` 477 GasUsed *big.Int `json:"gasUsed"` 478 GasLimit *big.Int `json:"gasLimit"` 479 Diff string `json:"difficulty"` 480 TotalDiff string `json:"totalDifficulty"` 481 Txs []txStats `json:"transactions"` 482 TxHash common.Hash `json:"transactionsRoot"` 483 Root common.Hash `json:"stateRoot"` 484 Uncles uncleStats `json:"uncles"` 485 } 486 487 // txStats is the information to report about individual transactions. 488 type txStats struct { 489 Hash common.Hash `json:"hash"` 490 } 491 492 // uncleStats is a custom wrapper around an uncle array to force serializing 493 // empty arrays instead of returning null for them. 494 type uncleStats []*types.Header 495 496 func (s uncleStats) MarshalJSON() ([]byte, error) { 497 if uncles := ([]*types.Header)(s); len(uncles) > 0 { 498 return json.Marshal(uncles) 499 } 500 return []byte("[]"), nil 501 } 502 503 // reportBlock retrieves the current chain head and repors it to the stats server. 504 func (s *Service) reportBlock(conn *websocket.Conn, block *types.Block) error { 505 // Gather the block details from the header or block chain 506 details := s.assembleBlockStats(block) 507 508 // Assemble the block report and send it to the server 509 log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash) 510 511 stats := map[string]interface{}{ 512 "id": s.node, 513 "block": details, 514 } 515 report := map[string][]interface{}{ 516 "emit": {"block", stats}, 517 } 518 return websocket.JSON.Send(conn, report) 519 } 520 521 // assembleBlockStats retrieves any required metadata to report a single block 522 // and assembles the block stats. If block is nil, the current head is processed. 523 func (s *Service) assembleBlockStats(block *types.Block) *blockStats { 524 // Gather the block infos from the local blockchain 525 var ( 526 header *types.Header 527 td *big.Int 528 txs []txStats 529 uncles []*types.Header 530 ) 531 if s.eth != nil { 532 // Full nodes have all needed information available 533 if block == nil { 534 block = s.eth.BlockChain().CurrentBlock() 535 } 536 header = block.Header() 537 td = s.eth.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 538 539 txs = make([]txStats, len(block.Transactions())) 540 for i, tx := range block.Transactions() { 541 txs[i].Hash = tx.Hash() 542 } 543 uncles = block.Uncles() 544 } else { 545 // Light nodes would need on-demand lookups for transactions/uncles, skip 546 if block != nil { 547 header = block.Header() 548 } else { 549 header = s.les.BlockChain().CurrentHeader() 550 } 551 td = s.les.BlockChain().GetTd(header.Hash(), header.Number.Uint64()) 552 txs = []txStats{} 553 } 554 // Assemble and return the block stats 555 author, _ := s.engine.Author(header) 556 557 return &blockStats{ 558 Number: header.Number, 559 Hash: header.Hash(), 560 ParentHash: header.ParentHash, 561 Timestamp: header.Time, 562 Miner: author, 563 GasUsed: new(big.Int).Set(header.GasUsed), 564 GasLimit: new(big.Int).Set(header.GasLimit), 565 Diff: header.Difficulty.String(), 566 TotalDiff: td.String(), 567 Txs: txs, 568 TxHash: header.TxHash, 569 Root: header.Root, 570 Uncles: uncles, 571 } 572 } 573 574 // reportHistory retrieves the most recent batch of blocks and reports it to the 575 // stats server. 576 func (s *Service) reportHistory(conn *websocket.Conn, list []uint64) error { 577 // Figure out the indexes that need reporting 578 indexes := make([]uint64, 0, historyUpdateRange) 579 if len(list) > 0 { 580 // Specific indexes requested, send them back in particular 581 indexes = append(indexes, list...) 582 } else { 583 // No indexes requested, send back the top ones 584 var head int64 585 if s.eth != nil { 586 head = s.eth.BlockChain().CurrentHeader().Number.Int64() 587 } else { 588 head = s.les.BlockChain().CurrentHeader().Number.Int64() 589 } 590 start := head - historyUpdateRange + 1 591 if start < 0 { 592 start = 0 593 } 594 for i := uint64(start); i <= uint64(head); i++ { 595 indexes = append(indexes, i) 596 } 597 } 598 // Gather the batch of blocks to report 599 history := make([]*blockStats, len(indexes)) 600 for i, number := range indexes { 601 // Retrieve the next block if it's known to us 602 var block *types.Block 603 if s.eth != nil { 604 block = s.eth.BlockChain().GetBlockByNumber(number) 605 } else { 606 if header := s.les.BlockChain().GetHeaderByNumber(number); header != nil { 607 block = types.NewBlockWithHeader(header) 608 } 609 } 610 // If we do have the block, add to the history and continue 611 if block != nil { 612 history[len(history)-1-i] = s.assembleBlockStats(block) 613 continue 614 } 615 // Ran out of blocks, cut the report short and send 616 history = history[len(history)-i:] 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 websocket.JSON.Send(conn, 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 websocket.JSON.Send(conn, 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 websocket.JSON.Send(conn, report) 717 }