download.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log/slog"
  9. "math"
  10. "math/rand/v2"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "sync/atomic"
  19. "syscall"
  20. "time"
  21. "golang.org/x/sync/errgroup"
  22. "github.com/ollama/ollama/api"
  23. "github.com/ollama/ollama/format"
  24. )
  25. const maxRetries = 6
  26. var (
  27. errMaxRetriesExceeded = errors.New("max retries exceeded")
  28. errPartStalled = errors.New("part stalled")
  29. )
  30. var blobDownloadManager sync.Map
  31. type blobDownload struct {
  32. Name string
  33. Digest string
  34. Total int64
  35. Completed atomic.Int64
  36. Parts []*blobDownloadPart
  37. context.CancelFunc
  38. done chan struct{}
  39. err error
  40. references atomic.Int32
  41. }
  42. type blobDownloadPart struct {
  43. N int
  44. Offset int64
  45. Size int64
  46. Completed atomic.Int64
  47. lastUpdatedMu sync.Mutex
  48. lastUpdated time.Time
  49. *blobDownload `json:"-"`
  50. }
  51. type jsonBlobDownloadPart struct {
  52. N int
  53. Offset int64
  54. Size int64
  55. Completed int64
  56. }
  57. func (p *blobDownloadPart) MarshalJSON() ([]byte, error) {
  58. return json.Marshal(jsonBlobDownloadPart{
  59. N: p.N,
  60. Offset: p.Offset,
  61. Size: p.Size,
  62. Completed: p.Completed.Load(),
  63. })
  64. }
  65. func (p *blobDownloadPart) UnmarshalJSON(b []byte) error {
  66. var j jsonBlobDownloadPart
  67. if err := json.Unmarshal(b, &j); err != nil {
  68. return err
  69. }
  70. *p = blobDownloadPart{
  71. N: j.N,
  72. Offset: j.Offset,
  73. Size: j.Size,
  74. }
  75. p.Completed.Store(j.Completed)
  76. return nil
  77. }
  78. const (
  79. numDownloadParts = 16
  80. minDownloadPartSize int64 = 100 * format.MegaByte
  81. maxDownloadPartSize int64 = 1000 * format.MegaByte
  82. )
  83. func (p *blobDownloadPart) Name() string {
  84. return strings.Join([]string{
  85. p.blobDownload.Name, "partial", strconv.Itoa(p.N),
  86. }, "-")
  87. }
  88. func (p *blobDownloadPart) StartsAt() int64 {
  89. return p.Offset + p.Completed.Load()
  90. }
  91. func (p *blobDownloadPart) StopsAt() int64 {
  92. return p.Offset + p.Size
  93. }
  94. func (p *blobDownloadPart) Write(b []byte) (n int, err error) {
  95. n = len(b)
  96. p.blobDownload.Completed.Add(int64(n))
  97. p.lastUpdatedMu.Lock()
  98. p.lastUpdated = time.Now()
  99. p.lastUpdatedMu.Unlock()
  100. return n, nil
  101. }
  102. func (b *blobDownload) Prepare(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
  103. partFilePaths, err := filepath.Glob(b.Name + "-partial-*")
  104. if err != nil {
  105. return err
  106. }
  107. b.done = make(chan struct{})
  108. for _, partFilePath := range partFilePaths {
  109. part, err := b.readPart(partFilePath)
  110. if err != nil {
  111. return err
  112. }
  113. b.Total += part.Size
  114. b.Completed.Add(part.Completed.Load())
  115. b.Parts = append(b.Parts, part)
  116. }
  117. if len(b.Parts) == 0 {
  118. resp, err := makeRequestWithRetry(ctx, http.MethodHead, requestURL, nil, nil, opts)
  119. if err != nil {
  120. return err
  121. }
  122. defer resp.Body.Close()
  123. b.Total, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
  124. size := b.Total / numDownloadParts
  125. switch {
  126. case size < minDownloadPartSize:
  127. size = minDownloadPartSize
  128. case size > maxDownloadPartSize:
  129. size = maxDownloadPartSize
  130. }
  131. var offset int64
  132. for offset < b.Total {
  133. if offset+size > b.Total {
  134. size = b.Total - offset
  135. }
  136. if err := b.newPart(offset, size); err != nil {
  137. return err
  138. }
  139. offset += size
  140. }
  141. } else {
  142. slog.Info(fmt.Sprintf("downloading %s in %d %s part(s)", b.Digest[7:19], len(b.Parts), format.HumanBytes(b.Parts[0].Size)))
  143. }
  144. return nil
  145. }
  146. func (b *blobDownload) Run(ctx context.Context, requestURL *url.URL, opts *registryOptions) {
  147. defer close(b.done)
  148. b.err = b.run(ctx, requestURL, opts)
  149. }
  150. func newBackoff(maxBackoff time.Duration) func(ctx context.Context) error {
  151. var n int
  152. return func(ctx context.Context) error {
  153. if ctx.Err() != nil {
  154. return ctx.Err()
  155. }
  156. n++
  157. // n^2 backoff timer is a little smoother than the
  158. // common choice of 2^n.
  159. d := min(time.Duration(n*n)*10*time.Millisecond, maxBackoff)
  160. // Randomize the delay between 0.5-1.5 x msec, in order
  161. // to prevent accidental "thundering herd" problems.
  162. d = time.Duration(float64(d) * (rand.Float64() + 0.5))
  163. t := time.NewTimer(d)
  164. defer t.Stop()
  165. select {
  166. case <-ctx.Done():
  167. return ctx.Err()
  168. case <-t.C:
  169. return nil
  170. }
  171. }
  172. }
  173. func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
  174. defer blobDownloadManager.Delete(b.Digest)
  175. ctx, b.CancelFunc = context.WithCancel(ctx)
  176. file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0o644)
  177. if err != nil {
  178. return err
  179. }
  180. defer file.Close()
  181. setSparse(file)
  182. _ = file.Truncate(b.Total)
  183. directURL, err := func() (*url.URL, error) {
  184. ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
  185. defer cancel()
  186. backoff := newBackoff(10 * time.Second)
  187. for {
  188. // shallow clone opts to be used in the closure
  189. // without affecting the outer opts.
  190. newOpts := new(registryOptions)
  191. *newOpts = *opts
  192. newOpts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  193. if len(via) > 10 {
  194. return errors.New("maximum redirects exceeded (10) for directURL")
  195. }
  196. // if the hostname is the same, allow the redirect
  197. if req.URL.Hostname() == requestURL.Hostname() {
  198. return nil
  199. }
  200. // stop at the first redirect that is not
  201. // the same hostname as the original
  202. // request.
  203. return http.ErrUseLastResponse
  204. }
  205. resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, nil, nil, newOpts)
  206. if err != nil {
  207. slog.Warn("failed to get direct URL; backing off and retrying", "err", err)
  208. if err := backoff(ctx); err != nil {
  209. return nil, err
  210. }
  211. continue
  212. }
  213. defer resp.Body.Close()
  214. if resp.StatusCode != http.StatusTemporaryRedirect && resp.StatusCode != http.StatusOK {
  215. return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
  216. }
  217. return resp.Location()
  218. }
  219. }()
  220. if err != nil {
  221. return err
  222. }
  223. g, inner := errgroup.WithContext(ctx)
  224. g.SetLimit(numDownloadParts)
  225. for i := range b.Parts {
  226. part := b.Parts[i]
  227. if part.Completed.Load() == part.Size {
  228. continue
  229. }
  230. g.Go(func() error {
  231. var err error
  232. for try := 0; try < maxRetries; try++ {
  233. w := io.NewOffsetWriter(file, part.StartsAt())
  234. err = b.downloadChunk(inner, directURL, w, part)
  235. switch {
  236. case errors.Is(err, context.Canceled), errors.Is(err, syscall.ENOSPC):
  237. // return immediately if the context is canceled or the device is out of space
  238. return err
  239. case errors.Is(err, errPartStalled):
  240. try--
  241. continue
  242. case err != nil:
  243. sleep := time.Second * time.Duration(math.Pow(2, float64(try)))
  244. slog.Info(fmt.Sprintf("%s part %d attempt %d failed: %v, retrying in %s", b.Digest[7:19], part.N, try, err, sleep))
  245. time.Sleep(sleep)
  246. continue
  247. default:
  248. return nil
  249. }
  250. }
  251. return fmt.Errorf("%w: %w", errMaxRetriesExceeded, err)
  252. })
  253. }
  254. if err := g.Wait(); err != nil {
  255. return err
  256. }
  257. // explicitly close the file so we can rename it
  258. if err := file.Close(); err != nil {
  259. return err
  260. }
  261. for i := range b.Parts {
  262. if err := os.Remove(file.Name() + "-" + strconv.Itoa(i)); err != nil {
  263. return err
  264. }
  265. }
  266. if err := os.Rename(file.Name(), b.Name); err != nil {
  267. return err
  268. }
  269. return nil
  270. }
  271. func (b *blobDownload) downloadChunk(ctx context.Context, requestURL *url.URL, w io.Writer, part *blobDownloadPart) error {
  272. g, ctx := errgroup.WithContext(ctx)
  273. g.Go(func() error {
  274. req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL.String(), nil)
  275. if err != nil {
  276. return err
  277. }
  278. req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", part.StartsAt(), part.StopsAt()-1))
  279. resp, err := http.DefaultClient.Do(req)
  280. if err != nil {
  281. return err
  282. }
  283. defer resp.Body.Close()
  284. n, err := io.CopyN(w, io.TeeReader(resp.Body, part), part.Size-part.Completed.Load())
  285. if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.ErrUnexpectedEOF) {
  286. // rollback progress
  287. b.Completed.Add(-n)
  288. return err
  289. }
  290. part.Completed.Add(n)
  291. if err := b.writePart(part.Name(), part); err != nil {
  292. return err
  293. }
  294. // return nil or context.Canceled or UnexpectedEOF (resumable)
  295. return err
  296. })
  297. g.Go(func() error {
  298. ticker := time.NewTicker(time.Second)
  299. for {
  300. select {
  301. case <-ticker.C:
  302. if part.Completed.Load() >= part.Size {
  303. return nil
  304. }
  305. part.lastUpdatedMu.Lock()
  306. lastUpdated := part.lastUpdated
  307. part.lastUpdatedMu.Unlock()
  308. if !lastUpdated.IsZero() && time.Since(lastUpdated) > 5*time.Second {
  309. const msg = "%s part %d stalled; retrying. If this persists, press ctrl-c to exit, then 'ollama pull' to find a faster connection."
  310. slog.Info(fmt.Sprintf(msg, b.Digest[7:19], part.N))
  311. // reset last updated
  312. part.lastUpdatedMu.Lock()
  313. part.lastUpdated = time.Time{}
  314. part.lastUpdatedMu.Unlock()
  315. return errPartStalled
  316. }
  317. case <-ctx.Done():
  318. return ctx.Err()
  319. }
  320. }
  321. })
  322. return g.Wait()
  323. }
  324. func (b *blobDownload) newPart(offset, size int64) error {
  325. part := blobDownloadPart{blobDownload: b, Offset: offset, Size: size, N: len(b.Parts)}
  326. if err := b.writePart(part.Name(), &part); err != nil {
  327. return err
  328. }
  329. b.Parts = append(b.Parts, &part)
  330. return nil
  331. }
  332. func (b *blobDownload) readPart(partName string) (*blobDownloadPart, error) {
  333. var part blobDownloadPart
  334. partFile, err := os.Open(partName)
  335. if err != nil {
  336. return nil, err
  337. }
  338. defer partFile.Close()
  339. if err := json.NewDecoder(partFile).Decode(&part); err != nil {
  340. return nil, err
  341. }
  342. part.blobDownload = b
  343. return &part, nil
  344. }
  345. func (b *blobDownload) writePart(partName string, part *blobDownloadPart) error {
  346. partFile, err := os.OpenFile(partName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o644)
  347. if err != nil {
  348. return err
  349. }
  350. defer partFile.Close()
  351. return json.NewEncoder(partFile).Encode(part)
  352. }
  353. func (b *blobDownload) acquire() {
  354. b.references.Add(1)
  355. }
  356. func (b *blobDownload) release() {
  357. if b.references.Add(-1) == 0 {
  358. b.CancelFunc()
  359. }
  360. }
  361. func (b *blobDownload) Wait(ctx context.Context, fn func(api.ProgressResponse)) error {
  362. b.acquire()
  363. defer b.release()
  364. ticker := time.NewTicker(60 * time.Millisecond)
  365. for {
  366. select {
  367. case <-b.done:
  368. return b.err
  369. case <-ticker.C:
  370. fn(api.ProgressResponse{
  371. Status: fmt.Sprintf("pulling %s", b.Digest[7:19]),
  372. Digest: b.Digest,
  373. Total: b.Total,
  374. Completed: b.Completed.Load(),
  375. })
  376. case <-ctx.Done():
  377. return ctx.Err()
  378. }
  379. }
  380. }
  381. type downloadOpts struct {
  382. mp ModelPath
  383. digest string
  384. regOpts *registryOptions
  385. fn func(api.ProgressResponse)
  386. }
  387. // downloadBlob downloads a blob from the registry and stores it in the blobs directory
  388. func downloadBlob(ctx context.Context, opts downloadOpts) (cacheHit bool, _ error) {
  389. fp, err := GetBlobsPath(opts.digest)
  390. if err != nil {
  391. return false, err
  392. }
  393. fi, err := os.Stat(fp)
  394. switch {
  395. case errors.Is(err, os.ErrNotExist):
  396. case err != nil:
  397. return false, err
  398. default:
  399. opts.fn(api.ProgressResponse{
  400. Status: fmt.Sprintf("pulling %s", opts.digest[7:19]),
  401. Digest: opts.digest,
  402. Total: fi.Size(),
  403. Completed: fi.Size(),
  404. })
  405. return true, nil
  406. }
  407. data, ok := blobDownloadManager.LoadOrStore(opts.digest, &blobDownload{Name: fp, Digest: opts.digest})
  408. download := data.(*blobDownload)
  409. if !ok {
  410. requestURL := opts.mp.BaseURL()
  411. requestURL = requestURL.JoinPath("v2", opts.mp.GetNamespaceRepository(), "blobs", opts.digest)
  412. if err := download.Prepare(ctx, requestURL, opts.regOpts); err != nil {
  413. blobDownloadManager.Delete(opts.digest)
  414. return false, err
  415. }
  416. //nolint:contextcheck
  417. go download.Run(context.Background(), requestURL, opts.regOpts)
  418. }
  419. return false, download.Wait(ctx, opts.fn)
  420. }