Files
w3cjandClaude Opus 5.5 a8f0517579 feat(lima): devvm downloads Ubuntu's cloud image itself
Lima's download of the cloud image neither retries nor times out: one cut
in its 900 MB fails base's build, and a stall hangs it. devvm now
downloads the pinned image itself through fetch.Resumable
(ubuntu.Download), into images/ubuntu/<sha256>.img (Dirs.UbuntuImage),
resuming across cuts, stalls and runs, and gives Lima that file. Lima
2.3 checks a local file against the digest before it copies it.

- Before downloading, it takes the image from Lima's own download cache
  when that holds it with the pin's SHA-256: copied into a new file of
  devvm's own, mode 600, hashed as it's written, capped, stopped by the
  context, and kept only once it checks out. Lima's cache is never
  changed, and a base whose dated release Ubuntu may have removed still
  builds again.
- One devvm downloads at a time (images/locks/ubuntu-image), another
  waiting under ubuntu_image_waiting and looking again under the lock
  (TestUbuntuImageAfterWait, which fails without that second look).
- The download goes through the company proxy and trusts the user's CAs
  (Lima.Roots, from trust.Pool, which internal/cli passes through the
  registry), as do the Finder's lookups (TestNewTrustsRoots, and the
  registry's TestOverrides). An untrusted certificate is
  ubuntu_untrusted, naming the CAs' folder, one from a trusted CA
  that's for another host, out of date or not valid yet
  ubuntu_bad_certificate (check the clock and what answers for the
  host), and any other that fails to verify (a SHA-1 signature, a CA's
  name constraints, a key for clients alone) ubuntu_certificate_invalid,
  naming Go's reason, for the lookups (the listing, the checksums, their
  signature: TestLookupCertificates) and the download alike
  (TestLocalImageFailsFor), and a release Ubuntu removed (404, 410)
  ubuntu_release_gone, which names devvm rebuild base; none is retried.
  ubuntu_download_failed no longer starts with devvm.
