281 lines
8.3 KiB
Go
281 lines
8.3 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
|
|
|
|
var allowedCommands = map[string]bool{
|
|
"capacity": true, "capacity-advisor": true, "capacity-limits": true,
|
|
"cluster-profile": true, "doctor-cluster": true, "doctor-edge": true,
|
|
"doctor-gitea": true, "doctor-homelab": true, "doctor-k8s": true,
|
|
"doctor-rpi": true, "explain": true, "inventory-check": true,
|
|
"map": true, "route-inventory": true, "scorecard": true, "status": 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 server struct {
|
|
mu sync.RWMutex
|
|
exec map[string]*execution
|
|
repoRoot string
|
|
token string
|
|
temporal client.Client
|
|
}
|
|
|
|
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")}
|
|
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("/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: 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 {
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
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 = ©
|
|
}
|
|
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 logging(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Printf("%s %s %s\n", time.Now().UTC().Format(time.RFC3339), r.Method, r.URL.Path)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|