images.go 20.6 KB
Newer Older
1
2
3
4
package server

import (
	"bytes"
5
	"context"
6
	"crypto/sha256"
Patrick Devine's avatar
Patrick Devine committed
7
	"encoding/hex"
8
9
10
11
12
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
13
	"log/slog"
14
	"net"
15
	"net/http"
Michael Yang's avatar
Michael Yang committed
16
	"net/url"
17
18
	"os"
	"path/filepath"
Michael Yang's avatar
Michael Yang committed
19
	"runtime"
20
	"slices"
Michael Yang's avatar
Michael Yang committed
21
	"strconv"
22
23
	"strings"

24
	"github.com/ollama/ollama/api"
Michael Yang's avatar
Michael Yang committed
25
	"github.com/ollama/ollama/envconfig"
Michael Yang's avatar
Michael Yang committed
26
	"github.com/ollama/ollama/fs/ggml"
27
	"github.com/ollama/ollama/parser"
Michael Yang's avatar
Michael Yang committed
28
	"github.com/ollama/ollama/template"
Michael Yang's avatar
Michael Yang committed
29
	"github.com/ollama/ollama/types/model"
30
	"github.com/ollama/ollama/version"
31
32
)

33
34
35
36
37
var (
	errCapabilities         = errors.New("does not support")
	errCapabilityCompletion = errors.New("completion")
	errCapabilityTools      = errors.New("tools")
	errCapabilityInsert     = errors.New("insert")
38
39
	errCapabilityVision     = errors.New("vision")
	errCapabilityEmbedding  = errors.New("embedding")
CYJiang's avatar
CYJiang committed
40
	errInsecureProtocol     = errors.New("insecure protocol http")
41
)
Michael Yang's avatar
Michael Yang committed
42

Michael Yang's avatar
Michael Yang committed
43
44
45
46
47
type registryOptions struct {
	Insecure bool
	Username string
	Password string
	Token    string
48
49

	CheckRedirect func(req *http.Request, via []*http.Request) error
Michael Yang's avatar
Michael Yang committed
50
51
}

52
type Model struct {
Michael Yang's avatar
Michael Yang committed
53
	Name           string `json:"name"`
54
	Config         ConfigV2
Michael Yang's avatar
Michael Yang committed
55
56
	ShortName      string
	ModelPath      string
57
	ParentModel    string
Michael Yang's avatar
Michael Yang committed
58
59
60
61
62
63
	AdapterPaths   []string
	ProjectorPaths []string
	System         string
	License        []string
	Digest         string
	Options        map[string]interface{}
Michael Yang's avatar
Michael Yang committed
64
	Messages       []api.Message
Michael Yang's avatar
Michael Yang committed
65
66

	Template *template.Template
67
68
}

69
70
71
// Capabilities returns the capabilities that the model supports
func (m *Model) Capabilities() []model.Capability {
	capabilities := []model.Capability{}
72

73
74
75
76
	// Check for completion capability
	r, err := os.Open(m.ModelPath)
	if err == nil {
		defer r.Close()
77

78
79
		f, _, err := ggml.Decode(r, 0)
		if err == nil {
Michael Yang's avatar
Michael Yang committed
80
			if _, ok := f.KV()[fmt.Sprintf("%s.pooling_type", f.KV().Architecture())]; ok {
81
82
83
				capabilities = append(capabilities, model.CapabilityEmbedding)
			} else {
				capabilities = append(capabilities, model.CapabilityCompletion)
84
			}
85
86
			if _, ok := f.KV()[fmt.Sprintf("%s.vision.block_count", f.KV().Architecture())]; ok {
				capabilities = append(capabilities, model.CapabilityVision)
Michael Yang's avatar
tools  
Michael Yang committed
87
			}
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
		} else {
			slog.Error("couldn't decode ggml", "error", err)
		}
	} else {
		slog.Error("couldn't open model file", "error", err)
	}

	if m.Template == nil {
		return capabilities
	}

	// Check for tools capability
	if slices.Contains(m.Template.Vars(), "tools") {
		capabilities = append(capabilities, model.CapabilityTools)
	}

	// Check for insert capability
	if slices.Contains(m.Template.Vars(), "suffix") {
		capabilities = append(capabilities, model.CapabilityInsert)
	}

	return capabilities
}