- fetch.Untrusted, fetch.BadCertificate (an x509.HostnameError, or a
  CertificateInvalidError that's Expired) and fetch.Unverified (any
  failure to verify, with its reason, so every error the other two
  name), beside fetch.Gone, are the one
  place that tells a certificate's failures apart: Transient asks
  Unverified, the lookups and the download ask all three, host mise
  asks Untrusted, and a forbidigo rule keeps x509's and tls's
  verification errors in internal/fetch (TestCertificateClasses,
  TestTransient, testdata/lint, the owners doc's row).
- An https address, or a test build's file:// DEVVM_UBUNTU_URL, read
  from disk the same way; anything else is refused. The CLI tests'
  sandbox has a stand-in of this host's image in the store.
- Base's record keeps the image's address, and the key is as it was: it
  hashes the pin (release, file, digest), not the location.
- devvm gc --caches frees devvm's copies that no record names and that
  aren't pinned now, unchanged for an hour, a stopped .part and a killed
  import's .import included, and those of a kept image once its .img is
  there. A pin it can't read fails it.
- Of Lima's cache, it frees only an entry that devvm's own state shows a
  build of devvm's left: a base record names its address, devvm has its
  own copy of the image, and the installed Lima's own templates
  (share/lima/templates beside limactl, Lima.Templates) don't name it.
  An entry no record names may be the user's own Lima's, so it stays,
  and none is freed when the templates can't be read, with a line in
  the run log naming the folder and why. A test build's
  DEVVM_LIMA_TEMPLATES stands in for the templates folder.
- ubuntu.ParseImage reads a record's image as Image.String writes it,
  and ubuntu.IsSHA256 is the one check of a cloud image's SHA-256, in
  place of Lima's own regex.
- devvm space shows the copies as a cloud images row, freed by gc
  --caches, kept as state, as a release Ubuntu removed can't be
  downloaded again.

0.1.0's frozen state runs the new commands (fixture_v010_cloud_image):
devvm looks in Lima's cache under the SHA-256 of the address 0.1.0's
base record keeps and never changes the entry, base builds from devvm's
own copy, and gc --caches keeps that copy, frees Lima's entry the
record names and devvm's own stale copies, and keeps an older entry no
record names.

Docs: images.md (the download, its failures, the import, gc's rules),
space.md, backends/lima.md, settings.md (the lookups and the download
trust your CAs), troubleshooting.md, overview.md, testing.md,
tests.md, structure.md's internal/fetch row; the CHANGELOG's two Fixed
lines, which later commits make highlights, What to do 5 and 6, and the
release page's Ubuntu's cloud image in devvm's folder.

New messages: downloading_ubuntu, importing_ubuntu, ubuntu_image_waiting,
ubuntu_download_failed, ubuntu_release_gone, ubuntu_bad_certificate,
ubuntu_certificate_invalid, ubuntu_image_checksum, ubuntu_untrusted.
Lima.LocalImage is the seam, Lima.ImageClient the client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 22:53:34 -07:00

341 lines
10 KiB
Go

package fetch
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var (
// ErrStalled is a try of a Resumable download that read nothing for
// its Stall: tried again, from where it stopped.
ErrStalled = errors.New("no bytes came for too long")
// ErrWrite is a Resumable download's part that can't be written, such
// as on a full disk: this machine's failure, not the network's, so
// it's never tried again.
ErrWrite = errors.New("can't write the download")
)
// Resumable is a large download that survives a bad network: what came
// stays in Path+".part" across failures, and the next try asks only for
// the rest (Range, with If-Range once the server has named a validator),
// in this run or the next. A try that reads nothing for Stall ends and is
// tried again; Tries tries in a row that bring nothing fail it, and so do
// maxTries in all. A part that's already the whole file is kept without
// asking for more. A failure
// that trying again won't mend in this run, such as a 403 or a proxy that
// refuses, keeps the part for the next; only a server that says the file
// is gone (404, 410) and a file over Limit take it with them. It's kept
// at Path only once its SHA-256 is the one asked for: a part that doesn't
// check out is removed, and the whole file fetched again, once.
type Resumable struct {
URL string
Path string
SHA256 string // hex
Limit int64 // a file over this fails with ErrTooLarge
// Stall is how long a try may read nothing before it ends.
Stall time.Duration
// Tries is how many tries in a row may bring no bytes before the
// download fails; a try that brought some starts the count again.
Tries int
// Delay is the wait after the first failure, doubling after each up
// to a minute.
Delay time.Duration
// Log gets a line for each try that failed; nil for none.
Log io.Writer
}
// maxTries bounds a Resumable download however much each try brings.
const maxTries = 100
// maxDelay is the longest wait between a Resumable download's tries.
const maxDelay = time.Minute
// part is what a Resumable download has so far: the bytes in its .part
// file, their hash, and the validator the server named for them.
type part struct {
path string
h hash.Hash
have int64
tag string // an ETag or Last-Modified, for If-Range
}
// Download fetches d, resuming what an earlier try or run left. It
// returns the context's error once ctx ends, keeping the part.
func (d Resumable) Download(ctx context.Context, c *Client) error {
p, err := openPart(d.Path+".part", d.Limit)
if err != nil {
return err
}
fails, delay, redone := 0, d.Delay, false
for n := 1; ; n++ {
if err := ctx.Err(); err != nil {
return err
}
// A part that's the whole file already, as a run killed before
// its rename or a try that failed after its last byte left it,
// is kept: a range past its end would start it again.
if p.have > 0 && d.sums(p) {
return d.keep(p)
}
before := p.have
err := d.try(ctx, c, p)
if err == nil {
if got := hex.EncodeToString(p.h.Sum(nil)); !strings.EqualFold(got, d.SHA256) {
_ = os.Remove(p.path)
if redone {
return fmt.Errorf("%s: %w: %s", d.URL, ErrChecksum, got)
}
// A part from another file (the server's changed it) or a
// bad resume: once more, from nothing.
redone, p = true, &part{path: p.path, h: sha256.New()}
continue
}
return d.keep(p)
}
if ctx.Err() != nil {
return ctx.Err()
}
if Gone(err) {
_ = os.Remove(p.path)
return err
}
if !Transient(err) {
return err // the part stays, for the next run
}
if p.have > before {
fails, delay = 0, d.Delay
} else {
fails++
}
if fails >= d.Tries || n >= maxTries {
return err
}
if d.Log != nil {
_, _ = fmt.Fprintf(d.Log, "%s: %v; trying again from byte %d in %s\n", d.URL, err, p.have, delay)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
delay = min(delay*2, maxDelay)
}
}
// sums reports whether p's bytes have the SHA-256 asked for.
func (d Resumable) sums(p *part) bool {
return strings.EqualFold(hex.EncodeToString(p.h.Sum(nil)), d.SHA256)
}
// keep puts p, which checked out, at Path: a rename that fails is this
// machine's failure (ErrWrite).
func (d Resumable) keep(p *part) error {
if err := os.Rename(p.path, d.Path); err != nil {
return fmt.Errorf("%w: %w", ErrWrite, err)
}
return nil
}
// openPart reads what an earlier run left at path, hashing it; one over
// limit is started again.
func openPart(path string, limit int64) (*part, error) {
p := &part{path: path, h: sha256.New()}
f, err := os.Open(path) //nolint:gosec // the caller's own path: a download's part
if errors.Is(err, os.ErrNotExist) {
return p, nil
} else if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
n, err := io.Copy(p.h, io.LimitReader(f, limit+1))
if err != nil {
return nil, err
}
if n > limit {
return &part{path: path, h: sha256.New()}, os.Remove(path)
}
p.have = n
return p, nil
}
// errRestart is a server that won't resume the part: it has nothing past
// what the part holds (416), so the part isn't the file, or it answered
// the range from another byte. The part starts again.
var errRestart = errors.New("the server can't go on from the part: starting again")
// try asks for what p lacks and appends it, hashing as it goes. A server
// that sends the whole file again (200, as for a part it can't resume)
// starts the part again.
func (d Resumable) try(ctx context.Context, c *Client, p *part) error {
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.URL, http.NoBody)
if err != nil {
return fmt.Errorf("%w: %w", errRequest, err)
}
// The file's own bytes, never gzip's, which net/http asks for unless
// told otherwise and would unpack: a range counts the bytes sent.
req.Header.Set("Accept-Encoding", "identity")
if p.have > 0 {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", p.have))
if p.tag != "" {
req.Header.Set("If-Range", p.tag)
}
}
stall := time.AfterFunc(d.Stall, func() { cancel(ErrStalled) })
defer stall.Stop()
resp, err := c.Do(req)
if err != nil {
return stalled(ctx, err)
}
defer func() { _ = resp.Body.Close() }()
appending := false
switch {
case resp.StatusCode == http.StatusPartialContent && p.have > 0:
start, _, total, ok := parseContentRange(resp.Header.Get("Content-Range"))
if !ok || start != p.have {
*p = part{path: p.path, h: sha256.New()}
return errRestart
}
if total > d.Limit {
_ = os.Remove(p.path)
return fmt.Errorf("%s: %w: %d bytes, more than %d", d.URL, ErrTooLarge, total, d.Limit)
}
appending = true
case resp.StatusCode == http.StatusOK:
case resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && p.have > 0:
*p = part{path: p.path, h: sha256.New()}
return errRestart
default:
return &StatusError{URL: d.URL, Code: resp.StatusCode, Status: resp.Status}
}
if !appending {
p.h.Reset()
p.have = 0
}
if tag := validator(resp.Header); tag != "" {
p.tag = tag
}
flags := os.O_WRONLY | os.O_CREATE | os.O_APPEND
if !appending {
flags = os.O_WRONLY | os.O_CREATE | os.O_TRUNC //nolint:forbidigo // a download streamed into its part, kept only once it checks out
}
f, err := os.OpenFile(p.path, flags, 0o600)
if err != nil {
return fmt.Errorf("%w: %w", ErrWrite, err)
}
body := &stallReader{r: resp.Body, t: stall, d: d.Stall}
_, err = io.Copy(partWriter{f: f, p: p}, io.LimitReader(body, d.Limit-p.have+1))
if cerr := f.Close(); err == nil && cerr != nil {
err = fmt.Errorf("%w: %w", ErrWrite, cerr)
}
if err != nil {
return stalled(ctx, err)
}
if p.have > d.Limit {
_ = os.Remove(p.path)
return fmt.Errorf("%s: %w: more than %d bytes", d.URL, ErrTooLarge, d.Limit)
}
return nil
}
// stalled is err, or ErrStalled when the try ended because nothing came.
func stalled(ctx context.Context, err error) error {
if errors.Is(context.Cause(ctx), ErrStalled) {
return ErrStalled
}
return err
}
// stallReader resets its timer at each read that brought bytes.
type stallReader struct {
r io.Reader
t *time.Timer
d time.Duration
}
func (s *stallReader) Read(b []byte) (int, error) {
n, err := s.r.Read(b)
if n > 0 {
s.t.Reset(s.d)
}
return n, err
}
// partWriter appends to a part's file, hashing and counting only the
// bytes the file took, so the part's hash and length never part ways,
// even on a full disk's short write.
type partWriter struct {
f *os.File
p *part
}
func (w partWriter) Write(b []byte) (int, error) {
n, err := w.f.Write(b)
_, _ = w.p.h.Write(b[:n]) // a hash.Hash never fails
w.p.have += int64(n)
if err != nil {
return n, fmt.Errorf("%w: %w", ErrWrite, err)
}
return n, nil
}
// parseContentRange reads a 206's Content-Range as RFC 9110 writes one,
// "bytes START-END/LENGTH" or "bytes START-END/*": its first and last
// byte and the file's length, -1 for *. False for anything else: a
// range that ends before it starts or at or past the length, and numbers
// with a sign, a space, a leading zero or more digits than an int64 has.
func parseContentRange(cr string) (start, end, total int64, ok bool) {
rest, ok := strings.CutPrefix(cr, "bytes ")
if !ok {
return 0, 0, 0, false
}
span, length, ok := strings.Cut(rest, "/")
if !ok {
return 0, 0, 0, false
}
first, last, ok := strings.Cut(span, "-")
if !ok {
return 0, 0, 0, false
}
start, ok1 := digits(first)
end, ok2 := digits(last)
total, ok3 := int64(-1), length == "*"
if !ok3 {
total, ok3 = digits(length)
}
if !ok1 || !ok2 || !ok3 || end < start || total >= 0 && end >= total {
return 0, 0, 0, false
}
return start, end, total, true
}
// digits reads s as a number in plain decimal digits, without a sign or
// a leading zero; false for anything else, and for one too large.
func digits(s string) (int64, bool) {
if s == "" || len(s) > 1 && s[0] == '0' || strings.Trim(s, "0123456789") != "" {
return 0, false
}
n, err := strconv.ParseInt(s, 10, 64)
return n, err == nil
}
// validator is what an answer names its body by, for If-Range: a strong
// ETag, else its Last-Modified; "" for neither. A weak ETag can't be one.
func validator(h http.Header) string {
if e := h.Get("ETag"); e != "" && !strings.HasPrefix(e, "W/") {
return e
}
return h.Get("Last-Modified")
}