download.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 = 64
  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. }
  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. return nil
  144. }
  145. func (b *blobDownload) Run(ctx context.Context, requestURL *url.URL, opts *registryOptions) {
  146. defer close(b.done)
  147. b.err = b.run(ctx, requestURL, opts)
  148. }
  149. func newBackoff(maxBackoff time.Duration) func(ctx context.Context) error {
  150. var n int
  151. return func(ctx context.Context) error {
  152. if ctx.Err() != nil {
  153. return ctx.Err()
  154. }
  155. n++
  156. // n^2 backoff timer is a little smoother than the
  157. // common choice of 2^n.
  158. d := min(time.Duration(n*n)*10*time.Millisecond, maxBackoff)
  159. // Randomize the delay between 0.5-1.5 x msec, in order
  160. // to prevent accidental "thundering herd" problems.
  161. d = time.Duration(float64(d) * (rand.Float64() + 0.5))
  162. t := time.NewTimer(d)
  163. defer t.Stop()
  164. select {
  165. case <-ctx.Done():
  166. return ctx.Err()
  167. case <-t.C:
  168. return nil
  169. }
  170. }
  171. }
  172. func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
  173. defer blobDownloadManager.Delete(b.Digest)
  174. ctx, b.CancelFunc = context.WithCancel(ctx)
  175. file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0o644)
  176. if err != nil {
  177. return err
  178. }
  179. defer file.Close()
  180. _ = file.Truncate(b.Total)
  181. directURL, err := func() (*url.URL, error) {
  182. ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
  183. defer cancel()
  184. backoff := newBackoff(10 * time.Second)
  185. for {
  186. // shallow clone opts to be used in the closure
  187. // without affecting the outer opts.
  188. newOpts := new(registryOptions)
  189. *newOpts = *opts
  190. newOpts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  191. if len(via) > 10 {
  192. return errors.New("maxium redirects exceeded (10) for directURL")
  193. }
  194. // if the hostname is the same, allow the redirect
  195. if req.URL.Hostname() == requestURL.Hostname() {
  196. return nil
  197. }
  198. // stop at the first redirect that is not
  199. // the same hostname as the original
  200. // request.
  201. return http.ErrUseLastResponse
  202. }
  203. resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, nil, nil, newOpts)
  204. if err != nil {
  205. slog.Warn("failed to get direct URL; backing off and retrying", "err", err)
  206. if err := backoff(ctx); err != nil {
  207. return nil, err
  208. }
  209. continue
  210. }
  211. defer resp.Body.Close()
  212. if resp.StatusCode != http.StatusTemporaryRedirect {
  213. return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
  214. }
  215. return resp.Location()
  216. }
  217. }()
  218. if err != nil {
  219. return err
  220. }
  221. g, inner := errgroup.WithContext(ctx)
  222. g.SetLimit(numDownloadParts)
  223. for i := range b.Parts {
  224. part := b.Parts[i]
  225. if part.Completed.Load() == part.Size {
  226. continue
  227. }
  228. g.Go(func() error {
  229. var err error
  230. for try := 0; try < maxRetries; try++ {
  231. w := io.NewOffsetWriter(file, part.StartsAt())
  232. err = b.downloadChunk(inner, directURL, w, part)
  233. switch {
  234. case errors.Is(err, context.Canceled), errors.Is(err, syscall.ENOSPC):
  235. // return immediately if the context is canceled or the device is out of space
  236. return err
  237. case errors.Is(err, errPartStalled):
  238. try--
  239. continue
  240. case err != nil:
  241. sleep := time.Second * time.Duration(math.Pow(2, float64(try)))
  242. slog.Info(fmt.Sprintf("%s part %d attempt %d failed: %v, retrying in %s", b.Digest[7:19], part.N, try, err, sleep))
  243. time.Sleep(sleep)
  244. continue
  245. default:
  246. return nil
  247. }
  248. }
  249. return fmt.Errorf("%w: %w", errMaxRetriesExceeded, err)
  250. })
  251. }
  252. if err := g.Wait(); err != nil {
  253. return err
  254. }
  255. // explicitly close the file so we can rename it
  256. if err := file.Close(); err != nil {
  257. return err
  258. }
  259. for i := range b.Parts {
  260. if err := os.Remove(file.Name() + "-" + strconv.Itoa(i)); err != nil {
  261. return err
  262. }
  263. }
  264. if err := os.Rename(file.Name(), b.Name); err != nil {
  265. return err
  266. }
  267. return nil
  268. }
  269. func (b *blobDownload) downloadChunk(ctx context.Context, requestURL *url.URL, w io.Writer, part *blobDownloadPart) error {
  270. g, ctx := errgroup.WithContext(ctx)
  271. g.Go(func() error {
  272. req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL.String(), nil)
  273. if err != nil {
  274. return err
  275. }
  276. req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", part.StartsAt(), part.StopsAt()-1))
  277. resp, err := http.DefaultClient.Do(req)
  278. if err != nil {
  279. return err
  280. }
  281. defer resp.Body.Close()
  282. n, err := io.CopyN(w, io.TeeReader(resp.Body, part), part.Size-part.Completed.Load())
  283. if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.ErrUnexpectedEOF) {
  284. // rollback progress
  285. b.Completed.Add(-n)
  286. return err
  287. }
  288. part.Completed.Add(n)
  289. if err := b.writePart(part.Name(), part); err != nil {
  290. return err
  291. }
  292. // return nil or context.Canceled or UnexpectedEOF (resumable)
  293. return err
  294. })
  295. g.Go(func() error {
  296. ticker := time.NewTicker(time.Second)
  297. for {
  298. select {
  299. case <-ticker.C:
  300. if part.Completed.Load() >= part.Size {
  301. return nil
  302. }
  303. part.lastUpdatedMu.Lock()
  304. lastUpdated := part.lastUpdated
  305. part.lastUpdatedMu.Unlock()
  306. if !lastUpdated.IsZero() && time.Since(lastUpdated) > 5*time.Second {
  307. const msg = "%s part %d stalled; retrying. If this persists, press ctrl-c to exit, then 'ollama pull' to find a faster connection."
  308. slog.Info(fmt.Sprintf(msg, b.Digest[7:19], part.N))
  309. // reset last updated
  310. part.lastUpdatedMu.Lock()
  311. part.lastUpdated = time.Time{}
  312. part.lastUpdatedMu.Unlock()
  313. return errPartStalled
  314. }
  315. case <-ctx.Done():
  316. return ctx.Err()
  317. }
  318. }
  319. })
  320. return g.Wait()
  321. }
  322. func (b *blobDownload) newPart(offset, size int64) error {
  323. part := blobDownloadPart{blobDownload: b, Offset: offset, Size: size, N: len(b.Parts)}
  324. if err := b.writePart(part.Name(), &part); err != nil {
  325. return err
  326. }
  327. b.Parts = append(b.Parts, &part)
  328. return nil
  329. }
  330. func (b *blobDownload) readPart(partName string) (*blobDownloadPart, error) {
  331. var part blobDownloadPart
  332. partFile, err := os.Open(partName)
  333. if err != nil {
  334. return nil, err
  335. }
  336. defer partFile.Close()
  337. if err := json.NewDecoder(partFile).Decode(&part); err != nil {
  338. return nil, err
  339. }
  340. part.blobDownload = b
  341. return &part, nil
  342. }
  343. func (b *blobDownload) writePart(partName string, part *blobDownloadPart) error {
  344. partFile, err := os.OpenFile(partName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o644)
  345. if err != nil {
  346. return err
  347. }
  348. defer partFile.Close()
  349. return json.NewEncoder(partFile).Encode(part)
  350. }
  351. func (b *blobDownload) acquire() {
  352. b.references.Add(1)
  353. }
  354. func (b *blobDownload) release() {
  355. if b.references.Add(-1) == 0 {
  356. b.CancelFunc()
  357. }
  358. }
  359. func (b *blobDownload) Wait(ctx context.Context, fn func(api.ProgressResponse)) error {
  360. b.acquire()
  361. defer b.release()
  362. ticker := time.NewTicker(60 * time.Millisecond)
  363. for {
  364. select {
  365. case <-b.done:
  366. return b.err
  367. case <-ticker.C:
  368. fn(api.ProgressResponse{
  369. Status: fmt.Sprintf("pulling %s", b.Digest[7:19]),
  370. Digest: b.Digest,
  371. Total: b.Total,
  372. Completed: b.Completed.Load(),
  373. })
  374. case <-ctx.Done():
  375. return ctx.Err()
  376. }
  377. }
  378. }
  379. type downloadOpts struct {
  380. mp ModelPath
  381. digest string
  382. regOpts *registryOptions
  383. fn func(api.ProgressResponse)
  384. }
  385. // downloadBlob downloads a blob from the registry and stores it in the blobs directory
  386. func downloadBlob(ctx context.Context, opts downloadOpts) (cacheHit bool, _ error) {
  387. fp, err := GetBlobsPath(opts.digest)
  388. if err != nil {
  389. return false, err
  390. }
  391. fi, err := os.Stat(fp)
  392. switch {
  393. case errors.Is(err, os.ErrNotExist):
  394. case err != nil:
  395. return false, err
  396. default:
  397. opts.fn(api.ProgressResponse{
  398. Status: fmt.Sprintf("pulling %s", opts.digest[7:19]),
  399. Digest: opts.digest,
  400. Total: fi.Size(),
  401. Completed: fi.Size(),
  402. })
  403. return true, nil
  404. }
  405. data, ok := blobDownloadManager.LoadOrStore(opts.digest, &blobDownload{Name: fp, Digest: opts.digest})
  406. download := data.(*blobDownload)
  407. if !ok {
  408. requestURL := opts.mp.BaseURL()
  409. requestURL = requestURL.JoinPath("v2", opts.mp.GetNamespaceRepository(), "blobs", opts.digest)
  410. if err := download.Prepare(ctx, requestURL, opts.regOpts); err != nil {
  411. blobDownloadManager.Delete(opts.digest)
  412. return false, err
  413. }
  414. //nolint:contextcheck
  415. go download.Run(context.Background(), requestURL, opts.regOpts)
  416. }
  417. return false, download.Wait(ctx, opts.fn)
  418. }