package api import ( "bytes" "context" "encoding/json" "net/http" "net/url" "path" "strings" "sync" "time" "github.com/coder/websocket" "github.com/gin-gonic/gin" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) const ( // pagesChannel is the Redis channel announcing organizations whose // status pages changed; uuid.Nil stands for all of them. pagesChannel = "uptimesebi:pages-changed" // streamInFlight bounds the requests of one stream handled at once. streamInFlight = 128 // streamReadLimit bounds a request read from a stream. streamReadLimit = 16 << 20 streamPing = 30 * time.Second // pushFirst and pushEvery pace the page events of one stream: changes // are collected for pushFirst, and a stream gets at most one event per // pushEvery, so a flapping monitor does not have its pages rebuilt // over and over. pushFirst = time.Second pushEvery = 5 * time.Second // drainWait is how long a draining instance lets requests on a stream // finish before closing it. drainWait = 5 * time.Second ) // streamedKey marks requests that arrived over a stream. type streamedKey struct{} // pagesChanged announces that status pages of orgs may look different // now, so status page servers fetch them at once instead of on their next // refresh. Losing the announcement only delays that. func (s *Server) pagesChanged(ctx context.Context, orgs ...uuid.UUID) { if s.rdb == nil { return } for _, org := range orgs { if err := s.rdb.Publish(ctx, pagesChannel, org.String()).Err(); err != nil { s.log.WarnContext(ctx, "announcing changed status pages failed", "org", org, "error", err) return } } } // announcePages is middleware announcing the changed status pages of the // request's organization, or of all with no organization, after every // change made through it. func (s *Server) announcePages() gin.HandlerFunc { return func(c *gin.Context) { c.Next() if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead || c.Writer.Status() >= 400 { return } org := uuid.Nil if p, ok := c.Get(ctxPrincipal); ok { org = p.(*principal).Org.ID } s.pagesChanged(context.WithoutCancel(c.Request.Context()), org) } } // agentStream serves an agent's stream: its requests run through the // agent API as if they had come over HTTP, each authenticated again, and // status page servers get told which of their pages changed. func (s *Server) agentStream(c *gin.Context) { up := c.Request if up.Context().Value(streamedKey{}) != nil || s.handler == nil { fail(c, http.StatusNotFound, "not_found") return } ws, err := websocket.Accept(c.Writer, up, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover}) if err != nil { // Accept has answered the request. return } ws.SetReadLimit(streamReadLimit) a := agentOf(c) ctx, cancel := context.WithCancel(context.WithoutCancel(up.Context())) defer cancel() st := &stream{s: s, ws: ws, up: up.Clone(ctx), ctx: ctx, inflight: map[uint64]context.CancelFunc{}} go st.ping(cancel) if a.Kind == "statuspage" { go s.pushPages(ctx, st, a.OrgID) } if s.draining != nil { go func() { select { case <-s.draining: st.drain() case <-ctx.Done(): } }() } err = st.read() cancel() st.wg.Wait() _ = ws.CloseNow() s.log.DebugContext(ctx, "agent stream closed", "agent", a.ID, "error", err) } // stream is one open agent stream on the API's side. type stream struct { s *Server ws *websocket.Conn up *http.Request ctx context.Context mu sync.Mutex inflight map[uint64]context.CancelFunc draining bool wg sync.WaitGroup } func (st *stream) read() error { for { _, msg, err := st.ws.Read(st.ctx) if err != nil { return err } f, body, err := agentapi.DecodeFrame(msg) if err != nil { continue } st.mu.Lock() if f.Cancel { if cancel := st.inflight[f.ID]; cancel != nil { cancel() } st.mu.Unlock() continue } _, dup := st.inflight[f.ID] refuse := 0 switch { case st.draining: refuse = http.StatusServiceUnavailable case dup || f.ID == 0: refuse = http.StatusBadRequest case len(st.inflight) >= streamInFlight: refuse = http.StatusTooManyRequests } if refuse != 0 { st.mu.Unlock() st.reply(f.ID, refuse, nil, nil) continue } rctx, cancel := context.WithCancel(context.WithValue(st.ctx, streamedKey{}, true)) st.inflight[f.ID] = cancel st.wg.Add(1) st.mu.Unlock() go func() { defer st.wg.Done() defer func() { st.mu.Lock() delete(st.inflight, f.ID) st.mu.Unlock() cancel() }() st.serve(rctx, f, body) }() } } // serve runs one request through the agent API. func (st *stream) serve(ctx context.Context, f agentapi.Frame, body []byte) { u, err := url.Parse(agentapi.Prefix + f.Path) switch { case err != nil, path.Clean(u.Path) != u.Path, !strings.HasPrefix(u.Path, agentapi.Prefix+"/"), u.Path == agentapi.Prefix+agentapi.StreamPath: st.reply(f.ID, http.StatusBadRequest, nil, nil) return } switch f.Method { case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch: default: st.reply(f.ID, http.StatusMethodNotAllowed, nil, nil) return } req, err := http.NewRequestWithContext(ctx, f.Method, u.String(), bytes.NewReader(body)) if err != nil { st.reply(f.ID, http.StatusBadRequest, nil, nil) return } if f.Header != nil { req.Header = f.Header } // Who is asking comes from the stream, never from the request. for _, k := range []string{"Authorization", agentapi.VersionHeader, agentapi.InstanceHeader, agentapi.ReleaseHeader, "X-Forwarded-For", "X-Real-Ip", "X-Forwarded-Proto", "X-Forwarded-Host"} { req.Header.Del(k) if v := st.up.Header.Values(k); len(v) > 0 { req.Header[k] = v } } req.Host, req.RemoteAddr, req.RequestURI = st.up.Host, st.up.RemoteAddr, u.RequestURI() w := &replyWriter{header: http.Header{}} st.s.handler.ServeHTTP(w, req) if w.status == 0 { w.status = http.StatusOK } st.reply(f.ID, w.status, w.header, w.body.Bytes()) if w.status == http.StatusUnauthorized { // The token was revoked: the stream ends with it. _ = st.ws.Close(websocket.StatusPolicyViolation, "unauthenticated") } } func (st *stream) reply(id uint64, status int, h http.Header, body []byte) { st.send(agentapi.Frame{ID: id, Status: status, Header: h}, body) } func (st *stream) send(f agentapi.Frame, body []byte) { ctx, cancel := context.WithTimeout(st.ctx, time.Minute) defer cancel() if err := st.ws.Write(ctx, websocket.MessageBinary, agentapi.EncodeFrame(f, body)); err != nil { _ = st.ws.CloseNow() } } // ping closes streams whose agent stopped answering. func (st *stream) ping(cancel context.CancelFunc) { tick := time.NewTicker(streamPing) defer tick.Stop() for { select { case <-st.ctx.Done(): return case <-tick.C: ctx, stop := context.WithTimeout(st.ctx, streamPing/2) err := st.ws.Ping(ctx) stop() if err != nil { cancel() _ = st.ws.CloseNow() return } } } } // drain refuses new requests, lets those running finish for a while and // closes the stream, so the agent reconnects to another instance. func (st *stream) drain() { st.mu.Lock() st.draining = true st.mu.Unlock() done := make(chan struct{}) go func() { st.wg.Wait(); close(done) }() select { case <-done: case <-time.After(drainWait): case <-st.ctx.Done(): } _ = st.ws.Close(websocket.StatusGoingAway, "instance shutting down") } // pushPages tells a status page server which of its pages changed, for an // organization's server only those of its organization. func (s *Server) pushPages(ctx context.Context, st *stream, agentOrg *uuid.UUID) { sub := s.rdb.Subscribe(ctx, pagesChannel) defer func() { _ = sub.Close() }() msgs := sub.Channel() changed := map[uuid.UUID]bool{} var ( due <-chan time.Time last time.Time ) for { select { case <-ctx.Done(): return case m, ok := <-msgs: if !ok { return } org, err := uuid.Parse(m.Payload) if err != nil || (agentOrg != nil && org != *agentOrg && org != uuid.Nil) { continue } changed[org] = true if due == nil { due = time.After(max(pushFirst, pushEvery-time.Since(last))) } case <-due: due, last = nil, time.Now() refs, err := s.changedPages(ctx, agentOrg, changed) clear(changed) if err != nil { s.log.WarnContext(ctx, "finding changed status pages failed", "error", err) continue } if len(refs) == 0 { continue } body, _ := json.Marshal(agentapi.PagesEvent{Pages: refs}) st.send(agentapi.Frame{Event: agentapi.EventPages}, body) } } } // changedPages lists the pages the server of agentOrg serves of the // organizations changed. func (s *Server) changedPages(ctx context.Context, agentOrg *uuid.UUID, changed map[uuid.UUID]bool) ([]agentapi.PageRef, error) { var rows []store.ServablePagesRow err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error rows, err = q.ServablePages(ctx, agentOrg) return err }) var refs []agentapi.PageRef for _, r := range rows { if changed[uuid.Nil] || changed[r.OrgID] { refs = append(refs, agentapi.PageRef{Slug: r.Slug, Host: r.Host}) } } return refs, err } // replyWriter collects a response to send back over a stream. type replyWriter struct { header http.Header status int body bytes.Buffer } // Header implements http.ResponseWriter. func (w *replyWriter) Header() http.Header { return w.header } // WriteHeader implements http.ResponseWriter. func (w *replyWriter) WriteHeader(status int) { if w.status == 0 { w.status = status } } // Write implements http.ResponseWriter. func (w *replyWriter) Write(b []byte) (int, error) { w.WriteHeader(http.StatusOK) return w.body.Write(b) }