// CheckCapabilities checks if the model has the specified capabilities returning an error describing
// any missing or unknown capabilities
func (m *Model) CheckCapabilities(want ...model.Capability) error {
	available := m.Capabilities()
	var errs []error

	// Map capabilities to their corresponding error
	capToErr := map[model.Capability]error{
		model.CapabilityCompletion: errCapabilityCompletion,
		model.CapabilityTools:      errCapabilityTools,
		model.CapabilityInsert:     errCapabilityInsert,
		model.CapabilityVision:     errCapabilityVision,
		model.CapabilityEmbedding:  errCapabilityEmbedding,
	}

	for _, cap := range want {
		err, ok := capToErr[cap]
		if !ok {
Michael Yang's avatar
Michael Yang committed
130
			slog.Error("unknown capability", "capability", cap)
Michael Yang's avatar
Michael Yang committed
131
			return fmt.Errorf("unknown capability: %s", cap)
Michael Yang's avatar
Michael Yang committed
132
		}
133
134
135
136

		if !slices.Contains(available, cap) {
			errs = append(errs, err)
		}
Michael Yang's avatar
Michael Yang committed
137
138
	}

139
	if len(errs) > 0 {
140
		return fmt.Errorf("%w %w", errCapabilities, errors.Join(errs...))
Michael Yang's avatar
Michael Yang committed
141
142
143
	}

	return nil
144
145
}

Michael Yang's avatar
Michael Yang committed
146
func (m *Model) String() string {
147
	var modelfile parser.Modelfile
Michael Yang's avatar
Michael Yang committed
148

149
	modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
150
151
152
		Name: "model",
		Args: m.ModelPath,
	})
153

Michael Yang's avatar
Michael Yang committed
154
	for _, adapter := range m.AdapterPaths {
155
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
156
157
			Name: "adapter",
			Args: adapter,
Michael Yang's avatar
Michael Yang committed
158
		})
159
160
	}

Michael Yang's avatar
Michael Yang committed
161
	for _, projector := range m.ProjectorPaths {
162
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
163
164
			Name: "model",
			Args: projector,
Michael Yang's avatar
Michael Yang committed
165
		})
166
167
	}

Michael Yang's avatar
Michael Yang committed
168
	if m.Template != nil {
169
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
170
			Name: "template",
Michael Yang's avatar
Michael Yang committed
171
			Args: m.Template.String(),
Michael Yang's avatar
Michael Yang committed
172
		})
173
174
	}

Michael Yang's avatar
Michael Yang committed
175
	if m.System != "" {
176
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
177
178
			Name: "system",
			Args: m.System,
Michael Yang's avatar
Michael Yang committed
179
		})
180
181
182
183
184
185
	}

	for k, v := range m.Options {
		switch v := v.(type) {
		case []any:
			for _, s := range v {
186
				modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
187
188
189
					Name: k,
					Args: fmt.Sprintf("%v", s),
				})
190
191
			}
		default:
192
			modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
193
194
195
				Name: k,
				Args: fmt.Sprintf("%v", v),
			})
196
197
198
199
		}
	}

	for _, license := range m.License {
200
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
201
202
203
			Name: "license",
			Args: license,
		})
204
205
206
	}

	for _, msg := range m.Messages {
207
		modelfile.Commands = append(modelfile.Commands, parser.Command{
Michael Yang's avatar
Michael Yang committed
208
			Name: "message",
Michael Yang's avatar
Michael Yang committed
209
			Args: fmt.Sprintf("%s: %s", msg.Role, msg.Content),
Michael Yang's avatar
Michael Yang committed
210
		})
211
212
	}

Michael Yang's avatar
Michael Yang committed
213
	return modelfile.String()
214
215
}

216
type ConfigV2 struct {
217
218
219
220
221
222
	ModelFormat   string   `json:"model_format"`
	ModelFamily   string   `json:"model_family"`
	ModelFamilies []string `json:"model_families"`
	ModelType     string   `json:"model_type"`
	FileType      string   `json:"file_type"`

223
	// required by spec
224
225
	Architecture string `json:"architecture"`
	OS           string `json:"os"`
226
	RootFS       RootFS `json:"rootfs"`
227
228
229
230
231
232
233
}

