server.go 6.5 KB

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