//go:build hostedlive // Command livectl makes the Lambda MicroVMs and Lambda core calls of the // Task 17 live check through the pinned Go SDK (controller ruling R40), so // the run uses the client production uses rather than the CLI's model. The // plan's bash blocks call it, one subcommand per operation: // // livectl [-run RUN] GROUP VERB [flags] // // Each success prints the SDK's complete output as one JSON object on // stdout. Each failure prints one JSON line on stderr and exits with: // // 2 an SDK call failed (code and HTTP status in the line) // 3 usage // 4 a guard refused (wrong account or region, or a name outside the run) // 5 a bounded wait ran out // 6 a wait reached a failed state (DELETE_FAILED, FAILED, TERMINATED) // 1 anything else (config load, encoding) // // Guards, before any other call: the caller's account must be // wantAccount and the region wantRegion (build-time constants, no flag); // every create needs a name starting with the run prefix // equipo-hosted-dev-t17-RUN; every delete, update and VM state change // reads its target first and refuses one outside the run. // // Credentials are static keys only, resolved once at startup (creds.go, // R41); any other provider is refused with exit 4. The clients // (newClients) ignore every configured endpoint override, so // all calls reach the standard eu-west-1 endpoints; make one attempt per // call; and bound each call by callTimeout. Waits also bound their reads. // // It is built only with -tags hostedlive and never runs in CI. package main import ( "context" "encoding/json" "errors" "flag" "fmt" "io" "os" "reflect" "regexp" "strings" "time" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/service/lambdacore" vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" "github.com/aws/aws-sdk-go-v2/service/sts" "github.com/aws/smithy-go" smithyhttp "github.com/aws/smithy-go/transport/http" ) // The one account and region this tool works in. Changing them is a code // change, reviewed like any other. const ( wantAccount = "640012953448" wantRegion = "eu-west-1" prefixBase = "equipo-hosted-dev-t17-" ) const ( exitOK = 0 exitOther = 1 exitAPI = 2 exitUsage = 3 exitGuard = 4 exitTimeout = 5 exitFailed = 6 ) // Waits are bounded: -timeout is capped at maxWait. const ( maxWait = 60 * time.Minute defaultInterval = 15 * time.Second ) type coreAPI interface { CreateNetworkConnector(context.Context, *lambdacore.CreateNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.CreateNetworkConnectorOutput, error) GetNetworkConnector(context.Context, *lambdacore.GetNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.GetNetworkConnectorOutput, error) ListNetworkConnectorVersions(context.Context, *lambdacore.ListNetworkConnectorVersionsInput, ...func(*lambdacore.Options)) (*lambdacore.ListNetworkConnectorVersionsOutput, error) DeleteNetworkConnector(context.Context, *lambdacore.DeleteNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.DeleteNetworkConnectorOutput, error) } type vmAPI interface { ListManagedMicrovmImageVersions(context.Context, *vms.ListManagedMicrovmImageVersionsInput, ...func(*vms.Options)) (*vms.ListManagedMicrovmImageVersionsOutput, error) CreateMicrovmImage(context.Context, *vms.CreateMicrovmImageInput, ...func(*vms.Options)) (*vms.CreateMicrovmImageOutput, error) UpdateMicrovmImage(context.Context, *vms.UpdateMicrovmImageInput, ...func(*vms.Options)) (*vms.UpdateMicrovmImageOutput, error) GetMicrovmImage(context.Context, *vms.GetMicrovmImageInput, ...func(*vms.Options)) (*vms.GetMicrovmImageOutput, error) GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error) ListMicrovmImages(context.Context, *vms.ListMicrovmImagesInput, ...func(*vms.Options)) (*vms.ListMicrovmImagesOutput, error) DeleteMicrovmImage(context.Context, *vms.DeleteMicrovmImageInput, ...func(*vms.Options)) (*vms.DeleteMicrovmImageOutput, error) RunMicrovm(context.Context, *vms.RunMicrovmInput, ...func(*vms.Options)) (*vms.RunMicrovmOutput, error) GetMicrovm(context.Context, *vms.GetMicrovmInput, ...func(*vms.Options)) (*vms.GetMicrovmOutput, error) ListMicrovms(context.Context, *vms.ListMicrovmsInput, ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error) SuspendMicrovm(context.Context, *vms.SuspendMicrovmInput, ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error) ResumeMicrovm(context.Context, *vms.ResumeMicrovmInput, ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error) TerminateMicrovm(context.Context, *vms.TerminateMicrovmInput, ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error) } type stsAPI interface { GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) } // clock is time for the waits; tests use a fake one. type clock interface { Now() time.Time Sleep(time.Duration) } type realClock struct{} func (realClock) Now() time.Time { return time.Now() } func (realClock) Sleep(d time.Duration) { time.Sleep(d) } // env is everything a subcommand uses. type env struct { ctx context.Context core coreAPI vms vmAPI sts stsAPI region string // the SDK config's region clock clock out io.Writer errw io.Writer prefix string // equipo-hosted-dev-t17-RUN, or "" without -run } // failure is a command's end other than success. type failure struct { exit int Kind string `json:"error"` // api, usage, guard, timeout, failed_state, other Op string `json:"op,omitempty"` Code string `json:"code,omitempty"` // smithy ErrorCode, or the failed state Status int `json:"http_status,omitempty"` // HTTP status of a failed call Message string `json:"message"` // fixed text // AWSMessage is the service's own message for a failed call, kept // apart from Message for the operator (the plan matches refusals on // it). It is never parsed by this tool. AWSMessage string `json:"aws_message,omitempty"` RequestID string `json:"request_id,omitempty"` } func (f *failure) Error() string { return f.Kind + ": " + f.Message } func usage(format string, args ...any) *failure { return &failure{exit: exitUsage, Kind: "usage", Message: fmt.Sprintf(format, args...)} } func guard(format string, args ...any) *failure { return &failure{exit: exitGuard, Kind: "guard", Message: fmt.Sprintf(format, args...)} } // apiFailure describes a failed SDK call op: its error code, HTTP status // and request ID when the SDK has them. func apiFailure(op string, err error) *failure { f := &failure{exit: exitAPI, Kind: "api", Op: op, Message: op + " failed"} var ae smithy.APIError if errors.As(err, &ae) { f.Code, f.AWSMessage = ae.ErrorCode(), ae.ErrorMessage() } else { f.Kind, f.Message = "transport", op+" failed before an answer came back" } var he *smithyhttp.ResponseError if errors.As(err, &he) && he.Response != nil { f.Status = he.HTTPStatusCode() } var re *awshttp.ResponseError if errors.As(err, &re) { f.RequestID = re.ServiceRequestID() } return f } // isCode reports whether err is an SDK error with code. func isCode(err error, code string) bool { var ae smithy.APIError return errors.As(err, &ae) && ae.ErrorCode() == code } func main() { ctx := context.Background() e := &env{ctx: ctx, clock: realClock{}, out: os.Stdout, errw: os.Stderr} region, creds, f := resolveCredentials(ctx) // once, before the account check (R41) if f != nil { os.Exit(report(e, f)) } cfg := staticConfig(region, creds) e.region = cfg.Region e.core, e.vms, e.sts = newClients(cfg) os.Exit(run(e, os.Args[1:])) } // run parses args, checks the account and region, and runs one // subcommand. It returns the exit code. func run(e *env, args []string) int { top := flag.NewFlagSet("livectl", flag.ContinueOnError) top.SetOutput(io.Discard) runID := top.String("run", "", "run ID; names must start with "+prefixBase+"RUN") if err := top.Parse(args); err != nil { return report(e, usage("%v", err)) } rest := top.Args() if len(rest) == 0 { return report(e, usage("want GROUP VERB: connector, image, vm or caller")) } if *runID != "" { if !runPattern.MatchString(*runID) { return report(e, usage("-run %q must be 1 to 32 lower-case letters, digits and '-'", *runID)) } e.prefix = prefixBase + *runID } cmd, ok := lookup(rest) if !ok { return report(e, usage("unknown command %q", strings.Join(rest[:min(2, len(rest))], " "))) } n := 2 if rest[0] == "caller" { n = 1 } fs := flag.NewFlagSet(strings.Join(rest[:n], " "), flag.ContinueOnError) fs.SetOutput(io.Discard) exec := cmd(fs) if err := fs.Parse(rest[n:]); err != nil { return report(e, usage("%v", err)) } if fs.NArg() != 0 { return report(e, usage("unexpected arguments %q", fs.Args())) } if f := checkCaller(e); f != nil { return report(e, f) } out, err := exec(e) if rv := reflect.ValueOf(out); out != nil && !(rv.Kind() == reflect.Pointer && rv.IsNil()) { if perr := printJSON(e.out, out); perr != nil { return report(e, &failure{exit: exitOther, Kind: "other", Message: "output did not encode"}) } } if err != nil { var f *failure if !errors.As(err, &f) { f = &failure{exit: exitOther, Kind: "other", Message: err.Error()} } return report(e, f) } return exitOK } var runPattern = regexp.MustCompile(`^[0-9a-z-]{1,32}$`) // command declares its flags on fs and returns the step to run after the // guards. A step returns what to print (even on failure, such as the // last state a failed wait read) and its error. type command func(fs *flag.FlagSet) func(*env) (any, error) func lookup(args []string) (command, bool) { if args[0] == "caller" { return cmdCaller, true } if len(args) < 2 { return nil, false } c, ok := commands[args[0]+" "+args[1]] return c, ok } var commands = map[string]command{} func init() { for name, c := range map[string]command{ "connector create": cmdConnectorCreate, "connector get": cmdConnectorGet, "connector list-versions": cmdConnectorListVersions, "connector wait-active": cmdConnectorWaitActive, "connector delete": cmdConnectorDelete, "connector wait-gone": cmdConnectorWaitGone, "image base-versions": cmdImageBaseVersions, "image create": cmdImageCreate, "image update": cmdImageUpdate, "image get": cmdImageGet, "image get-version": cmdImageGetVersion, "image list": cmdImageList, "image wait-version": cmdImageWaitVersion, "image delete": cmdImageDelete, "vm run": cmdVMRun, "vm get": cmdVMGet, "vm list": cmdVMList, "vm suspend": cmdVMSuspend, "vm resume": cmdVMResume, "vm terminate": cmdVMTerminate, "vm wait-state": cmdVMWaitState, } { commands[name] = c } } // checkCaller is the account and region guard every subcommand passes // first. func checkCaller(e *env) *failure { if e.region != wantRegion { return guard("region is %q, want %s", e.region, wantRegion) } out, err := e.sts.GetCallerIdentity(e.ctx, &sts.GetCallerIdentityInput{}) if err != nil { return apiFailure("GetCallerIdentity", err) } if a := aws.ToString(out.Account); a != wantAccount { return guard("caller account is %q, want %s", a, wantAccount) } return nil } func cmdCaller(*flag.FlagSet) func(*env) (any, error) { return func(e *env) (any, error) { out, err := e.sts.GetCallerIdentity(e.ctx, &sts.GetCallerIdentityInput{}) if err != nil { return nil, apiFailure("GetCallerIdentity", err) } return map[string]any{"Account": aws.ToString(out.Account), "Arn": aws.ToString(out.Arn), "UserId": aws.ToString(out.UserId), "Region": e.region}, nil } } // inRun refuses name unless it is the run prefix or starts with it and a // '-'. Without -run every name is refused. func (e *env) inRun(what, name string) error { if e.prefix == "" { return guard("%s needs -run", what) } if name != e.prefix && !strings.HasPrefix(name, e.prefix+"-") { return guard("%s %q is outside run %s", what, name, e.prefix) } return nil } // report writes f as one JSON line on stderr and returns its exit code. func report(e *env, f *failure) int { b, err := json.Marshal(f) if err != nil { b = []byte(`{"error":"other","message":"error did not encode"}`) } fmt.Fprintf(e.errw, "%s\n", b) return f.exit } // printJSON writes v as one JSON object. Every SDK output struct is // marshalled whole, so each field is present (null when the service left // it out); ResultMetadata is replaced by the response's server time and // request ID. func printJSON(w io.Writer, v any) error { b, err := json.Marshal(v) if err != nil { return err } var m map[string]json.RawMessage if json.Unmarshal(b, &m) == nil { if meta, ok := resultMetadata(v); ok { mb, err := json.Marshal(meta) if err != nil { return err } m["ResultMetadata"] = mb if b, err = json.Marshal(m); err != nil { return err } } } _, err = fmt.Fprintf(w, "%s\n", b) return err } // metaView is what ResultMetadata shows. type metaView struct { ServerTime *time.Time `json:"ServerTime"` // the response's Date header RequestID string `json:"RequestID"` } func resultMetadata(v any) (metaView, bool) { md, ok := metadataOf(v) if !ok { return metaView{}, false } var mv metaView if t, ok := awsmiddleware.GetServerTime(md); ok { mv.ServerTime = &t } mv.RequestID, _ = awsmiddleware.GetRequestIDMetadata(md) return mv, true } // readJSONFile decodes path into v, refusing unknown fields. func readJSONFile(path string, v any) error { f, err := os.Open(path) if err != nil { return usage("cannot read %s", path) } defer f.Close() dec := json.NewDecoder(f) dec.DisallowUnknownFields() if err := dec.Decode(v); err != nil { return usage("%s is not the expected JSON: %v", path, err) } return nil } // tagsFlag collects repeated -tag k=v flags. type tagsFlag map[string]string func (t tagsFlag) String() string { return fmt.Sprint(map[string]string(t)) } func (t tagsFlag) Set(s string) error { k, v, ok := strings.Cut(s, "=") if !ok || k == "" { return fmt.Errorf("tag %q is not key=value", s) } t[k] = v return nil } // need refuses empty required flags. func need(pairs ...string) error { for i := 0; i+1 < len(pairs); i += 2 { if pairs[i+1] == "" { return usage("-%s is required", pairs[i]) } } return nil }