carlos / platform Public

feat: create and follow managed fleet operations from the CLI

Expose account-member managed create, add and read-only preview with durable
request replay and frozen plans. Follow SQL progress from the CLI, preserve
BYO guards and document the disabled provider-neutral 2a scope.

Include targeted tests, claim route fixtures and a root census proposal
for controller review before landing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev adc1feea47c86304a37e82eae8246210190e8037 parent e6bb13e
16 files changed, +1,183 −23
  • apimode_managedfleets.go +149 −6
  • docs/site/cli.md +37 −1
  • docs/superpowers/notes/census-proposal-managed-fleets-2a-task-9.md +15 −0
  • fleets.go +33 −3
  • fleets_managed.go +55 −3
  • fleets_managed_test.go +115 −0
  • internal/console/authcli.go +2 −0
  • internal/console/claim_invariant_fixtures_test.go +12 −0
  • internal/console/fleets.go +2 −2
  • internal/console/managedapi.go +292 −0
  • internal/console/managedapi_test.go +362 −0
  • internal/console/managedview.go +96 −6
  • internal/console/svcroutes_test.go +4 −2
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-9.tsv +6 −0
diff --git a/apimode_managedfleets.go b/apimode_managedfleets.go
index c8e331707..4078edb6c 100644
--- a/apimode_managedfleets.go
+++ b/apimode_managedfleets.go
@@ -1,11 +1,14 @@
package main
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
+ "io"
"net/http"
"net/url"
+ "time"
)
type apiManagedCheck struct {
@@ -21,13 +24,20 @@ type apiFleetShowBox struct {
Checks map[string]apiManagedCheck `json:"checks"`
}
+type apiFleetShowPlan struct {
+ Region string `json:"region"`
+ Size string `json:"size"`
+ InstanceType string `json:"instance_type,omitempty"`
+ Boxes int `json:"boxes"`
+}
type apiFleetShowOperation struct {
- ID string `json:"id"`
- Kind string `json:"kind"`
- State string `json:"state"`
- Outcome string `json:"outcome"`
- Error string `json:"error"`
- Requested int `json:"requested"`
+ Plan *apiFleetShowPlan `json:"plan,omitempty"`
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ Outcome string `json:"outcome"`
+ Error string `json:"error"`
+ Requested int `json:"requested"`
}
type apiFleetShowReply struct {
@@ -54,3 +64,136 @@ func (s *apiSession) showFleet(ctx context.Context, a apiAcct, name string) (api
} // COPY
return out, nil
}
+
+// COPY: errors and progress await controller copy review.
+func (s *apiSession) createManagedFleet(ctx context.Context, a apiAcct, name, region, size, requestID string, boxes int) (apiFleetShowReply, error) {
+ return s.postManagedFleet(ctx, a, name, "/new", map[string]any{"name": name, "managed": true, "region": region, "size": size, "boxes": boxes, "request_id": requestID})
+}
+func (s *apiSession) addManagedFleetBoxes(ctx context.Context, a apiAcct, name, requestID string, boxes int) (apiFleetShowReply, error) {
+ return s.postManagedFleet(ctx, a, name, "/"+url.PathEscape(name)+"/managed-boxes", map[string]any{"boxes": boxes, "request_id": requestID})
+}
+func (s *apiSession) postManagedFleet(ctx context.Context, a apiAcct, name, path string, in any) (out apiFleetShowReply, err error) {
+ for attempt := 0; attempt < 3; attempt++ {
+ code, body, e := s.postJSON(ctx, fleetPath(a, path), in)
+ if e == nil && code != http.StatusAccepted {
+ return out, apiErrorFromBody(code, body)
+ }
+ if e == nil {
+ e = json.Unmarshal(body, &out)
+ if e == nil && out.Name == name && out.Managed && out.Boxes != nil && out.Operation != nil && out.Operation.ID != "" && out.Operation.Plan != nil {
+ return out, nil
+ }
+ if e == nil {
+ e = fmt.Errorf("managed fleet: incomplete operation response")
+ }
+ }
+ err = e
+ if ctx.Err() != nil {
+ return out, ctx.Err()
+ }
+ if attempt < 2 {
+ if e = waitManagedPoll(ctx); e != nil {
+ return out, e
+ }
+ }
+ }
+ return out, err
+}
+func waitManagedPoll(ctx context.Context) error {
+ timer := time.NewTimer(2 * time.Second)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return nil
+ }
+}
+func managedFollowInterrupted(w io.Writer, name string) {
+ fmt.Fprintf(w, "Following stopped. The operation continues. Resume with carlos fleets show %s.\n", name)
+}
+func (s *apiSession) followManagedFleet(ctx context.Context, a apiAcct, name string, w io.Writer) error {
+ return s.followManagedFleetFrom(ctx, a, name, w, nil)
+}
+func (s *apiSession) followManagedFleetFrom(ctx context.Context, a apiAcct, name string, w io.Writer, initial *apiFleetShowReply) (err error) {
+ defer func() {
+ if ctx.Err() != nil {
+ managedFollowInterrupted(w, name)
+ }
+ }()
+ var previous []byte
+ for {
+ var out apiFleetShowReply
+ if initial != nil {
+ out = *initial
+ initial = nil
+ } else {
+ out, err = s.showFleet(ctx, a, name)
+ if err != nil {
+ return err
+ }
+ }
+ encoded, _ := json.Marshal(out)
+ if !bytes.Equal(previous, encoded) {
+ printFleetShow(w, out)
+ previous = encoded
+ }
+ if out.Operation == nil || out.Operation.State != "open" {
+ if out.Operation != nil && (out.Operation.State == "failed" || out.Operation.Outcome == "failed" || out.Operation.Error != "") {
+ return fmt.Errorf("managed fleet operation %s finished with failures", out.Operation.ID)
+ }
+ return nil
+ }
+ if err = waitManagedPoll(ctx); err != nil {
+ return err
+ }
+ }
+}
+func printManagedPlan(w io.Writer, p *apiFleetShowPlan) {
+ if p == nil {
+ return
+ }
+ typ := p.InstanceType
+ if typ == "" {
+ typ = "pending allocation"
+ }
+ fmt.Fprintf(w, "Plan: %d boxes, region %s, size %s, instance type %s\n", p.Boxes, p.Region, p.Size, typ)
+}
+func (s *apiSession) runManagedFleet(ctx context.Context, a apiAcct, name, kind, region, size, requestID string, boxes int, w io.Writer) error {
+ req := map[string]any{"name": name, "kind": kind, "boxes": boxes, "request_id": requestID}
+ if kind == "create" {
+ req["region"], req["size"] = region, size
+ }
+ code, body, err := s.postJSON(ctx, fleetPath(a, "/managed-plan"), req)
+ if err != nil {
+ return err
+ }
+ if code != 200 {
+ return apiErrorFromBody(code, body)
+ }
+ var plan apiFleetShowPlan
+ if err = json.Unmarshal(body, &plan); err != nil {
+ return err
+ }
+ if plan.Region == "" || plan.Size == "" || plan.Boxes != boxes {
+ return fmt.Errorf("managed fleet: incomplete plan response")
+ }
+ printManagedPlan(w, &plan)
+ var out apiFleetShowReply
+ if kind == "create" {
+ out, err = s.createManagedFleet(ctx, a, name, region, size, requestID, boxes)
+ } else {
+ out, err = s.addManagedFleetBoxes(ctx, a, name, requestID, boxes)
+ }
+ if err != nil {
+ if ctx.Err() != nil {
+ managedFollowInterrupted(w, name)
+ }
+ return err
+ }
+ if *out.Operation.Plan != plan {
+ fmt.Fprintln(w, "Reserved plan:")
+ printManagedPlan(w, out.Operation.Plan)
+ }
+ return s.followManagedFleetFrom(ctx, a, name, w, &out)
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 8d5e4301d..372c090a3 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2256,14 +2256,50 @@ To check that a box holds the registered key, run `carlos secrets fingerprint` o
You can replace a fleet's key only while none of its apps holds a sealed value. Unset those apps' secrets, register the new key, set the secrets again and rotate the credentials the console minted. If a key may have leaked, take the box off the fleet first. A box that has never run an instance can be detached at once with `carlos fleets detach-box <fleet> <label>`. Otherwise drain it with `carlos fleets drain <fleet> <label>`, terminate its machine once its instances have moved, then detach it with `carlos fleets detach-box --terminated <fleet> <label>`. Rotate the credentials after detaching. The drain needs the box's current token: rotating first would cut the box off before it sees its instances leave. A detached box stops reading the platform's store.
+<!-- COPY: managed fleet command documentation awaits controller review. -->
+### carlos fleets create
+
+With managed fleets enabled, preview capacity and follow its operation:
+
+```sh
+carlos fleets create --managed --region eu-west-1 --size large --boxes 3 production
+```
+
+The CLI prints the region, named size, instance type and box count before
+submitting the request. If configuration changes before reservation, it also
+prints the plan actually reserved. Repeating an identical request while its
+operation is open follows that operation.
+
+The provider-neutral core in 2a is tested against fakes and stays off. The real
+adapter and complete readiness ship in 2b. This phase introduces no monthly
+charge or hourly compute billing. Bring-your-own creation still uses `--bucket`.
+
+### carlos fleets boxes add
+
+Add capacity using the fleet's creation region and named size:
+
+```sh
+carlos fleets boxes add --boxes 1 production
+```
+
+New capacity uses the current configuration for that size. If the operator has
+removed the region or size, new capacity is refused. Existing operations keep
+their reserved plan.
+
### carlos fleets show
-Show each box's active or detached status and its last observed version:
+Show each box's state and observed version. Managed fleets include readiness
+checks and operation progress:
```sh
carlos fleets show --account ops production
```
+An open operation is followed every two seconds. Ctrl-C stops following; the
+console keeps working. Run `carlos fleets show production` to follow it again.
+If some boxes fail, ready boxes remain available, failed labels and reasons are
+printed, and the command exits with a failure status. A settled fleet prints once.
+
A box with no available version report shows `unknown`. Bring-your-own fleets
have no managed readiness checks. Use `--account-id` to select an exact account sqid.
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-9.md b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-9.md
new file mode 100644
index 000000000..d264d1985
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-9.md
@@ -0,0 +1,15 @@
+# Census approval: managed-fleets-2a-task-9
+
+Ruling `census-ruling-managed-fleets-2a-task-9`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `fleets_managed.go:runManagedFleetCommand`: reads +file:Read; written legacy, accepted-legacy, frozen
+
+Seal: `63e8cb293a3ee2eea6250aee0f79d2fe7b381df9d19f90808a6768ef058a23e4` → `639b72119e79e65677359f437a70ea595749153fdee3f74be57237a8019115a2`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-9.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/fleets.go b/fleets.go
index 2477370fc..bde992795 100644
--- a/fleets.go
+++ b/fleets.go
@@ -31,7 +31,8 @@ import (
"github.com/carlosframework/platform/internal/registry"
)
-const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|drain|detach-box|secrets-key|show|ls> [flags]
+// COPY: managed create, boxes add and show help additions.
+const fleetsUsage = `usage: carlos fleets <create|boxes|add-box|rotate-token|tag-box|drain|detach-box|secrets-key|show|ls> [flags]
create --bucket <bucket> [--account <sqid|name>] <name>
mint an account-owned fleet: a named group of remote boxes
@@ -43,6 +44,12 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d
name is taken" refusal on a retry does not necessarily mean
YOU took it.
+ create --managed --region <region> --size <size> --boxes <count> <name>
+ preview and follow a durable managed fleet operation.
+
+ boxes add --boxes <count> [--account <sqid|name>] <fleet>
+ add managed boxes using the fleet creation region and size.
+
add-box [--account <sqid|name>] <fleet> <label>
register one box to a fleet and mint its bearer token. THE
TOKEN IS PRINTED EXACTLY ONCE, HERE — the console never
@@ -104,7 +111,8 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d
console could not read every box's report, and - otherwise.
show [--account <sqid|name>] <fleet>
- show each box's status and observed version.
+ show each box's status, observed version and readiness checks.
+ follow open operations; Ctrl-C stops following only.
--account <sqid|name> account the fleet belongs to (default: your only
account, or the configured/chosen one) —
@@ -128,6 +136,11 @@ func RunFleets(args []string) {
switch args[0] {
case "create":
runFleetsCreate(args[1:])
+ case "boxes":
+ if len(args) < 2 || args[1] != "add" {
+ log.Fatal("usage: carlos fleets boxes add --boxes <count> <fleet>")
+ } // COPY
+ runFleetsManagedAdd(args[2:])
case "add-box":
runFleetsAddBox(args[1:])
case "rotate-token":
@@ -191,13 +204,18 @@ func validBoxLabel(label string) error {
func runFleetsCreate(args []string) {
fs := flag.NewFlagSet("fleets create", flag.ExitOnError)
+ // COPY: managed create flags.
+ managed := fs.Bool("managed", false, "create a managed fleet")
+ region := fs.String("region", "", "managed fleet region")
+ size := fs.String("size", "", "managed fleet size")
+ boxes := fs.Int("boxes", 0, "number of managed boxes")
bucket := fs.String("bucket", "", "the customer's own data bucket (must already exist)")
acctRaw := fs.String("account", "", "account (sqid or name) to own the fleet (default: your only account, or the configured/chosen one)")
acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account")
consoleFlag := consoleOption(fs, "console to create it through (default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
- if fs.NArg() != 1 || strings.TrimSpace(*bucket) == "" {
+ if fs.NArg() != 1 || (!*managed && strings.TrimSpace(*bucket) == "") {
log.Fatal("usage: carlos fleets create --bucket <bucket> [--account <sqid|name>] " +
"[--account-id <sqid>] [--console <origin>] <name>")
}
@@ -205,6 +223,18 @@ func runFleetsCreate(args []string) {
if err := validFleetName(name); err != nil {
log.Fatalf("fleets create: %v", err)
}
+ if *managed {
+ if *bucket != "" || *region == "" || *size == "" || *boxes <= 0 {
+ log.Fatal("managed create needs --region, --size and positive --boxes; --bucket is not allowed")
+ } // COPY
+ sess := fleetsSignedInSession(*consoleFlag)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ runManagedFleetCommand(sess, acct, name, "create", *region, *size, *boxes)
+ return
+ }
+ if *region != "" || *size != "" || *boxes != 0 {
+ log.Fatal("--region, --size and --boxes require --managed")
+ } // COPY
bucketV := strings.TrimSpace(*bucket)
sess := fleetsSignedInSession(*consoleFlag)
diff --git a/fleets_managed.go b/fleets_managed.go
index 32d64f309..f34e8f33d 100644
--- a/fleets_managed.go
+++ b/fleets_managed.go
@@ -2,10 +2,15 @@ package main
import (
"context"
+ "crypto/rand"
+ "encoding/hex"
"flag"
"fmt"
"io"
"log"
+ "os"
+ "os/signal"
+ "sort"
"text/tabwriter"
)
@@ -27,15 +32,19 @@ func runFleetsShow(args []string) {
}
sess := fleetsSignedInSession(*consoleFlag)
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
- out, err := sess.showFleet(context.Background(), acct, name)
- if err != nil {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
+ defer stop()
+ if err := sess.followManagedFleet(ctx, acct, name, stdout); err != nil {
log.Fatal(err)
}
- printFleetShow(stdout, out)
}
func printFleetShow(w io.Writer, out apiFleetShowReply) {
fmt.Fprintln(w, out.Name)
+ if op := out.Operation; op != nil {
+ fmt.Fprintf(w, "Operation %s: %s %s %s\n", op.ID, op.State, op.Outcome, op.Error) // COPY
+ printManagedPlan(w, op.Plan)
+ }
if len(out.Boxes) == 0 {
fmt.Fprintln(w, "no boxes")
return
@@ -50,4 +59,47 @@ func printFleetShow(w io.Writer, out apiFleetShowReply) {
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", b.Label, b.State, version, b.LastError)
}
tw.Flush()
+ for _, b := range out.Boxes {
+ keys := make([]string, 0, len(b.Checks))
+ for key := range b.Checks {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ check := b.Checks[key]
+ fmt.Fprintf(w, " %s %s: %s %s\n", b.Label, key, check.State, check.Reason)
+ }
+ }
+}
+
+// COPY: flags, usage and errors await controller review.
+func runFleetsManagedAdd(args []string) {
+ fs := flag.NewFlagSet("fleets boxes add", flag.ExitOnError)
+ boxes := fs.Int("boxes", 0, "number of boxes to add")
+ acctRaw := fs.String("account", "", "account name or sqid")
+ acctIDRaw := fs.String("account-id", "", "exact account sqid; overrides --account")
+ consoleFlag := consoleOption(fs, "console to add boxes through")
+ fs.Usage = flagUsage(fs, "<fleet>")
+ fs.Parse(args)
+ if fs.NArg() != 1 || *boxes <= 0 {
+ log.Fatal("usage: carlos fleets boxes add --boxes <count> <fleet>")
+ }
+ name := fs.Arg(0)
+ if err := validFleetName(name); err != nil {
+ log.Fatal(err)
+ }
+ sess := fleetsSignedInSession(*consoleFlag)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ runManagedFleetCommand(sess, acct, name, "add", "", "", *boxes)
+}
+func runManagedFleetCommand(s *apiSession, a apiAcct, name, kind, region, size string, boxes int) {
+ var raw [16]byte
+ if _, err := rand.Read(raw[:]); err != nil {
+ log.Fatal(err)
+ }
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
+ defer stop()
+ if err := s.runManagedFleet(ctx, a, name, kind, region, size, hex.EncodeToString(raw[:]), boxes, stdout); err != nil {
+ log.Fatal(err)
+ }
}
diff --git a/fleets_managed_test.go b/fleets_managed_test.go
index a2eb0f73f..ac0f6a762 100644
--- a/fleets_managed_test.go
+++ b/fleets_managed_test.go
@@ -3,12 +3,16 @@ package main
import (
"bytes"
"context"
+ "encoding/json"
+ "errors"
"fmt"
"net/http"
"net/http/httptest"
"os/exec"
"strings"
+ "sync"
"testing"
+ "time"
)
func TestFleetsShowCLI(t *testing.T) {
@@ -69,3 +73,114 @@ func TestFleetsShowCLIRefusesDirectMode(t *testing.T) {
t.Fatalf("direct show: %v %s", err, out)
}
}
+
+func TestManagedCLIPreviewAndRetry(t *testing.T) {
+ var buf bytes.Buffer
+ posts, previews := 0, 0
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("exact") != "sqid" {
+ t.Error("lost exact account selector")
+ }
+ if strings.HasSuffix(r.URL.Path, "managed-plan") {
+ previews++
+ fmt.Fprint(w, `{"region":"eu-west-1","size":"large","instance_type":"m7g.large","boxes":2}`)
+ return
+ }
+ posts++
+ if !strings.Contains(buf.String(), "m7g.large") {
+ t.Error("POST before preview printed")
+ }
+ var in map[string]any
+ json.NewDecoder(r.Body).Decode(&in)
+ if in["request_id"] != "aaaaaaaaaaaaaaaaaaaaaa" {
+ t.Error("lost request id")
+ }
+ if posts == 1 {
+ h := w.(http.Hijacker)
+ c, _, _ := h.Hijack()
+ c.Close()
+ return
+ }
+ w.WriteHeader(http.StatusAccepted)
+ fmt.Fprint(w, `{"name":"production","managed":true,"boxes":[],"operation":{"id":"op","state":"done","outcome":"success","plan":{"region":"eu-west-1","size":"large","instance_type":"m8g.large","boxes":2}}}`)
+ }))
+ defer ts.Close()
+ s := newTestSession(ts.URL)
+ err := s.runManagedFleet(context.Background(), apiAcct{Seg: "chosen", Exact: true}, "production", "create", "eu-west-1", "large", "aaaaaaaaaaaaaaaaaaaaaa", 2, &buf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if posts != 2 || previews != 1 || !strings.Contains(buf.String(), "m8g.large") {
+ t.Fatalf("posts %d previews %d output %s", posts, previews, &buf)
+ }
+}
+func TestManagedCLIFollow(t *testing.T) {
+ var polls int
+ var times []time.Time
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ polls++
+ times = append(times, time.Now())
+ state := "open"
+ outcome := ""
+ if polls == 2 {
+ state = "done"
+ outcome = "failed"
+ }
+ fmt.Fprintf(w, `{"name":"production","managed":true,"boxes":[{"label":"box-1","state":"ready"},{"label":"box-2","state":"failed","last_error":"failed"}],"operation":{"id":"op","state":%q,"outcome":%q}}`, state, outcome)
+ }))
+ defer ts.Close()
+ var buf bytes.Buffer
+ err := newTestSession(ts.URL).followManagedFleet(context.Background(), apiAcct{Seg: "chosen"}, "production", &buf)
+ if err == nil || polls != 2 || times[1].Sub(times[0]) < 2*time.Second || !strings.Contains(buf.String(), "box-1") || !strings.Contains(buf.String(), "box-2") {
+ t.Fatalf("follow %v %d %s", err, polls, &buf)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ buf.Reset()
+ err = newTestSession(ts.URL).followManagedFleet(ctx, apiAcct{Seg: "chosen"}, "production", &buf)
+ if !errors.Is(err, context.Canceled) || !strings.Contains(buf.String(), "carlos fleets show production") {
+ t.Fatalf("cancel %v %s", err, &buf)
+ }
+}
+
+func TestManagedCLISelectors(t *testing.T) {
+ bin := buildCarlos(t)
+ path := useTempCredentials(t)
+ clearDeploymentEnv(t)
+ var mu sync.Mutex
+ polls := 0
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/cli/fleets/abc/production" || r.URL.Query().Get("exact") != "sqid" || r.Header.Get("Authorization") != "Bearer cli-token" {
+ t.Errorf("wrong selector or credential: %s", r.URL)
+ }
+ mu.Lock()
+ polls++
+ state := "open"
+ if polls >= 2 {
+ state = "done"
+ }
+ mu.Unlock()
+ fmt.Fprintf(w, `{"name":"production","managed":true,"boxes":[],"operation":{"id":"op","state":%q,"outcome":"success"}}`, state)
+ }))
+ defer ts.Close()
+ creds, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ creds.put(credential{Console: ts.URL, Address: "member@example.com", Token: "cli-token", ExpiresAt: time.Now().Add(time.Hour)})
+ if err = creds.save(); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(bin, "fleets", "show", "--console", ts.URL, "--account", "wrong", "--account-id", "abc", "production")
+ cmd.Dir = t.TempDir()
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+path)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatal(err, string(out))
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if polls != 2 || !strings.Contains(string(out), "done") {
+ t.Fatal(polls, string(out))
+ }
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 0fc735dc2..b59e34a12 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -983,6 +983,8 @@ func (s *Server) registerCLIRoutes() {
// act, and no service role reaches it — the same escalation cut as the
// mint door above. Pinned by TestNoRoleReachesAMintFleetOrPolicyDoor.
s.cliRoute("POST /api/cli/fleets/{account}/new", svcrole.Set{}, s.handleAPIFleetNew)
+ s.cliRoute("POST /api/cli/fleets/{account}/managed-plan", svcrole.Set{}, s.handleAPIManagedFleetPlan)
+ s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/managed-boxes", svcrole.Set{}, s.handleAPIManagedFleetAdd)
s.cliRoute("GET /api/cli/fleets/{account}", svcrole.Set{}, s.handleAPIFleetList)
s.cliRoute("GET /api/cli/fleets/{account}/{fleet}", svcrole.Set{}, s.handleAPIFleetShow)
s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes", svcrole.Set{}, s.handleAPIFleetAddBox)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index f28688913..b6859111d 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1350,6 +1350,18 @@ var claimFixtures = map[string]claimFixture{
// ---- POST: unauthenticated, signed ----
// SES delivery events count against the sending app (mail_sender_counts).
+ "route POST /api/cli/fleets/{account}/managed-plan": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodPost, "/api/cli/fleets/bab/managed-plan", `{"name":"production","kind":"create","region":"eu-west-1","size":"large","boxes":1}`), status: http.StatusConflict, msg: errManagedHostClaim.Error(),
+ }},
+ "route POST /api/cli/fleets/{account}/{fleet}/managed-boxes": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), setup: func(t *testing.T, cx *claimCase) {
+ reg := openTestReg(t, cx.consoleFixture)
+ defer reg.Close()
+ if err := reg.UpsertFleet(registry.Fleet{Name: "production", Account: "bab", Managed: true}); err != nil {
+ t.Fatal(err)
+ }
+ }, do: claimRefusedAPI(http.MethodPost, "/api/cli/fleets/bab/production/managed-boxes", `{"boxes":1,"request_id":"aaaaaaaaaaaaaaaaaaaaaa"}`), status: http.StatusConflict, msg: errManagedHostClaim.Error(),
+ }},
"route POST /api/fleet/enrol": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo"),
do: claimRefusedAPI(http.MethodPost, "/api/fleet/enrol", `{"token":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","data_dir_empty":true,"data_dir_entries":0}`),
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 39509d4b4..85d9a4e8c 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -182,7 +182,7 @@ var bucketNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$`)
// name a first caller just created (an earlier revision of this handler did
// a GetFleet pre-check before UpsertFleet, which had exactly that race;
// CreateFleet replaces both calls with the one atomic one).
-func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
+func (s *Server) handleAPIBYOFleetNew(w http.ResponseWriter, r *http.Request) {
addr, acct, ok := s.apiAccount(w, r)
if !ok {
return
@@ -291,7 +291,7 @@ func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusInternalServerError, "could not create the fleet — try again")
return
}
- if row == nil || row.Account != acct.Sqid {
+ if row == nil || row.Account != acct.Sqid || row.Managed {
jsonError(w, http.StatusConflict, "that name is taken")
return
}
diff --git a/internal/console/managedapi.go b/internal/console/managedapi.go
new file mode 100644
index 000000000..0d5cf446e
--- /dev/null
+++ b/internal/console/managedapi.go
@@ -0,0 +1,292 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "io"
+ "log"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type managedAPIRequest struct {
+ Name string `json:"name"`
+ Managed bool `json:"managed"`
+ Region string `json:"region"`
+ Size string `json:"size"`
+ Boxes int `json:"boxes"`
+ RequestID string `json:"request_id"`
+}
+
+func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
+ if _, _, ok := s.apiAccount(w, r); !ok {
+ return
+ }
+ var raw json.RawMessage
+ if !readManagedJSON(w, r, &raw) {
+ return
+ }
+ var kind struct {
+ Managed bool `json:"managed"`
+ }
+ if json.Unmarshal(raw, &kind) != nil {
+ jsonError(w, 400, "invalid fleet request")
+ return
+ } // COPY
+ r.Body = io.NopCloser(bytes.NewReader(raw))
+ if kind.Managed {
+ s.handleAPIManagedFleetCreate(w, r)
+ } else {
+ s.handleAPIBYOFleetNew(w, r)
+ }
+}
+
+// COPY: request errors and operation progress in this file await controller review.
+func readManagedJSON(w http.ResponseWriter, r *http.Request, out any) bool {
+ ct, _, _ := strings.Cut(r.Header.Get("Content-Type"), ";")
+ if strings.TrimSpace(strings.ToLower(ct)) != "application/json" {
+ jsonError(w, 415, "send a JSON request")
+ return false
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
+ d := json.NewDecoder(r.Body)
+ d.DisallowUnknownFields()
+ if err := d.Decode(out); err != nil {
+ jsonError(w, 400, "invalid managed fleet request")
+ return false
+ }
+ var extra any
+ if d.Decode(&extra) != io.EOF {
+ jsonError(w, 400, "send one managed fleet request")
+ return false
+ }
+ return true
+}
+func (s *Server) managedAPIError(w http.ResponseWriter, err error) {
+ var refusal *managedStoreError
+ if errors.As(err, &refusal) {
+ writeJSON(w, refusal.Status, struct {
+ Error string `json:"error"`
+ Operation string `json:"operation,omitempty"`
+ }{refusal.Reason, refusal.OpID})
+ return
+ }
+ log.Printf("console: managed fleet: %v", err)
+ jsonError(w, 503, "managed fleet operation is unavailable")
+}
+func (s *Server) managedAPIEntitlement(w http.ResponseWriter, acct *Account) bool {
+ if err := s.checkFleets(acct); err != nil {
+ if isPlanCap(err) {
+ writeJSON(w, 409, map[string]any{"error": err.Error(), "code": "cap"})
+ } else {
+ jsonError(w, 502, planCheckFailedCopy)
+ }
+ return false
+ }
+ return true
+}
+func (s *Server) handleAPIManagedFleetCreate(w http.ResponseWriter, r *http.Request) {
+ addr, acct, ok := s.apiAccount(w, r)
+ if !ok {
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowCreate(p, time.Now()) {
+ jsonError(w, 429, "fleet creation limit reached for today")
+ return
+ }
+ if s.cfg.HostClaim {
+ jsonError(w, 409, errManagedHostClaim.Error())
+ return
+ }
+ if !s.managedAPIEntitlement(w, acct) {
+ return
+ }
+ var in managedAPIRequest
+ if !readManagedJSON(w, r, &in) {
+ return
+ }
+ if !in.Managed {
+ jsonError(w, 400, "managed must be true")
+ return
+ }
+ req := managedRequest{RequestID: in.RequestID, Account: acct.Sqid, Fleet: strings.TrimSpace(in.Name), Kind: "create", Region: in.Region, Size: in.Size, Boxes: in.Boxes, CreatedBy: addr}
+ op, _, _, err := s.reserveManagedFleet(r.Context(), req)
+ if err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ s.managedAPIReserved(w, r, op)
+}
+func (s *Server) handleAPIManagedFleetAdd(w http.ResponseWriter, r *http.Request) {
+ addr, acct, fleet, _, ok := s.apiFleet(w, r)
+ if !ok {
+ return
+ }
+ if !fleet.Managed {
+ jsonError(w, 409, "this fleet is not managed")
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowWrite(p, time.Now()) {
+ jsonError(w, 429, "too many requests; try again shortly")
+ return
+ }
+ if s.cfg.HostClaim {
+ jsonError(w, 409, errManagedHostClaim.Error())
+ return
+ }
+ if !s.managedAPIEntitlement(w, acct) {
+ return
+ }
+ var in struct {
+ Boxes int `json:"boxes"`
+ RequestID string `json:"request_id"`
+ }
+ if !readManagedJSON(w, r, &in) {
+ return
+ }
+ req := managedRequest{RequestID: in.RequestID, Account: acct.Sqid, Fleet: fleet.Name, Kind: "add", Boxes: in.Boxes, CreatedBy: addr}
+ if err := s.managedAddShape(r.Context(), &req); err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ op, _, _, err := s.reserveManagedFleet(r.Context(), req)
+ if err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ s.managedAPIReserved(w, r, op)
+}
+func (s *Server) managedAddShape(ctx context.Context, req *managedRequest) error {
+ ops, boxes, err := s.store.ManagedFleet(ctx, req.Account, req.Fleet)
+ if err != nil {
+ return err
+ }
+ for _, op := range ops {
+ if op.Kind == "create" {
+ req.Region, req.Size = op.Region, op.Size
+ return nil
+ }
+ }
+ for _, b := range boxes {
+ req.Region, req.Size = b.Region, b.Size
+ return nil
+ }
+ return managedRefusal(409, "managed fleet has no creation plan", "")
+}
+func (s *Server) managedAPIReserved(w http.ResponseWriter, r *http.Request, op managedOp) {
+ out, err := s.managedFleetView(r.Context(), op.Account, op.Fleet, &op)
+ if err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
+func (s *Server) handleAPIManagedFleetPlan(w http.ResponseWriter, r *http.Request) {
+ _, acct, ok := s.apiAccount(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ jsonError(w, 409, errManagedHostClaim.Error())
+ return
+ }
+ if !s.managedAPIEntitlement(w, acct) {
+ return
+ }
+ var in struct {
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Region string `json:"region"`
+ Size string `json:"size"`
+ Boxes int `json:"boxes"`
+ RequestID string `json:"request_id"`
+ }
+ if !readManagedJSON(w, r, &in) {
+ return
+ }
+ req := managedRequest{Account: acct.Sqid, Fleet: strings.TrimSpace(in.Name), Kind: in.Kind, Region: in.Region, Size: in.Size, Boxes: in.Boxes, RequestID: in.RequestID}
+ if !registry.ValidTunnelName(req.Fleet) || req.Boxes <= 0 || (req.Kind != "create" && req.Kind != "add") || (req.RequestID != "" && !managedRequestID.MatchString(req.RequestID)) {
+ jsonError(w, 400, "invalid managed fleet request")
+ return
+ }
+ if req.Kind == "add" {
+ r.SetPathValue("fleet", req.Fleet)
+ f, _, ok := s.apiFleetOf(w, r, acct)
+ if !ok {
+ return
+ }
+ if !f.Managed {
+ jsonError(w, 409, "this fleet is not managed")
+ return
+ }
+ if in.Region != "" || in.Size != "" {
+ jsonError(w, 400, "managed add inherits its region and size")
+ return
+ }
+ if err := s.managedAddShape(r.Context(), &req); err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ }
+ if plan, found, err := s.managedPreviewExisting(r.Context(), req); err != nil {
+ s.managedAPIError(w, err)
+ return
+ } else if found {
+ writeJSON(w, 200, plan)
+ return
+ }
+ if s.cfg.ManagedCompute == nil || s.cfg.ManagedStorage == nil {
+ jsonError(w, 503, "managed providers are unavailable")
+ return
+ }
+ snap, err := s.managedSnapshot(r.Context())
+ if err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ resolved, err := resolveManagedConfig(snap, req.Region, req.Size, 1)
+ if err != nil {
+ jsonError(w, 409, err.Error())
+ return
+ }
+ writeJSON(w, 200, fleetShowPlan{Region: req.Region, Size: req.Size, InstanceType: resolved.Launch.InstanceType, Boxes: req.Boxes})
+}
+
+// Preview does not insert a request alias. Only the mutating POST joins an operation.
+func (s *Server) managedPreviewExisting(ctx context.Context, req managedRequest) (*fleetShowPlan, bool, error) {
+ var op managedOp
+ var id string
+ var payload []byte
+ err := s.store.db.QueryRowContext(ctx, `SELECT op_id,payload FROM managed_request_aliases WHERE account=? AND request_id=?`, req.Account, req.RequestID).Scan(&id, &payload)
+ if err == nil {
+ if !bytes.Equal(payload, managedPayload(req)) {
+ return nil, false, managedRefusal(409, "request ID has different parameters", "")
+ }
+ op, err = scanManagedOp(s.store.db.QueryRowContext(ctx, `SELECT `+managedOpCols+` FROM managed_ops WHERE id=? AND account=?`, id, req.Account))
+ } else if err == sql.ErrNoRows {
+ op, err = scanManagedOp(s.store.db.QueryRowContext(ctx, `SELECT `+managedOpCols+` FROM managed_ops WHERE fleet=? AND account=? AND state='open'`, req.Fleet, req.Account))
+ if err == sql.ErrNoRows {
+ return nil, false, nil
+ }
+ if err == nil && !managedMatches(op, req) {
+ return nil, false, managedRefusal(409, "fleet has a different open operation", op.ID)
+ }
+ }
+ if err != nil {
+ return nil, false, err
+ }
+ boxes, err := managedLoadBoxes(ctx, s.store.db, `WHERE op_id=? AND account=?`, op.ID, req.Account)
+ if err != nil {
+ return nil, false, err
+ }
+ return managedOperationView(op, boxes).Plan, true, nil
+}
diff --git a/internal/console/managedapi_test.go b/internal/console/managedapi_test.go
new file mode 100644
index 000000000..9464f0e18
--- /dev/null
+++ b/internal/console/managedapi_test.go
@@ -0,0 +1,362 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/status"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func managedAPIFixture(t *testing.T) *Server {
+ t.Helper()
+ s, _ := managedPreparationFixture(t)
+ s.cli = newCLILimits()
+ if err := s.store.CreateAccount(42, "abc", "shop", "owner@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.AddMember(42, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+func managedAPICall(s *Server, door, account, fleet, body string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.SetPathValue("account", account)
+ r.SetPathValue("fleet", fleet)
+ r = r.WithContext(context.WithValue(r.Context(), cliRouteKey{}, Principal{Kind: PrincipalUser, Address: "member@example.com"}))
+ w := httptest.NewRecorder()
+ switch door {
+ case "create":
+ s.handleAPIFleetNew(w, r)
+ case "add":
+ s.handleAPIManagedFleetAdd(w, r)
+ case "plan":
+ s.handleAPIManagedFleetPlan(w, r)
+ case "show":
+ s.handleAPIFleetShow(w, r)
+ }
+ return w
+}
+func managedAPIBody(id string, n int) string {
+ return fmt.Sprintf(`{"name":"production","managed":true,"region":"eu-west-1","size":"large","boxes":%d,"request_id":%q}`, n, strings.Repeat(id, 22))
+}
+func managedAPIReply(t *testing.T, w *httptest.ResponseRecorder) fleetShowReply {
+ t.Helper()
+ if w.Code != 202 && w.Code != 200 {
+ t.Fatalf("reply %d %s", w.Code, w.Body)
+ }
+ var out fleetShowReply
+ if e := json.Unmarshal(w.Body.Bytes(), &out); e != nil {
+ t.Fatal(e)
+ }
+ return out
+}
+func TestManagedAPIAnyMember(t *testing.T) {
+ s := managedAPIFixture(t)
+ out := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ if !out.Managed || out.Operation == nil || out.Operation.Plan.InstanceType == "" || len(out.Boxes) != 2 {
+ t.Fatalf("%+v", out)
+ }
+ for _, p := range [][2]string{{"abc", "absent"}, {"other", "production"}, {"other", "absent"}} {
+ w := managedAPICall(s, "show", p[0], p[1], "")
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" {
+ t.Fatal(w.Code, w.Body)
+ }
+ }
+ managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+}
+func TestManagedAPIPreview(t *testing.T) {
+ s := managedAPIFixture(t)
+ body := strings.Replace(managedAPIBody("a", 2), `"managed":true`, `"kind":"create"`, 1)
+ w := managedAPICall(s, "plan", "abc", "", body)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ var n int
+ s.store.db.QueryRow(`SELECT count(*) FROM managed_ops`).Scan(&n)
+ if n != 0 {
+ t.Fatal("preview reserved")
+ }
+ s.store.db.QueryRow(`SELECT count(*) FROM managed_request_aliases`).Scan(&n)
+ if n != 0 {
+ t.Fatal("preview wrote alias")
+ }
+ out := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ s.managed.snapshot.Config.Enabled = false
+ w = managedAPICall(s, "plan", "abc", "", strings.ReplaceAll(body, strings.Repeat("a", 22), strings.Repeat("b", 22)))
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ var plan fleetShowPlan
+ json.Unmarshal(w.Body.Bytes(), &plan)
+ if plan != *out.Operation.Plan {
+ t.Fatalf("plan changed: %+v", plan)
+ }
+ s.store.db.QueryRow(`SELECT count(*) FROM managed_request_aliases`).Scan(&n)
+ if n != 1 {
+ t.Fatal("preview joined by writing alias")
+ }
+ s.managed.snapshot.Config = validManagedConfig()
+ region := s.managed.snapshot.Config.Regions["eu-west-1"]
+ delete(region.Sizes, "large")
+ s.managed.snapshot.Config.Regions["eu-west-1"] = region
+ w = managedAPICall(s, "plan", "abc", "", body)
+ if w.Code != 200 {
+ t.Fatal("removed size blocked frozen preview", w.Code, w.Body)
+ }
+}
+func TestManagedAPIRetryClosed(t *testing.T) {
+ s := managedAPIFixture(t)
+ out := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ joined := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("b", 2)))
+ if joined.Operation.ID != out.Operation.ID {
+ t.Fatal("join changed operation")
+ }
+ s.store.db.Exec(`UPDATE managed_ops SET state='done'`)
+ s.managed.snapshot.Config.Enabled = false
+ for _, id := range []string{"a", "b"} {
+ retry := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody(id, 2)))
+ if retry.Operation.ID != out.Operation.ID {
+ t.Fatal("replay changed operation")
+ }
+ }
+ w := managedAPICall(s, "create", "abc", "", managedAPIBody("a", 3))
+ if w.Code != 409 {
+ t.Fatal(w.Code, w.Body)
+ }
+}
+func TestManagedAPIIsolation(t *testing.T) {
+ for _, field := range []string{"image", "subnet", "bucket", "client_token", "instance_type", "network"} {
+ t.Run(field, func(t *testing.T) {
+ s := managedAPIFixture(t)
+ body := strings.TrimSuffix(managedAPIBody("a", 2), "}") + fmt.Sprintf(`,%q:"injected"}`, field)
+ w := managedAPICall(s, "create", "abc", "", body)
+ if w.Code != 400 {
+ t.Fatal(w.Code, w.Body)
+ }
+ var n int
+ s.store.db.QueryRow(`SELECT count(*) FROM managed_ops`).Scan(&n)
+ if n != 0 {
+ t.Fatal("invalid request reserved")
+ }
+ })
+ }
+}
+func TestManagedAPIAddPreparation(t *testing.T) {
+ s := managedAPIFixture(t)
+ spy := &managedStorageSpy{Fake: fleetstore.NewFake(), fail: true}
+ s.cfg.ManagedStorage = spy
+ managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ s.store.db.Exec(`UPDATE managed_ops SET state='failed',error='managed_preparation_failed'`)
+ out := managedAPIReply(t, managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`))
+ if out.Operation.State != "open" || out.Operation.Kind != "add" || out.Operation.Plan.Boxes != 1 || out.Operation.Plan.InstanceType != "" {
+ t.Fatalf("%+v", out.Operation)
+ }
+ var n int
+ s.store.db.QueryRow(`SELECT count(*) FROM managed_boxes WHERE op_id=?`, out.Operation.ID).Scan(&n)
+ if n != 0 {
+ t.Fatal("allocated before preparation")
+ }
+ if spy.ensures != 0 || spy.rotations != 0 {
+ t.Fatal("POST called provider")
+ }
+ ops, _, err := s.store.ManagedFleet(context.Background(), "abc", "production")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var op managedOp
+ for _, o := range ops {
+ if o.ID == out.Operation.ID {
+ op = o
+ }
+ }
+ if err = s.prepareManagedFleet(context.Background(), op, nil); err == nil {
+ t.Fatal("preparation should fail")
+ }
+ visible := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if visible.Operation.Error != "managed_preparation_failed" {
+ t.Fatalf("hidden preparation failure %+v", visible.Operation)
+ }
+ spy.fail = false
+ if err = s.prepareManagedFleet(context.Background(), op, nil); err != nil {
+ t.Fatal(err)
+ }
+ boxes, err := s.store.AllocatePreparedManaged(context.Background(), op.ID, s.managed.snapshot, s.cfg.ManagedDeployment, time.Now(), managedHash)
+ if err != nil || len(boxes) != 1 {
+ t.Fatal("worker allocation", len(boxes), err)
+ }
+}
+
+func TestManagedAPIJoin(t *testing.T) {
+ s := managedAPIFixture(t)
+ first := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ w := managedAPICall(s, "create", "abc", "", managedAPIBody("c", 3))
+ if w.Code != 409 || !strings.Contains(w.Body.String(), first.Operation.ID) {
+ t.Fatal(w.Code, w.Body)
+ }
+ s.store.db.Exec(`UPDATE managed_ops SET state='done'`)
+ s.store.db.Exec(`INSERT INTO managed_fleet_storage(fleet,account,bucket,region,prepared) VALUES('production','abc','fake-bucket','eu-west-1',1)`)
+ add := `{"boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`
+ out := managedAPIReply(t, managedAPICall(s, "add", "abc", "production", add))
+ if out.Operation.ID == first.Operation.ID || len(out.Boxes) != 3 || out.Boxes[2].Label != "box-3" {
+ t.Fatalf("add %+v", out)
+ }
+ joined := managedAPIReply(t, managedAPICall(s, "add", "abc", "production", strings.ReplaceAll(add, "bbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccc")))
+ if joined.Operation.ID != out.Operation.ID {
+ t.Fatal("add did not join")
+ }
+ s.managed.snapshot.Config.Enabled = false
+ preview := managedAPICall(s, "plan", "abc", "", `{"name":"production","kind":"add","boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`)
+ if preview.Code != 200 {
+ t.Fatal("disabled config blocked open add preview", preview.Code, preview.Body)
+ }
+ s.store.db.Exec(`UPDATE managed_ops SET state='done'`)
+ s.managed.snapshot.Config.Regions = map[string]managedRegion{}
+ for _, id := range []string{"bbbbbbbbbbbbbbbbbbbbbb", "cccccccccccccccccccccc"} {
+ retry := managedAPIReply(t, managedAPICall(s, "add", "abc", "production", strings.ReplaceAll(add, "bbbbbbbbbbbbbbbbbbbbbb", id)))
+ if retry.Operation.ID != out.Operation.ID || len(retry.Boxes) != 3 {
+ t.Fatal("closed retry allocated")
+ }
+ }
+ s.managed.snapshot.Config = validManagedConfig()
+ next := managedAPIReply(t, managedAPICall(s, "add", "abc", "production", strings.ReplaceAll(add, "bbbbbbbbbbbbbbbbbbbbbb", "dddddddddddddddddddddd")))
+ if next.Operation.ID == out.Operation.ID || len(next.Boxes) != 4 || next.Boxes[3].Label != "box-4" {
+ t.Fatalf("new add %+v", next)
+ }
+ _, bs, _ := s.store.ManagedFleet(context.Background(), "abc", "production")
+ tokens := map[string]bool{}
+ for _, b := range bs {
+ if tokens[b.ClientToken] {
+ t.Fatal("recycled token")
+ }
+ tokens[b.ClientToken] = true
+ }
+}
+func TestManagedAPIAdmissionGuards(t *testing.T) {
+ for _, mode := range []string{"disabled", "provider", "invalid-id"} {
+ t.Run(mode, func(t *testing.T) {
+ s := managedAPIFixture(t)
+ body := managedAPIBody("a", 2)
+ switch mode {
+ case "disabled":
+ s.managed.snapshot.Config.Enabled = false
+ case "provider":
+ s.cfg.ManagedCompute = nil
+ case "invalid-id":
+ body = strings.ReplaceAll(body, strings.Repeat("a", 22), "bad")
+ }
+ w := managedAPICall(s, "create", "abc", "", body)
+ if w.Code < 400 {
+ t.Fatal(w.Code, w.Body)
+ }
+ ops, bs, err := s.store.ManagedFleet(context.Background(), "abc", "production")
+ if err != nil || len(ops) != 0 || len(bs) != 0 {
+ t.Fatalf("reserved on refusal %v", err)
+ }
+ reg, _ := openRegistry(s.cfg.Registry)
+ f, _ := reg.GetFleet("production")
+ if f != nil {
+ t.Fatal("left claim after refusal")
+ }
+ })
+ }
+ s := managedAPIFixture(t)
+ reg, _ := openRegistry(s.cfg.Registry)
+ reg.CreateFleet(registry.Fleet{Name: "production", Account: "abc", Bucket: "byo-bucket"})
+ w := managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"aaaaaaaaaaaaaaaaaaaaaa"}`)
+ if w.Code != 409 {
+ t.Fatal(w.Code, w.Body)
+ }
+ w = managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2))
+ if w.Code != 409 {
+ t.Fatal(w.Code, w.Body)
+ }
+}
+func TestManagedAPIShow(t *testing.T) {
+ s := managedAPIFixture(t)
+ first := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ _, bs, _ := s.store.ManagedFleet(context.Background(), "abc", "production")
+ next := bs[0]
+ next.State = "enrolled"
+ next.ObservedVersion = "v0.34.0"
+ next.Checks = map[string]managedCheck{"storage": {State: "pending", Reason: "waiting"}}
+ if ok, err := s.store.AdvanceManagedBox(context.Background(), bs[0], next); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ spy := &opCountStore{Store: s.cfg.Releases}
+ s.cfg.Releases = spy
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Boxes[0].State != "joining" || out.Boxes[0].Version != "v0.34.0" || out.Boxes[0].Checks["storage"].State != "pending" {
+ t.Fatalf("%+v", out)
+ }
+ if len(spy.snapshot()) != 0 {
+ t.Fatal("open show used store", spy.snapshot())
+ }
+ _, bs, _ = s.store.ManagedFleet(context.Background(), "abc", "production")
+ next = bs[1]
+ next.State = "publishing"
+ next.ReadyAt = time.Now()
+ next.LastError = "uncertain"
+ next.RecoveryReason = "uncertain"
+ if ok, err := s.store.AdvanceManagedBox(context.Background(), bs[1], next); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ s.store.db.Exec(`UPDATE managed_ops SET state='done',error='managed_partial_failure' WHERE id=?`, first.Operation.ID)
+ out = managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation.Outcome != "failed" || out.Boxes[1].State != "publishing" || out.Boxes[1].LastError != "uncertain" || len(spy.snapshot()) != 0 {
+ t.Fatalf("closed uncertain %+v calls %v", out, spy.snapshot())
+ }
+ raw, _ := json.Marshal(out)
+ for _, secret := range []string{"Image", "Subnet", "SecurityGroups", "ClientToken", "EnrolHash", "fake-bucket"} {
+ if strings.Contains(string(raw), secret) {
+ t.Fatal("leaked", secret)
+ }
+ }
+}
+func TestManagedAPIPreviewChangedConfig(t *testing.T) {
+ s := managedAPIFixture(t)
+ body := strings.Replace(managedAPIBody("a", 2), `"managed":true`, `"kind":"create"`, 1)
+ w := managedAPICall(s, "plan", "abc", "", body)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ var preview fleetShowPlan
+ json.Unmarshal(w.Body.Bytes(), &preview)
+ region := s.managed.snapshot.Config.Regions["eu-west-1"]
+ region.Sizes["large"] = "m8g.large"
+ s.managed.snapshot.Config.Regions["eu-west-1"] = region
+ out := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ if out.Operation.Plan.InstanceType != "m8g.large" || *out.Operation.Plan == preview {
+ t.Fatal("not the reserved plan")
+ }
+}
+
+func TestManagedAPISettledShow(t *testing.T) {
+ s := managedAPIFixture(t)
+ managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ _, boxes, _ := s.store.ManagedFleet(context.Background(), "abc", "production")
+ for _, b := range boxes {
+ next := b
+ next.State = "ready"
+ next.ReadyAt = time.Now()
+ next.DrainClearCompleted = true
+ next.ObservedVersion = "v0.34.0"
+ if ok, err := s.store.AdvanceManagedBox(context.Background(), b, next); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ readyBeat(t, s, b, status.Box{Label: b.Label, GeneratedAt: time.Now(), Metrics: &status.BoxMetrics{Release: "v0.35.0"}})
+ }
+ s.store.db.Exec(`UPDATE managed_ops SET state='done'`)
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Boxes[0].Version != "v0.35.0" {
+ t.Fatal("settled heartbeat stale", out)
+ }
+}
diff --git a/internal/console/managedview.go b/internal/console/managedview.go
index 056e7fe3c..3b5c7e7cf 100644
--- a/internal/console/managedview.go
+++ b/internal/console/managedview.go
@@ -1,6 +1,7 @@
package console
import (
+ "context"
"log"
"net/http"
)
@@ -18,13 +19,21 @@ type fleetShowBox struct {
Checks map[string]managedCheck `json:"checks"`
}
+type fleetShowPlan struct {
+ Region string `json:"region"`
+ Size string `json:"size"`
+ InstanceType string `json:"instance_type,omitempty"`
+ Boxes int `json:"boxes"`
+}
+
type fleetShowOperation struct {
- ID string `json:"id"`
- Kind string `json:"kind"`
- State string `json:"state"`
- Outcome string `json:"outcome"`
- Error string `json:"error"`
- Requested int `json:"requested"`
+ Plan *fleetShowPlan `json:"plan,omitempty"`
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ Outcome string `json:"outcome"`
+ Error string `json:"error"`
+ Requested int `json:"requested"`
}
type fleetShowReply struct {
@@ -39,6 +48,38 @@ func (s *Server) handleAPIFleetShow(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ if fleet.Managed {
+ out, err := s.managedFleetView(r.Context(), fleet.Account, fleet.Name, nil)
+ if err != nil {
+ s.managedAPIError(w, err)
+ return
+ }
+ settled := out.Operation == nil || out.Operation.State != "open"
+ for _, b := range out.Boxes {
+ if b.State == "publishing" {
+ settled = false
+ }
+ }
+ if settled && len(out.Boxes) > 0 && s.cfg.Releases != nil {
+ beats, _, err := s.loadBoxes(r.Context(), s.cfg.Releases, "fleets/"+fleet.Name+"/")
+ if err != nil {
+ log.Printf("console: settled managed fleet heartbeat: %v", err)
+ }
+ versions := map[string]string{}
+ for _, b := range beats {
+ if b.Metrics != nil {
+ versions[b.Label] = b.Metrics.Release
+ }
+ }
+ for i := range out.Boxes {
+ if version := versions[out.Boxes[i].Label]; version != "" {
+ out.Boxes[i].Version = version
+ }
+ }
+ }
+ writeJSON(w, http.StatusOK, out)
+ return
+ }
boxes, err := reg.ListFleetBoxes(fleet.Name)
if err != nil {
log.Printf("console: fleet show %s: %v", fleet.Name, err)
@@ -75,3 +116,52 @@ func managedChecksEqual(a, b map[string]managedCheck) bool {
}
return true
}
+
+func managedOperationView(op managedOp, boxes []managedBox) *fleetShowOperation {
+ out := &fleetShowOperation{ID: op.ID, Kind: op.Kind, State: op.State, Error: op.Error, Requested: op.Requested, Plan: &fleetShowPlan{Region: op.Region, Size: op.Size, Boxes: op.Requested}}
+ failed := op.State == "failed" || op.Error != ""
+ for _, b := range boxes {
+ if b.OpID == op.ID {
+ out.Plan.InstanceType = b.Launch.InstanceType
+ if b.LastError != "" || b.State == "failed" || b.State == "terminating" || b.State == "terminated" {
+ failed = true
+ }
+ }
+ }
+ if op.State != "open" {
+ out.Outcome = "success"
+ if failed {
+ out.Outcome = "failed"
+ }
+ }
+ return out
+}
+func (s *Server) managedFleetView(ctx context.Context, account, name string, selected *managedOp) (fleetShowReply, error) {
+ ops, boxes, err := s.store.ManagedFleet(ctx, account, name)
+ out := fleetShowReply{Name: name, Managed: true, Boxes: []fleetShowBox{}}
+ if err != nil {
+ return out, err
+ }
+ if selected == nil {
+ for i := range ops {
+ if selected == nil || selected.State != "open" || ops[i].State == "open" {
+ selected = &ops[i]
+ }
+ }
+ }
+ if selected != nil {
+ out.Operation = managedOperationView(*selected, boxes)
+ }
+ for _, b := range boxes {
+ state := b.State
+ if state == "enrolled" {
+ state = "joining"
+ }
+ checks := b.Checks
+ if checks == nil {
+ checks = map[string]managedCheck{}
+ }
+ out.Boxes = append(out.Boxes, fleetShowBox{Label: b.Label, State: state, Version: b.ObservedVersion, LastError: b.LastError, Checks: checks})
+ }
+ return out, nil
+}
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index d57712c43..c95571140 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -165,6 +165,8 @@ var closedDoors = []string{
// Enrolling a BOX into a fleet, and rotating or detaching one, is a
// human act with a machine's credentials as its output. Same cut.
"POST /api/cli/fleets/{account}/new",
+ "POST /api/cli/fleets/{account}/managed-plan",
+ "POST /api/cli/fleets/{account}/{fleet}/managed-boxes",
"GET /api/cli/fleets/{account}",
"POST /api/cli/fleets/{account}/{fleet}/boxes",
"POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate",
@@ -1153,8 +1155,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 79 {
- t.Errorf("walked %d closed doors, want all %d (and 79 today: the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 81 {
+ t.Errorf("walked %d closed doors, want all %d (and 81 today: two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 2977e4a85..989877717 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -300,12 +300,14 @@ route POST /api/cli/apps/{account}/{app}/store/scan/sweep
route POST /api/cli/apps/{account}/{app}/ttl
route POST /api/cli/billing/house
route POST /api/cli/billing/problems/{id}/close
+route POST /api/cli/fleets/{account}/managed-plan
route POST /api/cli/fleets/{account}/new
route POST /api/cli/fleets/{account}/{fleet}/boxes
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags
+route POST /api/cli/fleets/{account}/{fleet}/managed-boxes
route POST /api/cli/ops/hosts/{host}/resolve
route POST /api/cli/ops/hosts/{host}/resolve/inspect
route POST /api/cli/relay/rotate
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 1da489a23..b67a09f95 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -63,3 +63,4 @@ plan14-root-reads-managed-fleets-2a-task-5.tsv 19ad67bdbe2f4269fbfadd44bd36ca166
plan14-root-reads-managed-fleets-2a-task-6.tsv d63dcbb0494381ce43314094fecfd1780abc890af3774c145eb9ec9b1d54afde
plan14-root-reads-managed-fleets-2a-task-6-fix1.tsv 6f7852cb59ad8e795883178b98353b385b6ccfc430f28dada330d019d5e5061d
plan14-root-reads-managed-fleets-2a-task-7.tsv 63e8cb293a3ee2eea6250aee0f79d2fe7b381df9d19f90808a6768ef058a23e4
+plan14-root-reads-managed-fleets-2a-task-9.tsv 639b72119e79e65677359f437a70ea595749153fdee3f74be57237a8019115a2
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-9.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-9.tsv
new file mode 100644
index 000000000..674486e2a
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-9.tsv
@@ -0,0 +1,6 @@
+# Census overlay managed-fleets-2a-task-9, written by census-propose (#369). census-ruling-managed-fleets-2a-task-9, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-2a-task-9.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy fe54a819ceed931f27a00ea1e4bba0fa13ad9835ef60af5a380cfc60ed7c16f6 fleets_managed.go runManagedFleetCommand legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-9;basis=Generate an invocation request ID using crypto/rand.Read, then call authenticated console preview, POST and status APIs. No filesystem or root-state read is added; scanner classifies rand.Read as a file read. file:Read@132 a69787188d6c6c700c39c19821270f2d97aaecec6a1e541a25e8d9e01dd8a044
+fleets_managed.go runManagedFleetCommand legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-9;basis=Generate an invocation request ID using crypto/rand.Read, then call authenticated console preview, POST and status APIs. No filesystem or root-state read is added; scanner classifies rand.Read as a file read. file:Read@132 a69787188d6c6c700c39c19821270f2d97aaecec6a1e541a25e8d9e01dd8a044
+@coverage . 1e807a69cc197c0bdba31088efe897d306020b18272a033e4cadcf44159ef2ee