type RootFS struct {
	Type    string   `json:"type"`
	DiffIDs []string `json:"diff_ids"`
}

Michael Yang's avatar
Michael Yang committed
234
func GetManifest(mp ModelPath) (*Manifest, string, error) {
235
	fp, err := mp.GetManifestPath()
236
	if err != nil {
Patrick Devine's avatar
Patrick Devine committed
237
		return nil, "", err
238
	}
239

Michael Yang's avatar
Michael Yang committed
240
	f, err := os.Open(fp)
241
	if err != nil {
Michael Yang's avatar
Michael Yang committed
242
		return nil, "", err
243
	}
Michael Yang's avatar
Michael Yang committed
244
	defer f.Close()
245

Michael Yang's avatar
Michael Yang committed
246
	sha256sum := sha256.New()
Patrick Devine's avatar
Patrick Devine committed
247

Michael Yang's avatar
Michael Yang committed
248
249
	var manifest Manifest
	if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&manifest); err != nil {
Patrick Devine's avatar
Patrick Devine committed
250
		return nil, "", err
251
252
	}

Michael Yang's avatar
Michael Yang committed
253
	return &manifest, hex.EncodeToString(sha256sum.Sum(nil)), nil
254
255
256
}

func GetModel(name string) (*Model, error) {
257
	mp := ParseModelPath(name)
Patrick Devine's avatar
Patrick Devine committed
258
	manifest, digest, err := GetManifest(mp)
259
260
261
262
263
	if err != nil {
		return nil, err
	}

	model := &Model{
264
265
266
		Name:      mp.GetFullTagname(),
		ShortName: mp.GetShortTagname(),
		Digest:    digest,
Michael Yang's avatar
Michael Yang committed
267
		Template:  template.DefaultTemplate,
268
269
	}

270
271
272
273
274
	if manifest.Config.Digest != "" {
		filename, err := GetBlobsPath(manifest.Config.Digest)
		if err != nil {
			return nil, err
		}
275

276
277
278
279
280
		configFile, err := os.Open(filename)
		if err != nil {
			return nil, err
		}
		defer configFile.Close()
281

282
283
284
		if err := json.NewDecoder(configFile).Decode(&model.Config); err != nil {
			return nil, err
		}
285
286
	}

287
	for _, layer := range manifest.Layers {
Patrick Devine's avatar
Patrick Devine committed
288
		filename, err := GetBlobsPath(layer.Digest)
289
290
291
292
		if err != nil {
			return nil, err
		}

293
294
295
		switch layer.MediaType {
		case "application/vnd.ollama.image.model":
			model.ModelPath = filename
296
			model.ParentModel = layer.From
297
		case "application/vnd.ollama.image.embed":
298
299
			// Deprecated in versions  > 0.1.2
			// TODO: remove this warning in a future version
300
			slog.Info("WARNING: model contains embeddings, but embeddings in modelfiles have been deprecated and will be ignored.")
301
302
		case "application/vnd.ollama.image.adapter":
			model.AdapterPaths = append(model.AdapterPaths, filename)
Michael Yang's avatar
Michael Yang committed
303
304
		case "application/vnd.ollama.image.projector":
			model.ProjectorPaths = append(model.ProjectorPaths, filename)
Michael Yang's avatar
Michael Yang committed
305
306
		case "application/vnd.ollama.image.prompt",
			"application/vnd.ollama.image.template":
307
308
309
310
311
			bts, err := os.ReadFile(filename)
			if err != nil {
				return nil, err
			}

Michael Yang's avatar
Michael Yang committed
312
			model.Template, err = template.Parse(string(bts))
313
314
315
			if err != nil {
				return nil, err
			}
Michael Yang's avatar
Michael Yang committed
316
		case "application/vnd.ollama.image.system":
317
318
319
320
321
			bts, err := os.ReadFile(filename)
			if err != nil {
				return nil, err
			}

Michael Yang's avatar
Michael Yang committed
322
			model.System = string(bts)
323
		case "application/vnd.ollama.image.params":
Michael Yang's avatar
Michael Yang committed
324
325
326
327
328
			params, err := os.Open(filename)
			if err != nil {
				return nil, err
			}
			defer params.Close()
329

330
			// parse model options parameters into a map so that we can see which fields have been specified explicitly
331
			if err = json.NewDecoder(params).Decode(&model.Options); err != nil {
332
333
				return nil, err
			}
334
335
336
337
338
339
340
341
342
343
		case "application/vnd.ollama.image.messages":
			msgs, err := os.Open(filename)
			if err != nil {
				return nil, err
			}
			defer msgs.Close()

			if err = json.NewDecoder(msgs).Decode(&model.Messages); err != nil {
				return nil, err
			}
Patrick Devine's avatar
Patrick Devine committed
344
345
346
347
348
349
		case "application/vnd.ollama.image.license":
			bts, err := os.ReadFile(filename)
			if err != nil {
				return nil, err
			}
			model.License = append(model.License, string(bts))
350
351
352
353
354
355
		}
	}

	return model, nil
}

