ollama/server/download.go

348 lines
7.6 KiB
Go
Raw Normal View History

package server
import (
"context"
2023-09-27 23:22:30 +00:00
"encoding/json"
"errors"
"fmt"
"io"
"log"
2023-11-19 00:25:22 +00:00
"math"
"net/http"
2023-09-27 23:22:30 +00:00
"net/url"
"os"
2023-09-19 16:36:30 +00:00
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
2023-09-27 23:22:30 +00:00
"golang.org/x/sync/errgroup"
"github.com/jmorganca/ollama/api"
"github.com/jmorganca/ollama/format"
)
var blobDownloadManager sync.Map
type blobDownload struct {
Name string
Digest string
2023-08-15 18:07:19 +00:00
Total int64
Completed atomic.Int64
2023-08-15 18:07:19 +00:00
Parts []*blobDownloadPart
context.CancelFunc
2023-10-11 20:49:01 +00:00
done bool
err error
2023-10-03 23:44:35 +00:00
references atomic.Int32
}
type blobDownloadPart struct {
N int
Offset int64
Size int64
Completed int64
*blobDownload `json:"-"`
}
const (
numDownloadParts = 64
2023-11-17 21:17:55 +00:00
minDownloadPartSize int64 = 100 * format.MegaByte
maxDownloadPartSize int64 = 1000 * format.MegaByte
)
func (p *blobDownloadPart) Name() string {
return strings.Join([]string{
p.blobDownload.Name, "partial", strconv.Itoa(p.N),
}, "-")
}
2023-10-03 23:52:49 +00:00
func (p *blobDownloadPart) StartsAt() int64 {
return p.Offset + p.Completed
}
func (p *blobDownloadPart) StopsAt() int64 {
return p.Offset + p.Size
}
func (b *blobDownload) Prepare(ctx context.Context, requestURL *url.URL, opts *RegistryOptions) error {
partFilePaths, err := filepath.Glob(b.Name + "-partial-*")
2023-09-27 23:22:30 +00:00
if err != nil {
2023-08-15 18:07:19 +00:00
return err
}
2023-09-27 23:22:30 +00:00
for _, partFilePath := range partFilePaths {
part, err := b.readPart(partFilePath)
2023-08-01 19:34:52 +00:00
if err != nil {
return err
}
b.Total += part.Size
b.Completed.Add(part.Completed)
b.Parts = append(b.Parts, part)
2023-09-27 23:22:30 +00:00
}
if len(b.Parts) == 0 {
2023-11-02 20:13:32 +00:00
resp, err := makeRequestWithRetry(ctx, http.MethodHead, requestURL, nil, nil, opts)
if err != nil {
2023-09-27 23:22:30 +00:00
return err
}
defer resp.Body.Close()
b.Total, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
2023-09-27 23:22:30 +00:00
var size = b.Total / numDownloadParts
switch {
case size < minDownloadPartSize:
size = minDownloadPartSize
case size > maxDownloadPartSize:
size = maxDownloadPartSize
}
2023-09-27 23:22:30 +00:00
var offset int64
for offset < b.Total {
if offset+size > b.Total {
size = b.Total - offset
}
if err := b.newPart(offset, size); err != nil {
return err
2023-09-27 23:22:30 +00:00
}
offset += size
}
}
log.Printf("downloading %s in %d %s part(s)", b.Digest[7:19], len(b.Parts), format.HumanBytes(b.Parts[0].Size))
return nil
}
2023-10-11 20:49:01 +00:00
func (b *blobDownload) Run(ctx context.Context, requestURL *url.URL, opts *RegistryOptions) {
b.err = b.run(ctx, requestURL, opts)
}
func (b *blobDownload) run(ctx context.Context, requestURL *url.URL, opts *RegistryOptions) error {
defer blobDownloadManager.Delete(b.Digest)
ctx, b.CancelFunc = context.WithCancel(ctx)
2023-10-03 23:52:49 +00:00
file, err := os.OpenFile(b.Name+"-partial", os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return err
2023-09-27 23:22:30 +00:00
}
2023-10-03 23:52:49 +00:00
defer file.Close()
2023-10-03 23:52:49 +00:00
file.Truncate(b.Total)
2023-10-02 20:34:07 +00:00
2023-10-12 19:52:35 +00:00
g, inner := errgroup.WithContext(ctx)
g.SetLimit(numDownloadParts)
for i := range b.Parts {
part := b.Parts[i]
2023-09-27 23:22:30 +00:00
if part.Completed == part.Size {
continue
}
2023-09-27 23:22:30 +00:00
g.Go(func() error {
2023-11-03 23:49:51 +00:00
var err error
2023-09-27 23:22:30 +00:00
for try := 0; try < maxRetries; try++ {
2023-10-03 23:52:49 +00:00
w := io.NewOffsetWriter(file, part.StartsAt())
2023-11-03 23:49:51 +00:00
err = b.downloadChunk(inner, requestURL, w, part, opts)
switch {
case errors.Is(err, context.Canceled), errors.Is(err, syscall.ENOSPC):
// return immediately if the context is canceled or the device is out of space
return err
case err != nil:
2023-11-19 00:25:22 +00:00
sleep := time.Second * time.Duration(math.Pow(2, float64(try)))
log.Printf("%s part %d attempt %d failed: %v, retrying in %s", b.Digest[7:19], part.N, try, err, sleep)
2023-11-17 21:17:55 +00:00
time.Sleep(sleep)
2023-09-27 23:22:30 +00:00
continue
default:
return nil
2023-09-27 23:22:30 +00:00
}
}
2023-11-03 23:49:51 +00:00
return fmt.Errorf("%w: %w", errMaxRetriesExceeded, err)
2023-09-27 23:22:30 +00:00
})
}
2023-09-27 23:22:30 +00:00
if err := g.Wait(); err != nil {
return err
}
2023-10-03 23:52:49 +00:00
// explicitly close the file so we can rename it
if err := file.Close(); err != nil {
2023-09-27 23:22:30 +00:00
return err
}
for i := range b.Parts {
2023-10-03 23:52:49 +00:00
if err := os.Remove(file.Name() + "-" + strconv.Itoa(i)); err != nil {
2023-09-27 23:22:30 +00:00
return err
}
}
2023-10-09 17:14:49 +00:00
if err := os.Rename(file.Name(), b.Name); err != nil {
return err
}
b.done = true
return nil
}
2023-10-03 23:52:49 +00:00
func (b *blobDownload) downloadChunk(ctx context.Context, requestURL *url.URL, w io.Writer, part *blobDownloadPart, opts *RegistryOptions) error {
2023-09-27 23:22:30 +00:00
headers := make(http.Header)
2023-10-03 23:52:49 +00:00
headers.Set("Range", fmt.Sprintf("bytes=%d-%d", part.StartsAt(), part.StopsAt()-1))
2023-11-02 20:13:32 +00:00
resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, headers, nil, opts)
2023-09-27 23:22:30 +00:00
if err != nil {
return err
}
defer resp.Body.Close()
n, err := io.Copy(w, io.TeeReader(resp.Body, b))
if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.ErrUnexpectedEOF) {
// rollback progress
b.Completed.Add(-n)
2023-09-27 23:22:30 +00:00
return err
}
2023-09-27 23:22:30 +00:00
part.Completed += n
if err := b.writePart(part.Name(), part); err != nil {
2023-10-02 20:34:07 +00:00
return err
}
// return nil or context.Canceled or UnexpectedEOF (resumable)
2023-10-02 20:34:07 +00:00
return err
}
func (b *blobDownload) newPart(offset, size int64) error {
part := blobDownloadPart{blobDownload: b, Offset: offset, Size: size, N: len(b.Parts)}
if err := b.writePart(part.Name(), &part); err != nil {
return err
}
b.Parts = append(b.Parts, &part)
return nil
}
func (b *blobDownload) readPart(partName string) (*blobDownloadPart, error) {
var part blobDownloadPart
partFile, err := os.Open(partName)
if err != nil {
return nil, err
}
defer partFile.Close()
if err := json.NewDecoder(partFile).Decode(&part); err != nil {
return nil, err
}
part.blobDownload = b
return &part, nil
2023-09-27 23:22:30 +00:00
}
func (b *blobDownload) writePart(partName string, part *blobDownloadPart) error {
partFile, err := os.OpenFile(partName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
2023-09-27 23:22:30 +00:00
if err != nil {
return err
}
2023-09-27 23:22:30 +00:00
defer partFile.Close()
2023-09-27 23:22:30 +00:00
return json.NewEncoder(partFile).Encode(part)
}
func (b *blobDownload) Write(p []byte) (n int, err error) {
n = len(p)
b.Completed.Add(int64(n))
return n, nil
}
2023-10-03 23:44:35 +00:00
func (b *blobDownload) acquire() {
b.references.Add(1)
}
func (b *blobDownload) release() {
if b.references.Add(-1) == 0 {
b.CancelFunc()
}
}
func (b *blobDownload) Wait(ctx context.Context, fn func(api.ProgressResponse)) error {
2023-10-03 23:44:35 +00:00
b.acquire()
defer b.release()
ticker := time.NewTicker(60 * time.Millisecond)
for {
select {
case <-ticker.C:
case <-ctx.Done():
return ctx.Err()
}
fn(api.ProgressResponse{
2023-11-19 14:20:22 +00:00
Status: fmt.Sprintf("pulling %s", b.Digest[7:19]),
Digest: b.Digest,
Total: b.Total,
Completed: b.Completed.Load(),
})
2023-10-11 20:49:01 +00:00
if b.done || b.err != nil {
return b.err
}
}
}
type downloadOpts struct {
mp ModelPath
digest string
regOpts *RegistryOptions
fn func(api.ProgressResponse)
}
2023-11-19 00:25:22 +00:00
const maxRetries = 6
2023-10-09 17:24:27 +00:00
var errMaxRetriesExceeded = errors.New("max retries exceeded")
// downloadBlob downloads a blob from the registry and stores it in the blobs directory
func downloadBlob(ctx context.Context, opts downloadOpts) error {
fp, err := GetBlobsPath(opts.digest)
if err != nil {
return err
}
fi, err := os.Stat(fp)
switch {
case errors.Is(err, os.ErrNotExist):
case err != nil:
return err
default:
opts.fn(api.ProgressResponse{
2023-11-19 14:20:22 +00:00
Status: fmt.Sprintf("pulling %s", opts.digest[7:19]),
Digest: opts.digest,
Total: fi.Size(),
Completed: fi.Size(),
})
return nil
}
2023-10-04 00:06:13 +00:00
data, ok := blobDownloadManager.LoadOrStore(opts.digest, &blobDownload{Name: fp, Digest: opts.digest})
download := data.(*blobDownload)
if !ok {
requestURL := opts.mp.BaseURL()
requestURL = requestURL.JoinPath("v2", opts.mp.GetNamespaceRepository(), "blobs", opts.digest)
2023-10-04 00:06:13 +00:00
if err := download.Prepare(ctx, requestURL, opts.regOpts); err != nil {
2023-10-10 17:12:29 +00:00
blobDownloadManager.Delete(opts.digest)
return err
}
2023-10-04 00:06:13 +00:00
go download.Run(context.Background(), requestURL, opts.regOpts)
}
2023-10-04 00:06:13 +00:00
return download.Wait(ctx, opts.fn)
}