Files
w3cjandClaude Opus 5.5 32a3469ed2 fix(assets): image builds' downloads retry, resume and time out on a stall
What a build VM downloads failed on a network's first hiccup: curl's
--retry 3 skips a connection cut mid-transfer (exit 18) and waits for
ever on a stall, apt's retries were off, and oh-my-bash's clone had
none.

- devvm-fetch: each try has --connect-timeout 20 and a stall limit
  (--speed-limit 1024 --speed-time 30), and any failure is tried again,
  five tries in all, from where it stopped (-C -): curl's own --retry,
  --retry-all-errors included, starts again from nothing (measured on
  curl 8.7). A server that can't resume (33, 36) starts it again; a file
  that came whole and checks out ends the loop; a file that doesn't
  check out is fetched again from nothing once, as a resume may have
  joined two versions. A redirect goes only to https
  (--proto-redir =https), so no try or resume moves to plain http.
  TestDevvmFetchTries runs it against a server that cuts, ignores
  ranges, changes the file, fails and redirects to http.
- apt.sh: package lists still fail fast (exit 75 when no source
  answers), and once they're in, the build's installs get
  Acquire::Retries "3", with apt's own backoff.
- crane (oci/build.sh, the --from conversion, which has no devvm-fetch):
  --retry 5 --retry-all-errors --retry-delay 2 and the same timeouts.
- oh-my-bash: the clone is tried five times in all, with git's
  low-speed limit.

Docs: images.md's Building and Base's packages, customizing.md's
devvm-fetch; the CHANGELOG's second highlight, which says which
downloads resume, and What to do 1, which names the layers and --from
bases that rebuild and pull again; the release page's A first run on a
bad network.

Image keys change: base's (base.sh, apt.sh, omb.sh), every layer's
(apt.sh is in each), and a --from conversion's (oci/build.sh). Tool
images' keys don't (shared-tools/build.sh is unchanged).

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

149 lines
5.2 KiB
Go

package assets
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"sync"
"testing"
"time"
)
// devvmFetch is devvm-fetch as base.sh installs it, written into a
// folder of the test's own, with a sleep there that waits for nothing, so
// its tries don't wait on the real clock.
func devvmFetch(t *testing.T) (script, bin string) {
t.Helper()
for _, tool := range []string{"curl", "sha256sum"} {
if _, err := exec.LookPath(tool); err != nil {
t.Skipf("no %s: devvm-fetch runs it", tool)
}
}
body := heredoc(t, "sudo tee /usr/local/bin/devvm-fetch >/dev/null <<'SH'", "SH")
dir := t.TempDir()
script = filepath.Join(dir, "devvm-fetch")
must(t, os.WriteFile(script, []byte(body+"\n"), 0o600))
bin = filepath.Join(dir, "bin")
must(t, os.Mkdir(bin, 0o700))
must(t, os.WriteFile(filepath.Join(bin, "sleep"), []byte("#!/bin/sh\nexit 0\n"), 0o700)) //nolint:gosec // a program: the script runs it
return script, bin
}
// fetchServer serves body as a file server does (Range), going wrong on
// its first requests as fail says, and records each request's Range:
// "cut" sends a quarter of the body then drops the connection, "500"
// answers that, "whole" sends the whole body (200) whatever range it was
// asked for, and "other" serves another file of the same length.
type fetchServer struct {
body, other []byte
fail []string
mu sync.Mutex
ranges []string
}
func (f *fetchServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
n := len(f.ranges)
f.ranges = append(f.ranges, r.Header.Get("Range"))
f.mu.Unlock()
how := ""
if n < len(f.fail) {
how = f.fail[n]
}
switch how {
case "500":
http.Error(w, "no", http.StatusInternalServerError)
case "redirect":
http.Redirect(w, r, "http://"+r.Host+r.URL.Path, http.StatusFound) //nolint:gosec // G710: the test's own server, sending curl back to itself over http
case "whole":
_, _ = w.Write(f.body)
case "other":
http.ServeContent(w, r, "f", time.Time{}, bytes.NewReader(f.other))
case "cut":
cw := &quarterWriter{ResponseWriter: w, left: len(f.body) / 4}
http.ServeContent(cw, r, "f", time.Time{}, bytes.NewReader(f.body))
panic(http.ErrAbortHandler) // drops the connection
default:
http.ServeContent(w, r, "f", time.Time{}, bytes.NewReader(f.body))
}
}
// quarterWriter writes no more than left bytes of a body, flushed.
type quarterWriter struct {
http.ResponseWriter
left int
}
func (q *quarterWriter) Write(b []byte) (int, error) {
n := min(len(b), q.left)
q.left -= n
n, err := q.ResponseWriter.Write(b[:n])
if fl, ok := q.ResponseWriter.(http.Flusher); ok {
fl.Flush()
}
if err == nil && n < len(b) {
panic(http.ErrAbortHandler)
}
return n, err
}
// devvm-fetch keeps only a file whose checksum is the one asked for: it
// resumes a download that was cut from where it stopped, starts again from
// nothing when the server won't resume (curl's 33) or a resume joined two
// files (the server changed it), and fails after five tries that failed.
func TestDevvmFetchTries(t *testing.T) {
script, bin := devvmFetch(t)
body := bytes.Repeat([]byte("0123456789abcdef"), 4096)
other := bytes.Repeat([]byte("fedcba9876543210"), 4096)
sum := sha256.Sum256(body)
quarter := "bytes=" + strconv.Itoa(len(body)/4) + "-"
for _, tc := range []struct {
name string
fail []string
want bool
wantRanges []string
}{
{name: "whole", want: true, wantRanges: []string{""}},
{name: "cut", fail: []string{"cut"}, want: true, wantRanges: []string{"", quarter}},
{name: "a range answered whole", fail: []string{"cut", "whole"}, want: true, wantRanges: []string{"", quarter, ""}},
{name: "the file changed", fail: []string{"cut", "other"}, want: true, wantRanges: []string{"", quarter, ""}},
{name: "five failures", fail: []string{"500", "500", "500", "500", "500"}, wantRanges: []string{"", "", "", "", ""}},
// A redirect goes only to https, as devvm's own downloads do.
{name: "a redirect to http", fail: []string{"redirect", "redirect", "redirect", "redirect", "redirect"}, wantRanges: []string{"", "", "", "", ""}},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fetchServer{body: body, other: other, fail: tc.fail}
srv := httptest.NewServer(f)
defer srv.Close()
out := filepath.Join(t.TempDir(), "f")
cmd := exec.CommandContext(t.Context(), "sh", script, srv.URL+"/f", hex.EncodeToString(sum[:]), out) //nolint:gosec // G204: devvm's own embedded script, with the test's arguments
cmd.Env = []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), "HOME=" + t.TempDir()}
msgs, err := cmd.CombinedOutput()
if (err == nil) != tc.want {
t.Fatalf("devvm-fetch: %v, want success %v:\n%s", err, tc.want, msgs)
}
f.mu.Lock()
got := f.ranges
f.mu.Unlock()
if !slices.Equal(got, tc.wantRanges) {
t.Errorf("ranges asked: %q, want %q\n%s", got, tc.wantRanges, msgs)
}
data, rerr := os.ReadFile(out) //nolint:gosec // the test's own temp folder
switch {
case tc.want && !bytes.Equal(data, body):
t.Errorf("the file: %d bytes, %v", len(data), rerr)
case !tc.want && rerr == nil:
t.Error("a failed download left its file")
}
})
}
}