download.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log/slog"
  9. "math"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "sync/atomic"
  18. "syscall"
  19. "time"
  20. "golang.org/x/sync/errgroup"
  21. "github.com/ollama/ollama/api"
  22. "github.com/ollama/ollama/format"
  23. )
  24. const maxRetries = 6
  25. var errMaxRetriesExceeded = errors.New("max retries exceeded")
  26. var errPartStalled = errors.New("part stalled")
  27. var blobDownloadManager sync.Map
  28. type blobDownload struct {
  29. Name string
  30. Digest string
  31. Total int64
  32. Completed atomic.Int64
  33. Parts []*blobDownloadPart
  34. context.CancelFunc
  35. done bool
  36. err error
  37. references atomic.Int32
  38. }
  39. type blobDownloadPart struct {
  40. N int
  41. Offset int64
  42. Size int64
  43. Completed int64
  44. lastUpdated time.Time
  45. *blobDownload `json:"-"`
  46. }
  47. const (
  48. numDownloadParts = 64
  49. minDownloadPartSize int64 = 100 * format.MegaByte
  50. maxDownloadPartSize int64 = 1000 * format.MegaByte
  51. )
  52. func (p *blobDownloadPart) Name() string {
  53. return strings.Join([]string{
  54. p.blobDownload.Name, "partial", strconv.Itoa(p.N),
  55. }, "-")
  56. }
  57. func (p *blobDownloadPart) StartsAt() int64 {
  58. return p.Offset + p.Completed
  59. }
  60. func (p *blobDownloadPart) StopsAt() int64 {
  61. return p.Offset + p.Size
  62. }
  63. func (p *blobDownloadPart) Write(b []byte) (n int, err error) {
  64. n = len(b)
  65. p.blobDownload.Completed.Add(int64(n))
  66. p.lastUpdated = time.Now()
  67. return n, nil
  68. }
  69. func (b *blobDownload) Prepare(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
  70. partFilePaths, err := filepath.Glob(b.Name + "-partial-*")
  71. if err != nil {
  72. return err
  73. }
  74. for _, partFilePath := range partFilePaths {
  75. part, err := b.readPart(partFilePath)
  76. if err != nil {
  77. return err
  78. }
  79. b.Total += part.Size
  80. b.Completed.Add(part.Completed)
  81. b.Parts = append(b.Parts, part)
  82. }
  83. if len(b.Parts) == 0 {
  84. resp, err := makeRequestWithRetry(ctx, http.MethodHead, requestURL, nil, nil, opts)
  85. if err != nil {
  86. return err
  87. }
  88. defer resp.Body.Close()
  89. b.Total, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
  90. size := b.Total / numDownloadParts
  91. switch {
  92. case size < minDownloadPartSize:
  93. size = minDownloadPartSize
  94. case size > maxDownloadPartSize:
  95. size = maxDownloadPartSize
  96. }
  97. var offset int64
  98. for offset < b.Total {
  99. if offset+size > b.Total {
  100. size = b.Total - offset
  101. }
  102. if err := b.newPart(offset, size); err != nil {
  103. return err
  104. }
  105. offset += size
  106. }
  107. }
  108. slog.Info(fmt.Sprintf("downloading %s in %d %s part(s)", b.Digest[7:19], len(b.Parts), format.HumanBytes(b.Parts[0].Size)))
  109. return nil
  110. }
  111. func (b *blobDownload) Run(ctx context.Context, requestURL *url.URL, opts *registryOptions) {
  112. b.err = b.run(ctx, requestURL, opts)
  113. }
  114. func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *registryOptions) error {
  115. defer blobDownloadManager.Delete(b.Digest)
  116. ctx, b.CancelFunc = context.WithCancel(ctx)
  117. file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0o644)
  118. if err != nil {
  119. return err
  120. }
  121. defer file.Close()
  122. _ = file.Truncate(b.Total)
  123. g, inner := errgroup.WithContext(ctx)
  124. g.SetLimit(numDownloadParts)
  125. for i := range b.Parts {
  126. part := b.Parts[i]
  127. if part.Completed == part.Size {
  128. continue
  129. }
  130. g.Go(func() error {
  131. var err error
  132. for try := 0; try < maxRetries; try++ {
  133. w := io.NewOffsetWriter(file, part.StartsAt())
  134. err = b.downloadChunk(inner, requestURL, w, part, opts)
  135. switch {
  136. case errors.Is(err, context.Canceled), errors.Is(err, syscall.ENOSPC):
  137. // return immediately if the context is canceled or the device is out of space
  138. return err
  139. case errors.Is(err, errPartStalled):
  140. try--
  141. continue
  142. case err != nil:
  143. sleep := time.Second * time.Duration(math.Pow(2, float64(try)))
  144. slog.Info(fmt.Sprintf("%s part %d attempt %d failed: %v, retrying in %s", b.Digest[7:19], part.N, try, err, sleep))
  145. time.Sleep(sleep)
  146. continue
  147. default:
  148. return nil
  149. }
  150. }
  151. return fmt.Errorf("%w: %w", errMaxRetriesExceeded, err)
  152. })
  153. }
  154. if err := g.Wait(); err != nil {
  155. return err
  156. }
  157. // explicitly close the file so we can rename it
  158. if err := file.Close(); err != nil {
  159. return err
  160. }
  161. for i := range b.Parts {
  162. if err := os.Remove(file.Name() + "-" + strconv.Itoa(i)); err != nil {
  163. return err
  164. }
  165. }
  166. if err := os.Rename(file.Name(), b.Name); err != nil {
  167. return err
  168. }
  169. b.done = true
  170. return nil
  171. }
  172. func (b *blobDownload) downloadChunk(ctx context.Context, requestURL *url.URL, w io.Writer, part *blobDownloadPart, opts *registryOptions) error {
  173. g, ctx := errgroup.WithContext(ctx)
  174. g.Go(func() error {
  175. headers := make(http.Header)
  176. headers.Set("Range", fmt.Sprintf("bytes=%d-%d", part.StartsAt(), part.StopsAt()-1))
  177. resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, headers, nil, opts)
  178. if err != nil {
  179. return err
  180. }
  181. defer resp.Body.Close()
  182. n, err := io.CopyN(w, io.TeeReader(resp.Body, part), part.Size-part.Completed)
  183. if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.ErrUnexpectedEOF) {
  184. // rollback progress
  185. b.Completed.Add(-n)
  186. return err
  187. }
  188. part.Completed += n
  189. if err := b.writePart(part.Name(), part); err != nil {
  190. return err
  191. }
  192. // return nil or context.Canceled or UnexpectedEOF (resumable)
  193. return err
  194. })
  195. g.Go(func() error {
  196. ticker := time.NewTicker(time.Second)
  197. for {
  198. select {
  199. case <-ticker.C:
  200. if part.Completed >= part.Size {
  201. return nil
  202. }
  203. if !part.lastUpdated.IsZero() && time.Since(part.lastUpdated) > 5*time.Second {
  204. const msg = "%s part %d stalled; retrying. If this persists, press ctrl-c to exit, then 'ollama pull' to find a faster connection."
  205. slog.Info(fmt.Sprintf(msg, b.Digest[7:19], part.N))
  206. // reset last updated
  207. part.lastUpdated = time.Time{}
  208. return errPartStalled
  209. }
  210. case <-ctx.Done():
  211. return ctx.Err()
  212. }
  213. }
  214. })
  215. return g.Wait()
  216. }
  217. func (b *blobDownload) newPart(offset, size int64) error {
  218. part := blobDownloadPart{blobDownload: b, Offset: offset, Size: size, N: len(b.Parts)}
  219. if err := b.writePart(part.Name(), &part); err != nil {
  220. return err
  221. }
  222. b.Parts = append(b.Parts, &part)
  223. return nil
  224. }
  225. func (b *blobDownload) readPart(partName string) (*blobDownloadPart, error) {
  226. var part blobDownloadPart
  227. partFile, err := os.Open(partName)
  228. if err != nil {
  229. return nil, err
  230. }
  231. defer partFile.Close()
  232. if err := json.NewDecoder(partFile).Decode(&part); err != nil {
  233. return nil, err
  234. }
  235. part.blobDownload = b
  236. return &part, nil
  237. }
  238. func (b *blobDownload) writePart(partName string, part *blobDownloadPart) error {
  239. partFile, err := os.OpenFile(partName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o644)
  240. if err != nil {
  241. return err
  242. }
  243. defer partFile.Close()
  244. return json.NewEncoder(partFile).Encode(part)
  245. }
  246. func (b *blobDownload) acquire() {
  247. b.references.Add(1)
  248. }
  249. func (b *blobDownload) release() {
  250. if b.references.Add(-1) == 0 {
  251. b.CancelFunc()
  252. }
  253. }
  254. func (b *blobDownload) Wait(ctx context.Context, fn func(api.ProgressResponse)) error {
  255. b.acquire()
  256. defer b.release()
  257. ticker := time.NewTicker(60 * time.Millisecond)
  258. for {
  259. select {
  260. case <-ticker.C:
  261. fn(api.ProgressResponse{
  262. Status: fmt.Sprintf("pulling %s", b.Digest[7:19]),
  263. Digest: b.Digest,
  264. Total: b.Total,
  265. Completed: b.Completed.Load(),
  266. })
  267. if b.done || b.err != nil {
  268. return b.err
  269. }
  270. case <-ctx.Done():
  271. return ctx.Err()
  272. }
  273. }
  274. }
  275. type downloadOpts struct {
  276. mp ModelPath
  277. digest string
  278. regOpts *registryOptions
  279. fn func(api.ProgressResponse)
  280. }
  281. // downloadBlob downloads a blob from the registry and stores it in the blobs directory
  282. func downloadBlob(ctx context.Context, opts downloadOpts) (cacheHit bool, _ error) {
  283. fp, err := GetBlobsPath(opts.digest)
  284. if err != nil {
  285. return false, err
  286. }
  287. fi, err := os.Stat(fp)
  288. switch {
  289. case errors.Is(err, os.ErrNotExist):
  290. case err != nil:
  291. return false, err
  292. default:
  293. opts.fn(api.ProgressResponse{
  294. Status: fmt.Sprintf("pulling %s", opts.digest[7:19]),
  295. Digest: opts.digest,
  296. Total: fi.Size(),
  297. Completed: fi.Size(),
  298. })
  299. return true, nil
  300. }
  301. data, ok := blobDownloadManager.LoadOrStore(opts.digest, &blobDownload{Name: fp, Digest: opts.digest})
  302. download := data.(*blobDownload)
  303. if !ok {
  304. requestURL := opts.mp.BaseURL()
  305. requestURL = requestURL.JoinPath("v2", opts.mp.GetNamespaceRepository(), "blobs", opts.digest)
  306. if err := download.Prepare(ctx, requestURL, opts.regOpts); err != nil {
  307. blobDownloadManager.Delete(opts.digest)
  308. return false, err
  309. }
  310. //nolint:contextcheck
  311. go download.Run(context.Background(), requestURL, opts.regOpts)
  312. }
  313. return false, download.Wait(ctx, opts.fn)
  314. }