├── .gitignore ├── .gitreview ├── .pre-commit-config.yaml ├── .stestr.conf ├── .zuul.yaml ├── LICENSE ├── Makefile ├── README.rst ├── doc ├── requirements.txt └── source │ ├── conf.py │ └── index.rst ├── microversion_parse ├── __init__.py ├── middleware.py └── tests │ ├── __init__.py │ ├── gabbits │ ├── middleware.yaml │ └── simple.yaml │ ├── test_extract_version.py │ ├── test_get_version.py │ ├── test_headers_from_wsgi_environ.py │ ├── test_middleware.py │ └── test_webob.py ├── releasenotes └── notes │ └── drop-python27-support-5b9a4e0ce63b730e.yaml ├── requirements.txt ├── setup.cfg ├── setup.py ├── test-requirements.txt └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | .stestr 65 | cover 66 | -------------------------------------------------------------------------------- /.gitreview: -------------------------------------------------------------------------------- 1 | [gerrit] 2 | host=review.opendev.org 3 | port=29418 4 | project=openstack/microversion-parse.git 5 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # We from the Oslo project decided to pin repos based on the 2 | # commit hash instead of the version tag to prevend arbitrary 3 | # code from running in developer's machines. To update to a 4 | # newer version, run `pre-commit autoupdate` and then replace 5 | # the newer versions with their commit hash. 6 | 7 | default_language_version: 8 | python: python3 9 | 10 | repos: 11 | - repo: https://github.com/pre-commit/pre-commit-hooks 12 | rev: 9136088a246768144165fcc3ecc3d31bb686920a # v3.3.0 13 | hooks: 14 | - id: trailing-whitespace 15 | # Replaces or checks mixed line ending 16 | - id: mixed-line-ending 17 | args: ['--fix', 'lf'] 18 | exclude: '.*\.(svg)$' 19 | # Forbid files which have a UTF-8 byte-order marker 20 | - id: check-byte-order-marker 21 | # Checks that non-binary executables have a proper shebang 22 | - id: check-executables-have-shebangs 23 | # Check for files that contain merge conflict strings. 24 | - id: check-merge-conflict 25 | # Check for debugger imports and py37+ breakpoint() 26 | # calls in python source 27 | - id: debug-statements 28 | - id: check-yaml 29 | files: .*\.(yaml|yml)$ 30 | - repo: local 31 | hooks: 32 | - id: flake8 33 | name: flake8 34 | additional_dependencies: 35 | - hacking>=6.1.0,<6.2.0 36 | language: python 37 | entry: flake8 38 | files: '^.*\.py$' 39 | exclude: '^(doc|releasenotes|tools)/.*$' 40 | -------------------------------------------------------------------------------- /.stestr.conf: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | test_path=./microversion_parse/tests 3 | top_dir=./ 4 | # This regex ensures each yaml file used by gabbi is run in only one 5 | # process. 6 | group_regex=microversion_parse\.tests\.test_middleware(?:\.|_)([^_]+) 7 | -------------------------------------------------------------------------------- /.zuul.yaml: -------------------------------------------------------------------------------- 1 | - project: 2 | templates: 3 | - openstack-python3-jobs 4 | - check-requirements 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # simple Makefile for some common tasks 2 | .PHONY: clean test dist release pypi tagv docs 3 | 4 | clean: 5 | find . -name "*.pyc" |xargs rm || true 6 | rm -r dist || true 7 | rm -r build || true 8 | rm -r .tox || true 9 | rm -r .testrepository || true 10 | rm -r cover .coverage || true 11 | rm -r .eggs || true 12 | rm -r microversion_parse.egg-info || true 13 | 14 | tagv: 15 | git tag \ 16 | -m `python -c 'import microversion_parse; print microversion_parse.__version__'` \ 17 | `python -c 'import microversion_parse; print microversion_parse.__version__'` 18 | git push origin master --tags 19 | 20 | cleanagain: 21 | find . -name "*.pyc" |xargs rm || true 22 | rm -r dist || true 23 | rm -r build || true 24 | rm -r .tox || true 25 | rm -r .testrepository || true 26 | rm -r cover .coverage || true 27 | rm -r .eggs || true 28 | rm -r microversion_parse.egg-info || true 29 | 30 | docs: 31 | cd docs ; $(MAKE) html 32 | 33 | test: 34 | tox --skip-missing-interpreters 35 | 36 | dist: test 37 | python setup.py sdist 38 | 39 | release: clean test cleanagain tagv pypi 40 | 41 | pypi: 42 | python setup.py sdist upload 43 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | microversion_parse 2 | ================== 3 | 4 | A small set of functions to manage OpenStack `microversion`_ headers that can 5 | be used in middleware, application handlers and decorators to effectively 6 | manage microversions. 7 | 8 | Also included, in the ``middleware`` module, is a ``MicroversionMiddleware`` 9 | that will process incoming microversion headers. 10 | 11 | get_version 12 | ----------- 13 | 14 | A simple parser for OpenStack microversion headers:: 15 | 16 | import microversion_parse 17 | 18 | # headers is a dict of headers with folded (comma-separated 19 | # values) or a list of header, value tuples 20 | version = microversion_parse.get_version( 21 | headers, service_type='compute', 22 | legacy_headers=['x-openstack-nova-api-version']) 23 | 24 | # If headers are not already available, a dict of headers 25 | # can be extracted from the WSGI environ 26 | headers = microversion_parse.headers_from_wsgi_environ(environ) 27 | version = microversion_parse.get_version( 28 | headers, service_type='placement') 29 | 30 | It processes microversion headers with the standard form:: 31 | 32 | OpenStack-API-Version: compute 2.1 33 | 34 | In that case, the response will be '2.1'. 35 | 36 | If provided with a ``legacy_headers`` argument, this is treated as 37 | a list of additional headers to check for microversions. Some examples of 38 | headers include:: 39 | 40 | OpenStack-telemetry-api-version: 2.1 41 | OpenStack-nova-api-version: 2.1 42 | X-OpenStack-nova-api-version: 2.1 43 | 44 | If a version string cannot be found, ``None`` will be returned. If 45 | the input is incorrect usual Python exceptions (ValueError, 46 | TypeError) are allowed to raise to the caller. 47 | 48 | parse_version_string 49 | -------------------- 50 | 51 | A function to turn a version string into a ``Version``, a comparable 52 | ``namedtuple``:: 53 | 54 | version_tuple = microversion_parse.parse_version_string('2.1') 55 | 56 | If the provided string is not a valid microversion string, ``TypeError`` 57 | is raised. 58 | 59 | extract_version 60 | --------------- 61 | 62 | Combines ``get_version`` and ``parse_version_string`` to find and validate 63 | a microversion for a given service type in a collection of headers:: 64 | 65 | version_tuple = microversion_parse.extract_version( 66 | headers, # a representation of headers, as accepted by get_version 67 | service_type, # service type identify to match in headers 68 | versions_list, # an ordered list of strings of version numbers that 69 | # are the valid versions presented by this service 70 | ) 71 | 72 | ``latest`` will be translated to whatever the max version is in versions_list. 73 | 74 | If the found version is not in versions_list a ``ValueError`` is raised. 75 | 76 | Note that ``extract_version`` does not support ``legacy_headers``. 77 | 78 | MicroversionMiddleware 79 | ---------------------- 80 | 81 | A WSGI middleware that can wrap an application that needs to be microversion 82 | aware. The application will get a WSGI environ with a 83 | 'SERVICE_TYPE.microversion' key that has a value of the microversion found at 84 | an 'openstack-api-version' header that matches SERVICE_TYPE. If no header is 85 | found, the minimum microversion will be set. If the special keyword 'latest' is 86 | used, the maximum microversion will be set. 87 | 88 | If the requested microversion is not available a 406 response is returned. 89 | 90 | If there is an error parsing a provided header, a 400 response is returned. 91 | 92 | Otherwise the application is called. 93 | 94 | The middleware is configured when it is created. Three parameters are required: 95 | 96 | app 97 | The next WSGI middleware or application in the stack. 98 | 99 | service_type 100 | The service type of the application, used to identify microversion headers. 101 | 102 | versions_list 103 | An ordered list of legitimate microversions (as strings) for the application. 104 | It's assumed that any application that is using microversions will have such 105 | a list for its own housekeeping and documentation. 106 | 107 | One named parameter is optional: 108 | 109 | json_error_formatter 110 | A Webob error formatter that can be used to structure the response when JSON 111 | is expected. 112 | 113 | For example:: 114 | 115 | def app(): 116 | app = middleware.MicroversionMiddleware( 117 | MyWSGIApp(), 'cats', ['1.0', '1.1', '1.2']) 118 | return app 119 | 120 | 121 | .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html 122 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | openstackdocstheme>=1.18.1 # Apache-2.0 2 | sphinx!=1.6.6,!=1.6.7,>=1.6.2 # BSD 3 | -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2020 Red Hat, Inc. 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 | # microversion-parse documentation build configuration file, created by 17 | # sphinx-quickstart on Thu Mar 31 11:40:03 2016. 18 | # 19 | # This file is execfile()d with the current directory set to its 20 | # containing dir. 21 | # 22 | # Note that not all possible configuration values are present in this 23 | # autogenerated file. 24 | # 25 | # All configuration values have a default; values that are commented out 26 | # serve to show the default. 27 | 28 | # -- General configuration ------------------------------------------------ 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | 'sphinx.ext.intersphinx', 36 | 'openstackdocstheme' 37 | ] 38 | 39 | # Add any paths that contain templates here, relative to this directory. 40 | templates_path = ['_templates'] 41 | 42 | # The suffix(es) of source filenames. 43 | # You can specify multiple suffix as a list of string: 44 | # source_suffix = ['.rst', '.md'] 45 | source_suffix = '.rst' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = 'microversion-parse' 52 | copyright = '2016, OpenStack' 53 | author = u'OpenStack' 54 | 55 | # openstackdocstheme options 56 | repository_name = 'openstack/microversion-parse' 57 | bug_project = 'microversion-parse' 58 | bug_tag = '' 59 | html_theme = 'openstackdocs' 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | # 64 | # This is also used if you do content translation via gettext catalogs. 65 | # Usually you set "language" from the command line for these cases. 66 | # language = None 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = [] 71 | 72 | # The name of the Pygments (syntax highlighting) style to use. 73 | pygments_style = 'sphinx' 74 | 75 | # If true, `todo` and `todoList` produce output, else they produce nothing. 76 | todo_include_todos = False 77 | 78 | # -- Options for HTML output ---------------------------------------------- 79 | 80 | # Output file base name for HTML help builder. 81 | htmlhelp_basename = 'microversion-parsedoc' 82 | 83 | # -- Options for LaTeX output --------------------------------------------- 84 | 85 | latex_elements = {} 86 | # Grouping the document tree into LaTeX files. List of tuples 87 | # (source start file, target name, title, 88 | # author, documentclass [howto, manual, or own class]). 89 | latex_documents = [ 90 | ( 91 | master_doc, 92 | 'microversion-parse.tex', 93 | 'microversion-parse Documentation', 94 | 'OpenStack', 95 | 'manual' 96 | ), 97 | ] 98 | 99 | # -- Options for manual page output --------------------------------------- 100 | 101 | # One entry per manual page. List of tuples 102 | # (source start file, name, description, authors, manual section). 103 | man_pages = [ 104 | ( 105 | master_doc, 106 | 'microversion-parse', 107 | u'microversion-parse Documentation', 108 | [author], 109 | 1 110 | ) 111 | ] 112 | 113 | 114 | # -- Options for Texinfo output ------------------------------------------- 115 | 116 | # Grouping the document tree into Texinfo files. List of tuples 117 | # (source start file, target name, title, author, 118 | # dir menu entry, description, category) 119 | texinfo_documents = [ 120 | ( 121 | master_doc, 122 | 'microversion-parse', 123 | u'microversion-parse Documentation', 124 | author, 125 | 'microversion-parse', 126 | 'One line description of project.', 127 | 'Miscellaneous' 128 | ), 129 | ] 130 | 131 | # Example configuration for intersphinx: refer to the Python standard library. 132 | intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} 133 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. microversion-parse documentation master file, created by 2 | sphinx-quickstart on Thu Mar 31 11:40:03 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. include:: ../../README.rst 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | 12 | Indices and tables 13 | ================== 14 | 15 | * :ref:`genindex` 16 | * :ref:`modindex` 17 | * :ref:`search` 18 | 19 | -------------------------------------------------------------------------------- /microversion_parse/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | import collections 15 | 16 | 17 | ENVIRON_HTTP_HEADER_FMT = 'http_{}' 18 | STANDARD_HEADER = 'openstack-api-version' 19 | 20 | 21 | class Version(collections.namedtuple('Version', 'major minor')): 22 | """A namedtuple containing major and minor values. 23 | 24 | Since it is a tuple, it is automatically comparable. 25 | """ 26 | 27 | def __new__(cls, major, minor): 28 | """Add min and max version attributes to the tuple.""" 29 | self = super(Version, cls).__new__(cls, major, minor) 30 | self.max_version = (-1, 0) 31 | self.min_version = (-1, 0) 32 | return self 33 | 34 | def __str__(self): 35 | return '%s.%s' % (self.major, self.minor) 36 | 37 | def matches(self, min_version=None, max_version=None): 38 | """Is this version within min_version and max_version. 39 | """ 40 | # NOTE(cdent): min_version and max_version are expected 41 | # to be set by the code that is creating the Version, if 42 | # they are known. 43 | if min_version is None: 44 | min_version = self.min_version 45 | if max_version is None: 46 | max_version = self.max_version 47 | return min_version <= self <= max_version 48 | 49 | 50 | def get_version(headers, service_type, legacy_headers=None): 51 | """Parse a microversion out of headers 52 | 53 | :param headers: The headers of a request, dict or list 54 | :param service_type: The service type being looked for in the headers 55 | :param legacy_headers: Other headers to look at for a version 56 | :returns: a version string or "latest" 57 | :raises: ValueError 58 | 59 | If headers is not a dict we assume is an iterator of 60 | tuple-like headers, which we will fold into a dict. 61 | 62 | The flow is that we first look for the new standard singular 63 | header: 64 | 65 | * openstack-api-version: 66 | 67 | If that's not present we fall back to the headers listed in 68 | legacy_headers. These often look like this: 69 | 70 | * openstack--api-version: 71 | * openstack--api-version: 72 | * x-openstack--api-version: 73 | 74 | Folded headers are joined by ','. 75 | """ 76 | 77 | folded_headers = fold_headers(headers) 78 | 79 | version = check_standard_header(folded_headers, service_type) 80 | if version: 81 | return version 82 | 83 | if legacy_headers: 84 | version = check_legacy_headers(folded_headers, legacy_headers) 85 | return version 86 | 87 | return None 88 | 89 | 90 | def check_legacy_headers(headers, legacy_headers): 91 | """Gather values from old headers.""" 92 | for legacy_header in legacy_headers: 93 | try: 94 | value = _extract_header_value(headers, legacy_header.lower()) 95 | return value.split(',')[-1].strip() 96 | except KeyError: 97 | pass 98 | return None 99 | 100 | 101 | def check_standard_header(headers, service_type): 102 | """Parse the standard header to get value for service.""" 103 | try: 104 | header = _extract_header_value(headers, STANDARD_HEADER) 105 | for header_value in reversed(header.split(',')): 106 | try: 107 | service, version = header_value.strip().split(None, 1) 108 | if service.lower() == service_type.lower(): 109 | return version.strip() 110 | except ValueError: 111 | pass 112 | except (KeyError, ValueError): 113 | return None 114 | 115 | 116 | def fold_headers(headers): 117 | """Turn a list of headers into a folded dict.""" 118 | # If it behaves like a dict, return it. Webob uses objects which 119 | # are not dicts, but behave like them. 120 | try: 121 | return dict((k.lower(), v) for k, v in headers.items()) 122 | except AttributeError: 123 | pass 124 | header_dict = collections.defaultdict(list) 125 | for header, value in headers: 126 | header_dict[header.lower()].append(value.strip()) 127 | 128 | folded_headers = {} 129 | for header, value in header_dict.items(): 130 | folded_headers[header] = ','.join(value) 131 | 132 | return folded_headers 133 | 134 | 135 | def headers_from_wsgi_environ(environ): 136 | """Extract all the HTTP_ keys and values from environ to a new dict. 137 | 138 | Note that this does not change the keys in any way in the returned 139 | dict. Nor is the incoming environ modified. 140 | 141 | :param environ: A PEP 3333 compliant WSGI environ dict. 142 | """ 143 | return {key: environ[key] for key in environ if key.startswith('HTTP_')} 144 | 145 | 146 | def _extract_header_value(headers, header_name): 147 | """Get the value of a header. 148 | 149 | The provided headers is a dict. If a key doesn't exist for 150 | header_name, try using the WSGI environ form of the name. 151 | 152 | Raises KeyError if neither key is found. 153 | """ 154 | try: 155 | value = headers[header_name] 156 | except KeyError: 157 | wsgi_header_name = ENVIRON_HTTP_HEADER_FMT.format( 158 | header_name.replace('-', '_')) 159 | value = headers[wsgi_header_name] 160 | return value 161 | 162 | 163 | def parse_version_string(version_string): 164 | """Turn a version string into a Version 165 | 166 | :param version_string: A string of two numerals, X.Y. 167 | :returns: a Version 168 | :raises: TypeError 169 | """ 170 | try: 171 | # The combination of int and a limited split with the 172 | # named tuple means that this incantation will raise 173 | # ValueError, TypeError or AttributeError when the incoming 174 | # data is poorly formed but will, however, naturally adapt to 175 | # extraneous whitespace. 176 | return Version(*(int(value) for value 177 | in version_string.split('.', 1))) 178 | except (ValueError, TypeError, AttributeError) as exc: 179 | raise TypeError('invalid version string: %s; %s' % ( 180 | version_string, exc)) 181 | 182 | 183 | def extract_version(headers, service_type, versions_list): 184 | """Extract the microversion from the headers. 185 | 186 | There may be multiple headers and some which don't match our 187 | service. 188 | 189 | If no version is found then the extracted version is the minimum 190 | available version. 191 | 192 | :param headers: Request headers as dict list or WSGI environ 193 | :param service_type: The service_type as a string 194 | :param versions_list: List of all possible microversions as strings, 195 | sorted from earliest to latest version. 196 | :returns: a Version with the optional min_version and max_version 197 | attributes set. 198 | :raises: ValueError 199 | """ 200 | found_version = get_version(headers, service_type=service_type) 201 | min_version_string = versions_list[0] 202 | max_version_string = versions_list[-1] 203 | 204 | # If there was no version found in the headers, choose the minimum 205 | # available version. 206 | version_string = found_version or min_version_string 207 | if version_string == 'latest': 208 | version_string = max_version_string 209 | request_version = parse_version_string(version_string) 210 | request_version.max_version = parse_version_string(max_version_string) 211 | request_version.min_version = parse_version_string(min_version_string) 212 | # We need a version that is in versions_list. This gives us the option 213 | # to administratively disable a version if we really need to. 214 | if str(request_version) in versions_list: 215 | return request_version 216 | raise ValueError('Unacceptable version header: %s' % version_string) 217 | -------------------------------------------------------------------------------- /microversion_parse/middleware.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | """WSGI middleware for getting microversion info.""" 14 | 15 | import webob 16 | import webob.dec 17 | 18 | import microversion_parse 19 | 20 | 21 | class MicroversionMiddleware(object): 22 | """WSGI middleware for getting microversion info. 23 | 24 | The application will get a WSGI environ with a 25 | 'SERVICE_TYPE.microversion' key that has a value of the microversion 26 | found at an 'openstack-api-version' header that matches SERVICE_TYPE. If 27 | no header is found, the minimum microversion will be set. If the 28 | special keyword 'latest' is used, the maximum microversion will be 29 | set. 30 | 31 | If the requested microversion is not available a 406 response is 32 | returned. 33 | 34 | If there is an error parsing a provided header, a 400 response is 35 | returned. 36 | 37 | Otherwise the application is called. 38 | """ 39 | 40 | def __init__(self, application, service_type, versions, 41 | json_error_formatter=None): 42 | """Create the WSGI middleware. 43 | 44 | :param application: The application hosting the service. 45 | :param service_type: The service type (entry in keystone catalog) 46 | of the application. 47 | :param versions: An ordered list of legitimate versions for the 48 | application. 49 | :param json_error_formatter: A Webob exception error formatter. 50 | See Webob for details. 51 | """ 52 | self.application = application 53 | self.service_type = service_type 54 | self.microversion_environ = '%s.microversion' % service_type 55 | self.versions = versions 56 | self.json_error_formatter = json_error_formatter 57 | 58 | @webob.dec.wsgify 59 | def __call__(self, req): 60 | try: 61 | microversion = microversion_parse.extract_version( 62 | req.headers, self.service_type, self.versions) 63 | # TODO(cdent): These error response are not formatted according to 64 | # api-sig guidelines, unless a json_error_formatter is provided 65 | # that can do it. For an example, see the placement service. 66 | except ValueError as exc: 67 | raise webob.exc.HTTPNotAcceptable( 68 | ('Invalid microversion: %(error)s') % {'error': exc}, 69 | json_formatter=self.json_error_formatter) 70 | except TypeError as exc: 71 | raise webob.exc.HTTPBadRequest( 72 | ('Invalid microversion: %(error)s') % {'error': exc}, 73 | json_formatter=self.json_error_formatter) 74 | 75 | req.environ[self.microversion_environ] = microversion 76 | microversion_header = '%s %s' % (self.service_type, microversion) 77 | standard_header = microversion_parse.STANDARD_HEADER 78 | 79 | try: 80 | response = req.get_response(self.application) 81 | except webob.exc.HTTPError as exc: 82 | # If there was an HTTPError in the application we still need 83 | # to send the microversion header, so add the header and 84 | # re-raise the exception. 85 | exc.headers.add(standard_header, microversion_header) 86 | raise exc 87 | 88 | response.headers.add(standard_header, microversion_header) 89 | response.headers.add('vary', standard_header) 90 | return response 91 | -------------------------------------------------------------------------------- /microversion_parse/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack/microversion-parse/26a2dc96cc2a0e6baf528c846f2d6d48e1dd3379/microversion_parse/tests/__init__.py -------------------------------------------------------------------------------- /microversion_parse/tests/gabbits/middleware.yaml: -------------------------------------------------------------------------------- 1 | # Tests that the middleware does microversioning as we expect 2 | # The min version of the service is 1.0, the max is 1.2, 3 | # the service type is "cats" (because the internet is for cats). 4 | 5 | defaults: 6 | request_headers: 7 | # We must guard against webob requiring an accept header. 8 | # We don't want to do this in the middleware itself as 9 | # we don't know what the application would prefer as a 10 | # default. 11 | accept: application/json 12 | 13 | tests: 14 | 15 | - name: min default 16 | GET: /good 17 | response_headers: 18 | openstack-api-version: cats 1.0 19 | 20 | - name: max latest 21 | GET: /good 22 | request_headers: 23 | openstack-api-version: cats latest 24 | response_headers: 25 | openstack-api-version: cats 1.2 26 | 27 | - name: explict 28 | GET: /good 29 | request_headers: 30 | openstack-api-version: cats 1.1 31 | response_headers: 32 | openstack-api-version: cats 1.1 33 | 34 | - name: out of range 35 | GET: /good 36 | request_headers: 37 | openstack-api-version: cats 1.9 38 | status: 406 39 | response_strings: 40 | - Unacceptable version header 41 | 42 | - name: invalid format 43 | GET: /good 44 | request_headers: 45 | openstack-api-version: cats 1.9.5 46 | status: 400 47 | response_strings: 48 | - invalid literal 49 | 50 | - name: different service 51 | desc: end up with default microversion 52 | GET: /good 53 | request_headers: 54 | openstack-api-version: dogs 1.9 55 | response_headers: 56 | openstack-api-version: cats 1.0 57 | 58 | - name: multiple services 59 | GET: /good 60 | request_headers: 61 | openstack-api-version: dogs 1.9, cats 1.1 62 | response_headers: 63 | openstack-api-version: cats 1.1 64 | 65 | - name: header present on exception 66 | GET: /bad 67 | request_headers: 68 | openstack-api-version: dogs 1.9, cats 1.1 69 | response_headers: 70 | openstack-api-version: cats 1.1 71 | status: 404 72 | response_strings: 73 | - /bad not found 74 | 75 | 76 | -------------------------------------------------------------------------------- /microversion_parse/tests/gabbits/simple.yaml: -------------------------------------------------------------------------------- 1 | # tests that the SimpleWSGI app is present 2 | 3 | tests: 4 | 5 | - name: get good 6 | GET: /good 7 | status: 200 8 | response_strings: 9 | - good 10 | 11 | - name: get bad 12 | GET: /bad 13 | status: 404 14 | response_strings: 15 | - not found 16 | -------------------------------------------------------------------------------- /microversion_parse/tests/test_extract_version.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | 15 | import testtools 16 | 17 | import microversion_parse 18 | 19 | 20 | class TestVersion(testtools.TestCase): 21 | 22 | def setUp(self): 23 | super(TestVersion, self).setUp() 24 | self.version = microversion_parse.Version(1, 5) 25 | 26 | def test_version_is_tuple(self): 27 | self.assertEqual((1, 5), self.version) 28 | 29 | def test_version_stringifies(self): 30 | self.assertEqual('1.5', str(self.version)) 31 | 32 | def test_version_matches(self): 33 | max_version = microversion_parse.Version(1, 20) 34 | min_version = microversion_parse.Version(1, 3) 35 | 36 | self.assertTrue(self.version.matches(min_version, max_version)) 37 | self.assertFalse(self.version.matches(max_version, min_version)) 38 | 39 | def test_version_matches_inclusive(self): 40 | max_version = microversion_parse.Version(1, 5) 41 | min_version = microversion_parse.Version(1, 5) 42 | 43 | self.assertTrue(self.version.matches(min_version, max_version)) 44 | 45 | def test_version_matches_no_extremes(self): 46 | """If no extremes are present, never match.""" 47 | self.assertFalse(self.version.matches()) 48 | 49 | def test_version_zero_can_match(self): 50 | """If a version is '0.0' we want to it be able to match.""" 51 | version = microversion_parse.Version(0, 0) 52 | min_version = microversion_parse.Version(0, 0) 53 | max_version = microversion_parse.Version(0, 0) 54 | version.min_version = min_version 55 | version.max_version = max_version 56 | 57 | self.assertTrue(version.matches()) 58 | 59 | def test_version_zero_no_defaults(self): 60 | """Any version, even 0.0, should never match without a min 61 | and max being set. 62 | """ 63 | version = microversion_parse.Version(0, 0) 64 | 65 | self.assertFalse(version.matches()) 66 | 67 | def test_version_init_failure(self): 68 | self.assertRaises(TypeError, microversion_parse.Version, 1, 2, 3) 69 | 70 | 71 | class TestParseVersionString(testtools.TestCase): 72 | 73 | def test_good_version(self): 74 | version = microversion_parse.parse_version_string('1.1') 75 | self.assertEqual((1, 1), version) 76 | self.assertEqual(microversion_parse.Version(1, 1), version) 77 | 78 | def test_adapt_whitespace(self): 79 | version = microversion_parse.parse_version_string(' 1.1 ') 80 | self.assertEqual((1, 1), version) 81 | self.assertEqual(microversion_parse.Version(1, 1), version) 82 | 83 | def test_non_numeric(self): 84 | self.assertRaises(TypeError, 85 | microversion_parse.parse_version_string, 86 | 'hello') 87 | 88 | def test_mixed_alphanumeric(self): 89 | self.assertRaises(TypeError, 90 | microversion_parse.parse_version_string, 91 | '1.a') 92 | 93 | def test_too_many_numeric(self): 94 | self.assertRaises(TypeError, 95 | microversion_parse.parse_version_string, 96 | '1.1.1') 97 | 98 | def test_not_string(self): 99 | self.assertRaises(TypeError, 100 | microversion_parse.parse_version_string, 101 | 1.1) 102 | 103 | 104 | class TestExtractVersion(testtools.TestCase): 105 | 106 | def setUp(self): 107 | super(TestExtractVersion, self).setUp() 108 | self.headers = [ 109 | ('OpenStack-API-Version', 'service1 1.2'), 110 | ('OpenStack-API-Version', 'service2 1.5'), 111 | ('OpenStack-API-Version', 'service3 latest'), 112 | ('OpenStack-API-Version', 'service4 2.5'), 113 | ] 114 | self.version_list = ['1.1', '1.2', '1.3', '1.4', 115 | '2.1', '2.2', '2.3', '2.4'] 116 | 117 | def test_simple_extract(self): 118 | version = microversion_parse.extract_version( 119 | self.headers, 'service1', self.version_list) 120 | self.assertEqual((1, 2), version) 121 | 122 | def test_default_min(self): 123 | version = microversion_parse.extract_version( 124 | self.headers, 'notlisted', self.version_list) 125 | self.assertEqual((1, 1), version) 126 | 127 | def test_latest(self): 128 | version = microversion_parse.extract_version( 129 | self.headers, 'service3', self.version_list) 130 | self.assertEqual((2, 4), version) 131 | 132 | def test_min_max_extract(self): 133 | version = microversion_parse.extract_version( 134 | self.headers, 'service1', self.version_list) 135 | 136 | # below min 137 | self.assertFalse(version.matches((1, 3))) 138 | # at min 139 | self.assertTrue(version.matches((1, 2))) 140 | # within extremes 141 | self.assertTrue(version.matches()) 142 | # explicit max 143 | self.assertTrue(version.matches(max_version=(2, 3))) 144 | # explicit min 145 | self.assertFalse(version.matches(min_version=(2, 3))) 146 | # explicit both 147 | self.assertTrue(version.matches(min_version=(0, 3), 148 | max_version=(1, 5))) 149 | 150 | def test_version_disabled(self): 151 | self.assertRaises(ValueError, microversion_parse.extract_version, 152 | self.headers, 'service2', self.version_list) 153 | 154 | def test_version_out_of_range(self): 155 | self.assertRaises(ValueError, microversion_parse.extract_version, 156 | self.headers, 'service4', self.version_list) 157 | -------------------------------------------------------------------------------- /microversion_parse/tests/test_get_version.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | import testtools 15 | 16 | import microversion_parse 17 | 18 | 19 | class TestFoldHeaders(testtools.TestCase): 20 | 21 | def test_dict_headers(self): 22 | headers = { 23 | 'header-one': 'alpha', 24 | 'header-two': 'beta', 25 | 'header-three': 'gamma', 26 | } 27 | 28 | folded_headers = microversion_parse.fold_headers(headers) 29 | self.assertEqual(3, len(folded_headers)) 30 | self.assertEqual(set(headers.keys()), set(folded_headers.keys())) 31 | self.assertEqual('gamma', folded_headers['header-three']) 32 | 33 | def test_listed_tuple_headers(self): 34 | headers = [ 35 | ('header-one', 'alpha'), 36 | ('header-two', 'beta'), 37 | ('header-one', 'gamma'), 38 | ] 39 | 40 | folded_headers = microversion_parse.fold_headers(headers) 41 | self.assertEqual(2, len(folded_headers)) 42 | self.assertEqual(set(['header-one', 'header-two']), 43 | set(folded_headers.keys())) 44 | self.assertEqual('alpha,gamma', folded_headers['header-one']) 45 | 46 | def test_bad_headers(self): 47 | headers = 'wow this is not a headers' 48 | self.assertRaises(ValueError, microversion_parse.fold_headers, 49 | headers) 50 | 51 | # TODO(cdent): Test with request objects from frameworks. 52 | 53 | 54 | class TestStandardHeader(testtools.TestCase): 55 | 56 | def test_simple_match(self): 57 | headers = { 58 | 'header-one': 'alpha', 59 | 'openstack-api-version': 'compute 2.1', 60 | 'header-two': 'beta', 61 | } 62 | version = microversion_parse.check_standard_header(headers, 'compute') 63 | # TODO(cdent): String or number. Choosing string for now 64 | # since 'latest' is always a string. 65 | self.assertEqual('2.1', version) 66 | 67 | def test_match_extra_whitespace(self): 68 | headers = { 69 | 'header-one': 'alpha', 70 | 'openstack-api-version': ' compute 2.1 ', 71 | 'header-two': 'beta', 72 | } 73 | version = microversion_parse.check_standard_header(headers, 'compute') 74 | self.assertEqual('2.1', version) 75 | 76 | def test_no_match_no_value(self): 77 | headers = { 78 | 'header-one': 'alpha', 79 | 'openstack-api-version': 'compute ', 80 | 'header-two': 'beta', 81 | } 82 | version = microversion_parse.check_standard_header(headers, 'compute') 83 | self.assertEqual(None, version) 84 | 85 | def test_no_match_wrong_service(self): 86 | headers = { 87 | 'header-one': 'alpha', 88 | 'openstack-api-version': 'network 5.9 ', 89 | 'header-two': 'beta', 90 | } 91 | version = microversion_parse.check_standard_header( 92 | headers, 'compute') 93 | self.assertEqual(None, version) 94 | 95 | def test_match_multiple_services(self): 96 | headers = { 97 | 'header-one': 'alpha', 98 | 'openstack-api-version': 'network 5.9 ,compute 2.1,telemetry 7.8', 99 | 'header-two': 'beta', 100 | } 101 | version = microversion_parse.check_standard_header( 102 | headers, 'compute') 103 | self.assertEqual('2.1', version) 104 | version = microversion_parse.check_standard_header( 105 | headers, 'telemetry') 106 | self.assertEqual('7.8', version) 107 | 108 | def test_match_multiple_same_service(self): 109 | headers = { 110 | 'header-one': 'alpha', 111 | 'openstack-api-version': 'compute 5.9 ,compute 2.1,compute 7.8', 112 | 'header-two': 'beta', 113 | } 114 | version = microversion_parse.check_standard_header( 115 | headers, 'compute') 116 | self.assertEqual('7.8', version) 117 | 118 | 119 | class TestLegacyHeaders(testtools.TestCase): 120 | 121 | def test_legacy_headers_straight(self): 122 | headers = { 123 | 'header-one': 'alpha', 124 | 'openstack-compute-api-version': ' 2.1 ', 125 | 'header-two': 'beta', 126 | } 127 | version = microversion_parse.get_version( 128 | headers, service_type='compute', 129 | legacy_headers=['openstack-CoMpUte-api-version']) 130 | self.assertEqual('2.1', version) 131 | 132 | def test_legacy_headers_folded(self): 133 | headers = { 134 | 'header-one': 'alpha', 135 | 'openstack-compute-api-version': ' 2.1, 9.2 ', 136 | 'header-two': 'beta', 137 | } 138 | version = microversion_parse.get_version( 139 | headers, service_type='compute', 140 | legacy_headers=['openstack-compute-api-version']) 141 | self.assertEqual('9.2', version) 142 | 143 | def test_older_legacy_headers(self): 144 | headers = { 145 | 'header-one': 'alpha', 146 | 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 147 | 'header-two': 'beta', 148 | } 149 | version = microversion_parse.get_version( 150 | headers, service_type='compute', 151 | legacy_headers=['openstack-nova-api-version', 152 | 'x-openstack-nova-api-version']) 153 | # We don't do x- for service types. 154 | self.assertEqual('9.2', version) 155 | 156 | def test_legacy_headers_prefer(self): 157 | headers = { 158 | 'header-one': 'alpha', 159 | 'openstack-compute-api-version': '3.7', 160 | 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 161 | 'header-two': 'beta', 162 | } 163 | version = microversion_parse.get_version( 164 | headers, service_type='compute', 165 | legacy_headers=['openstack-compute-api-version', 166 | 'x-openstack-nova-api-version']) 167 | self.assertEqual('3.7', version) 168 | version = microversion_parse.get_version( 169 | headers, service_type='compute', 170 | legacy_headers=['x-openstack-nova-api-version', 171 | 'openstack-compute-api-version']) 172 | self.assertEqual('9.2', version) 173 | 174 | 175 | class TestGetHeaders(testtools.TestCase): 176 | 177 | def test_preference(self): 178 | headers = { 179 | 'header-one': 'alpha', 180 | 'openstack-api-version': 'compute 11.12, telemetry 9.7', 181 | 'openstack-compute-api-version': '3.7', 182 | 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 183 | 'header-two': 'beta', 184 | } 185 | version = microversion_parse.get_version( 186 | headers, service_type='compute', 187 | legacy_headers=['openstack-compute-api-version', 188 | 'x-openstack-nova-api-version']) 189 | self.assertEqual('11.12', version) 190 | 191 | def test_no_headers(self): 192 | headers = {} 193 | version = microversion_parse.get_version( 194 | headers, service_type='compute') 195 | self.assertEqual(None, version) 196 | 197 | def test_unfolded_service(self): 198 | headers = [ 199 | ('header-one', 'alpha'), 200 | ('openstack-api-version', 'compute 1.0'), 201 | ('openstack-api-version', 'compute 2.0'), 202 | ('openstack-api-version', '3.0'), 203 | ] 204 | version = microversion_parse.get_version( 205 | headers, service_type='compute') 206 | self.assertEqual('2.0', version) 207 | 208 | def test_unfolded_in_name(self): 209 | headers = [ 210 | ('header-one', 'alpha'), 211 | ('x-openstack-nova-api-version', '1.0'), 212 | ('x-openstack-nova-api-version', '2.0'), 213 | ('openstack-telemetry-api-version', '3.0'), 214 | ] 215 | version = microversion_parse.get_version( 216 | headers, service_type='compute', 217 | legacy_headers=['x-openstack-nova-api-version']) 218 | self.assertEqual('2.0', version) 219 | 220 | def test_capitalized_headers(self): 221 | headers = { 222 | 'X-Openstack-Ironic-Api-Version': '123.456' 223 | } 224 | version = microversion_parse.get_version( 225 | headers, service_type='ironic', 226 | legacy_headers=['X-Openstack-Ironic-Api-Version']) 227 | self.assertEqual('123.456', version) 228 | -------------------------------------------------------------------------------- /microversion_parse/tests/test_headers_from_wsgi_environ.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | import testtools 15 | 16 | import microversion_parse 17 | 18 | 19 | class TestHeadersFromWSGIEnviron(testtools.TestCase): 20 | 21 | def test_empty_environ(self): 22 | environ = {} 23 | expected = {} 24 | self.assertEqual( 25 | expected, 26 | microversion_parse.headers_from_wsgi_environ(environ)) 27 | 28 | def test_non_empty_no_headers(self): 29 | environ = {'PATH_INFO': '/foo/bar'} 30 | expected = {} 31 | found_headers = microversion_parse.headers_from_wsgi_environ(environ) 32 | self.assertEqual(expected, found_headers) 33 | 34 | def test_headers(self): 35 | environ = {'PATH_INFO': '/foo/bar', 36 | 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 37 | 'HTTP_CONTENT_TYPE': 'application/json'} 38 | expected = {'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 39 | 'HTTP_CONTENT_TYPE': 'application/json'} 40 | found_headers = microversion_parse.headers_from_wsgi_environ(environ) 41 | self.assertEqual(expected, found_headers) 42 | 43 | def test_get_version_from_environ(self): 44 | environ = {'PATH_INFO': '/foo/bar', 45 | 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 46 | 'HTTP_CONTENT_TYPE': 'application/json'} 47 | expected_version = '2.1' 48 | headers = microversion_parse.headers_from_wsgi_environ(environ) 49 | version = microversion_parse.get_version(headers, 'placement') 50 | self.assertEqual(expected_version, version) 51 | 52 | def test_get_version_from_environ_legacy(self): 53 | environ = {'PATH_INFO': '/foo/bar', 54 | 'HTTP_X_OPENSTACK_PLACEMENT_API_VERSION': '2.1', 55 | 'HTTP_CONTENT_TYPE': 'application/json'} 56 | expected_version = '2.1' 57 | headers = microversion_parse.headers_from_wsgi_environ(environ) 58 | version = microversion_parse.get_version( 59 | headers, 'placement', 60 | legacy_headers=['x-openstack-placement-api-version']) 61 | self.assertEqual(expected_version, version) 62 | -------------------------------------------------------------------------------- /microversion_parse/tests/test_middleware.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | # The microversion_parse middlware is tests using gabbi to run real 15 | # http requests through it. To do that, we need a simple WSGI 16 | # application running under wsgi-intercept (handled by gabbi). 17 | 18 | import os 19 | 20 | from gabbi import driver 21 | import webob 22 | 23 | from microversion_parse import middleware 24 | 25 | 26 | TESTS_DIR = 'gabbits' 27 | SERVICE_TYPE = 'cats' 28 | VERSIONS = [ 29 | '1.0', # initial version 30 | '1.1', # now with kittens 31 | '1.2', # added breeds 32 | ] 33 | 34 | 35 | class SimpleWSGI(object): 36 | """A WSGI application that can be contiained within a middlware.""" 37 | 38 | def __call__(self, environ, start_response): 39 | path_info = environ['PATH_INFO'] 40 | if path_info == '/good': 41 | start_response('200 OK', [('content-type', 'text/plain')]) 42 | return [b'good'] 43 | 44 | raise webob.exc.HTTPNotFound('%s not found' % path_info) 45 | 46 | 47 | def app(): 48 | app = middleware.MicroversionMiddleware( 49 | SimpleWSGI(), SERVICE_TYPE, VERSIONS) 50 | return app 51 | 52 | 53 | def load_tests(loader, tests, pattern): 54 | """Provide a TestSuite to the discovery process.""" 55 | test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR) 56 | return driver.build_tests( 57 | test_dir, loader, test_loader_name=__name__, intercept=app) 58 | -------------------------------------------------------------------------------- /microversion_parse/tests/test_webob.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | import testtools 15 | 16 | from webob import headers as wb_headers 17 | 18 | import microversion_parse 19 | 20 | 21 | class TestWebobHeaders(testtools.TestCase): 22 | """Webob uses a dict-like header which is not actually a dict.""" 23 | 24 | def test_simple_headers(self): 25 | headers = wb_headers.EnvironHeaders({ 26 | 'HTTP_HEADER_ONE': 'alpha', 27 | 'HTTP_HEADER_TWO': 'beta', 28 | 'HTTP_HEADER_THREE': 'gamma', 29 | }) 30 | 31 | folded_headers = microversion_parse.fold_headers(headers) 32 | self.assertEqual(3, len(folded_headers)) 33 | self.assertEqual(set(['header-one', 'header-three', 'header-two']), 34 | set(folded_headers.keys())) 35 | self.assertEqual('gamma', folded_headers['header-three']) 36 | 37 | def test_simple_match(self): 38 | headers = wb_headers.EnvironHeaders({ 39 | 'HTTP_HEADER_ONE': 'alpha', 40 | 'HTTP_OPENSTACK_API_VERSION': 'compute 2.1', 41 | 'HTTP_HEADER_TWO': 'beta', 42 | }) 43 | version = microversion_parse.check_standard_header(headers, 'compute') 44 | self.assertEqual('2.1', version) 45 | 46 | def test_match_multiple_services(self): 47 | headers = wb_headers.EnvironHeaders({ 48 | 'HTTP_HEADER_ONE': 'alpha', 49 | 'HTTP_OPENSTACK_API_VERSION': 50 | 'network 5.9 ,compute 2.1,telemetry 7.8', 51 | 'HTTP_HEADER_TWO': 'beta', 52 | }) 53 | version = microversion_parse.check_standard_header( 54 | headers, 'compute') 55 | self.assertEqual('2.1', version) 56 | version = microversion_parse.check_standard_header( 57 | headers, 'telemetry') 58 | self.assertEqual('7.8', version) 59 | 60 | def test_legacy_headers_straight(self): 61 | headers = wb_headers.EnvironHeaders({ 62 | 'HTTP_HEADER_ONE': 'alpha', 63 | 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1 ', 64 | 'HTTP_HEADER_TWO': 'beta', 65 | }) 66 | version = microversion_parse.get_version( 67 | headers, service_type='compute', 68 | legacy_headers=['x-openstack-nova-api-version']) 69 | self.assertEqual('2.1', version) 70 | 71 | def test_legacy_headers_folded(self): 72 | headers = wb_headers.EnvironHeaders({ 73 | 'HTTP_HEADER_ONE': 'alpha', 74 | 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1, 9.2 ', 75 | 'HTTP_HEADER_TWO': 'beta', 76 | }) 77 | version = microversion_parse.get_version( 78 | headers, service_type='compute', 79 | legacy_headers=['x-openstack-nova-api-version']) 80 | self.assertEqual('9.2', version) 81 | -------------------------------------------------------------------------------- /releasenotes/notes/drop-python27-support-5b9a4e0ce63b730e.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | upgrade: 3 | - | 4 | Support for Python 2.7 has been dropped. The minimum version of Python now 5 | supported is Python 3.6. 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | WebOb>=1.2.3 # MIT 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = microversion_parse 3 | summary = OpenStack microversion header parser 4 | description_file = README.rst 5 | author = OpenStack 6 | author_email = openstack-discuss@lists.openstack.org 7 | home_page = http://www.openstack.org/ 8 | python_requires = >=3.8 9 | classifier = 10 | Environment :: OpenStack 11 | Intended Audience :: Information Technology 12 | License :: OSI Approved :: Apache Software License 13 | Operating System :: POSIX :: Linux 14 | Programming Language :: Python 15 | Programming Language :: Python :: 3 16 | Programming Language :: Python :: 3.8 17 | Programming Language :: Python :: 3.9 18 | Programming Language :: Python :: 3.10 19 | Programming Language :: Python :: 3.11 20 | Programming Language :: Python :: 3 :: Only 21 | Programming Language :: Python :: Implementation :: CPython 22 | 23 | [files] 24 | packages = 25 | microversion_parse 26 | 27 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); 2 | # you may not use this file except in compliance with the License. 3 | # You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 10 | # implied. 11 | # See the License for the specific language governing permissions and 12 | # limitations under the License. 13 | 14 | import setuptools 15 | 16 | setuptools.setup( 17 | setup_requires=['pbr'], 18 | pbr=True) 19 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | hacking>=6.1.0,<6.2.0 # Apache-2.0 2 | coverage>=3.6 # Apache-2.0 3 | stestr>=1.0.0 # Apache-2.0 4 | testtools>=1.4.0 # MIT 5 | gabbi>=1.35.0 # Apache-2.0 6 | pre-commit>=2.6.0 # MIT 7 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | minversion = 3.1.1 3 | skipsdist = True 4 | # If you want pypy or pypy3, do 'tox -epypy,pypy3', it might work! 5 | # And you can get coverage with 'tox -ecover'. 6 | envlist = py3,pep8 7 | ignore_basepython_conflict = True 8 | 9 | [testenv] 10 | deps = -r{toxinidir}/requirements.txt 11 | -r{toxinidir}/test-requirements.txt 12 | install_command = pip install -U {opts} {packages} 13 | usedevelop = True 14 | commands = stestr run {posargs} 15 | 16 | [testenv:venv] 17 | deps = -r{toxinidir}/requirements.txt 18 | -r{toxinidir}/test-requirements.txt 19 | commands = {posargs} 20 | 21 | [testenv:pep8] 22 | usedevelop = False 23 | commands = 24 | pre-commit run -a 25 | 26 | [testenv:cover] 27 | setenv = PYTHON=coverage run --source microversion_parse --parallel-mode 28 | commands = 29 | coverage erase 30 | find . -type f -name "*.pyc" -delete 31 | stestr run {posargs} 32 | coverage combine 33 | coverage html -d cover 34 | whitelist_externals = 35 | find 36 | 37 | [testenv:docs] 38 | deps = -r{toxinidir}/doc/requirements.txt 39 | commands = 40 | rm -rf doc/build 41 | sphinx-build -W --keep-going -b html -d doc/build/doctrees doc/source doc/build/html 42 | whitelist_externals = 43 | rm 44 | 45 | [flake8] 46 | ignore = H405,E126 47 | exclude=.venv,.git,.tox,dist,*egg,*.egg-info,build,examples,doc 48 | show-source = True 49 | --------------------------------------------------------------------------------