Michael Yang's avatar
Michael Yang committed
356
func CopyModel(src, dst model.Name) error {
357
358
359
360
361
362
363
	if !dst.IsFullyQualified() {
		return model.Unqualified(dst)
	}
	if !src.IsFullyQualified() {
		return model.Unqualified(src)
	}

364
365
366
367
	if src.Filepath() == dst.Filepath() {
		return nil
	}

Michael Yang's avatar
Michael Yang committed
368
	manifests, err := GetManifestPath()
369
370
371
372
	if err != nil {
		return err
	}

373
	dstpath := filepath.Join(manifests, dst.Filepath())
Michael Yang's avatar
Michael Yang committed
374
	if err := os.MkdirAll(filepath.Dir(dstpath), 0o755); err != nil {
375
376
		return err
	}
Patrick Devine's avatar
Patrick Devine committed
377

378
	srcpath := filepath.Join(manifests, src.Filepath())
Michael Yang's avatar
Michael Yang committed
379
	srcfile, err := os.Open(srcpath)
Patrick Devine's avatar
Patrick Devine committed
380
381
382
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
383
	defer srcfile.Close()
Patrick Devine's avatar
Patrick Devine committed
384

Michael Yang's avatar
Michael Yang committed
385
	dstfile, err := os.Create(dstpath)
Patrick Devine's avatar
Patrick Devine committed
386
387
388
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
389
	defer dstfile.Close()
Patrick Devine's avatar
Patrick Devine committed
390

Michael Yang's avatar
Michael Yang committed
391
392
	_, err = io.Copy(dstfile, srcfile)
	return err
Patrick Devine's avatar
Patrick Devine committed
393
394
}

Michael Yang's avatar
Michael Yang committed
395
func deleteUnusedLayers(deleteMap map[string]struct{}) error {
396
397
	// Ignore corrupt manifests to avoid blocking deletion of layers that are freshly orphaned
	manifests, err := Manifests(true)
398
399
400
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
401

Michael Yang's avatar
Michael Yang committed
402
	for _, manifest := range manifests {
Michael Yang's avatar
Michael Yang committed
403
404
405
406
407
		for _, layer := range manifest.Layers {
			delete(deleteMap, layer.Digest)
		}

		delete(deleteMap, manifest.Config.Digest)
Michael Yang's avatar
Michael Yang committed
408
	}
409
410

	// only delete the files which are still in the deleteMap
Michael Yang's avatar
Michael Yang committed
411
412
413
	for k := range deleteMap {
		fp, err := GetBlobsPath(k)
		if err != nil {
414
			slog.Info(fmt.Sprintf("couldn't get file path for '%s': %v", k, err))
Michael Yang's avatar
Michael Yang committed
415
416
			continue
		}
417
418
419
		if err := os.Remove(fp); err != nil {
			slog.Info(fmt.Sprintf("couldn't remove file '%s': %v", fp, err))
			continue
420
421
422
		}
	}

423
424
425
426
	return nil
}

