-
Notifications
You must be signed in to change notification settings - Fork 0
feat: admin system power control via microinit #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ( | ||
| // 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" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 ofNewSystemControlto gracefully handlenilServiceManagerimplementations (e.g., for tests or--no-supervisormode) is a good practice for robustness.