| 1 | package hostedwire |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "math" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 13 | ) |
| 14 | |
| 15 | // Wire types for the controller's routes. Every body is one JSON object with |
| 16 | // lower-case snake_case keys, read with DecodeStrict. Durations are whole |
| 17 | // milliseconds in fields ending _ms; controller time is whole nanoseconds |
| 18 | // since the controller's epoch in fields ending _ns. No field holds wall |
| 19 | // time. |
| 20 | // |
| 21 | // POST /v1/jobs LaunchRequest -> JobView |
| 22 | // GET /v1/jobs/{attempt} (empty body) -> JobView |
| 23 | // POST /v1/jobs/{attempt}/stop StopRequest -> StopProof |
| 24 | // POST /v1/jobs/{attempt}/drain DrainRequest -> DrainResponse |
| 25 | // POST /v1/jobs/{attempt}/quiescent QuiescentRequest -> QuiescentResponse |
| 26 | // POST /v1/jobs/{attempt}/suspend SuspendRequest -> SuspendResponse |
| 27 | // POST /v1/jobs/{attempt}/reopen ReopenRequest -> ReopenResponse |
| 28 | // POST /v1/jobs/{attempt}/resume ResumeRequest -> ResumeResponse |
| 29 | // GET /v1/vms (empty body) -> VMListResponse |
| 30 | // |
| 31 | // A refused request gets an ErrorResponse. Every response, refusals included, |
| 32 | // is signed with SignResponse. |
| 33 | |
| 34 | // ErrBadJSON is a body DecodeStrict refuses for any reason but its size. |
| 35 | var ErrBadJSON = errors.New("hostedwire: body is not one strict JSON object") |
| 36 | |
| 37 | // LaunchRequest asks for one VM for one task attempt. |
| 38 | type LaunchRequest struct { |
| 39 | AttemptID string `json:"attempt_id"` |
| 40 | TaskID string `json:"task_id"` |
| 41 | Account string `json:"account"` |
| 42 | Replaces string `json:"replaces"` // attempt this one replaces, or "" |
| 43 | Image isolatedjob.ImageDigest `json:"image"` |
| 44 | Size isolatedjob.Size `json:"size"` |
| 45 | MaxLifetimeMS int64 `json:"max_lifetime_ms"` |
| 46 | InstanceCode string `json:"instance_code"` |
| 47 | } |
| 48 | |
| 49 | // MaxLifetime is MaxLifetimeMS as a duration. A negative value, or one too |
| 50 | // large for a time.Duration, is ErrDuration: multiplied unchecked it would |
| 51 | // wrap round to a plausible lifetime. |
| 52 | func (q LaunchRequest) MaxLifetime() (time.Duration, error) { |
| 53 | return millis(q.MaxLifetimeMS) |
| 54 | } |
| 55 | |
| 56 | // ErrDuration is a wire duration that is negative or does not fit a |
| 57 | // time.Duration. |
| 58 | var ErrDuration = errors.New("hostedwire: duration out of range") |
| 59 | |
| 60 | // millis converts whole milliseconds from the wire, checking the integer |
| 61 | // before it is multiplied. Every _ms field read as a duration goes through it. |
| 62 | func millis(ms int64) (time.Duration, error) { |
| 63 | if ms < 0 || ms > math.MaxInt64/int64(time.Millisecond) { |
| 64 | return 0, ErrDuration |
| 65 | } |
| 66 | return time.Duration(ms) * time.Millisecond, nil |
| 67 | } |
| 68 | |
| 69 | // JobView is the controller's view of one attempt. The *_in_ms fields count |
| 70 | // down from the moment the controller answered, in controller time. |
| 71 | type JobView struct { |
| 72 | AttemptID string `json:"attempt_id"` |
| 73 | LaunchID string `json:"launch_id"` |
| 74 | State string `json:"state"` |
| 75 | VMRef isolatedjob.Ref `json:"vm_ref"` |
| 76 | Epoch int64 `json:"epoch"` |
| 77 | DeadlineInMS int64 `json:"deadline_in_ms"` |
| 78 | DrainInMS int64 `json:"drain_in_ms"` |
| 79 | StopInMS int64 `json:"stop_in_ms"` |
| 80 | } |
| 81 | |
| 82 | // StopRequest stops an attempt's VM. |
| 83 | type StopRequest struct { |
| 84 | Reason string `json:"reason"` |
| 85 | } |
| 86 | |
| 87 | // StopProof says the provider reported the VM terminal, or gone after the |
| 88 | // stop request. ObservedAt is controller time (Task 9), never wall time. |
| 89 | type StopProof struct { |
| 90 | AttemptID string `json:"attempt_id"` |
| 91 | VMRef isolatedjob.Ref `json:"vm_ref"` |
| 92 | State isolatedjob.State `json:"state"` |
| 93 | ObservedAt time.Duration `json:"observed_at_ns"` // controller time: nanoseconds since the controller's epoch |
| 94 | } |
| 95 | |
| 96 | // DrainRequest opens a new pause generation. It has no fields; its body is {}. |
| 97 | type DrainRequest struct{} |
| 98 | |
| 99 | type DrainResponse struct { |
| 100 | Generation int64 `json:"generation"` |
| 101 | } |
| 102 | |
| 103 | type QuiescentRequest struct { |
| 104 | Generation int64 `json:"generation"` |
| 105 | } |
| 106 | |
| 107 | type QuiescentResponse struct { |
| 108 | Generation int64 `json:"generation"` |
| 109 | } |
| 110 | |
| 111 | type SuspendRequest struct { |
| 112 | Generation int64 `json:"generation"` |
| 113 | } |
| 114 | |
| 115 | type SuspendResponse struct { |
| 116 | Generation int64 `json:"generation"` |
| 117 | } |
| 118 | |
| 119 | type ReopenRequest struct { |
| 120 | Generation int64 `json:"generation"` |
| 121 | } |
| 122 | |
| 123 | type ReopenResponse struct { |
| 124 | Generation int64 `json:"generation"` |
| 125 | } |
| 126 | |
| 127 | // ResumeRequest resumes a suspended VM. OperationID makes a retry of the same |
| 128 | // resume return the same epoch. |
| 129 | type ResumeRequest struct { |
| 130 | OperationID string `json:"operation_id"` |
| 131 | } |
| 132 | |
| 133 | type ResumeResponse struct { |
| 134 | Epoch int64 `json:"epoch"` |
| 135 | } |
| 136 | |
| 137 | // VMView is one VM the provider lists, for operators. AttemptID is "" for a |
| 138 | // VM no job or intent owns. |
| 139 | type VMView struct { |
| 140 | VMRef isolatedjob.Ref `json:"vm_ref"` |
| 141 | State isolatedjob.State `json:"state"` |
| 142 | AttemptID string `json:"attempt_id"` |
| 143 | AgeKnown bool `json:"age_known"` |
| 144 | AgeMS int64 `json:"age_ms"` |
| 145 | } |
| 146 | |
| 147 | type VMListResponse struct { |
| 148 | VMs []VMView `json:"vms"` |
| 149 | } |
| 150 | |
| 151 | // ErrorResponse is the body of every refusal. Code is a short fixed word the |
| 152 | // client can branch on; Message is for people and never holds key material |
| 153 | // or request bodies. |
| 154 | type ErrorResponse struct { |
| 155 | Code string `json:"code"` |
| 156 | Message string `json:"message"` |
| 157 | } |
| 158 | |
| 159 | // BootstrapVersion is the Bootstrap layout this package writes. |
| 160 | const BootstrapVersion = 1 |
| 161 | |
| 162 | // Bootstrap is the one-time payload the VM's /run hook receives. Slice 1b |
| 163 | // adds ProxyCode. |
| 164 | type Bootstrap struct { |
| 165 | Version int `json:"version"` |
| 166 | LaunchID string `json:"launch_id"` |
| 167 | InstanceCode string `json:"instance_code"` |
| 168 | } |
| 169 | |
| 170 | // DecodeStrict reads at most MaxBody bytes from r and decodes them into v. |
| 171 | // The body must be exactly one JSON object, with nothing after it but white |
| 172 | // space. It refuses fields v does not have, keys that are not lower case |
| 173 | // (encoding/json would otherwise match "Reason" to "reason"), and a key that |
| 174 | // appears twice in one object (encoding/json would keep the last). Error |
| 175 | // texts name the rule broken, never the body. |
| 176 | func DecodeStrict(r io.Reader, v any) error { |
| 177 | data, err := io.ReadAll(io.LimitReader(r, MaxBody+1)) |
| 178 | if err != nil { |
| 179 | return fmt.Errorf("hostedwire: reading body: %w", err) |
| 180 | } |
| 181 | if len(data) > MaxBody { |
| 182 | return ErrTooLarge |
| 183 | } |
| 184 | // checkKeys also refuses anything after the one object. |
| 185 | if err := checkKeys(data); err != nil { |
| 186 | return err |
| 187 | } |
| 188 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 189 | dec.DisallowUnknownFields() |
| 190 | if err := dec.Decode(v); err != nil { |
| 191 | return fmt.Errorf("%w: does not fit the request type", ErrBadJSON) |
| 192 | } |
| 193 | return nil |
| 194 | } |
| 195 | |
| 196 | // checkKeys walks the tokens of data: one top-level object, every key lower |
| 197 | // case snake_case, no key twice in one object. |
| 198 | func checkKeys(data []byte) error { |
| 199 | type frame struct { |
| 200 | object bool |
| 201 | wantKey bool |
| 202 | keys map[string]bool |
| 203 | } |
| 204 | var stack []*frame |
| 205 | values := 0 |
| 206 | valueDone := func() { |
| 207 | if n := len(stack); n > 0 && stack[n-1].object { |
| 208 | stack[n-1].wantKey = true |
| 209 | } else if n == 0 { |
| 210 | values++ |
| 211 | } |
| 212 | } |
| 213 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 214 | dec.UseNumber() |
| 215 | for first := true; ; first = false { |
| 216 | tok, err := dec.Token() |
| 217 | if err == io.EOF { |
| 218 | break |
| 219 | } |
| 220 | if err != nil { |
| 221 | return fmt.Errorf("%w: syntax", ErrBadJSON) |
| 222 | } |
| 223 | if first && tok != json.Delim('{') { |
| 224 | return fmt.Errorf("%w: not an object", ErrBadJSON) |
| 225 | } |
| 226 | if n := len(stack); n > 0 && stack[n-1].object && stack[n-1].wantKey { |
| 227 | if tok == json.Delim('}') { |
| 228 | stack = stack[:n-1] |
| 229 | valueDone() |
| 230 | continue |
| 231 | } |
| 232 | key, _ := tok.(string) |
| 233 | if !validWireKey(key) { |
| 234 | return fmt.Errorf("%w: key not lower-case snake_case", ErrBadJSON) |
| 235 | } |
| 236 | if stack[n-1].keys[key] { |
| 237 | return fmt.Errorf("%w: key repeated", ErrBadJSON) |
| 238 | } |
| 239 | stack[n-1].keys[key] = true |
| 240 | stack[n-1].wantKey = false |
| 241 | continue |
| 242 | } |
| 243 | switch tok { |
| 244 | case json.Delim('{'): |
| 245 | stack = append(stack, &frame{object: true, wantKey: true, keys: map[string]bool{}}) |
| 246 | case json.Delim('['): |
| 247 | stack = append(stack, &frame{}) |
| 248 | case json.Delim(']'): |
| 249 | stack = stack[:len(stack)-1] |
| 250 | valueDone() |
| 251 | default: |
| 252 | valueDone() |
| 253 | } |
| 254 | } |
| 255 | if values != 1 || len(stack) != 0 { |
| 256 | return fmt.Errorf("%w: not one complete object", ErrBadJSON) |
| 257 | } |
| 258 | return nil |
| 259 | } |
| 260 | |
| 261 | func validWireKey(s string) bool { |
| 262 | if s == "" { |
| 263 | return false |
| 264 | } |
| 265 | for i := 0; i < len(s); i++ { |
| 266 | c := s[i] |
| 267 | if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') { |
| 268 | return false |
| 269 | } |
| 270 | } |
| 271 | return true |
| 272 | } |
| 273 | |