2023-04-24 20:52:12 +02:00
|
|
|
package queue
|
|
|
|
|
|
|
|
import (
|
2024-09-27 10:09:25 +02:00
|
|
|
"bytes"
|
2023-04-24 20:52:12 +02:00
|
|
|
"context"
|
|
|
|
"fmt"
|
2023-06-13 03:57:13 +02:00
|
|
|
"html/template"
|
2024-09-27 10:09:25 +02:00
|
|
|
"io"
|
2023-06-30 18:26:27 +02:00
|
|
|
"math/rand"
|
2023-04-24 20:52:12 +02:00
|
|
|
"net/http"
|
2023-06-13 03:57:13 +02:00
|
|
|
"path/filepath"
|
2023-07-05 21:35:21 +02:00
|
|
|
"strconv"
|
2023-06-13 03:57:13 +02:00
|
|
|
"sync"
|
2023-04-24 20:52:12 +02:00
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"forge.cadoles.com/Cadoles/go-proxy"
|
2023-07-05 21:54:01 +02:00
|
|
|
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
|
2023-04-24 20:52:12 +02:00
|
|
|
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
|
|
|
|
"forge.cadoles.com/cadoles/bouncer/internal/store"
|
2023-06-13 03:57:13 +02:00
|
|
|
"github.com/Masterminds/sprig/v3"
|
2023-04-24 20:52:12 +02:00
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/pkg/errors"
|
2023-06-30 18:26:27 +02:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2023-04-24 20:52:12 +02:00
|
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
const LayerType store.LayerType = "queue"
|
|
|
|
|
|
|
|
type Queue struct {
|
2023-06-13 03:57:13 +02:00
|
|
|
adapter Adapter
|
|
|
|
|
|
|
|
defaultKeepAlive time.Duration
|
|
|
|
|
|
|
|
templateDir string
|
|
|
|
loadOnce sync.Once
|
|
|
|
tmpl *template.Template
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
refreshJobRunning uint32
|
|
|
|
updateMetricsJobRunning uint32
|
|
|
|
postKeepAliveDebouncer *DebouncerMap
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// LayerType implements director.MiddlewareLayer
|
|
|
|
func (q *Queue) LayerType() store.LayerType {
|
|
|
|
return LayerType
|
|
|
|
}
|
|
|
|
|
|
|
|
// Middleware implements director.MiddlewareLayer
|
|
|
|
func (q *Queue) Middleware(layer *store.Layer) proxy.Middleware {
|
|
|
|
return func(h http.Handler) http.Handler {
|
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
2023-06-13 03:57:13 +02:00
|
|
|
options, err := fromStoreOptions(layer.Options, q.defaultKeepAlive)
|
2023-04-24 20:52:12 +02:00
|
|
|
if err != nil {
|
2024-11-08 11:07:19 +01:00
|
|
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not parse layer options"))
|
2023-04-24 20:52:12 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-07-05 21:54:01 +02:00
|
|
|
matches := wildcard.MatchAny(r.URL.String(), options.MatchURLs...)
|
|
|
|
if !matches {
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-23 10:34:24 +02:00
|
|
|
defer q.updateMetrics(layer.Proxy, layer.Name, options)
|
2023-06-30 18:26:27 +02:00
|
|
|
|
2023-04-24 20:52:12 +02:00
|
|
|
cookieName := q.getCookieName(layer.Name)
|
|
|
|
|
|
|
|
cookie, err := r.Cookie(cookieName)
|
|
|
|
if err != nil && !errors.Is(err, http.ErrNoCookie) {
|
2024-09-27 10:15:08 +02:00
|
|
|
logger.Error(ctx, "could not retrieve cookie", logger.CapturedE(errors.WithStack(err)))
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if cookie == nil {
|
|
|
|
cookie = &http.Cookie{
|
|
|
|
Name: cookieName,
|
|
|
|
Value: uuid.NewString(),
|
|
|
|
Path: "/",
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Add("Set-Cookie", cookie.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
sessionID := cookie.Value
|
|
|
|
queueName := string(layer.Name)
|
|
|
|
|
|
|
|
rank, err := q.adapter.Touch(ctx, queueName, sessionID)
|
|
|
|
if err != nil {
|
2024-11-08 11:07:19 +01:00
|
|
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not update queue session rank"))
|
2023-04-24 20:52:12 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if rank >= options.Capacity {
|
|
|
|
q.renderQueuePage(w, r, queueName, options, rank)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx = logger.With(ctx,
|
|
|
|
logger.F("queueSessionId", sessionID),
|
|
|
|
logger.F("queueName", queueName),
|
|
|
|
logger.F("queueSessionRank", rank),
|
|
|
|
)
|
|
|
|
r = r.WithContext(ctx)
|
|
|
|
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.HandlerFunc(fn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
func (q *Queue) updateSessionsMetric(ctx context.Context, proxyName store.ProxyName, layerName store.LayerName) {
|
|
|
|
if !atomic.CompareAndSwapUint32(&q.updateMetricsJobRunning, 0, 1) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer atomic.StoreUint32(&q.updateMetricsJobRunning, 0)
|
|
|
|
|
|
|
|
queueName := string(layerName)
|
|
|
|
|
|
|
|
status, err := q.adapter.Status(ctx, queueName)
|
|
|
|
if err != nil {
|
2024-09-27 10:15:08 +02:00
|
|
|
logger.Error(ctx, "could not retrieve queue status", logger.CapturedE(errors.WithStack(err)))
|
2023-06-30 18:26:27 +02:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
metricQueueSessions.With(
|
|
|
|
prometheus.Labels{
|
|
|
|
metricLabelLayer: string(layerName),
|
|
|
|
metricLabelProxy: string(proxyName),
|
|
|
|
},
|
|
|
|
).Set(float64(status.Sessions))
|
|
|
|
}
|
|
|
|
|
2023-04-24 20:52:12 +02:00
|
|
|
func (q *Queue) renderQueuePage(w http.ResponseWriter, r *http.Request, queueName string, options *LayerOptions, rank int64) {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
|
|
|
status, err := q.adapter.Status(ctx, queueName)
|
|
|
|
if err != nil {
|
2024-11-08 11:07:19 +01:00
|
|
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not retrieve queue status"))
|
2023-04-24 20:52:12 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-13 03:57:13 +02:00
|
|
|
q.loadOnce.Do(func() {
|
|
|
|
pattern := filepath.Join(q.templateDir, "*.gohtml")
|
|
|
|
|
|
|
|
logger.Info(ctx, "loading queue page templates", logger.F("pattern", pattern))
|
|
|
|
|
|
|
|
tmpl, err := template.New("").Funcs(sprig.FuncMap()).ParseGlob(pattern)
|
|
|
|
if err != nil {
|
2024-09-27 10:15:08 +02:00
|
|
|
logger.Error(ctx, "could not load queue templates", logger.CapturedE(errors.WithStack(err)))
|
2023-06-13 03:57:13 +02:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
q.tmpl = tmpl
|
|
|
|
})
|
|
|
|
|
|
|
|
if q.tmpl == nil {
|
2024-09-27 10:09:25 +02:00
|
|
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.New("queue page templates not loaded"))
|
2023-06-13 03:57:13 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
refreshRate := time.Duration(int64(options.KeepAlive.Seconds()/2)) * time.Second
|
|
|
|
|
2023-06-13 03:57:13 +02:00
|
|
|
templateData := struct {
|
|
|
|
QueueName string
|
|
|
|
LayerOptions *LayerOptions
|
|
|
|
Rank int64
|
|
|
|
CurrentSessions int64
|
|
|
|
MaxSessions int64
|
2023-06-30 18:26:27 +02:00
|
|
|
RefreshRate time.Duration
|
2023-06-13 03:57:13 +02:00
|
|
|
}{
|
|
|
|
QueueName: queueName,
|
|
|
|
LayerOptions: options,
|
|
|
|
Rank: rank + 1,
|
|
|
|
CurrentSessions: status.Sessions,
|
|
|
|
MaxSessions: options.Capacity,
|
2023-06-30 18:26:27 +02:00
|
|
|
RefreshRate: refreshRate,
|
2023-06-13 03:57:13 +02:00
|
|
|
}
|
|
|
|
|
2023-07-05 21:35:21 +02:00
|
|
|
w.Header().Add("Cache-Control", "no-cache")
|
|
|
|
w.Header().Add("Retry-After", strconv.FormatInt(int64(refreshRate.Seconds()), 10))
|
2023-06-13 03:57:13 +02:00
|
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
|
|
|
2024-09-27 10:09:25 +02:00
|
|
|
var buf bytes.Buffer
|
2023-06-13 03:57:13 +02:00
|
|
|
|
2024-09-27 10:09:25 +02:00
|
|
|
if err := q.tmpl.ExecuteTemplate(&buf, "queue", templateData); err != nil {
|
2024-11-08 11:07:19 +01:00
|
|
|
director.HandleError(ctx, w, r, http.StatusInternalServerError, errors.Wrap(err, "could not render queue page"))
|
2023-06-13 03:57:13 +02:00
|
|
|
return
|
|
|
|
}
|
2024-09-27 10:09:25 +02:00
|
|
|
|
|
|
|
if _, err := io.Copy(w, &buf); err != nil {
|
|
|
|
logger.Error(ctx, "could not write queue page", logger.CapturedE(errors.WithStack(err)))
|
|
|
|
}
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
func (q *Queue) refreshQueue(ctx context.Context, layerName store.LayerName, keepAlive time.Duration) {
|
2023-04-24 20:52:12 +02:00
|
|
|
if !atomic.CompareAndSwapUint32(&q.refreshJobRunning, 0, 1) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
defer atomic.StoreUint32(&q.refreshJobRunning, 0)
|
2023-04-24 20:52:12 +02:00
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
if err := q.adapter.Refresh(ctx, string(layerName), keepAlive); err != nil {
|
|
|
|
logger.Error(ctx, "could not refresh queue",
|
2024-09-27 10:15:08 +02:00
|
|
|
logger.CapturedE(errors.WithStack(err)),
|
2023-06-30 18:26:27 +02:00
|
|
|
logger.F("queue", layerName),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2023-04-24 20:52:12 +02:00
|
|
|
|
2024-09-23 10:34:24 +02:00
|
|
|
func (q *Queue) updateMetrics(proxyName store.ProxyName, layerName store.LayerName, options *LayerOptions) {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
2023-06-30 18:26:27 +02:00
|
|
|
// Update queue capacity metric
|
|
|
|
metricQueueCapacity.With(
|
|
|
|
prometheus.Labels{
|
|
|
|
metricLabelLayer: string(layerName),
|
|
|
|
metricLabelProxy: string(proxyName),
|
|
|
|
},
|
|
|
|
).Set(float64(options.Capacity))
|
|
|
|
|
|
|
|
// Refresh queue data and metrics
|
|
|
|
q.refreshQueue(ctx, layerName, options.KeepAlive)
|
|
|
|
q.updateSessionsMetric(ctx, proxyName, layerName)
|
|
|
|
|
|
|
|
// (Re)schedule an update job after session ttl + semi-random time padding
|
|
|
|
// to update metrics after last session expiration
|
|
|
|
randDuration := rand.Int63n(int64(options.KeepAlive))
|
|
|
|
timePadding := options.KeepAlive/2 + time.Duration(randDuration)
|
|
|
|
after := options.KeepAlive + timePadding
|
|
|
|
|
|
|
|
debouncingKey := fmt.Sprintf("%s/%s", proxyName, layerName)
|
|
|
|
|
|
|
|
q.postKeepAliveDebouncer.Do(debouncingKey, after, func() {
|
|
|
|
ctx := logger.With(
|
|
|
|
context.Background(),
|
|
|
|
logger.F("proxy", proxyName),
|
|
|
|
logger.F("layer", layerName),
|
|
|
|
logger.F("after", after),
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.Info(ctx, "running post keep alive refresh job")
|
|
|
|
|
|
|
|
q.refreshQueue(ctx, layerName, options.KeepAlive)
|
|
|
|
q.updateSessionsMetric(ctx, proxyName, layerName)
|
|
|
|
})
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (q *Queue) getCookieName(layerName store.LayerName) string {
|
2024-04-12 16:41:11 +02:00
|
|
|
return fmt.Sprintf("_bouncer_%s_%s", LayerType, layerName)
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func New(adapter Adapter, funcs ...OptionFunc) *Queue {
|
|
|
|
opts := defaultOptions()
|
|
|
|
for _, fn := range funcs {
|
|
|
|
fn(opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Queue{
|
2023-06-30 18:26:27 +02:00
|
|
|
adapter: adapter,
|
|
|
|
templateDir: opts.TemplateDir,
|
|
|
|
defaultKeepAlive: opts.DefaultKeepAlive,
|
|
|
|
postKeepAliveDebouncer: NewDebouncerMap(),
|
2023-04-24 20:52:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ director.MiddlewareLayer = &Queue{}
|