Merge pull request 'fix: smoother rollouts for checkers, and say when they recover' (#158) from fix/checker-recovery-and-rollouts into main
This commit is contained in:
commit
00d37943e4
9 files changed
+236
-9
No files matched your search
@@ -89,6 +89,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
|||||||
health.Register(r)
|
health.Register(r)
|
||||||
r.StaticFS("/static", web.Static())
|
r.StaticFS("/static", web.Static())
|
||||||
srv.Mount(r)
|
srv.Mount(r)
|
||||||
|
srv.EndLongPollsOn(health.Draining())
|
||||||
go srv.RunScheduler(ctx)
|
go srv.RunScheduler(ctx)
|
||||||
go srv.RunNotifier(ctx)
|
go srv.RunNotifier(ctx)
|
||||||
go srv.RunHousekeeping(ctx)
|
go srv.RunHousekeeping(ctx)
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ metadata:
|
|||||||
app.kubernetes.io/component: api
|
app.kubernetes.io/component: api
|
||||||
spec:
|
spec:
|
||||||
replicas: {{ .Values.api.replicas }}
|
replicas: {{ .Values.api.replicas }}
|
||||||
|
# Roll one pod at a time without ever having fewer ready than wanted;
|
||||||
|
# a new pod serves a few seconds before an old one goes, so the ingress
|
||||||
|
# has picked it up.
|
||||||
|
strategy:
|
||||||
|
type: RollingUpdate
|
||||||
|
rollingUpdate:
|
||||||
|
maxUnavailable: 0
|
||||||
|
maxSurge: 1
|
||||||
|
minReadySeconds: 5
|
||||||
selector:
|
selector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
|
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
|
||||||
|
|||||||
@@ -9,6 +9,15 @@ metadata:
|
|||||||
app.kubernetes.io/component: statuspage
|
app.kubernetes.io/component: statuspage
|
||||||
spec:
|
spec:
|
||||||
replicas: {{ .Values.statuspage.replicas }}
|
replicas: {{ .Values.statuspage.replicas }}
|
||||||
|
# Roll one pod at a time without ever having fewer ready than wanted;
|
||||||
|
# a new pod serves a few seconds before an old one goes, so the ingress
|
||||||
|
# has picked it up.
|
||||||
|
strategy:
|
||||||
|
type: RollingUpdate
|
||||||
|
rollingUpdate:
|
||||||
|
maxUnavailable: 0
|
||||||
|
maxSurge: 1
|
||||||
|
minReadySeconds: 5
|
||||||
selector:
|
selector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
|
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
|
||||||
|
|||||||
+24
-3
@@ -32,7 +32,9 @@ const (
|
|||||||
ctxAgent = "api.agent"
|
ctxAgent = "api.agent"
|
||||||
ctxInstance = "api.instance"
|
ctxInstance = "api.instance"
|
||||||
maxJobWait = 25 * time.Second
|
maxJobWait = 25 * time.Second
|
||||||
maxJobBatch = 200
|
// drainingPollHold is how long a draining instance still holds a poll.
|
||||||
|
drainingPollHold = time.Second
|
||||||
|
maxJobBatch = 200
|
||||||
)
|
)
|
||||||
|
|
||||||
func (s *Server) mountAgentAPI(r gin.IRouter) {
|
func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||||
@@ -197,8 +199,27 @@ func (s *Server) agentJobs(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
|
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
|
||||||
entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait)
|
// A draining instance ends long polls within a second or so, empty, so
|
||||||
if err != nil && ctx.Err() == nil {
|
// the shutdown is not held up and the checker's next poll reaches
|
||||||
|
// another instance. It still holds them that second, so checkers that
|
||||||
|
// poll again at once do not spin against it.
|
||||||
|
pollCtx, stop := context.WithCancel(ctx)
|
||||||
|
defer stop()
|
||||||
|
if s.draining != nil {
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case <-s.draining:
|
||||||
|
select {
|
||||||
|
case <-time.After(drainingPollHold):
|
||||||
|
case <-pollCtx.Done():
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
case <-pollCtx.Done():
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||||
|
if err != nil && pollCtx.Err() == nil {
|
||||||
internalError(c, err)
|
internalError(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package api_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLongPollsEndWhenDraining(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
tok, _ := e.platformChecker(t, uniq("eu-"))
|
||||||
|
drain := make(chan struct{})
|
||||||
|
e.api.EndLongPollsOn(drain)
|
||||||
|
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||||
|
|
||||||
|
go func() { time.Sleep(300 * time.Millisecond); close(drain) }()
|
||||||
|
start := time.Now()
|
||||||
|
jobs, err := client.Jobs(context.Background(), 10, 20*time.Second)
|
||||||
|
if err != nil || len(jobs) != 0 {
|
||||||
|
t.Fatalf("Jobs() while draining = %v, %v; want no jobs and no error", jobs, err)
|
||||||
|
}
|
||||||
|
if took := time.Since(start); took > 3*time.Second {
|
||||||
|
t.Errorf("a long poll ran %v after draining began, want it to end within about a second", took)
|
||||||
|
}
|
||||||
|
// Once draining, polls answer at once.
|
||||||
|
start = time.Now()
|
||||||
|
if _, err := client.Jobs(context.Background(), 10, 20*time.Second); err != nil || time.Since(start) > 2*time.Second {
|
||||||
|
t.Errorf("a poll on a draining instance took %v (%v)", time.Since(start), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -55,6 +55,8 @@ type Server struct {
|
|||||||
limits *versioned[Limits]
|
limits *versioned[Limits]
|
||||||
// support caches how the platform runs support tickets.
|
// support caches how the platform runs support tickets.
|
||||||
support *versioned[supportSettings]
|
support *versioned[supportSettings]
|
||||||
|
// draining, once closed, ends the long polls of checkers.
|
||||||
|
draining <-chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deps are the external resources a Server needs.
|
// Deps are the external resources a Server needs.
|
||||||
@@ -94,6 +96,10 @@ func New(cfg config.API, d Deps) *Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EndLongPollsOn makes the checkers' long polls return as soon as ch is
|
||||||
|
// closed, as when the instance starts draining for a shutdown.
|
||||||
|
func (s *Server) EndLongPollsOn(ch <-chan struct{}) { s.draining = ch }
|
||||||
|
|
||||||
// Mount installs session loading, locale resolution and CSRF protection and
|
// Mount installs session loading, locale resolution and CSRF protection and
|
||||||
// registers the JSON API and the console pages below them.
|
// registers the JSON API and the console pages below them.
|
||||||
func (s *Server) Mount(r gin.IRouter) {
|
func (s *Server) Mount(r gin.IRouter) {
|
||||||
|
|||||||
@@ -26,7 +26,9 @@ type API interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
pollWait = 20 * time.Second
|
pollWait = 20 * time.Second
|
||||||
|
// quickPoll is a long poll answered empty faster than any wait would.
|
||||||
|
quickPoll = 200 * time.Millisecond
|
||||||
flushInterval = 2 * time.Second
|
flushInterval = 2 * time.Second
|
||||||
// maxPending bounds results kept while the API is unreachable.
|
// maxPending bounds results kept while the API is unreachable.
|
||||||
maxPending = 50_000
|
maxPending = 50_000
|
||||||
@@ -127,6 +129,12 @@ func (r *Runner) Run(ctx context.Context, drain time.Duration) error {
|
|||||||
|
|
||||||
func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||||
backoff := time.Second
|
backoff := time.Second
|
||||||
|
// failing and failures track an outage, so its end is logged too: a log
|
||||||
|
// whose last line is an error otherwise reads as a checker stuck.
|
||||||
|
var (
|
||||||
|
failing time.Time
|
||||||
|
failures int
|
||||||
|
)
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
free := cap(r.slots) - len(r.slots)
|
free := cap(r.slots) - len(r.slots)
|
||||||
wait := pollWait
|
wait := pollWait
|
||||||
@@ -134,6 +142,7 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
|||||||
// Still poll as a heartbeat, but do not take work.
|
// Still poll as a heartbeat, but do not take work.
|
||||||
wait = 0
|
wait = 0
|
||||||
}
|
}
|
||||||
|
asked := time.Now()
|
||||||
jobs, err := r.api.Jobs(ctx, free, wait)
|
jobs, err := r.api.Jobs(ctx, free, wait)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, agentapi.ErrUnauthorized):
|
case errors.Is(err, agentapi.ErrUnauthorized):
|
||||||
@@ -143,11 +152,19 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff)
|
r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff)
|
||||||
|
if failing.IsZero() {
|
||||||
|
failing = time.Now()
|
||||||
|
}
|
||||||
|
failures++
|
||||||
sleep(ctx, backoff)
|
sleep(ctx, backoff)
|
||||||
backoff = min(backoff*2, 30*time.Second)
|
backoff = min(backoff*2, 30*time.Second)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
backoff = time.Second
|
backoff = time.Second
|
||||||
|
if !failing.IsZero() {
|
||||||
|
r.log.Info("polling for jobs works again", "failed_for", time.Since(failing).Round(time.Second).String(), "failures", failures)
|
||||||
|
failing, failures = time.Time{}, 0
|
||||||
|
}
|
||||||
r.lastPoll.Store(time.Now().UnixMilli())
|
r.lastPoll.Store(time.Now().UnixMilli())
|
||||||
for _, j := range jobs {
|
for _, j := range jobs {
|
||||||
r.slots <- struct{}{}
|
r.slots <- struct{}{}
|
||||||
@@ -157,7 +174,9 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
|||||||
r.results <- r.execute(ctx, j)
|
r.results <- r.execute(ctx, j)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
if free == 0 {
|
// A long poll answered empty at once, as by an instance shutting
|
||||||
|
// down, is not repeated at once either.
|
||||||
|
if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) {
|
||||||
sleep(ctx, time.Second)
|
sleep(ctx, time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,15 +207,27 @@ func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
|
|||||||
func (r *Runner) report(ctx context.Context) {
|
func (r *Runner) report(ctx context.Context) {
|
||||||
tick := time.NewTicker(flushInterval)
|
tick := time.NewTicker(flushInterval)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
var pending []agentapi.Result
|
var (
|
||||||
|
pending []agentapi.Result
|
||||||
|
// failing is when reporting started to fail, zero while it works.
|
||||||
|
failing time.Time
|
||||||
|
)
|
||||||
flush := func(ctx context.Context) {
|
flush := func(ctx context.Context) {
|
||||||
|
sent := 0
|
||||||
for len(pending) > 0 {
|
for len(pending) > 0 {
|
||||||
n := min(len(pending), agentapi.MaxResults)
|
n := min(len(pending), agentapi.MaxResults)
|
||||||
if err := r.api.Report(ctx, pending[:n]); err != nil {
|
if err := r.api.Report(ctx, pending[:n]); err != nil {
|
||||||
r.log.Warn("reporting results failed", "error", err, "pending", len(pending))
|
r.log.Warn("reporting results failed", "error", err, "pending", len(pending))
|
||||||
|
if failing.IsZero() {
|
||||||
|
failing = time.Now()
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pending = pending[n:]
|
pending, sent = pending[n:], sent+n
|
||||||
|
}
|
||||||
|
if !failing.IsZero() {
|
||||||
|
r.log.Info("reporting results works again", "failed_for", time.Since(failing).Round(time.Second).String(), "sent", sent)
|
||||||
|
failing = time.Time{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package checker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||||
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||||
|
)
|
||||||
|
|
||||||
|
// flakyAPI fails its first calls, like an API being rolled out.
|
||||||
|
type flakyAPI struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
jobFails int
|
||||||
|
reportFails int
|
||||||
|
gave bool
|
||||||
|
reported int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flakyAPI) Jobs(ctx context.Context, _ int, wait time.Duration) ([]agentapi.Job, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
if f.jobFails > 0 {
|
||||||
|
f.jobFails--
|
||||||
|
f.mu.Unlock()
|
||||||
|
return nil, errors.New("504 Gateway Timeout")
|
||||||
|
}
|
||||||
|
if !f.gave {
|
||||||
|
f.gave = true
|
||||||
|
f.mu.Unlock()
|
||||||
|
return []agentapi.Job{{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}}, nil
|
||||||
|
}
|
||||||
|
f.mu.Unlock()
|
||||||
|
select {
|
||||||
|
case <-time.After(min(wait, 50*time.Millisecond)):
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flakyAPI) Report(_ context.Context, rs []agentapi.Result) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if f.reportFails > 0 {
|
||||||
|
f.reportFails--
|
||||||
|
return errors.New("context deadline exceeded")
|
||||||
|
}
|
||||||
|
f.reported += len(rs)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flakyAPI) Release(context.Context) error { return nil }
|
||||||
|
|
||||||
|
type syncBuffer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
b bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.b.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *syncBuffer) String() string {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecoveryIsLogged(t *testing.T) {
|
||||||
|
api := &flakyAPI{jobFails: 1, reportFails: 1}
|
||||||
|
var logs syncBuffer
|
||||||
|
r := New(api, 2, slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||||
|
r.run = func(context.Context, check.Spec) check.Outcome { return check.Outcome{OK: true} }
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- r.Run(ctx, time.Second) }()
|
||||||
|
|
||||||
|
deadline := time.Now().Add(10 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
out := logs.String()
|
||||||
|
if strings.Contains(out, "polling for jobs works again") && strings.Contains(out, "reporting results works again") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
<-done
|
||||||
|
out := logs.String()
|
||||||
|
for _, want := range []string{`"msg":"polling for jobs works again"`, `"failures":1`, `"msg":"reporting results works again"`, `"sent":1`} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("log lacks %s:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n := strings.Count(out, "works again"); n != 2 {
|
||||||
|
t.Errorf("recovery logged %d times, want once each", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package platform
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -17,15 +18,24 @@ type Probe func(context.Context) error
|
|||||||
type Health struct {
|
type Health struct {
|
||||||
probes map[string]Probe
|
probes map[string]Probe
|
||||||
draining atomic.Bool
|
draining atomic.Bool
|
||||||
|
drained chan struct{}
|
||||||
|
once sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHealth returns a Health that is ready while all probes pass.
|
// NewHealth returns a Health that is ready while all probes pass.
|
||||||
func NewHealth(probes map[string]Probe) *Health {
|
func NewHealth(probes map[string]Probe) *Health {
|
||||||
return &Health{probes: probes}
|
return &Health{probes: probes, drained: make(chan struct{})}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Drain makes /readyz fail permanently. Call it before shutdown.
|
// Drain makes /readyz fail permanently. Call it before shutdown.
|
||||||
func (h *Health) Drain() { h.draining.Store(true) }
|
func (h *Health) Drain() {
|
||||||
|
h.draining.Store(true)
|
||||||
|
h.once.Do(func() { close(h.drained) })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draining is closed once Drain is called, so long-running requests can
|
||||||
|
// end early instead of holding up the shutdown.
|
||||||
|
func (h *Health) Draining() <-chan struct{} { return h.drained }
|
||||||
|
|
||||||
// Register mounts /healthz (liveness) and /readyz (readiness).
|
// Register mounts /healthz (liveness) and /readyz (readiness).
|
||||||
func (h *Health) Register(r gin.IRoutes) {
|
func (h *Health) Register(r gin.IRoutes) {
|
||||||
|
|||||||
Reference in new issue
Block a user