automc: operator UI on AUTOMC_UI_BINDING
Adds a separate HTTP server (not the upstream API on :25590) for the operator dashboard. Single-page UI with two panes: * routes table — current pg-synced mappings, polled every 2s * logs — SSE stream backed by a logrus hook + 500-entry ring buffer Opt-in via AUTOMC_UI_BINDING (e.g. ":8082"); unset = no-op, behaves exactly like upstream. Designed to live behind server-manager's /infra/mc-router/* reverse-proxy. Patch is internal/automc-only, same fork philosophy as the rest — upstream files stay verbatim. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
package automc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// LogEntry is the structured shape pushed to UI subscribers via SSE.
|
||||
type LogEntry struct {
|
||||
Time time.Time `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Msg string `json:"msg"`
|
||||
Attrs string `json:"attrs,omitempty"`
|
||||
}
|
||||
|
||||
// LogBus is a fan-out buffer for logrus entries: a ring of the last N
|
||||
// entries (replayed on connect) + live broadcast to current subscribers.
|
||||
// Identical model to the one in svc-proxy/internal/httpsrv — kept local to
|
||||
// avoid a cross-repo dep on the fork.
|
||||
type LogBus struct {
|
||||
cap int
|
||||
|
||||
mu sync.RWMutex
|
||||
ring []LogEntry
|
||||
next int
|
||||
full bool
|
||||
listeners map[chan LogEntry]struct{}
|
||||
}
|
||||
|
||||
func NewLogBus(capacity int) *LogBus {
|
||||
if capacity <= 0 {
|
||||
capacity = 500
|
||||
}
|
||||
return &LogBus{
|
||||
cap: capacity,
|
||||
ring: make([]LogEntry, capacity),
|
||||
listeners: map[chan LogEntry]struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *LogBus) Push(e LogEntry) {
|
||||
b.mu.Lock()
|
||||
b.ring[b.next] = e
|
||||
b.next = (b.next + 1) % b.cap
|
||||
if b.next == 0 {
|
||||
b.full = true
|
||||
}
|
||||
subs := make([]chan LogEntry, 0, len(b.listeners))
|
||||
for ch := range b.listeners {
|
||||
subs = append(subs, ch)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
for _, ch := range subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *LogBus) Backlog() []LogEntry {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
if !b.full {
|
||||
out := make([]LogEntry, b.next)
|
||||
copy(out, b.ring[:b.next])
|
||||
return out
|
||||
}
|
||||
out := make([]LogEntry, 0, b.cap)
|
||||
out = append(out, b.ring[b.next:]...)
|
||||
out = append(out, b.ring[:b.next]...)
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *LogBus) Subscribe() chan LogEntry {
|
||||
ch := make(chan LogEntry, 32)
|
||||
b.mu.Lock()
|
||||
b.listeners[ch] = struct{}{}
|
||||
b.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *LogBus) Unsubscribe(ch chan LogEntry) {
|
||||
b.mu.Lock()
|
||||
delete(b.listeners, ch)
|
||||
b.mu.Unlock()
|
||||
close(ch)
|
||||
}
|
||||
|
||||
// logrusBusHook adapts the LogBus to logrus's Hook interface. Registered
|
||||
// globally from Wire() so every upstream log emission is captured.
|
||||
type logrusBusHook struct{ bus *LogBus }
|
||||
|
||||
func (h *logrusBusHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
func (h *logrusBusHook) Fire(e *logrus.Entry) error {
|
||||
var attrs string
|
||||
for k, v := range e.Data {
|
||||
if attrs != "" {
|
||||
attrs += " "
|
||||
}
|
||||
attrs += fmt.Sprintf("%s=%v", k, v)
|
||||
}
|
||||
h.bus.Push(LogEntry{
|
||||
Time: e.Time,
|
||||
Level: e.Level.String(),
|
||||
Msg: e.Message,
|
||||
Attrs: attrs,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>mc-router</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1115; --panel: #161922; --panel-2: #1c2030;
|
||||
--border: #2a2f42; --text: #d6d9e0; --muted: #7a8194;
|
||||
--accent: #6aa9ff;
|
||||
--err: #f87171; --warn: #fbbf24; --info: #93c5fd; --dbg: #6b7280;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 0;
|
||||
font: 13px/1.4 ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace;
|
||||
background: var(--bg); color: var(--text);
|
||||
display: grid; grid-template-rows: auto 1fr 1fr; height: 100vh;
|
||||
}
|
||||
header {
|
||||
padding: 10px 16px; border-bottom: 1px solid var(--border);
|
||||
background: var(--panel);
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
h1 { margin: 0; font-size: 14px; font-weight: 600; letter-spacing: 0.5px; }
|
||||
h1 .meta { color: var(--muted); margin-left: 12px; font-weight: normal; }
|
||||
.status { color: var(--muted); font-size: 12px; }
|
||||
.status.ok { color: #4ade80; }
|
||||
.status.err { color: var(--err); }
|
||||
|
||||
section { padding: 12px 16px; overflow: auto; border-bottom: 1px solid var(--border); }
|
||||
section h2 {
|
||||
margin: 0 0 10px; font-size: 12px; text-transform: uppercase;
|
||||
letter-spacing: 0.7px; color: var(--muted); font-weight: 600;
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
section h2 .clear {
|
||||
background: transparent; color: var(--muted); border: 1px solid var(--border);
|
||||
padding: 2px 8px; cursor: pointer; font: inherit; border-radius: 3px;
|
||||
}
|
||||
section h2 .clear:hover { color: var(--text); border-color: var(--accent); }
|
||||
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td {
|
||||
text-align: left; padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
tbody tr:hover { background: var(--panel-2); }
|
||||
.empty { color: var(--muted); padding: 20px; text-align: center; }
|
||||
|
||||
pre.logbox { margin: 0; white-space: pre-wrap; word-break: break-word; max-height: 100%; }
|
||||
.log-line { padding: 1px 0; }
|
||||
.log-line .ts { color: var(--muted); margin-right: 8px; }
|
||||
.log-line .lvl { margin-right: 6px; font-weight: 600; }
|
||||
.log-line.lvl-debug .lvl { color: var(--dbg); }
|
||||
.log-line.lvl-info .lvl { color: var(--info); }
|
||||
.log-line.lvl-warning .lvl, .log-line.lvl-warn .lvl { color: var(--warn); }
|
||||
.log-line.lvl-error .lvl { color: var(--err); }
|
||||
.log-line .attrs { color: var(--muted); margin-left: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>mc-router <span class="meta" id="meta">— connecting…</span></h1>
|
||||
<span class="status" id="status">log stream: connecting</span>
|
||||
</header>
|
||||
|
||||
<section class="routes">
|
||||
<h2><span>Routes <span id="route-count" style="color:var(--muted);"></span></span></h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Server address (host)</th>
|
||||
<th>Backend</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="route-rows"></tbody>
|
||||
</table>
|
||||
<div id="route-empty" class="empty">no routes registered</div>
|
||||
</section>
|
||||
|
||||
<section class="logs">
|
||||
<h2>
|
||||
<span>Logs</span>
|
||||
<button class="clear" onclick="document.getElementById('logbox').innerHTML=''">clear</button>
|
||||
</h2>
|
||||
<pre class="logbox" id="logbox"></pre>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
async function refreshRoutes() {
|
||||
try {
|
||||
const r = await fetch('/api/routes');
|
||||
const j = await r.json();
|
||||
const rows = document.getElementById('route-rows');
|
||||
const empty = document.getElementById('route-empty');
|
||||
const count = document.getElementById('route-count');
|
||||
rows.innerHTML = '';
|
||||
if (!j.routes || j.routes.length === 0) {
|
||||
empty.style.display = '';
|
||||
count.textContent = '';
|
||||
} else {
|
||||
empty.style.display = 'none';
|
||||
count.textContent = '(' + j.routes.length + ')';
|
||||
for (const r of j.routes) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = '<td>' + r.server_address + '</td><td>' + r.backend + '</td>';
|
||||
rows.appendChild(tr);
|
||||
}
|
||||
}
|
||||
document.getElementById('meta').textContent = '— ' + j.routes.length + ' routes';
|
||||
} catch (e) {
|
||||
document.getElementById('meta').textContent = '— api error';
|
||||
}
|
||||
}
|
||||
setInterval(refreshRoutes, 2000);
|
||||
refreshRoutes();
|
||||
|
||||
function startLogStream() {
|
||||
const status = document.getElementById('status');
|
||||
const box = document.getElementById('logbox');
|
||||
const es = new EventSource('/api/logs');
|
||||
es.onopen = () => { status.textContent = 'log stream: live'; status.className = 'status ok'; };
|
||||
es.onerror = () => { status.textContent = 'log stream: reconnecting'; status.className = 'status err'; };
|
||||
es.onmessage = ev => {
|
||||
let e;
|
||||
try { e = JSON.parse(ev.data); } catch { return; }
|
||||
const ts = e.time ? e.time.split('T')[1].split('.')[0] : '';
|
||||
const div = document.createElement('div');
|
||||
const lvl = (e.level || 'info').toLowerCase();
|
||||
div.className = 'log-line lvl-' + lvl;
|
||||
div.innerHTML =
|
||||
'<span class="ts">' + ts + '</span>' +
|
||||
'<span class="lvl">' + (e.level || 'info') + '</span>' +
|
||||
(e.msg || '') +
|
||||
(e.attrs ? '<span class="attrs">' + e.attrs + '</span>' : '');
|
||||
box.appendChild(div);
|
||||
const parent = box.parentElement;
|
||||
if (parent.scrollHeight - parent.scrollTop - parent.clientHeight < 60) {
|
||||
parent.scrollTop = parent.scrollHeight;
|
||||
}
|
||||
while (box.children.length > 1000) box.removeChild(box.firstChild);
|
||||
};
|
||||
}
|
||||
startLogStream();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,119 @@
|
||||
package automc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/itzg/mc-router/server"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
//go:embed static/*
|
||||
var staticFS embed.FS
|
||||
|
||||
// startUI starts a separate HTTP server on uiBinding serving the operator
|
||||
// dashboard (embedded index.html), an SSE log feed, and a JSON snapshot of
|
||||
// the current route table. The upstream JSON API on API_BINDING is left
|
||||
// untouched so existing tooling keeps working.
|
||||
func startUI(ctx context.Context, uiBinding string, bus *LogBus) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
sub, err := fs.Sub(staticFS, "static")
|
||||
if err != nil {
|
||||
logrus.WithError(err).Error("automc ui: embed misconfigured")
|
||||
return
|
||||
}
|
||||
mux.Handle("GET /", http.FileServer(http.FS(sub)))
|
||||
mux.HandleFunc("GET /api/routes", routesSnapshotHandler)
|
||||
mux.HandleFunc("GET /api/logs", sseLogsHandler(bus))
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: uiBinding,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutCtx)
|
||||
}()
|
||||
go func() {
|
||||
logrus.WithField("binding", uiBinding).Info("automc: ui server listening")
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logrus.WithError(err).Error("automc ui server failed")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// RouteSnapshot is one row of the routes table the UI renders. Same shape as
|
||||
// the upstream /routes JSON but flatter — the UI doesn't need both backend
|
||||
// and scalingTarget shown separately.
|
||||
type RouteSnapshot struct {
|
||||
ServerAddress string `json:"server_address"`
|
||||
Backend string `json:"backend"`
|
||||
}
|
||||
|
||||
func routesSnapshotHandler(w http.ResponseWriter, _ *http.Request) {
|
||||
mappings := server.Routes.GetMappings()
|
||||
out := make([]RouteSnapshot, 0, len(mappings))
|
||||
for addr, backend := range mappings {
|
||||
out = append(out, RouteSnapshot{ServerAddress: addr, Backend: backend})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ServerAddress < out[j].ServerAddress })
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"routes": out,
|
||||
"at": time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func sseLogsHandler(bus *LogBus) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
for _, e := range bus.Backlog() {
|
||||
writeSSEEvent(w, e)
|
||||
}
|
||||
flusher.Flush()
|
||||
|
||||
ch := bus.Subscribe()
|
||||
defer bus.Unsubscribe(ch)
|
||||
|
||||
hb := time.NewTicker(30 * time.Second)
|
||||
defer hb.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case e := <-ch:
|
||||
writeSSEEvent(w, e)
|
||||
flusher.Flush()
|
||||
case <-hb.C:
|
||||
_, _ = io.WriteString(w, ":hb\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeSSEEvent(w io.Writer, e LogEntry) {
|
||||
fmt.Fprintf(w, "data: {\"time\":%q,\"level\":%q,\"msg\":%q,\"attrs\":%q}\n\n",
|
||||
e.Time.Format(time.RFC3339Nano), e.Level, e.Msg, e.Attrs)
|
||||
}
|
||||
@@ -20,5 +20,14 @@ func Wire(ctx context.Context) error {
|
||||
s := newSyncer(dsn, waker)
|
||||
go s.run(ctx)
|
||||
logrus.Info("automc: pg route sync started")
|
||||
|
||||
// Operator UI on a separate port — upstream's API_BINDING stays
|
||||
// JSON-only and untouched. Enable by setting AUTOMC_UI_BINDING (e.g.
|
||||
// ":8082"); leave unset to skip and behave exactly like upstream.
|
||||
if uiBinding := os.Getenv("AUTOMC_UI_BINDING"); uiBinding != "" {
|
||||
bus := NewLogBus(500)
|
||||
logrus.AddHook(&logrusBusHook{bus: bus})
|
||||
startUI(ctx, uiBinding, bus)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user