version.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package middleware // import "github.com/docker/docker/api/server/middleware"
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "runtime"
  7. "github.com/docker/docker/api/server/httputils"
  8. "github.com/docker/docker/api/types/versions"
  9. )
  10. // VersionMiddleware is a middleware that
  11. // validates the client and server versions.
  12. type VersionMiddleware struct {
  13. serverVersion string
  14. defaultVersion string
  15. minVersion string
  16. }
  17. // NewVersionMiddleware creates a new VersionMiddleware
  18. // with the default versions.
  19. func NewVersionMiddleware(s, d, m string) VersionMiddleware {
  20. return VersionMiddleware{
  21. serverVersion: s,
  22. defaultVersion: d,
  23. minVersion: m,
  24. }
  25. }
  26. type versionUnsupportedError struct {
  27. version, minVersion, maxVersion string
  28. }
  29. func (e versionUnsupportedError) Error() string {
  30. if e.minVersion != "" {
  31. return fmt.Sprintf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", e.version, e.minVersion)
  32. }
  33. return fmt.Sprintf("client version %s is too new. Maximum supported API version is %s", e.version, e.maxVersion)
  34. }
  35. func (e versionUnsupportedError) InvalidParameter() {}
  36. // WrapHandler returns a new handler function wrapping the previous one in the request chain.
  37. func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  38. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  39. w.Header().Set("Server", fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS))
  40. w.Header().Set("API-Version", v.defaultVersion)
  41. w.Header().Set("OSType", runtime.GOOS)
  42. apiVersion := vars["version"]
  43. if apiVersion == "" {
  44. apiVersion = v.defaultVersion
  45. }
  46. if versions.LessThan(apiVersion, v.minVersion) {
  47. return versionUnsupportedError{version: apiVersion, minVersion: v.minVersion}
  48. }
  49. if versions.GreaterThan(apiVersion, v.defaultVersion) {
  50. return versionUnsupportedError{version: apiVersion, maxVersion: v.defaultVersion}
  51. }
  52. ctx = context.WithValue(ctx, httputils.APIVersionKey{}, apiVersion)
  53. return handler(ctx, w, r, vars)
  54. }
  55. }