-
-
Notifications
You must be signed in to change notification settings - Fork 847
[server] Add health check HTTP endpoint for Relay server #4297
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,195 @@ | ||
package healthcheck | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"net" | ||
"net/http" | ||
"sync" | ||
"time" | ||
|
||
log "github.com/sirupsen/logrus" | ||
|
||
"github.com/netbirdio/netbird/relay/protocol" | ||
"github.com/netbirdio/netbird/relay/server/listener/quic" | ||
"github.com/netbirdio/netbird/relay/server/listener/ws" | ||
) | ||
|
||
const ( | ||
statusHealthy = "healthy" | ||
statusUnhealthy = "unhealthy" | ||
|
||
path = "/health" | ||
|
||
cacheTTL = 3 * time.Second // Cache TTL for health status | ||
) | ||
|
||
type ServiceChecker interface { | ||
ListenerProtocols() []protocol.Protocol | ||
ListenAddress() string | ||
} | ||
|
||
type HealthStatus struct { | ||
Status string `json:"status"` | ||
Timestamp time.Time `json:"timestamp"` | ||
Listeners []protocol.Protocol `json:"listeners"` | ||
CertificateValid bool `json:"certificate_valid"` | ||
} | ||
|
||
type Config struct { | ||
ListenAddress string | ||
ServiceChecker ServiceChecker | ||
} | ||
|
||
type Server struct { | ||
config Config | ||
httpServer *http.Server | ||
|
||
cacheMu sync.Mutex | ||
cacheStatus *HealthStatus | ||
} | ||
|
||
func NewServer(config Config) (*Server, error) { | ||
mux := http.NewServeMux() | ||
|
||
if config.ServiceChecker == nil { | ||
return nil, errors.New("service checker is required") | ||
} | ||
|
||
server := &Server{ | ||
config: config, | ||
httpServer: &http.Server{ | ||
Addr: config.ListenAddress, | ||
Handler: mux, | ||
ReadTimeout: 5 * time.Second, | ||
WriteTimeout: 10 * time.Second, | ||
IdleTimeout: 15 * time.Second, | ||
}, | ||
} | ||
|
||
mux.HandleFunc(path, server.handleHealthcheck) | ||
return server, nil | ||
} | ||
|
||
func (s *Server) ListenAndServe() error { | ||
log.Infof("starting healthcheck server on: http://%s%s", dialAddress(s.config.ListenAddress), path) | ||
return s.httpServer.ListenAndServe() | ||
} | ||
|
||
// Shutdown gracefully shuts down the healthcheck server | ||
func (s *Server) Shutdown(ctx context.Context) error { | ||
log.Info("Shutting down healthcheck server") | ||
return s.httpServer.Shutdown(ctx) | ||
} | ||
|
||
func (s *Server) handleHealthcheck(w http.ResponseWriter, _ *http.Request) { | ||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
|
||
var ( | ||
status *HealthStatus | ||
ok bool | ||
) | ||
// Cache check | ||
s.cacheMu.Lock() | ||
status = s.cacheStatus | ||
s.cacheMu.Unlock() | ||
|
||
if status != nil && time.Since(status.Timestamp) <= cacheTTL { | ||
ok = status.Status == statusHealthy | ||
} else { | ||
status, ok = s.getHealthStatus(ctx) | ||
// Update cache | ||
s.cacheMu.Lock() | ||
s.cacheStatus = status | ||
s.cacheMu.Unlock() | ||
} | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
|
||
if ok { | ||
w.WriteHeader(http.StatusOK) | ||
} else { | ||
w.WriteHeader(http.StatusServiceUnavailable) | ||
} | ||
|
||
encoder := json.NewEncoder(w) | ||
if err := encoder.Encode(status); err != nil { | ||
log.Errorf("Failed to encode healthcheck response: %v", err) | ||
} | ||
} | ||
|
||
func (s *Server) getHealthStatus(ctx context.Context) (*HealthStatus, bool) { | ||
healthy := true | ||
status := &HealthStatus{ | ||
Timestamp: time.Now(), | ||
Status: statusHealthy, | ||
CertificateValid: true, | ||
} | ||
|
||
listeners, ok := s.validateListeners() | ||
if !ok { | ||
status.Status = statusUnhealthy | ||
healthy = false | ||
} | ||
status.Listeners = listeners | ||
|
||
if ok := s.validateCertificate(ctx); !ok { | ||
status.Status = statusUnhealthy | ||
status.CertificateValid = false | ||
healthy = false | ||
} | ||
|
||
return status, healthy | ||
} | ||
|
||
func (s *Server) validateListeners() ([]protocol.Protocol, bool) { | ||
listeners := s.config.ServiceChecker.ListenerProtocols() | ||
if len(listeners) == 0 { | ||
return nil, false | ||
} | ||
return listeners, true | ||
} | ||
|
||
func (s *Server) validateCertificate(ctx context.Context) bool { | ||
listenAddress := s.config.ServiceChecker.ListenAddress() | ||
if listenAddress == "" { | ||
log.Warn("listen address is empty") | ||
return false | ||
} | ||
|
||
dAddr := dialAddress(listenAddress) | ||
|
||
for _, proto := range s.config.ServiceChecker.ListenerProtocols() { | ||
switch proto { | ||
case ws.Proto: | ||
if err := dialWS(ctx, dAddr); err != nil { | ||
log.Errorf("failed to dial WebSocket listener: %v", err) | ||
return false | ||
} | ||
case quic.Proto: | ||
if err := dialQUIC(ctx, dAddr); err != nil { | ||
log.Errorf("failed to dial QUIC listener: %v", err) | ||
return false | ||
} | ||
default: | ||
log.Warnf("unknown protocol for healthcheck: %s", proto) | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
func dialAddress(listenAddress string) string { | ||
host, port, err := net.SplitHostPort(listenAddress) | ||
if err != nil { | ||
return listenAddress // fallback, might be invalid for dialing | ||
} | ||
|
||
if host == "" || host == "::" || host == "0.0.0.0" { | ||
host = "0.0.0.0" | ||
} | ||
|
||
return net.JoinHostPort(host, port) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package healthcheck | ||
|
||
import ( | ||
"context" | ||
"crypto/tls" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/quic-go/quic-go" | ||
|
||
tlsnb "github.com/netbirdio/netbird/shared/relay/tls" | ||
) | ||
|
||
func dialQUIC(ctx context.Context, address string) error { | ||
tlsConfig := &tls.Config{ | ||
InsecureSkipVerify: false, // Keep certificate validation enabled | ||
NextProtos: []string{tlsnb.NBalpn}, | ||
} | ||
|
||
conn, err := quic.DialAddr(ctx, address, tlsConfig, &quic.Config{ | ||
MaxIdleTimeout: 30 * time.Second, | ||
KeepAlivePeriod: 10 * time.Second, | ||
EnableDatagrams: true, | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to connect to QUIC server: %w", err) | ||
} | ||
|
||
_ = conn.CloseWithError(0, "availability check complete") | ||
return nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package healthcheck | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/coder/websocket" | ||
|
||
"github.com/netbirdio/netbird/shared/relay" | ||
) | ||
|
||
func dialWS(ctx context.Context, address string) error { | ||
url := fmt.Sprintf("wss://%s%s", address, relay.WebSocketURLPath) | ||
|
||
conn, resp, err := websocket.Dial(ctx, url, nil) | ||
if resp != nil { | ||
defer func() { | ||
_ = resp.Body.Close() | ||
}() | ||
|
||
} | ||
if err != nil { | ||
return fmt.Errorf("failed to connect to websocket: %w", err) | ||
} | ||
|
||
_ = conn.Close(websocket.StatusNormalClosure, "availability check complete") | ||
return nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package protocol | ||
|
||
type Protocol string |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The empty line after the anonymous function declaration creates unnecessary whitespace. Remove the blank line for cleaner code formatting.
Copilot uses AI. Check for mistakes.