github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+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" 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 p := s.engine.Protocol() 378 if info := infos.Protocols[p.Name]; info != nil { 379 network = fmt.Sprintf("%d", info.(*eth.EthNodeInfo).Network) 380 protocol = fmt.Sprintf("%s/%d", p.Name, p.Versions[0]) 381 } else { 382 network = fmt.Sprintf("%d", infos.Protocols["les"].(*eth.EthNodeInfo).Network) 383 protocol = fmt.Sprintf("les/%d", les.ProtocolVersions[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 := websocket.JSON.Send(conn, login); err != nil { 405 return err 406 } 407 // Retrieve the remote ack or connection termination 408 var ack map[string][]string 409 if err := websocket.JSON.Receive(conn, &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 := websocket.JSON.Send(conn, 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 websocket.JSON.Send(conn, 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 *big.Int `json:"gasUsed"` 479 GasLimit *big.Int `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 repors 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 websocket.JSON.Send(conn, 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: header.Time, 563 Miner: author, 564 GasUsed: new(big.Int).Set(header.GasUsed), 565 GasLimit: new(big.Int).Set(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 } 619 // Assemble the history report and send it to the server 620 if len(history) > 0 { 621 log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number) 622 } else { 623 log.Trace("No history to send to stats server") 624 } 625 stats := map[string]interface{}{ 626 "id": s.node, 627 "history": history, 628 } 629 report := map[string][]interface{}{ 630 "emit": {"history", stats}, 631 } 632 return websocket.JSON.Send(conn, report) 633 } 634 635 // pendStats is the information to report about pending transactions. 636 type pendStats struct { 637 Pending int `json:"pending"` 638 } 639 640 // reportPending retrieves the current number of pending transactions and reports 641 // it to the stats server. 642 func (s *Service) reportPending(conn *websocket.Conn) error { 643 // Retrieve the pending count from the local blockchain 644 var pending int 645 if s.eth != nil { 646 pending, _ = s.eth.TxPool().Stats() 647 } else { 648 pending = s.les.TxPool().Stats() 649 } 650 // Assemble the transaction stats and send it to the server 651 log.Trace("Sending pending transactions to ethstats", "count", pending) 652 653 stats := map[string]interface{}{ 654 "id": s.node, 655 "stats": &pendStats{ 656 Pending: pending, 657 }, 658 } 659 report := map[string][]interface{}{ 660 "emit": {"pending", stats}, 661 } 662 return websocket.JSON.Send(conn, report) 663 } 664 665 // nodeStats is the information to report about the local node. 666 type nodeStats struct { 667 Active bool `json:"active"` 668 Syncing bool `json:"syncing"` 669 Mining bool `json:"mining"` 670 Hashrate int `json:"hashrate"` 671 Peers int `json:"peers"` 672 GasPrice int `json:"gasPrice"` 673 Uptime int `json:"uptime"` 674 } 675 676 // reportPending retrieves various stats about the node at the networking and 677 // mining layer and reports it to the stats server. 678 func (s *Service) reportStats(conn *websocket.Conn) error { 679 // Gather the syncing and mining infos from the local miner instance 680 var ( 681 mining bool 682 hashrate int 683 syncing bool 684 gasprice int 685 ) 686 if s.eth != nil { 687 mining = s.eth.Miner().Mining() 688 hashrate = int(s.eth.Miner().HashRate()) 689 690 sync := s.eth.Downloader().Progress() 691 syncing = s.eth.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 692 693 price, _ := s.eth.ApiBackend.SuggestPrice(context.Background()) 694 gasprice = int(price.Uint64()) 695 } else { 696 sync := s.les.Downloader().Progress() 697 syncing = s.les.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock 698 } 699 // Assemble the node stats and send it to the server 700 log.Trace("Sending node details to ethstats") 701 702 stats := map[string]interface{}{ 703 "id": s.node, 704 "stats": &nodeStats{ 705 Active: true, 706 Mining: mining, 707 Hashrate: hashrate, 708 Peers: s.server.PeerCount(), 709 GasPrice: gasprice, 710 Syncing: syncing, 711 Uptime: 100, 712 }, 713 } 714 report := map[string][]interface{}{ 715 "emit": {"stats", stats}, 716 } 717 return websocket.JSON.Send(conn, report) 718 }