server.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Package registry provides an http.Handler for handling local Ollama API
  2. // requests for performing tasks related to the ollama.com model registry and
  3. // the local disk cache.
  4. package registry
  5. import (
  6. "cmp"
  7. "encoding/json"
  8. "errors"
  9. "io"
  10. "log/slog"
  11. "net/http"
  12. "github.com/ollama/ollama/server/internal/cache/blob"
  13. "github.com/ollama/ollama/server/internal/client/ollama"
  14. )
  15. // Local is an http.Handler for handling local Ollama API requests for
  16. // performing tasks related to the ollama.com model registry combined with the
  17. // local disk cache.
  18. //
  19. // It is not concern of Local, or this package, to handle model creation, which
  20. // proceeds any registry operations for models it produces.
  21. //
  22. // NOTE: The package built for dealing with model creation should use
  23. // [DefaultCache] to access the blob store and not attempt to read or write
  24. // directly to the blob disk cache.
  25. type Local struct {
  26. Client *ollama.Registry // required
  27. Cache *blob.DiskCache // required
  28. Logger *slog.Logger // required
  29. // Fallback, if set, is used to handle requests that are not handled by
  30. // this handler.
  31. Fallback http.Handler
  32. }
  33. // serverError is like ollama.Error, but with a Status field for the HTTP
  34. // response code. We want to avoid adding that field to ollama.Error because it
  35. // would always be 0 to clients (we don't want to leak the status code in
  36. // errors), and so it would be confusing to have a field that is always 0.
  37. type serverError struct {
  38. Status int `json:"-"`
  39. // TODO(bmizerany): Decide if we want to keep this and maybe
  40. // bring back later.
  41. Code string `json:"code"`
  42. Message string `json:"error"`
  43. }
  44. func (e serverError) Error() string {
  45. return e.Message
  46. }
  47. // Common API errors
  48. var (
  49. errMethodNotAllowed = &serverError{405, "method_not_allowed", "method not allowed"}
  50. errNotFound = &serverError{404, "not_found", "not found"}
  51. errInternalError = &serverError{500, "internal_error", "internal server error"}
  52. )
  53. type statusCodeRecorder struct {
  54. _status int // use status() to get the status code
  55. http.ResponseWriter
  56. }
  57. func (r *statusCodeRecorder) WriteHeader(status int) {
  58. if r._status == 0 {
  59. r._status = status
  60. }
  61. r.ResponseWriter.WriteHeader(status)
  62. }
  63. var (
  64. _ http.ResponseWriter = (*statusCodeRecorder)(nil)
  65. _ http.CloseNotifier = (*statusCodeRecorder)(nil)
  66. _ http.Flusher = (*statusCodeRecorder)(nil)
  67. )
  68. // CloseNotify implements the http.CloseNotifier interface, for Gin. Remove with Gin.
  69. //
  70. // It panics if the underlying ResponseWriter is not a CloseNotifier.
  71. func (r *statusCodeRecorder) CloseNotify() <-chan bool {
  72. return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
  73. }
  74. // Flush implements the http.Flusher interface, for Gin. Remove with Gin.
  75. //
  76. // It panics if the underlying ResponseWriter is not a Flusher.
  77. func (r *statusCodeRecorder) Flush() {
  78. r.ResponseWriter.(http.Flusher).Flush()
  79. }
  80. func (r *statusCodeRecorder) status() int {
  81. return cmp.Or(r._status, 200)
  82. }
  83. func (s *Local) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  84. rec := &statusCodeRecorder{ResponseWriter: w}
  85. s.serveHTTP(rec, r)
  86. }
  87. func (s *Local) serveHTTP(rec *statusCodeRecorder, r *http.Request) {
  88. var errattr slog.Attr
  89. proxied, err := func() (bool, error) {
  90. switch r.URL.Path {
  91. case "/api/delete":
  92. return false, s.handleDelete(rec, r)
  93. default:
  94. if s.Fallback != nil {
  95. s.Fallback.ServeHTTP(rec, r)
  96. return true, nil
  97. }
  98. return false, errNotFound
  99. }
  100. }()
  101. if err != nil {
  102. // We always log the error, so fill in the error log attribute
  103. errattr = slog.String("error", err.Error())
  104. var e *serverError
  105. switch {
  106. case errors.As(err, &e):
  107. case errors.Is(err, ollama.ErrNameInvalid):
  108. e = &serverError{400, "bad_request", err.Error()}
  109. default:
  110. e = errInternalError
  111. }
  112. data, err := json.Marshal(e)
  113. if err != nil {
  114. // unreachable
  115. panic(err)
  116. }
  117. rec.Header().Set("Content-Type", "application/json")
  118. rec.WriteHeader(e.Status)
  119. rec.Write(data)
  120. // fallthrough to log
  121. }
  122. if !proxied {
  123. // we're only responsible for logging if we handled the request
  124. var level slog.Level
  125. if rec.status() >= 500 {
  126. level = slog.LevelError
  127. } else if rec.status() >= 400 {
  128. level = slog.LevelWarn
  129. }
  130. s.Logger.LogAttrs(r.Context(), level, "http",
  131. errattr, // report first in line to make it easy to find
  132. // TODO(bmizerany): Write a test to ensure that we are logging
  133. // all of this correctly. That also goes for the level+error
  134. // logic above.
  135. slog.Int("status", rec.status()),
  136. slog.String("method", r.Method),
  137. slog.String("path", r.URL.Path),
  138. slog.Int64("content-length", r.ContentLength),
  139. slog.String("remote", r.RemoteAddr),
  140. slog.String("proto", r.Proto),
  141. slog.String("query", r.URL.RawQuery),
  142. )
  143. }
  144. }
  145. type params struct {
  146. DeprecatedName string `json:"name"` // Use [params.model]
  147. Model string `json:"model"` // Use [params.model]
  148. // AllowNonTLS is a flag that indicates a client using HTTP
  149. // is doing so, deliberately.
  150. //
  151. // Deprecated: This field is ignored and only present for this
  152. // deprecation message. It should be removed in a future release.
  153. //
  154. // Users can just use http or https+insecure to show intent to
  155. // communicate they want to do insecure things, without awkward and
  156. // confusing flags such as this.
  157. AllowNonTLS bool `json:"insecure"`
  158. // ProgressStream is a flag that indicates the client is expecting a stream of
  159. // progress updates.
  160. ProgressStream bool `json:"stream"`
  161. }
  162. // model returns the model name for both old and new API requests.
  163. func (p params) model() string {
  164. return cmp.Or(p.Model, p.DeprecatedName)
  165. }
  166. func (s *Local) handleDelete(_ http.ResponseWriter, r *http.Request) error {
  167. if r.Method != "DELETE" {
  168. return errMethodNotAllowed
  169. }
  170. p, err := decodeUserJSON[*params](r.Body)
  171. if err != nil {
  172. return err
  173. }
  174. ok, err := s.Client.Unlink(s.Cache, p.model())
  175. if err != nil {
  176. return err
  177. }
  178. if !ok {
  179. return &serverError{404, "not_found", "model not found"}
  180. }
  181. return nil
  182. }
  183. func decodeUserJSON[T any](r io.Reader) (T, error) {
  184. var v T
  185. err := json.NewDecoder(r).Decode(&v)
  186. if err == nil {
  187. return v, nil
  188. }
  189. var zero T
  190. // Not sure why, but I can't seem to be able to use:
  191. //
  192. // errors.As(err, &json.UnmarshalTypeError{})
  193. //
  194. // This is working fine in stdlib, so I'm not sure what rules changed
  195. // and why this no longer works here. So, we do it the verbose way.
  196. var a *json.UnmarshalTypeError
  197. var b *json.SyntaxError
  198. if errors.As(err, &a) || errors.As(err, &b) {
  199. err = &serverError{Status: 400, Message: err.Error(), Code: "bad_request"}
  200. }
  201. if errors.Is(err, io.EOF) {
  202. err = &serverError{Status: 400, Message: "empty request body", Code: "bad_request"}
  203. }
  204. return zero, err
  205. }