my-homelab-configs/cmd/jeannie-server/main.go

420 lines
14 KiB
Go

package main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"go.temporal.io/sdk/client"
"my-homelab-configs/internal/jeannieworkflow"
)
const maxOutputBytes = 1 << 20
// allowedCommands is the remote API command boundary. Keep this list aligned
// with the public top-level cases in ./jeannie. Internal __up-task and the
// recursive remote command are intentionally excluded.
var allowedCommands = map[string]bool{
"help": true, "up": true, "plan": true,
"cluster-profile": true, "rebuild-cluster": true, "stop-cluster": true,
"start-cluster": true, "cleanup-debian-k8s": true,
"status": true, "capacity": true, "capacity-advisor": true,
"capacity-limits": true, "recover-plan": true, "gitops-status": true,
"gitops": true,
"storage": true,
"mesh": true,
"platform": true, "edge": true, "edge-cache-flush": true,
"promote": true, "cert-check": true, "release-snapshot": true,
"backup-status": true, "synthetic-checks": true, "resource-budget": true,
"control-plane": true, "artifact-cache": true,
"blockchain-devnet": true, "blockchain-test": true,
"blockchain-wallet": true, "golden-ledger": true,
"route-inventory": true, "explain": true, "recover-power": true,
"heal": true, "self-heal": true, "incident": true,
"safety-case": true, "agent-sandbox": true, "scorecard": true,
"grafana-dashboards": true, "sso-grafana": true, "sso-gitea": true,
"sso": true, "dex-secret": true, "gitea-runner-secret": true,
"workers": true, "change-journal": true, "map": true,
"validate": true, "access-audit": true, "kubeconfig-readonly": true,
"apps": true, "website-translation-model": true,
"website-ollama-listen": true, "ollama-setup": true,
"deploy-gitea": true, "deploy-api": true, "deploy-heimdall": true,
"deploy-dex": true, "deploy-matrix": true, "deploy-ai-stack": true,
"deploy-office": true,
"deploy-ai-tools": true, "deploy-omniroute": true, "deploy-hermes": true,
"rpi-services": true, "bootstrap-gitea-repo": true, "backup-gitea": true,
"backup": true, "drill-restore": true, "drill-gitea-restore": true,
"drill-pihole-restore": true, "install-gitea-runner": true,
"move-prometheus-stack-workers": true, "doctor-versions": true,
"doctor-edge": true, "doctor-homelab": true, "doctor-gitea": true,
"doctor-rpi": true, "doctor-cluster": true, "doctor-k8s": true,
"preflight": true, "doctor-preapply": true, "inventory-check": true,
"state-backup": true, "fix-debian-docker-root": true,
"secrets-init": true, "secrets-check": true, "tailnet-policy-check": true,
"ai-index": true, "ai-check": true, "ask": true, "ai-evals": true,
"ai-scheduler": true, "ai-memory": true, "model-observe": true,
"impact": true, "review-last-change": true,
"security-scan": true, "security-prepare": true, "security-zap": true,
"security-k8s": true, "security-host": true, "security-trivy": true,
"security-secrets": true, "security-nuclei": true, "security-web": true,
"security-logs": true, "security-runtime": true,
"security-attack-path": true, "prompt-injection-lab": true,
"red-blue": true, "openwrt": true, "nuke": true,
}
type executeRequest struct {
Command string `json:"command"`
Args []string `json:"args,omitempty"`
}
type execution struct {
ID string `json:"id"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Status string `json:"status"`
Output string `json:"output,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
Error string `json:"error,omitempty"`
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
}
type requestMetric struct {
count uint64
totalDuration time.Duration
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(body []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(body)
}
type server struct {
mu sync.RWMutex
exec map[string]*execution
repoRoot string
token string
temporal client.Client
requests map[string]*requestMetric
authFailures uint64
}
func main() {
root := os.Getenv("JEANNIE_SERVER_REPO_ROOT")
if root == "" {
root, _ = os.Getwd()
}
root, _ = filepath.Abs(root)
s := &server{
exec: make(map[string]*execution),
repoRoot: root,
token: os.Getenv("JEANNIE_SERVER_TOKEN"),
requests: make(map[string]*requestMetric),
}
if os.Getenv("JEANNIE_EXECUTION_MODE") == "temporal" {
address := os.Getenv("JEANNIE_TEMPORAL_ADDRESS")
if address == "" {
address = "127.0.0.1:7233"
}
var err error
s.temporal, err = client.Dial(client.Options{HostPort: address})
if err != nil {
fmt.Fprintf(os.Stderr, "connect to Temporal: %v\n", err)
os.Exit(2)
}
defer s.temporal.Close()
}
mux := http.NewServeMux()
mux.HandleFunc("/v1/health", s.auth(s.health))
mux.HandleFunc("/metrics", s.auth(s.metrics))
mux.HandleFunc("/v1/commands", s.auth(s.commands))
mux.HandleFunc("/v1/execute", s.auth(s.execute))
mux.HandleFunc("/v1/executions/", s.auth(s.execution))
addr := os.Getenv("JEANNIE_SERVER_ADDR")
if addr == "" {
addr = "127.0.0.1:8787"
}
if os.Getenv("JEANNIE_SERVER_TOKEN") == "" && !strings.HasPrefix(addr, "127.0.0.1:") && !strings.HasPrefix(addr, "localhost:") {
fmt.Fprintln(os.Stderr, "JEANNIE_SERVER_TOKEN is required when the API is not loopback-bound")
os.Exit(2)
}
httpServer := &http.Server{Addr: addr, Handler: s.logging(mux), ReadHeaderTimeout: 5 * time.Second}
fmt.Printf("Jeannie API listening on %s\n", addr)
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func (s *server) auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.token != "" && r.Header.Get("Authorization") != "Bearer "+s.token {
s.mu.Lock()
s.authFailures++
s.mu.Unlock()
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return
}
next(w, r)
}
}
func (s *server) metrics(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
s.mu.RLock()
defer s.mu.RUnlock()
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
fmt.Fprintln(w, "# HELP jeannie_http_requests_total Total HTTP requests handled by Jeannie.")
fmt.Fprintln(w, "# TYPE jeannie_http_requests_total counter")
for key, metric := range s.requests {
parts := strings.SplitN(key, "|", 3)
if len(parts) != 3 {
continue
}
method, path, status := parts[0], parts[1], parts[2]
fmt.Fprintf(w, "jeannie_http_requests_total{method=%q,path=%q,status=%q} %d\n", method, path, status, metric.count)
}
fmt.Fprintln(w, "# HELP jeannie_http_request_duration_seconds_sum Total HTTP request duration in seconds.")
fmt.Fprintln(w, "# TYPE jeannie_http_request_duration_seconds_sum counter")
for key, metric := range s.requests {
parts := strings.SplitN(key, "|", 3)
if len(parts) != 3 {
continue
}
method, path, status := parts[0], parts[1], parts[2]
fmt.Fprintf(w, "jeannie_http_request_duration_seconds_sum{method=%q,path=%q,status=%q} %f\n", method, path, status, metric.totalDuration.Seconds())
}
fmt.Fprintln(w, "# HELP jeannie_http_request_duration_seconds_count Number of HTTP requests observed for duration tracking.")
fmt.Fprintln(w, "# TYPE jeannie_http_request_duration_seconds_count counter")
for key, metric := range s.requests {
parts := strings.SplitN(key, "|", 3)
if len(parts) != 3 {
continue
}
method, path, status := parts[0], parts[1], parts[2]
fmt.Fprintf(w, "jeannie_http_request_duration_seconds_count{method=%q,path=%q,status=%q} %d\n", method, path, status, metric.count)
}
fmt.Fprintln(w, "# HELP jeannie_auth_failures_total Total rejected authentication attempts.")
fmt.Fprintln(w, "# TYPE jeannie_auth_failures_total counter")
fmt.Fprintf(w, "jeannie_auth_failures_total %d\n", s.authFailures)
}
func (s *server) health(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (s *server) commands(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
commands := make([]string, 0, len(allowedCommands))
for command := range allowedCommands {
commands = append(commands, command)
}
sort.Strings(commands)
writeJSON(w, http.StatusOK, map[string]any{"commands": commands})
}
func (s *server) execute(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
var request executeRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
request.Command = strings.TrimSpace(request.Command)
if !allowedCommands[request.Command] {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "command is not remotely enabled"})
return
}
item := &execution{ID: newID(), Command: request.Command, Args: request.Args, Status: "queued", StartedAt: time.Now().UTC()}
s.mu.Lock()
s.exec[item.ID] = item
s.mu.Unlock()
go s.run(item)
writeJSON(w, http.StatusAccepted, item)
}
func (s *server) run(item *execution) {
if s.temporal != nil {
s.runTemporal(item)
return
}
s.update(item.ID, func(item *execution) { item.Status = "running" })
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
args := append([]string{item.Command}, item.Args...)
command := exec.CommandContext(ctx, filepath.Join(s.repoRoot, "jeannie"), args...)
command.Dir = s.repoRoot
command.Env = append(os.Environ(), "JEANNIE_REMOTE_SERVER=true")
output, err := command.CombinedOutput()
if len(output) > maxOutputBytes {
output = append(output[:maxOutputBytes], []byte("\n[output truncated]\n")...)
}
ended := time.Now().UTC()
s.update(item.ID, func(item *execution) {
item.Output, item.EndedAt, item.Status = redact(string(output)), &ended, "succeeded"
if err == nil {
return
}
item.Status, item.Error, item.ExitCode = "failed", err.Error(), 1
if exitErr, ok := err.(*exec.ExitError); ok {
item.ExitCode = exitErr.ExitCode()
}
})
}
func (s *server) runTemporal(item *execution) {
s.update(item.ID, func(item *execution) { item.Status = "running" })
taskQueue := os.Getenv("JEANNIE_TEMPORAL_TASK_QUEUE")
if taskQueue == "" {
taskQueue = jeannieworkflow.TaskQueue
}
workflowID := "jeannie-" + item.ID
workflowRun, err := s.temporal.ExecuteWorkflow(context.Background(), client.StartWorkflowOptions{
ID: workflowID,
TaskQueue: taskQueue,
}, jeannieworkflow.Workflow, jeannieworkflow.CommandInput{
RepoRoot: s.repoRoot,
Command: item.Command,
Args: item.Args,
})
if err != nil {
s.finish(item.ID, "", 1, err)
return
}
var result jeannieworkflow.CommandResult
err = workflowRun.Get(context.Background(), &result)
if err != nil {
s.finish(item.ID, result.Output, 1, err)
return
}
if result.ExitCode != 0 {
s.finish(item.ID, result.Output, result.ExitCode, fmt.Errorf("remote command exited with status %d", result.ExitCode))
return
}
s.finish(item.ID, result.Output, 0, nil)
}
func (s *server) finish(id, output string, exitCode int, err error) {
ended := time.Now().UTC()
s.update(id, func(item *execution) {
item.Output, item.EndedAt, item.Status, item.ExitCode = redact(output), &ended, "succeeded", exitCode
if err != nil {
item.Status, item.Error = "failed", err.Error()
}
})
}
func (s *server) execution(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
id := strings.TrimPrefix(r.URL.Path, "/v1/executions/")
s.mu.RLock()
item, ok := s.exec[id]
if ok {
copy := *item
item = &copy
}
s.mu.RUnlock()
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "execution not found"})
return
}
writeJSON(w, http.StatusOK, item)
}
func (s *server) update(id string, fn func(*execution)) {
s.mu.Lock()
defer s.mu.Unlock()
if item, ok := s.exec[id]; ok {
fn(item)
}
}
func newID() string {
var data [16]byte
if _, err := rand.Read(data[:]); err != nil {
return fmt.Sprintf("execution-%d", time.Now().UnixNano())
}
return hex.EncodeToString(data[:])
}
func redact(value string) string {
for _, key := range []string{"JEANNIE_SERVER_TOKEN", "OPENROUTER_API_KEY", "NVIDIA_API_KEY"} {
if secret := os.Getenv(key); secret != "" {
value = strings.ReplaceAll(value, secret, "[REDACTED]")
}
}
return value
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func (s *server) logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
capture := &statusWriter{ResponseWriter: w}
fmt.Printf("%s %s %s\n", time.Now().UTC().Format(time.RFC3339), r.Method, r.URL.Path)
next.ServeHTTP(capture, r)
status := capture.status
if status == 0 {
status = http.StatusOK
}
path := r.URL.Path
if strings.HasPrefix(path, "/v1/executions/") {
path = "/v1/executions/:id"
}
key := fmt.Sprintf("%s|%s|%d", r.Method, path, status)
s.mu.Lock()
metric := s.requests[key]
if metric == nil {
metric = &requestMetric{}
s.requests[key] = metric
}
metric.count++
metric.totalDuration += time.Since(started)
s.mu.Unlock()
})
}