package instancectl import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "strconv" "strings" "time" "github.com/carlosframework/platform/internal/version" ) // Deadlines per verb (design §5.3). A start or stop that exceeds its // deadline is a failed wake or an unproven stop, never a hang: §6.7 puts // one such call on a path that must not stall the activator. The seed's is // long because a seed is allowed to be slow. const ( DeadlineControl = 30 * time.Second DeadlineSeed = 150 * time.Second DeadlineSweep = 60 * time.Second DeadlineReady = 5 * time.Second // DeadlineCmdPoll bounds GET /cmd/{host}; the server answers within 30 s. DeadlineCmdPoll = 35 * time.Second ) // Client is the agent's side of the control channel. It is plain HTTP over // the unix socket at Path; unixdial's checks are for UPSTREAMS the edge // proxies to, and this socket is the one path they refuse, so the client // dials it directly. type Client struct { Path string // Dial is the dialer; nil means net.Dialer. Tests do not need to override // it, but a caller composing several clients may. Dial func(ctx context.Context, path string) (net.Conn, error) // Build is the build this agent runs. Ready refuses a service whose // BuildHeader does not name it (#256); empty skips the comparison, // for tests that build a Client literal. NewClient sets version.Build. Build string } func NewClient(path string) *Client { return &Client{Path: path, Build: version.Build} } // StaleBuildError is Ready's answer to a control service running a build // other than the agent's own: the service outlived a binary change and // serves this release's units with the previous release's code (#256). type StaleBuildError struct{ Running, Want string } func (e *StaleBuildError) Error() string { if e.Running == "" { return fmt.Sprintf("instance control: carlos-instance-control.service is running an older build than this agent (%s); restart carlos-instance-control.service", e.Want) } return fmt.Sprintf("instance control: carlos-instance-control.service is running build %s, this agent is %s; restart carlos-instance-control.service", e.Running, e.Want) } // NotReadyError carries the probe verdict a 503 /ready returned. type NotReadyError struct{ Report ProbeReport } func (e *NotReadyError) Error() string { var fails []string for _, l := range e.Report.Lines { if l.Verdict != "ok" { fails = append(fails, l.Check+" "+l.Verdict+" "+l.Detail) } } if len(fails) == 0 { return "instance control: box not ready (no verdict yet)" } return "instance control: box not ready: " + strings.Join(fails, "; ") } // httpClient builds a fresh Transport per call rather than caching one on c. // DisableKeepAlives is what makes that the right trade: a pooled idle // connection nothing ever reuses (each call already builds its own client) // would just sit open, leaking one file descriptor per call instead of // closing when the response is read. func (c *Client) httpClient() *http.Client { dial := c.Dial if dial == nil { dial = func(ctx context.Context, path string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, "unix", path) } } return &http.Client{Transport: &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return dial(ctx, c.Path) }, DisableKeepAlives: true, }} } // do issues one verb with the given deadline and decodes a JSON body when // there is one. A non-2xx answer becomes an error carrying the server's // message; a dial failure names the socket so a forgotten enable reads as // what it is from carlos logs. func (c *Client) do(ctx context.Context, deadline time.Duration, method, path string, q url.Values, out any) (int, http.Header, error) { ctx, cancel := context.WithTimeout(ctx, deadline) defer cancel() u := "http://control" + path if len(q) > 0 { u += "?" + q.Encode() } req, err := http.NewRequestWithContext(ctx, method, u, nil) if err != nil { return 0, nil, err } resp, err := c.httpClient().Do(req) if err != nil { return 0, nil, fmt.Errorf("instance control socket %s: %w", c.Path, err) } defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) if resp.StatusCode == http.StatusServiceUnavailable && path == "/ready" { var r ProbeReport _ = json.Unmarshal(body, &r) return resp.StatusCode, resp.Header, &NotReadyError{Report: r} } // A 502 from /sweep still carries the units it did and didn't manage to // stop, so it is decoded into out here even though it is about to be // reported as an error too; the caller needs the partial list alongside // the failure, not instead of it. if out != nil && len(body) > 0 && (resp.StatusCode/100 == 2 || (resp.StatusCode == http.StatusBadGateway && path == "/sweep")) { if err := json.Unmarshal(body, out); err != nil { return resp.StatusCode, resp.Header, fmt.Errorf("instance control %s: %v", path, err) } } if resp.StatusCode/100 != 2 { return resp.StatusCode, resp.Header, fmt.Errorf("instance control %s: %d: %s", path, resp.StatusCode, strings.TrimSpace(string(body))) } return resp.StatusCode, resp.Header, nil } func hostRole(host string, role Role) url.Values { q := url.Values{"host": {host}} if role != "" { q.Set("role", string(role)) } return q } // Start starts the run or sidecar unit for host with the memory tier and // returns the invocation id the server read after the start. func (c *Client) Start(ctx context.Context, host string, role Role, memoryMax int64) (string, error) { q := hostRole(host, role) q.Set("memory_max", strconv.FormatInt(memoryMax, 10)) var out StartResponse if _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/start", q, &out); err != nil { return "", err } return out.InvocationID, nil } // Seed runs the seed unit to completion and returns its retained result. func (c *Client) Seed(ctx context.Context, host string, memoryMax int64) (SeedResponse, error) { return c.seedQuery(ctx, host, memoryMax, nil) } // SeedExe is Seed with the seed's executable named: the staged build the // wake recorded (settings spec §4.2), which root validates and binds in // place of the live link. A 403 is root's refusal, reported as // ErrStagedExe: nothing was laid out or run. func (c *Client) SeedExe(ctx context.Context, host string, memoryMax int64, x StagedExe) (SeedResponse, error) { return c.seedQuery(ctx, host, memoryMax, &x) } func (c *Client) seedQuery(ctx context.Context, host string, memoryMax int64, x *StagedExe) (SeedResponse, error) { q := hostRole(host, "") q.Set("memory_max", strconv.FormatInt(memoryMax, 10)) if x != nil { setStagedExe(q, *x) } var out SeedResponse status, _, err := c.do(ctx, DeadlineSeed, http.MethodPost, "/seed", q, &out) if err != nil && status == http.StatusForbidden && x != nil { return out, fmt.Errorf("%w: %v", ErrStagedExe, err) } return out, err } // setStagedExe puts x on a start or seed query. func setStagedExe(q url.Values, x StagedExe) { q.Set("exe", x.Path) q.Set("version", x.Version) q.Set("digest", x.Digest) } func (c *Client) Stop(ctx context.Context, host string, role Role) error { _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/stop", hostRole(host, role), nil) return err } // Cmd starts host's cmd unit and returns its invocation (run spec §5.4). func (c *Client) Cmd(ctx context.Context, host string, memoryMax int64) (string, error) { return c.cmdQuery(ctx, host, memoryMax, nil) } // CmdExe is Cmd with the executable named: the serving generation's staged // build, which root validates and mounts in place of the live link, as for // the legacy sidecar (zero-downtime spec §7.5). A 403 is root's refusal, // reported as ErrStagedExe. func (c *Client) CmdExe(ctx context.Context, host string, memoryMax int64, x StagedExe) (string, error) { return c.cmdQuery(ctx, host, memoryMax, &x) } func (c *Client) cmdQuery(ctx context.Context, host string, memoryMax int64, x *StagedExe) (string, error) { q := hostRole(host, "") q.Set("memory_max", strconv.FormatInt(memoryMax, 10)) if x != nil { q.Set("exe", x.Path) q.Set("version", x.Version) q.Set("digest", x.Digest) } var out StartResponse status, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/cmd", q, &out) if err != nil { if status == http.StatusForbidden && x != nil { return "", fmt.Errorf("%w: %v", ErrStagedExe, err) } return "", err } return out.InvocationID, nil } // CmdStatus long-polls the named invocation of host's cmd unit. func (c *Client) CmdStatus(ctx context.Context, host, invocation string) (CmdStatus, error) { var out CmdStatus _, _, err := c.do(ctx, DeadlineCmdPoll, http.MethodGet, "/cmd/"+url.PathEscape(host), url.Values{"invocation": {invocation}}, &out) return out, err } func (c *Client) Reset(ctx context.Context, host string, role Role) error { _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/reset", hostRole(host, role), nil) return err } // genValues is the query of a generation verb: the run role and gen=. func genValues(host string, n uint64) url.Values { q := hostRole(host, RoleRun) q.Set("gen", strconv.FormatUint(n, 10)) return q } // StartGen starts generation n's unit (zero-downtime spec §7.6) with its // tier and returns the invocation id the server read after the start. A // failure whose cleanup could not prove the unit gone wraps ErrGenUnproven. func (c *Client) StartGen(ctx context.Context, host string, n uint64, memoryMax int64) (string, error) { return c.startUnitQuery(ctx, genValues(host, n), memoryMax, nil) } // StartGenExe is StartGen with the generation's executable named: the // staged build root validates and mounts in place of the live link. A 403 // is root's refusal, reported as ErrStagedExe. func (c *Client) StartGenExe(ctx context.Context, host string, n uint64, memoryMax int64, x StagedExe) (string, error) { return c.startUnitQuery(ctx, genValues(host, n), memoryMax, &x) } // StartExe is Start with the unit's executable named: a staged build root // validates and mounts in place of the live link, for the original // template's run unit (the build a cold wake recorded, settings spec §4.2) // or the legacy sidecar. A 403 is root's refusal, reported as // ErrStagedExe. func (c *Client) StartExe(ctx context.Context, host string, role Role, memoryMax int64, x StagedExe) (string, error) { return c.startUnitQuery(ctx, hostRole(host, role), memoryMax, &x) } // StartSidecarExe is StartExe for the legacy sidecar role: the serving // generation's staged build (zero-downtime spec §7.5). func (c *Client) StartSidecarExe(ctx context.Context, host string, memoryMax int64, x StagedExe) (string, error) { return c.StartExe(ctx, host, RoleSidecar, memoryMax, x) } // startUnitQuery is /start for a generation or the sidecar, optionally with // a staged executable. One place maps root's two distinct refusals: 403 is // ErrStagedExe (nothing was mounted), and the generation verbs' unproven // status is ErrGenUnproven. func (c *Client) startUnitQuery(ctx context.Context, q url.Values, memoryMax int64, x *StagedExe) (string, error) { q.Set("memory_max", strconv.FormatInt(memoryMax, 10)) if x != nil { setStagedExe(q, *x) } var out StartResponse status, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/start", q, &out) if err != nil { switch { case status == http.StatusForbidden && x != nil: return "", fmt.Errorf("%w: %v", ErrStagedExe, err) case status == statusGenUnproven && q.Has("gen"): return "", fmt.Errorf("%w: %w", ErrGenUnproven, err) } return "", err } return out.InvocationID, nil } // StopGen stops generation n's unit only. kill kills it outright and // returns once its cgroup is empty. func (c *Client) StopGen(ctx context.Context, host string, n uint64, kill bool) error { q := genValues(host, n) if kill { q.Set("kill", "1") } _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/stop", q, nil) return err } func (c *Client) ResetGen(ctx context.Context, host string, n uint64) error { _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/reset", genValues(host, n), nil) return err } // Parent sets host's slice memory, the generation parent's backstop (spec // §7.3): one tier, or two summed during an overlap. func (c *Client) Parent(ctx context.Context, host string, memoryMax int64) error { q := url.Values{"host": {host}, "memory_max": {strconv.FormatInt(memoryMax, 10)}} _, _, err := c.do(ctx, DeadlineControl, http.MethodPost, "/parent", q, nil) return err } // Sweep stops every instance unit on the box (design §6.7). A 502 carries // the units that were stopped and the ones that would not; both are // returned with the error. func (c *Client) Sweep(ctx context.Context) (SweepResponse, error) { var out SweepResponse status, _, err := c.do(ctx, DeadlineSweep, http.MethodPost, "/sweep", nil, &out) if err != nil && status == http.StatusBadGateway { return out, errors.Join(err, errors.New("some instance units would not stop")) } return out, err } // Ready is nil on 204 from a service of this agent's own build, a // *NotReadyError on 503, and a *StaleBuildError on a 204 whose BuildHeader // is missing or names another build (#256). The verdict is asked first: // a service that is both stale and not ready says why it is not ready. func (c *Client) Ready(ctx context.Context) error { _, hdr, err := c.do(ctx, DeadlineReady, http.MethodGet, "/ready", nil, nil) if err != nil { return err } if got := hdr.Get(BuildHeader); c.Build != "" && got != c.Build { return &StaleBuildError{Running: got, Want: c.Build} } return nil }