OpenStack Compute (Nova)
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.

api_version_request.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # Copyright 2014 IBM Corp.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. import re
  15. from nova import exception
  16. from nova.i18n import _
  17. # Define the minimum and maximum version of the API across all of the
  18. # REST API. The format of the version is:
  19. # X.Y where:
  20. #
  21. # - X will only be changed if a significant backwards incompatible API
  22. # change is made which affects the API as whole. That is, something
  23. # that is only very very rarely incremented.
  24. #
  25. # - Y when you make any change to the API. Note that this includes
  26. # semantic changes which may not affect the input or output formats or
  27. # even originate in the API code layer. We are not distinguishing
  28. # between backwards compatible and backwards incompatible changes in
  29. # the versioning system. It must be made clear in the documentation as
  30. # to what is a backwards compatible change and what is a backwards
  31. # incompatible one.
  32. #
  33. # You must update the API version history string below with a one or
  34. # two line description as well as update rest_api_version_history.rst
  35. REST_API_VERSION_HISTORY = """REST API Version History:
  36. * 2.1 - Initial version. Equivalent to v2.0 code
  37. * 2.2 - Adds (keypair) type parameter for os-keypairs plugin
  38. Fixes success status code for create/delete a keypair method
  39. * 2.3 - Exposes additional os-extended-server-attributes
  40. Exposes delete_on_termination for os-extended-volumes
  41. * 2.4 - Exposes reserved field in os-fixed-ips.
  42. * 2.5 - Allow server search option ip6 for non-admin
  43. * 2.6 - Consolidate the APIs for getting remote consoles
  44. * 2.7 - Check flavor type before add tenant access.
  45. * 2.8 - Add new protocol for VM console (mks)
  46. * 2.9 - Exposes lock information in server details.
  47. * 2.10 - Allow admins to query, create and delete keypairs owned by any
  48. user.
  49. * 2.11 - Exposes forced_down attribute for os-services
  50. * 2.12 - Exposes VIF net_id in os-virtual-interfaces
  51. * 2.13 - Add project id and user id information for os-server-groups API
  52. * 2.14 - Remove onSharedStorage from evacuate request body and remove
  53. adminPass from the response body
  54. * 2.15 - Add soft-affinity and soft-anti-affinity policies
  55. * 2.16 - Exposes host_status for servers/detail and servers/{server_id}
  56. * 2.17 - Add trigger_crash_dump to server actions
  57. * 2.18 - Makes project_id optional in v2.1
  58. * 2.19 - Allow user to set and get the server description
  59. * 2.20 - Add attach and detach volume operations for instances in shelved
  60. and shelved_offloaded state
  61. * 2.21 - Make os-instance-actions read deleted instances
  62. * 2.22 - Add API to force live migration to complete
  63. * 2.23 - Add index/show API for server migrations.
  64. Also add migration_type for /os-migrations and add ref link for it
  65. when the migration is an in progress live migration.
  66. * 2.24 - Add API to cancel a running live migration
  67. * 2.25 - Make block_migration support 'auto' and remove
  68. disk_over_commit for os-migrateLive.
  69. * 2.26 - Adds support of server tags
  70. * 2.27 - Adds support for new-style microversion headers while
  71. keeping support for the original style.
  72. * 2.28 - Changes compute_node.cpu_info from string to object
  73. * 2.29 - Add a force flag in evacuate request body and change the
  74. behaviour for the host flag by calling the scheduler.
  75. * 2.30 - Add a force flag in live-migrate request body and change the
  76. behaviour for the host flag by calling the scheduler.
  77. * 2.31 - Fix os-console-auth-tokens to work for all console types.
  78. * 2.32 - Add tag to networks and block_device_mapping_v2 in server boot
  79. request body.
  80. * 2.33 - Add pagination support for hypervisors.
  81. * 2.34 - Checks before live-migration are made in asynchronous way.
  82. os-Migratelive Action does not throw badRequest in case of
  83. pre-checks failure. Verification result is available over
  84. instance-actions.
  85. * 2.35 - Adds keypairs pagination support.
  86. * 2.36 - Deprecates all the API which proxy to another service and fping
  87. API.
  88. * 2.37 - Adds support for auto-allocating networking, otherwise known as
  89. "Get me a Network". Also enforces server.networks.uuid to be in
  90. UUID format.
  91. * 2.38 - Add a condition to return HTTPBadRequest if invalid status is
  92. provided for listing servers.
  93. * 2.39 - Deprecates image-metadata proxy API
  94. * 2.40 - Adds simple tenant usage pagination support.
  95. * 2.41 - Return uuid attribute for aggregates.
  96. * 2.42 - In the context of device tagging at instance boot time,
  97. re-introduce the tag attribute that, due to bugs, was lost
  98. starting with version 2.33 for block devices and starting with
  99. version 2.37 for network interfaces.
  100. * 2.43 - Deprecate os-hosts API
  101. * 2.44 - The servers action addFixedIp, removeFixedIp, addFloatingIp,
  102. removeFloatingIp and os-virtual-interfaces APIs are deprecated.
  103. * 2.45 - The createImage and createBackup APIs no longer return a Location
  104. header in the response for the snapshot image, they now return a
  105. json dict in the response body with an image_id key and uuid
  106. value.
  107. * 2.46 - Return ``X-OpenStack-Request-ID`` header on requests.
  108. * 2.47 - When displaying server details, display the flavor as a dict
  109. rather than a link. If the user is prevented from retrieving
  110. the flavor extra-specs by policy, simply omit the field from
  111. the output.
  112. * 2.48 - Standardize VM diagnostics info.
  113. * 2.49 - Support tagged attachment of network interfaces and block devices.
  114. * 2.50 - Exposes ``server_groups`` and ``server_group_members`` keys in
  115. GET & PUT ``os-quota-class-sets`` APIs response.
  116. Also filter out Network related quotas from
  117. ``os-quota-class-sets`` API
  118. * 2.51 - Adds new event name to external-events (volume-extended). Also,
  119. non-admins can see instance action event details except for the
  120. traceback field.
  121. * 2.52 - Adds support for applying tags when creating a server.
  122. * 2.53 - Service and compute node (hypervisor) database ids are hidden.
  123. The os-services and os-hypervisors APIs now return a uuid in the
  124. id field, and takes a uuid in requests. PUT and GET requests
  125. and responses are also changed.
  126. * 2.54 - Enable reset key pair while rebuilding instance.
  127. * 2.55 - Added flavor.description to GET/POST/PUT flavors APIs.
  128. * 2.56 - Add a host parameter in migrate request body in order to
  129. enable users to specify a target host in cold migration.
  130. The target host is checked by the scheduler.
  131. * 2.57 - Deprecated personality files from POST /servers and the rebuild
  132. server action APIs. Added the ability to pass new user_data to
  133. the rebuild server action API. Personality / file injection
  134. related limits and quota resources are also removed.
  135. * 2.58 - Add pagination support and changes-since filter for
  136. os-instance-actions API.
  137. * 2.59 - Add pagination support and changes-since filter for os-migrations
  138. API. And the os-migrations API now returns both the id and the
  139. uuid in response.
  140. * 2.60 - Add support for attaching a single volume to multiple instances.
  141. * 2.61 - Exposes flavor extra_specs in the flavor representation. Flavor
  142. extra_specs will be included in Response body of GET, POST, PUT
  143. /flavors APIs.
  144. * 2.62 - Add ``host`` and ``hostId`` fields to instance action detail API
  145. responses.
  146. * 2.63 - Add support for applying trusted certificates when creating or
  147. rebuilding a server.
  148. * 2.64 - Add support for the "max_server_per_host" policy rule for
  149. ``anti-affinity`` server group policy, the ``policies`` and
  150. ``metadata`` fields are removed and the ``policy`` (required)
  151. and ``rules`` (optional) fields are added in response body of
  152. GET, POST /os-server-groups APIs and GET
  153. /os-server-groups/{group_id} API.
  154. * 2.65 - Add support for abort live migrations in ``queued`` and
  155. ``preparing`` status.
  156. * 2.66 - Add ``changes-before`` to support users to specify the
  157. ``updated_at`` time to filter nova resources, the resources
  158. include the servers API, os-instance-action API and
  159. os-migrations API.
  160. * 2.67 - Adds the optional ``volume_type`` field to the
  161. ``block_device_mapping_v2`` parameter when creating a server.
  162. * 2.68 - Remove support for forced live migration and evacuate server
  163. actions.
  164. * 2.69 - Add support for returning minimal constructs for ``GET /servers``,
  165. ``GET /servers/detail``, ``GET /servers/{server_id}`` and
  166. ``GET /os-services`` when there is a transient unavailability
  167. condition in the deployment like an infrastructure failure.
  168. * 2.70 - Exposes virtual device tags in the response of the
  169. ``os-volume_attachments`` and ``os-interface`` APIs.
  170. * 2.71 - Adds the ``server_groups`` field to ``GET /servers/{id}``,
  171. ``PUT /servers/{server_id}`` and
  172. ``POST /servers/{server_id}/action`` (rebuild) responses.
  173. * 2.72 - Add support for neutron ports with resource request during server
  174. create. Server move operations are not yet supported for servers
  175. with such ports.
  176. * 2.73 - Adds support for specifying a reason when locking the server and
  177. exposes this via the response from ``GET /servers/detail``,
  178. ``GET /servers/{server_id}``, ``PUT servers/{server_id}`` and
  179. ``POST /servers/{server_id}/action`` where the action is rebuild.
  180. It also supports ``locked`` as a filter/sort parameter for
  181. ``GET /servers/detail`` and ``GET /servers``.
  182. """
  183. # The minimum and maximum versions of the API supported
  184. # The default api version request is defined to be the
  185. # minimum version of the API supported.
  186. # Note(cyeoh): This only applies for the v2.1 API once microversions
  187. # support is fully merged. It does not affect the V2 API.
  188. _MIN_API_VERSION = "2.1"
  189. _MAX_API_VERSION = "2.73"
  190. DEFAULT_API_VERSION = _MIN_API_VERSION
  191. # Almost all proxy APIs which are related to network, images and baremetal
  192. # were deprecated from 2.36.
  193. MAX_PROXY_API_SUPPORT_VERSION = '2.35'
  194. MIN_WITHOUT_PROXY_API_SUPPORT_VERSION = '2.36'
  195. # Starting from microversion 2.39 also image-metadata proxy API is deprecated.
  196. MAX_IMAGE_META_PROXY_API_VERSION = '2.38'
  197. MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION = '2.39'
  198. # NOTE(cyeoh): min and max versions declared as functions so we can
  199. # mock them for unittests. Do not use the constants directly anywhere
  200. # else.
  201. def min_api_version():
  202. return APIVersionRequest(_MIN_API_VERSION)
  203. def max_api_version():
  204. return APIVersionRequest(_MAX_API_VERSION)
  205. def is_supported(req, min_version=_MIN_API_VERSION,
  206. max_version=_MAX_API_VERSION):
  207. """Check if API request version satisfies version restrictions.
  208. :param req: request object
  209. :param min_version: minimal version of API needed for correct
  210. request processing
  211. :param max_version: maximum version of API needed for correct
  212. request processing
  213. :returns: True if request satisfies minimal and maximum API version
  214. requirements. False in other case.
  215. """
  216. return (APIVersionRequest(max_version) >= req.api_version_request >=
  217. APIVersionRequest(min_version))
  218. class APIVersionRequest(object):
  219. """This class represents an API Version Request with convenience
  220. methods for manipulation and comparison of version
  221. numbers that we need to do to implement microversions.
  222. """
  223. def __init__(self, version_string=None):
  224. """Create an API version request object.
  225. :param version_string: String representation of APIVersionRequest.
  226. Correct format is 'X.Y', where 'X' and 'Y' are int values.
  227. None value should be used to create Null APIVersionRequest,
  228. which is equal to 0.0
  229. """
  230. self.ver_major = 0
  231. self.ver_minor = 0
  232. if version_string is not None:
  233. match = re.match(r"^([1-9]\d*)\.([1-9]\d*|0)$",
  234. version_string)
  235. if match:
  236. self.ver_major = int(match.group(1))
  237. self.ver_minor = int(match.group(2))
  238. else:
  239. raise exception.InvalidAPIVersionString(version=version_string)
  240. def __str__(self):
  241. """Debug/Logging representation of object."""
  242. return ("API Version Request Major: %s, Minor: %s"
  243. % (self.ver_major, self.ver_minor))
  244. def is_null(self):
  245. return self.ver_major == 0 and self.ver_minor == 0
  246. def _format_type_error(self, other):
  247. return TypeError(_("'%(other)s' should be an instance of '%(cls)s'") %
  248. {"other": other, "cls": self.__class__})
  249. def __lt__(self, other):
  250. if not isinstance(other, APIVersionRequest):
  251. raise self._format_type_error(other)
  252. return ((self.ver_major, self.ver_minor) <
  253. (other.ver_major, other.ver_minor))
  254. def __eq__(self, other):
  255. if not isinstance(other, APIVersionRequest):
  256. raise self._format_type_error(other)
  257. return ((self.ver_major, self.ver_minor) ==
  258. (other.ver_major, other.ver_minor))
  259. def __gt__(self, other):
  260. if not isinstance(other, APIVersionRequest):
  261. raise self._format_type_error(other)
  262. return ((self.ver_major, self.ver_minor) >
  263. (other.ver_major, other.ver_minor))
  264. def __le__(self, other):
  265. return self < other or self == other
  266. def __ne__(self, other):
  267. return not self.__eq__(other)
  268. def __ge__(self, other):
  269. return self > other or self == other
  270. def matches(self, min_version, max_version):
  271. """Returns whether the version object represents a version
  272. greater than or equal to the minimum version and less than
  273. or equal to the maximum version.
  274. @param min_version: Minimum acceptable version.
  275. @param max_version: Maximum acceptable version.
  276. @returns: boolean
  277. If min_version is null then there is no minimum limit.
  278. If max_version is null then there is no maximum limit.
  279. If self is null then raise ValueError
  280. """
  281. if self.is_null():
  282. raise ValueError
  283. if max_version.is_null() and min_version.is_null():
  284. return True
  285. elif max_version.is_null():
  286. return min_version <= self
  287. elif min_version.is_null():
  288. return self <= max_version
  289. else:
  290. return min_version <= self <= max_version
  291. def get_string(self):
  292. """Converts object to string representation which if used to create
  293. an APIVersionRequest object results in the same version request.
  294. """
  295. if self.is_null():
  296. raise ValueError
  297. return "%s.%s" % (self.ver_major, self.ver_minor)