refactored some stuff, added healthcheck support, fixed 'include file' reload not showing in log

This commit is contained in:
yusing
2024-10-12 13:56:38 +08:00
parent 64e30f59e8
commit d47b672aa5
41 changed files with 783 additions and 421 deletions

View File

@@ -1,67 +1,42 @@
package loadbalancer
import (
"context"
"net/http"
"sync/atomic"
"time"
"github.com/yusing/go-proxy/internal/net/types"
U "github.com/yusing/go-proxy/internal/utils"
"github.com/yusing/go-proxy/internal/watcher/health"
)
type (
Server struct {
Name string
URL types.URL
Weight weightType
handler http.Handler
_ U.NoCopy
pinger *http.Client
available atomic.Bool
Name string
URL types.URL
Weight weightType
handler http.Handler
healthMon health.HealthMonitor
}
servers []*Server
)
func NewServer(name string, url types.URL, weight weightType, handler http.Handler) *Server {
func NewServer(name string, url types.URL, weight weightType, handler http.Handler, healthMon health.HealthMonitor) *Server {
srv := &Server{
Name: name,
URL: url,
Weight: weight,
handler: handler,
pinger: &http.Client{Timeout: 3 * time.Second},
Name: name,
URL: url,
Weight: weight,
handler: handler,
healthMon: healthMon,
}
srv.available.Store(true)
return srv
}
func (srv *Server) checkUpdateAvail(ctx context.Context) {
req, err := http.NewRequestWithContext(
ctx,
http.MethodHead,
srv.URL.String(),
nil,
)
if err != nil {
logger.Error("failed to create request: ", err)
srv.available.Store(false)
}
resp, err := srv.pinger.Do(req)
if err == nil && resp.StatusCode != http.StatusServiceUnavailable {
if !srv.available.Swap(true) {
logger.Infof("server %s is up", srv.Name)
}
} else if err != nil {
if srv.available.Swap(false) {
logger.Warnf("server %s is down: %s", srv.Name, err)
}
} else {
if srv.available.Swap(false) {
logger.Warnf("server %s is down: status %s", srv.Name, resp.Status)
}
}
}
func (srv *Server) String() string {
return srv.Name
}
func (srv *Server) IsHealthy() bool {
return srv.healthMon.IsHealthy()
}