assets.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package gpu
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. )
  15. var (
  16. lock sync.Mutex
  17. payloadsDir = ""
  18. )
  19. func PayloadsDir() (string, error) {
  20. lock.Lock()
  21. defer lock.Unlock()
  22. var err error
  23. if payloadsDir == "" {
  24. runnersDir := os.Getenv("OLLAMA_RUNNERS_DIR")
  25. // On Windows we do not carry the payloads inside the main executable
  26. if runtime.GOOS == "windows" && runnersDir == "" {
  27. appExe, err := os.Executable()
  28. if err != nil {
  29. slog.Error("failed to lookup executable path", "error", err)
  30. return "", err
  31. }
  32. // Try a few variations to improve developer experience when building from source in the local tree
  33. for _, d := range []string{".", "windows-" + runtime.GOARCH, "dist\\windows-" + runtime.GOARCH} {
  34. candidate := filepath.Join(filepath.Dir(appExe), d, "ollama_runners")
  35. _, err := os.Stat(candidate)
  36. if err == nil {
  37. runnersDir = candidate
  38. break
  39. }
  40. }
  41. if runnersDir == "" {
  42. err = fmt.Errorf("unable to locate llm runner directory. Set OLLAMA_RUNNERS_DIR to the location of 'ollama_runners'")
  43. slog.Error("incomplete distribution", "error", err)
  44. return "", err
  45. }
  46. }
  47. if runnersDir != "" {
  48. payloadsDir = runnersDir
  49. return payloadsDir, nil
  50. }
  51. // The remainder only applies on non-windows where we still carry payloads in the main executable
  52. cleanupTmpDirs()
  53. tmpDir := os.Getenv("OLLAMA_TMPDIR")
  54. if tmpDir == "" {
  55. tmpDir, err = os.MkdirTemp("", "ollama")
  56. if err != nil {
  57. return "", fmt.Errorf("failed to generate tmp dir: %w", err)
  58. }
  59. } else {
  60. err = os.MkdirAll(tmpDir, 0755)
  61. if err != nil {
  62. return "", fmt.Errorf("failed to generate tmp dir %s: %w", tmpDir, err)
  63. }
  64. }
  65. // Track our pid so we can clean up orphaned tmpdirs
  66. pidFilePath := filepath.Join(tmpDir, "ollama.pid")
  67. pidFile, err := os.OpenFile(pidFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.ModePerm)
  68. if err != nil {
  69. return "", err
  70. }
  71. if _, err := pidFile.Write([]byte(fmt.Sprint(os.Getpid()))); err != nil {
  72. return "", err
  73. }
  74. // We create a distinct subdirectory for payloads within the tmpdir
  75. // This will typically look like /tmp/ollama3208993108/runners on linux
  76. payloadsDir = filepath.Join(tmpDir, "runners")
  77. }
  78. return payloadsDir, nil
  79. }
  80. // Best effort to clean up prior tmpdirs
  81. func cleanupTmpDirs() {
  82. dirs, err := filepath.Glob(filepath.Join(os.TempDir(), "ollama*"))
  83. if err != nil {
  84. return
  85. }
  86. for _, d := range dirs {
  87. info, err := os.Stat(d)
  88. if err != nil || !info.IsDir() {
  89. continue
  90. }
  91. raw, err := os.ReadFile(filepath.Join(d, "ollama.pid"))
  92. if err == nil {
  93. pid, err := strconv.Atoi(string(raw))
  94. if err == nil {
  95. if proc, err := os.FindProcess(int(pid)); err == nil && !errors.Is(proc.Signal(syscall.Signal(0)), os.ErrProcessDone) {
  96. // Another running ollama, ignore this tmpdir
  97. continue
  98. }
  99. }
  100. } else {
  101. slog.Debug("failed to open ollama.pid", "path", d, "error", err)
  102. }
  103. err = os.RemoveAll(d)
  104. if err != nil {
  105. slog.Debug("unable to cleanup stale tmpdir", "path", d, "error", err)
  106. }
  107. }
  108. }
  109. func Cleanup() {
  110. lock.Lock()
  111. defer lock.Unlock()
  112. runnersDir := os.Getenv("OLLAMA_RUNNERS_DIR")
  113. if payloadsDir != "" && runnersDir == "" && runtime.GOOS != "windows" {
  114. // We want to fully clean up the tmpdir parent of the payloads dir
  115. tmpDir := filepath.Clean(filepath.Join(payloadsDir, ".."))
  116. slog.Debug("cleaning up", "dir", tmpDir)
  117. err := os.RemoveAll(tmpDir)
  118. if err != nil {
  119. // On windows, if we remove too quickly the llama.dll may still be in-use and fail to remove
  120. time.Sleep(1000 * time.Millisecond)
  121. err = os.RemoveAll(tmpDir)
  122. if err != nil {
  123. slog.Warn("failed to clean up", "dir", tmpDir, "err", err)
  124. }
  125. }
  126. }
  127. }
  128. func UpdatePath(dir string) {
  129. if runtime.GOOS == "windows" {
  130. tmpDir := filepath.Dir(dir)
  131. pathComponents := strings.Split(os.Getenv("PATH"), ";")
  132. i := 0
  133. for _, comp := range pathComponents {
  134. if strings.EqualFold(comp, dir) {
  135. return
  136. }
  137. // Remove any other prior paths to our temp dir
  138. if !strings.HasPrefix(strings.ToLower(comp), strings.ToLower(tmpDir)) {
  139. pathComponents[i] = comp
  140. i++
  141. }
  142. }
  143. newPath := strings.Join(append([]string{dir}, pathComponents...), ";")
  144. slog.Info("updating", "PATH", newPath)
  145. os.Setenv("PATH", newPath)
  146. }
  147. // linux and darwin rely on rpath
  148. }