cache.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. // Package blob implements a content-addressable disk cache for blobs and
  2. // manifests.
  3. package blob
  4. import (
  5. "bytes"
  6. "crypto/sha256"
  7. "errors"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "io/fs"
  12. "iter"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "time"
  17. "github.com/ollama/ollama/server/internal/internal/names"
  18. )
  19. // Entry contains metadata about a blob in the cache.
  20. type Entry struct {
  21. Digest Digest
  22. Size int64
  23. Time time.Time // when added to the cache
  24. }
  25. // DiskCache caches blobs and manifests on disk.
  26. //
  27. // The cache is rooted at a directory, which is created if it does not exist.
  28. //
  29. // Blobs are stored in the "blobs" subdirectory, and manifests are stored in the
  30. // "manifests" subdirectory. A example directory structure might look like:
  31. //
  32. // <dir>/
  33. // blobs/
  34. // sha256-<digest> - <blob data>
  35. // manifests/
  36. // <host>/
  37. // <namespace>/
  38. // <name>/
  39. // <tag> - <manifest data>
  40. //
  41. // The cache is safe for concurrent use.
  42. //
  43. // Name casing is preserved in the cache, but is not significant when resolving
  44. // names. For example, "Foo" and "foo" are considered the same name.
  45. //
  46. // The cache is not safe for concurrent use. It guards concurrent writes, but
  47. // does not prevent duplicated effort. Because blobs are immutable, duplicate
  48. // writes should result in the same file being written to disk.
  49. type DiskCache struct {
  50. // Dir specifies the top-level directory where blobs and manifest
  51. // pointers are stored.
  52. dir string
  53. now func() time.Time
  54. testHookBeforeFinalWrite func(f *os.File)
  55. }
  56. // PutString is a convenience function for c.Put(d, strings.NewReader(s), int64(len(s))).
  57. func PutBytes[S string | []byte](c *DiskCache, d Digest, data S) error {
  58. return c.Put(d, bytes.NewReader([]byte(data)), int64(len(data)))
  59. }
  60. // Open opens a cache rooted at the given directory. If the directory does not
  61. // exist, it is created. If the directory is not a directory, an error is
  62. // returned.
  63. func Open(dir string) (*DiskCache, error) {
  64. if dir == "" {
  65. return nil, errors.New("blob: empty directory name")
  66. }
  67. info, err := os.Stat(dir)
  68. if err == nil && !info.IsDir() {
  69. return nil, fmt.Errorf("%q is not a directory", dir)
  70. }
  71. if err := os.MkdirAll(dir, 0o777); err != nil {
  72. return nil, err
  73. }
  74. subdirs := []string{"blobs", "manifests"}
  75. for _, subdir := range subdirs {
  76. if err := os.MkdirAll(filepath.Join(dir, subdir), 0o777); err != nil {
  77. return nil, err
  78. }
  79. }
  80. // TODO(bmizerany): support shards
  81. c := &DiskCache{
  82. dir: dir,
  83. now: time.Now,
  84. }
  85. return c, nil
  86. }
  87. func readAndSum(filename string, limit int64) (data []byte, _ Digest, err error) {
  88. f, err := os.Open(filename)
  89. if err != nil {
  90. return nil, Digest{}, err
  91. }
  92. defer f.Close()
  93. h := sha256.New()
  94. r := io.TeeReader(f, h)
  95. data, err = io.ReadAll(io.LimitReader(r, limit))
  96. if err != nil {
  97. return nil, Digest{}, err
  98. }
  99. var d Digest
  100. h.Sum(d.sum[:0])
  101. return data, d, nil
  102. }
  103. //lint:ignore U1000 used for debugging purposes as needed in tests
  104. var debug = false
  105. // debugger returns a function that can be used to add a step to the error message.
  106. // The error message will be a list of steps that were taken before the error occurred.
  107. // The steps are added in the order they are called.
  108. //
  109. // To set the error message, call the returned function with an empty string.
  110. //
  111. //lint:ignore U1000 used for debugging purposes as needed in tests
  112. func debugger(err *error) func(step string) {
  113. if !debug {
  114. return func(string) {}
  115. }
  116. var steps []string
  117. return func(step string) {
  118. if step == "" && *err != nil {
  119. *err = fmt.Errorf("%q: %w", steps, *err)
  120. return
  121. }
  122. steps = append(steps, step)
  123. if len(steps) > 100 {
  124. // shift hints in case of a bug that causes a lot of hints
  125. copy(steps, steps[1:])
  126. steps = steps[:100]
  127. }
  128. }
  129. }
  130. // Resolve resolves a name to a digest. The name is expected to
  131. // be in either of the following forms:
  132. //
  133. // @<digest>
  134. // <name>@<digest>
  135. // <name>
  136. //
  137. // If a digest is provided, it is returned as is and nothing else happens.
  138. //
  139. // If a name is provided for a manifest that exists in the cache, the digest
  140. // of the manifest is returned. If there is no manifest in the cache, it
  141. // returns [fs.ErrNotExist].
  142. //
  143. // To cover the case where a manifest may change without the cache knowing
  144. // (e.g. it was reformatted or modified by hand), the manifest data read and
  145. // hashed is passed to a PutBytes call to ensure that the manifest is in the
  146. // blob store. This is done to ensure that future calls to [Get] succeed in
  147. // these cases.
  148. func (c *DiskCache) Resolve(name string) (Digest, error) {
  149. name, digest := splitNameDigest(name)
  150. if digest != "" {
  151. return ParseDigest(digest)
  152. }
  153. // We want to address manifests files by digest using Get. That requires
  154. // them to be blobs. This cannot be directly accomplished by looking in
  155. // the blob store because manifests can change without Ollama knowing
  156. // (e.g. a user modifies a manifests by hand then pushes it to update
  157. // their model). We also need to support the blob caches inherited from
  158. // older versions of Ollama, which do not store manifests in the blob
  159. // store, so for these cases, we need to handle adding the manifests to
  160. // the blob store, just in time.
  161. //
  162. // So now we read the manifests file, hash it, and copy it to the blob
  163. // store if it's not already there.
  164. //
  165. // This should be cheap because manifests are small, and accessed
  166. // infrequently.
  167. file, err := c.manifestPath(name)
  168. if err != nil {
  169. return Digest{}, err
  170. }
  171. data, d, err := readAndSum(file, 1<<20)
  172. if err != nil {
  173. return Digest{}, err
  174. }
  175. // Ideally we'd read the "manifest" file as a manifest to the blob file,
  176. // but we are not changing this yet, so copy the manifest to the blob
  177. // store so it can be addressed by digest subsequent calls to Get.
  178. if err := PutBytes(c, d, data); err != nil {
  179. return Digest{}, err
  180. }
  181. return d, nil
  182. }
  183. // Put writes a new blob to the cache, identified by its digest. The operation
  184. // reads content from r, which must precisely match both the specified size and
  185. // digest.
  186. //
  187. // Concurrent write safety is achieved through file locking. The implementation
  188. // guarantees write integrity by enforcing size limits and content validation
  189. // before allowing the file to reach its final state.
  190. func (c *DiskCache) Put(d Digest, r io.Reader, size int64) error {
  191. return c.copyNamedFile(c.GetFile(d), r, d, size)
  192. }
  193. // Import imports a blob from the provided reader into the cache. It reads the
  194. // entire content of the reader, calculates its digest, and stores it in the
  195. // cache.
  196. //
  197. // Import should be considered unsafe for use with untrusted data, such as data
  198. // read from a network. The caller is responsible for ensuring the integrity of
  199. // the data being imported.
  200. func (c *DiskCache) Import(r io.Reader, size int64) (Digest, error) {
  201. // users that want to change the temp dir can set TEMPDIR.
  202. f, err := os.CreateTemp("", "blob-")
  203. if err != nil {
  204. return Digest{}, err
  205. }
  206. defer os.Remove(f.Name())
  207. // Copy the blob to a temporary file.
  208. h := sha256.New()
  209. r = io.TeeReader(r, h)
  210. n, err := io.Copy(f, r)
  211. if err != nil {
  212. return Digest{}, err
  213. }
  214. if n != size {
  215. return Digest{}, fmt.Errorf("blob: expected %d bytes, got %d", size, n)
  216. }
  217. // Check the digest.
  218. var d Digest
  219. h.Sum(d.sum[:0])
  220. if err := f.Close(); err != nil {
  221. return Digest{}, err
  222. }
  223. name := c.GetFile(d)
  224. // Rename the temporary file to the final file.
  225. if err := os.Rename(f.Name(), name); err != nil {
  226. return Digest{}, err
  227. }
  228. os.Chtimes(name, c.now(), c.now()) // mainly for tests
  229. return d, nil
  230. }
  231. // Get retrieves a blob from the cache using the provided digest. The operation
  232. // fails if the digest is malformed or if any errors occur during blob
  233. // retrieval.
  234. func (c *DiskCache) Get(d Digest) (Entry, error) {
  235. name := c.GetFile(d)
  236. info, err := os.Stat(name)
  237. if err != nil {
  238. return Entry{}, err
  239. }
  240. if info.Size() == 0 {
  241. return Entry{}, fs.ErrNotExist
  242. }
  243. return Entry{
  244. Digest: d,
  245. Size: info.Size(),
  246. Time: info.ModTime(),
  247. }, nil
  248. }
  249. // Link creates a symbolic reference in the cache that maps the provided name
  250. // to a blob identified by its digest, making it retrievable by name using
  251. // [Resolve].
  252. //
  253. // It returns an error if either the name or digest is invalid, or if link
  254. // creation encounters any issues.
  255. func (c *DiskCache) Link(name string, d Digest) error {
  256. manifest, err := c.manifestPath(name)
  257. if err != nil {
  258. return err
  259. }
  260. f, err := os.OpenFile(c.GetFile(d), os.O_RDONLY, 0)
  261. if err != nil {
  262. return err
  263. }
  264. defer f.Close()
  265. // TODO(bmizerany): test this happens only if the blob was found to
  266. // avoid leaving debris
  267. if err := os.MkdirAll(filepath.Dir(manifest), 0o777); err != nil {
  268. return err
  269. }
  270. info, err := f.Stat()
  271. if err != nil {
  272. return err
  273. }
  274. // Copy manifest to cache directory.
  275. return c.copyNamedFile(manifest, f, d, info.Size())
  276. }
  277. // Unlink unlinks the manifest by name from the cache. If the name is not
  278. // found. If a manifest is removed ok will be true, otherwise false. If an
  279. // error occurs, it returns ok false, and the error.
  280. func (c *DiskCache) Unlink(name string) (ok bool, _ error) {
  281. manifest, err := c.manifestPath(name)
  282. if err != nil {
  283. return false, err
  284. }
  285. err = os.Remove(manifest)
  286. if errors.Is(err, fs.ErrNotExist) {
  287. return false, nil
  288. }
  289. return true, err
  290. }
  291. // GetFile returns the absolute path to the file, in the cache, for the given
  292. // digest. It does not check if the file exists.
  293. //
  294. // The returned path should not be stored, used outside the lifetime of the
  295. // cache, or interpreted in any way.
  296. func (c *DiskCache) GetFile(d Digest) string {
  297. filename := fmt.Sprintf("sha256-%x", d.sum)
  298. return absJoin(c.dir, "blobs", filename)
  299. }
  300. // Links returns a sequence of link names. The sequence is in lexical order.
  301. // Names are converted from their relative path form to their name form but are
  302. // not guaranteed to be valid. Callers should validate the names before using.
  303. func (c *DiskCache) Links() iter.Seq2[string, error] {
  304. return func(yield func(string, error) bool) {
  305. for path, err := range c.links() {
  306. if err != nil {
  307. yield("", err)
  308. return
  309. }
  310. if !yield(pathToName(path), nil) {
  311. return
  312. }
  313. }
  314. }
  315. }
  316. // pathToName converts a path to a name. It is the inverse of nameToPath. The
  317. // path is assumed to be in filepath.ToSlash format.
  318. func pathToName(s string) string {
  319. s = strings.TrimPrefix(s, "manifests/")
  320. rr := []rune(s)
  321. for i := len(rr) - 1; i > 0; i-- {
  322. if rr[i] == '/' {
  323. rr[i] = ':'
  324. return string(rr)
  325. }
  326. }
  327. return s
  328. }
  329. // manifestPath finds the first manifest file on disk that matches the given
  330. // name using a case-insensitive comparison. If no manifest file is found, it
  331. // returns the path where the manifest file would be if it existed.
  332. //
  333. // If two manifest files exists on disk that match the given name using a
  334. // case-insensitive comparison, the one that sorts first, lexically, is
  335. // returned.
  336. func (c *DiskCache) manifestPath(name string) (string, error) {
  337. np, err := nameToPath(name)
  338. if err != nil {
  339. return "", err
  340. }
  341. maybe := filepath.Join("manifests", np)
  342. for l, err := range c.links() {
  343. if err != nil {
  344. return "", err
  345. }
  346. if strings.EqualFold(maybe, l) {
  347. return filepath.Join(c.dir, l), nil
  348. }
  349. }
  350. return filepath.Join(c.dir, maybe), nil
  351. }
  352. // links returns a sequence of links in the cache in lexical order.
  353. func (c *DiskCache) links() iter.Seq2[string, error] {
  354. // TODO(bmizerany): reuse empty dirnames if exist
  355. return func(yield func(string, error) bool) {
  356. fsys := os.DirFS(c.dir)
  357. manifests, err := fs.Glob(fsys, "manifests/*/*/*/*")
  358. if err != nil {
  359. yield("", err)
  360. return
  361. }
  362. for _, manifest := range manifests {
  363. if !yield(manifest, nil) {
  364. return
  365. }
  366. }
  367. }
  368. }
  369. type checkWriter struct {
  370. size int64
  371. d Digest
  372. f *os.File
  373. h hash.Hash
  374. w io.Writer // underlying writer; set by creator
  375. n int64
  376. err error
  377. testHookBeforeFinalWrite func(*os.File)
  378. }
  379. func (w *checkWriter) seterr(err error) error {
  380. if w.err == nil {
  381. w.err = err
  382. }
  383. return err
  384. }
  385. // Write writes p to the underlying hash and writer. The last write to the
  386. // underlying writer is guaranteed to be the last byte of p as verified by the
  387. // hash.
  388. func (w *checkWriter) Write(p []byte) (int, error) {
  389. if w.err != nil {
  390. return 0, w.err
  391. }
  392. _, err := w.h.Write(p)
  393. if err != nil {
  394. return 0, w.seterr(err)
  395. }
  396. nextSize := w.n + int64(len(p))
  397. if nextSize == w.size {
  398. // last write. check hash.
  399. sum := w.h.Sum(nil)
  400. if !bytes.Equal(sum, w.d.sum[:]) {
  401. return 0, w.seterr(fmt.Errorf("file content changed underfoot"))
  402. }
  403. if w.testHookBeforeFinalWrite != nil {
  404. w.testHookBeforeFinalWrite(w.f)
  405. }
  406. }
  407. if nextSize > w.size {
  408. return 0, w.seterr(fmt.Errorf("content exceeds expected size: %d > %d", nextSize, w.size))
  409. }
  410. n, err := w.w.Write(p)
  411. w.n += int64(n)
  412. return n, w.seterr(err)
  413. }
  414. // copyNamedFile copies file into name, expecting it to have the given Digest
  415. // and size, if that file is not present already.
  416. func (c *DiskCache) copyNamedFile(name string, file io.Reader, out Digest, size int64) error {
  417. info, err := os.Stat(name)
  418. if err == nil && info.Size() == size {
  419. // File already exists with correct size. This is good enough.
  420. // We can skip expensive hash checks.
  421. //
  422. // TODO: Do the hash check, but give caller a way to skip it.
  423. return nil
  424. }
  425. // Copy file to cache directory.
  426. mode := os.O_RDWR | os.O_CREATE
  427. if err == nil && info.Size() > size { // shouldn't happen but fix in case
  428. mode |= os.O_TRUNC
  429. }
  430. f, err := os.OpenFile(name, mode, 0o666)
  431. if err != nil {
  432. return err
  433. }
  434. defer f.Close()
  435. if size == 0 {
  436. // File now exists with correct size.
  437. // Only one possible zero-length file, so contents are OK too.
  438. // Early return here makes sure there's a "last byte" for code below.
  439. return nil
  440. }
  441. // From here on, if any of the I/O writing the file fails,
  442. // we make a best-effort attempt to truncate the file f
  443. // before returning, to avoid leaving bad bytes in the file.
  444. // Copy file to f, but also into h to double-check hash.
  445. cw := &checkWriter{
  446. d: out,
  447. size: size,
  448. h: sha256.New(),
  449. f: f,
  450. w: f,
  451. testHookBeforeFinalWrite: c.testHookBeforeFinalWrite,
  452. }
  453. n, err := io.Copy(cw, file)
  454. if err != nil {
  455. f.Truncate(0)
  456. return err
  457. }
  458. if n < size {
  459. f.Truncate(0)
  460. return io.ErrUnexpectedEOF
  461. }
  462. if err := f.Close(); err != nil {
  463. // Data might not have been written,
  464. // but file may look like it is the right size.
  465. // To be extra careful, remove cached file.
  466. os.Remove(name)
  467. return err
  468. }
  469. os.Chtimes(name, c.now(), c.now()) // mainly for tests
  470. return nil
  471. }
  472. func splitNameDigest(s string) (name, digest string) {
  473. i := strings.LastIndexByte(s, '@')
  474. if i < 0 {
  475. return s, ""
  476. }
  477. return s[:i], s[i+1:]
  478. }
  479. var errInvalidName = errors.New("invalid name")
  480. func nameToPath(name string) (_ string, err error) {
  481. n := names.Parse(name)
  482. if !n.IsFullyQualified() {
  483. return "", errInvalidName
  484. }
  485. return filepath.Join(n.Host(), n.Namespace(), n.Model(), n.Tag()), nil
  486. }
  487. func absJoin(pp ...string) string {
  488. abs, err := filepath.Abs(filepath.Join(pp...))
  489. if err != nil {
  490. panic(err) // this should never happen
  491. }
  492. return abs
  493. }