func PruneLayers() error {
Michael Yang's avatar
Michael Yang committed
427
	deleteMap := make(map[string]struct{})
428
429
430
431
432
433
434
	p, err := GetBlobsPath("")
	if err != nil {
		return err
	}

	blobs, err := os.ReadDir(p)
	if err != nil {
435
		slog.Info(fmt.Sprintf("couldn't read dir '%s': %v", p, err))
436
437
438
439
440
		return err
	}

	for _, blob := range blobs {
		name := blob.Name()
441
		name = strings.ReplaceAll(name, "-", ":")
442
443
444
445
446
447
448
449
450
451
452

		_, err := GetBlobsPath(name)
		if err != nil {
			if errors.Is(err, ErrInvalidDigestFormat) {
				// remove invalid blobs (e.g. partial downloads)
				if err := os.Remove(filepath.Join(p, blob.Name())); err != nil {
					slog.Error("couldn't remove blob", "blob", blob.Name(), "error", err)
				}
			}

			continue
Michael Yang's avatar
Michael Yang committed
453
		}
454
455

		deleteMap[name] = struct{}{}
456
457
	}

458
	slog.Info(fmt.Sprintf("total blobs: %d", len(deleteMap)))
459

Michael Yang's avatar
Michael Yang committed
460
	if err := deleteUnusedLayers(deleteMap); err != nil {
461
		slog.Error(fmt.Sprintf("couldn't remove unused layers: %v", err))
462
		return nil
463
464
	}

465
	slog.Info(fmt.Sprintf("total unused blobs removed: %d", len(deleteMap)))
466
467
468
469

	return nil
}

Michael Yang's avatar
Michael Yang committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
func PruneDirectory(path string) error {
	info, err := os.Lstat(path)
	if err != nil {
		return err
	}

	if info.IsDir() && info.Mode()&os.ModeSymlink == 0 {
		entries, err := os.ReadDir(path)
		if err != nil {
			return err
		}

		for _, entry := range entries {
			if err := PruneDirectory(filepath.Join(path, entry.Name())); err != nil {
				return err
			}
		}

		entries, err = os.ReadDir(path)
		if err != nil {
			return err
		}

		if len(entries) > 0 {
			return nil
		}

		return os.Remove(path)
	}

	return nil
}

Michael Yang's avatar
Michael Yang committed
503
func PushModel(ctx context.Context, name string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
504
	mp := ParseModelPath(name)
505
506
	fn(api.ProgressResponse{Status: "retrieving manifest"})

507
	if mp.ProtocolScheme == "http" && !regOpts.Insecure {
CYJiang's avatar
CYJiang committed
508
		return errInsecureProtocol
509
510
	}

Patrick Devine's avatar
Patrick Devine committed
511
	manifest, _, err := GetManifest(mp)
512
	if err != nil {
513
		fn(api.ProgressResponse{Status: "couldn't retrieve manifest"})
514
515
516
		return err
	}

517
	var layers []Layer
Jeffrey Morgan's avatar
Jeffrey Morgan committed
518
	layers = append(layers, manifest.Layers...)
519
	if manifest.Config.Digest != "" {
520
		layers = append(layers, manifest.Config)
521
	}
522
523

	for _, layer := range layers {
Michael Yang's avatar
Michael Yang committed
524
		if err := uploadBlob(ctx, mp, layer, regOpts, fn); err != nil {
525
			slog.Info(fmt.Sprintf("error uploading blob: %v", err))
526
527
			return err
		}
528
529
	}

530
	fn(api.ProgressResponse{Status: "pushing manifest"})
Michael Yang's avatar
Michael Yang committed
531
532
	requestURL := mp.BaseURL()
	requestURL = requestURL.JoinPath("v2", mp.GetNamespaceRepository(), "manifests", mp.Tag)
533
534
535
536
537
538

	manifestJSON, err := json.Marshal(manifest)
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
539
540
	headers := make(http.Header)
	headers.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
Michael Yang's avatar
Michael Yang committed
541
	resp, err := makeRequestWithRetry(ctx, http.MethodPut, requestURL, headers, bytes.NewReader(manifestJSON), regOpts)
542
543
544
545
546
	if err != nil {
		return err
	}
	defer resp.Body.Close()

547
	fn(api.ProgressResponse{Status: "success"})
548
549
550
551

	return nil
}

