server.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. func (r *statusCodeRecorder) status() int {
  64. return cmp.Or(r._status, 200)
  65. }
  66. func (s *Local) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  67. rec := &statusCodeRecorder{ResponseWriter: w}
  68. s.serveHTTP(rec, r)
  69. }
  70. func (s *Local) serveHTTP(rec *statusCodeRecorder, r *http.Request) {
  71. var errattr slog.Attr
  72. proxied, err := func() (bool, error) {
  73. switch r.URL.Path {
  74. case "/api/delete":
  75. return false, s.handleDelete(rec, r)
  76. default:
  77. if s.Fallback != nil {
  78. s.Fallback.ServeHTTP(rec, r)
  79. return true, nil
  80. }
  81. return false, errNotFound
  82. }
  83. }()
  84. if err != nil {
  85. // We always log the error, so fill in the error log attribute
  86. errattr = slog.String("error", err.Error())
  87. var e *serverError
  88. switch {
  89. case errors.As(err, &e):
  90. case errors.Is(err, ollama.ErrNameInvalid):
  91. e = &serverError{400, "bad_request", err.Error()}
  92. default:
  93. e = errInternalError
  94. }
  95. data, err := json.Marshal(e)
  96. if err != nil {
  97. // unreachable
  98. panic(err)
  99. }
  100. rec.Header().Set("Content-Type", "application/json")
  101. rec.WriteHeader(e.Status)
  102. rec.Write(data)
  103. // fallthrough to log
  104. }
  105. if !proxied {
  106. // we're only responsible for logging if we handled the request
  107. var level slog.Level
  108. if rec.status() >= 500 {
  109. level = slog.LevelError
  110. } else if rec.status() >= 400 {
  111. level = slog.LevelWarn
  112. }
  113. s.Logger.LogAttrs(r.Context(), level, "http",
  114. errattr, // report first in line to make it easy to find
  115. // TODO(bmizerany): Write a test to ensure that we are logging
  116. // all of this correctly. That also goes for the level+error
  117. // logic above.
  118. slog.Int("status", rec.status()),
  119. slog.String("method", r.Method),
  120. slog.String("path", r.URL.Path),
  121. slog.Int64("content-length", r.ContentLength),
  122. slog.String("remote", r.RemoteAddr),
  123. slog.String("proto", r.Proto),
  124. slog.String("query", r.URL.RawQuery),
  125. )
  126. }
  127. }
  128. type params struct {
  129. DeprecatedName string `json:"name"` // Use [params.model]
  130. Model string `json:"model"` // Use [params.model]
  131. // AllowNonTLS is a flag that indicates a client using HTTP
  132. // is doing so, deliberately.
  133. //
  134. // Deprecated: This field is ignored and only present for this
  135. // deprecation message. It should be removed in a future release.
  136. //
  137. // Users can just use http or https+insecure to show intent to
  138. // communicate they want to do insecure things, without awkward and
  139. // confusing flags such as this.
  140. AllowNonTLS bool `json:"insecure"`
  141. // ProgressStream is a flag that indicates the client is expecting a stream of
  142. // progress updates.
  143. ProgressStream bool `json:"stream"`
  144. }
  145. // model returns the model name for both old and new API requests.
  146. func (p params) model() string {
  147. return cmp.Or(p.Model, p.DeprecatedName)
  148. }
  149. func (s *Local) handleDelete(_ http.ResponseWriter, r *http.Request) error {
  150. if r.Method != "DELETE" {
  151. return errMethodNotAllowed
  152. }
  153. p, err := decodeUserJSON[*params](r.Body)
  154. if err != nil {
  155. return err
  156. }
  157. ok, err := s.Client.Unlink(s.Cache, p.model())
  158. if err != nil {
  159. return err
  160. }
  161. if !ok {
  162. return &serverError{404, "manifest_not_found", "manifest not found"}
  163. }
  164. return nil
  165. }
  166. func decodeUserJSON[T any](r io.Reader) (T, error) {
  167. var v T
  168. err := json.NewDecoder(r).Decode(&v)
  169. if err == nil {
  170. return v, nil
  171. }
  172. var zero T
  173. // Not sure why, but I can't seem to be able to use:
  174. //
  175. // errors.As(err, &json.UnmarshalTypeError{})
  176. //
  177. // This is working fine in stdlib, so I'm not sure what rules changed
  178. // and why this no longer works here. So, we do it the verbose way.
  179. var a *json.UnmarshalTypeError
  180. var b *json.SyntaxError
  181. if errors.As(err, &a) || errors.As(err, &b) {
  182. err = &serverError{Status: 400, Message: err.Error(), Code: "bad_request"}
  183. }
  184. if errors.Is(err, io.EOF) {
  185. err = &serverError{Status: 400, Message: "empty request body", Code: "bad_request"}
  186. }
  187. return zero, err
  188. }