|
| 1 | +// Copyright 2024 Louis Royer and the NextMN contributors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | +// SPDX-License-Identifier: MIT |
| 5 | + |
| 6 | +package healthcheck |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "encoding/json" |
| 11 | + "fmt" |
| 12 | + "net/http" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/sirupsen/logrus" |
| 16 | +) |
| 17 | + |
| 18 | +// Healthcheck allows to check status of the node |
| 19 | +type Healthcheck struct { |
| 20 | + uri string |
| 21 | + userAgent string |
| 22 | +} |
| 23 | + |
| 24 | +// Status of the node |
| 25 | +type Status struct { |
| 26 | + Ready bool `json:"ready"` |
| 27 | +} |
| 28 | + |
| 29 | +// Create a new Healthcheck |
| 30 | +func NewHealthcheck(uri string, userAgent string) *Healthcheck { |
| 31 | + return &Healthcheck{ |
| 32 | + uri: uri, |
| 33 | + userAgent: userAgent, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// Run returns an error if the node status is not `ready` |
| 38 | +func (h *Healthcheck) Run(ctx context.Context) error { |
| 39 | + client := http.Client{ |
| 40 | + Timeout: 100 * time.Millisecond, |
| 41 | + } |
| 42 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.uri+"/status", nil) |
| 43 | + if err != nil { |
| 44 | + logrus.WithError(err).Error("Error while creating http get request") |
| 45 | + return err |
| 46 | + } |
| 47 | + req.Header.Add("User-Agent", h.userAgent) |
| 48 | + req.Header.Set("Accept", "application/json") |
| 49 | + req.Header.Set("Accept-Charset", "utf-8") |
| 50 | + resp, err := client.Do(req) |
| 51 | + if err != nil { |
| 52 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("No http response") |
| 53 | + return err |
| 54 | + } |
| 55 | + defer resp.Body.Close() |
| 56 | + if resp.StatusCode != 200 { |
| 57 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Http response is not 200 OK") |
| 58 | + return err |
| 59 | + } |
| 60 | + decoder := json.NewDecoder(resp.Body) |
| 61 | + var status Status |
| 62 | + if err := decoder.Decode(&status); err != nil { |
| 63 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Could not decode json response") |
| 64 | + return err |
| 65 | + } |
| 66 | + if !status.Ready { |
| 67 | + err := fmt.Errorf("Server is not ready") |
| 68 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Server is not ready") |
| 69 | + return err |
| 70 | + } |
| 71 | + return nil |
| 72 | +} |
0 commit comments