Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/alicebob/miniredis/v2 v2.38.0
github.com/brutella/dnssd v1.2.14
github.com/coder/websocket v1.8.13
github.com/dcc-bigfred/microinit/go v0.5.0
github.com/dcc-bigfred/microinit/go v0.5.1-0.20260806072850-022153bd9391
github.com/fsnotify/fsnotify v1.9.0
github.com/go-chi/chi/v5 v5.3.0
github.com/go-chi/cors v1.2.2
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dcc-bigfred/microinit/go v0.5.0 h1:Ts0qJ5VFwXZndFyLwmnZEAt+1ZOjnucrpbvbykCYzjI=
github.com/dcc-bigfred/microinit/go v0.5.0/go.mod h1:pWmLbG5Xl+PEx0nr0t70gc+Ztizk/+LuJcBvz00dtys=
github.com/dcc-bigfred/microinit/go v0.5.1-0.20260805200933-fc2b4ab607ba h1:hkQRJOh9w19fXx4nLiMI1Fr3baTeMl4dZQPk0+/2C6o=
github.com/dcc-bigfred/microinit/go v0.5.1-0.20260805200933-fc2b4ab607ba/go.mod h1:pWmLbG5Xl+PEx0nr0t70gc+Ztizk/+LuJcBvz00dtys=
github.com/dcc-bigfred/microinit/go v0.5.1-0.20260806072850-022153bd9391 h1:Gq3X+Nfpa3tiHnM7OXR5SnXZsmb6DWzorEjpgsMl3uI=
github.com/dcc-bigfred/microinit/go v0.5.1-0.20260806072850-022153bd9391/go.mod h1:pWmLbG5Xl+PEx0nr0t70gc+Ztizk/+LuJcBvz00dtys=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
Expand Down
1 change: 1 addition & 0 deletions pkgs/bigfred/server/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,7 @@ func run(ctx context.Context, log *logrus.Logger, f Flags) error {
Sudo: sudoSvc,
CommandStations: commandStationSvc,
Diagnostics: diagSvc,
System: service.NewSystemControl(supSvc),
Hub: hub,
DccBus: dccBusSvc,
Radio: radioSvc,
Expand Down
5 changes: 5 additions & 0 deletions pkgs/bigfred/server/http/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type RouterConfig struct {
Sudo *cmd.Sudo
CommandStations *cmd.CommandStation
Diagnostics *service.DiagnosticsService
System *service.SystemControl
Hub *ws.Hub
DccBus *service.DccBusService
Radio *service.RadioService
Expand Down Expand Up @@ -101,6 +102,7 @@ func NewRouter(cfg RouterConfig) http.Handler {
commandStationH.SetExecutable(cfg.DccBus.Executable())
}
diagnosticsH := NewDiagnosticsHandler(cfg.Diagnostics)
systemH := NewSystemHandler(cfg.System)
radioH := NewRadioHandler(cfg.Radio)
auditH := NewAuditHandler(cfg.Audit)
leaseH := NewLeaseHandler(cfg.Leases, cfg.Auth)
Expand Down Expand Up @@ -266,6 +268,9 @@ func NewRouter(cfg RouterConfig) http.Handler {
r.Get("/diagnostics/sources", diagnosticsH.ListSources)
r.Get("/diagnostics/content", diagnosticsH.ReadContent)

r.Get("/admin/system", systemH.Get)
r.Post("/admin/system/shutdown", systemH.Shutdown)

if cfg.DccBus != nil {
slotsProxy := NewDccBusSlotsProxy(cfg.Auth, cfg.DccBus)
r.Get("/admin/dcc-bus/{commandStationId}/slots/ws", slotsProxy.ServeHTTP)
Expand Down
70 changes: 70 additions & 0 deletions pkgs/bigfred/server/http/system.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package httpapi

import (
"encoding/json"
"errors"
"net/http"

"github.com/keskad/loco/pkgs/bigfred/server/service"
)

// SystemHandler serves admin host power control (BigFredOS / microinit init).
type SystemHandler struct {
svc *service.SystemControl
}

// NewSystemHandler returns a SystemHandler. svc may be nil (503).
func NewSystemHandler(svc *service.SystemControl) *SystemHandler {
return &SystemHandler{svc: svc}
}

// Get handles GET /api/v1/admin/system.
func (h *SystemHandler) Get(w http.ResponseWriter, _ *http.Request) {
if h.svc == nil {
writeJSONError(w, http.StatusServiceUnavailable, "system_unavailable")
return
}
info, err := h.svc.Info()
if err != nil {
if errors.Is(err, service.ErrSystemUnavailable) {
writeJSONError(w, http.StatusServiceUnavailable, "system_unavailable")
return
}
writeJSONError(w, http.StatusInternalServerError, "internal_error")
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(info)
}

type systemShutdownBody struct {
Mode string `json:"mode"`
}

// Shutdown handles POST /api/v1/admin/system/shutdown.
func (h *SystemHandler) Shutdown(w http.ResponseWriter, r *http.Request) {
if h.svc == nil {
writeJSONError(w, http.StatusServiceUnavailable, "system_unavailable")
return
}
var body systemShutdownBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid_body")
return
}
err := h.svc.RequestShutdown(body.Mode)
if err != nil {
switch {
case errors.Is(err, service.ErrInvalidShutdownMode):
writeJSONError(w, http.StatusBadRequest, "invalid_mode")
case errors.Is(err, service.ErrSystemNotInit):
writeJSONError(w, http.StatusConflict, "system_not_init")
case errors.Is(err, service.ErrSystemUnavailable):
writeJSONError(w, http.StatusServiceUnavailable, "system_unavailable")
default:
writeJSONError(w, http.StatusInternalServerError, "internal_error")
}
return
}
w.WriteHeader(http.StatusNoContent)
}
92 changes: 92 additions & 0 deletions pkgs/bigfred/server/http/system_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package httpapi

import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/require"

miclient "github.com/dcc-bigfred/microinit/go/client"
"github.com/keskad/loco/pkgs/bigfred/server/service"
)

func mountSystem(h *SystemHandler) http.Handler {
r := chi.NewRouter()
r.Get("/api/v1/admin/system", h.Get)
r.Post("/api/v1/admin/system/shutdown", h.Shutdown)
return r
}

type fakePower struct {
info *miclient.DaemonInfo
infoErr error
}

func (f *fakePower) Info() (*miclient.DaemonInfo, error) {
if f.infoErr != nil {
return nil, f.infoErr
}
return f.info, nil
}

func (f *fakePower) ShutdownMode(string) error { return nil }

func TestSystemGetUnavailable(t *testing.T) {
h := NewSystemHandler(nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/system", nil)
rec := httptest.NewRecorder()
mountSystem(h).ServeHTTP(rec, req)
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
}

func TestSystemShutdownInvalidMode(t *testing.T) {
ctl := service.NewSystemControl(nil)
h := NewSystemHandler(ctl)
body, _ := json.Marshal(map[string]string{"mode": "halt"})
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/system/shutdown", bytes.NewReader(body))
rec := httptest.NewRecorder()
mountSystem(h).ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
}

func TestSystemShutdownModeValidationOrder(t *testing.T) {
err := service.NewSystemControl(nil).RequestShutdown("halt")
require.True(t, errors.Is(err, service.ErrInvalidShutdownMode))
err = service.NewSystemControl(nil).RequestShutdown("poweroff")
require.True(t, errors.Is(err, service.ErrSystemUnavailable))
}

func TestSystemShutdownNotInit(t *testing.T) {
ctl := service.NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: "supervise"},
})
h := NewSystemHandler(ctl)
body, _ := json.Marshal(map[string]string{"mode": "poweroff"})
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/system/shutdown", bytes.NewReader(body))
rec := httptest.NewRecorder()
mountSystem(h).ServeHTTP(rec, req)
require.Equal(t, http.StatusConflict, rec.Code)
var env map[string]string
require.NoError(t, json.NewDecoder(rec.Body).Decode(&env))
require.Equal(t, "system_not_init", env["error"])
}

func TestSystemGetInit(t *testing.T) {
ctl := service.NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: "init"},
})
h := NewSystemHandler(ctl)
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/system", nil)
rec := httptest.NewRecorder()
mountSystem(h).ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var info service.SystemInfo
require.NoError(t, json.NewDecoder(rec.Body).Decode(&info))
require.Equal(t, "init", info.Mode)
require.True(t, info.CanShutdown)
}
101 changes: 101 additions & 0 deletions pkgs/bigfred/server/service/system.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package service