Michael Yang's avatar
Michael Yang committed
552
func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
553
554
	mp := ParseModelPath(name)

555
	// build deleteMap to prune unused layers
Michael Yang's avatar
Michael Yang committed
556
	deleteMap := make(map[string]struct{})
Michael Yang's avatar
Michael Yang committed
557
558
559
	manifest, _, err := GetManifest(mp)
	if errors.Is(err, os.ErrNotExist) {
		// noop
560
561
	} else if err != nil {
		slog.Warn("pulling model with bad existing manifest", "name", name, "error", err)
Michael Yang's avatar
Michael Yang committed
562
563
564
	} else {
		for _, l := range manifest.Layers {
			deleteMap[l.Digest] = struct{}{}
565
		}
Michael Yang's avatar
Michael Yang committed
566
567
		if manifest.Config.Digest != "" {
			deleteMap[manifest.Config.Digest] = struct{}{}
568
569
570
		}
	}

571
	if mp.ProtocolScheme == "http" && !regOpts.Insecure {
CYJiang's avatar
CYJiang committed
572
		return errInsecureProtocol
573
	}
574

575
	fn(api.ProgressResponse{Status: "pulling manifest"})
576

577
	manifest, err = pullModelManifest(ctx, mp, regOpts)
578
	if err != nil {
579
		return fmt.Errorf("pull model manifest: %s", err)
580
581
	}

582
	var layers []Layer
Bruce MacDonald's avatar
Bruce MacDonald committed
583
	layers = append(layers, manifest.Layers...)
584
	if manifest.Config.Digest != "" {
585
		layers = append(layers, manifest.Config)
586
	}
587

588
	skipVerify := make(map[string]bool)
589
	for _, layer := range layers {
590
591
592
593
594
595
596
		cacheHit, err := downloadBlob(ctx, downloadOpts{
			mp:      mp,
			digest:  layer.Digest,
			regOpts: regOpts,
			fn:      fn,
		})
		if err != nil {
597
598
			return err
		}
599
		skipVerify[layer.Digest] = cacheHit
600
		delete(deleteMap, layer.Digest)
601
	}
602
	delete(deleteMap, manifest.Config.Digest)
603

Michael Yang's avatar
Michael Yang committed
604
605
	fn(api.ProgressResponse{Status: "verifying sha256 digest"})
	for _, layer := range layers {
606
607
608
		if skipVerify[layer.Digest] {
			continue
		}
Michael Yang's avatar
Michael Yang committed
609
		if err := verifyBlob(layer.Digest); err != nil {
610
611
612
613
614
615
616
617
			if errors.Is(err, errDigestMismatch) {
				// something went wrong, delete the blob
				fp, err := GetBlobsPath(layer.Digest)
				if err != nil {
					return err
				}
				if err := os.Remove(fp); err != nil {
					// log this, but return the original error
618
					slog.Info(fmt.Sprintf("couldn't remove file with digest mismatch '%s': %v", fp, err))
619
620
				}
			}
Michael Yang's avatar
Michael Yang committed
621
622
623
624
			return err
		}
	}

625
	fn(api.ProgressResponse{Status: "writing manifest"})
626

627
	manifestJSON, err := json.Marshal(manifest)
628
629
630
631
	if err != nil {
		return err
	}

632
	fp, err := mp.GetManifestPath()
633
634
635
	if err != nil {
		return err
	}
636
637
638
	if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
		return err
	}
639

Bruce MacDonald's avatar
Bruce MacDonald committed
640
	err = os.WriteFile(fp, manifestJSON, 0o644)
641
	if err != nil {
642
		slog.Info(fmt.Sprintf("couldn't write to %s", fp))
643
644
645
		return err
	}

Michael Yang's avatar
Michael Yang committed
646
647
	if !envconfig.NoPrune() && len(deleteMap) > 0 {
		fn(api.ProgressResponse{Status: "removing unused layers"})
Michael Yang's avatar
Michael Yang committed
648
		if err := deleteUnusedLayers(deleteMap); err != nil {
649
			fn(api.ProgressResponse{Status: fmt.Sprintf("couldn't remove unused layers: %v", err)})
650
651
652
		}
	}

