84b185be39
Phase A - Stability: - Engine.Start(): recovers orphaned jobs (running/queued/waking_up) after crash - Engine.Stop(): graceful shutdown - cancels all in-flight jobs and waits - Queue keyed by jobID (not syncPairID): cancel now targets exact job - Local rsync uses jobCtx (context.Background() replaced) - Migrations wrapped in transactions; checksums stored Phase B - Security: - admin/admin default removed: SYNCSERVER_ADMIN_PASSWORD required on first run - Path validation: rejects .., leading -, null bytes in sync pair paths - Rsync flags allowlist: dangerous flags blocked (--rsync-path, -e, --files-from) - Shell concat in RunRemote replaced with proper sh -c escaping - knownhosts: replaced custom parser with golang.org/x/crypto/ssh/knownhosts - RequireAdmin wired: machine CRUD, SSH key ops, settings require admin role - deploy-keys: uses authorized_keys only (no private key upload) - Hardcoded /var/lib/syncserver/ssh paths replaced with cfg.SSHDir() Phase C - Operational: - /readyz health check: DB query + SSH dir accessibility - /metrics endpoint: Prometheus text format (jobs, queue, machines) - Event struct JSON tags: job_id, machine_id, type (snake_case) - EventBus broadcast: fanned out to all subscribers - SQLite VACUUM INTO backup: scheduled before cleanup if BackupDir set - Filesystem job log cleanup: removes .log files for purged jobs - Backup retention: old backups auto-purged Phase D - Frontend: - Schedules page: REST API + full CRUD UI for cron schedules - Dashboard: cancel button for running/queued jobs - JobDetail: server-side log download via API - Settings: displays data_dir from server - 404 page: proper NotFound component Phase E - Tests: - auth_test.go: JWT, bcrypt, middleware, seed (18 tests) - models_test.go: Job, Machine, SyncPair, Schedule repos (18 tests) - go test -race: no data races found
612 lines
17 KiB
Go
612 lines
17 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/syncserver/internal/config"
|
|
"golang.org/x/crypto/ssh"
|
|
"github.com/syncserver/internal/models"
|
|
"github.com/syncserver/internal/sshmanager"
|
|
"github.com/syncserver/internal/syncengine"
|
|
"github.com/syncserver/internal/wol"
|
|
)
|
|
|
|
type MachineHandler struct {
|
|
db *sql.DB
|
|
engine *syncengine.Engine
|
|
cfg *config.Config
|
|
}
|
|
|
|
func NewMachineHandler(db *sql.DB, engine *syncengine.Engine, cfg *config.Config) *MachineHandler {
|
|
return &MachineHandler{db: db, engine: engine, cfg: cfg}
|
|
}
|
|
|
|
var macRegex = regexp.MustCompile(`^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$`)
|
|
|
|
func (h *MachineHandler) List(w http.ResponseWriter, r *http.Request) {
|
|
repo := models.NewMachineRepository(h.db)
|
|
ms, err := repo.GetAll()
|
|
if err != nil {
|
|
slog.Error("failed to fetch machines", "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machines")
|
|
return
|
|
}
|
|
out := make([]MachineResponse, len(ms))
|
|
for i, m := range ms {
|
|
out[i] = machineToResp(m)
|
|
}
|
|
writeJSON(w, out)
|
|
}
|
|
|
|
func (h *MachineHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
writeJSON(w, machineToResp(*m))
|
|
}
|
|
|
|
func (h *MachineHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|
var req MachineRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
if req.Name == "" || req.Host == "" {
|
|
writeError(w, http.StatusBadRequest, "name and host are required")
|
|
return
|
|
}
|
|
if req.Port <= 0 || req.Port > 65535 {
|
|
writeError(w, http.StatusBadRequest, "invalid port")
|
|
return
|
|
}
|
|
if req.SSHUser == "" {
|
|
req.SSHUser = "root"
|
|
}
|
|
if req.WakeTimeoutSeconds <= 0 {
|
|
req.WakeTimeoutSeconds = 180
|
|
}
|
|
if req.WakeCheckIntervalSeconds <= 0 {
|
|
req.WakeCheckIntervalSeconds = 5
|
|
}
|
|
if req.WoLEnabled && req.MACAddress != nil && !macRegex.MatchString(*req.MACAddress) {
|
|
writeError(w, http.StatusBadRequest, "invalid mac_address format (expected AA:BB:CC:DD:EE:FF)")
|
|
return
|
|
}
|
|
|
|
shutdownCmd := req.ShutdownCommand
|
|
if shutdownCmd == "" {
|
|
shutdownCmd = "shutdown now"
|
|
}
|
|
m := &models.Machine{
|
|
Name: req.Name,
|
|
Host: req.Host,
|
|
Port: req.Port,
|
|
SSHUser: req.SSHUser,
|
|
SSHKeyID: req.SSHKeyID,
|
|
MACAddress: req.MACAddress,
|
|
WoLEnabled: req.WoLEnabled,
|
|
BroadcastAddr: req.BroadcastAddr,
|
|
WakeTimeoutSeconds: req.WakeTimeoutSeconds,
|
|
WakeCheckIntervalSeconds: req.WakeCheckIntervalSeconds,
|
|
FingerprintConfirmed: false,
|
|
Status: "unknown",
|
|
ShutdownCommand: shutdownCmd,
|
|
}
|
|
|
|
repo := models.NewMachineRepository(h.db)
|
|
id, err := repo.Create(m)
|
|
if err != nil {
|
|
slog.Error("failed to create machine", "name", req.Name, "host", req.Host, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to create machine")
|
|
return
|
|
}
|
|
m.ID = id
|
|
w.Header().Set("Location", "/api/machines/"+strconv.FormatInt(id, 10))
|
|
writeJSON(w, machineToResp(*m), http.StatusCreated)
|
|
}
|
|
|
|
func (h *MachineHandler) Update(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
|
|
var req MachineRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
if req.Name == "" || req.Host == "" {
|
|
writeError(w, http.StatusBadRequest, "name and host are required")
|
|
return
|
|
}
|
|
if req.Port <= 0 || req.Port > 65535 {
|
|
writeError(w, http.StatusBadRequest, "invalid port")
|
|
return
|
|
}
|
|
if req.SSHUser == "" {
|
|
req.SSHUser = "root"
|
|
}
|
|
if req.WoLEnabled && req.MACAddress != nil && !macRegex.MatchString(*req.MACAddress) {
|
|
writeError(w, http.StatusBadRequest, "invalid mac_address format")
|
|
return
|
|
}
|
|
|
|
repo := models.NewMachineRepository(h.db)
|
|
existing, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
|
|
existing.Name = req.Name
|
|
existing.Host = req.Host
|
|
existing.Port = req.Port
|
|
existing.SSHUser = req.SSHUser
|
|
existing.SSHKeyID = req.SSHKeyID
|
|
existing.MACAddress = req.MACAddress
|
|
existing.WoLEnabled = req.WoLEnabled
|
|
existing.BroadcastAddr = req.BroadcastAddr
|
|
if req.WakeTimeoutSeconds > 0 {
|
|
existing.WakeTimeoutSeconds = req.WakeTimeoutSeconds
|
|
}
|
|
if req.WakeCheckIntervalSeconds > 0 {
|
|
existing.WakeCheckIntervalSeconds = req.WakeCheckIntervalSeconds
|
|
}
|
|
if req.ShutdownCommand != "" {
|
|
existing.ShutdownCommand = req.ShutdownCommand
|
|
}
|
|
|
|
if err := repo.Update(existing); err != nil {
|
|
slog.Error("failed to update machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to update machine")
|
|
return
|
|
}
|
|
writeJSON(w, machineToResp(*existing))
|
|
}
|
|
|
|
func (h *MachineHandler) TestWoL(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
if !m.WoLEnabled || m.MACAddress == nil {
|
|
writeError(w, http.StatusBadRequest, "WoL is not enabled for this machine or MAC address is missing")
|
|
return
|
|
}
|
|
mac, err := wol.ParseMAC(*m.MACAddress)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid MAC address")
|
|
return
|
|
}
|
|
bcast := ""
|
|
if m.BroadcastAddr != nil {
|
|
bcast = *m.BroadcastAddr
|
|
}
|
|
if err := wol.Send(mac, bcast); err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, map[string]interface{}{"ok": true, "sent": 3})
|
|
}
|
|
|
|
func (h *MachineHandler) Shutdown(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
|
|
knownHostsPath, err := sshmanager.EnsureKnownHosts(h.cfg.SSHDir())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to ensure known_hosts")
|
|
return
|
|
}
|
|
|
|
privKeyPath := filepath.Join(h.cfg.SSHDir(), "id_ed25519")
|
|
if m.SSHKeyID != nil {
|
|
sshKeyRepo := models.NewSSHKeyRepository(h.db)
|
|
sshKey, err := sshKeyRepo.GetByID(*m.SSHKeyID)
|
|
if err == nil && sshKey.PrivateKeyPath != "" {
|
|
privKeyPath = sshKey.PrivateKeyPath
|
|
}
|
|
}
|
|
|
|
cmd := m.ShutdownCommand
|
|
if cmd == "" {
|
|
cmd = "shutdown now"
|
|
}
|
|
|
|
slog.Info("shutdown requested", "machine_id", id, "name", m.Name, "command", cmd)
|
|
result, err := sshmanager.RunRemoteCommand(
|
|
context.Background(), m.Host, m.Port, m.SSHUser,
|
|
privKeyPath, knownHostsPath, m.FingerprintConfirmed, cmd,
|
|
)
|
|
|
|
if err != nil {
|
|
slog.Error("shutdown failed", "machine_id", id, "error", err)
|
|
writeJSON(w, ShutdownResponse{Success: false, Error: err.Error()})
|
|
return
|
|
}
|
|
|
|
responseSuccess := result.Success
|
|
responseOutput := result.Output
|
|
responseError := result.Error
|
|
|
|
if !responseSuccess && m.ShutdownCommand != "" && sshmanager.IsShutdownCommand(m.ShutdownCommand) {
|
|
if isExpectedShutdownError(result.Error) {
|
|
responseSuccess = true
|
|
responseError = ""
|
|
if responseOutput == "" {
|
|
responseOutput = "shutdown command sent (host session terminated as expected)"
|
|
}
|
|
}
|
|
}
|
|
|
|
writeJSON(w, ShutdownResponse{
|
|
Success: responseSuccess,
|
|
Output: responseOutput,
|
|
Error: responseError,
|
|
})
|
|
}
|
|
|
|
func isExpectedShutdownError(errMsg string) bool {
|
|
if errMsg == "" {
|
|
return false
|
|
}
|
|
return strings.Contains(errMsg, "remote command exited without exit status") ||
|
|
strings.Contains(errMsg, "connection refused") ||
|
|
strings.Contains(errMsg, "connection reset by peer") ||
|
|
strings.Contains(errMsg, "use of closed network connection")
|
|
}
|
|
|
|
func (h *MachineHandler) TestConnection(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
|
|
knownHostsPath, err := sshmanager.EnsureKnownHosts(h.cfg.SSHDir())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to ensure known_hosts")
|
|
return
|
|
}
|
|
|
|
privKeyPath := filepath.Join(h.cfg.SSHDir(), "id_ed25519")
|
|
if m.SSHKeyID != nil {
|
|
sshKeyRepo := models.NewSSHKeyRepository(h.db)
|
|
sshKey, err := sshKeyRepo.GetByID(*m.SSHKeyID)
|
|
if err == nil && sshKey.PrivateKeyPath != "" {
|
|
privKeyPath = sshKey.PrivateKeyPath
|
|
}
|
|
}
|
|
|
|
result, err := sshmanager.TestSSHConnection(
|
|
context.Background(),
|
|
m.Host, m.Port, m.SSHUser,
|
|
privKeyPath, knownHostsPath,
|
|
m.FingerprintConfirmed,
|
|
)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, TestConnectionResponse{
|
|
Success: result.Success,
|
|
Output: result.Output,
|
|
Error: result.Error,
|
|
Fingerprint: result.Fingerprint,
|
|
})
|
|
}
|
|
|
|
func (h *MachineHandler) ApproveFingerprint(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Fingerprint string `json:"fingerprint"`
|
|
HostKey string `json:"host_key"`
|
|
}
|
|
json.NewDecoder(r.Body).Decode(&req)
|
|
|
|
sshDir := h.cfg.SSHDir()
|
|
knownHostsPath, err := sshmanager.EnsureKnownHosts(sshDir)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to ensure known_hosts")
|
|
return
|
|
}
|
|
|
|
privKeyPath := filepath.Join(h.cfg.SSHDir(), "id_ed25519")
|
|
if m.SSHKeyID != nil {
|
|
sshKeyRepo := models.NewSSHKeyRepository(h.db)
|
|
sshKey, err := sshKeyRepo.GetByID(*m.SSHKeyID)
|
|
if err == nil && sshKey.PrivateKeyPath != "" {
|
|
privKeyPath = sshKey.PrivateKeyPath
|
|
}
|
|
}
|
|
|
|
var fingerprint, pubKeyLine string
|
|
|
|
if req.HostKey != "" {
|
|
pubKeyLine = req.HostKey
|
|
} else {
|
|
conn, fp, pubKey, err := sshmanager.ConnectForApproval(
|
|
context.Background(), m.Host, m.Port, m.SSHUser,
|
|
privKeyPath, knownHostsPath,
|
|
)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, fmt.Sprintf("could not retrieve host key: %v", err))
|
|
return
|
|
}
|
|
conn.Close()
|
|
fingerprint = fp
|
|
pubKeyLine = string(ssh.MarshalAuthorizedKey(pubKey))
|
|
}
|
|
|
|
if fingerprint == "" && req.Fingerprint != "" {
|
|
fingerprint = req.Fingerprint
|
|
}
|
|
|
|
if pubKeyLine != "" {
|
|
if err := sshmanager.AddKnownHost(sshDir, m.Host, m.Port, []byte(pubKeyLine)); err != nil {
|
|
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to add known_host entry: %v", err))
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := repo.UpdateFingerprint(id, true, fingerprint); err != nil {
|
|
slog.Error("failed to update fingerprint", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to update fingerprint")
|
|
return
|
|
}
|
|
|
|
m.FingerprintConfirmed = true
|
|
m.HostKeyFingerprint = &fingerprint
|
|
writeJSON(w, machineToResp(*m))
|
|
}
|
|
|
|
func (h *MachineHandler) DeployKeys(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
repo := models.NewMachineRepository(h.db)
|
|
m, err := repo.GetByID(id)
|
|
if err == sql.ErrNoRows {
|
|
writeError(w, http.StatusNotFound, "machine not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.Error("failed to fetch machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
KnownHostsHost string `json:"known_hosts_host"`
|
|
IncludeServerKey bool `json:"include_server_key"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
serverKeyPath := h.cfg.SSHDir() + "/id_ed25519"
|
|
|
|
if m.SSHKeyID != nil {
|
|
sshKeyRepo := models.NewSSHKeyRepository(h.db)
|
|
sshKey, err := sshKeyRepo.GetByID(*m.SSHKeyID)
|
|
if err == nil && sshKey.PrivateKeyPath != "" {
|
|
serverKeyPath = sshKey.PrivateKeyPath
|
|
}
|
|
}
|
|
|
|
allMachines, err := repo.GetAll()
|
|
if err != nil {
|
|
slog.Warn("failed to fetch machines for auto-detect", "error", err)
|
|
}
|
|
|
|
var keys []sshmanager.DeployKey
|
|
seenKeys := make(map[string]bool)
|
|
knownHostsHosts := []string{}
|
|
|
|
for _, other := range allMachines {
|
|
if other.ID == m.ID {
|
|
continue
|
|
}
|
|
knownHostsHosts = append(knownHostsHosts, fmt.Sprintf("%s:%d", other.Host, other.Port))
|
|
if other.SSHKeyID != nil {
|
|
skRepo := models.NewSSHKeyRepository(h.db)
|
|
sk, err := skRepo.GetByID(*other.SSHKeyID)
|
|
if err == nil && sk.PrivateKeyPath != "" {
|
|
if seenKeys[sk.PrivateKeyPath] {
|
|
continue
|
|
}
|
|
seenKeys[sk.PrivateKeyPath] = true
|
|
keys = append(keys, sshmanager.DeployKey{
|
|
LocalPath: sk.PrivateKeyPath,
|
|
RemotePath: h.cfg.SSHDir() + "/keys/" + filepath.Base(sk.PrivateKeyPath),
|
|
Mode: 0600,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(keys) == 0 {
|
|
slog.Info("no keys auto-detected for machine, using empty key list", "machine", m.Name)
|
|
}
|
|
|
|
result, err := sshmanager.DeployKeysToMachine(
|
|
context.Background(),
|
|
serverKeyPath,
|
|
m.Host,
|
|
m.Port,
|
|
m.SSHUser,
|
|
keys,
|
|
knownHostsHosts,
|
|
h.cfg.SSHDir(),
|
|
)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
writeJSON(w, result)
|
|
}
|
|
|
|
func (h *MachineHandler) Refresh(w http.ResponseWriter, r *http.Request) {
|
|
if h.engine == nil {
|
|
writeError(w, http.StatusInternalServerError, "engine not available")
|
|
return
|
|
}
|
|
go func() {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
slog.Error("ProbeAllMachines panicked", "panic", r)
|
|
}
|
|
}()
|
|
h.engine.ProbeAllMachines()
|
|
}()
|
|
w.WriteHeader(http.StatusAccepted)
|
|
writeJSON(w, map[string]string{"status": "probing"})
|
|
}
|
|
|
|
func (h *MachineHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid id")
|
|
return
|
|
}
|
|
|
|
repo := models.NewMachineRepository(h.db)
|
|
if err := repo.Delete(id); err != nil {
|
|
slog.Error("failed to delete machine", "id", id, "error", err)
|
|
writeError(w, http.StatusInternalServerError, "failed to delete machine")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func machineToResp(m models.Machine) MachineResponse {
|
|
var lastSeen *string
|
|
if m.LastSeenAt != nil {
|
|
s := m.LastSeenAt.Format(time.RFC3339)
|
|
lastSeen = &s
|
|
}
|
|
return MachineResponse{
|
|
ID: m.ID,
|
|
Name: m.Name,
|
|
Host: m.Host,
|
|
Port: m.Port,
|
|
SSHUser: m.SSHUser,
|
|
SSHKeyID: m.SSHKeyID,
|
|
MACAddress: m.MACAddress,
|
|
WoLEnabled: m.WoLEnabled,
|
|
BroadcastAddr: m.BroadcastAddr,
|
|
WakeTimeoutSeconds: m.WakeTimeoutSeconds,
|
|
WakeCheckIntervalSeconds: m.WakeCheckIntervalSeconds,
|
|
FingerprintConfirmed: m.FingerprintConfirmed,
|
|
HostKeyFingerprint: m.HostKeyFingerprint,
|
|
Status: m.Status,
|
|
LastSeenAt: lastSeen,
|
|
CreatedAt: m.CreatedAt.Format(time.RFC3339),
|
|
ShutdownCommand: m.ShutdownCommand,
|
|
}
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, code int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
json.NewEncoder(w).Encode(ErrorResponse{Error: msg})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, data interface{}, codes ...int) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if len(codes) > 0 {
|
|
w.WriteHeader(codes[0])
|
|
}
|
|
json.NewEncoder(w).Encode(data)
|
|
}
|