| 1 | |
| 2 | |
| 3 | |
| 4 | package downloader |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/lima-vm/lima/v2/pkg/progressbar" |
| 19 | "github.com/opencontainers/go-digest" |
| 20 | "github.com/sirupsen/logrus" |
| 21 | ) |
| 22 | |
| 23 | |
| 24 | |
| 25 | func downloadHTTPResumable(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest) error { |
| 26 | part := local + ".part" |
| 27 | identity := part + ".digest" |
| 28 | previous, err := os.ReadFile(identity) |
| 29 | if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 30 | return err |
| 31 | } |
| 32 | if string(previous) != expected.String() { |
| 33 | if err := os.Remove(part); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 34 | return err |
| 35 | } |
| 36 | if err := os.WriteFile(identity, []byte(expected.String()), 0600); err != nil { |
| 37 | return err |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | if validateLocalFileDigest(part, expected) == nil { |
| 42 | return publishPartial(part, local, identity) |
| 43 | } |
| 44 | for attempt := 0; attempt < 4; attempt++ { |
| 45 | if ctx.Err() != nil { |
| 46 | return ctx.Err() |
| 47 | } |
| 48 | var retry bool |
| 49 | retry, err = resumeHTTPOnce(ctx, local, modified, contentType, remote, description, expected, time.Minute) |
| 50 | if err == nil { |
| 51 | return publishPartial(part, local, identity) |
| 52 | } |
| 53 | if !retry { |
| 54 | return err |
| 55 | } |
| 56 | if attempt < 3 { |
| 57 | logrus.Infof("Image download interrupted; retry %d/3 will reuse saved partial data", attempt+1) |
| 58 | select { |
| 59 | case <-ctx.Done(): |
| 60 | return ctx.Err() |
| 61 | case <-time.After(time.Duration(attempt+1) * time.Second): |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | return fmt.Errorf("image download interrupted; partial data retained for setup retry: %w", err) |
| 66 | } |
| 67 | |
| 68 | func publishPartial(part, local, identity string) error { |
| 69 | if err := os.Rename(part, local); err != nil { |
| 70 | return err |
| 71 | } |
| 72 | return os.Remove(identity) |
| 73 | } |
| 74 | |
| 75 | func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest, idleTimeout time.Duration) (bool, error) { |
| 76 | part := local + ".part" |
| 77 | var offset int64 |
| 78 | if st, err := os.Stat(part); err == nil { |
| 79 | offset = st.Size() |
| 80 | } else if !errors.Is(err, os.ErrNotExist) { |
| 81 | return false, err |
| 82 | } |
| 83 | ctx, cancel := context.WithCancel(ctx) |
| 84 | defer cancel() |
| 85 | |
| 86 | |
| 87 | idle := newDownloadIdleWatchdog(idleTimeout, cancel) |
| 88 | defer idle.stop() |
| 89 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, remote, nil) |
| 90 | if err != nil { |
| 91 | return false, err |
| 92 | } |
| 93 | req.Header.Set("Accept-Encoding", "identity") |
| 94 | if offset > 0 { |
| 95 | req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) |
| 96 | } |
| 97 | resp, err := http.DefaultClient.Do(req) |
| 98 | if err != nil { |
| 99 | return true, err |
| 100 | } |
| 101 | defer resp.Body.Close() |
| 102 | var total int64 |
| 103 | expectedBody := resp.ContentLength |
| 104 | switch resp.StatusCode { |
| 105 | case http.StatusOK: |
| 106 | |
| 107 | offset, total = 0, resp.ContentLength |
| 108 | case http.StatusPartialContent: |
| 109 | start, end, size, ok := parseDownloadRange(resp.Header.Get("Content-Range")) |
| 110 | if !ok || start != offset || (resp.ContentLength >= 0 && resp.ContentLength != end-start+1) { |
| 111 | return false, errors.New("invalid image Content-Range; partial data left unchanged") |
| 112 | } |
| 113 | total = size |
| 114 | expectedBody = end - start + 1 |
| 115 | case http.StatusRequestedRangeNotSatisfiable: |
| 116 | |
| 117 | |
| 118 | if err := os.Remove(part); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 119 | return false, err |
| 120 | } |
| 121 | return true, errors.New("image range rejected; restarting this artifact") |
| 122 | default: |
| 123 | return resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode >= 500, fmt.Errorf("image download returned HTTP %d", resp.StatusCode) |
| 124 | } |
| 125 | for name, value := range map[string]string{modified: resp.Header.Get("Last-Modified"), contentType: resp.Header.Get("Content-Type")} { |
| 126 | if name != "" { |
| 127 | if err := os.WriteFile(name, []byte(value), 0600); err != nil { |
| 128 | return false, err |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | flags := os.O_CREATE | os.O_WRONLY |
| 133 | if offset == 0 { |
| 134 | flags |= os.O_TRUNC |
| 135 | } |
| 136 | out, err := os.OpenFile(part, flags, 0600) |
| 137 | if err != nil { |
| 138 | return false, err |
| 139 | } |
| 140 | defer out.Close() |
| 141 | if _, err := out.Seek(offset, io.SeekStart); err != nil { |
| 142 | return false, err |
| 143 | } |
| 144 | bar, err := progressbar.New(total) |
| 145 | if err != nil { |
| 146 | return false, err |
| 147 | } |
| 148 | if HideProgress { |
| 149 | hideBar(bar) |
| 150 | } |
| 151 | bar.SetCurrent(offset) |
| 152 | if description == "" { |
| 153 | description = "pinned image" |
| 154 | } |
| 155 | logrus.Infof("Downloading %s; continuing at %d bytes", description, offset) |
| 156 | bar.Start() |
| 157 | defer bar.Finish() |
| 158 | reader := &downloadActivityReader{reader: resp.Body, activity: idle.touch} |
| 159 | |
| 160 | |
| 161 | if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { |
| 162 | reader.received = offset |
| 163 | reader.total = total |
| 164 | reader.report = func(received, total int64) { |
| 165 | fmt.Fprintf(os.Stderr, "CAGE_IMAGE_BYTES %d %d\n", received, total) |
| 166 | } |
| 167 | reader.report(offset, total) |
| 168 | reader.lastReport = time.Now() |
| 169 | } |
| 170 | n, err := io.Copy(out, bar.NewProxyReader(reader)) |
| 171 | idle.stop() |
| 172 | if err != nil { |
| 173 | return true, err |
| 174 | } |
| 175 | if expectedBody >= 0 && n != expectedBody { |
| 176 | if n > expectedBody { |
| 177 | _ = out.Close() |
| 178 | _ = os.Remove(part) |
| 179 | return false, errors.New("image response exceeded its declared range; partial data discarded") |
| 180 | } |
| 181 | return true, io.ErrUnexpectedEOF |
| 182 | } |
| 183 | if total >= 0 && n+offset != total { |
| 184 | return true, io.ErrUnexpectedEOF |
| 185 | } |
| 186 | if reader.report != nil { |
| 187 | reader.report(reader.received, total) |
| 188 | fmt.Fprintln(os.Stderr, "CAGE_IMAGE_VERIFY") |
| 189 | } |
| 190 | if err := out.Sync(); err != nil { |
| 191 | return false, err |
| 192 | } |
| 193 | if err := out.Close(); err != nil { |
| 194 | return false, err |
| 195 | } |
| 196 | if err := validateLocalFileDigest(part, expected); err != nil { |
| 197 | _ = os.Remove(part) |
| 198 | return false, fmt.Errorf("image checksum mismatch; partial data discarded: %w", err) |
| 199 | } |
| 200 | return false, nil |
| 201 | } |
| 202 | |
| 203 | type downloadActivityReader struct { |
| 204 | reader io.Reader |
| 205 | activity func() |
| 206 | received, total int64 |
| 207 | report func(int64, int64) |
| 208 | lastReport time.Time |
| 209 | } |
| 210 | |
| 211 | func (r *downloadActivityReader) Read(p []byte) (int, error) { |
| 212 | n, err := r.reader.Read(p) |
| 213 | if n > 0 { |
| 214 | r.activity() |
| 215 | if r.report != nil { |
| 216 | r.received += int64(n) |
| 217 | if time.Since(r.lastReport) >= time.Second { |
| 218 | r.report(r.received, r.total) |
| 219 | r.lastReport = time.Now() |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | return n, err |
| 224 | } |
| 225 | |
| 226 | |
| 227 | |
| 228 | type downloadIdleWatchdog struct { |
| 229 | mu sync.Mutex |
| 230 | timer *time.Timer |
| 231 | last time.Time |
| 232 | timeout time.Duration |
| 233 | cancel context.CancelFunc |
| 234 | stopped bool |
| 235 | } |
| 236 | |
| 237 | func newDownloadIdleWatchdog(timeout time.Duration, cancel context.CancelFunc) *downloadIdleWatchdog { |
| 238 | w := &downloadIdleWatchdog{last: time.Now(), timeout: timeout, cancel: cancel} |
| 239 | w.timer = time.AfterFunc(timeout, func() { |
| 240 | w.mu.Lock() |
| 241 | defer w.mu.Unlock() |
| 242 | if w.stopped { |
| 243 | return |
| 244 | } |
| 245 | if remaining := w.timeout - time.Since(w.last); remaining > 0 { |
| 246 | w.timer.Reset(remaining) |
| 247 | } else { |
| 248 | w.stopped = true |
| 249 | w.cancel() |
| 250 | } |
| 251 | }) |
| 252 | return w |
| 253 | } |
| 254 | |
| 255 | func (w *downloadIdleWatchdog) touch() { |
| 256 | w.mu.Lock() |
| 257 | defer w.mu.Unlock() |
| 258 | w.last = time.Now() |
| 259 | } |
| 260 | |
| 261 | func (w *downloadIdleWatchdog) stop() { |
| 262 | w.mu.Lock() |
| 263 | defer w.mu.Unlock() |
| 264 | w.stopped = true |
| 265 | w.timer.Stop() |
| 266 | } |
| 267 | |
| 268 | func parseDownloadRange(value string) (start, end, total int64, ok bool) { |
| 269 | span, size, found := strings.Cut(strings.TrimPrefix(value, "bytes "), "/") |
| 270 | first, last, dash := strings.Cut(span, "-") |
| 271 | if !strings.HasPrefix(value, "bytes ") || !found || !dash { |
| 272 | return |
| 273 | } |
| 274 | var a, b, c error |
| 275 | start, a = strconv.ParseInt(first, 10, 64) |
| 276 | end, b = strconv.ParseInt(last, 10, 64) |
| 277 | total, c = strconv.ParseInt(size, 10, 64) |
| 278 | ok = a == nil && b == nil && c == nil && start >= 0 && end >= start && total > end |
| 279 | return |
| 280 | } |