oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build hostedlive
2
3// Command livectl makes the Lambda MicroVMs and Lambda core calls of the
4// Task 17 live check through the pinned Go SDK (controller ruling R40), so
5// the run uses the client production uses rather than the CLI's model. The
6// plan's bash blocks call it, one subcommand per operation:
7//
8// livectl [-run RUN] GROUP VERB [flags]
9//
10// Each success prints the SDK's complete output as one JSON object on
11// stdout. Each failure prints one JSON line on stderr and exits with:
12//
13// 2 an SDK call failed (code and HTTP status in the line)
14// 3 usage
15// 4 a guard refused (wrong account or region, or a name outside the run)
16// 5 a bounded wait ran out
17// 6 a wait reached a failed state (DELETE_FAILED, FAILED, TERMINATED)
18// 1 anything else (config load, encoding)
19//
20// Guards, before any other call: the caller's account must be
21// wantAccount and the region wantRegion (build-time constants, no flag);
22// every create needs a name starting with the run prefix
23// equipo-hosted-dev-t17-RUN; every delete, update and VM state change
24// reads its target first and refuses one outside the run.
25//
26// Credentials are static keys only, resolved once at startup (creds.go,
27// R41); any other provider is refused with exit 4. The clients
28// (newClients) ignore every configured endpoint override, so
29// all calls reach the standard eu-west-1 endpoints; make one attempt per
30// call; and bound each call by callTimeout. Waits also bound their reads.
31//
32// It is built only with -tags hostedlive and never runs in CI.
33package main
34
35import (
36 "context"
37 "encoding/json"
38 "errors"
39 "flag"
40 "fmt"
41 "io"
42 "os"
43 "reflect"
44 "regexp"
45 "strings"
46 "time"
47
48 "github.com/aws/aws-sdk-go-v2/aws"
49 awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
50 awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
51 "github.com/aws/aws-sdk-go-v2/service/lambdacore"
52 vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
53 "github.com/aws/aws-sdk-go-v2/service/sts"
54 "github.com/aws/smithy-go"
55 smithyhttp "github.com/aws/smithy-go/transport/http"
56)
57
58// The one account and region this tool works in. Changing them is a code
59// change, reviewed like any other.
60const (
61 wantAccount = "640012953448"
62 wantRegion = "eu-west-1"
63 prefixBase = "equipo-hosted-dev-t17-"
64)
65
66const (
67 exitOK = 0
68 exitOther = 1
69 exitAPI = 2
70 exitUsage = 3
71 exitGuard = 4
72 exitTimeout = 5
73 exitFailed = 6
74)
75
76// Waits are bounded: -timeout is capped at maxWait.
77const (
78 maxWait = 60 * time.Minute
79 defaultInterval = 15 * time.Second
80)
81
82type coreAPI interface {
83 CreateNetworkConnector(context.Context, *lambdacore.CreateNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.CreateNetworkConnectorOutput, error)
84 GetNetworkConnector(context.Context, *lambdacore.GetNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.GetNetworkConnectorOutput, error)
85 ListNetworkConnectorVersions(context.Context, *lambdacore.ListNetworkConnectorVersionsInput, ...func(*lambdacore.Options)) (*lambdacore.ListNetworkConnectorVersionsOutput, error)
86 DeleteNetworkConnector(context.Context, *lambdacore.DeleteNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.DeleteNetworkConnectorOutput, error)
87}
88
89type vmAPI interface {
90 ListManagedMicrovmImageVersions(context.Context, *vms.ListManagedMicrovmImageVersionsInput, ...func(*vms.Options)) (*vms.ListManagedMicrovmImageVersionsOutput, error)
91 CreateMicrovmImage(context.Context, *vms.CreateMicrovmImageInput, ...func(*vms.Options)) (*vms.CreateMicrovmImageOutput, error)
92 UpdateMicrovmImage(context.Context, *vms.UpdateMicrovmImageInput, ...func(*vms.Options)) (*vms.UpdateMicrovmImageOutput, error)
93 GetMicrovmImage(context.Context, *vms.GetMicrovmImageInput, ...func(*vms.Options)) (*vms.GetMicrovmImageOutput, error)
94 GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error)
95 ListMicrovmImages(context.Context, *vms.ListMicrovmImagesInput, ...func(*vms.Options)) (*vms.ListMicrovmImagesOutput, error)
96 DeleteMicrovmImage(context.Context, *vms.DeleteMicrovmImageInput, ...func(*vms.Options)) (*vms.DeleteMicrovmImageOutput, error)
97 RunMicrovm(context.Context, *vms.RunMicrovmInput, ...func(*vms.Options)) (*vms.RunMicrovmOutput, error)
98 GetMicrovm(context.Context, *vms.GetMicrovmInput, ...func(*vms.Options)) (*vms.GetMicrovmOutput, error)
99 ListMicrovms(context.Context, *vms.ListMicrovmsInput, ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error)
100 SuspendMicrovm(context.Context, *vms.SuspendMicrovmInput, ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error)
101 ResumeMicrovm(context.Context, *vms.ResumeMicrovmInput, ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error)
102 TerminateMicrovm(context.Context, *vms.TerminateMicrovmInput, ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error)
103}
104
105type stsAPI interface {
106 GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error)
107}
108
109// clock is time for the waits; tests use a fake one.
110type clock interface {
111 Now() time.Time
112 Sleep(time.Duration)
113}
114
115type realClock struct{}
116
117func (realClock) Now() time.Time { return time.Now() }
118func (realClock) Sleep(d time.Duration) { time.Sleep(d) }
119
120// env is everything a subcommand uses.
121type env struct {
122 ctx context.Context
123 core coreAPI
124 vms vmAPI
125 sts stsAPI
126 region string // the SDK config's region
127 clock clock
128 out io.Writer
129 errw io.Writer
130 prefix string // equipo-hosted-dev-t17-RUN, or "" without -run
131}
132
133// failure is a command's end other than success.
134type failure struct {
135 exit int
136 Kind string `json:"error"` // api, usage, guard, timeout, failed_state, other
137 Op string `json:"op,omitempty"`
138 Code string `json:"code,omitempty"` // smithy ErrorCode, or the failed state
139 Status int `json:"http_status,omitempty"` // HTTP status of a failed call
140 Message string `json:"message"` // fixed text
141 // AWSMessage is the service's own message for a failed call, kept
142 // apart from Message for the operator (the plan matches refusals on
143 // it). It is never parsed by this tool.
144 AWSMessage string `json:"aws_message,omitempty"`
145 RequestID string `json:"request_id,omitempty"`
146}
147
148func (f *failure) Error() string { return f.Kind + ": " + f.Message }
149
150func usage(format string, args ...any) *failure {
151 return &failure{exit: exitUsage, Kind: "usage", Message: fmt.Sprintf(format, args...)}
152}
153
154func guard(format string, args ...any) *failure {
155 return &failure{exit: exitGuard, Kind: "guard", Message: fmt.Sprintf(format, args...)}
156}
157
158// apiFailure describes a failed SDK call op: its error code, HTTP status
159// and request ID when the SDK has them.
160func apiFailure(op string, err error) *failure {
161 f := &failure{exit: exitAPI, Kind: "api", Op: op, Message: op + " failed"}
162 var ae smithy.APIError
163 if errors.As(err, &ae) {
164 f.Code, f.AWSMessage = ae.ErrorCode(), ae.ErrorMessage()
165 } else {
166 f.Kind, f.Message = "transport", op+" failed before an answer came back"
167 }
168 var he *smithyhttp.ResponseError
169 if errors.As(err, &he) && he.Response != nil {
170 f.Status = he.HTTPStatusCode()
171 }
172 var re *awshttp.ResponseError
173 if errors.As(err, &re) {
174 f.RequestID = re.ServiceRequestID()
175 }
176 return f
177}
178
179// isCode reports whether err is an SDK error with code.
180func isCode(err error, code string) bool {
181 var ae smithy.APIError
182 return errors.As(err, &ae) && ae.ErrorCode() == code
183}
184
185func main() {
186 ctx := context.Background()
187 e := &env{ctx: ctx, clock: realClock{}, out: os.Stdout, errw: os.Stderr}
188 region, creds, f := resolveCredentials(ctx) // once, before the account check (R41)
189 if f != nil {
190 os.Exit(report(e, f))
191 }
192 cfg := staticConfig(region, creds)
193 e.region = cfg.Region
194 e.core, e.vms, e.sts = newClients(cfg)
195 os.Exit(run(e, os.Args[1:]))
196}
197
198// run parses args, checks the account and region, and runs one
199// subcommand. It returns the exit code.
200func run(e *env, args []string) int {
201 top := flag.NewFlagSet("livectl", flag.ContinueOnError)
202 top.SetOutput(io.Discard)
203 runID := top.String("run", "", "run ID; names must start with "+prefixBase+"RUN")
204 if err := top.Parse(args); err != nil {
205 return report(e, usage("%v", err))
206 }
207 rest := top.Args()
208 if len(rest) == 0 {
209 return report(e, usage("want GROUP VERB: connector, image, vm or caller"))
210 }
211 if *runID != "" {
212 if !runPattern.MatchString(*runID) {
213 return report(e, usage("-run %q must be 1 to 32 lower-case letters, digits and '-'", *runID))
214 }
215 e.prefix = prefixBase + *runID
216 }
217 cmd, ok := lookup(rest)
218 if !ok {
219 return report(e, usage("unknown command %q", strings.Join(rest[:min(2, len(rest))], " ")))
220 }
221 n := 2
222 if rest[0] == "caller" {
223 n = 1
224 }
225 fs := flag.NewFlagSet(strings.Join(rest[:n], " "), flag.ContinueOnError)
226 fs.SetOutput(io.Discard)
227 exec := cmd(fs)
228 if err := fs.Parse(rest[n:]); err != nil {
229 return report(e, usage("%v", err))
230 }
231 if fs.NArg() != 0 {
232 return report(e, usage("unexpected arguments %q", fs.Args()))
233 }
234 if f := checkCaller(e); f != nil {
235 return report(e, f)
236 }
237 out, err := exec(e)
238 if rv := reflect.ValueOf(out); out != nil && !(rv.Kind() == reflect.Pointer && rv.IsNil()) {
239 if perr := printJSON(e.out, out); perr != nil {
240 return report(e, &failure{exit: exitOther, Kind: "other", Message: "output did not encode"})
241 }
242 }
243 if err != nil {
244 var f *failure
245 if !errors.As(err, &f) {
246 f = &failure{exit: exitOther, Kind: "other", Message: err.Error()}
247 }
248 return report(e, f)
249 }
250 return exitOK
251}
252
253var runPattern = regexp.MustCompile(`^[0-9a-z-]{1,32}$`)
254
255// command declares its flags on fs and returns the step to run after the
256// guards. A step returns what to print (even on failure, such as the
257// last state a failed wait read) and its error.
258type command func(fs *flag.FlagSet) func(*env) (any, error)
259
260func lookup(args []string) (command, bool) {
261 if args[0] == "caller" {
262 return cmdCaller, true
263 }
264 if len(args) < 2 {
265 return nil, false
266 }
267 c, ok := commands[args[0]+" "+args[1]]
268 return c, ok
269}
270
271var commands = map[string]command{}
272
273func init() {
274 for name, c := range map[string]command{
275 "connector create": cmdConnectorCreate, "connector get": cmdConnectorGet,
276 "connector list-versions": cmdConnectorListVersions, "connector wait-active": cmdConnectorWaitActive,
277 "connector delete": cmdConnectorDelete, "connector wait-gone": cmdConnectorWaitGone,
278 "image base-versions": cmdImageBaseVersions, "image create": cmdImageCreate, "image update": cmdImageUpdate,
279 "image get": cmdImageGet, "image get-version": cmdImageGetVersion, "image list": cmdImageList,
280 "image wait-version": cmdImageWaitVersion, "image delete": cmdImageDelete,
281 "vm run": cmdVMRun, "vm get": cmdVMGet, "vm list": cmdVMList, "vm suspend": cmdVMSuspend,
282 "vm resume": cmdVMResume, "vm terminate": cmdVMTerminate, "vm wait-state": cmdVMWaitState,
283 } {
284 commands[name] = c
285 }
286}
287
288// checkCaller is the account and region guard every subcommand passes
289// first.
290func checkCaller(e *env) *failure {
291 if e.region != wantRegion {
292 return guard("region is %q, want %s", e.region, wantRegion)
293 }
294 out, err := e.sts.GetCallerIdentity(e.ctx, &sts.GetCallerIdentityInput{})
295 if err != nil {
296 return apiFailure("GetCallerIdentity", err)
297 }
298 if a := aws.ToString(out.Account); a != wantAccount {
299 return guard("caller account is %q, want %s", a, wantAccount)
300 }
301 return nil
302}
303
304func cmdCaller(*flag.FlagSet) func(*env) (any, error) {
305 return func(e *env) (any, error) {
306 out, err := e.sts.GetCallerIdentity(e.ctx, &sts.GetCallerIdentityInput{})
307 if err != nil {
308 return nil, apiFailure("GetCallerIdentity", err)
309 }
310 return map[string]any{"Account": aws.ToString(out.Account), "Arn": aws.ToString(out.Arn),
311 "UserId": aws.ToString(out.UserId), "Region": e.region}, nil
312 }
313}
314
315// inRun refuses name unless it is the run prefix or starts with it and a
316// '-'. Without -run every name is refused.
317func (e *env) inRun(what, name string) error {
318 if e.prefix == "" {
319 return guard("%s needs -run", what)
320 }
321 if name != e.prefix && !strings.HasPrefix(name, e.prefix+"-") {
322 return guard("%s %q is outside run %s", what, name, e.prefix)
323 }
324 return nil
325}
326
327// report writes f as one JSON line on stderr and returns its exit code.
328func report(e *env, f *failure) int {
329 b, err := json.Marshal(f)
330 if err != nil {
331 b = []byte(`{"error":"other","message":"error did not encode"}`)
332 }
333 fmt.Fprintf(e.errw, "%s\n", b)
334 return f.exit
335}
336
337// printJSON writes v as one JSON object. Every SDK output struct is
338// marshalled whole, so each field is present (null when the service left
339// it out); ResultMetadata is replaced by the response's server time and
340// request ID.
341func printJSON(w io.Writer, v any) error {
342 b, err := json.Marshal(v)
343 if err != nil {
344 return err
345 }
346 var m map[string]json.RawMessage
347 if json.Unmarshal(b, &m) == nil {
348 if meta, ok := resultMetadata(v); ok {
349 mb, err := json.Marshal(meta)
350 if err != nil {
351 return err
352 }
353 m["ResultMetadata"] = mb
354 if b, err = json.Marshal(m); err != nil {
355 return err
356 }
357 }
358 }
359 _, err = fmt.Fprintf(w, "%s\n", b)
360 return err
361}
362
363// metaView is what ResultMetadata shows.
364type metaView struct {
365 ServerTime *time.Time `json:"ServerTime"` // the response's Date header
366 RequestID string `json:"RequestID"`
367}
368
369func resultMetadata(v any) (metaView, bool) {
370 md, ok := metadataOf(v)
371 if !ok {
372 return metaView{}, false
373 }
374 var mv metaView
375 if t, ok := awsmiddleware.GetServerTime(md); ok {
376 mv.ServerTime = &t
377 }
378 mv.RequestID, _ = awsmiddleware.GetRequestIDMetadata(md)
379 return mv, true
380}
381
382// readJSONFile decodes path into v, refusing unknown fields.
383func readJSONFile(path string, v any) error {
384 f, err := os.Open(path)
385 if err != nil {
386 return usage("cannot read %s", path)
387 }
388 defer f.Close()
389 dec := json.NewDecoder(f)
390 dec.DisallowUnknownFields()
391 if err := dec.Decode(v); err != nil {
392 return usage("%s is not the expected JSON: %v", path, err)
393 }
394 return nil
395}
396
397// tagsFlag collects repeated -tag k=v flags.
398type tagsFlag map[string]string
399
400func (t tagsFlag) String() string { return fmt.Sprint(map[string]string(t)) }
401func (t tagsFlag) Set(s string) error {
402 k, v, ok := strings.Cut(s, "=")
403 if !ok || k == "" {
404 return fmt.Errorf("tag %q is not key=value", s)
405 }
406 t[k] = v
407 return nil
408}
409
410// need refuses empty required flags.
411func need(pairs ...string) error {
412 for i := 0; i+1 < len(pairs); i += 2 {
413 if pairs[i+1] == "" {
414 return usage("-%s is required", pairs[i])
415 }
416 }
417 return nil
418}
419