import (
"errors"
"fmt"

miclient "github.com/dcc-bigfred/microinit/go/client"
)

var (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ [POSITIVE] The explicit error types (ErrSystemUnavailable, ErrSystemNotInit, ErrInvalidShutdownMode) and their consistent usage throughout the service and HTTP layers provide excellent clarity and allow for precise error handling on the client side. Additionally, the design of NewSystemControl to gracefully handle nil ServiceManager implementations (e.g., for tests or --no-supervisor mode) is a good practice for robustness.

// ErrSystemUnavailable is returned when microinit is not wired
// (--no-supervisor) or the control socket cannot be reached.
ErrSystemUnavailable = errors.New("system control unavailable")
// ErrSystemNotInit is returned when machine poweroff/reboot is
// requested but microinit is running in supervise mode.
ErrSystemNotInit = errors.New("system shutdown requires microinit init mode")
// ErrInvalidShutdownMode is returned for unknown shutdown modes.
ErrInvalidShutdownMode = errors.New("invalid shutdown mode")
)

// SystemInfo is the admin-facing snapshot of host power capability.
type SystemInfo struct {
Mode string `json:"mode"`
CanShutdown bool `json:"canShutdown"`
}

// MicroinitPower is the subset of the microinit Go client used for host power.
type MicroinitPower interface {
Info() (*miclient.DaemonInfo, error)
ShutdownMode(mode string) error
}

