oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package awsjob
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/netip"
8 "slices"
9 "strings"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/isolatedjob"
14 "github.com/aws/aws-sdk-go-v2/aws"
15 awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
16 "github.com/aws/aws-sdk-go-v2/service/ec2"
17 "github.com/aws/aws-sdk-go-v2/service/lambdacore"
18 vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
19 "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
20 "github.com/aws/smithy-go/middleware"
21)
22
23// MicroVMAPI is the part of the Lambda MicroVMs client the runner calls.
24// *lambdamicrovms.Client satisfies it.
25type MicroVMAPI interface {
26 RunMicrovm(context.Context, *vms.RunMicrovmInput, ...func(*vms.Options)) (*vms.RunMicrovmOutput, error)
27 GetMicrovm(context.Context, *vms.GetMicrovmInput, ...func(*vms.Options)) (*vms.GetMicrovmOutput, error)
28 SuspendMicrovm(context.Context, *vms.SuspendMicrovmInput, ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error)
29 ResumeMicrovm(context.Context, *vms.ResumeMicrovmInput, ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error)
30 TerminateMicrovm(context.Context, *vms.TerminateMicrovmInput, ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error)
31 ListMicrovms(context.Context, *vms.ListMicrovmsInput, ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error)
32 GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error)
33}
34
35// EC2API is the part of the EC2 client the network audit calls.
36// *ec2.Client satisfies it.
37type EC2API interface {
38 DescribeVpcAttribute(context.Context, *ec2.DescribeVpcAttributeInput, ...func(*ec2.Options)) (*ec2.DescribeVpcAttributeOutput, error)
39 DescribeSubnets(context.Context, *ec2.DescribeSubnetsInput, ...func(*ec2.Options)) (*ec2.DescribeSubnetsOutput, error)
40 DescribeRouteTables(context.Context, *ec2.DescribeRouteTablesInput, ...func(*ec2.Options)) (*ec2.DescribeRouteTablesOutput, error)
41 DescribeSecurityGroups(context.Context, *ec2.DescribeSecurityGroupsInput, ...func(*ec2.Options)) (*ec2.DescribeSecurityGroupsOutput, error)
42}
43
44// ConnectorAPI is the part of the Lambda core client the network audit
45// calls to read the egress connector. *lambdacore.Client satisfies it.
46type ConnectorAPI interface {
47 GetNetworkConnector(context.Context, *lambdacore.GetNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.GetNetworkConnectorOutput, error)
48}
49
50// API is every provider call the runner makes.
51type API interface {
52 MicroVMAPI
53 EC2API
54 ConnectorAPI
55}
56
57// NewAPI joins the three clients into an API, for example
58// NewAPI(lambdamicrovms.NewFromConfig(cfg), ec2.NewFromConfig(cfg),
59// lambdacore.NewFromConfig(cfg)).
60func NewAPI(m MicroVMAPI, e EC2API, c ConnectorAPI) API {
61 return clients{m, e, c}
62}
63
64type clients struct {
65 MicroVMAPI
66 EC2API
67 ConnectorAPI
68}
69
70// Image is one certified base image: its MicroVM image ARN and the image
71// version to run for each size. Memory, CPU and OS capabilities are set on
72// an image version, and one version has one memory size, so each size needs
73// a version of its own.
74type Image struct {
75 ARN string
76 Versions map[isolatedjob.Size]string
77}
78
79// Config is where hosted VMs launch and what they may reach.
80type Config struct {
81 Region string
82 // ConnectorID is the version-qualified ARN of the VPC_EGRESS network
83 // connector, the VMs' only egress:
84 // arn:aws:lambda:REGION:ACCOUNT:network-connector:ID:VERSION. The
85 // version pins the connector's subnets and groups, so an update to the
86 // connector cannot change what launched VMs use without a config change.
87 ConnectorID string
88 VPCID string // the VPC of the connector's subnet
89 VMSubnetID string // the connector's only subnet
90 VMSecurityGroupID string // the connector's only security group
91 // Images are the certified images, by digest. They also bound what
92 // List sees (ruling R32): only VMs running one of these image ARNs are
93 // listed, so VMs of other images in a shared account are never taken
94 // for orphans and stopped by the reaper.
95 Images map[isolatedjob.ImageDigest]Image
96 // Egress is every destination the security group should let VMs
97 // reach: the shared proxies. Empty means none: the group has no
98 // outbound rules, as in slice 1a, which has no egress stack.
99 Egress []netip.AddrPort
100}
101
102// Runner is the isolatedjob.Runner and isolatedjob.NetworkAuditor for AWS
103// Lambda MicroVMs. It is safe for concurrent use.
104type Runner struct {
105 cfg Config
106 api API
107
108 mu sync.Mutex
109 verified map[imageVersion]int // memory in MiB of each version that passed the image check
110}
111
112type imageVersion struct{ arn, version string }
113
114var (
115 _ isolatedjob.Runner = (*Runner)(nil)
116 _ isolatedjob.NetworkAuditor = (*Runner)(nil)
117)
118
119// New checks cfg and returns a Runner that calls api. Every config error
120// wraps isolatedjob.ErrInvalid.
121func New(cfg Config, api API) (*Runner, error) {
122 if err := cfg.check(); err != nil {
123 return nil, fmt.Errorf("%w: awsjob config: %v", isolatedjob.ErrInvalid, err)
124 }
125 if api == nil {
126 return nil, fmt.Errorf("%w: awsjob: no API", isolatedjob.ErrInvalid)
127 }
128 return &Runner{cfg: cfg, api: api, verified: map[imageVersion]int{}}, nil
129}
130
131func (c Config) check() error {
132 for name, v := range map[string]string{"region": c.Region, "connector": c.ConnectorID, "vpc": c.VPCID,
133 "subnet": c.VMSubnetID, "security group": c.VMSecurityGroupID} {
134 if v == "" {
135 return fmt.Errorf("%s is empty", name)
136 }
137 }
138 if !qualifiedConnector(c.ConnectorID, c.Region) {
139 return fmt.Errorf("connector %q is not a version-qualified network connector ARN in %s", c.ConnectorID, c.Region)
140 }
141 if len(c.Images) == 0 {
142 return errors.New("no images")
143 }
144 for d, img := range c.Images {
145 if img.ARN == "" || len(img.Versions) == 0 {
146 return fmt.Errorf("image %s needs an ARN and at least one version", d)
147 }
148 for size, v := range img.Versions {
149 if size.MemoryMiB() == 0 || v == "" {
150 return fmt.Errorf("image %s: size %q, version %q", d, size, v)
151 }
152 }
153 }
154 for _, e := range c.Egress {
155 if !e.IsValid() || e.Port() == 0 {
156 return fmt.Errorf("egress %v is not an address and port", e)
157 }
158 }
159 return nil
160}
161
162// qualifiedConnector reports whether arn has the form
163// arn:PARTITION:lambda:region:ACCOUNT:network-connector:ID:VERSION with a
164// numeric version.
165func qualifiedConnector(arn, region string) bool {
166 f := strings.Split(arn, ":")
167 if len(f) != 8 || f[0] != "arn" || f[1] == "" || f[2] != "lambda" || f[3] != region || f[4] == "" ||
168 f[5] != "network-connector" || f[6] == "" || f[7] == "" {
169 return false
170 }
171 for _, c := range f[7] {
172 if c < '0' || c > '9' {
173 return false
174 }
175 }
176 return true
177}
178
179// Fingerprint names what a launch of image d at size s sends to AWS beyond
180// the spec: the region (and with it the NO_INGRESS connector), the egress
181// connector, and the image ARN and version. The controller keeps it with
182// each launch intent and refuses to replay an intent under another one
183// (hostedctl Config.ProviderFingerprint). An image or size with no version
184// gives a fingerprint with empty fields, which a configured one never
185// matches.
186func (c Config) Fingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
187 img := c.Images[d]
188 return fmt.Sprintf("region=%q connector=%q image=%q version=%q", c.Region, c.ConnectorID, img.ARN, img.Versions[s])
189}
190
191// NoIngressConnectorARN is the Lambda-provided NO_INGRESS connector in
192// region, in the form the developer guide prints for the managed ingress
193// connectors (doc.go, Connectors). The guide does not print this one; the
194// live check confirms it.
195func NoIngressConnectorARN(region string) string {
196 return "arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:NO_INGRESS"
197}
198
199// Limits are the spike's findings and doc.go's: 8 hours including suspended
200// time, a 4096-byte run hook payload, and connections dropped by suspend.
201func (r *Runner) Limits() isolatedjob.Limits {
202 return isolatedjob.Limits{
203 MaxLifetime: 28800 * time.Second,
204 MaxBootstrapBytes: 4096,
205 SuspendUsesLifetime: true,
206 ConnectionsSurvive: false,
207 }
208}
209
210// Launch runs one VM with NO_INGRESS, the configured connector as its only
211// egress, no execution role, no idle policy, the spec's lifetime as the
212// maximum duration and the attempt ID as the client token. It refuses with
213// isolatedjob.ErrInvalid, before any run call, a spec that fails Validate,
214// a bootstrap that is not ASCII, an image or size with no configured
215// version, and an image version that is not x86_64 with all OS capabilities
216// and the size's memory.
217func (r *Runner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
218 if err := s.Validate(r.Limits()); err != nil {
219 return "", err
220 }
221 // runHookPayload is a JSON string: the SDK would turn invalid UTF-8
222 // into U+FFFD, and AWS does not say whether its limit counts bytes or
223 // characters. The bootstrap is an enrolment code, so ASCII is enough
224 // and every ASCII byte survives JSON unchanged.
225 for i, b := range s.Bootstrap {
226 if b >= 0x80 {
227 return "", fmt.Errorf("%w: bootstrap byte %d is 0x%02x; only ASCII survives the run hook payload unchanged", isolatedjob.ErrInvalid, i, b)
228 }
229 }
230 img, ok := r.cfg.Images[s.Image]
231 if !ok {
232 return "", fmt.Errorf("%w: image %s is not configured", isolatedjob.ErrInvalid, s.Image)
233 }
234 version, ok := img.Versions[s.Size]
235 if !ok {
236 return "", fmt.Errorf("%w: image %s has no version for size %s", isolatedjob.ErrInvalid, s.Image, s.Size)
237 }
238 seconds := int64(s.MaxLifetime / time.Second)
239 if seconds < 1 || seconds > 28800 {
240 return "", fmt.Errorf("%w: lifetime %v is not 1 to 28800 whole seconds", isolatedjob.ErrInvalid, s.MaxLifetime)
241 }
242 if err := r.checkImageVersion(ctx, img.ARN, version, s.Size); err != nil {
243 return "", err
244 }
245 out, err := r.api.RunMicrovm(ctx, &vms.RunMicrovmInput{
246 ImageIdentifier: aws.String(img.ARN),
247 ImageVersion: aws.String(version),
248 ClientToken: aws.String(s.AttemptID), // always set: the SDK invents one when it is nil
249 IngressNetworkConnectors: []string{NoIngressConnectorARN(r.cfg.Region)},
250 EgressNetworkConnectors: []string{r.cfg.ConnectorID},
251 MaximumDurationInSeconds: aws.Int32(int32(seconds)),
252 RunHookPayload: aws.String(string(s.Bootstrap)),
253 })
254 if err != nil {
255 return "", mapErr("run", err)
256 }
257 id := isolatedjob.Ref(aws.ToString(out.MicrovmId))
258 if !id.Valid() {
259 // The text is fixed: a malformed ID is never echoed (R36).
260 return "", fmt.Errorf("awsjob: run %s: the reply's microvm id is missing or malformed", s.AttemptID)
261 }
262 return id, nil
263}
264
265// checkImageVersion reads the image version once and refuses it unless it
266// has exactly the "ALL" OS capability, one x86_64 CPU configuration and
267// one memory setting equal to the size's. A pass is kept for the life of
268// the Runner; a failure is not, so a fixed version passes on the next try.
269func (r *Runner) checkImageVersion(ctx context.Context, arn, version string, size isolatedjob.Size) error {
270 key := imageVersion{arn, version}
271 want := size.MemoryMiB()
272 r.mu.Lock()
273 mem, seen := r.verified[key]
274 r.mu.Unlock()
275 if seen {
276 if mem != want {
277 return fmt.Errorf("%w: image version %s:%s has %d MiB, size %s needs %d", isolatedjob.ErrInvalid, arn, version, mem, size, want)
278 }
279 return nil
280 }
281 out, err := r.api.GetMicrovmImageVersion(ctx, &vms.GetMicrovmImageVersionInput{
282 ImageIdentifier: aws.String(arn),
283 ImageVersion: aws.String(version),
284 })
285 if err != nil {
286 err = mapErr("get image version", err)
287 if errors.Is(err, isolatedjob.ErrNotFound) {
288 return fmt.Errorf("%w: image version %s:%s: %w", isolatedjob.ErrInvalid, arn, version, err)
289 }
290 return err
291 }
292 if !slices.Equal(out.AdditionalOsCapabilities, []types.Capability{types.CapabilityAll}) {
293 return fmt.Errorf("%w: image version %s:%s has OS capabilities %v, want [ALL]", isolatedjob.ErrInvalid, arn, version, out.AdditionalOsCapabilities)
294 }
295 if len(out.CpuConfigurations) != 1 || out.CpuConfigurations[0].Architecture != types.ArchitectureX8664 {
296 return fmt.Errorf("%w: image version %s:%s has CPU configurations %v, want one X86_64", isolatedjob.ErrInvalid, arn, version, out.CpuConfigurations)
297 }
298 if len(out.Resources) != 1 || out.Resources[0].MinimumMemoryInMiB == nil || int(*out.Resources[0].MinimumMemoryInMiB) != want {
299 return fmt.Errorf("%w: image version %s:%s has memory %v, size %s needs one setting of %d MiB", isolatedjob.ErrInvalid, arn, version, memories(out.Resources), size, want)
300 }
301 r.mu.Lock()
302 r.verified[key] = want
303 r.mu.Unlock()
304 return nil
305}
306
307func memories(rs []types.Resources) []int32 {
308 var out []int32
309 for _, r := range rs {
310 out = append(out, aws.ToInt32(r.MinimumMemoryInMiB))
311 }
312 return out
313}
314
315// Get reads one VM.
316func (r *Runner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
317 if !ref.Valid() {
318 return isolatedjob.Job{}, fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid)
319 }
320 out, err := r.api.GetMicrovm(ctx, &vms.GetMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
321 if err != nil {
322 return isolatedjob.Job{}, mapErr("get", err)
323 }
324 // The reply must name a valid ID (R36, R38): a missing one is an error,
325 // never the asked-for ref, so a malformed reply cannot become stop proof.
326 id := isolatedjob.Ref(aws.ToString(out.MicrovmId))
327 if !id.Valid() {
328 return isolatedjob.Job{}, errors.New("awsjob: get: the reply's microvm id is missing or malformed")
329 }
330 return job(id, out.State, out.StateReason, out.StartedAt, out.ResultMetadata), nil
331}
332
333// Suspend asks AWS to suspend the VM.
334func (r *Runner) Suspend(ctx context.Context, ref isolatedjob.Ref) error {
335 if !ref.Valid() {
336 return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid)
337 }
338 _, err := r.api.SuspendMicrovm(ctx, &vms.SuspendMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
339 return mapErr("suspend", err)
340}
341
342// Resume asks AWS to resume the VM. AWS refuses to resume a VM that is not
343// suspended with a ConflictException; Resume then reads the VM once and
344// returns nil only if it is running, so resuming a running VM is a no-op.
345func (r *Runner) Resume(ctx context.Context, ref isolatedjob.Ref) error {
346 if !ref.Valid() {
347 return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid)
348 }
349 _, err := r.api.ResumeMicrovm(ctx, &vms.ResumeMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
350 var conflict *types.ConflictException
351 if !errors.As(err, &conflict) {
352 return mapErr("resume", err)
353 }
354 j, getErr := r.Get(ctx, ref)
355 if getErr != nil {
356 return fmt.Errorf("%w: resume %s refused (%v) and its state is unreadable: %v", isolatedjob.ErrConflict, ref, err, getErr)
357 }
358 if j.State == isolatedjob.StateRunning {
359 return nil
360 }
361 return fmt.Errorf("%w: resume %s refused in state %s: %w", isolatedjob.ErrConflict, ref, j.State, err)
362}
363
364// Stop terminates the VM. AWS has no field for the reason, so it is not
365// sent. A VM AWS no longer knows is already gone, which is success.
366func (r *Runner) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
367 if !ref.Valid() {
368 return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid)
369 }
370 _, err := r.api.TerminateMicrovm(ctx, &vms.TerminateMicrovmInput{MicrovmIdentifier: aws.String(string(ref))})
371 if err = mapErr("terminate", err); errors.Is(err, isolatedjob.ErrNotFound) {
372 return nil
373 }
374 return err
375}
376
377// listPageSize is the most ListMicrovms returns in one page.
378const listPageSize = 50
379
380// List reads the VMs of the configured images in the account and region
381// (ruling R32): one ListMicrovms walk per configured image ARN, in ARN
382// order, filtered by that image, every page of each. An item whose imageArn
383// is not the ARN asked for is dropped, so a VM from another image is never
384// returned even if the filter were ignored; the account may be shared, and
385// the reaper stops listed VMs no job owns. If any page fails, repeats a
386// token or holds a VM whose ID is missing or fails isolatedjob.Ref.Valid
387// (R36), List returns no jobs and an error wrapping
388// isolatedjob.ErrIncomplete.
389func (r *Runner) List(ctx context.Context) ([]isolatedjob.Job, error) {
390 var jobs []isolatedjob.Job
391 for _, arn := range r.imageARNs() {
392 got, err := r.listImage(ctx, arn)
393 if err != nil {
394 return nil, err
395 }
396 jobs = append(jobs, got...)
397 }
398 return jobs, nil
399}
400
401// imageARNs is every configured image ARN once, sorted.
402func (r *Runner) imageARNs() []string {
403 var arns []string
404 for _, img := range r.cfg.Images {
405 arns = append(arns, img.ARN)
406 }
407 slices.Sort(arns)
408 return slices.Compact(arns)
409}
410
411// listImage walks every page of ListMicrovms filtered by image arn.
412func (r *Runner) listImage(ctx context.Context, arn string) ([]isolatedjob.Job, error) {
413 var jobs []isolatedjob.Job
414 var token *string
415 seen := map[string]bool{}
416 for page := 1; ; page++ {
417 out, err := r.api.ListMicrovms(ctx, &vms.ListMicrovmsInput{ImageIdentifier: aws.String(arn),
418 MaxResults: aws.Int32(listPageSize), NextToken: token})
419 if err != nil {
420 return nil, fmt.Errorf("%w: list image %s page %d: %w", isolatedjob.ErrIncomplete, arn, page, mapErr("list", err))
421 }
422 for _, it := range out.Items {
423 if aws.ToString(it.ImageArn) != arn {
424 continue
425 }
426 id := isolatedjob.Ref(aws.ToString(it.MicrovmId))
427 if !id.Valid() {
428 return nil, fmt.Errorf("%w: list image %s page %d holds a VM with a missing or malformed id", isolatedjob.ErrIncomplete, arn, page)
429 }
430 jobs = append(jobs, job(id, it.State, nil, it.StartedAt, out.ResultMetadata))
431 }
432 next := aws.ToString(out.NextToken)
433 if next == "" {
434 return jobs, nil
435 }
436 if seen[next] {
437 return nil, fmt.Errorf("%w: list image %s page %d repeats a page token", isolatedjob.ErrIncomplete, arn, page)
438 }
439 seen[next] = true
440 token = aws.String(next)
441 }
442}
443
444// job builds a Job from one response. ProviderAge is the response's server
445// time minus the VM's start time, both from AWS; with either missing, or a
446// start after the server time, AgeKnown is false.
447func job(ref isolatedjob.Ref, raw types.MicrovmState, reason *string, started *time.Time, meta middleware.Metadata) isolatedjob.Job {
448 j := isolatedjob.Job{Ref: ref}
449 j.State, j.Reason = state(raw, aws.ToString(reason))
450 if started != nil {
451 j.StartedAt = *started
452 }
453 if server, ok := awsmiddleware.GetServerTime(meta); ok && started != nil && !server.Before(*started) {
454 j.ProviderAge, j.AgeKnown = server.Sub(*started), true
455 }
456 return j
457}
458
459// state maps an AWS MicroVM state. A state this package does not know is
460// unknown, with the raw value in the reason; AWS says the set can grow.
461func state(raw types.MicrovmState, reason string) (isolatedjob.State, string) {
462 switch raw {
463 case types.MicrovmStatePending:
464 return isolatedjob.StateStarting, reason
465 case types.MicrovmStateRunning:
466 return isolatedjob.StateRunning, reason
467 case types.MicrovmStateSuspending:
468 return isolatedjob.StateSuspending, reason
469 case types.MicrovmStateSuspended:
470 return isolatedjob.StateSuspended, reason
471 case types.MicrovmStateTerminating:
472 return isolatedjob.StateStopping, reason
473 case types.MicrovmStateTerminated:
474 return isolatedjob.StateStopped, reason
475 }
476 why := fmt.Sprintf("provider state %q", string(raw))
477 if reason != "" {
478 why += ": " + reason
479 }
480 return isolatedjob.StateUnknown, why
481}
482