653
	fn(api.ProgressResponse{Status: "success"})
654
655
656
657

	return nil
}

Michael Yang's avatar
Michael Yang committed
658
func pullModelManifest(ctx context.Context, mp ModelPath, regOpts *registryOptions) (*Manifest, error) {
Michael Yang's avatar
Michael Yang committed
659
	requestURL := mp.BaseURL().JoinPath("v2", mp.GetNamespaceRepository(), "manifests", mp.Tag)
660

Michael Yang's avatar
Michael Yang committed
661
662
	headers := make(http.Header)
	headers.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
Michael Yang's avatar
Michael Yang committed
663
	resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, headers, nil, regOpts)
664
665
666
667
668
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

Michael Yang's avatar
Michael Yang committed
669
	var m Manifest
670
671
672
673
	if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
674
	return &m, err
675
676
677
}

// GetSHA256Digest returns the SHA256 hash of a given buffer and returns it, and the size of buffer
Michael Yang's avatar
Michael Yang committed
678
func GetSHA256Digest(r io.Reader) (string, int64) {
Michael Yang's avatar
Michael Yang committed
679
680
681
682
683
684
	h := sha256.New()
	n, err := io.Copy(h, r)
	if err != nil {
		log.Fatal(err)
	}

Michael Yang's avatar
Michael Yang committed
685
	return fmt.Sprintf("sha256:%x", h.Sum(nil)), n
686
687
}

Michael Yang's avatar
lint  
Michael Yang committed
688
var errUnauthorized = errors.New("unauthorized: access denied")
689

Michael Yang's avatar
Michael Yang committed
690
func makeRequestWithRetry(ctx context.Context, method string, requestURL *url.URL, headers http.Header, body io.ReadSeeker, regOpts *registryOptions) (*http.Response, error) {
Michael Yang's avatar
lint  
Michael Yang committed
691
	for range 2 {
Michael Yang's avatar
Michael Yang committed
692
		resp, err := makeRequest(ctx, method, requestURL, headers, body, regOpts)
Michael Yang's avatar
Michael Yang committed
693
		if err != nil {
Michael Yang's avatar
Michael Yang committed
694
			if !errors.Is(err, context.Canceled) {
695
				slog.Info(fmt.Sprintf("request failed: %v", err))
Michael Yang's avatar
Michael Yang committed
696
697
			}

Michael Yang's avatar
Michael Yang committed
698
699
			return nil, err
		}
Michael Yang's avatar
Michael Yang committed
700
701
702

		switch {
		case resp.StatusCode == http.StatusUnauthorized:
703
704
			resp.Body.Close()

Michael Yang's avatar
Michael Yang committed
705
			// Handle authentication error with one retry
Michael Yang's avatar
Michael Yang committed
706
707
			challenge := parseRegistryChallenge(resp.Header.Get("www-authenticate"))
			token, err := getAuthorizationToken(ctx, challenge)
Michael Yang's avatar
Michael Yang committed
708
709
710
			if err != nil {
				return nil, err
			}
Michael Yang's avatar
Michael Yang committed
711
712
713
714
715
716
717
718
			regOpts.Token = token
			if body != nil {
				_, err = body.Seek(0, io.SeekStart)
				if err != nil {
					return nil, err
				}
			}
		case resp.StatusCode == http.StatusNotFound:
719
			resp.Body.Close()
Michael Yang's avatar
Michael Yang committed
720
721
			return nil, os.ErrNotExist
		case resp.StatusCode >= http.StatusBadRequest:
722
			defer resp.Body.Close()
Michael Yang's avatar
Michael Yang committed
723
724
725
726
727
728
729
			responseBody, err := io.ReadAll(resp.Body)
			if err != nil {
				return nil, fmt.Errorf("%d: %s", resp.StatusCode, err)
			}
			return nil, fmt.Errorf("%d: %s", resp.StatusCode, responseBody)
		default:
			return resp, nil
Michael Yang's avatar
Michael Yang committed
730
731
732
		}
	}

Michael Yang's avatar
Michael Yang committed
733
	return nil, errUnauthorized
Michael Yang's avatar
Michael Yang committed
734
735
}