// SystemControl talks to microinit for host power control.
type SystemControl struct {
power MicroinitPower
}

// NewSystemControl wraps a ServiceManager when it is the microinit-backed
// *manager with a live supervisor; otherwise returns a control that always
// reports unavailable (tests / --no-supervisor).
func NewSystemControl(mgr ServiceManager) *SystemControl {
m, ok := mgr.(*manager)
if !ok || m == nil || m.supervisor == nil {
return &SystemControl{}
}
return &SystemControl{power: m.supervisor.Client()}
}

// NewSystemControlWithPower is for tests that inject a fake microinit client.
func NewSystemControlWithPower(power MicroinitPower) *SystemControl {
return &SystemControl{power: power}
}

// Info returns microinit mode and whether machine poweroff/reboot is allowed.
func (s *SystemControl) Info() (SystemInfo, error) {
if s == nil || s.power == nil {
return SystemInfo{}, ErrSystemUnavailable
}
info, err := s.power.Info()
if err != nil {
return SystemInfo{}, fmt.Errorf("%w: %v", ErrSystemUnavailable, err)
}
mode := normalizeDaemonMode(info.Mode)
return SystemInfo{
Mode: mode,
CanShutdown: mode == "init",
}, nil
}

// RequestShutdown sends poweroff or reboot to microinit when mode is init.
// Halt is intentionally rejected here — BigFred admin UI only offers
// poweroff/reboot; direct SDK callers may use Client.ShutdownMode("halt").
func (s *SystemControl) RequestShutdown(mode string) error {
switch mode {
case "poweroff", "reboot":
default:
return fmt.Errorf("%w: %q", ErrInvalidShutdownMode, mode)
}
if s == nil || s.power == nil {
return ErrSystemUnavailable
}
info, err := s.power.Info()
if err != nil {
return fmt.Errorf("%w: %v", ErrSystemUnavailable, err)
}
// Empty Mode (older microinit without the field) is treated as supervise:
// refuse host power rather than assume init. Same rule as Info().
if normalizeDaemonMode(info.Mode) != "init" {
return ErrSystemNotInit
}
return s.power.ShutdownMode(mode)
}

// normalizeDaemonMode maps wire values to "init" or "supervise".
// Unknown / empty → supervise (safe side: deny host power).
func normalizeDaemonMode(mode string) string {
if mode == "init" {
return "init"
}
return "supervise"
}
79 changes: 79 additions & 0 deletions pkgs/bigfred/server/service/system_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package service

import (
"errors"
"testing"

miclient "github.com/dcc-bigfred/microinit/go/client"
"github.com/stretchr/testify/require"
)

type fakePower struct {
info *miclient.DaemonInfo
infoErr error
shutErr error
lastMode string
}

func (f *fakePower) Info() (*miclient.DaemonInfo, error) {
if f.infoErr != nil {
return nil, f.infoErr
}
return f.info, nil
}

func (f *fakePower) ShutdownMode(mode string) error {
f.lastMode = mode
return f.shutErr
}

func TestSystemControlInfoEmptyModeIsSupervise(t *testing.T) {
ctl := NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: ""},
})
info, err := ctl.Info()
require.NoError(t, err)
require.Equal(t, "supervise", info.Mode)
require.False(t, info.CanShutdown)
}

func TestSystemControlInfoInit(t *testing.T) {
ctl := NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: "init"},
})
info, err := ctl.Info()
require.NoError(t, err)
require.Equal(t, "init", info.Mode)
require.True(t, info.CanShutdown)
}

func TestSystemControlRequestShutdownEmptyModeNotInit(t *testing.T) {
ctl := NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: ""},
})
err := ctl.RequestShutdown("poweroff")
require.True(t, errors.Is(err, ErrSystemNotInit))
}

func TestSystemControlRequestShutdownSupervise(t *testing.T) {
ctl := NewSystemControlWithPower(&fakePower{
info: &miclient.DaemonInfo{Mode: "supervise"},
})
err := ctl.RequestShutdown("reboot")
require.True(t, errors.Is(err, ErrSystemNotInit))
}

func TestSystemControlRequestShutdownInit(t *testing.T) {
fp := &fakePower{info: &miclient.DaemonInfo{Mode: "init"}}
ctl := NewSystemControlWithPower(fp)
require.NoError(t, ctl.RequestShutdown("poweroff"))
require.Equal(t, "poweroff", fp.lastMode)
}

func TestSystemControlNilPowerUnavailable(t *testing.T) {
ctl := NewSystemControl(nil)
_, err := ctl.Info()
require.True(t, errors.Is(err, ErrSystemUnavailable))
err = ctl.RequestShutdown("poweroff")
require.True(t, errors.Is(err, ErrSystemUnavailable))
}
Loading
Loading