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