images.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. package server
  2. import (
  3. "bytes"
  4. "cmp"
  5. "context"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log"
  14. "log/slog"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "path/filepath"
  19. "runtime"
  20. "slices"
  21. "strconv"
  22. "strings"
  23. "github.com/ollama/ollama/api"
  24. "github.com/ollama/ollama/auth"
  25. "github.com/ollama/ollama/envconfig"
  26. "github.com/ollama/ollama/format"
  27. "github.com/ollama/ollama/llm"
  28. "github.com/ollama/ollama/parser"
  29. "github.com/ollama/ollama/template"
  30. "github.com/ollama/ollama/types/errtypes"
  31. "github.com/ollama/ollama/types/model"
  32. "github.com/ollama/ollama/version"
  33. )
  34. var errCapabilityCompletion = errors.New("completion")
  35. type Capability string
  36. const CapabilityCompletion = Capability("completion")
  37. type registryOptions struct {
  38. Insecure bool
  39. Username string
  40. Password string
  41. Token string
  42. }
  43. type Model struct {
  44. Name string `json:"name"`
  45. Config ConfigV2
  46. ShortName string
  47. ModelPath string
  48. ParentModel string
  49. AdapterPaths []string
  50. ProjectorPaths []string
  51. System string
  52. License []string
  53. Digest string
  54. Options map[string]interface{}
  55. Messages []Message
  56. Template *template.Template
  57. }
  58. // CheckCapabilities checks if the model has the specified capabilities returning an error describing
  59. // any missing or unknown capabilities
  60. func (m *Model) CheckCapabilities(caps ...Capability) error {
  61. var errs []error
  62. for _, cap := range caps {
  63. switch cap {
  64. case CapabilityCompletion:
  65. f, err := os.Open(m.ModelPath)
  66. if err != nil {
  67. slog.Error("couldn't open model file", "error", err)
  68. continue
  69. }
  70. defer f.Close()
  71. // TODO(mxyng): decode the GGML into model to avoid doing this multiple times
  72. ggml, _, err := llm.DecodeGGML(f, 0)
  73. if err != nil {
  74. slog.Error("couldn't decode ggml", "error", err)
  75. continue
  76. }
  77. if _, ok := ggml.KV()[fmt.Sprintf("%s.pooling_type", ggml.KV().Architecture())]; ok {
  78. errs = append(errs, errCapabilityCompletion)
  79. }
  80. default:
  81. slog.Error("unknown capability", "capability", cap)
  82. return fmt.Errorf("unknown capability: %s", cap)
  83. }
  84. }
  85. if err := errors.Join(errs...); err != nil {
  86. return fmt.Errorf("missing capabilities: %w", errors.Join(errs...))
  87. }
  88. return nil
  89. }
  90. func (m *Model) String() string {
  91. var modelfile parser.File
  92. modelfile.Commands = append(modelfile.Commands, parser.Command{
  93. Name: "model",
  94. Args: m.ModelPath,
  95. })
  96. for _, adapter := range m.AdapterPaths {
  97. modelfile.Commands = append(modelfile.Commands, parser.Command{
  98. Name: "adapter",
  99. Args: adapter,
  100. })
  101. }
  102. for _, projector := range m.ProjectorPaths {
  103. modelfile.Commands = append(modelfile.Commands, parser.Command{
  104. Name: "model",
  105. Args: projector,
  106. })
  107. }
  108. if m.Template != nil {
  109. modelfile.Commands = append(modelfile.Commands, parser.Command{
  110. Name: "template",
  111. Args: m.Template.String(),
  112. })
  113. }
  114. if m.System != "" {
  115. modelfile.Commands = append(modelfile.Commands, parser.Command{
  116. Name: "system",
  117. Args: m.System,
  118. })
  119. }
  120. for k, v := range m.Options {
  121. switch v := v.(type) {
  122. case []any:
  123. for _, s := range v {
  124. modelfile.Commands = append(modelfile.Commands, parser.Command{
  125. Name: k,
  126. Args: fmt.Sprintf("%v", s),
  127. })
  128. }
  129. default:
  130. modelfile.Commands = append(modelfile.Commands, parser.Command{
  131. Name: k,
  132. Args: fmt.Sprintf("%v", v),
  133. })
  134. }
  135. }
  136. for _, license := range m.License {
  137. modelfile.Commands = append(modelfile.Commands, parser.Command{
  138. Name: "license",
  139. Args: license,
  140. })
  141. }
  142. for _, msg := range m.Messages {
  143. modelfile.Commands = append(modelfile.Commands, parser.Command{
  144. Name: "message",
  145. Args: fmt.Sprintf("%s %s", msg.Role, msg.Content),
  146. })
  147. }
  148. return modelfile.String()
  149. }
  150. type Message struct {
  151. Role string `json:"role"`
  152. Content string `json:"content"`
  153. }
  154. type ConfigV2 struct {
  155. ModelFormat string `json:"model_format"`
  156. ModelFamily string `json:"model_family"`
  157. ModelFamilies []string `json:"model_families"`
  158. ModelType string `json:"model_type"`
  159. FileType string `json:"file_type"`
  160. // required by spec
  161. Architecture string `json:"architecture"`
  162. OS string `json:"os"`
  163. RootFS RootFS `json:"rootfs"`
  164. }
  165. type RootFS struct {
  166. Type string `json:"type"`
  167. DiffIDs []string `json:"diff_ids"`
  168. }
  169. func GetManifest(mp ModelPath) (*Manifest, string, error) {
  170. fp, err := mp.GetManifestPath()
  171. if err != nil {
  172. return nil, "", err
  173. }
  174. if _, err = os.Stat(fp); err != nil {
  175. return nil, "", err
  176. }
  177. var manifest *Manifest
  178. bts, err := os.ReadFile(fp)
  179. if err != nil {
  180. return nil, "", fmt.Errorf("couldn't open file '%s'", fp)
  181. }
  182. shaSum := sha256.Sum256(bts)
  183. shaStr := hex.EncodeToString(shaSum[:])
  184. if err := json.Unmarshal(bts, &manifest); err != nil {
  185. return nil, "", err
  186. }
  187. return manifest, shaStr, nil
  188. }
  189. func GetModel(name string) (*Model, error) {
  190. mp := ParseModelPath(name)
  191. manifest, digest, err := GetManifest(mp)
  192. if err != nil {
  193. return nil, err
  194. }
  195. model := &Model{
  196. Name: mp.GetFullTagname(),
  197. ShortName: mp.GetShortTagname(),
  198. Digest: digest,
  199. Template: template.DefaultTemplate,
  200. }
  201. filename, err := GetBlobsPath(manifest.Config.Digest)
  202. if err != nil {
  203. return nil, err
  204. }
  205. configFile, err := os.Open(filename)
  206. if err != nil {
  207. return nil, err
  208. }
  209. defer configFile.Close()
  210. if err := json.NewDecoder(configFile).Decode(&model.Config); err != nil {
  211. return nil, err
  212. }
  213. for _, layer := range manifest.Layers {
  214. filename, err := GetBlobsPath(layer.Digest)
  215. if err != nil {
  216. return nil, err
  217. }
  218. switch layer.MediaType {
  219. case "application/vnd.ollama.image.model":
  220. model.ModelPath = filename
  221. model.ParentModel = layer.From
  222. case "application/vnd.ollama.image.embed":
  223. // Deprecated in versions > 0.1.2
  224. // TODO: remove this warning in a future version
  225. slog.Info("WARNING: model contains embeddings, but embeddings in modelfiles have been deprecated and will be ignored.")
  226. case "application/vnd.ollama.image.adapter":
  227. model.AdapterPaths = append(model.AdapterPaths, filename)
  228. case "application/vnd.ollama.image.projector":
  229. model.ProjectorPaths = append(model.ProjectorPaths, filename)
  230. case "application/vnd.ollama.image.prompt",
  231. "application/vnd.ollama.image.template":
  232. bts, err := os.ReadFile(filename)
  233. if err != nil {
  234. return nil, err
  235. }
  236. model.Template, err = template.Parse(string(bts))
  237. if err != nil {
  238. return nil, err
  239. }
  240. case "application/vnd.ollama.image.system":
  241. bts, err := os.ReadFile(filename)
  242. if err != nil {
  243. return nil, err
  244. }
  245. model.System = string(bts)
  246. case "application/vnd.ollama.image.params":
  247. params, err := os.Open(filename)
  248. if err != nil {
  249. return nil, err
  250. }
  251. defer params.Close()
  252. // parse model options parameters into a map so that we can see which fields have been specified explicitly
  253. if err = json.NewDecoder(params).Decode(&model.Options); err != nil {
  254. return nil, err
  255. }
  256. case "application/vnd.ollama.image.messages":
  257. msgs, err := os.Open(filename)
  258. if err != nil {
  259. return nil, err
  260. }
  261. defer msgs.Close()
  262. if err = json.NewDecoder(msgs).Decode(&model.Messages); err != nil {
  263. return nil, err
  264. }
  265. case "application/vnd.ollama.image.license":
  266. bts, err := os.ReadFile(filename)
  267. if err != nil {
  268. return nil, err
  269. }
  270. model.License = append(model.License, string(bts))
  271. }
  272. }
  273. return model, nil
  274. }
  275. func realpath(rel, from string) string {
  276. abspath, err := filepath.Abs(from)
  277. if err != nil {
  278. return from
  279. }
  280. home, err := os.UserHomeDir()
  281. if err != nil {
  282. return abspath
  283. }
  284. if from == "~" {
  285. return home
  286. } else if strings.HasPrefix(from, "~/") {
  287. return filepath.Join(home, from[2:])
  288. }
  289. if _, err := os.Stat(filepath.Join(rel, from)); err == nil {
  290. // this is a file relative to the Modelfile
  291. return filepath.Join(rel, from)
  292. }
  293. return abspath
  294. }
  295. func CreateModel(ctx context.Context, name model.Name, modelFileDir, quantization string, modelfile *parser.File, fn func(resp api.ProgressResponse)) (err error) {
  296. config := ConfigV2{
  297. OS: "linux",
  298. Architecture: "amd64",
  299. RootFS: RootFS{
  300. Type: "layers",
  301. },
  302. }
  303. var messages []*api.Message
  304. parameters := make(map[string]any)
  305. var layers []*Layer
  306. for _, c := range modelfile.Commands {
  307. mediatype := fmt.Sprintf("application/vnd.ollama.image.%s", c.Name)
  308. switch c.Name {
  309. case "model", "adapter":
  310. var baseLayers []*layerGGML
  311. if name := model.ParseName(c.Args); name.IsValid() {
  312. baseLayers, err = parseFromModel(ctx, name, fn)
  313. if err != nil {
  314. return err
  315. }
  316. } else if strings.HasPrefix(c.Args, "@") {
  317. digest := strings.TrimPrefix(c.Args, "@")
  318. if ib, ok := intermediateBlobs[digest]; ok {
  319. p, err := GetBlobsPath(ib)
  320. if err != nil {
  321. return err
  322. }
  323. if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
  324. // pass
  325. } else if err != nil {
  326. return err
  327. } else {
  328. fn(api.ProgressResponse{Status: fmt.Sprintf("using cached layer %s", ib)})
  329. digest = ib
  330. }
  331. }
  332. blobpath, err := GetBlobsPath(digest)
  333. if err != nil {
  334. return err
  335. }
  336. blob, err := os.Open(blobpath)
  337. if err != nil {
  338. return err
  339. }
  340. defer blob.Close()
  341. baseLayers, err = parseFromFile(ctx, blob, digest, fn)
  342. if err != nil {
  343. return err
  344. }
  345. } else if file, err := os.Open(realpath(modelFileDir, c.Args)); err == nil {
  346. defer file.Close()
  347. baseLayers, err = parseFromFile(ctx, file, "", fn)
  348. if err != nil {
  349. return err
  350. }
  351. } else {
  352. return fmt.Errorf("invalid model reference: %s", c.Args)
  353. }
  354. for _, baseLayer := range baseLayers {
  355. if quantization != "" &&
  356. baseLayer.MediaType == "application/vnd.ollama.image.model" &&
  357. baseLayer.GGML != nil &&
  358. baseLayer.GGML.Name() == "gguf" {
  359. want, err := llm.ParseFileType(quantization)
  360. if err != nil {
  361. return err
  362. }
  363. ft := baseLayer.GGML.KV().FileType()
  364. if !slices.Contains([]string{"F16", "F32"}, ft.String()) {
  365. return errors.New("quantization is only supported for F16 and F32 models")
  366. } else if want != ft {
  367. fn(api.ProgressResponse{Status: fmt.Sprintf("quantizing %s model to %s", ft, quantization)})
  368. blob, err := GetBlobsPath(baseLayer.Digest)
  369. if err != nil {
  370. return err
  371. }
  372. temp, err := os.CreateTemp(filepath.Dir(blob), quantization)
  373. if err != nil {
  374. return err
  375. }
  376. defer temp.Close()
  377. defer os.Remove(temp.Name())
  378. if err := llm.Quantize(blob, temp.Name(), want); err != nil {
  379. return err
  380. }
  381. layer, err := NewLayer(temp, baseLayer.MediaType)
  382. if err != nil {
  383. return err
  384. }
  385. if _, err := temp.Seek(0, io.SeekStart); err != nil {
  386. return err
  387. }
  388. ggml, _, err := llm.DecodeGGML(temp, 0)
  389. if err != nil {
  390. return err
  391. }
  392. baseLayer.Layer = layer
  393. baseLayer.GGML = ggml
  394. }
  395. }
  396. if baseLayer.GGML != nil {
  397. config.ModelFormat = cmp.Or(config.ModelFormat, baseLayer.GGML.Name())
  398. config.ModelFamily = cmp.Or(config.ModelFamily, baseLayer.GGML.KV().Architecture())
  399. config.ModelType = cmp.Or(config.ModelType, format.HumanNumber(baseLayer.GGML.KV().ParameterCount()))
  400. config.FileType = cmp.Or(config.FileType, baseLayer.GGML.KV().FileType().String())
  401. config.ModelFamilies = append(config.ModelFamilies, baseLayer.GGML.KV().Architecture())
  402. }
  403. layers = append(layers, baseLayer.Layer)
  404. }
  405. case "license", "template", "system":
  406. if c.Name != "license" {
  407. // replace
  408. layers = slices.DeleteFunc(layers, func(layer *Layer) bool {
  409. if layer.MediaType != mediatype {
  410. return false
  411. }
  412. if err := layer.Remove(); err != nil {
  413. return false
  414. }
  415. return true
  416. })
  417. }
  418. blob := strings.NewReader(c.Args)
  419. layer, err := NewLayer(blob, mediatype)
  420. if err != nil {
  421. return err
  422. }
  423. layers = append(layers, layer)
  424. case "message":
  425. role, content, ok := strings.Cut(c.Args, ": ")
  426. if !ok {
  427. return fmt.Errorf("invalid message: %s", c.Args)
  428. }
  429. messages = append(messages, &api.Message{Role: role, Content: content})
  430. default:
  431. ps, err := api.FormatParams(map[string][]string{c.Name: {c.Args}})
  432. if err != nil {
  433. return err
  434. }
  435. for k, v := range ps {
  436. if ks, ok := parameters[k].([]string); ok {
  437. parameters[k] = append(ks, v.([]string)...)
  438. } else if vs, ok := v.([]string); ok {
  439. parameters[k] = vs
  440. } else {
  441. parameters[k] = v
  442. }
  443. }
  444. }
  445. }
  446. var err2 error
  447. layers = slices.DeleteFunc(layers, func(layer *Layer) bool {
  448. switch layer.MediaType {
  449. case "application/vnd.ollama.image.message":
  450. // if there are new messages, remove the inherited ones
  451. if len(messages) > 0 {
  452. return true
  453. }
  454. return false
  455. case "application/vnd.ollama.image.params":
  456. // merge inherited parameters with new ones
  457. r, err := layer.Open()
  458. if err != nil {
  459. err2 = err
  460. return false
  461. }
  462. defer r.Close()
  463. var ps map[string]any
  464. if err := json.NewDecoder(r).Decode(&ps); err != nil {
  465. err2 = err
  466. return false
  467. }
  468. for k, v := range ps {
  469. if _, ok := parameters[k]; !ok {
  470. parameters[k] = v
  471. }
  472. }
  473. return true
  474. default:
  475. return false
  476. }
  477. })
  478. if err2 != nil {
  479. return err2
  480. }
  481. if len(messages) > 0 {
  482. var b bytes.Buffer
  483. if err := json.NewEncoder(&b).Encode(messages); err != nil {
  484. return err
  485. }
  486. layer, err := NewLayer(&b, "application/vnd.ollama.image.messages")
  487. if err != nil {
  488. return err
  489. }
  490. layers = append(layers, layer)
  491. }
  492. if len(parameters) > 0 {
  493. var b bytes.Buffer
  494. if err := json.NewEncoder(&b).Encode(parameters); err != nil {
  495. return err
  496. }
  497. layer, err := NewLayer(&b, "application/vnd.ollama.image.params")
  498. if err != nil {
  499. return err
  500. }
  501. layers = append(layers, layer)
  502. }
  503. digests := make([]string, len(layers))
  504. for i, layer := range layers {
  505. digests[i] = layer.Digest
  506. }
  507. config.RootFS.DiffIDs = digests
  508. var b bytes.Buffer
  509. if err := json.NewEncoder(&b).Encode(config); err != nil {
  510. return err
  511. }
  512. layer, err := NewLayer(&b, "application/vnd.docker.container.image.v1+json")
  513. if err != nil {
  514. return err
  515. }
  516. for _, layer := range append(layers, layer) {
  517. if layer.status != "" {
  518. fn(api.ProgressResponse{Status: layer.status})
  519. }
  520. }
  521. old, _ := ParseNamedManifest(name)
  522. fn(api.ProgressResponse{Status: "writing manifest"})
  523. if err := WriteManifest(name, layer, layers); err != nil {
  524. return err
  525. }
  526. if !envconfig.NoPrune && old != nil {
  527. if err := old.RemoveLayers(); err != nil {
  528. return err
  529. }
  530. }
  531. fn(api.ProgressResponse{Status: "success"})
  532. return nil
  533. }
  534. func CopyModel(src, dst model.Name) error {
  535. if !dst.IsFullyQualified() {
  536. return model.Unqualified(dst)
  537. }
  538. if !src.IsFullyQualified() {
  539. return model.Unqualified(src)
  540. }
  541. if src.Filepath() == dst.Filepath() {
  542. return nil
  543. }
  544. manifests, err := GetManifestPath()
  545. if err != nil {
  546. return err
  547. }
  548. dstpath := filepath.Join(manifests, dst.Filepath())
  549. if err := os.MkdirAll(filepath.Dir(dstpath), 0o755); err != nil {
  550. return err
  551. }
  552. srcpath := filepath.Join(manifests, src.Filepath())
  553. srcfile, err := os.Open(srcpath)
  554. if err != nil {
  555. return err
  556. }
  557. defer srcfile.Close()
  558. dstfile, err := os.Create(dstpath)
  559. if err != nil {
  560. return err
  561. }
  562. defer dstfile.Close()
  563. _, err = io.Copy(dstfile, srcfile)
  564. return err
  565. }
  566. func deleteUnusedLayers(skipModelPath *ModelPath, deleteMap map[string]struct{}) error {
  567. fp, err := GetManifestPath()
  568. if err != nil {
  569. return err
  570. }
  571. walkFunc := func(path string, info os.FileInfo, _ error) error {
  572. if info.IsDir() {
  573. return nil
  574. }
  575. dir, file := filepath.Split(path)
  576. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  577. tag := strings.Join([]string{dir, file}, ":")
  578. fmp := ParseModelPath(tag)
  579. // skip the manifest we're trying to delete
  580. if skipModelPath != nil && skipModelPath.GetFullTagname() == fmp.GetFullTagname() {
  581. return nil
  582. }
  583. // save (i.e. delete from the deleteMap) any files used in other manifests
  584. manifest, _, err := GetManifest(fmp)
  585. if err != nil {
  586. //nolint:nilerr
  587. return nil
  588. }
  589. for _, layer := range manifest.Layers {
  590. delete(deleteMap, layer.Digest)
  591. }
  592. delete(deleteMap, manifest.Config.Digest)
  593. return nil
  594. }
  595. if err := filepath.Walk(fp, walkFunc); err != nil {
  596. return err
  597. }
  598. // only delete the files which are still in the deleteMap
  599. for k := range deleteMap {
  600. fp, err := GetBlobsPath(k)
  601. if err != nil {
  602. slog.Info(fmt.Sprintf("couldn't get file path for '%s': %v", k, err))
  603. continue
  604. }
  605. if err := os.Remove(fp); err != nil {
  606. slog.Info(fmt.Sprintf("couldn't remove file '%s': %v", fp, err))
  607. continue
  608. }
  609. }
  610. return nil
  611. }
  612. func PruneLayers() error {
  613. deleteMap := make(map[string]struct{})
  614. p, err := GetBlobsPath("")
  615. if err != nil {
  616. return err
  617. }
  618. blobs, err := os.ReadDir(p)
  619. if err != nil {
  620. slog.Info(fmt.Sprintf("couldn't read dir '%s': %v", p, err))
  621. return err
  622. }
  623. for _, blob := range blobs {
  624. name := blob.Name()
  625. name = strings.ReplaceAll(name, "-", ":")
  626. _, err := GetBlobsPath(name)
  627. if err != nil {
  628. if errors.Is(err, ErrInvalidDigestFormat) {
  629. // remove invalid blobs (e.g. partial downloads)
  630. if err := os.Remove(filepath.Join(p, blob.Name())); err != nil {
  631. slog.Error("couldn't remove blob", "blob", blob.Name(), "error", err)
  632. }
  633. }
  634. continue
  635. }
  636. deleteMap[name] = struct{}{}
  637. }
  638. slog.Info(fmt.Sprintf("total blobs: %d", len(deleteMap)))
  639. err = deleteUnusedLayers(nil, deleteMap)
  640. if err != nil {
  641. return err
  642. }
  643. slog.Info(fmt.Sprintf("total unused blobs removed: %d", len(deleteMap)))
  644. return nil
  645. }
  646. func PruneDirectory(path string) error {
  647. info, err := os.Lstat(path)
  648. if err != nil {
  649. return err
  650. }
  651. if info.IsDir() && info.Mode()&os.ModeSymlink == 0 {
  652. entries, err := os.ReadDir(path)
  653. if err != nil {
  654. return err
  655. }
  656. for _, entry := range entries {
  657. if err := PruneDirectory(filepath.Join(path, entry.Name())); err != nil {
  658. return err
  659. }
  660. }
  661. entries, err = os.ReadDir(path)
  662. if err != nil {
  663. return err
  664. }
  665. if len(entries) > 0 {
  666. return nil
  667. }
  668. return os.Remove(path)
  669. }
  670. return nil
  671. }
  672. func PushModel(ctx context.Context, name string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
  673. mp := ParseModelPath(name)
  674. fn(api.ProgressResponse{Status: "retrieving manifest"})
  675. if mp.ProtocolScheme == "http" && !regOpts.Insecure {
  676. return fmt.Errorf("insecure protocol http")
  677. }
  678. manifest, _, err := GetManifest(mp)
  679. if err != nil {
  680. fn(api.ProgressResponse{Status: "couldn't retrieve manifest"})
  681. return err
  682. }
  683. var layers []*Layer
  684. layers = append(layers, manifest.Layers...)
  685. layers = append(layers, manifest.Config)
  686. for _, layer := range layers {
  687. if err := uploadBlob(ctx, mp, layer, regOpts, fn); err != nil {
  688. slog.Info(fmt.Sprintf("error uploading blob: %v", err))
  689. return err
  690. }
  691. }
  692. fn(api.ProgressResponse{Status: "pushing manifest"})
  693. requestURL := mp.BaseURL()
  694. requestURL = requestURL.JoinPath("v2", mp.GetNamespaceRepository(), "manifests", mp.Tag)
  695. manifestJSON, err := json.Marshal(manifest)
  696. if err != nil {
  697. return err
  698. }
  699. headers := make(http.Header)
  700. headers.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
  701. resp, err := makeRequestWithRetry(ctx, http.MethodPut, requestURL, headers, bytes.NewReader(manifestJSON), regOpts)
  702. if err != nil {
  703. return err
  704. }
  705. defer resp.Body.Close()
  706. fn(api.ProgressResponse{Status: "success"})
  707. return nil
  708. }
  709. func PullModel(ctx context.Context, name string, regOpts *registryOptions, fn func(api.ProgressResponse)) error {
  710. mp := ParseModelPath(name)
  711. var manifest *Manifest
  712. var err error
  713. var noprune string
  714. // build deleteMap to prune unused layers
  715. deleteMap := make(map[string]struct{})
  716. if !envconfig.NoPrune {
  717. manifest, _, err = GetManifest(mp)
  718. if err != nil && !errors.Is(err, os.ErrNotExist) {
  719. return err
  720. }
  721. if manifest != nil {
  722. for _, l := range manifest.Layers {
  723. deleteMap[l.Digest] = struct{}{}
  724. }
  725. deleteMap[manifest.Config.Digest] = struct{}{}
  726. }
  727. }
  728. if mp.ProtocolScheme == "http" && !regOpts.Insecure {
  729. return fmt.Errorf("insecure protocol http")
  730. }
  731. fn(api.ProgressResponse{Status: "pulling manifest"})
  732. manifest, err = pullModelManifest(ctx, mp, regOpts)
  733. if err != nil {
  734. return fmt.Errorf("pull model manifest: %s", err)
  735. }
  736. var layers []*Layer
  737. layers = append(layers, manifest.Layers...)
  738. layers = append(layers, manifest.Config)
  739. skipVerify := make(map[string]bool)
  740. for _, layer := range layers {
  741. cacheHit, err := downloadBlob(ctx, downloadOpts{
  742. mp: mp,
  743. digest: layer.Digest,
  744. regOpts: regOpts,
  745. fn: fn,
  746. })
  747. if err != nil {
  748. return err
  749. }
  750. skipVerify[layer.Digest] = cacheHit
  751. delete(deleteMap, layer.Digest)
  752. }
  753. delete(deleteMap, manifest.Config.Digest)
  754. fn(api.ProgressResponse{Status: "verifying sha256 digest"})
  755. for _, layer := range layers {
  756. if skipVerify[layer.Digest] {
  757. continue
  758. }
  759. if err := verifyBlob(layer.Digest); err != nil {
  760. if errors.Is(err, errDigestMismatch) {
  761. // something went wrong, delete the blob
  762. fp, err := GetBlobsPath(layer.Digest)
  763. if err != nil {
  764. return err
  765. }
  766. if err := os.Remove(fp); err != nil {
  767. // log this, but return the original error
  768. slog.Info(fmt.Sprintf("couldn't remove file with digest mismatch '%s': %v", fp, err))
  769. }
  770. }
  771. return err
  772. }
  773. }
  774. fn(api.ProgressResponse{Status: "writing manifest"})
  775. manifestJSON, err := json.Marshal(manifest)
  776. if err != nil {
  777. return err
  778. }
  779. fp, err := mp.GetManifestPath()
  780. if err != nil {
  781. return err
  782. }
  783. if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
  784. return err
  785. }
  786. err = os.WriteFile(fp, manifestJSON, 0o644)
  787. if err != nil {
  788. slog.Info(fmt.Sprintf("couldn't write to %s", fp))
  789. return err
  790. }
  791. if noprune == "" {
  792. fn(api.ProgressResponse{Status: "removing any unused layers"})
  793. err = deleteUnusedLayers(nil, deleteMap)
  794. if err != nil {
  795. return err
  796. }
  797. }
  798. fn(api.ProgressResponse{Status: "success"})
  799. return nil
  800. }
  801. func pullModelManifest(ctx context.Context, mp ModelPath, regOpts *registryOptions) (*Manifest, error) {
  802. requestURL := mp.BaseURL().JoinPath("v2", mp.GetNamespaceRepository(), "manifests", mp.Tag)
  803. headers := make(http.Header)
  804. headers.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
  805. resp, err := makeRequestWithRetry(ctx, http.MethodGet, requestURL, headers, nil, regOpts)
  806. if err != nil {
  807. return nil, err
  808. }
  809. defer resp.Body.Close()
  810. var m *Manifest
  811. if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
  812. return nil, err
  813. }
  814. return m, err
  815. }
  816. // GetSHA256Digest returns the SHA256 hash of a given buffer and returns it, and the size of buffer
  817. func GetSHA256Digest(r io.Reader) (string, int64) {
  818. h := sha256.New()
  819. n, err := io.Copy(h, r)
  820. if err != nil {
  821. log.Fatal(err)
  822. }
  823. return fmt.Sprintf("sha256:%x", h.Sum(nil)), n
  824. }
  825. var errUnauthorized = fmt.Errorf("unauthorized: access denied")
  826. // getTokenSubject returns the subject of a JWT token, it does not validate the token
  827. func getTokenSubject(token string) string {
  828. parts := strings.Split(token, ".")
  829. if len(parts) != 3 {
  830. return ""
  831. }
  832. payload := parts[1]
  833. payloadBytes, err := base64.RawURLEncoding.DecodeString(payload)
  834. if err != nil {
  835. slog.Error(fmt.Sprintf("failed to decode jwt payload: %v", err))
  836. return ""
  837. }
  838. var payloadMap map[string]interface{}
  839. if err := json.Unmarshal(payloadBytes, &payloadMap); err != nil {
  840. slog.Error(fmt.Sprintf("failed to unmarshal payload JSON: %v", err))
  841. return ""
  842. }
  843. sub, ok := payloadMap["sub"]
  844. if !ok {
  845. slog.Error("jwt does not contain 'sub' field")
  846. return ""
  847. }
  848. return fmt.Sprintf("%s", sub)
  849. }
  850. func makeRequestWithRetry(ctx context.Context, method string, requestURL *url.URL, headers http.Header, body io.ReadSeeker, regOpts *registryOptions) (*http.Response, error) {
  851. anonymous := true // access will default to anonymous if no user is found associated with the public key
  852. for range 2 {
  853. resp, err := makeRequest(ctx, method, requestURL, headers, body, regOpts)
  854. if err != nil {
  855. if !errors.Is(err, context.Canceled) {
  856. slog.Info(fmt.Sprintf("request failed: %v", err))
  857. }
  858. return nil, err
  859. }
  860. switch {
  861. case resp.StatusCode == http.StatusUnauthorized:
  862. // Handle authentication error with one retry
  863. challenge := parseRegistryChallenge(resp.Header.Get("www-authenticate"))
  864. token, err := getAuthorizationToken(ctx, challenge)
  865. if err != nil {
  866. return nil, err
  867. }
  868. anonymous = getTokenSubject(token) == "anonymous"
  869. regOpts.Token = token
  870. if body != nil {
  871. _, err = body.Seek(0, io.SeekStart)
  872. if err != nil {
  873. return nil, err
  874. }
  875. }
  876. case resp.StatusCode == http.StatusNotFound:
  877. return nil, os.ErrNotExist
  878. case resp.StatusCode >= http.StatusBadRequest:
  879. responseBody, err := io.ReadAll(resp.Body)
  880. if err != nil {
  881. return nil, fmt.Errorf("%d: %s", resp.StatusCode, err)
  882. }
  883. return nil, fmt.Errorf("%d: %s", resp.StatusCode, responseBody)
  884. default:
  885. return resp, nil
  886. }
  887. }
  888. if anonymous {
  889. // no user is associated with the public key, and the request requires non-anonymous access
  890. pubKey, nestedErr := auth.GetPublicKey()
  891. if nestedErr != nil {
  892. slog.Error(fmt.Sprintf("couldn't get public key: %v", nestedErr))
  893. return nil, errUnauthorized
  894. }
  895. return nil, &errtypes.UnknownOllamaKey{Key: pubKey}
  896. }
  897. // user is associated with the public key, but is not authorized to make the request
  898. return nil, errUnauthorized
  899. }
  900. func makeRequest(ctx context.Context, method string, requestURL *url.URL, headers http.Header, body io.Reader, regOpts *registryOptions) (*http.Response, error) {
  901. if requestURL.Scheme != "http" && regOpts != nil && regOpts.Insecure {
  902. requestURL.Scheme = "http"
  903. }
  904. req, err := http.NewRequestWithContext(ctx, method, requestURL.String(), body)
  905. if err != nil {
  906. return nil, err
  907. }
  908. if headers != nil {
  909. req.Header = headers
  910. }
  911. if regOpts != nil {
  912. if regOpts.Token != "" {
  913. req.Header.Set("Authorization", "Bearer "+regOpts.Token)
  914. } else if regOpts.Username != "" && regOpts.Password != "" {
  915. req.SetBasicAuth(regOpts.Username, regOpts.Password)
  916. }
  917. }
  918. req.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  919. if s := req.Header.Get("Content-Length"); s != "" {
  920. contentLength, err := strconv.ParseInt(s, 10, 64)
  921. if err != nil {
  922. return nil, err
  923. }
  924. req.ContentLength = contentLength
  925. }
  926. resp, err := http.DefaultClient.Do(req)
  927. if err != nil {
  928. return nil, err
  929. }
  930. return resp, nil
  931. }
  932. func getValue(header, key string) string {
  933. startIdx := strings.Index(header, key+"=")
  934. if startIdx == -1 {
  935. return ""
  936. }
  937. // Move the index to the starting quote after the key.
  938. startIdx += len(key) + 2
  939. endIdx := startIdx
  940. for endIdx < len(header) {
  941. if header[endIdx] == '"' {
  942. if endIdx+1 < len(header) && header[endIdx+1] != ',' { // If the next character isn't a comma, continue
  943. endIdx++
  944. continue
  945. }
  946. break
  947. }
  948. endIdx++
  949. }
  950. return header[startIdx:endIdx]
  951. }
  952. func parseRegistryChallenge(authStr string) registryChallenge {
  953. authStr = strings.TrimPrefix(authStr, "Bearer ")
  954. return registryChallenge{
  955. Realm: getValue(authStr, "realm"),
  956. Service: getValue(authStr, "service"),
  957. Scope: getValue(authStr, "scope"),
  958. }
  959. }
  960. var errDigestMismatch = errors.New("digest mismatch, file must be downloaded again")
  961. func verifyBlob(digest string) error {
  962. fp, err := GetBlobsPath(digest)
  963. if err != nil {
  964. return err
  965. }
  966. f, err := os.Open(fp)
  967. if err != nil {
  968. return err
  969. }
  970. defer f.Close()
  971. fileDigest, _ := GetSHA256Digest(f)
  972. if digest != fileDigest {
  973. return fmt.Errorf("%w: want %s, got %s", errDigestMismatch, digest, fileDigest)
  974. }
  975. return nil
  976. }