|
| 1 | +package healthcheck |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | + |
| 12 | + log "github.com/sirupsen/logrus" |
| 13 | + |
| 14 | + "github.com/netbirdio/netbird/relay/protocol" |
| 15 | + "github.com/netbirdio/netbird/relay/server/listener/quic" |
| 16 | + "github.com/netbirdio/netbird/relay/server/listener/ws" |
| 17 | +) |
| 18 | + |
| 19 | +const ( |
| 20 | + statusHealthy = "healthy" |
| 21 | + statusUnhealthy = "unhealthy" |
| 22 | + |
| 23 | + path = "/health" |
| 24 | + |
| 25 | + cacheTTL = 3 * time.Second // Cache TTL for health status |
| 26 | +) |
| 27 | + |
| 28 | +type ServiceChecker interface { |
| 29 | + ListenerProtocols() []protocol.Protocol |
| 30 | + ListenAddress() string |
| 31 | +} |
| 32 | + |
| 33 | +type HealthStatus struct { |
| 34 | + Status string `json:"status"` |
| 35 | + Timestamp time.Time `json:"timestamp"` |
| 36 | + Listeners []protocol.Protocol `json:"listeners"` |
| 37 | + CertificateValid bool `json:"certificate_valid"` |
| 38 | +} |
| 39 | + |
| 40 | +type Config struct { |
| 41 | + ListenAddress string |
| 42 | + ServiceChecker ServiceChecker |
| 43 | +} |
| 44 | + |
| 45 | +type Server struct { |
| 46 | + config Config |
| 47 | + httpServer *http.Server |
| 48 | + |
| 49 | + cacheMu sync.Mutex |
| 50 | + cacheStatus *HealthStatus |
| 51 | +} |
| 52 | + |
| 53 | +func NewServer(config Config) (*Server, error) { |
| 54 | + mux := http.NewServeMux() |
| 55 | + |
| 56 | + if config.ServiceChecker == nil { |
| 57 | + return nil, errors.New("service checker is required") |
| 58 | + } |
| 59 | + |
| 60 | + server := &Server{ |
| 61 | + config: config, |
| 62 | + httpServer: &http.Server{ |
| 63 | + Addr: config.ListenAddress, |
| 64 | + Handler: mux, |
| 65 | + ReadTimeout: 5 * time.Second, |
| 66 | + WriteTimeout: 10 * time.Second, |
| 67 | + IdleTimeout: 15 * time.Second, |
| 68 | + }, |
| 69 | + } |
| 70 | + |
| 71 | + mux.HandleFunc(path, server.handleHealthcheck) |
| 72 | + return server, nil |
| 73 | +} |
| 74 | + |
| 75 | +func (s *Server) ListenAndServe() error { |
| 76 | + log.Infof("starting healthcheck server on: http://%s%s", dialAddress(s.config.ListenAddress), path) |
| 77 | + return s.httpServer.ListenAndServe() |
| 78 | +} |
| 79 | + |
| 80 | +// Shutdown gracefully shuts down the healthcheck server |
| 81 | +func (s *Server) Shutdown(ctx context.Context) error { |
| 82 | + log.Info("Shutting down healthcheck server") |
| 83 | + return s.httpServer.Shutdown(ctx) |
| 84 | +} |
| 85 | + |
| 86 | +func (s *Server) handleHealthcheck(w http.ResponseWriter, _ *http.Request) { |
| 87 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 88 | + defer cancel() |
| 89 | + |
| 90 | + var ( |
| 91 | + status *HealthStatus |
| 92 | + ok bool |
| 93 | + ) |
| 94 | + // Cache check |
| 95 | + s.cacheMu.Lock() |
| 96 | + status = s.cacheStatus |
| 97 | + s.cacheMu.Unlock() |
| 98 | + |
| 99 | + if status != nil && time.Since(status.Timestamp) <= cacheTTL { |
| 100 | + ok = status.Status == statusHealthy |
| 101 | + } else { |
| 102 | + status, ok = s.getHealthStatus(ctx) |
| 103 | + // Update cache |
| 104 | + s.cacheMu.Lock() |
| 105 | + s.cacheStatus = status |
| 106 | + s.cacheMu.Unlock() |
| 107 | + } |
| 108 | + |
| 109 | + w.Header().Set("Content-Type", "application/json") |
| 110 | + |
| 111 | + if ok { |
| 112 | + w.WriteHeader(http.StatusOK) |
| 113 | + } else { |
| 114 | + w.WriteHeader(http.StatusServiceUnavailable) |
| 115 | + } |
| 116 | + |
| 117 | + encoder := json.NewEncoder(w) |
| 118 | + if err := encoder.Encode(status); err != nil { |
| 119 | + log.Errorf("Failed to encode healthcheck response: %v", err) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +func (s *Server) getHealthStatus(ctx context.Context) (*HealthStatus, bool) { |
| 124 | + healthy := true |
| 125 | + status := &HealthStatus{ |
| 126 | + Timestamp: time.Now(), |
| 127 | + Status: statusHealthy, |
| 128 | + CertificateValid: true, |
| 129 | + } |
| 130 | + |
| 131 | + listeners, ok := s.validateListeners() |
| 132 | + if !ok { |
| 133 | + status.Status = statusUnhealthy |
| 134 | + healthy = false |
| 135 | + } |
| 136 | + status.Listeners = listeners |
| 137 | + |
| 138 | + if ok := s.validateCertificate(ctx); !ok { |
| 139 | + status.Status = statusUnhealthy |
| 140 | + status.CertificateValid = false |
| 141 | + healthy = false |
| 142 | + } |
| 143 | + |
| 144 | + return status, healthy |
| 145 | +} |
| 146 | + |
| 147 | +func (s *Server) validateListeners() ([]protocol.Protocol, bool) { |
| 148 | + listeners := s.config.ServiceChecker.ListenerProtocols() |
| 149 | + if len(listeners) == 0 { |
| 150 | + return nil, false |
| 151 | + } |
| 152 | + return listeners, true |
| 153 | +} |
| 154 | + |
| 155 | +func (s *Server) validateCertificate(ctx context.Context) bool { |
| 156 | + listenAddress := s.config.ServiceChecker.ListenAddress() |
| 157 | + if listenAddress == "" { |
| 158 | + log.Warn("listen address is empty") |
| 159 | + return false |
| 160 | + } |
| 161 | + |
| 162 | + dAddr := dialAddress(listenAddress) |
| 163 | + |
| 164 | + for _, proto := range s.config.ServiceChecker.ListenerProtocols() { |
| 165 | + switch proto { |
| 166 | + case ws.Proto: |
| 167 | + if err := dialWS(ctx, dAddr); err != nil { |
| 168 | + log.Errorf("failed to dial WebSocket listener: %v", err) |
| 169 | + return false |
| 170 | + } |
| 171 | + case quic.Proto: |
| 172 | + if err := dialQUIC(ctx, dAddr); err != nil { |
| 173 | + log.Errorf("failed to dial QUIC listener: %v", err) |
| 174 | + return false |
| 175 | + } |
| 176 | + default: |
| 177 | + log.Warnf("unknown protocol for healthcheck: %s", proto) |
| 178 | + return false |
| 179 | + } |
| 180 | + } |
| 181 | + return true |
| 182 | +} |
| 183 | + |
| 184 | +func dialAddress(listenAddress string) string { |
| 185 | + host, port, err := net.SplitHostPort(listenAddress) |
| 186 | + if err != nil { |
| 187 | + return listenAddress // fallback, might be invalid for dialing |
| 188 | + } |
| 189 | + |
| 190 | + if host == "" || host == "::" || host == "0.0.0.0" { |
| 191 | + host = "0.0.0.0" |
| 192 | + } |
| 193 | + |
| 194 | + return net.JoinHostPort(host, port) |
| 195 | +} |
0 commit comments