736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// testMakeRequestDialContext specifies the dial function for the http client in
// makeRequest. It can be used to resolve hosts in model names to local
// addresses for testing. For example, the model name ("example.com/my/model")
// can be directed to push/pull from "127.0.0.1:1234".
//
// This is not safe to set across goroutines. It should be set in
// the main test goroutine, and not by tests marked to run in parallel with
// t.Parallel().
//
// It should be cleared after use, otherwise it will affect other tests.
//
// Ideally we would have some set this up the stack, but the code is not
// structured in a way that makes this easy, so this will have to do for now.
var testMakeRequestDialContext func(ctx context.Context, network, addr string) (net.Conn, error)

Michael Yang's avatar
Michael Yang committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
func makeRequest(ctx context.Context, method string, requestURL *url.URL, headers http.Header, body io.Reader, regOpts *registryOptions) (*http.Response, error) {
	if requestURL.Scheme != "http" && regOpts != nil && regOpts.Insecure {
		requestURL.Scheme = "http"
	}

	req, err := http.NewRequestWithContext(ctx, method, requestURL.String(), body)
	if err != nil {
		return nil, err
	}

	if headers != nil {
		req.Header = headers
	}

	if regOpts != nil {
		if regOpts.Token != "" {
			req.Header.Set("Authorization", "Bearer "+regOpts.Token)
		} else if regOpts.Username != "" && regOpts.Password != "" {
			req.SetBasicAuth(regOpts.Username, regOpts.Password)
		}
	}

773
	req.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
Michael Yang's avatar
Michael Yang committed
774
775
776
777
778
779
780
781
782
783

	if s := req.Header.Get("Content-Length"); s != "" {
		contentLength, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			return nil, err
		}

		req.ContentLength = contentLength
	}

784
	c := &http.Client{
785
		CheckRedirect: regOpts.CheckRedirect,
Michael Yang's avatar
Michael Yang committed
786
	}
787
788
789
790
791
792
	if testMakeRequestDialContext != nil {
		tr := http.DefaultTransport.(*http.Transport).Clone()
		tr.DialContext = testMakeRequestDialContext
		c.Transport = tr
	}
	return c.Do(req)
Michael Yang's avatar
Michael Yang committed
793
794
}

Patrick Devine's avatar
Patrick Devine committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
func getValue(header, key string) string {
	startIdx := strings.Index(header, key+"=")
	if startIdx == -1 {
		return ""
	}

	// Move the index to the starting quote after the key.
	startIdx += len(key) + 2
	endIdx := startIdx

	for endIdx < len(header) {
		if header[endIdx] == '"' {
			if endIdx+1 < len(header) && header[endIdx+1] != ',' { // If the next character isn't a comma, continue
				endIdx++
				continue
			}
			break
		}
		endIdx++
	}
	return header[startIdx:endIdx]
}

Michael Yang's avatar
Michael Yang committed
818
func parseRegistryChallenge(authStr string) registryChallenge {
Patrick Devine's avatar
Patrick Devine committed
819
820
	authStr = strings.TrimPrefix(authStr, "Bearer ")

Michael Yang's avatar
Michael Yang committed
821
	return registryChallenge{
Patrick Devine's avatar
Patrick Devine committed
822
823
824
825
826
827
		Realm:   getValue(authStr, "realm"),
		Service: getValue(authStr, "service"),
		Scope:   getValue(authStr, "scope"),
	}
}

828
var errDigestMismatch = errors.New("digest mismatch, file must be downloaded again")
829

Michael Yang's avatar
Michael Yang committed
830
831
832
833
834
835
836
837
838
839
840
841
842
843
func verifyBlob(digest string) error {
	fp, err := GetBlobsPath(digest)
	if err != nil {
		return err
	}

	f, err := os.Open(fp)
	if err != nil {
		return err
	}
	defer f.Close()

	fileDigest, _ := GetSHA256Digest(f)
	if digest != fileDigest {
844
		return fmt.Errorf("%w: want %s, got %s", errDigestMismatch, digest, fileDigest)
Michael Yang's avatar
Michael Yang committed
845
846
847
848
	}

	return nil
}