2352 lines
64 KiB
Go
2352 lines
64 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"runtime"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
"github.com/klipperanywhere/klipperanywhere/internal/protocol"
|
|
)
|
|
|
|
var agentVersion = "dev"
|
|
|
|
const (
|
|
normalHeartbeatInterval = 15 * time.Second
|
|
activePrintHeartbeatInterval = 2 * time.Second
|
|
moonrakerSubscriptionStartupTimeout = 5 * time.Second
|
|
)
|
|
|
|
const defaultStateFile = "/var/lib/klipperanywhere/agent-state.json"
|
|
|
|
type config struct {
|
|
ServerURL string `json:"server_url"`
|
|
PrinterID string `json:"printer_id"`
|
|
Token string `json:"token"`
|
|
MoonrakerURL string `json:"moonraker_url"`
|
|
ControlMode string `json:"control_mode"`
|
|
UIURL string `json:"ui_url"`
|
|
UIAutoDetect *bool `json:"ui_auto_detect"`
|
|
StateFile string `json:"state_file"`
|
|
Cameras []cameraConfig `json:"cameras"`
|
|
}
|
|
|
|
type cameraConfig struct {
|
|
Name string `json:"name"`
|
|
SnapshotURL string `json:"snapshot_url"`
|
|
StreamURL string `json:"stream_url"`
|
|
Source string `json:"source"`
|
|
Service string `json:"service"`
|
|
Location string `json:"location"`
|
|
AspectRatio string `json:"aspect_ratio"`
|
|
Rotation int `json:"rotation"`
|
|
FlipHorizontal bool `json:"flip_horizontal"`
|
|
FlipVertical bool `json:"flip_vertical"`
|
|
}
|
|
|
|
type cameraStore struct {
|
|
mu sync.RWMutex
|
|
cameras []cameraConfig
|
|
}
|
|
|
|
type uiTarget struct {
|
|
URL *url.URL
|
|
Source string
|
|
Reachable bool
|
|
}
|
|
|
|
type runtimeState struct {
|
|
mu sync.RWMutex
|
|
uiURL string
|
|
uiAutoDetect bool
|
|
controlMode string
|
|
ui *uiTarget
|
|
}
|
|
|
|
type moonrakerStatusCache struct {
|
|
mu sync.Mutex
|
|
status map[string]any
|
|
key string
|
|
updatedAt time.Time
|
|
lastLogAt time.Time
|
|
}
|
|
|
|
type wsStore struct {
|
|
mu sync.Mutex
|
|
conns map[string]*websocket.Conn
|
|
}
|
|
|
|
type agentStatusRecord struct {
|
|
PrinterID string `json:"printer_id"`
|
|
ServerURL string `json:"server_url"`
|
|
MoonrakerURL string `json:"moonraker_url"`
|
|
AgentVersion string `json:"agent_version,omitempty"`
|
|
ControlMode string `json:"control_mode"`
|
|
UIURL string `json:"ui_url,omitempty"`
|
|
UIAutoDetect bool `json:"ui_auto_detect"`
|
|
UIReachable bool `json:"ui_reachable"`
|
|
UISource string `json:"ui_source,omitempty"`
|
|
MoonrakerReachable bool `json:"moonraker_reachable"`
|
|
MoonrakerState string `json:"moonraker_state,omitempty"`
|
|
MoonrakerMessage string `json:"moonraker_message,omitempty"`
|
|
PrintStatus *protocol.PrintStatus `json:"print_status,omitempty"`
|
|
LastHeartbeatAt time.Time `json:"last_heartbeat_at"`
|
|
LastSyncAt time.Time `json:"last_sync_at,omitempty"`
|
|
LastSyncDetail string `json:"last_sync_detail,omitempty"`
|
|
Cameras []cameraConfig `json:"cameras,omitempty"`
|
|
}
|
|
|
|
type agentStatusStore struct {
|
|
path string
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func newAgentStatusStore(path string) *agentStatusStore {
|
|
if path == "" {
|
|
path = defaultStateFile
|
|
}
|
|
return &agentStatusStore{path: path}
|
|
}
|
|
|
|
func (s *agentStatusStore) recordHeartbeat(record agentStatusRecord) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
current, err := s.readLocked()
|
|
if err == nil {
|
|
record.LastSyncAt = current.LastSyncAt
|
|
record.LastSyncDetail = current.LastSyncDetail
|
|
}
|
|
return s.writeLocked(record)
|
|
}
|
|
|
|
func (s *agentStatusStore) recordSync(record agentStatusRecord) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
current, err := s.readLocked()
|
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
if current.PrinterID != "" {
|
|
record.LastHeartbeatAt = current.LastHeartbeatAt
|
|
record.Cameras = current.Cameras
|
|
record.MoonrakerReachable = current.MoonrakerReachable
|
|
record.MoonrakerState = current.MoonrakerState
|
|
record.MoonrakerMessage = current.MoonrakerMessage
|
|
record.PrintStatus = current.PrintStatus
|
|
record.UIReachable = current.UIReachable
|
|
record.UISource = current.UISource
|
|
if record.PrinterID == "" {
|
|
record.PrinterID = current.PrinterID
|
|
}
|
|
if record.ServerURL == "" {
|
|
record.ServerURL = current.ServerURL
|
|
}
|
|
if record.MoonrakerURL == "" {
|
|
record.MoonrakerURL = current.MoonrakerURL
|
|
}
|
|
}
|
|
return s.writeLocked(record)
|
|
}
|
|
|
|
func (s *agentStatusStore) read() (agentStatusRecord, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.readLocked()
|
|
}
|
|
|
|
func (s *agentStatusStore) writeLocked(record agentStatusRecord) error {
|
|
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
|
|
return err
|
|
}
|
|
encoded, err := json.MarshalIndent(record, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
encoded = append(encoded, '\n')
|
|
return os.WriteFile(s.path, encoded, 0o600)
|
|
}
|
|
|
|
func (s *agentStatusStore) readLocked() (agentStatusRecord, error) {
|
|
data, err := os.ReadFile(s.path)
|
|
if err != nil {
|
|
return agentStatusRecord{}, err
|
|
}
|
|
var record agentStatusRecord
|
|
if err := json.Unmarshal(data, &record); err != nil {
|
|
return agentStatusRecord{}, err
|
|
}
|
|
return record, nil
|
|
}
|
|
|
|
func main() {
|
|
cfg := config{
|
|
ServerURL: "ws://127.0.0.1:8080/agent/tunnel",
|
|
PrinterID: "test",
|
|
Token: "dev-token",
|
|
MoonrakerURL: "http://127.0.0.1:7125",
|
|
ControlMode: "readonly",
|
|
StateFile: defaultStateFile,
|
|
}
|
|
args := os.Args[1:]
|
|
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
|
|
switch args[0] {
|
|
case "version":
|
|
fmt.Println(agentVersion)
|
|
return
|
|
case "status":
|
|
if err := runStatus(args[1:], cfg); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return
|
|
case "rollback-watchdog":
|
|
if err := runRollbackWatchdog(args[1:]); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return
|
|
case "run":
|
|
args = args[1:]
|
|
}
|
|
}
|
|
|
|
runCfg, err := parseRunConfig(args, cfg)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
baseURL, err := url.Parse(runCfg.MoonrakerURL)
|
|
if err != nil {
|
|
log.Fatalf("invalid moonraker URL: %v", err)
|
|
}
|
|
tunnelURL, err := withAuthQuery(runCfg.ServerURL, runCfg.PrinterID, runCfg.Token)
|
|
if err != nil {
|
|
log.Fatalf("invalid server URL: %v", err)
|
|
}
|
|
stop := make(chan os.Signal, 1)
|
|
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
|
backoff := 3 * time.Second
|
|
for {
|
|
err := run(tunnelURL, baseURL, runCfg.UIURL, *runCfg.UIAutoDetect, runCfg.ControlMode, runCfg.Cameras, runCfg.StateFile, runCfg.PrinterID, runCfg.ServerURL, stop)
|
|
if err == nil {
|
|
return
|
|
}
|
|
|
|
log.Printf("tunnel stopped: %v; reconnecting in %s", err, backoff)
|
|
select {
|
|
case <-time.After(backoff):
|
|
case <-stop:
|
|
return
|
|
}
|
|
if backoff < 30*time.Second {
|
|
backoff *= 2
|
|
if backoff > 30*time.Second {
|
|
backoff = 30 * time.Second
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func parseRunConfig(args []string, defaults config) (config, error) {
|
|
fs := flag.NewFlagSet("klipperanywhere-agent", flag.ContinueOnError)
|
|
var configPath string
|
|
var serverURLOverride string
|
|
var printerIDOverride string
|
|
var tokenOverride string
|
|
var moonrakerURLOverride string
|
|
var stateFileOverride string
|
|
|
|
fs.StringVar(&configPath, "config", "", "path to agent JSON config file")
|
|
fs.StringVar(&serverURLOverride, "server", "", "server tunnel URL")
|
|
fs.StringVar(&printerIDOverride, "printer-id", "", "printer id registered on the server")
|
|
fs.StringVar(&tokenOverride, "token", "", "agent token")
|
|
fs.StringVar(&moonrakerURLOverride, "moonraker", "", "local Moonraker base URL")
|
|
fs.StringVar(&stateFileOverride, "state-file", "", "path to the local agent state file")
|
|
if err := fs.Parse(args); err != nil {
|
|
return config{}, err
|
|
}
|
|
|
|
cfg := defaults
|
|
if configPath != "" {
|
|
fileCfg, err := loadConfig(configPath)
|
|
if err != nil {
|
|
return config{}, fmt.Errorf("failed to load config: %w", err)
|
|
}
|
|
cfg = mergeConfig(cfg, fileCfg)
|
|
}
|
|
if serverURLOverride != "" {
|
|
cfg.ServerURL = serverURLOverride
|
|
}
|
|
if printerIDOverride != "" {
|
|
cfg.PrinterID = printerIDOverride
|
|
}
|
|
if tokenOverride != "" {
|
|
cfg.Token = tokenOverride
|
|
}
|
|
if moonrakerURLOverride != "" {
|
|
cfg.MoonrakerURL = moonrakerURLOverride
|
|
}
|
|
if stateFileOverride != "" {
|
|
cfg.StateFile = stateFileOverride
|
|
}
|
|
if cfg.UIAutoDetect == nil {
|
|
enabled := true
|
|
cfg.UIAutoDetect = &enabled
|
|
}
|
|
if cfg.ControlMode == "" {
|
|
cfg.ControlMode = "readonly"
|
|
}
|
|
if cfg.StateFile == "" {
|
|
cfg.StateFile = defaultStateFile
|
|
}
|
|
if err := validateConfig(cfg); err != nil {
|
|
return config{}, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func runStatus(args []string, defaults config) error {
|
|
fs := flag.NewFlagSet("klipperanywhere-agent status", flag.ContinueOnError)
|
|
var configPath string
|
|
var stateFileOverride string
|
|
var jsonOutput bool
|
|
fs.StringVar(&configPath, "config", "", "path to agent JSON config file")
|
|
fs.StringVar(&stateFileOverride, "state-file", "", "path to the local agent state file")
|
|
fs.BoolVar(&jsonOutput, "json", false, "print JSON")
|
|
if err := fs.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
cfg, err := parseRunConfig(fs.Args(), defaults)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if configPath != "" {
|
|
cfgFromFile, err := loadConfig(configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to load config: %w", err)
|
|
}
|
|
cfg = mergeConfig(cfg, cfgFromFile)
|
|
}
|
|
if stateFileOverride != "" {
|
|
cfg.StateFile = stateFileOverride
|
|
}
|
|
if cfg.StateFile == "" {
|
|
cfg.StateFile = defaultStateFile
|
|
}
|
|
status, err := readAgentStatus(cfg.StateFile)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if jsonOutput {
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
return enc.Encode(status)
|
|
}
|
|
printAgentStatus(os.Stdout, cfg, status)
|
|
return nil
|
|
}
|
|
|
|
func loadConfig(path string) (config, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return config{}, err
|
|
}
|
|
defer f.Close()
|
|
|
|
var cfg config
|
|
if err := json.NewDecoder(f).Decode(&cfg); err != nil {
|
|
return config{}, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func mergeConfig(base config, override config) config {
|
|
if override.ServerURL != "" {
|
|
base.ServerURL = override.ServerURL
|
|
}
|
|
if override.PrinterID != "" {
|
|
base.PrinterID = override.PrinterID
|
|
}
|
|
if override.Token != "" {
|
|
base.Token = override.Token
|
|
}
|
|
if override.MoonrakerURL != "" {
|
|
base.MoonrakerURL = override.MoonrakerURL
|
|
}
|
|
if override.ControlMode != "" {
|
|
base.ControlMode = override.ControlMode
|
|
}
|
|
if override.UIURL != "" {
|
|
base.UIURL = override.UIURL
|
|
}
|
|
if override.UIAutoDetect != nil {
|
|
base.UIAutoDetect = override.UIAutoDetect
|
|
}
|
|
if override.StateFile != "" {
|
|
base.StateFile = override.StateFile
|
|
}
|
|
if len(override.Cameras) > 0 {
|
|
base.Cameras = override.Cameras
|
|
}
|
|
return base
|
|
}
|
|
|
|
func validateConfig(cfg config) error {
|
|
if cfg.ServerURL == "" {
|
|
return errors.New("server_url is required")
|
|
}
|
|
if cfg.PrinterID == "" {
|
|
return errors.New("printer_id is required")
|
|
}
|
|
if cfg.Token == "" {
|
|
return errors.New("token is required")
|
|
}
|
|
if cfg.MoonrakerURL == "" {
|
|
return errors.New("moonraker_url is required")
|
|
}
|
|
if cfg.ControlMode != "readonly" && cfg.ControlMode != "full" {
|
|
return fmt.Errorf("invalid control_mode %q", cfg.ControlMode)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func readAgentStatus(path string) (agentStatusRecord, error) {
|
|
store := newAgentStatusStore(path)
|
|
return store.read()
|
|
}
|
|
|
|
func printAgentStatus(w io.Writer, cfg config, status agentStatusRecord) {
|
|
lastHeartbeat := "never"
|
|
if !status.LastHeartbeatAt.IsZero() {
|
|
lastHeartbeat = status.LastHeartbeatAt.Format(time.RFC3339)
|
|
}
|
|
lastSync := "never"
|
|
if !status.LastSyncAt.IsZero() {
|
|
lastSync = status.LastSyncAt.Format(time.RFC3339)
|
|
}
|
|
fmt.Fprintf(w, "KlipperAnywhere Agent\n")
|
|
fmt.Fprintf(w, " printer: %s\n", firstNonEmpty(status.PrinterID, cfg.PrinterID))
|
|
fmt.Fprintf(w, " server: %s\n", firstNonEmpty(status.ServerURL, cfg.ServerURL))
|
|
fmt.Fprintf(w, " moonraker: %s\n", firstNonEmpty(status.MoonrakerURL, cfg.MoonrakerURL))
|
|
fmt.Fprintf(w, " version: %s\n", firstNonEmpty(status.AgentVersion, agentVersion))
|
|
fmt.Fprintf(w, " control mode: %s\n", firstNonEmpty(status.ControlMode, cfg.ControlMode))
|
|
fmt.Fprintf(w, " ui: %s\n", firstNonEmpty(status.UIURL, cfg.UIURL))
|
|
fmt.Fprintf(w, " ui auto-detect: %t\n", status.UIAutoDetect)
|
|
fmt.Fprintf(w, " ui source: %s\n", firstNonEmpty(status.UISource, "unknown"))
|
|
fmt.Fprintf(w, " ui reachable: %t\n", status.UIReachable)
|
|
fmt.Fprintf(w, " moonraker reachable: %t\n", status.MoonrakerReachable)
|
|
fmt.Fprintf(w, " moonraker state: %s\n", firstNonEmpty(status.MoonrakerState, "unknown"))
|
|
fmt.Fprintf(w, " last heartbeat: %s\n", lastHeartbeat)
|
|
fmt.Fprintf(w, " last sync: %s\n", lastSync)
|
|
if status.LastSyncDetail != "" {
|
|
fmt.Fprintf(w, " sync detail: %s\n", status.LastSyncDetail)
|
|
}
|
|
}
|
|
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, value := range values {
|
|
if strings.TrimSpace(value) != "" {
|
|
return value
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func run(tunnelURL string, moonrakerURL *url.URL, configuredUIURL string, uiAutoDetect bool, controlMode string, cameras []cameraConfig, stateFile string, printerID string, serverURL string, stop <-chan os.Signal) error {
|
|
conn, _, err := websocket.DefaultDialer.Dial(tunnelURL, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer conn.Close()
|
|
|
|
log.Printf("connected to %s", tunnelURL)
|
|
|
|
var writeMu sync.Mutex
|
|
errCh := make(chan error, 1)
|
|
store := &cameraStore{cameras: discoverCameras(moonrakerURL, cameras)}
|
|
wsStore := &wsStore{conns: make(map[string]*websocket.Conn)}
|
|
statusStore := newAgentStatusStore(stateFile)
|
|
statusCache := &moonrakerStatusCache{}
|
|
state := &runtimeState{uiURL: configuredUIURL, uiAutoDetect: uiAutoDetect, controlMode: controlMode}
|
|
state.ui = discoverUI(configuredUIURL, uiAutoDetect, moonrakerURL)
|
|
done := make(chan struct{})
|
|
subscriptionReady := make(chan struct{})
|
|
defer close(done)
|
|
go heartbeatLoop(done, subscriptionReady, errCh, conn, &writeMu, moonrakerURL, state, cameras, store, statusStore, statusCache, printerID, serverURL)
|
|
go moonrakerSubscriptionLoop(done, subscriptionReady, conn, &writeMu, moonrakerURL, state, store, statusStore, statusCache, printerID, serverURL)
|
|
go func() {
|
|
for {
|
|
var msg protocol.Message
|
|
if err := conn.ReadJSON(&msg); err != nil {
|
|
errCh <- err
|
|
return
|
|
}
|
|
if msg.Target == "ws_frame" {
|
|
wsStore.write(msg)
|
|
continue
|
|
}
|
|
if msg.Type == protocol.MessageConfigSync {
|
|
if err := applyConfigSync(state, moonrakerURL, &writeMu, conn, store.snapshot(), statusStore, statusCache, printerID, serverURL, msg); err != nil {
|
|
log.Printf("failed to apply config sync: %v", err)
|
|
}
|
|
continue
|
|
}
|
|
if msg.Type != protocol.MessageHTTPRequest {
|
|
continue
|
|
}
|
|
go handleRequest(conn, &writeMu, wsStore, moonrakerURL, state.snapshotUI(), store.snapshot(), stateFile, msg)
|
|
}
|
|
}()
|
|
|
|
select {
|
|
case err := <-errCh:
|
|
return err
|
|
case <-stop:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func heartbeatLoop(done <-chan struct{}, subscriptionReady <-chan struct{}, errCh chan<- error, conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, configured []cameraConfig, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) {
|
|
waitForMoonrakerSubscription(subscriptionReady)
|
|
lastFullRefresh := time.Now()
|
|
printStatus, err := sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, cache, printerID, serverURL)
|
|
if err != nil {
|
|
reportAgentLoopError(errCh, fmt.Errorf("heartbeat write failed: %w", err))
|
|
return
|
|
}
|
|
for {
|
|
interval := normalHeartbeatInterval
|
|
if isActivePrintStatus(printStatus) {
|
|
interval = activePrintHeartbeatInterval
|
|
}
|
|
select {
|
|
case <-time.After(interval):
|
|
case <-done:
|
|
return
|
|
}
|
|
|
|
if time.Since(lastFullRefresh) >= normalHeartbeatInterval {
|
|
store.replace(discoverCameras(moonrakerURL, configured))
|
|
state.refreshUI(moonrakerURL)
|
|
lastFullRefresh = time.Now()
|
|
}
|
|
printStatus, err = sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, cache, printerID, serverURL)
|
|
if err != nil {
|
|
reportAgentLoopError(errCh, fmt.Errorf("heartbeat write failed: %w", err))
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func reportAgentLoopError(errCh chan<- error, err error) {
|
|
select {
|
|
case errCh <- err:
|
|
default:
|
|
}
|
|
}
|
|
|
|
func (s *runtimeState) snapshot() (string, bool, string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.uiURL, s.uiAutoDetect, s.controlMode
|
|
}
|
|
|
|
func (s *runtimeState) snapshotUI() *uiTarget {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if s.ui == nil {
|
|
return nil
|
|
}
|
|
copy := *s.ui
|
|
return ©
|
|
}
|
|
|
|
func (s *runtimeState) snapshotUIURL() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.uiURL
|
|
}
|
|
|
|
func (s *runtimeState) snapshotControlMode() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.controlMode
|
|
}
|
|
|
|
func (s *runtimeState) snapshotUIAutoDetect() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.uiAutoDetect
|
|
}
|
|
|
|
func (s *runtimeState) apply(settings protocol.Settings) {
|
|
s.mu.Lock()
|
|
s.uiURL = settings.UIURL
|
|
s.uiAutoDetect = settings.UIAutoDetect
|
|
if settings.ControlMode != "" {
|
|
s.controlMode = settings.ControlMode
|
|
}
|
|
s.mu.Unlock()
|
|
}
|
|
|
|
func (s *runtimeState) refreshUI(moonrakerURL *url.URL) {
|
|
uiURL, uiAutoDetect, _ := s.snapshot()
|
|
ui := discoverUI(uiURL, uiAutoDetect, moonrakerURL)
|
|
s.mu.Lock()
|
|
s.ui = ui
|
|
s.mu.Unlock()
|
|
}
|
|
|
|
func applyConfigSync(state *runtimeState, moonrakerURL *url.URL, writeMu *sync.Mutex, conn *websocket.Conn, cameras []cameraConfig, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string, msg protocol.Message) error {
|
|
if msg.Settings == nil {
|
|
return writeJSONLocked(conn, writeMu, protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: http.StatusOK,
|
|
})
|
|
}
|
|
state.apply(*msg.Settings)
|
|
state.refreshUI(moonrakerURL)
|
|
if _, err := sendHeartbeat(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), cameras, statusStore, cache, printerID, serverURL); err != nil {
|
|
return err
|
|
}
|
|
if statusStore != nil {
|
|
if err := statusStore.recordSync(agentStatusRecord{
|
|
PrinterID: printerID,
|
|
ServerURL: serverURL,
|
|
MoonrakerURL: moonrakerURL.String(),
|
|
AgentVersion: agentVersion,
|
|
ControlMode: state.snapshotControlMode(),
|
|
UIURL: state.snapshotUIURL(),
|
|
UIAutoDetect: state.snapshotUIAutoDetect(),
|
|
LastSyncAt: time.Now().UTC(),
|
|
LastSyncDetail: "accepted server config sync",
|
|
}); err != nil {
|
|
log.Printf("failed to record agent sync state: %v", err)
|
|
}
|
|
}
|
|
log.Printf("applied config sync control_mode=%s ui_url=%q ui_auto_detect=%t", state.snapshotControlMode(), state.snapshotUIURL(), state.snapshotUIAutoDetect())
|
|
return writeJSONLocked(conn, writeMu, protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: http.StatusOK,
|
|
})
|
|
}
|
|
|
|
func (s *cameraStore) snapshot() []cameraConfig {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
cameras := make([]cameraConfig, len(s.cameras))
|
|
copy(cameras, s.cameras)
|
|
return cameras
|
|
}
|
|
|
|
func (s *cameraStore) replace(cameras []cameraConfig) {
|
|
s.mu.Lock()
|
|
s.cameras = cameras
|
|
s.mu.Unlock()
|
|
}
|
|
|
|
func sendHeartbeat(conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) (*protocol.PrintStatus, error) {
|
|
printStatus := cachedMoonrakerPrintStatus(cache, moonrakerURL)
|
|
if printStatus == nil {
|
|
printStatus = collectPrintStatus(moonrakerURL)
|
|
if cache != nil && printStatus != nil {
|
|
cache.seed(printStatus)
|
|
}
|
|
}
|
|
return printStatus, sendHeartbeatWithPrintStatus(conn, writeMu, moonrakerURL, ui, controlMode, uiAutoDetect, cameras, statusStore, printerID, serverURL, printStatus)
|
|
}
|
|
|
|
func sendHeartbeatWithPrintStatus(conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, statusStore *agentStatusStore, printerID string, serverURL string, printStatus *protocol.PrintStatus) error {
|
|
health := collectHealth(moonrakerURL, ui, controlMode, uiAutoDetect, cameras, printStatus)
|
|
msg := protocol.Message{
|
|
ID: fmt.Sprintf("heartbeat-%d", health.CheckedAtUnix),
|
|
Type: protocol.MessageHeartbeat,
|
|
Health: &health,
|
|
}
|
|
if err := writeJSONLocked(conn, writeMu, msg); err != nil {
|
|
log.Printf("failed to write heartbeat: %v", err)
|
|
return err
|
|
}
|
|
if statusStore != nil {
|
|
if err := statusStore.recordHeartbeat(agentStatusRecord{
|
|
PrinterID: printerID,
|
|
ServerURL: serverURL,
|
|
MoonrakerURL: moonrakerURL.String(),
|
|
AgentVersion: agentVersion,
|
|
ControlMode: controlMode,
|
|
UIURL: health.UIURL,
|
|
UIAutoDetect: uiAutoDetect,
|
|
UIReachable: health.UIReachable,
|
|
UISource: health.UISource,
|
|
MoonrakerReachable: health.MoonrakerReachable,
|
|
MoonrakerState: health.MoonrakerState,
|
|
MoonrakerMessage: health.MoonrakerMessage,
|
|
PrintStatus: health.PrintStatus,
|
|
LastHeartbeatAt: time.Unix(health.CheckedAtUnix, 0).UTC(),
|
|
Cameras: cameras,
|
|
}); err != nil {
|
|
log.Printf("failed to write agent status: %v", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isActivePrintStatus(status *protocol.PrintStatus) bool {
|
|
if status == nil {
|
|
return false
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(status.State)) {
|
|
case "printing", "paused":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func collectHealth(moonrakerURL *url.URL, ui *uiTarget, controlMode string, uiAutoDetect bool, cameras []cameraConfig, printStatus *protocol.PrintStatus) protocol.Health {
|
|
hostname, _ := os.Hostname()
|
|
health := protocol.Health{
|
|
AgentVersion: agentVersion,
|
|
Hostname: hostname,
|
|
MoonrakerURL: moonrakerURL.String(),
|
|
UIAutoDetect: uiAutoDetect,
|
|
ControlMode: controlMode,
|
|
CheckedAtUnix: time.Now().Unix(),
|
|
}
|
|
if printStatus != nil {
|
|
health.PrintStatus = printStatus
|
|
}
|
|
if ui != nil && ui.URL != nil {
|
|
health.UIURL = ui.URL.String()
|
|
health.UIReachable = ui.Reachable
|
|
health.UISource = ui.Source
|
|
}
|
|
for _, camera := range cameras {
|
|
if camera.Name == "" {
|
|
continue
|
|
}
|
|
health.Cameras = append(health.Cameras, protocol.CameraHealth{
|
|
Name: camera.Name,
|
|
Source: camera.Source,
|
|
Service: camera.Service,
|
|
Location: camera.Location,
|
|
AspectRatio: camera.AspectRatio,
|
|
Rotation: camera.Rotation,
|
|
FlipHorizontal: camera.FlipHorizontal,
|
|
FlipVertical: camera.FlipVertical,
|
|
HasSnapshot: camera.SnapshotURL != "",
|
|
HasStream: camera.StreamURL != "",
|
|
})
|
|
}
|
|
|
|
target := *moonrakerURL
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/printer/info")
|
|
target.RawQuery = ""
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
resp, err := client.Get(target.String())
|
|
if err != nil {
|
|
health.MoonrakerMessage = err.Error()
|
|
return health
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
health.MoonrakerMessage = resp.Status
|
|
return health
|
|
}
|
|
|
|
var body struct {
|
|
Result struct {
|
|
State string `json:"state"`
|
|
StateMessage string `json:"state_message"`
|
|
} `json:"result"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil {
|
|
health.MoonrakerMessage = err.Error()
|
|
return health
|
|
}
|
|
|
|
health.MoonrakerReachable = true
|
|
health.MoonrakerState = body.Result.State
|
|
health.MoonrakerMessage = body.Result.StateMessage
|
|
return health
|
|
}
|
|
|
|
func collectPrintStatus(moonrakerURL *url.URL) *protocol.PrintStatus {
|
|
target := *moonrakerURL
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/printer/objects/query")
|
|
target.RawQuery = "print_stats&display_status&gcode_move&toolhead"
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
rawResult := fetchMoonrakerJSON(client, &target)
|
|
rawStatus := moonrakerObjectStatus(rawResult)
|
|
if rawStatus == nil {
|
|
return nil
|
|
}
|
|
printStatus := printStatusFromMoonrakerStatus(rawStatus)
|
|
if printStatus == nil {
|
|
return nil
|
|
}
|
|
printStatus.MoonrakerMetadataFilename = printStatus.Filename
|
|
rawStatus["moonraker_metadata_filename"] = printStatus.Filename
|
|
if metadata := collectPrintMetadata(moonrakerURL, printStatus.Filename); metadata != nil {
|
|
rawStatus["moonraker_metadata"] = metadata
|
|
printStatus.MoonrakerMetadata = metadata
|
|
}
|
|
return printStatus
|
|
}
|
|
|
|
func printStatusFromMoonrakerStatus(rawStatus map[string]any) *protocol.PrintStatus {
|
|
if rawStatus == nil {
|
|
return nil
|
|
}
|
|
status, ok := rawStatus["print_stats"].(map[string]any)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
printStatus := &protocol.PrintStatus{
|
|
MoonrakerStatus: rawStatus,
|
|
}
|
|
if state, _ := status["state"].(string); state != "" {
|
|
printStatus.State = state
|
|
}
|
|
if filename, _ := status["filename"].(string); filename != "" {
|
|
printStatus.Filename = filename
|
|
}
|
|
if message, _ := status["message"].(string); message != "" {
|
|
printStatus.Message = message
|
|
}
|
|
if progress, ok := rawStatus["display_status"].(map[string]any); ok {
|
|
if value, ok := progress["progress"].(float64); ok {
|
|
printStatus.Progress = value
|
|
}
|
|
if message, _ := progress["message"].(string); message != "" && printStatus.Message == "" {
|
|
printStatus.Message = message
|
|
}
|
|
}
|
|
if value, ok := status["print_duration"].(float64); ok {
|
|
printStatus.PrintDuration = value
|
|
}
|
|
if value, ok := status["total_duration"].(float64); ok {
|
|
printStatus.TotalDuration = value
|
|
}
|
|
if value, ok := status["filament_used"].(float64); ok {
|
|
printStatus.FilamentUsed = value
|
|
}
|
|
if value, ok := status["estimated_time_remaining"].(float64); ok {
|
|
printStatus.EstimatedTimeRemaining = value
|
|
}
|
|
currentLayer, totalLayer := 0, 0
|
|
if info, ok := status["info"].(map[string]any); ok {
|
|
if value, ok := info["current_layer"]; ok {
|
|
if layer, ok := jsonNumberToInt(value); ok {
|
|
currentLayer = layer
|
|
}
|
|
}
|
|
if value, ok := info["total_layer"]; ok {
|
|
if layer, ok := jsonNumberToInt(value); ok {
|
|
totalLayer = layer
|
|
}
|
|
}
|
|
}
|
|
if currentLayer > 0 {
|
|
printStatus.CurrentLayer = currentLayer
|
|
}
|
|
if totalLayer > 0 {
|
|
printStatus.TotalLayer = totalLayer
|
|
}
|
|
if printStatus.LayerSource == "" {
|
|
if printStatus.CurrentLayer > 0 || printStatus.TotalLayer > 0 {
|
|
printStatus.LayerSource = "print_stats"
|
|
}
|
|
}
|
|
if metadata, ok := rawStatus["moonraker_metadata"].(map[string]any); ok {
|
|
printStatus.MoonrakerMetadata = metadata
|
|
}
|
|
if metadataFilename, _ := rawStatus["moonraker_metadata_filename"].(string); metadataFilename != "" {
|
|
printStatus.MoonrakerMetadataFilename = metadataFilename
|
|
}
|
|
return printStatus
|
|
}
|
|
|
|
func (c *moonrakerStatusCache) update(partial map[string]any) (*protocol.PrintStatus, bool, bool) {
|
|
if c == nil || partial == nil {
|
|
return nil, false, false
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.status == nil {
|
|
c.status = map[string]any{}
|
|
}
|
|
mergeMoonrakerStatus(c.status, partial)
|
|
c.updatedAt = time.Now().UTC()
|
|
status := printStatusFromMoonrakerStatus(c.status)
|
|
key := moonrakerSubscriptionStatusKey(c.status)
|
|
if key == "" || key == c.key {
|
|
return status, false, false
|
|
}
|
|
c.key = key
|
|
logUpdate := moonrakerSubscriptionUpdateShouldLog(partial, status, c.lastLogAt)
|
|
if logUpdate {
|
|
c.lastLogAt = c.updatedAt
|
|
}
|
|
return status, true, logUpdate
|
|
}
|
|
|
|
func (c *moonrakerStatusCache) seed(status *protocol.PrintStatus) {
|
|
if c == nil || status == nil {
|
|
return
|
|
}
|
|
c.mu.Lock()
|
|
if c.status == nil {
|
|
c.status = map[string]any{}
|
|
}
|
|
c.status["print_stats"] = map[string]any{
|
|
"state": status.State,
|
|
"filename": status.Filename,
|
|
"message": status.Message,
|
|
"progress": status.Progress,
|
|
"print_duration": status.PrintDuration,
|
|
"total_duration": status.TotalDuration,
|
|
"filament_used": status.FilamentUsed,
|
|
"estimated_time_remaining": status.EstimatedTimeRemaining,
|
|
"info": map[string]any{
|
|
"current_layer": status.CurrentLayer,
|
|
"total_layer": status.TotalLayer,
|
|
},
|
|
}
|
|
if status.MoonrakerStatus != nil {
|
|
for key, value := range status.MoonrakerStatus {
|
|
c.status[key] = value
|
|
}
|
|
}
|
|
if status.MoonrakerMetadata != nil {
|
|
c.status["moonraker_metadata"] = status.MoonrakerMetadata
|
|
}
|
|
if status.MoonrakerMetadataFilename != "" {
|
|
c.status["moonraker_metadata_filename"] = status.MoonrakerMetadataFilename
|
|
}
|
|
c.key = moonrakerSubscriptionStatusKey(c.status)
|
|
c.updatedAt = time.Now().UTC()
|
|
c.mu.Unlock()
|
|
}
|
|
|
|
func (c *moonrakerStatusCache) reset() {
|
|
if c == nil {
|
|
return
|
|
}
|
|
c.mu.Lock()
|
|
c.status = nil
|
|
c.key = ""
|
|
c.updatedAt = time.Time{}
|
|
c.lastLogAt = time.Time{}
|
|
c.mu.Unlock()
|
|
}
|
|
|
|
func (c *moonrakerStatusCache) snapshot(maxAge time.Duration) *protocol.PrintStatus {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.status == nil || c.updatedAt.IsZero() {
|
|
return nil
|
|
}
|
|
if maxAge > 0 && time.Since(c.updatedAt) > maxAge {
|
|
return nil
|
|
}
|
|
return printStatusFromMoonrakerStatus(c.status)
|
|
}
|
|
|
|
func cachedMoonrakerPrintStatus(cache *moonrakerStatusCache, moonrakerURL *url.URL) *protocol.PrintStatus {
|
|
if cache == nil {
|
|
return nil
|
|
}
|
|
status := cache.snapshot(45 * time.Second)
|
|
if status == nil {
|
|
return nil
|
|
}
|
|
if needsMetadataRefresh(status) {
|
|
refreshed := collectPrintStatus(moonrakerURL)
|
|
if refreshed != nil {
|
|
cache.seed(refreshed)
|
|
return refreshed
|
|
}
|
|
}
|
|
return status
|
|
}
|
|
|
|
func needsMetadataRefresh(status *protocol.PrintStatus) bool {
|
|
if status == nil {
|
|
return false
|
|
}
|
|
if strings.TrimSpace(status.Filename) == "" {
|
|
return false
|
|
}
|
|
if strings.TrimSpace(status.MoonrakerMetadataFilename) == "" {
|
|
return true
|
|
}
|
|
return !strings.EqualFold(strings.TrimSpace(status.MoonrakerMetadataFilename), strings.TrimSpace(status.Filename))
|
|
}
|
|
|
|
func collectPrintMetadata(moonrakerURL *url.URL, filename string) map[string]any {
|
|
filename = strings.TrimSpace(filename)
|
|
if filename == "" {
|
|
return nil
|
|
}
|
|
target := *moonrakerURL
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/server/files/metadata")
|
|
target.RawQuery = "filename=" + url.QueryEscape(filename)
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
result := fetchMoonrakerJSON(client, &target)
|
|
if result == nil {
|
|
return nil
|
|
}
|
|
return result
|
|
}
|
|
|
|
func moonrakerSubscriptionStatusKey(status map[string]any) string {
|
|
if len(status) == 0 {
|
|
return ""
|
|
}
|
|
data, err := json.Marshal(status)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return string(data)
|
|
}
|
|
|
|
func moonrakerSubscriptionUpdateShouldLog(partial map[string]any, status *protocol.PrintStatus, lastLogAt time.Time) bool {
|
|
if status == nil {
|
|
return false
|
|
}
|
|
if lastLogAt.IsZero() || time.Since(lastLogAt) > 30*time.Second {
|
|
return true
|
|
}
|
|
for _, key := range mapKeys(partial) {
|
|
switch key {
|
|
case "print_stats", "display_status", "gcode_move", "toolhead":
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func mergeMoonrakerStatus(dst map[string]any, src map[string]any) {
|
|
for key, value := range src {
|
|
if srcMap, ok := value.(map[string]any); ok {
|
|
if dstMap, ok := dst[key].(map[string]any); ok {
|
|
mergeMoonrakerStatus(dstMap, srcMap)
|
|
continue
|
|
}
|
|
}
|
|
dst[key] = value
|
|
}
|
|
}
|
|
|
|
func moonrakerSubscriptionLoop(done <-chan struct{}, subscriptionReady chan<- struct{}, conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) {
|
|
var readyOnce sync.Once
|
|
ready := func() {
|
|
readyOnce.Do(func() {
|
|
if subscriptionReady != nil {
|
|
close(subscriptionReady)
|
|
}
|
|
})
|
|
}
|
|
backoff := time.Second
|
|
for {
|
|
if cache != nil {
|
|
cache.reset()
|
|
}
|
|
err := runMoonrakerSubscription(done, ready, conn, writeMu, moonrakerURL, state, store, statusStore, cache, printerID, serverURL)
|
|
select {
|
|
case <-done:
|
|
ready()
|
|
return
|
|
default:
|
|
}
|
|
if err != nil {
|
|
log.Printf("moonraker subscription stopped: %v; reconnecting in %s", err, backoff)
|
|
}
|
|
select {
|
|
case <-time.After(backoff):
|
|
case <-done:
|
|
return
|
|
}
|
|
if backoff < 30*time.Second {
|
|
backoff *= 2
|
|
if backoff > 30*time.Second {
|
|
backoff = 30 * time.Second
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func runMoonrakerSubscription(done <-chan struct{}, ready func(), conn *websocket.Conn, writeMu *sync.Mutex, moonrakerURL *url.URL, state *runtimeState, store *cameraStore, statusStore *agentStatusStore, cache *moonrakerStatusCache, printerID string, serverURL string) error {
|
|
if cache == nil {
|
|
cache = &moonrakerStatusCache{}
|
|
}
|
|
target := moonrakerWebSocketURL(moonrakerURL)
|
|
upstream, _, err := websocket.DefaultDialer.Dial(target.String(), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer upstream.Close()
|
|
if ready != nil {
|
|
ready()
|
|
}
|
|
go func() {
|
|
<-done
|
|
_ = upstream.Close()
|
|
}()
|
|
|
|
objects, err := moonrakerSubscriptionObjectNames(upstream)
|
|
if err != nil {
|
|
log.Printf("moonraker object discovery failed: %v", err)
|
|
}
|
|
if len(objects) == 0 {
|
|
objects = defaultMoonrakerSubscriptionObjects()
|
|
}
|
|
log.Printf("moonraker subscription objects printer_id=%s objects=%v", printerID, objects)
|
|
|
|
subscriptionObjects := make(map[string]any, len(objects))
|
|
for _, object := range objects {
|
|
subscriptionObjects[object] = nil
|
|
}
|
|
if err := upstream.WriteJSON(map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"method": "printer.objects.subscribe",
|
|
"params": map[string]any{
|
|
"objects": subscriptionObjects,
|
|
},
|
|
"id": 2,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case <-done:
|
|
return nil
|
|
default:
|
|
}
|
|
var msg map[string]any
|
|
if err := upstream.ReadJSON(&msg); err != nil {
|
|
return err
|
|
}
|
|
partial := moonrakerSubscriptionStatus(msg)
|
|
if partial == nil {
|
|
continue
|
|
}
|
|
printStatus, changed, logUpdate := cache.update(partial)
|
|
if !changed {
|
|
continue
|
|
}
|
|
if logUpdate {
|
|
log.Printf("moonraker subscription update printer_id=%s keys=%v layers=%d/%d", printerID, mapKeys(partial), printStatus.CurrentLayer, printStatus.TotalLayer)
|
|
}
|
|
if err := sendHeartbeatWithPrintStatus(conn, writeMu, moonrakerURL, state.snapshotUI(), state.snapshotControlMode(), state.snapshotUIAutoDetect(), store.snapshot(), statusStore, printerID, serverURL, printStatus); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
func moonrakerSubscriptionObjectNames(conn *websocket.Conn) ([]string, error) {
|
|
if conn == nil {
|
|
return nil, fmt.Errorf("moonraker websocket unavailable")
|
|
}
|
|
if err := conn.WriteJSON(map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"method": "printer.objects.list",
|
|
"id": 1,
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
for {
|
|
var msg map[string]any
|
|
if err := conn.ReadJSON(&msg); err != nil {
|
|
return nil, err
|
|
}
|
|
if id, ok := jsonNumberToInt(msg["id"]); !ok || id != 1 {
|
|
continue
|
|
}
|
|
if names := moonrakerObjectNamesFromResultAny(msg["result"]); len(names) > 0 {
|
|
return selectMoonrakerSubscriptionObjects(names), nil
|
|
}
|
|
return nil, fmt.Errorf("moonraker object list missing objects (%T)", msg["result"])
|
|
}
|
|
}
|
|
|
|
func moonrakerObjectNamesFromResult(result map[string]any) []string {
|
|
if len(result) == 0 {
|
|
return nil
|
|
}
|
|
if rawObjects, ok := result["objects"].([]any); ok {
|
|
names := make([]string, 0, len(rawObjects))
|
|
for _, raw := range rawObjects {
|
|
name, _ := raw.(string)
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
continue
|
|
}
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|
|
if rawObjects, ok := result["objects"].([]string); ok {
|
|
names := make([]string, 0, len(rawObjects))
|
|
for _, name := range rawObjects {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
continue
|
|
}
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func waitForMoonrakerSubscription(subscriptionReady <-chan struct{}) {
|
|
if subscriptionReady == nil {
|
|
return
|
|
}
|
|
select {
|
|
case <-subscriptionReady:
|
|
case <-time.After(moonrakerSubscriptionStartupTimeout):
|
|
}
|
|
}
|
|
|
|
func moonrakerObjectNamesFromResultAny(result any) []string {
|
|
switch v := result.(type) {
|
|
case map[string]any:
|
|
return moonrakerObjectNamesFromResult(v)
|
|
case []any:
|
|
names := make([]string, 0, len(v))
|
|
for _, raw := range v {
|
|
name, _ := raw.(string)
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
continue
|
|
}
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
case []string:
|
|
names := make([]string, 0, len(v))
|
|
for _, name := range v {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
continue
|
|
}
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func defaultMoonrakerSubscriptionObjects() []string {
|
|
return []string{
|
|
"print_stats",
|
|
"display_status",
|
|
"gcode_move",
|
|
"toolhead",
|
|
"extruder",
|
|
"heater_bed",
|
|
"fan",
|
|
}
|
|
}
|
|
|
|
func selectMoonrakerSubscriptionObjects(available []string) []string {
|
|
if len(available) == 0 {
|
|
return defaultMoonrakerSubscriptionObjects()
|
|
}
|
|
wanted := map[string]struct{}{
|
|
"print_stats": {},
|
|
"display_status": {},
|
|
"gcode_move": {},
|
|
"toolhead": {},
|
|
"extruder": {},
|
|
"heater_bed": {},
|
|
"fan": {},
|
|
}
|
|
prefixes := []string{
|
|
"extruder",
|
|
"temperature_sensor ",
|
|
"temperature_fan ",
|
|
"controller_fan ",
|
|
"fan_generic ",
|
|
"heater_fan ",
|
|
}
|
|
selected := make([]string, 0, len(wanted)+8)
|
|
seen := map[string]struct{}{}
|
|
for _, name := range available {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
continue
|
|
}
|
|
if _, ok := wanted[name]; ok {
|
|
if _, seenAlready := seen[name]; !seenAlready {
|
|
selected = append(selected, name)
|
|
seen[name] = struct{}{}
|
|
}
|
|
continue
|
|
}
|
|
for _, prefix := range prefixes {
|
|
if strings.HasPrefix(name, prefix) {
|
|
if _, seenAlready := seen[name]; !seenAlready {
|
|
selected = append(selected, name)
|
|
seen[name] = struct{}{}
|
|
}
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(selected) == 0 {
|
|
return defaultMoonrakerSubscriptionObjects()
|
|
}
|
|
sort.Strings(selected)
|
|
return selected
|
|
}
|
|
|
|
func mapKeys(values map[string]any) []string {
|
|
if len(values) == 0 {
|
|
return nil
|
|
}
|
|
keys := make([]string, 0, len(values))
|
|
for key := range values {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
return keys
|
|
}
|
|
|
|
func moonrakerWebSocketURL(moonrakerURL *url.URL) *url.URL {
|
|
target := *moonrakerURL
|
|
if target.Scheme == "https" {
|
|
target.Scheme = "wss"
|
|
} else {
|
|
target.Scheme = "ws"
|
|
}
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/websocket")
|
|
target.RawQuery = ""
|
|
return &target
|
|
}
|
|
|
|
func moonrakerSubscriptionStatus(msg map[string]any) map[string]any {
|
|
if msg == nil {
|
|
return nil
|
|
}
|
|
if result, ok := msg["result"].(map[string]any); ok {
|
|
if status, ok := result["status"].(map[string]any); ok {
|
|
return status
|
|
}
|
|
}
|
|
if method, _ := msg["method"].(string); method != "notify_status_update" {
|
|
return nil
|
|
}
|
|
params, ok := msg["params"].([]any)
|
|
if !ok || len(params) == 0 {
|
|
return nil
|
|
}
|
|
status, _ := params[0].(map[string]any)
|
|
return status
|
|
}
|
|
|
|
func moonrakerObjectStatus(result map[string]any) map[string]any {
|
|
if result == nil {
|
|
return nil
|
|
}
|
|
if status, ok := result["status"].(map[string]any); ok {
|
|
return status
|
|
}
|
|
return result
|
|
}
|
|
|
|
func fetchMoonrakerJSON(client *http.Client, target *url.URL) map[string]any {
|
|
resp, err := client.Get(target.String())
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil
|
|
}
|
|
var body map[string]any
|
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil {
|
|
return nil
|
|
}
|
|
if result, ok := body["result"].(map[string]any); ok {
|
|
return result
|
|
}
|
|
return body
|
|
}
|
|
|
|
func jsonNumberToInt(value any) (int, bool) {
|
|
switch v := value.(type) {
|
|
case float64:
|
|
return int(v), true
|
|
case float32:
|
|
return int(v), true
|
|
case int:
|
|
return v, true
|
|
case int32:
|
|
return int(v), true
|
|
case int64:
|
|
return int(v), true
|
|
case json.Number:
|
|
if n, err := v.Int64(); err == nil {
|
|
return int(n), true
|
|
}
|
|
if f, err := v.Float64(); err == nil {
|
|
return int(f), true
|
|
}
|
|
}
|
|
return 0, false
|
|
}
|
|
|
|
func discoverCameras(moonrakerURL *url.URL, configured []cameraConfig) []cameraConfig {
|
|
discovered := fetchMoonrakerCameras(moonrakerURL)
|
|
if len(discovered) == 0 {
|
|
return configured
|
|
}
|
|
|
|
merged := make(map[string]cameraConfig, len(configured)+len(discovered))
|
|
order := make([]string, 0, len(configured)+len(discovered))
|
|
for _, camera := range discovered {
|
|
if camera.Name == "" {
|
|
continue
|
|
}
|
|
merged[camera.Name] = camera
|
|
order = append(order, camera.Name)
|
|
}
|
|
for _, camera := range configured {
|
|
if camera.Name == "" {
|
|
continue
|
|
}
|
|
if _, exists := merged[camera.Name]; !exists {
|
|
order = append(order, camera.Name)
|
|
}
|
|
merged[camera.Name] = mergeCamera(merged[camera.Name], camera)
|
|
}
|
|
|
|
cameras := make([]cameraConfig, 0, len(order))
|
|
for _, name := range order {
|
|
cameras = append(cameras, merged[name])
|
|
}
|
|
return cameras
|
|
}
|
|
|
|
func fetchMoonrakerCameras(moonrakerURL *url.URL) []cameraConfig {
|
|
target := *moonrakerURL
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/server/webcams/list")
|
|
target.RawQuery = ""
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
resp, err := client.Get(target.String())
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil
|
|
}
|
|
|
|
var body struct {
|
|
Result struct {
|
|
Webcams []struct {
|
|
Name string `json:"name"`
|
|
Enabled bool `json:"enabled"`
|
|
SnapshotURL string `json:"snapshot_url"`
|
|
StreamURL string `json:"stream_url"`
|
|
Source string `json:"source"`
|
|
Service string `json:"service"`
|
|
Location string `json:"location"`
|
|
AspectRatio string `json:"aspect_ratio"`
|
|
Rotation int `json:"rotation"`
|
|
FlipHorizontal bool `json:"flip_horizontal"`
|
|
FlipVertical bool `json:"flip_vertical"`
|
|
} `json:"webcams"`
|
|
} `json:"result"`
|
|
Webcams []struct {
|
|
Name string `json:"name"`
|
|
Enabled bool `json:"enabled"`
|
|
SnapshotURL string `json:"snapshot_url"`
|
|
StreamURL string `json:"stream_url"`
|
|
Source string `json:"source"`
|
|
Service string `json:"service"`
|
|
Location string `json:"location"`
|
|
AspectRatio string `json:"aspect_ratio"`
|
|
Rotation int `json:"rotation"`
|
|
FlipHorizontal bool `json:"flip_horizontal"`
|
|
FlipVertical bool `json:"flip_vertical"`
|
|
} `json:"webcams"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&body); err != nil {
|
|
return nil
|
|
}
|
|
|
|
webcams := body.Result.Webcams
|
|
if len(webcams) == 0 {
|
|
webcams = body.Webcams
|
|
}
|
|
|
|
cameras := make([]cameraConfig, 0, len(webcams))
|
|
for _, webcam := range webcams {
|
|
if webcam.Name == "" || !webcam.Enabled {
|
|
continue
|
|
}
|
|
cameras = append(cameras, cameraConfig{
|
|
Name: webcam.Name,
|
|
SnapshotURL: resolveCameraURL(moonrakerURL, webcam.SnapshotURL),
|
|
StreamURL: resolveCameraURL(moonrakerURL, webcam.StreamURL),
|
|
Source: webcam.Source,
|
|
Service: webcam.Service,
|
|
Location: webcam.Location,
|
|
AspectRatio: webcam.AspectRatio,
|
|
Rotation: webcam.Rotation,
|
|
FlipHorizontal: webcam.FlipHorizontal,
|
|
FlipVertical: webcam.FlipVertical,
|
|
})
|
|
}
|
|
for i := range cameras {
|
|
cameras[i] = resolveMoonrakerCameraTest(moonrakerURL, cameras[i])
|
|
}
|
|
return cameras
|
|
}
|
|
|
|
func resolveMoonrakerCameraTest(moonrakerURL *url.URL, camera cameraConfig) cameraConfig {
|
|
target := *moonrakerURL
|
|
target.Path = joinURLPath(moonrakerURL.Path, "/server/webcams/test")
|
|
target.RawQuery = url.Values{"name": []string{camera.Name}}.Encode()
|
|
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
req, err := http.NewRequest(http.MethodPost, target.String(), nil)
|
|
if err != nil {
|
|
return camera
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return camera
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return camera
|
|
}
|
|
|
|
var body struct {
|
|
Result struct {
|
|
SnapshotURL string `json:"snapshot_url"`
|
|
StreamURL string `json:"stream_url"`
|
|
} `json:"result"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&body); err != nil {
|
|
return camera
|
|
}
|
|
if body.Result.SnapshotURL != "" {
|
|
camera.SnapshotURL = normalizeDiscoveredCameraURL(moonrakerURL, body.Result.SnapshotURL)
|
|
}
|
|
if body.Result.StreamURL != "" {
|
|
camera.StreamURL = normalizeDiscoveredCameraURL(moonrakerURL, body.Result.StreamURL)
|
|
}
|
|
return camera
|
|
}
|
|
|
|
func mergeCamera(base cameraConfig, override cameraConfig) cameraConfig {
|
|
if override.Name != "" {
|
|
base.Name = override.Name
|
|
}
|
|
if override.SnapshotURL != "" {
|
|
base.SnapshotURL = override.SnapshotURL
|
|
}
|
|
if override.StreamURL != "" {
|
|
base.StreamURL = override.StreamURL
|
|
}
|
|
if override.Source != "" {
|
|
base.Source = override.Source
|
|
}
|
|
if override.Service != "" {
|
|
base.Service = override.Service
|
|
}
|
|
if override.Location != "" {
|
|
base.Location = override.Location
|
|
}
|
|
if override.AspectRatio != "" {
|
|
base.AspectRatio = override.AspectRatio
|
|
}
|
|
if override.Rotation != 0 {
|
|
base.Rotation = override.Rotation
|
|
}
|
|
if override.FlipHorizontal {
|
|
base.FlipHorizontal = true
|
|
}
|
|
if override.FlipVertical {
|
|
base.FlipVertical = true
|
|
}
|
|
return base
|
|
}
|
|
|
|
func resolveCameraURL(base *url.URL, raw string) string {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" {
|
|
return ""
|
|
}
|
|
parsed, err := url.Parse(raw)
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
return normalizeDiscoveredCameraURL(base, base.ResolveReference(parsed).String())
|
|
}
|
|
|
|
func normalizeDiscoveredCameraURL(base *url.URL, raw string) string {
|
|
parsed, err := url.Parse(raw)
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
if isLoopbackHost(parsed.Hostname()) && !isLoopbackHost(base.Hostname()) {
|
|
host := base.Hostname()
|
|
if parsed.Port() != "" {
|
|
host += ":" + parsed.Port()
|
|
}
|
|
parsed.Host = host
|
|
}
|
|
return parsed.String()
|
|
}
|
|
|
|
func isLoopbackHost(host string) bool {
|
|
switch strings.ToLower(host) {
|
|
case "localhost", "127.0.0.1", "::1":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func discoverUI(configured string, autoDetect bool, moonrakerURL *url.URL) *uiTarget {
|
|
if configured != "" {
|
|
u, err := url.Parse(configured)
|
|
if err != nil {
|
|
log.Printf("invalid ui_url %q: %v", configured, err)
|
|
return nil
|
|
}
|
|
return &uiTarget{URL: u, Source: "config", Reachable: checkUIReachable(u)}
|
|
}
|
|
if !autoDetect {
|
|
return nil
|
|
}
|
|
for _, candidate := range uiCandidates(moonrakerURL) {
|
|
u, err := url.Parse(candidate)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if sameOrigin(u, moonrakerURL) {
|
|
continue
|
|
}
|
|
if checkUIReachable(u) {
|
|
return &uiTarget{URL: u, Source: "auto", Reachable: true}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func uiCandidates(moonrakerURL *url.URL) []string {
|
|
candidates := []string{
|
|
"http://127.0.0.1",
|
|
"http://127.0.0.1:80",
|
|
"http://127.0.0.1:4408",
|
|
"http://127.0.0.1:8080",
|
|
}
|
|
if moonrakerURL == nil {
|
|
return candidates
|
|
}
|
|
|
|
host := moonrakerURL.Hostname()
|
|
if host == "" {
|
|
return candidates
|
|
}
|
|
candidates = append(candidates,
|
|
"http://"+host,
|
|
"http://"+host+":80",
|
|
"http://"+host+":4408",
|
|
"http://"+host+":8080",
|
|
)
|
|
if moonrakerURL.Scheme == "https" || moonrakerURL.Port() == "443" {
|
|
candidates = append(candidates, "https://"+host, "https://"+host+":443")
|
|
}
|
|
return candidates
|
|
}
|
|
|
|
func checkUIReachable(base *url.URL) bool {
|
|
client := &http.Client{Timeout: 2 * time.Second}
|
|
req, err := http.NewRequest(http.MethodGet, base.String(), nil)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
req.Header.Set("Accept-Encoding", "identity")
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<10))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 500 {
|
|
return false
|
|
}
|
|
lower := strings.ToLower(string(body))
|
|
if strings.Contains(lower, "welcome to moonraker") || strings.Contains(lower, "<title>moonraker") || strings.Contains(lower, "mjpg-streamer") {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func sameOrigin(a *url.URL, b *url.URL) bool {
|
|
if a == nil || b == nil {
|
|
return false
|
|
}
|
|
return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
|
|
}
|
|
|
|
func handleRequest(conn *websocket.Conn, writeMu *sync.Mutex, wsStore *wsStore, moonrakerURL *url.URL, ui *uiTarget, cameras []cameraConfig, stateFile string, msg protocol.Message) {
|
|
if msg.Target == "moonraker_ws" {
|
|
proxyWebSocket(conn, writeMu, wsStore, moonrakerURL, msg)
|
|
return
|
|
}
|
|
if msg.Target == "ui_ws" {
|
|
var uiURL *url.URL
|
|
if ui != nil {
|
|
uiURL = ui.URL
|
|
}
|
|
proxyWebSocket(conn, writeMu, wsStore, uiURL, msg)
|
|
return
|
|
}
|
|
if msg.Target == "camera" {
|
|
proxyCamera(conn, writeMu, cameras, msg)
|
|
return
|
|
}
|
|
if msg.Target == "camera_snapshot" {
|
|
sendCameraSnapshot(conn, writeMu, cameras, msg)
|
|
return
|
|
}
|
|
if msg.Target == "ui" {
|
|
var uiURL *url.URL
|
|
if ui != nil {
|
|
uiURL = ui.URL
|
|
}
|
|
resp := proxyHTTP(uiURL, msg, 64<<20)
|
|
if err := writeJSONLocked(conn, writeMu, resp); err != nil {
|
|
log.Printf("failed to write ui response id=%s: %v", msg.ID, err)
|
|
}
|
|
return
|
|
}
|
|
if msg.Target == "agent_update" {
|
|
if err := performAgentUpdate(conn, writeMu, stateFile, msg); err != nil {
|
|
writeError(conn, writeMu, msg.ID, err.Error())
|
|
}
|
|
return
|
|
}
|
|
|
|
resp := proxyMoonraker(moonrakerURL, msg)
|
|
|
|
if err := writeJSONLocked(conn, writeMu, resp); err != nil {
|
|
log.Printf("failed to write response id=%s: %v", msg.ID, err)
|
|
}
|
|
}
|
|
|
|
func performAgentUpdate(conn *websocket.Conn, writeMu *sync.Mutex, stateFile string, msg protocol.Message) error {
|
|
if msg.Update == nil {
|
|
return errors.New("missing agent update payload")
|
|
}
|
|
releaseURL := strings.TrimSpace(msg.Update.ReleaseURL)
|
|
if releaseURL == "" {
|
|
return errors.New("missing release URL")
|
|
}
|
|
asset, err := agentAssetForRuntime()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
binary, err := downloadReleaseAsset(ctx, releaseURL, asset)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
backupPath, err := prepareUpdateBackupPath(stateFile)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := copyFile(exePath, backupPath); err != nil {
|
|
return fmt.Errorf("failed to back up current agent: %w", err)
|
|
}
|
|
tempPath := exePath + ".new"
|
|
if err := os.WriteFile(tempPath, binary, 0o755); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Rename(tempPath, exePath); err != nil {
|
|
_ = os.Remove(tempPath)
|
|
return err
|
|
}
|
|
if err := os.Chmod(exePath, 0o755); err != nil {
|
|
return err
|
|
}
|
|
if err := startRollbackWatchdog(exePath, backupPath, stateFile, msg.Update.Version); err != nil {
|
|
log.Printf("failed to start rollback watchdog: %v", err)
|
|
}
|
|
go func() {
|
|
time.Sleep(500 * time.Millisecond)
|
|
os.Exit(0)
|
|
}()
|
|
if err := writeJSONLocked(conn, writeMu, protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: http.StatusOK,
|
|
Body: base64.StdEncoding.EncodeToString([]byte(`{"ok":true}`)),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
log.Printf("agent update applied asset=%s version=%s", asset, msg.Update.Version)
|
|
return nil
|
|
}
|
|
|
|
func agentAssetForRuntime() (string, error) {
|
|
switch runtime.GOARCH {
|
|
case "amd64":
|
|
return "klipperanywhere-agent-linux-amd64", nil
|
|
case "arm64":
|
|
return "klipperanywhere-agent-linux-arm64", nil
|
|
case "arm":
|
|
return "klipperanywhere-agent-linux-armv7", nil
|
|
case "mipsle":
|
|
return "klipperanywhere-agent-linux-mipsle", nil
|
|
default:
|
|
return "", fmt.Errorf("unsupported agent architecture: %s", runtime.GOARCH)
|
|
}
|
|
}
|
|
|
|
func downloadReleaseAsset(ctx context.Context, baseURL string, asset string) ([]byte, error) {
|
|
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/"+asset, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
client := &http.Client{Timeout: 2 * time.Minute}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
|
if len(snippet) > 0 {
|
|
return nil, fmt.Errorf("download failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet)))
|
|
}
|
|
return nil, fmt.Errorf("download failed: %s", resp.Status)
|
|
}
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func copyFile(src string, dst string) error {
|
|
in, err := os.Open(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer in.Close()
|
|
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
|
return err
|
|
}
|
|
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer out.Close()
|
|
if _, err := io.Copy(out, in); err != nil {
|
|
return err
|
|
}
|
|
return out.Sync()
|
|
}
|
|
|
|
func prepareUpdateBackupPath(stateFile string) (string, error) {
|
|
base := filepath.Dir(stateFile)
|
|
if base == "." || base == "" {
|
|
base = filepath.Dir(defaultStateFile)
|
|
}
|
|
backupDir := filepath.Join(base, "update-backups")
|
|
if err := os.MkdirAll(backupDir, 0o755); err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.Join(backupDir, "klipperanywhere-agent.bak"), nil
|
|
}
|
|
|
|
func startRollbackWatchdog(targetPath, backupPath, stateFile, expectedVersion string) error {
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
devNull, err := os.OpenFile(os.DevNull, os.O_RDWR, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer devNull.Close()
|
|
args := []string{
|
|
exePath,
|
|
"rollback-watchdog",
|
|
"--target", targetPath,
|
|
"--backup", backupPath,
|
|
"--state-file", stateFile,
|
|
"--expected-version", expectedVersion,
|
|
"--timeout", "2m",
|
|
}
|
|
proc, err := os.StartProcess(exePath, args, &os.ProcAttr{
|
|
Files: []*os.File{devNull, devNull, devNull},
|
|
Env: os.Environ(),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
go func() {
|
|
_, _ = proc.Wait()
|
|
}()
|
|
return nil
|
|
}
|
|
|
|
func runRollbackWatchdog(args []string) error {
|
|
fs := flag.NewFlagSet("klipperanywhere-agent rollback-watchdog", flag.ContinueOnError)
|
|
var targetPath string
|
|
var backupPath string
|
|
var stateFile string
|
|
var expectedVersion string
|
|
var timeout time.Duration
|
|
fs.StringVar(&targetPath, "target", "", "path to the agent binary")
|
|
fs.StringVar(&backupPath, "backup", "", "path to the backup binary")
|
|
fs.StringVar(&stateFile, "state-file", defaultStateFile, "path to the agent state file")
|
|
fs.StringVar(&expectedVersion, "expected-version", "", "expected agent version after update")
|
|
fs.DurationVar(&timeout, "timeout", 2*time.Minute, "rollback timeout")
|
|
if err := fs.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
if targetPath == "" || backupPath == "" {
|
|
return errors.New("target and backup are required")
|
|
}
|
|
time.Sleep(timeout)
|
|
status, err := readAgentStatus(stateFile)
|
|
if err == nil && strings.TrimSpace(status.AgentVersion) == strings.TrimSpace(expectedVersion) && !status.LastHeartbeatAt.IsZero() {
|
|
return nil
|
|
}
|
|
if err := copyFile(backupPath, targetPath); err != nil {
|
|
return fmt.Errorf("rollback restore failed: %w", err)
|
|
}
|
|
if err := restartAgentService(); err != nil {
|
|
return fmt.Errorf("rollback restart failed: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func restartAgentService() error {
|
|
commands := []string{
|
|
"systemctl restart klipperanywhere-agent",
|
|
"rc-service klipperanywhere-agent restart 2>/dev/null || rc-service klipperanywhere-agent start",
|
|
"service klipperanywhere-agent restart",
|
|
"/etc/init.d/klipperanywhere-agent restart",
|
|
}
|
|
for _, command := range commands {
|
|
if strings.Contains(command, "systemctl") && !(fileExists("/run/systemd/system") || commandExists("systemctl")) {
|
|
continue
|
|
}
|
|
if strings.Contains(command, "rc-service") && !commandExists("rc-service") {
|
|
continue
|
|
}
|
|
if strings.Contains(command, "/etc/init.d/klipperanywhere-agent") && !fileExists("/etc/init.d/klipperanywhere-agent") {
|
|
continue
|
|
}
|
|
out, err := exec.Command("sh", "-lc", command).CombinedOutput()
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if len(out) > 0 {
|
|
log.Printf("rollback restart command failed: %s: %s", command, strings.TrimSpace(string(out)))
|
|
}
|
|
}
|
|
return errors.New("no supported service manager found to restart the agent")
|
|
}
|
|
|
|
func fileExists(path string) bool {
|
|
info, err := os.Stat(path)
|
|
return err == nil && !info.IsDir()
|
|
}
|
|
|
|
func commandExists(name string) bool {
|
|
_, err := exec.LookPath(name)
|
|
return err == nil
|
|
}
|
|
|
|
func proxyWebSocket(tunnel *websocket.Conn, writeMu *sync.Mutex, store *wsStore, baseURL *url.URL, msg protocol.Message) {
|
|
if baseURL == nil {
|
|
writeError(tunnel, writeMu, msg.ID, "target is not configured")
|
|
return
|
|
}
|
|
target := *baseURL
|
|
if target.Scheme == "https" {
|
|
target.Scheme = "wss"
|
|
} else {
|
|
target.Scheme = "ws"
|
|
}
|
|
target.Path = joinURLPath(baseURL.Path, msg.Path)
|
|
target.RawQuery = ""
|
|
if i := strings.Index(msg.Path, "?"); i >= 0 {
|
|
target.Path = joinURLPath(baseURL.Path, msg.Path[:i])
|
|
target.RawQuery = msg.Path[i+1:]
|
|
}
|
|
|
|
upstream, _, err := websocket.DefaultDialer.Dial(target.String(), nil)
|
|
if err != nil {
|
|
writeError(tunnel, writeMu, msg.ID, err.Error())
|
|
return
|
|
}
|
|
store.add(msg.ID, upstream)
|
|
if err := writeJSONLocked(tunnel, writeMu, protocol.Message{ID: msg.ID, Type: protocol.MessageHTTPResponse, Status: http.StatusSwitchingProtocols}); err != nil {
|
|
store.close(msg.ID)
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
defer store.close(msg.ID)
|
|
for {
|
|
messageType, payload, err := upstream.ReadMessage()
|
|
if err != nil {
|
|
_ = writeJSONLocked(tunnel, writeMu, protocol.Message{ID: msg.ID, Target: "ws_frame", End: true})
|
|
return
|
|
}
|
|
if messageType != websocket.TextMessage && messageType != websocket.BinaryMessage {
|
|
continue
|
|
}
|
|
_ = writeJSONLocked(tunnel, writeMu, protocol.Message{
|
|
ID: msg.ID,
|
|
Target: "ws_frame",
|
|
Type: protocol.MessageHTTPResponse,
|
|
Body: base64.StdEncoding.EncodeToString(payload),
|
|
WSMessageType: messageType,
|
|
})
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (s *wsStore) add(id string, conn *websocket.Conn) {
|
|
s.mu.Lock()
|
|
s.conns[id] = conn
|
|
s.mu.Unlock()
|
|
}
|
|
|
|
func (s *wsStore) write(msg protocol.Message) {
|
|
body, err := base64.StdEncoding.DecodeString(msg.Body)
|
|
if err != nil {
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
conn := s.conns[msg.ID]
|
|
s.mu.Unlock()
|
|
if conn == nil {
|
|
return
|
|
}
|
|
if msg.End {
|
|
_ = conn.Close()
|
|
return
|
|
}
|
|
messageType := msg.WSMessageType
|
|
if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage {
|
|
messageType = websocket.TextMessage
|
|
}
|
|
_ = conn.WriteMessage(messageType, body)
|
|
}
|
|
|
|
func (s *wsStore) close(id string) {
|
|
s.mu.Lock()
|
|
conn := s.conns[id]
|
|
delete(s.conns, id)
|
|
s.mu.Unlock()
|
|
if conn != nil {
|
|
_ = conn.Close()
|
|
}
|
|
}
|
|
|
|
func proxyCamera(conn *websocket.Conn, writeMu *sync.Mutex, cameras []cameraConfig, msg protocol.Message) {
|
|
camera, ok := findCamera(cameras, msg.CameraName)
|
|
if !ok {
|
|
writeError(conn, writeMu, msg.ID, "camera is not configured")
|
|
return
|
|
}
|
|
|
|
rawURL := camera.SnapshotURL
|
|
if msg.CameraKind == "stream" {
|
|
rawURL = camera.StreamURL
|
|
}
|
|
if rawURL == "" {
|
|
writeError(conn, writeMu, msg.ID, "camera endpoint is not configured")
|
|
return
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
writeError(conn, writeMu, msg.ID, err.Error())
|
|
return
|
|
}
|
|
|
|
client := &http.Client{}
|
|
if msg.CameraKind != "stream" {
|
|
client.Timeout = 15 * time.Second
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
writeError(conn, writeMu, msg.ID, err.Error())
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
header := protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: resp.StatusCode,
|
|
Headers: headersFromHTTP(resp.Header),
|
|
}
|
|
if err := writeJSONLocked(conn, writeMu, header); err != nil {
|
|
log.Printf("failed to write camera response header id=%s: %v", msg.ID, err)
|
|
return
|
|
}
|
|
|
|
buf := make([]byte, 32*1024)
|
|
for {
|
|
n, readErr := resp.Body.Read(buf)
|
|
if n > 0 {
|
|
chunk := protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Body: base64.StdEncoding.EncodeToString(buf[:n]),
|
|
}
|
|
if err := writeJSONLocked(conn, writeMu, chunk); err != nil {
|
|
log.Printf("failed to write camera chunk id=%s: %v", msg.ID, err)
|
|
return
|
|
}
|
|
}
|
|
if readErr != nil {
|
|
end := protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
End: true,
|
|
}
|
|
if readErr != io.EOF {
|
|
end.Type = protocol.MessageError
|
|
end.Error = readErr.Error()
|
|
}
|
|
if err := writeJSONLocked(conn, writeMu, end); err != nil {
|
|
log.Printf("failed to write camera end id=%s: %v", msg.ID, err)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendCameraSnapshot(conn *websocket.Conn, writeMu *sync.Mutex, cameras []cameraConfig, msg protocol.Message) {
|
|
camera, ok := findCamera(cameras, msg.CameraName)
|
|
if !ok {
|
|
writeError(conn, writeMu, msg.ID, "camera is not configured")
|
|
return
|
|
}
|
|
data, headers, status, err := fetchCameraSnapshot(camera)
|
|
if err != nil {
|
|
writeError(conn, writeMu, msg.ID, err.Error())
|
|
return
|
|
}
|
|
resp := protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: status,
|
|
Headers: headers,
|
|
Body: base64.StdEncoding.EncodeToString(data),
|
|
End: true,
|
|
}
|
|
if err := writeJSONLocked(conn, writeMu, resp); err != nil {
|
|
log.Printf("failed to write camera snapshot response id=%s: %v", msg.ID, err)
|
|
}
|
|
}
|
|
|
|
func fetchCameraSnapshot(camera cameraConfig) ([]byte, []protocol.Header, int, error) {
|
|
rawURL := strings.TrimSpace(camera.SnapshotURL)
|
|
if rawURL == "" {
|
|
return nil, nil, 0, fmt.Errorf("camera snapshot endpoint is not configured")
|
|
}
|
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
return nil, nil, 0, err
|
|
}
|
|
client := &http.Client{Timeout: 20 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, nil, 0, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
detail := strings.TrimSpace(string(body))
|
|
if detail != "" {
|
|
return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("camera snapshot failed: %s: %s", resp.Status, detail)
|
|
}
|
|
return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("camera snapshot failed: %s", resp.Status)
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(resp.Body, 20<<20))
|
|
if err != nil {
|
|
return nil, headersFromHTTP(resp.Header), resp.StatusCode, err
|
|
}
|
|
if len(data) == 0 {
|
|
return nil, headersFromHTTP(resp.Header), resp.StatusCode, fmt.Errorf("empty camera snapshot")
|
|
}
|
|
return data, headersFromHTTP(resp.Header), resp.StatusCode, nil
|
|
}
|
|
|
|
func writeError(conn *websocket.Conn, writeMu *sync.Mutex, id string, message string) {
|
|
if err := writeJSONLocked(conn, writeMu, errorMessage(id, message)); err != nil {
|
|
log.Printf("failed to write error id=%s: %v", id, err)
|
|
}
|
|
}
|
|
|
|
func findCamera(cameras []cameraConfig, name string) (cameraConfig, bool) {
|
|
for _, camera := range cameras {
|
|
if camera.Name == name {
|
|
return camera, true
|
|
}
|
|
}
|
|
return cameraConfig{}, false
|
|
}
|
|
|
|
func writeJSONLocked(conn *websocket.Conn, writeMu *sync.Mutex, msg protocol.Message) error {
|
|
writeMu.Lock()
|
|
defer writeMu.Unlock()
|
|
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
return conn.WriteJSON(msg)
|
|
}
|
|
|
|
func proxyMoonraker(baseURL *url.URL, msg protocol.Message) protocol.Message {
|
|
return proxyHTTP(baseURL, msg, 64<<20)
|
|
}
|
|
|
|
func proxyHTTP(baseURL *url.URL, msg protocol.Message, limit int64) protocol.Message {
|
|
if baseURL == nil {
|
|
return errorMessage(msg.ID, "target is not configured")
|
|
}
|
|
body, err := base64.StdEncoding.DecodeString(msg.Body)
|
|
if err != nil {
|
|
return errorMessage(msg.ID, "invalid request body")
|
|
}
|
|
|
|
target := *baseURL
|
|
target.RawQuery = ""
|
|
if i := strings.Index(msg.Path, "?"); i >= 0 {
|
|
target.Path = joinURLPath(baseURL.Path, msg.Path[:i])
|
|
target.RawQuery = msg.Path[i+1:]
|
|
} else {
|
|
target.Path = joinURLPath(baseURL.Path, msg.Path)
|
|
}
|
|
|
|
req, err := http.NewRequest(msg.Method, target.String(), bytes.NewReader(body))
|
|
if err != nil {
|
|
return errorMessage(msg.ID, err.Error())
|
|
}
|
|
for _, h := range msg.Headers {
|
|
if strings.EqualFold(h.Name, "Accept-Encoding") {
|
|
continue
|
|
}
|
|
for _, v := range h.Values {
|
|
req.Header.Add(h.Name, v)
|
|
}
|
|
}
|
|
req.Header.Set("Accept-Encoding", "identity")
|
|
|
|
client := &http.Client{Timeout: 30 * time.Second}
|
|
httpResp, err := client.Do(req)
|
|
if err != nil {
|
|
return errorMessage(msg.ID, err.Error())
|
|
}
|
|
defer httpResp.Body.Close()
|
|
|
|
respBody, err := io.ReadAll(io.LimitReader(httpResp.Body, limit))
|
|
if err != nil {
|
|
return errorMessage(msg.ID, err.Error())
|
|
}
|
|
|
|
return protocol.Message{
|
|
ID: msg.ID,
|
|
Type: protocol.MessageHTTPResponse,
|
|
Status: httpResp.StatusCode,
|
|
Headers: headersFromHTTP(httpResp.Header),
|
|
Body: base64.StdEncoding.EncodeToString(respBody),
|
|
}
|
|
}
|
|
|
|
func errorMessage(id string, message string) protocol.Message {
|
|
return protocol.Message{
|
|
ID: id,
|
|
Type: protocol.MessageError,
|
|
Error: message,
|
|
}
|
|
}
|
|
|
|
func headersFromHTTP(h http.Header) []protocol.Header {
|
|
headers := make([]protocol.Header, 0, len(h))
|
|
for name, values := range h {
|
|
headers = append(headers, protocol.Header{Name: name, Values: values})
|
|
}
|
|
return headers
|
|
}
|
|
|
|
func withAuthQuery(rawURL, printerID, token string) (string, error) {
|
|
u, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
q := u.Query()
|
|
q.Set("printer_id", printerID)
|
|
q.Set("token", token)
|
|
u.RawQuery = q.Encode()
|
|
return u.String(), nil
|
|
}
|
|
|
|
func joinURLPath(basePath, requestPath string) string {
|
|
basePath = strings.TrimRight(basePath, "/")
|
|
requestPath = "/" + strings.TrimLeft(requestPath, "/")
|
|
if basePath == "" {
|
|
return requestPath
|
|
}
|
|
return basePath + requestPath
|
|
}
|
|
|
|
func init() {
|
|
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
|
|
}
|