download.go 11 KB

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