|
| 1 | +package healthmon |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "sync/atomic" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/ethereum/go-ethereum" |
| 13 | + "github.com/ethereum/go-ethereum/core/types" |
| 14 | + "github.com/ethereum/go-ethereum/ethclient" |
| 15 | + mevboostrelay "github.com/flashbots/builder-playground/mev-boost-relay" |
| 16 | + "github.com/flashbots/go-template/common" |
| 17 | + "github.com/flashbots/mev-boost-relay/beaconclient" |
| 18 | + mevRCommon "github.com/flashbots/mev-boost-relay/common" |
| 19 | + "github.com/go-chi/httplog/v2" |
| 20 | +) |
| 21 | + |
| 22 | +var isHealthy atomic.Bool |
| 23 | + |
| 24 | +type Config struct { |
| 25 | + Chain string |
| 26 | + URL string |
| 27 | + Addr string |
| 28 | + BlockTimeSeconds int |
| 29 | +} |
| 30 | + |
| 31 | +func Start(config *Config) { |
| 32 | + log := common.SetupLogger(&common.LoggingOpts{ |
| 33 | + Version: common.Version, |
| 34 | + }) |
| 35 | + |
| 36 | + updates := make(chan blockUpdate, 10) |
| 37 | + log.Info("Started", "chain", config.Chain, "url", config.URL) |
| 38 | + |
| 39 | + switch config.Chain { |
| 40 | + case "beacon": |
| 41 | + go monitorBeacon(log, context.Background(), config.URL, updates) |
| 42 | + case "execution": |
| 43 | + go monitorExecution(log, context.Background(), config.URL, updates) |
| 44 | + default: |
| 45 | + log.Error("Unknown chain", "chain", config.Chain) |
| 46 | + os.Exit(1) |
| 47 | + } |
| 48 | + |
| 49 | + go monitor(log, config.BlockTimeSeconds, context.Background(), updates) |
| 50 | + |
| 51 | + log.Info("Starting service server", "addr", config.Addr) |
| 52 | + |
| 53 | + http.HandleFunc("/ready", statusHandler) |
| 54 | + http.ListenAndServe(config.Addr, nil) |
| 55 | +} |
| 56 | + |
| 57 | +func statusHandler(w http.ResponseWriter, req *http.Request) { |
| 58 | + if isHealthy.Load() { |
| 59 | + io.WriteString(w, "OK") |
| 60 | + } else { |
| 61 | + w.WriteHeader(503) |
| 62 | + io.WriteString(w, "NOT READY") |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func setHealthy(healthy bool) { |
| 67 | + isHealthy.Store(healthy) |
| 68 | +} |
| 69 | + |
| 70 | +type monitorState struct { |
| 71 | + log *httplog.Logger |
| 72 | + firstBlockUpdate *blockUpdate |
| 73 | + blockTimeSeconds int |
| 74 | + blockTimer *time.Timer |
| 75 | +} |
| 76 | + |
| 77 | +func newMonitorState(log *httplog.Logger, blockTimeSeconds int) *monitorState { |
| 78 | + // this timer will start after the blocks are received and we can figure out the block time |
| 79 | + blockTimer := time.NewTimer(0) |
| 80 | + blockTimer.Stop() |
| 81 | + |
| 82 | + return &monitorState{ |
| 83 | + log: log, |
| 84 | + firstBlockUpdate: nil, |
| 85 | + blockTimeSeconds: blockTimeSeconds, |
| 86 | + blockTimer: blockTimer, |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +var wiggleRoomSeconds = 1 |
| 91 | + |
| 92 | +func (m *monitorState) handleUpdate(update blockUpdate) { |
| 93 | + m.log.Info("Processing block update", "number", update.Number, "timestamp", update.Timestamp) |
| 94 | + |
| 95 | + if m.firstBlockUpdate == nil { |
| 96 | + m.firstBlockUpdate = &update |
| 97 | + } |
| 98 | + |
| 99 | + if m.blockTimeSeconds == 0 { |
| 100 | + // if block time is not known, either: |
| 101 | + // - use the block time provided in the update (beacon) |
| 102 | + // - use the difference between the first and current block (execution) |
| 103 | + if update.BlockTime != 0 { |
| 104 | + m.log.Info("Using block time from update", "block time seconds", update.BlockTime) |
| 105 | + m.blockTimeSeconds = update.BlockTime |
| 106 | + } else if m.firstBlockUpdate != nil && update.Number > m.firstBlockUpdate.Number { |
| 107 | + blocktime := update.Timestamp.Sub(m.firstBlockUpdate.Timestamp) |
| 108 | + m.log.Info("Calculated block time from timestamps", "block time seconds", blocktime) |
| 109 | + m.blockTimeSeconds = int(blocktime.Seconds()) |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + if m.blockTimeSeconds != 0 { |
| 114 | + m.log.Info("Resetting block timer", "blockTimeSeconds", m.blockTimeSeconds) |
| 115 | + m.blockTimer.Reset(time.Duration(m.blockTimeSeconds+wiggleRoomSeconds) * time.Second) |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +func monitor(log *httplog.Logger, blockTimeSeconds int, ctx context.Context, updates <-chan blockUpdate) { |
| 120 | + state := newMonitorState(log, blockTimeSeconds) |
| 121 | + |
| 122 | + for { |
| 123 | + select { |
| 124 | + case <-ctx.Done(): |
| 125 | + return |
| 126 | + case update := <-updates: |
| 127 | + // receiving a block always means healthy since the node is producing blocks |
| 128 | + // and the unhealthy state is set during the block timer timeout |
| 129 | + setHealthy(true) |
| 130 | + |
| 131 | + state.handleUpdate(update) |
| 132 | + |
| 133 | + case <-state.blockTimer.C: |
| 134 | + log.Warn("Block timer expired, setting unhealthy") |
| 135 | + setHealthy(false) |
| 136 | + } |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +type blockUpdate struct { |
| 141 | + Number uint64 |
| 142 | + Timestamp time.Time |
| 143 | + BlockTime int |
| 144 | +} |
| 145 | + |
| 146 | +func monitorBeacon(log *httplog.Logger, ctx context.Context, url string, updates chan<- blockUpdate) { |
| 147 | + bLog := mevRCommon.LogSetup(false, "info") |
| 148 | + beaconClient := beaconclient.NewProdBeaconInstance(bLog, url, url) |
| 149 | + |
| 150 | + var lastSlot *uint64 |
| 151 | + var blockTime int |
| 152 | + |
| 153 | + for { |
| 154 | + select { |
| 155 | + case <-ctx.Done(): |
| 156 | + return |
| 157 | + case <-time.After(500 * time.Millisecond): |
| 158 | + sync, err := beaconClient.SyncStatus() |
| 159 | + if err != nil { |
| 160 | + log.Error("Failed to get beacon sync status", "err", err) |
| 161 | + continue |
| 162 | + } |
| 163 | + |
| 164 | + if sync.IsSyncing { |
| 165 | + log.Debug("Beacon node is syncing", "headSlot", sync.HeadSlot) |
| 166 | + continue |
| 167 | + } |
| 168 | + |
| 169 | + if blockTime == 0 { |
| 170 | + spec, err := mevboostrelay.GetSpec(url) |
| 171 | + if err != nil { |
| 172 | + log.Error("Failed to get beacon spec", "err", err) |
| 173 | + } else { |
| 174 | + blockTime = int(spec.SecondsPerSlot) |
| 175 | + log.Info("Fetched beacon spec", "blockTime", blockTime) |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + if lastSlot == nil || *lastSlot < sync.HeadSlot { |
| 180 | + lastSlot = &sync.HeadSlot |
| 181 | + log.Info("New beacon block received", "slot", sync.HeadSlot) |
| 182 | + updates <- blockUpdate{Number: sync.HeadSlot, BlockTime: blockTime} |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +func monitorExecution(log *httplog.Logger, ctx context.Context, url string, updates chan<- blockUpdate) { |
| 189 | + client, err := ethclient.Dial(url) |
| 190 | + if err != nil { |
| 191 | + log.Error("Failed to connect to execution client", "err", err) |
| 192 | + os.Exit(1) |
| 193 | + } |
| 194 | + |
| 195 | + getLatestBlock := func() (*types.Header, error) { |
| 196 | + // We use a manual RPC call instead of the Geth SDK's HeaderByNumber because |
| 197 | + // we query both OP and normal L1 clients which have different transaction types |
| 198 | + // that cannot be decoded with a single Geth SDK. The Geth SDK only returns blocks |
| 199 | + // with transactions fully decoded (not just hashes), so we call the RPC directly |
| 200 | + // to avoid transaction decoding issues. |
| 201 | + var raw json.RawMessage |
| 202 | + if err := client.Client().CallContext(ctx, &raw, "eth_getBlockByNumber", "latest", false); err != nil { |
| 203 | + return nil, err |
| 204 | + } |
| 205 | + |
| 206 | + // Decode header and transactions. |
| 207 | + var head *types.Header |
| 208 | + if err := json.Unmarshal(raw, &head); err != nil { |
| 209 | + return nil, err |
| 210 | + } |
| 211 | + // When the block is not found, the API returns JSON null. |
| 212 | + if head == nil { |
| 213 | + return nil, ethereum.NotFound |
| 214 | + } |
| 215 | + return head, nil |
| 216 | + } |
| 217 | + |
| 218 | + var lastBlock *uint64 |
| 219 | + for { |
| 220 | + select { |
| 221 | + case <-ctx.Done(): |
| 222 | + return |
| 223 | + case <-time.After(500 * time.Millisecond): |
| 224 | + sync, err := client.SyncProgress(ctx) |
| 225 | + if err != nil { |
| 226 | + log.Error("Failed to get execution sync progress", "err", err) |
| 227 | + continue |
| 228 | + } |
| 229 | + |
| 230 | + if sync != nil && !sync.Done() { |
| 231 | + log.Debug("Execution node is syncing", "currentBlock", sync.CurrentBlock, "highestBlock", sync.HighestBlock) |
| 232 | + continue |
| 233 | + } |
| 234 | + header, err := getLatestBlock() |
| 235 | + if err != nil { |
| 236 | + log.Error("Failed to get execution block number", "err", err) |
| 237 | + continue |
| 238 | + } |
| 239 | + num := header.Number.Uint64() |
| 240 | + if lastBlock == nil || num > *lastBlock { |
| 241 | + lastBlock = &num |
| 242 | + timestamp := time.Unix(int64(header.Time), 0) |
| 243 | + |
| 244 | + log.Info("New execution block received", "number", num) |
| 245 | + updates <- blockUpdate{Number: num, Timestamp: timestamp} |
| 246 | + } |
| 247 | + } |
| 248 | + } |
| 249 | +} |
0 commit comments