OpenStack Image Management (Glance)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

version_negotiation.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Copyright 2011 OpenStack Foundation
  2. # All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """
  16. A filter middleware that inspects the requested URI for a version string
  17. and/or Accept headers and attempts to negotiate an API controller to
  18. return
  19. """
  20. from oslo_config import cfg
  21. from oslo_log import log as logging
  22. from glance.api import versions
  23. from glance.common import wsgi
  24. CONF = cfg.CONF
  25. LOG = logging.getLogger(__name__)
  26. class VersionNegotiationFilter(wsgi.Middleware):
  27. def __init__(self, app):
  28. self.versions_app = versions.Controller()
  29. self.allowed_versions = None
  30. self.vnd_mime_type = 'application/vnd.openstack.images-'
  31. super(VersionNegotiationFilter, self).__init__(app)
  32. def process_request(self, req):
  33. """Try to find a version first in the accept header, then the URL"""
  34. args = {'method': req.method, 'path': req.path, 'accept': req.accept}
  35. LOG.debug("Determining version of request: %(method)s %(path)s "
  36. "Accept: %(accept)s", args)
  37. # If the request is for /versions, just return the versions container
  38. if req.path_info_peek() == "versions":
  39. return self.versions_app.index(req, explicit=True)
  40. accept = str(req.accept)
  41. if accept.startswith(self.vnd_mime_type):
  42. LOG.debug("Using media-type versioning")
  43. token_loc = len(self.vnd_mime_type)
  44. req_version = accept[token_loc:]
  45. else:
  46. LOG.debug("Using url versioning")
  47. # Remove version in url so it doesn't conflict later
  48. req_version = self._pop_path_info(req)
  49. try:
  50. version = self._match_version_string(req_version)
  51. except ValueError:
  52. LOG.debug("Unknown version. Returning version choices.")
  53. return self.versions_app
  54. req.environ['api.version'] = version
  55. req.path_info = ''.join(('/v', str(version), req.path_info))
  56. LOG.debug("Matched version: v%d", version)
  57. LOG.debug('new path %s', req.path_info)
  58. return None
  59. def _get_allowed_versions(self):
  60. allowed_versions = {}
  61. if CONF.enable_v2_api:
  62. allowed_versions['v2'] = 2
  63. allowed_versions['v2.0'] = 2
  64. allowed_versions['v2.1'] = 2
  65. allowed_versions['v2.2'] = 2
  66. allowed_versions['v2.3'] = 2
  67. allowed_versions['v2.4'] = 2
  68. allowed_versions['v2.5'] = 2
  69. allowed_versions['v2.6'] = 2
  70. return allowed_versions
  71. def _match_version_string(self, subject):
  72. """
  73. Given a string, tries to match a major and/or
  74. minor version number.
  75. :param subject: The string to check
  76. :returns: version found in the subject
  77. :raises ValueError: if no acceptable version could be found
  78. """
  79. if self.allowed_versions is None:
  80. self.allowed_versions = self._get_allowed_versions()
  81. if subject in self.allowed_versions:
  82. return self.allowed_versions[subject]
  83. else:
  84. raise ValueError()
  85. def _pop_path_info(self, req):
  86. """
  87. 'Pops' off the next segment of PATH_INFO, returns the popped
  88. segment. Do NOT push it onto SCRIPT_NAME.
  89. """
  90. path = req.path_info
  91. if not path:
  92. return None
  93. while path.startswith('/'):
  94. path = path[1:]
  95. idx = path.find('/')
  96. if idx == -1:
  97. idx = len(path)
  98. r = path[:idx]
  99. req.path_info = path[idx:]
  100. return r