oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package isolatedjob is the provider-neutral face of hosted runner VMs. The
2// controller launches, watches, suspends and stops VMs through Runner and
3// never sees a provider type. The AWS Lambda MicroVMs implementation belongs
4// in awsjob.
5//
6// A provider state this package does not know maps to StateUnknown, which is
7// never live, never terminal and never proof that a VM has stopped.
8package isolatedjob
9
10import (
11 "context"
12 "errors"
13 "fmt"
14 "net/netip"
15 "slices"
16 "strings"
17 "time"
18)
19
20// Runner launches and manages isolated job VMs.
21type Runner interface {
22 Launch(ctx context.Context, s LaunchSpec) (Ref, error) // idempotent on AttemptID
23 Get(ctx context.Context, ref Ref) (Job, error)
24 Suspend(ctx context.Context, ref Ref) error
25 Resume(ctx context.Context, ref Ref) error
26 Stop(ctx context.Context, ref Ref, reason string) error // succeeds if already gone
27 List(ctx context.Context) ([]Job, error) // all VMs the provider holds
28 Limits() Limits
29}
30
31// Ref is the provider's identifier for one VM.
32type Ref string
33
34// MaxRefLen is the longest Ref Valid accepts.
35const MaxRefLen = 128
36
37// Valid reports whether r is 1 to MaxRefLen letters, digits and '-' (ruling
38// R36). A provider's ID is checked with it before it is used, stored or
39// logged, so a malformed reply can never carry other text into the
40// controller's records.
41func (r Ref) Valid() bool {
42 if len(r) == 0 || len(r) > MaxRefLen {
43 return false
44 }
45 for i := 0; i < len(r); i++ {
46 switch c := r[i]; {
47 case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '-':
48 default:
49 return false
50 }
51 }
52 return true
53}
54
55// ImageDigest names a certified base image: "sha256:" and 64 lower-case hex
56// digits.
57type ImageDigest string
58
59// Size is the memory class of a VM. One image version has one size.
60type Size string
61
62const (
63 SizeSmall Size = "small" // 2 GB
64 SizeLarge Size = "large" // 4 GB
65)
66
67// MemoryMiB returns the VM memory for s in MiB, or 0 when s is not a known
68// size.
69func (s Size) MemoryMiB() int {
70 switch s {
71 case SizeSmall:
72 return 2048
73 case SizeLarge:
74 return 4096
75 }
76 return 0
77}
78
79// State is a VM's lifecycle state in this package's vocabulary.
80type State string
81
82const (
83 StateStarting State = "starting"
84 StateRunning State = "running"
85 StateSuspending State = "suspending"
86 StateSuspended State = "suspended"
87 StateStopping State = "stopping"
88 StateStopped State = "stopped"
89 StateFailed State = "failed"
90 StateUnknown State = "unknown"
91)
92
93// Live reports whether the VM may still exist and run or resume work.
94// Unknown and unrecognised states are not live.
95func (s State) Live() bool {
96 switch s {
97 case StateStarting, StateRunning, StateSuspending, StateSuspended, StateStopping:
98 return true
99 }
100 return false
101}
102
103// Terminal reports whether the state proves the VM has ended. Unknown and
104// unrecognised states are not terminal.
105func (s State) Terminal() bool {
106 switch s {
107 case StateStopped, StateFailed:
108 return true
109 }
110 return false
111}
112
113// HardMaxLifetime is the longest a VM may live, running and suspended time
114// together, whatever a provider allows.
115const HardMaxLifetime = 28800 * time.Second
116
117// LaunchSpec is one launch request. Launching the same AttemptID twice gives
118// the same VM.
119type LaunchSpec struct {
120 AttemptID string
121 Image ImageDigest // must be certified
122 Size Size // SizeSmall or SizeLarge
123 MaxLifetime time.Duration // includes suspended time
124 Bootstrap []byte // the one-time enrolment code only
125}
126
127// Job is one VM as the provider reports it.
128type Job struct {
129 Ref Ref
130 State State
131 StartedAt time.Time
132 Reason string
133
134 // ProviderAge is the provider's server time minus the provider's start
135 // time for the VM, both taken from one response. It is never worked out
136 // from this host's clock. AgeKnown is false when the response lacked
137 // either time.
138 ProviderAge time.Duration
139 AgeKnown bool
140}
141
142// Limits are what a provider allows.
143type Limits struct {
144 MaxLifetime time.Duration
145 MaxBootstrapBytes int
146 SuspendUsesLifetime bool // suspended time counts towards MaxLifetime
147 ConnectionsSurvive bool // open connections survive suspend and resume
148}
149
150var (
151 // ErrNotFound: the provider holds no VM with this ref.
152 ErrNotFound = errors.New("isolatedjob: not found")
153 // ErrInvalid: the request is malformed or outside the provider's limits.
154 ErrInvalid = errors.New("isolatedjob: invalid request")
155 // ErrConflict: the VM's current state does not allow the operation, or
156 // an attempt ID was reused with a different request.
157 ErrConflict = errors.New("isolatedjob: conflict")
158 // ErrThrottled: the provider asked us to slow down; retry later.
159 ErrThrottled = errors.New("isolatedjob: throttled")
160 // ErrIncomplete: the provider's answer cannot be trusted as whole, for
161 // example a list that could not read every page.
162 ErrIncomplete = errors.New("isolatedjob: incomplete answer")
163 // ErrBootstrapTooLarge: the bootstrap is longer than the provider takes.
164 // Validate returns it instead of ErrInvalid for an oversized bootstrap.
165 ErrBootstrapTooLarge = errors.New("isolatedjob: bootstrap too large")
166)
167
168// NetworkAuditor reads the provider's network settings for hosted VMs as they
169// are now, not as they were configured.
170type NetworkAuditor interface {
171 AuditNetwork(ctx context.Context) (NetworkAudit, error)
172}
173
174// NetworkAudit is one reading of the network hosted VMs launch into.
175type NetworkAudit struct {
176 ResolverDisabled bool // the provider's managed DNS is off
177 IngressClosed bool // VMs take no inbound connections
178 RouteOutAbsent bool // the VMs' subnet has no internet route
179 EgressOnly []netip.AddrPort // every destination VMs are allowed to reach
180}
181
182// OK returns nil only when the resolver is off, ingress is closed, no route
183// out exists and EgressOnly holds exactly the destinations in want, in any
184// order. Otherwise its error names every property that failed.
185func (a NetworkAudit) OK(want []netip.AddrPort) error {
186 var failed []string
187 if !a.ResolverDisabled {
188 failed = append(failed, "resolver enabled")
189 }
190 if !a.IngressClosed {
191 failed = append(failed, "ingress open")
192 }
193 if !a.RouteOutAbsent {
194 failed = append(failed, "route out present")
195 }
196 extra := missingFrom(a.EgressOnly, want)
197 missing := missingFrom(want, a.EgressOnly)
198 if len(extra) > 0 || len(missing) > 0 {
199 failed = append(failed, fmt.Sprintf("egress differs (extra %v, missing %v)", extra, missing))
200 }
201 if len(failed) == 0 {
202 return nil
203 }
204 return errors.New("isolatedjob: network audit failed: " + strings.Join(failed, "; "))
205}
206
207// missingFrom returns the members of have that are not in set.
208func missingFrom(have, set []netip.AddrPort) []netip.AddrPort {
209 var out []netip.AddrPort
210 for _, p := range have {
211 if !slices.Contains(set, p) && !slices.Contains(out, p) {
212 out = append(out, p)
213 }
214 }
215 return out
216}
217