reporter.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. // Copyright 2018 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. package protocols
  17. import (
  18. "encoding/binary"
  19. "time"
  20. "github.com/ethereum/go-ethereum/log"
  21. "github.com/ethereum/go-ethereum/metrics"
  22. "github.com/syndtr/goleveldb/leveldb"
  23. )
  24. //AccountMetrics abstracts away the metrics DB and
  25. //the reporter to persist metrics
  26. type AccountingMetrics struct {
  27. reporter *reporter
  28. }
  29. //Close will be called when the node is being shutdown
  30. //for a graceful cleanup
  31. func (am *AccountingMetrics) Close() {
  32. close(am.reporter.quit)
  33. // wait for reporter loop to finish saving metrics
  34. // before reporter database is closed
  35. select {
  36. case <-time.After(10 * time.Second):
  37. log.Error("accounting metrics reporter timeout")
  38. case <-am.reporter.done:
  39. }
  40. am.reporter.db.Close()
  41. }
  42. //reporter is an internal structure used to write p2p accounting related
  43. //metrics to a LevelDB. It will periodically write the accrued metrics to the DB.
  44. type reporter struct {
  45. reg metrics.Registry //the registry for these metrics (independent of other metrics)
  46. interval time.Duration //duration at which the reporter will persist metrics
  47. db *leveldb.DB //the actual DB
  48. quit chan struct{} //quit the reporter loop
  49. done chan struct{} //signal that reporter loop is done
  50. }
  51. //NewMetricsDB creates a new LevelDB instance used to persist metrics defined
  52. //inside p2p/protocols/accounting.go
  53. func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *AccountingMetrics {
  54. var val = make([]byte, 8)
  55. var err error
  56. //Create the LevelDB
  57. db, err := leveldb.OpenFile(path, nil)
  58. if err != nil {
  59. log.Error(err.Error())
  60. return nil
  61. }
  62. //Check for all defined metrics that there is a value in the DB
  63. //If there is, assign it to the metric. This means that the node
  64. //has been running before and that metrics have been persisted.
  65. metricsMap := map[string]metrics.Counter{
  66. "account.balance.credit": mBalanceCredit,
  67. "account.balance.debit": mBalanceDebit,
  68. "account.bytes.credit": mBytesCredit,
  69. "account.bytes.debit": mBytesDebit,
  70. "account.msg.credit": mMsgCredit,
  71. "account.msg.debit": mMsgDebit,
  72. "account.peerdrops": mPeerDrops,
  73. "account.selfdrops": mSelfDrops,
  74. }
  75. //iterate the map and get the values
  76. for key, metric := range metricsMap {
  77. val, err = db.Get([]byte(key), nil)
  78. //until the first time a value is being written,
  79. //this will return an error.
  80. //it could be beneficial though to log errors later,
  81. //but that would require a different logic
  82. if err == nil {
  83. metric.Inc(int64(binary.BigEndian.Uint64(val)))
  84. }
  85. }
  86. //create the reporter
  87. rep := &reporter{
  88. reg: r,
  89. interval: d,
  90. db: db,
  91. quit: make(chan struct{}),
  92. done: make(chan struct{}),
  93. }
  94. //run the go routine
  95. go rep.run()
  96. m := &AccountingMetrics{
  97. reporter: rep,
  98. }
  99. return m
  100. }
  101. //run is the goroutine which periodically sends the metrics to the configured LevelDB
  102. func (r *reporter) run() {
  103. // signal that the reporter loop is done
  104. defer close(r.done)
  105. intervalTicker := time.NewTicker(r.interval)
  106. for {
  107. select {
  108. case <-intervalTicker.C:
  109. //at each tick send the metrics
  110. if err := r.save(); err != nil {
  111. log.Error("unable to send metrics to LevelDB", "err", err)
  112. //If there is an error in writing, exit the routine; we assume here that the error is
  113. //severe and don't attempt to write again.
  114. //Also, this should prevent leaking when the node is stopped
  115. return
  116. }
  117. case <-r.quit:
  118. //graceful shutdown
  119. if err := r.save(); err != nil {
  120. log.Error("unable to send metrics to LevelDB", "err", err)
  121. }
  122. return
  123. }
  124. }
  125. }
  126. //send the metrics to the DB
  127. func (r *reporter) save() error {
  128. //create a LevelDB Batch
  129. batch := leveldb.Batch{}
  130. //for each metric in the registry (which is independent)...
  131. r.reg.Each(func(name string, i interface{}) {
  132. metric, ok := i.(metrics.Counter)
  133. if ok {
  134. //assuming every metric here to be a Counter (separate registry)
  135. //...create a snapshot...
  136. ms := metric.Snapshot()
  137. byteVal := make([]byte, 8)
  138. binary.BigEndian.PutUint64(byteVal, uint64(ms.Count()))
  139. //...and save the value to the DB
  140. batch.Put([]byte(name), byteVal)
  141. }
  142. })
  143. return r.db.Write(&batch, nil)
  144. }