gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/common/metrics/healthcheck.go (about) 1 // Copyright 2018 The aquachain Authors 2 // This file is part of the aquachain library. 3 // 4 // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package metrics 18 19 // Healthchecks hold an error value describing an arbitrary up/down status. 20 type Healthcheck interface { 21 Check() 22 Error() error 23 Healthy() 24 Unhealthy(error) 25 } 26 27 // NewHealthcheck constructs a new Healthcheck which will use the given 28 // function to update its status. 29 func NewHealthcheck(f func(Healthcheck)) Healthcheck { 30 if !Enabled { 31 return NilHealthcheck{} 32 } 33 return &StandardHealthcheck{nil, f} 34 } 35 36 // NilHealthcheck is a no-op. 37 type NilHealthcheck struct{} 38 39 // Check is a no-op. 40 func (NilHealthcheck) Check() {} 41 42 // Error is a no-op. 43 func (NilHealthcheck) Error() error { return nil } 44 45 // Healthy is a no-op. 46 func (NilHealthcheck) Healthy() {} 47 48 // Unhealthy is a no-op. 49 func (NilHealthcheck) Unhealthy(error) {} 50 51 // StandardHealthcheck is the standard implementation of a Healthcheck and 52 // stores the status and a function to call to update the status. 53 type StandardHealthcheck struct { 54 err error 55 f func(Healthcheck) 56 } 57 58 // Check runs the healthcheck function to update the healthcheck's status. 59 func (h *StandardHealthcheck) Check() { 60 h.f(h) 61 } 62 63 // Error returns the healthcheck's status, which will be nil if it is healthy. 64 func (h *StandardHealthcheck) Error() error { 65 return h.err 66 } 67 68 // Healthy marks the healthcheck as healthy. 69 func (h *StandardHealthcheck) Healthy() { 70 h.err = nil 71 } 72 73 // Unhealthy marks the healthcheck as unhealthy. The error is stored and 74 // may be retrieved by the Error method. 75 func (h *StandardHealthcheck) Unhealthy(err error) { 76 h.err = err 77 }