|
| 1 | +// Copyright 2024 Louis Royer and the NextMN-SRv6 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 | +package healthcheck |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "encoding/json" |
| 10 | + "fmt" |
| 11 | + "net/http" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/sirupsen/logrus" |
| 15 | + |
| 16 | + "github.com/nextmn/srv6/internal/config" |
| 17 | +) |
| 18 | + |
| 19 | +type Healthcheck struct { |
| 20 | + uri string |
| 21 | +} |
| 22 | + |
| 23 | +// TODO: move this in json-api |
| 24 | +type Status struct { |
| 25 | + Ready bool `json:"ready"` |
| 26 | +} |
| 27 | + |
| 28 | +func NewHealthcheck(conf *config.SRv6Config) *Healthcheck { |
| 29 | + httpPort := "80" // default http port |
| 30 | + if conf.HTTPPort != nil { |
| 31 | + httpPort = *conf.HTTPPort |
| 32 | + } |
| 33 | + httpURI := "http://" |
| 34 | + if conf.HTTPAddress.Is6() { |
| 35 | + httpURI = httpURI + "[" + conf.HTTPAddress.String() + "]:" + httpPort |
| 36 | + } else { |
| 37 | + httpURI = httpURI + conf.HTTPAddress.String() + ":" + httpPort |
| 38 | + } |
| 39 | + return &Healthcheck{ |
| 40 | + uri: httpURI, |
| 41 | + } |
| 42 | +} |
| 43 | +func (h *Healthcheck) Run(ctx context.Context) error { |
| 44 | + client := http.Client{ |
| 45 | + Timeout: 100 * time.Millisecond, |
| 46 | + } |
| 47 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.uri+"/status", nil) |
| 48 | + if err != nil { |
| 49 | + logrus.WithError(err).Error("Error while creating http get request") |
| 50 | + return err |
| 51 | + } |
| 52 | + req.Header.Add("User-Agent", "go-github-nextmn-srv6") |
| 53 | + req.Header.Set("Accept", "application/json") |
| 54 | + req.Header.Set("Accept-Charset", "utf-8") |
| 55 | + resp, err := client.Do(req) |
| 56 | + if err != nil { |
| 57 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("No http response") |
| 58 | + return err |
| 59 | + } |
| 60 | + defer resp.Body.Close() |
| 61 | + if resp.StatusCode != 200 { |
| 62 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Http response is not 200 OK") |
| 63 | + return err |
| 64 | + } |
| 65 | + decoder := json.NewDecoder(resp.Body) |
| 66 | + var status Status |
| 67 | + if err := decoder.Decode(&status); err != nil { |
| 68 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Could not decode json response") |
| 69 | + return err |
| 70 | + } |
| 71 | + if !status.Ready { |
| 72 | + err := fmt.Errorf("Server is not ready") |
| 73 | + logrus.WithFields(logrus.Fields{"remote-server": h.uri}).WithError(err).Info("Server is not ready") |
| 74 | + return err |
| 75 | + } |
| 76 | + return nil |
| 77 | +} |
0 commit comments