├── .coveragerc ├── .gitignore ├── .gitreview ├── .mailmap ├── .stestr.conf ├── .zuul.yaml ├── CONTRIBUTING.rst ├── HACKING.rst ├── LICENSE ├── Makefile ├── NEWS ├── README.rst ├── babel.cfg ├── congressclient ├── __init__.py ├── common │ ├── __init__.py │ ├── parseractions.py │ └── utils.py ├── exceptions.py ├── i18n.py ├── osc │ ├── __init__.py │ ├── osc_plugin.py │ └── v1 │ │ ├── __init__.py │ │ ├── api_versions.py │ │ ├── datasource.py │ │ ├── driver.py │ │ └── policy.py ├── tests │ ├── __init__.py │ ├── base.py │ ├── common.py │ ├── fakes.py │ ├── utils.py │ └── v1 │ │ ├── __init__.py │ │ ├── test_api_versions.py │ │ ├── test_datasource.py │ │ ├── test_drivers.py │ │ ├── test_policy.py │ │ └── test_policy_file.yaml └── v1 │ ├── __init__.py │ └── client.py ├── doc ├── requirements.txt └── source │ ├── conf.py │ ├── contributor │ └── index.rst │ ├── index.rst │ ├── install │ └── index.rst │ ├── reference │ └── index.rst │ └── user │ ├── index.rst │ └── readme.rst ├── lower-constraints.txt ├── releasenotes ├── notes │ ├── add-datasource-push-d92854a72b4d6480.yaml │ └── drop-py-2-7-0991cef98d96593e.yaml └── source │ ├── _static │ └── .placeholder │ ├── _templates │ └── .placeholder │ ├── conf.py │ ├── index.rst │ └── train.rst ├── requirements.txt ├── setup.cfg ├── setup.py ├── tenant-list.log ├── test-requirements.txt └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = congressclient 4 | omit = congressclient/tests/* 5 | 6 | [report] 7 | ignore_errors = True 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Congress build/runtime artifacts 2 | subunit.log 3 | 4 | *.py[cod] 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Packages 10 | *.egg 11 | *.egg-info 12 | dist 13 | build 14 | eggs 15 | parts 16 | bin 17 | var 18 | sdist 19 | develop-eggs 20 | .installed.cfg 21 | .eggs 22 | /lib 23 | /lib64 24 | 25 | # Installer logs 26 | pip-log.txt 27 | 28 | # Unit test / coverage reports 29 | .coverage 30 | .tox 31 | .stestr/ 32 | 33 | # Translations 34 | *.mo 35 | 36 | # Mr Developer 37 | .mr.developer.cfg 38 | .project 39 | .pydevproject 40 | 41 | # Complexity 42 | output/*.html 43 | output/*/index.html 44 | 45 | # Sphinx 46 | doc/build 47 | 48 | # pbr generates these 49 | AUTHORS 50 | ChangeLog 51 | 52 | # Editors 53 | *~ 54 | .*.swp 55 | *.swo 56 | *.swn 57 | -------------------------------------------------------------------------------- /.gitreview: -------------------------------------------------------------------------------- 1 | [gerrit] 2 | host=review.opendev.org 3 | port=29418 4 | project=openstack/python-congressclient.git 5 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | # Format is: 2 | # 3 | # -------------------------------------------------------------------------------- /.stestr.conf: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | test_path=./congressclient/tests 3 | top_dir=./ 4 | 5 | -------------------------------------------------------------------------------- /.zuul.yaml: -------------------------------------------------------------------------------- 1 | - project: 2 | templates: 3 | - check-requirements 4 | - openstack-lower-constraints-jobs 5 | - openstack-python3-ussuri-jobs 6 | - release-notes-jobs-python3 7 | - openstackclient-plugin-jobs 8 | - publish-openstack-docs-pti 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | If you would like to contribute to the development of OpenStack, 2 | you must follow the steps in this page: 3 | 4 | https://docs.openstack.org/infra/manual/developers.html 5 | 6 | Once those steps have been completed, changes to OpenStack 7 | should be submitted for review via the Gerrit tool, following 8 | the workflow documented at: 9 | 10 | https://docs.openstack.org/infra/manual/developers.html#development-workflow 11 | 12 | Pull requests submitted through GitHub will be ignored. 13 | 14 | Bugs should be filed on Launchpad, not GitHub: 15 | 16 | https://bugs.launchpad.net/python-congressclient -------------------------------------------------------------------------------- /HACKING.rst: -------------------------------------------------------------------------------- 1 | python-congressclient Style Commandments 2 | =============================================== 3 | 4 | Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | TOPDIR=$(CURDIR) 3 | SRCDIR=$(TOPDIR)/congressclient 4 | 5 | all: docs 6 | 7 | clean: rm -Rf $(TOPDIR)/doc/html/* 8 | 9 | docs: $(TOPDIR)/doc/source/*.rst 10 | sphinx-build -b html $(TOPDIR)/doc/source $(TOPDIR)/doc/html 11 | 12 | 13 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | 1.0.4 - XXXX-XX-XX 2 | ------------------ 3 | - Add new CLI command to trigger a datasource to poll 4 | - congress datasource request-refresh Trigger a datasource to poll. 5 | 6 | 1.0.3 - 2015-03-30 7 | ------------------ 8 | 9 | - Add new CLI commands to manage datasources/drivers 10 | - congress datasource create Create a datasource. 11 | - congress datasource delete Delete a datasource. 12 | - congress driver config show List driver tables. 13 | - congress driver list List drivers. 14 | - congress driver schema show List datasource tables. 15 | - All api commands now use uuids instead of names and the cli 16 | now looks up their ids when needed thou allows the user to still use 17 | the name for convenience. 18 | 19 | 20 | 1.0.2 - 2015-01-15 21 | ------------------ 22 | - Add new CLI comment to create/delete policy 23 | - congress policy create Create a policy. 24 | - congress policy delete Delete a policy. 25 | - Restructure simulate API to pass query/sequence/action_policy in body instead of URI. 26 | 27 | 28 | 1.0.1 - 2014-12-05 29 | ------------------ 30 | - Add missing CLI command 31 | - openstack congress policy rule show 32 | - python34 compatibility 33 | - New CLI command to simulate results of rule 34 | - openstack congress policy simulate Show the result of simulation. 35 | - Add new CLI command to check the status of a datasource 36 | - openstack congress datasource status list 37 | - Add new CLI for viewing schemas 38 | - openstack congress datasource table schema show Show schema for datasource table. 39 | - openstack congress datasource schema show Show schema for datasource. 40 | - Add CLI for creating/deleting policies 41 | - openstack congress policy create 42 | - openstack congress policy delete 43 | 44 | 45 | 46 | 1.0.0 - 2014-09-29 47 | ------------------ 48 | - First release 49 | - python-openstackclient integration 50 | - CLI 51 | - keystone catalog and auth 52 | - Support for the following CLI commands: 53 | - openstack congress datasource list List Datasources. 54 | - openstack congress datasource row list List datasource rows. 55 | - openstack congress datasource table list List datasource tables. 56 | - openstack congress policy list List Policy. 57 | - openstack congress policy row list List policy rows. 58 | - openstack congress policy rule create Create a policy rule. 59 | - openstack congress policy rule delete Delete a policy rule. 60 | - openstack congress policy rule list List policy rules. 61 | - openstack congress policy table list List policy tables. 62 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | python-congressclient 3 | =============================== 4 | 5 | .. only::html 6 | 7 | .. image:: https://governance.openstack.org/tc/badges/python-congressclient.svg 8 | :target: https://governance.openstack.org/tc/reference/tags/index.html 9 | 10 | .. only::latex 11 | 12 | .. image:: python-congressclient.svg 13 | 14 | 15 | .. Change things from this point on 16 | 17 | Client for Congress 18 | 19 | * Free software: Apache license 20 | * Documentation: https://docs.openstack.org/python-congressclient/latest/ 21 | * Source: https://opendev.org/openstack/python-congressclient 22 | * Bugs: https://bugs.launchpad.net/python-congressclient 23 | 24 | 25 | Client for Standalone Congress 26 | ------------------------------ 27 | Install the Congress CLI by cloning the repository and running the setup file. 28 | The master repository always contains the latest source code, so if you are 29 | installing and testing a specific branch of Congress, clone the matching branch 30 | of the python-congressclient. 31 | 32 | To execute CLI commands to standalone Congress installed with noauth: 33 | 34 | * Install python-openstackclient:: 35 | 36 | $ pip install python-openstackclient 37 | 38 | * Clone master repository & install python-congressclient:: 39 | 40 | $ git clone https://github.com/openstack/python-congressclient.git 41 | $ cd python-congressclient 42 | $ python setup.py install 43 | 44 | * (Optional) Clone a branch; for example, if you are using the Ocata version of OpenStack and Congress:: 45 | 46 | $ git clone -b stable/ocata https://github.com/openstack/python-congressclient.git 47 | $ cd python-congressclient 48 | $ python setup.py install 49 | 50 | * Read the HTML documentation. Install python-sphinx and the oslosphinx extension if missing:: 51 | 52 | $ sudo pip install sphinx 53 | $ sudo pip install oslosphinx 54 | 55 | Build the docs 56 | $ make docs 57 | 58 | Open doc/html/index.html in a browser 59 | 60 | * To execute CLI commands:: 61 | 62 | $ cd python-congressclient 63 | 64 | For example: 65 | $ export CONGRESS_URL="http://127.0.0.1:1789" 66 | $ openstack --os-token foo --os-url $CONGRESS_URL 67 | (openstack) congress policy create test_policy 68 | +--------------+--------------------------------------+ 69 | | Field | Value | 70 | +--------------+--------------------------------------+ 71 | | abbreviation | test_ | 72 | | description | | 73 | | id | 8595f24a-7d74-45ee-8168-0b3e937b8419 | 74 | | kind | nonrecursive | 75 | | name | test_policy | 76 | | owner_id | user | 77 | +--------------+--------------------------------------+ 78 | 79 | (openstack) congress policy rule create test_policy "p(5)" 80 | +---------+--------------------------------------+ 81 | | Field | Value | 82 | +---------+--------------------------------------+ 83 | | comment | None | 84 | | id | 5ce7fb18-a227-447e-bec8-93e99c0052a5 | 85 | | name | None | 86 | | rule | p(5) | 87 | +---------+--------------------------------------+ 88 | 89 | (openstack) congress policy rule list test_policy 90 | // ID: 5ce7fb18-a227-447e-bec8-93e99c0052a5 91 | // Name: None 92 | p(5) 93 | 94 | (openstack) exit 95 | $ 96 | 97 | Features 98 | -------- 99 | 100 | * TODO 101 | -------------------------------------------------------------------------------- /babel.cfg: -------------------------------------------------------------------------------- 1 | [python: **.py] 2 | -------------------------------------------------------------------------------- /congressclient/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | import pbr.version 14 | 15 | __all__ = ['__version__'] 16 | 17 | version_info = pbr.version.VersionInfo('python-congressclient') 18 | try: 19 | __version__ = version_info.version_string() 20 | except AttributeError: 21 | __version__ = None 22 | -------------------------------------------------------------------------------- /congressclient/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/common/__init__.py -------------------------------------------------------------------------------- /congressclient/common/parseractions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 OpenStack Foundation 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 | # 15 | 16 | """argparse Custom Actions""" 17 | 18 | import argparse 19 | 20 | 21 | class KeyValueAction(argparse.Action): 22 | """A custom action to parse arguments as key=value pairs 23 | 24 | Ensures that ``dest`` is a dict 25 | """ 26 | 27 | def __call__(self, parser, namespace, values, option_string=None): 28 | # Make sure we have an empty dict rather than None 29 | if getattr(namespace, self.dest, None) is None: 30 | setattr(namespace, self.dest, {}) 31 | 32 | # Add value if an assignment else remove it 33 | if '=' in values: 34 | getattr(namespace, self.dest, {}).update([values.split('=', 1)]) 35 | else: 36 | getattr(namespace, self.dest, {}).pop(values, None) 37 | 38 | 39 | class RangeAction(argparse.Action): 40 | """A custom action to parse a single value or a range of values 41 | 42 | Parses single integer values or a range of integer values delimited 43 | by a colon and returns a tuple of integers: 44 | '4' sets ``dest`` to (4, 4) 45 | '6:9' sets ``dest`` to (6, 9) 46 | """ 47 | 48 | def __call__(self, parser, namespace, values, option_string=None): 49 | range = values.split(':') 50 | if len(range) == 0: 51 | # Nothing passed, return a zero default 52 | setattr(namespace, self.dest, (0, 0)) 53 | elif len(range) == 1: 54 | # Only a single value is present 55 | setattr(namespace, self.dest, (int(range[0]), int(range[0]))) 56 | elif len(range) == 2: 57 | # Range of two values 58 | if int(range[0]) <= int(range[1]): 59 | setattr(namespace, self.dest, (int(range[0]), int(range[1]))) 60 | else: 61 | msg = ("Invalid range, %s is not less than %s" % 62 | (range[0], range[1])) 63 | raise argparse.ArgumentError(self, msg) 64 | else: 65 | # Too many values 66 | msg = "Invalid range, too many values" 67 | raise argparse.ArgumentError(self, msg) 68 | -------------------------------------------------------------------------------- /congressclient/common/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012-2013 OpenStack, LLC. 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 | 15 | import importlib 16 | import os 17 | 18 | from congressclient import exceptions 19 | 20 | 21 | def env(*vars, **kwargs): 22 | """Search for the first defined of possibly many env vars 23 | 24 | Returns the first environment variable defined in vars, or 25 | returns the default defined in kwargs. 26 | """ 27 | for v in vars: 28 | value = os.environ.get(v, None) 29 | if value: 30 | return value 31 | return kwargs.get('default', '') 32 | 33 | 34 | def import_class(import_str): 35 | """Returns a class from a string including module and class 36 | 37 | :param import_str: a string representation of the class name 38 | :rtype: the requested class 39 | """ 40 | mod_str, _sep, class_str = import_str.rpartition('.') 41 | mod = importlib.import_module(mod_str) 42 | return getattr(mod, class_str) 43 | 44 | 45 | def get_client_class(api_name, version, version_map): 46 | """Returns the client class for the requested API version 47 | 48 | :param api_name: the name of the API, e.g. 'compute', 'image', etc 49 | :param version: the requested API version 50 | :param version_map: a dict of client classes keyed by version 51 | :rtype: a client class for the requested API version 52 | """ 53 | try: 54 | client_path = version_map[str(version)] 55 | except (KeyError, ValueError): 56 | msg = "Invalid %s client version '%s'. must be one of: %s" % ( 57 | (api_name, version, ', '.join(version_map.keys()))) 58 | raise exceptions.UnsupportedVersion(msg) 59 | 60 | return import_class(client_path) 61 | 62 | 63 | def format_long_dict_list(data): 64 | """Return a formatted string. 65 | 66 | :param data: a list of dicts 67 | :rtype: a string formatted to {a:b, c:d}, {e:f, g:h} 68 | """ 69 | newdata = [str({str(key): str(value) for key, value in d.iteritems()}) 70 | for d in data] 71 | return ',\n'.join(newdata) + '\n' 72 | 73 | 74 | def format_dict(data): 75 | """Return a formatted string. 76 | 77 | :param data: a dict 78 | :rtype: a string formatted to {a:b, c:d} 79 | """ 80 | if not isinstance(data, dict): 81 | return str(data) 82 | return str({str(key): str(value) for key, value in data.items()}) 83 | 84 | 85 | def format_list(data): 86 | """Return a formatted strings 87 | 88 | :param data: a list of strings 89 | :rtype: a string formatted to a,b,c 90 | """ 91 | 92 | return ', '.join(data) 93 | 94 | 95 | def get_dict_properties(item, fields, mixed_case_fields=[], formatters={}): 96 | """Return a tuple containing the item properties. 97 | 98 | :param item: a single dict resource 99 | :param fields: tuple of strings with the desired field names 100 | :param mixed_case_fields: tuple of field names to preserve case 101 | :param formatters: dictionary mapping field names to callables 102 | to format the values 103 | """ 104 | row = [] 105 | for field in fields: 106 | if field in mixed_case_fields: 107 | field_name = field.replace(' ', '_') 108 | else: 109 | field_name = field.lower().replace(' ', '_') 110 | data = item[field_name] if field_name in item else '' 111 | if field in formatters: 112 | row.append(formatters[field](data)) 113 | else: 114 | row.append(data) 115 | return tuple(row) 116 | 117 | 118 | def get_resource_id_from_name(name, results): 119 | # FIXME(arosen): move to common lib and add tests... 120 | name_match = None 121 | id_match = None 122 | double_name_match = False 123 | for result in results['results']: 124 | if result['id'] == name: 125 | id_match = result['id'] 126 | if result['name'] == name: 127 | if name_match: 128 | double_name_match = True 129 | name_match = result['id'] 130 | if not double_name_match and name_match: 131 | return name_match 132 | if double_name_match and not id_match: 133 | # NOTE(arosen): this should only occur is using congress 134 | # as admin and multiple projects use the same datsource name. 135 | raise exceptions.Conflict( 136 | "Multiple resources have this name %s. Please specify id." % name) 137 | if id_match: 138 | return id_match 139 | 140 | raise exceptions.NotFound("Resource %s not found" % name) 141 | -------------------------------------------------------------------------------- /congressclient/exceptions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2010 Jacob Kaplan-Moss 2 | # Copyright 2011 Nebula, Inc. 3 | # Copyright 2013 Alessio Ababilov 4 | # Copyright 2013 OpenStack Foundation 5 | # All Rights Reserved. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | """ 20 | Exception definitions. 21 | """ 22 | 23 | import inspect 24 | import sys 25 | 26 | import six 27 | 28 | from congressclient.i18n import _ 29 | 30 | 31 | class ClientException(Exception): 32 | """The base exception class for all exceptions this library raises.""" 33 | pass 34 | 35 | 36 | class MissingArgs(ClientException): 37 | """Supplied arguments are not sufficient for calling a function.""" 38 | def __init__(self, missing): 39 | self.missing = missing 40 | msg = _("Missing arguments: %s") % ", ".join(missing) 41 | super(MissingArgs, self).__init__(msg) 42 | 43 | 44 | class ValidationError(ClientException): 45 | """Error in validation on API client side.""" 46 | pass 47 | 48 | 49 | class UnsupportedVersion(ClientException): 50 | """User is trying to use an unsupported version of the API.""" 51 | pass 52 | 53 | 54 | class CommandError(ClientException): 55 | """Error in CLI tool.""" 56 | pass 57 | 58 | 59 | class AuthorizationFailure(ClientException): 60 | """Cannot authorize API client.""" 61 | pass 62 | 63 | 64 | class ConnectionRefused(ClientException): 65 | """Cannot connect to API service.""" 66 | pass 67 | 68 | 69 | class AuthPluginOptionsMissing(AuthorizationFailure): 70 | """Auth plugin misses some options.""" 71 | def __init__(self, opt_names): 72 | super(AuthPluginOptionsMissing, self).__init__( 73 | _("Authentication failed. Missing options: %s") % 74 | ", ".join(opt_names)) 75 | self.opt_names = opt_names 76 | 77 | 78 | class AuthSystemNotFound(AuthorizationFailure): 79 | """User has specified an AuthSystem that is not installed.""" 80 | def __init__(self, auth_system): 81 | super(AuthSystemNotFound, self).__init__( 82 | _("AuthSystemNotFound: %s") % repr(auth_system)) 83 | self.auth_system = auth_system 84 | 85 | 86 | class NoUniqueMatch(ClientException): 87 | """Multiple entities found instead of one.""" 88 | pass 89 | 90 | 91 | class EndpointException(ClientException): 92 | """Something is rotten in Service Catalog.""" 93 | pass 94 | 95 | 96 | class EndpointNotFound(EndpointException): 97 | """Could not find requested endpoint in Service Catalog.""" 98 | pass 99 | 100 | 101 | class AmbiguousEndpoints(EndpointException): 102 | """Found more than one matching endpoint in Service Catalog.""" 103 | def __init__(self, endpoints=None): 104 | super(AmbiguousEndpoints, self).__init__( 105 | _("AmbiguousEndpoints: %s") % repr(endpoints)) 106 | self.endpoints = endpoints 107 | 108 | 109 | class HttpError(ClientException): 110 | """The base exception class for all HTTP exceptions.""" 111 | http_status = 0 112 | message = _("HTTP Error") 113 | 114 | def __init__(self, message=None, details=None, 115 | response=None, request_id=None, 116 | url=None, method=None, http_status=None): 117 | self.http_status = http_status or self.http_status 118 | self.message = message or self.message 119 | self.details = details 120 | self.request_id = request_id 121 | self.response = response 122 | self.url = url 123 | self.method = method 124 | formatted_string = "%s (HTTP %s)" % (self.message, self.http_status) 125 | if request_id: 126 | formatted_string += " (Request-ID: %s)" % request_id 127 | super(HttpError, self).__init__(formatted_string) 128 | 129 | 130 | class HTTPRedirection(HttpError): 131 | """HTTP Redirection.""" 132 | message = _("HTTP Redirection") 133 | 134 | 135 | class HTTPClientError(HttpError): 136 | """Client-side HTTP error. 137 | 138 | Exception for cases in which the client seems to have erred. 139 | """ 140 | message = _("HTTP Client Error") 141 | 142 | 143 | class HttpServerError(HttpError): 144 | """Server-side HTTP error. 145 | 146 | Exception for cases in which the server is aware that it has 147 | erred or is incapable of performing the request. 148 | """ 149 | message = _("HTTP Server Error") 150 | 151 | 152 | class MultipleChoices(HTTPRedirection): 153 | """HTTP 300 - Multiple Choices. 154 | 155 | Indicates multiple options for the resource that the client may follow. 156 | """ 157 | 158 | http_status = 300 159 | message = _("Multiple Choices") 160 | 161 | 162 | class BadRequest(HTTPClientError): 163 | """HTTP 400 - Bad Request. 164 | 165 | The request cannot be fulfilled due to bad syntax. 166 | """ 167 | http_status = 400 168 | message = _("Bad Request") 169 | 170 | 171 | class Unauthorized(HTTPClientError): 172 | """HTTP 401 - Unauthorized. 173 | 174 | Similar to 403 Forbidden, but specifically for use when authentication 175 | is required and has failed or has not yet been provided. 176 | """ 177 | http_status = 401 178 | message = _("Unauthorized") 179 | 180 | 181 | class PaymentRequired(HTTPClientError): 182 | """HTTP 402 - Payment Required. 183 | 184 | Reserved for future use. 185 | """ 186 | http_status = 402 187 | message = _("Payment Required") 188 | 189 | 190 | class Forbidden(HTTPClientError): 191 | """HTTP 403 - Forbidden. 192 | 193 | The request was a valid request, but the server is refusing to respond 194 | to it. 195 | """ 196 | http_status = 403 197 | message = _("Forbidden") 198 | 199 | 200 | class NotFound(HTTPClientError): 201 | """HTTP 404 - Not Found. 202 | 203 | The requested resource could not be found but may be available again 204 | in the future. 205 | """ 206 | http_status = 404 207 | message = _("Not Found") 208 | 209 | 210 | class MethodNotAllowed(HTTPClientError): 211 | """HTTP 405 - Method Not Allowed. 212 | 213 | A request was made of a resource using a request method not supported 214 | by that resource. 215 | """ 216 | http_status = 405 217 | message = _("Method Not Allowed") 218 | 219 | 220 | class NotAcceptable(HTTPClientError): 221 | """HTTP 406 - Not Acceptable. 222 | 223 | The requested resource is only capable of generating content not 224 | acceptable according to the Accept headers sent in the request. 225 | """ 226 | http_status = 406 227 | message = _("Not Acceptable") 228 | 229 | 230 | class ProxyAuthenticationRequired(HTTPClientError): 231 | """HTTP 407 - Proxy Authentication Required. 232 | 233 | The client must first authenticate itself with the proxy. 234 | """ 235 | http_status = 407 236 | message = _("Proxy Authentication Required") 237 | 238 | 239 | class RequestTimeout(HTTPClientError): 240 | """HTTP 408 - Request Timeout. 241 | 242 | The server timed out waiting for the request. 243 | """ 244 | http_status = 408 245 | message = _("Request Timeout") 246 | 247 | 248 | class Conflict(HTTPClientError): 249 | """HTTP 409 - Conflict. 250 | 251 | Indicates that the request could not be processed because of conflict 252 | in the request, such as an edit conflict. 253 | """ 254 | http_status = 409 255 | message = _("Conflict") 256 | 257 | 258 | class Gone(HTTPClientError): 259 | """HTTP 410 - Gone. 260 | 261 | Indicates that the resource requested is no longer available and will 262 | not be available again. 263 | """ 264 | http_status = 410 265 | message = _("Gone") 266 | 267 | 268 | class LengthRequired(HTTPClientError): 269 | """HTTP 411 - Length Required. 270 | 271 | The request did not specify the length of its content, which is 272 | required by the requested resource. 273 | """ 274 | http_status = 411 275 | message = _("Length Required") 276 | 277 | 278 | class PreconditionFailed(HTTPClientError): 279 | """HTTP 412 - Precondition Failed. 280 | 281 | The server does not meet one of the preconditions that the requester 282 | put on the request. 283 | """ 284 | http_status = 412 285 | message = _("Precondition Failed") 286 | 287 | 288 | class RequestEntityTooLarge(HTTPClientError): 289 | """HTTP 413 - Request Entity Too Large. 290 | 291 | The request is larger than the server is willing or able to process. 292 | """ 293 | http_status = 413 294 | message = _("Request Entity Too Large") 295 | 296 | def __init__(self, *args, **kwargs): 297 | try: 298 | self.retry_after = int(kwargs.pop('retry_after')) 299 | except (KeyError, ValueError): 300 | self.retry_after = 0 301 | 302 | super(RequestEntityTooLarge, self).__init__(*args, **kwargs) 303 | 304 | 305 | class RequestUriTooLong(HTTPClientError): 306 | """HTTP 414 - Request-URI Too Long. 307 | 308 | The URI provided was too long for the server to process. 309 | """ 310 | http_status = 414 311 | message = _("Request-URI Too Long") 312 | 313 | 314 | class UnsupportedMediaType(HTTPClientError): 315 | """HTTP 415 - Unsupported Media Type. 316 | 317 | The request entity has a media type which the server or resource does 318 | not support. 319 | """ 320 | http_status = 415 321 | message = _("Unsupported Media Type") 322 | 323 | 324 | class RequestedRangeNotSatisfiable(HTTPClientError): 325 | """HTTP 416 - Requested Range Not Satisfiable. 326 | 327 | The client has asked for a portion of the file, but the server cannot 328 | supply that portion. 329 | """ 330 | http_status = 416 331 | message = _("Requested Range Not Satisfiable") 332 | 333 | 334 | class ExpectationFailed(HTTPClientError): 335 | """HTTP 417 - Expectation Failed. 336 | 337 | The server cannot meet the requirements of the Expect request-header field. 338 | """ 339 | http_status = 417 340 | message = _("Expectation Failed") 341 | 342 | 343 | class UnprocessableEntity(HTTPClientError): 344 | """HTTP 422 - Unprocessable Entity. 345 | 346 | The request was well-formed but was unable to be followed due to semantic 347 | errors. 348 | """ 349 | http_status = 422 350 | message = _("Unprocessable Entity") 351 | 352 | 353 | class InternalServerError(HttpServerError): 354 | """HTTP 500 - Internal Server Error. 355 | 356 | A generic error message, given when no more specific message is suitable. 357 | """ 358 | http_status = 500 359 | message = _("Internal Server Error") 360 | 361 | 362 | # NotImplemented is a python keyword. 363 | class HttpNotImplemented(HttpServerError): 364 | """HTTP 501 - Not Implemented. 365 | 366 | The server either does not recognize the request method, or it lacks 367 | the ability to fulfill the request. 368 | """ 369 | http_status = 501 370 | message = _("Not Implemented") 371 | 372 | 373 | class BadGateway(HttpServerError): 374 | """HTTP 502 - Bad Gateway. 375 | 376 | The server was acting as a gateway or proxy and received an invalid 377 | response from the upstream server. 378 | """ 379 | http_status = 502 380 | message = _("Bad Gateway") 381 | 382 | 383 | class ServiceUnavailable(HttpServerError): 384 | """HTTP 503 - Service Unavailable. 385 | 386 | The server is currently unavailable. 387 | """ 388 | http_status = 503 389 | message = _("Service Unavailable") 390 | 391 | 392 | class GatewayTimeout(HttpServerError): 393 | """HTTP 504 - Gateway Timeout. 394 | 395 | The server was acting as a gateway or proxy and did not receive a timely 396 | response from the upstream server. 397 | """ 398 | http_status = 504 399 | message = _("Gateway Timeout") 400 | 401 | 402 | class HttpVersionNotSupported(HttpServerError): 403 | """HTTP 505 - HttpVersion Not Supported. 404 | 405 | The server does not support the HTTP protocol version used in the request. 406 | """ 407 | http_status = 505 408 | message = _("HTTP Version Not Supported") 409 | 410 | 411 | # _code_map contains all the classes that have http_status attribute. 412 | _code_map = dict( 413 | (getattr(obj, 'http_status', None), obj) 414 | for name, obj in six.iteritems(vars(sys.modules[__name__])) 415 | if inspect.isclass(obj) and getattr(obj, 'http_status', False) 416 | ) 417 | 418 | 419 | def from_response(response, method, url): 420 | """Returns an instance of :class:`HttpError` or subclass based on response. 421 | 422 | :param response: instance of `requests.Response` class 423 | :param method: HTTP method used for request 424 | :param url: URL used for request 425 | """ 426 | 427 | req_id = response.headers.get("x-openstack-request-id") 428 | # NOTE(hdd) true for older versions of nova and cinder 429 | if not req_id: 430 | req_id = response.headers.get("x-compute-request-id") 431 | kwargs = { 432 | "http_status": response.status_code, 433 | "response": response, 434 | "method": method, 435 | "url": url, 436 | "request_id": req_id, 437 | } 438 | if "retry-after" in response.headers: 439 | kwargs["retry_after"] = response.headers["retry-after"] 440 | 441 | content_type = response.headers.get("Content-Type", "") 442 | if content_type.startswith("application/json"): 443 | try: 444 | body = response.json() 445 | except ValueError: 446 | pass 447 | else: 448 | if isinstance(body, dict) and isinstance(body.get("error"), dict): 449 | error = body["error"] 450 | kwargs["message"] = error.get("message") 451 | kwargs["details"] = error.get("details") 452 | elif content_type.startswith("text/"): 453 | kwargs["details"] = response.text 454 | 455 | try: 456 | cls = _code_map[response.status_code] 457 | except KeyError: 458 | if 500 <= response.status_code < 600: 459 | cls = HttpServerError 460 | elif 400 <= response.status_code < 500: 461 | cls = HTTPClientError 462 | else: 463 | cls = HttpError 464 | return cls(**kwargs) 465 | -------------------------------------------------------------------------------- /congressclient/i18n.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | """oslo_i18n integration module for novaclient. 14 | 15 | See https://docs.openstack.org/oslo.i18n/latest/user/usage.html. 16 | 17 | """ 18 | 19 | import oslo_i18n 20 | 21 | 22 | _translators = oslo_i18n.TranslatorFactory(domain='congressclient') 23 | 24 | # The primary translation function using the well-known name "_" 25 | _ = _translators.primary 26 | -------------------------------------------------------------------------------- /congressclient/osc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/osc/__init__.py -------------------------------------------------------------------------------- /congressclient/osc/osc_plugin.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 VMWare. 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 | 15 | """OpenStackClient plugin for Governance service.""" 16 | 17 | from oslo_log import log as logging 18 | 19 | from congressclient.common import utils 20 | 21 | LOG = logging.getLogger(__name__) 22 | 23 | DEFAULT_POLICY_API_VERSION = '1' 24 | API_VERSION_OPTION = 'os_policy_api_version' 25 | API_NAME = 'congressclient' 26 | API_VERSIONS = { 27 | '1': 'congressclient.v1.client.Client', 28 | } 29 | 30 | 31 | def make_client(instance): 32 | """Returns a congress service client.""" 33 | congress_client = utils.get_client_class( 34 | API_NAME, 35 | instance._api_version[API_NAME], 36 | API_VERSIONS) 37 | LOG.debug('instantiating congress client: %s', congress_client) 38 | return congress_client(session=instance.session, 39 | auth=None, 40 | interface='publicURL', 41 | service_type='policy', 42 | region_name=instance._region_name) 43 | 44 | 45 | def build_option_parser(parser): 46 | """Hook to add global options.""" 47 | parser.add_argument( 48 | '--os-policy-api-version', 49 | metavar='', 50 | default=utils.env( 51 | 'OS_POLICY_API_VERSION', 52 | default=DEFAULT_POLICY_API_VERSION), 53 | help=('Policy API version, default=%s (Env: OS_POLICY_API_VERSION)' % 54 | DEFAULT_POLICY_API_VERSION)) 55 | return parser 56 | -------------------------------------------------------------------------------- /congressclient/osc/v1/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/osc/v1/__init__.py -------------------------------------------------------------------------------- /congressclient/osc/v1/api_versions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Huawei. 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 | """List API versions implemenations""" 17 | 18 | from cliff import lister 19 | from oslo_log import log as logging 20 | 21 | from congressclient.common import utils 22 | 23 | 24 | class ListAPIVersions(lister.Lister): 25 | """List API Versions.""" 26 | 27 | log = logging.getLogger(__name__ + '.ListAPIVersions') 28 | 29 | def get_parser(self, prog_name): 30 | return super(ListAPIVersions, self).get_parser(prog_name) 31 | 32 | def take_action(self, parsed_args): 33 | # set default max-width 34 | if parsed_args.max_width == 0: 35 | parsed_args.max_width = 80 36 | client = self.app.client_manager.congressclient 37 | data = client.list_api_versions()['versions'] 38 | # sort API by id 39 | data.sort(key=lambda item: item.get('id')) 40 | columns = ['id', 'status', 'updated'] 41 | return (columns, 42 | (utils.get_dict_properties(s, columns) for s in data)) 43 | -------------------------------------------------------------------------------- /congressclient/osc/v1/datasource.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012-2013 OpenStack, LLC. 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 | 15 | """Datasource action implemenations""" 16 | 17 | from cliff import command 18 | from cliff import lister 19 | from cliff import show 20 | from oslo_log import log as logging 21 | from oslo_serialization import jsonutils 22 | import six 23 | 24 | from congressclient.common import parseractions 25 | from congressclient.common import utils 26 | 27 | 28 | class ListDatasources(lister.Lister): 29 | """List Datasources.""" 30 | 31 | log = logging.getLogger(__name__ + '.ListDatasources') 32 | 33 | def get_parser(self, prog_name): 34 | parser = super(ListDatasources, self).get_parser(prog_name) 35 | return parser 36 | 37 | def take_action(self, parsed_args): 38 | # set default max-width 39 | if parsed_args.max_width == 0: 40 | parsed_args.max_width = 80 41 | client = self.app.client_manager.congressclient 42 | data = client.list_datasources()['results'] 43 | # Type is always None, so disabling it for now. 44 | columns = ['id', 'name', 'enabled', 'driver', 'config'] 45 | formatters = {'config': utils.format_dict} 46 | return (columns, 47 | (utils.get_dict_properties(s, columns, 48 | formatters=formatters) 49 | for s in data)) 50 | 51 | 52 | class ListDatasourceTables(lister.Lister): 53 | """List datasource tables.""" 54 | 55 | log = logging.getLogger(__name__ + '.ListDatasourceTables') 56 | 57 | def get_parser(self, prog_name): 58 | parser = super(ListDatasourceTables, self).get_parser(prog_name) 59 | parser.add_argument( 60 | 'datasource_name', 61 | metavar="", 62 | help="Name or ID of the datasource") 63 | return parser 64 | 65 | def take_action(self, parsed_args): 66 | self.log.debug('take_action(%s)' % parsed_args) 67 | # set default max-width 68 | if parsed_args.max_width == 0: 69 | parsed_args.max_width = 80 70 | client = self.app.client_manager.congressclient 71 | name_or_id = parsed_args.datasource_name 72 | data = client.list_datasource_tables(name_or_id)['results'] 73 | columns = ['id'] 74 | formatters = {'DatasourceTables': utils.format_list} 75 | return (columns, 76 | (utils.get_dict_properties(s, columns, 77 | formatters=formatters) 78 | for s in data)) 79 | 80 | 81 | class ShowDatasourceStatus(show.ShowOne): 82 | """List status for datasource.""" 83 | 84 | log = logging.getLogger(__name__ + '.ShowDatasourceStatus') 85 | 86 | def get_parser(self, prog_name): 87 | parser = super(ShowDatasourceStatus, self).get_parser(prog_name) 88 | parser.add_argument( 89 | 'datasource_name', 90 | metavar="", 91 | help="Name or ID of the datasource") 92 | return parser 93 | 94 | def take_action(self, parsed_args): 95 | self.log.debug('take_action(%s)' % parsed_args) 96 | # set default max-width 97 | if parsed_args.max_width == 0: 98 | parsed_args.max_width = 80 99 | client = self.app.client_manager.congressclient 100 | datasource_id = parsed_args.datasource_name 101 | data = client.list_datasource_status(datasource_id) 102 | return zip(*sorted(six.iteritems(data))) 103 | 104 | 105 | class ShowDatasourceActions(lister.Lister): 106 | """List supported actions for datasource.""" 107 | 108 | log = logging.getLogger(__name__ + '.ShowDatasourceActions') 109 | 110 | def get_parser(self, prog_name): 111 | parser = super(ShowDatasourceActions, self).get_parser(prog_name) 112 | parser.add_argument( 113 | 'datasource_name', 114 | metavar="", 115 | help="Name or ID of the datasource") 116 | return parser 117 | 118 | def take_action(self, parsed_args): 119 | self.log.debug('take_action(%s)' % parsed_args) 120 | # as we know output it's long, limit column length here 121 | if parsed_args.max_width == 0: 122 | parsed_args.max_width = 80 123 | 124 | client = self.app.client_manager.congressclient 125 | datasource_id = parsed_args.datasource_name 126 | data = client.list_datasource_actions(datasource_id) 127 | formatters = {'args': utils.format_long_dict_list} 128 | newdata = [{'action': x['name'], 129 | 'args': x['args'], 130 | 'description': x['description']} 131 | for x in data['results']] 132 | columns = ['action', 'args', 'description'] 133 | return (columns, (utils.get_dict_properties(s, 134 | columns, 135 | formatters=formatters) 136 | for s in newdata)) 137 | 138 | 139 | class ShowDatasourceSchema(lister.Lister): 140 | """Show schema for datasource.""" 141 | 142 | log = logging.getLogger(__name__ + '.ShowDatasourceSchema') 143 | 144 | def get_parser(self, prog_name): 145 | parser = super(ShowDatasourceSchema, self).get_parser(prog_name) 146 | parser.add_argument( 147 | 'datasource_name', 148 | metavar="", 149 | help="Name or ID of the datasource") 150 | return parser 151 | 152 | def take_action(self, parsed_args): 153 | self.log.debug('take_action(%s)' % parsed_args) 154 | # set default max-width 155 | if parsed_args.max_width == 0: 156 | parsed_args.max_width = 80 157 | client = self.app.client_manager.congressclient 158 | datasource_id = parsed_args.datasource_name 159 | data = client.show_datasource_schema(datasource_id) 160 | formatters = {'columns': utils.format_long_dict_list} 161 | newdata = [{'table': x['table_id'], 162 | 'columns': x['columns']} 163 | for x in data['tables']] 164 | columns = ['table', 'columns'] 165 | return (columns, 166 | (utils.get_dict_properties(s, columns, 167 | formatters=formatters) 168 | for s in newdata)) 169 | 170 | 171 | class ShowDatasourceTableSchema(lister.Lister): 172 | """Show schema for datasource table.""" 173 | 174 | log = logging.getLogger(__name__ + '.ShowDatasourceTableSchema') 175 | 176 | def get_parser(self, prog_name): 177 | parser = super(ShowDatasourceTableSchema, self).get_parser(prog_name) 178 | parser.add_argument( 179 | 'datasource_name', 180 | metavar="", 181 | help="Name or ID of the datasource") 182 | parser.add_argument( 183 | 'table_name', 184 | metavar="", 185 | help="Name of the table") 186 | return parser 187 | 188 | def take_action(self, parsed_args): 189 | self.log.debug('take_action(%s)' % parsed_args) 190 | # set default max-width 191 | if parsed_args.max_width == 0: 192 | parsed_args.max_width = 80 193 | client = self.app.client_manager.congressclient 194 | datasource_id = parsed_args.datasource_name 195 | data = client.show_datasource_table_schema( 196 | datasource_id, 197 | parsed_args.table_name) 198 | columns = ['name', 'description'] 199 | return (columns, 200 | (utils.get_dict_properties(s, columns) 201 | for s in data['columns'])) 202 | 203 | 204 | class ListDatasourceRows(lister.Lister): 205 | """List datasource rows.""" 206 | 207 | log = logging.getLogger(__name__ + '.ListDatasourceRows') 208 | 209 | def get_parser(self, prog_name): 210 | parser = super(ListDatasourceRows, self).get_parser(prog_name) 211 | parser.add_argument( 212 | 'datasource_name', 213 | metavar="", 214 | help="Name or ID of the datasource to show") 215 | parser.add_argument( 216 | 'table', 217 | metavar="", 218 | help="Table to get the datasource rows from") 219 | return parser 220 | 221 | def take_action(self, parsed_args): 222 | self.log.debug('take_action(%s)' % parsed_args) 223 | # set default max-width 224 | if parsed_args.max_width == 0: 225 | parsed_args.max_width = 80 226 | client = self.app.client_manager.congressclient 227 | datasource_id = parsed_args.datasource_name 228 | results = client.list_datasource_rows(datasource_id, 229 | parsed_args.table)['results'] 230 | if results: 231 | columns = client.show_datasource_table_schema( 232 | datasource_id, parsed_args.table)['columns'] 233 | columns = [col['name'] for col in columns] 234 | else: 235 | columns = ['data'] # doesn't matter because the rows are empty 236 | return (columns, (x['data'] for x in results)) 237 | 238 | 239 | class ShowDatasourceTable(show.ShowOne): 240 | """Show Datasource Table properties.""" 241 | 242 | log = logging.getLogger(__name__ + '.ShowDatasourceTable') 243 | 244 | def get_parser(self, prog_name): 245 | parser = super(ShowDatasourceTable, self).get_parser(prog_name) 246 | parser.add_argument( 247 | 'datasource_name', 248 | metavar='', 249 | help="Name or ID of datasource") 250 | parser.add_argument( 251 | 'table_id', 252 | metavar='', 253 | help="Table id") 254 | 255 | return parser 256 | 257 | def take_action(self, parsed_args): 258 | self.log.debug('take_action(%s)' % parsed_args) 259 | # set default max-width 260 | if parsed_args.max_width == 0: 261 | parsed_args.max_width = 80 262 | client = self.app.client_manager.congressclient 263 | data = client.show_datasource_table(parsed_args.datasource_name, 264 | parsed_args.table_id) 265 | return zip(*sorted(six.iteritems(data))) 266 | 267 | 268 | class CreateDatasource(show.ShowOne): 269 | """Create a datasource.""" 270 | 271 | log = logging.getLogger(__name__ + '.CreateDatasource') 272 | 273 | def get_parser(self, prog_name): 274 | parser = super(CreateDatasource, self).get_parser(prog_name) 275 | parser.add_argument( 276 | 'driver', 277 | metavar="", 278 | help="Selected datasource driver") 279 | parser.add_argument( 280 | 'name', 281 | metavar="", 282 | help="Name you want to call the datasource") 283 | parser.add_argument( 284 | '--description', 285 | metavar="", 286 | help="Description of the datasource") 287 | 288 | parser.add_argument( 289 | '--config', 290 | metavar="", 291 | action=parseractions.KeyValueAction, 292 | help="config dictionary to pass in") 293 | 294 | return parser 295 | 296 | def take_action(self, parsed_args): 297 | self.log.debug('take_action(%s)' % parsed_args) 298 | # set default max-width 299 | if parsed_args.max_width == 0: 300 | parsed_args.max_width = 80 301 | client = self.app.client_manager.congressclient 302 | body = {'name': parsed_args.name, 303 | 'driver': parsed_args.driver, 304 | 'config': parsed_args.config} 305 | if parsed_args.description: 306 | body['description'] = parsed_args.description 307 | results = client.create_datasource(body) 308 | return zip(*sorted(six.iteritems(results))) 309 | 310 | 311 | class DeleteDatasource(command.Command): 312 | """Delete a datasource.""" 313 | 314 | log = logging.getLogger(__name__ + '.DeleteDatasource') 315 | 316 | def get_parser(self, prog_name): 317 | parser = super(DeleteDatasource, self).get_parser(prog_name) 318 | parser.add_argument( 319 | 'datasource', 320 | metavar="", 321 | help="Name or ID of the datasource to delete") 322 | return parser 323 | 324 | def take_action(self, parsed_args): 325 | self.log.debug('take_action(%s)' % parsed_args) 326 | client = self.app.client_manager.congressclient 327 | try: 328 | datasource_id = parsed_args.datasource 329 | client.delete_datasource(datasource_id) 330 | except Exception: 331 | # for backwards compatibility with pre-Ocata congress server, 332 | # try old method of explicit conversion from name to UUID 333 | results = client.list_datasources() 334 | datasource_id = utils.get_resource_id_from_name( 335 | parsed_args.datasource, results) 336 | client.delete_datasource(datasource_id) 337 | 338 | 339 | class UpdateDatasourceRow(command.Command): 340 | """Update rows to a datasource table.""" 341 | 342 | log = logging.getLogger(__name__ + '.UpdateDatasourceRow') 343 | 344 | def get_parser(self, prog_name): 345 | parser = super(UpdateDatasourceRow, self).get_parser(prog_name) 346 | parser.add_argument( 347 | 'datasource', 348 | metavar="", 349 | help="Name or ID of the datasource to Update") 350 | parser.add_argument( 351 | 'table', 352 | metavar="
", 353 | help="Name or ID of the table to Update") 354 | parser.add_argument( 355 | 'rows', 356 | type=jsonutils.loads, 357 | metavar="", 358 | help=("List of Rows should be formmated json style." 359 | " ex. [[row1], [row2]]")) 360 | return parser 361 | 362 | def take_action(self, parsed_args): 363 | self.log.debug('take_action(%s)' % parsed_args) 364 | client = self.app.client_manager.congressclient 365 | body = parsed_args.rows 366 | client.update_datasource_rows( 367 | parsed_args.datasource, parsed_args.table, body) 368 | 369 | 370 | class DatasourceRequestRefresh(command.Command): 371 | """Trigger a datasource to poll.""" 372 | 373 | log = logging.getLogger(__name__ + '.DatasourceRequestRefresh') 374 | 375 | def get_parser(self, prog_name): 376 | parser = super(DatasourceRequestRefresh, self).get_parser(prog_name) 377 | parser.add_argument( 378 | 'datasource', 379 | metavar="", 380 | help="Name or ID of the datasource to poll") 381 | return parser 382 | 383 | def take_action(self, parsed_args): 384 | self.log.debug('take_action(%s)' % parsed_args) 385 | client = self.app.client_manager.congressclient 386 | results = client.list_datasources() 387 | datasource_id = utils.get_resource_id_from_name( 388 | parsed_args.datasource, results) 389 | client.request_refresh(datasource_id, {}) 390 | -------------------------------------------------------------------------------- /congressclient/osc/v1/driver.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012-2013 OpenStack, LLC. 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 | 15 | """Driver action implemenations""" 16 | 17 | from cliff import lister 18 | from cliff import show 19 | from oslo_log import log as logging 20 | import six 21 | 22 | from congressclient.common import utils 23 | 24 | 25 | class ListDrivers(lister.Lister): 26 | """List drivers.""" 27 | 28 | log = logging.getLogger(__name__ + '.ListDrivers') 29 | 30 | def get_parser(self, prog_name): 31 | parser = super(ListDrivers, self).get_parser(prog_name) 32 | return parser 33 | 34 | def take_action(self, parsed_args): 35 | # set default max-width 36 | if parsed_args.max_width == 0: 37 | parsed_args.max_width = 80 38 | client = self.app.client_manager.congressclient 39 | data = client.list_drivers()['results'] 40 | columns = ['id', 'description'] 41 | formatters = {'Drivers': utils.format_list} 42 | return (columns, 43 | (utils.get_dict_properties(s, columns, 44 | formatters=formatters) 45 | for s in data)) 46 | 47 | 48 | class ShowDriverConfig(show.ShowOne): 49 | """List driver tables.""" 50 | 51 | log = logging.getLogger(__name__ + '.ShowDriverConfig') 52 | 53 | def get_parser(self, prog_name): 54 | parser = super(ShowDriverConfig, self).get_parser(prog_name) 55 | parser.add_argument( 56 | 'driver', 57 | metavar="", 58 | help="Name of the datasource driver") 59 | return parser 60 | 61 | def take_action(self, parsed_args): 62 | self.log.debug('take_action(%s)' % parsed_args) 63 | # set default max-width 64 | if parsed_args.max_width == 0: 65 | parsed_args.max_width = 80 66 | client = self.app.client_manager.congressclient 67 | data = client.show_driver( 68 | parsed_args.driver) 69 | # remove table schema info from displaying 70 | del data['tables'] 71 | return zip(*sorted(six.iteritems(data))) 72 | columns = ['id'] 73 | formatters = {'DriverTables': utils.format_list} 74 | return (columns, 75 | (utils.get_dict_properties(s, columns, 76 | formatters=formatters) 77 | for s in data)) 78 | 79 | 80 | class ShowDriverSchema(lister.Lister): 81 | """List datasource tables.""" 82 | 83 | log = logging.getLogger(__name__ + '.ShowDriverSchema') 84 | 85 | def get_parser(self, prog_name): 86 | parser = super(ShowDriverSchema, self).get_parser(prog_name) 87 | parser.add_argument( 88 | 'driver', 89 | metavar="", 90 | help="Name of the datasource driver") 91 | return parser 92 | 93 | def take_action(self, parsed_args): 94 | self.log.debug('take_action(%s)' % parsed_args) 95 | # set default max-width 96 | if parsed_args.max_width == 0: 97 | parsed_args.max_width = 80 98 | client = self.app.client_manager.congressclient 99 | data = client.show_driver( 100 | parsed_args.driver) 101 | formatters = {'columns': utils.format_long_dict_list} 102 | newdata = [{'table': x['table_id'], 103 | 'columns': x['columns']} 104 | for x in data['tables']] 105 | columns = ['table', 'columns'] 106 | return (columns, 107 | (utils.get_dict_properties(s, columns, 108 | formatters=formatters) 109 | for s in newdata)) 110 | -------------------------------------------------------------------------------- /congressclient/osc/v1/policy.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012-2013 OpenStack, LLC. 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 | 15 | """Policy action implemenations""" 16 | 17 | import sys 18 | 19 | from cliff import command 20 | from cliff import lister 21 | from cliff import show 22 | from keystoneauth1 import exceptions 23 | from oslo_log import log as logging 24 | from oslo_serialization import jsonutils 25 | import six 26 | import yaml 27 | 28 | from congressclient.common import utils 29 | 30 | 31 | def _format_rule(rule): 32 | """Break up rule string so it fits on screen.""" 33 | 34 | rule_split = jsonutils.dumps(rule).split(":-") 35 | formatted_string = rule_split[0] + ":-\n" 36 | for rule in rule_split[1].split("), "): 37 | formatted_string += rule + '\n' 38 | return formatted_string 39 | 40 | 41 | def get_rule_id_from_name(client, parsed_args): 42 | results = client.list_policy_rules(parsed_args.policy_name)['results'] 43 | rule_id = None 44 | for result in results: 45 | if result.get('name') == parsed_args.rule_id: 46 | if rule_id is None: 47 | rule_id = result.get('id') 48 | else: 49 | raise exceptions.Conflict( 50 | "[Multiple rules with same name: %s]" % 51 | parsed_args.rule_id) 52 | if rule_id is None: 53 | raise exceptions.NotFound( 54 | "[No rule found with name: %s]" % parsed_args.rule_id) 55 | return rule_id 56 | 57 | 58 | class CreatePolicyRule(show.ShowOne): 59 | """Create a policy rule.""" 60 | 61 | log = logging.getLogger(__name__ + '.CreatePolicyRule') 62 | 63 | def get_parser(self, prog_name): 64 | parser = super(CreatePolicyRule, self).get_parser(prog_name) 65 | parser.add_argument( 66 | 'policy_name', 67 | metavar="", 68 | help="Name or identifier of the policy") 69 | parser.add_argument( 70 | 'rule', 71 | metavar="", 72 | help="Policy rule") 73 | parser.add_argument( 74 | '--name', dest="rule_name", 75 | help="Name of the policy rule") 76 | parser.add_argument( 77 | '--comment', dest="comment", 78 | help="Comment about policy rule") 79 | return parser 80 | 81 | def take_action(self, parsed_args): 82 | self.log.debug('take_action(%s)' % parsed_args) 83 | # set default max-width 84 | if parsed_args.max_width == 0: 85 | parsed_args.max_width = 80 86 | client = self.app.client_manager.congressclient 87 | body = {'rule': parsed_args.rule} 88 | if parsed_args.rule_name: 89 | body['name'] = parsed_args.rule_name 90 | if parsed_args.comment: 91 | body['comment'] = parsed_args.comment 92 | data = client.create_policy_rule(parsed_args.policy_name, body) 93 | return zip(*sorted(six.iteritems(data))) 94 | 95 | 96 | class DeletePolicyRule(command.Command): 97 | """Delete a policy rule.""" 98 | 99 | log = logging.getLogger(__name__ + '.DeletePolicyRule') 100 | 101 | def get_parser(self, prog_name): 102 | parser = super(DeletePolicyRule, self).get_parser(prog_name) 103 | parser.add_argument( 104 | 'policy_name', 105 | metavar="", 106 | help="Name of the policy to delete") 107 | parser.add_argument( 108 | 'rule_id', 109 | metavar="", 110 | help="ID/Name of the policy rule to delete") 111 | return parser 112 | 113 | def take_action(self, parsed_args): 114 | self.log.debug('take_action(%s)' % parsed_args) 115 | client = self.app.client_manager.congressclient 116 | results = client.list_policy_rules(parsed_args.policy_name) 117 | rule_id = utils.get_resource_id_from_name( 118 | parsed_args.rule_id, results) 119 | client.delete_policy_rule(parsed_args.policy_name, rule_id) 120 | 121 | 122 | class ListPolicyRules(command.Command): 123 | """List policy rules.""" 124 | 125 | log = logging.getLogger(__name__ + '.ListPolicyRules') 126 | 127 | def get_parser(self, prog_name): 128 | parser = super(ListPolicyRules, self).get_parser(prog_name) 129 | parser.add_argument( 130 | 'policy_name', 131 | metavar="", 132 | help="Name of the policy") 133 | return parser 134 | 135 | def take_action(self, parsed_args): 136 | self.log.debug('take_action(%s)' % parsed_args) 137 | client = self.app.client_manager.congressclient 138 | results = client.list_policy_rules(parsed_args.policy_name)['results'] 139 | for result in results: 140 | print("// ID: %s" % str(result['id'])) 141 | print("// Name: %s" % str(result.get('name'))) 142 | if result['comment'] != "None" and result['comment']: 143 | print("// %s" % str(result['comment'])) 144 | print(result['rule']) 145 | print('') 146 | return 0 147 | 148 | 149 | class SimulatePolicy(command.Command): 150 | """Show the result of simulation.""" 151 | 152 | log = logging.getLogger(__name__ + '.SimulatePolicy') 153 | 154 | def get_parser(self, prog_name): 155 | parser = super(SimulatePolicy, self).get_parser(prog_name) 156 | parser.add_argument( 157 | 'policy', 158 | metavar="", 159 | help="Name of the policy") 160 | parser.add_argument( 161 | 'query', 162 | metavar="", 163 | help="String representing query (policy rule or literal)") 164 | parser.add_argument( 165 | 'sequence', 166 | metavar="", 167 | help="String representing sequence of updates/actions") 168 | parser.add_argument( 169 | 'action_policy', 170 | metavar="", 171 | help="Name of the policy with actions", 172 | default=None) 173 | parser.add_argument( 174 | '--delta', 175 | action='store_true', 176 | default=False, 177 | help="Return difference in query caused by update sequence") 178 | parser.add_argument( 179 | '--trace', 180 | action='store_true', 181 | default=False, 182 | help="Include trace describing computation") 183 | return parser 184 | 185 | def take_action(self, parsed_args): 186 | self.log.debug('take_action(%s)' % parsed_args) 187 | client = self.app.client_manager.congressclient 188 | args = {} 189 | args['query'] = parsed_args.query 190 | args['sequence'] = parsed_args.sequence 191 | if parsed_args.action_policy is not None: 192 | args['action_policy'] = parsed_args.action_policy 193 | if parsed_args.delta: 194 | args['delta'] = parsed_args.delta 195 | if parsed_args.trace: 196 | args['trace'] = parsed_args.trace 197 | 198 | body = {'query': parsed_args.query, 199 | 'sequence': parsed_args.sequence, 200 | 'action_policy': parsed_args.action_policy} 201 | 202 | results = client.execute_policy_action( 203 | policy_name=parsed_args.policy, 204 | action="simulate", 205 | trace=parsed_args.trace, 206 | delta=parsed_args.delta, 207 | body=body) 208 | for result in results['result']: 209 | print(result) 210 | if 'trace' in results: 211 | print(results['trace']) 212 | return 0 213 | 214 | 215 | class ListPolicyTables(lister.Lister): 216 | """List policy tables.""" 217 | 218 | log = logging.getLogger(__name__ + '.ListPolicyTables') 219 | 220 | def get_parser(self, prog_name): 221 | parser = super(ListPolicyTables, self).get_parser(prog_name) 222 | parser.add_argument( 223 | 'policy_name', 224 | metavar="", 225 | help="Name of the policy") 226 | return parser 227 | 228 | def take_action(self, parsed_args): 229 | self.log.debug('take_action(%s)' % parsed_args) 230 | # set default max-width 231 | if parsed_args.max_width == 0: 232 | parsed_args.max_width = 80 233 | client = self.app.client_manager.congressclient 234 | data = client.list_policy_tables(parsed_args.policy_name)['results'] 235 | columns = ['id'] 236 | formatters = {'PolicyTables': utils.format_list} 237 | return (columns, 238 | (utils.get_dict_properties(s, columns, 239 | formatters=formatters) 240 | for s in data)) 241 | 242 | 243 | class ListPolicy(lister.Lister): 244 | """List Policy.""" 245 | 246 | log = logging.getLogger(__name__ + '.ListPolicy') 247 | 248 | def get_parser(self, prog_name): 249 | parser = super(ListPolicy, self).get_parser(prog_name) 250 | return parser 251 | 252 | def take_action(self, parsed_args): 253 | # set default max-width 254 | if parsed_args.max_width == 0: 255 | parsed_args.max_width = 80 256 | client = self.app.client_manager.congressclient 257 | data = client.list_policy()['results'] 258 | columns = ['id', 'name', 'owner_id', 'kind', 'description'] 259 | formatters = {'Policies': utils.format_list} 260 | return (columns, 261 | (utils.get_dict_properties(s, columns, 262 | formatters=formatters) 263 | for s in data)) 264 | 265 | 266 | class CreatePolicy(show.ShowOne): 267 | """Create a policy.""" 268 | 269 | log = logging.getLogger(__name__ + '.CreatePolicy') 270 | 271 | def get_parser(self, prog_name): 272 | parser = super(CreatePolicy, self).get_parser(prog_name) 273 | parser.add_argument( 274 | 'policy_name', 275 | metavar="", 276 | help="Name of the policy") 277 | parser.add_argument( 278 | '--description', 279 | metavar="", 280 | help="Policy description") 281 | parser.add_argument( 282 | '--abbreviation', 283 | metavar="", 284 | help="Policy abbreviation (used in traces). The length of the " 285 | "string must be equal to or less than 5 characters. Defaults " 286 | "to the first five characters of policy_name if not set.") 287 | parser.add_argument( 288 | '--kind', 289 | metavar="", 290 | choices=['nonrecursive', 'database', 'action', 'materialized', 291 | 'z3'], 292 | help="Kind of policy: " 293 | "{nonrecursive, database, action, materialized, z3}") 294 | return parser 295 | 296 | def take_action(self, parsed_args): 297 | self.log.debug('take_action(%s)' % parsed_args) 298 | # set default max-width 299 | if parsed_args.max_width == 0: 300 | parsed_args.max_width = 80 301 | client = self.app.client_manager.congressclient 302 | body = {'name': parsed_args.policy_name, 303 | 'description': parsed_args.description, 304 | 'abbreviation': parsed_args.abbreviation, 305 | 'kind': parsed_args.kind} 306 | data = client.create_policy(body) 307 | return zip(*sorted(six.iteritems(data))) 308 | 309 | 310 | class CreatePolicyFromFile(show.ShowOne): 311 | """Create a policy.""" 312 | 313 | log = logging.getLogger(__name__ + '.CreatePolicy') 314 | 315 | def get_parser(self, prog_name): 316 | parser = super(CreatePolicyFromFile, self).get_parser(prog_name) 317 | parser.add_argument( 318 | 'policy_file_path', 319 | metavar="", 320 | help="Path to policy file") 321 | return parser 322 | 323 | def take_action(self, parsed_args): 324 | self.log.debug('take_action(%s)' % parsed_args) 325 | # set default max-width 326 | if parsed_args.max_width == 0: 327 | parsed_args.max_width = 80 328 | client = self.app.client_manager.congressclient 329 | with open(parsed_args.policy_file_path, "r") as stream: 330 | policies = yaml.load_all(stream) 331 | try: 332 | body = next(policies) 333 | except StopIteration: 334 | raise Exception('No policy found in file.') 335 | try: 336 | body = next(policies) 337 | raise Exception( 338 | 'More than one policy found in file. None imported.') 339 | except StopIteration: 340 | pass 341 | data = client.create_policy(body) 342 | 343 | def rule_dict_to_string(rules): 344 | rule_str_list = [rule['rule'] for rule in rules] 345 | return "\n".join(rule_str_list) 346 | 347 | data['rules'] = rule_dict_to_string(data['rules']) 348 | return zip(*sorted(six.iteritems(data))) 349 | 350 | 351 | class DeletePolicy(command.Command): 352 | """Delete a policy.""" 353 | 354 | log = logging.getLogger(__name__ + '.DeletePolicy') 355 | 356 | def get_parser(self, prog_name): 357 | parser = super(DeletePolicy, self).get_parser(prog_name) 358 | parser.add_argument( 359 | 'policy', 360 | metavar="", 361 | help="ID or name of the policy to delete") 362 | return parser 363 | 364 | def take_action(self, parsed_args): 365 | self.log.debug('take_action(%s)' % parsed_args) 366 | client = self.app.client_manager.congressclient 367 | 368 | client.delete_policy(parsed_args.policy) 369 | 370 | 371 | class ListPolicyRows(lister.Lister): 372 | """List policy rows.""" 373 | 374 | log = logging.getLogger(__name__ + '.ListPolicyRows') 375 | 376 | def get_parser(self, prog_name): 377 | parser = super(ListPolicyRows, self).get_parser(prog_name) 378 | parser.add_argument( 379 | 'policy_name', 380 | metavar="", 381 | help="Name of the policy to show") 382 | parser.add_argument( 383 | 'table', 384 | metavar="
", 385 | help="Table to get the policy rows from") 386 | parser.add_argument( 387 | '--trace', 388 | action='store_true', 389 | default=False, 390 | help="Display explanation of result") 391 | return parser 392 | 393 | def take_action(self, parsed_args): 394 | self.log.debug('take_action(%s)' % parsed_args) 395 | # set default max-width 396 | if parsed_args.max_width == 0: 397 | parsed_args.max_width = 80 398 | client = self.app.client_manager.congressclient 399 | answer = client.list_policy_rows(parsed_args.policy_name, 400 | parsed_args.table, 401 | parsed_args.trace) 402 | 403 | if 'trace' in answer: 404 | sys.stdout.write(answer['trace'] + '\n') 405 | results = answer['results'] 406 | columns = [] 407 | if results: 408 | columns = ['Col%s' % (i) 409 | for i in range(0, len(results[0]['data']))] 410 | self.log.debug("Columns: " + str(columns)) 411 | return (columns, (x['data'] for x in results)) 412 | 413 | 414 | class ShowPolicyRule(show.ShowOne): 415 | """Show a policy rule.""" 416 | 417 | log = logging.getLogger(__name__ + '.ShowPolicyRule') 418 | 419 | def get_parser(self, prog_name): 420 | parser = super(ShowPolicyRule, self).get_parser(prog_name) 421 | parser.add_argument( 422 | 'policy_name', 423 | metavar="", 424 | help="Name or identifier of the policy") 425 | parser.add_argument( 426 | 'rule_id', 427 | metavar="", 428 | help="Policy rule id or rule name") 429 | 430 | return parser 431 | 432 | def take_action(self, parsed_args): 433 | self.log.debug('take_action(%s)' % parsed_args) 434 | # set default max-width 435 | if parsed_args.max_width == 0: 436 | parsed_args.max_width = 80 437 | client = self.app.client_manager.congressclient 438 | results = client.list_policy_rules(parsed_args.policy_name) 439 | rule_id = utils.get_resource_id_from_name( 440 | parsed_args.rule_id, results) 441 | data = client.show_policy_rule(parsed_args.policy_name, rule_id) 442 | return zip(*sorted(six.iteritems(data))) 443 | 444 | 445 | class ShowPolicyTable(show.ShowOne): 446 | """Show policy table properties.""" 447 | 448 | log = logging.getLogger(__name__ + '.ShowPolicyTable') 449 | 450 | def get_parser(self, prog_name): 451 | parser = super(ShowPolicyTable, self).get_parser(prog_name) 452 | parser.add_argument( 453 | 'policy_name', 454 | metavar='', 455 | help="Name of policy") 456 | parser.add_argument( 457 | 'table_id', 458 | metavar='', 459 | help="Table id") 460 | 461 | return parser 462 | 463 | def take_action(self, parsed_args): 464 | self.log.debug('take_action(%s)' % parsed_args) 465 | # set default max-width 466 | if parsed_args.max_width == 0: 467 | parsed_args.max_width = 80 468 | client = self.app.client_manager.congressclient 469 | data = client.show_policy_table(parsed_args.policy_name, 470 | parsed_args.table_id) 471 | return zip(*sorted(six.iteritems(data))) 472 | 473 | 474 | class ShowPolicy(show.ShowOne): 475 | """Show policy properties.""" 476 | 477 | log = logging.getLogger(__name__ + '.ShowPolicy') 478 | 479 | def get_parser(self, prog_name): 480 | parser = super(ShowPolicy, self).get_parser(prog_name) 481 | parser.add_argument( 482 | 'policy_name', 483 | metavar='', 484 | help="Name of policy") 485 | 486 | return parser 487 | 488 | def take_action(self, parsed_args): 489 | self.log.debug('take_action(%s)' % parsed_args) 490 | # set default max-width 491 | if parsed_args.max_width == 0: 492 | parsed_args.max_width = 80 493 | client = self.app.client_manager.congressclient 494 | results = client.list_policy() 495 | policy_id = utils.get_resource_id_from_name( 496 | parsed_args.policy_name, results) 497 | data = client.show_policy(policy_id) 498 | return zip(*sorted(six.iteritems(data))) 499 | -------------------------------------------------------------------------------- /congressclient/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/tests/__init__.py -------------------------------------------------------------------------------- /congressclient/tests/base.py: -------------------------------------------------------------------------------- 1 | # Copyright 2010-2011 OpenStack Foundation 2 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. 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 | import os 17 | 18 | import fixtures 19 | import testtools 20 | 21 | _TRUE_VALUES = ('True', 'true', '1', 'yes') 22 | 23 | 24 | class TestCase(testtools.TestCase): 25 | 26 | """Test case base class for all unit tests.""" 27 | 28 | def setUp(self): 29 | """Run before each test method to initialize test environment.""" 30 | 31 | super(TestCase, self).setUp() 32 | test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) 33 | try: 34 | test_timeout = int(test_timeout) 35 | except ValueError: 36 | # If timeout value is invalid do not set a timeout. 37 | test_timeout = 0 38 | if test_timeout > 0: 39 | self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) 40 | 41 | self.useFixture(fixtures.NestedTempfile()) 42 | self.useFixture(fixtures.TempHomeDir()) 43 | 44 | if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: 45 | stdout = self.useFixture(fixtures.StringStream('stdout')).stream 46 | self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) 47 | if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: 48 | stderr = self.useFixture(fixtures.StringStream('stderr')).stream 49 | self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) 50 | 51 | self.log_fixture = self.useFixture(fixtures.FakeLogger()) 52 | -------------------------------------------------------------------------------- /congressclient/tests/common.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | # 13 | 14 | import argparse 15 | 16 | import mock 17 | 18 | from congressclient.tests import utils 19 | 20 | 21 | class TestCongressBase(utils.TestCommand): 22 | def setUp(self): 23 | super(TestCongressBase, self).setUp() 24 | self.app = mock.Mock(name='app') 25 | self.app.client_manager = mock.Mock(name='client_manager') 26 | self.namespace = argparse.Namespace() 27 | 28 | given_show_options = [ 29 | '-f', 30 | 'shell', 31 | '-c', 32 | 'id', 33 | '--prefix', 34 | 'TST', 35 | ] 36 | then_show_options = [ 37 | ('formatter', 'shell'), 38 | ('columns', ['id']), 39 | ('prefix', 'TST'), 40 | ] 41 | given_list_options = [ 42 | '-f', 43 | 'csv', 44 | '-c', 45 | 'id', 46 | '--quote', 47 | 'all', 48 | ] 49 | then_list_options = [ 50 | ('formatter', 'csv'), 51 | ('columns', ['id']), 52 | ('quote_mode', 'all'), 53 | ] 54 | -------------------------------------------------------------------------------- /congressclient/tests/fakes.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Nebula Inc. 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 | # 15 | 16 | import sys 17 | 18 | import six 19 | 20 | 21 | AUTH_TOKEN = "foobar" 22 | AUTH_URL = "http://0.0.0.0" 23 | 24 | 25 | class FakeStdout(object): 26 | def __init__(self): 27 | self.content = [] 28 | 29 | def write(self, text): 30 | self.content.append(text) 31 | 32 | def make_string(self): 33 | result = '' 34 | for line in self.content: 35 | result = result + line 36 | return result 37 | 38 | 39 | class FakeApp(object): 40 | def __init__(self, _stdout): 41 | self.stdout = _stdout 42 | self.client_manager = None 43 | self.stdin = sys.stdin 44 | self.stdout = _stdout or sys.stdout 45 | self.stderr = sys.stderr 46 | self.restapi = None 47 | 48 | 49 | class FakeClientManager(object): 50 | def __init__(self): 51 | self.compute = None 52 | self.identity = None 53 | self.image = None 54 | self.object = None 55 | self.volume = None 56 | self.network = None 57 | self.auth_ref = None 58 | 59 | 60 | class FakeModule(object): 61 | def __init__(self, name, version): 62 | self.name = name 63 | self.__version__ = version 64 | 65 | 66 | class FakeResource(object): 67 | def __init__(self, manager, info, loaded=False): 68 | self.manager = manager 69 | self._info = info 70 | self._add_details(info) 71 | self._loaded = loaded 72 | 73 | def _add_details(self, info): 74 | for (k, v) in six.iteritems(info): 75 | setattr(self, k, v) 76 | 77 | def __repr__(self): 78 | reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and 79 | k != 'manager') 80 | info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys) 81 | return "<%s %s>" % (self.__class__.__name__, info) 82 | -------------------------------------------------------------------------------- /congressclient/tests/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012-2013 OpenStack Foundation 2 | # Copyright 2013 Nebula 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 | 17 | import os 18 | import sys 19 | 20 | import fixtures 21 | import testtools 22 | 23 | from congressclient.tests import fakes 24 | 25 | 26 | class TestCase(testtools.TestCase): 27 | def setUp(self): 28 | testtools.TestCase.setUp(self) 29 | 30 | if (os.environ.get("OS_STDOUT_CAPTURE") == "True" or 31 | os.environ.get("OS_STDOUT_CAPTURE") == "1"): 32 | stdout = self.useFixture(fixtures.StringStream("stdout")).stream 33 | self.useFixture(fixtures.MonkeyPatch("sys.stdout", stdout)) 34 | 35 | if (os.environ.get("OS_STDERR_CAPTURE") == "True" or 36 | os.environ.get("OS_STDERR_CAPTURE") == "1"): 37 | stderr = self.useFixture(fixtures.StringStream("stderr")).stream 38 | self.useFixture(fixtures.MonkeyPatch("sys.stderr", stderr)) 39 | 40 | def assertNotCalled(self, m, msg=None): 41 | """Assert a function was not called.""" 42 | 43 | if m.called: 44 | if not msg: 45 | msg = 'method %s should not have been called' % m 46 | self.fail(msg) 47 | 48 | # 2.6 doesn't have the assert dict equals so make sure that it exists 49 | if tuple(sys.version_info)[0:2] < (2, 7): 50 | 51 | def assertIsInstance(self, obj, cls, msg=None): 52 | """self.assertTrue(isinstance(obj, cls)), with a nicer message.""" 53 | 54 | if not isinstance(obj, cls): 55 | standardMsg = '%s is not an instance of %r' % (obj, cls) 56 | self.fail(self._formatMessage(msg, standardMsg)) 57 | 58 | def assertDictEqual(self, d1, d2, msg=None): 59 | # Simple version taken from 2.7 60 | self.assertIsInstance(d1, dict, 61 | 'First argument is not a dictionary') 62 | self.assertIsInstance(d2, dict, 63 | 'Second argument is not a dictionary') 64 | if d1 != d2: 65 | if msg: 66 | self.fail(msg) 67 | else: 68 | standardMsg = '%r != %r' % (d1, d2) 69 | self.fail(standardMsg) 70 | 71 | 72 | class TestCommand(TestCase): 73 | """Test cliff command classes.""" 74 | 75 | def setUp(self): 76 | super(TestCommand, self).setUp() 77 | # Build up a fake app 78 | self.fake_stdout = fakes.FakeStdout() 79 | self.app = fakes.FakeApp(self.fake_stdout) 80 | self.app.client_manager = fakes.FakeClientManager() 81 | 82 | def check_parser(self, cmd, args, verify_args): 83 | cmd_parser = cmd.get_parser('check_parser') 84 | try: 85 | parsed_args = cmd_parser.parse_args(args) 86 | except SystemExit: 87 | raise Exception("Argument parse failed") 88 | for av in verify_args: 89 | attr, value = av 90 | if attr: 91 | self.assertIn(attr, parsed_args) 92 | self.assertEqual(getattr(parsed_args, attr), value) 93 | return parsed_args 94 | -------------------------------------------------------------------------------- /congressclient/tests/v1/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/tests/v1/__init__.py -------------------------------------------------------------------------------- /congressclient/tests/v1/test_api_versions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Huawei. 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 | import mock 17 | 18 | from congressclient.osc.v1 import api_versions 19 | from congressclient.tests import common 20 | 21 | 22 | class TestAPIVersions(common.TestCongressBase): 23 | 24 | def test_list_api_versions(self): 25 | fake_response = { 26 | "versions": [ 27 | { 28 | "status": "CURRENT", 29 | "updated": "2015-08-12T17:42:13Z", 30 | "id": "v2", 31 | "links": [ 32 | { 33 | "href": "http://localhost:1789/v2/", 34 | "rel": "self" 35 | } 36 | ] 37 | }, 38 | { 39 | "status": "SUPPORTED", 40 | "updated": "2013-08-12T17:42:13Z", 41 | "id": "v1", 42 | "links": [ 43 | { 44 | "href": "http://localhost:1789/v1/", 45 | "rel": "self" 46 | } 47 | ] 48 | } 49 | ] 50 | } 51 | 52 | with mock.patch.object(self.app.client_manager.congressclient, 53 | 'list_api_versions', 54 | return_value=fake_response) as lister: 55 | 56 | cmd = api_versions.ListAPIVersions(self.app, self.namespace) 57 | parsed_args = self.check_parser(cmd, [], []) 58 | result = cmd.take_action(parsed_args) 59 | 60 | lister.assert_called_once_with() 61 | self.assertEqual(['id', 'status', 'updated'], result[0]) 62 | self.assertEqual(('v1', 'SUPPORTED', '2013-08-12T17:42:13Z'), 63 | next(result[1])) 64 | self.assertEqual(('v2', 'CURRENT', '2015-08-12T17:42:13Z'), 65 | next(result[1])) 66 | -------------------------------------------------------------------------------- /congressclient/tests/v1/test_datasource.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | # 13 | 14 | import mock 15 | from oslo_serialization import jsonutils 16 | 17 | from congressclient.common import utils 18 | from congressclient.osc.v1 import datasource 19 | from congressclient.tests import common 20 | 21 | 22 | class TestListDatasources(common.TestCongressBase): 23 | def test_list_datasource(self): 24 | datasource_name = 'neutron' 25 | arglist = [ 26 | ] 27 | verifylist = [ 28 | ] 29 | response = { 30 | "results": [{"id": datasource_name, 31 | "name": "my_name", 32 | "enabled": "True", 33 | "driver": "driver1", 34 | "config": None}] 35 | } 36 | lister = mock.Mock(return_value=response) 37 | self.app.client_manager.congressclient.list_datasources = lister 38 | cmd = datasource.ListDatasources(self.app, self.namespace) 39 | 40 | parsed_args = self.check_parser(cmd, arglist, verifylist) 41 | result = cmd.take_action(parsed_args) 42 | 43 | lister.assert_called_with() 44 | self.assertEqual(['id', 'name', 'enabled', 'driver', 'config'], 45 | result[0]) 46 | for row in result[1]: 47 | self.assertEqual(datasource_name, row[0]) 48 | self.assertEqual("my_name", row[1]) 49 | self.assertEqual("True", row[2]) 50 | self.assertEqual("driver1", row[3]) 51 | self.assertEqual("None", row[4]) 52 | 53 | def test_list_datasource_output_not_unicode(self): 54 | # response json string is converted to dict by oslo jsonutils.loads(), 55 | # so the key and value in the dict should be unicode type. 56 | response = { 57 | u"results": [{u"id": u"neutron", 58 | u"name": u"my_name", 59 | u"enabled": True, 60 | u"driver": 'driver1', 61 | u"config": { 62 | u'username': u'admin', 63 | u'project_name': u'admin', 64 | u'poll_time': u'10', 65 | u'password': u'', 66 | u'auth_url': u'http://127.0.0.1:5000/v2.0' 67 | }}] 68 | } 69 | lister = mock.Mock(return_value=response) 70 | self.app.client_manager.congressclient.list_datasources = lister 71 | cmd = datasource.ListDatasources(self.app, self.namespace) 72 | 73 | parsed_args = self.check_parser(cmd, [], []) 74 | result = cmd.take_action(parsed_args) 75 | 76 | lister.assert_called_with() 77 | self.assertEqual(['id', 'name', 'enabled', 'driver', 'config'], 78 | result[0]) 79 | # get 'config' column 80 | config = list(result[1])[0][-1] 81 | self.assertIn("'username': 'admin'", config) 82 | self.assertNotIn("u'username': u'admin'", config) 83 | 84 | 85 | class TestListDatasourceTables(common.TestCongressBase): 86 | def test_list_datasource_tables(self): 87 | datasource_name = 'neutron' 88 | arglist = [ 89 | datasource_name 90 | ] 91 | verifylist = [ 92 | ('datasource_name', datasource_name) 93 | ] 94 | response = { 95 | "results": [{"id": "ports"}, 96 | {"id": "networks"}] 97 | } 98 | lister = mock.Mock(return_value=response) 99 | self.app.client_manager.congressclient.list_datasource_tables = lister 100 | cmd = datasource.ListDatasourceTables(self.app, self.namespace) 101 | 102 | parsed_args = self.check_parser(cmd, arglist, verifylist) 103 | 104 | result = cmd.take_action(parsed_args) 105 | lister.assert_called_with(datasource_name) 106 | self.assertEqual(['id'], result[0]) 107 | 108 | 109 | class TestListDatasourceStatus(common.TestCongressBase): 110 | def test_list_datasource_status(self): 111 | datasource_name = 'neutron' 112 | arglist = [ 113 | datasource_name 114 | ] 115 | verifylist = [ 116 | ('datasource_name', datasource_name) 117 | ] 118 | response = {'last_updated': "now", 119 | 'last_error': "None"} 120 | lister = mock.Mock(return_value=response) 121 | self.app.client_manager.congressclient.list_datasource_status = lister 122 | cmd = datasource.ShowDatasourceStatus(self.app, self.namespace) 123 | 124 | parsed_args = self.check_parser(cmd, arglist, verifylist) 125 | result = list(cmd.take_action(parsed_args)) 126 | 127 | lister.assert_called_with(datasource_name) 128 | self.assertEqual([('last_error', 'last_updated'), 129 | ('None', 'now')], 130 | result) 131 | 132 | 133 | class TestShowDatasourceActions(common.TestCongressBase): 134 | def test_show_datasource_actions(self): 135 | datasource_name = 'fake' 136 | arglist = [ 137 | datasource_name 138 | ] 139 | verifylist = [ 140 | ('datasource_name', datasource_name) 141 | ] 142 | response = { 143 | "results": 144 | [{'name': 'execute', 145 | 'args': [{"name": "name", "description": "None"}, 146 | {"name": "status", "description": "None"}, 147 | {"name": "id", "description": "None"}], 148 | 'description': 'execute action'}] 149 | } 150 | lister = mock.Mock(return_value=response) 151 | self.app.client_manager.congressclient.list_datasource_actions = lister 152 | cmd = datasource.ShowDatasourceActions(self.app, self.namespace) 153 | 154 | parsed_args = self.check_parser(cmd, arglist, verifylist) 155 | result = cmd.take_action(parsed_args) 156 | 157 | lister.assert_called_once_with(datasource_name) 158 | self.assertEqual(['action', 'args', 'description'], result[0]) 159 | 160 | 161 | class TestShowDatasourceSchema(common.TestCongressBase): 162 | def test_show_datasource_schema(self): 163 | datasource_name = 'neutron' 164 | arglist = [ 165 | datasource_name 166 | ] 167 | verifylist = [ 168 | ('datasource_name', datasource_name) 169 | ] 170 | response = { 171 | "tables": 172 | [{'table_id': 'ports', 173 | 'columns': [{"name": "name", "description": "None"}, 174 | {"name": "status", "description": "None"}, 175 | {"name": "id", "description": "None"}]}, 176 | {'table_id': 'routers', 177 | 'columns': [{"name": "name", "description": "None"}, 178 | {"name": "floating_ip", "description": "None"}, 179 | {"name": "id", "description": "None"}]}] 180 | } 181 | lister = mock.Mock(return_value=response) 182 | self.app.client_manager.congressclient.show_datasource_schema = lister 183 | cmd = datasource.ShowDatasourceSchema(self.app, self.namespace) 184 | 185 | parsed_args = self.check_parser(cmd, arglist, verifylist) 186 | result = cmd.take_action(parsed_args) 187 | 188 | lister.assert_called_with(datasource_name) 189 | self.assertEqual(['table', 'columns'], result[0]) 190 | 191 | 192 | class TestShowDatasourceTableSchema(common.TestCongressBase): 193 | def test_show_datasource_table_schema(self): 194 | datasource_name = 'neutron' 195 | table_name = 'ports' 196 | arglist = [ 197 | datasource_name, table_name 198 | ] 199 | verifylist = [ 200 | ('datasource_name', datasource_name), 201 | ('table_name', table_name) 202 | ] 203 | response = { 204 | 'table_id': 'ports', 205 | 'columns': [{"name": "name", "description": "None"}, 206 | {"name": "status", "description": "None"}, 207 | {"name": "id", "description": "None"}] 208 | } 209 | lister = mock.Mock(return_value=response) 210 | client = self.app.client_manager.congressclient 211 | client.show_datasource_table_schema = lister 212 | cmd = datasource.ShowDatasourceTableSchema(self.app, self.namespace) 213 | 214 | parsed_args = self.check_parser(cmd, arglist, verifylist) 215 | result = cmd.take_action(parsed_args) 216 | 217 | lister.assert_called_with(datasource_name, table_name) 218 | self.assertEqual(['name', 'description'], result[0]) 219 | 220 | 221 | class TestListDatasourceRows(common.TestCongressBase): 222 | 223 | def test_list_datasource_row(self): 224 | datasource_name = 'neutron' 225 | table_name = 'ports' 226 | arglist = [ 227 | datasource_name, table_name 228 | ] 229 | verifylist = [ 230 | ('datasource_name', datasource_name), 231 | ('table', table_name) 232 | ] 233 | response = { 234 | "results": [{"data": ["69abc88b-c950-4625-801b-542e84381509", 235 | "default"]}] 236 | } 237 | schema_response = { 238 | 'table_id': 'ports', 239 | 'columns': [{"name": "ID", "description": "None"}, 240 | {"name": "name", "description": "None"}] 241 | } 242 | 243 | client = self.app.client_manager.congressclient 244 | lister = mock.Mock(return_value=response) 245 | client.list_datasource_rows = lister 246 | schema_lister = mock.Mock(return_value=schema_response) 247 | client.show_datasource_table_schema = schema_lister 248 | cmd = datasource.ListDatasourceRows(self.app, self.namespace) 249 | 250 | parsed_args = self.check_parser(cmd, arglist, verifylist) 251 | result = cmd.take_action(parsed_args) 252 | 253 | lister.assert_called_with(datasource_name, table_name) 254 | self.assertEqual(['ID', 'name'], result[0]) 255 | 256 | 257 | class TestShowDatasourceTable(common.TestCongressBase): 258 | def test_show_datasource_table(self): 259 | datasource_name = 'neutron' 260 | table_id = 'ports' 261 | arglist = [ 262 | datasource_name, table_id 263 | ] 264 | verifylist = [ 265 | ('datasource_name', datasource_name), 266 | ('table_id', table_id) 267 | ] 268 | response = { 269 | 'id': 'ports', 270 | } 271 | lister = mock.Mock(return_value=response) 272 | client = self.app.client_manager.congressclient 273 | client.show_datasource_table = lister 274 | cmd = datasource.ShowDatasourceTable(self.app, self.namespace) 275 | expected_ret = [('id',), ('ports',)] 276 | 277 | parsed_args = self.check_parser(cmd, arglist, verifylist) 278 | result = list(cmd.take_action(parsed_args)) 279 | 280 | self.assertEqual(expected_ret, result) 281 | 282 | 283 | class TestCreateDatasource(common.TestCongressBase): 284 | 285 | def test_create_datasource(self): 286 | driver = 'neutronv2' 287 | name = 'arosen-neutronv2' 288 | response = {"description": '', 289 | "config": {"username": "admin", 290 | "project_name": "admin", 291 | "password": "password", 292 | "auth_url": "http://127.0.0.1:5000/v2.0"}, 293 | "enabled": True, 294 | "owner": "user", 295 | "driver": "neutronv2", 296 | "type": None, 297 | "id": "b72f81a0-32b5-4bf4-a1f6-d69c09c42cec", 298 | "name": "arosen-neutronv2"} 299 | 300 | arglist = [driver, name, 301 | "--config", "username=admin", 302 | "--config", "password=password", 303 | "--config", "auth_url=http://1.1.1.1/foo", 304 | "--config", "project_name=admin"] 305 | verifylist = [ 306 | ('driver', driver), 307 | ('name', name), 308 | ('config', {'username': 'admin', 'password': 'password', 309 | 'auth_url': 'http://1.1.1.1/foo', 310 | 'project_name': 'admin'}), 311 | ] 312 | 313 | mocker = mock.Mock(return_value=response) 314 | self.app.client_manager.congressclient.create_datasource = mocker 315 | cmd = datasource.CreateDatasource(self.app, self.namespace) 316 | parsed_args = self.check_parser(cmd, arglist, verifylist) 317 | result = list(cmd.take_action(parsed_args)) 318 | filtered = [('config', 'description', 319 | 'driver', 'enabled', 'id', 'name', 320 | 'owner', 'type'), 321 | (response['config'], response['description'], 322 | response['driver'], response['enabled'], 323 | response['id'], response['name'], 324 | response['owner'], response['type'])] 325 | self.assertEqual(filtered, result) 326 | 327 | 328 | class TestDeleteDatasourceDriver(common.TestCongressBase): 329 | 330 | def test_delete_datasource(self): 331 | driver = 'neutronv2' 332 | 333 | arglist = [driver] 334 | verifylist = [('datasource', driver), ] 335 | 336 | mocker = mock.Mock(return_value=None) 337 | self.app.client_manager.congressclient.delete_datasource = mocker 338 | cmd = datasource.DeleteDatasource(self.app, self.namespace) 339 | parsed_args = self.check_parser(cmd, arglist, verifylist) 340 | result = cmd.take_action(parsed_args) 341 | mocker.assert_called_with(driver) 342 | self.assertIsNone(result) 343 | 344 | 345 | class TestUpdateDatasourceRow(common.TestCongressBase): 346 | 347 | def test_update_datasource_row(self): 348 | driver = 'push' 349 | table_name = 'table' 350 | rows = [["data1", "data2"], 351 | ["data3", "data4"]] 352 | 353 | arglist = [driver, table_name, jsonutils.dumps(rows)] 354 | verifylist = [('datasource', driver), 355 | ('table', table_name), 356 | ('rows', rows)] 357 | 358 | mocker = mock.Mock(return_value=None) 359 | self.app.client_manager.congressclient.update_datasource_rows = mocker 360 | self.app.client_manager.congressclient.list_datasources = mock.Mock() 361 | 362 | cmd = datasource.UpdateDatasourceRow(self.app, self.namespace) 363 | parsed_args = self.check_parser(cmd, arglist, verifylist) 364 | with mock.patch.object(utils, 'get_resource_id_from_name', 365 | return_value="push"): 366 | cmd.take_action(parsed_args) 367 | mocker.assert_called_with(driver, table_name, rows) 368 | 369 | 370 | class TestDatasourceRequestRefresh(common.TestCongressBase): 371 | 372 | def test_datasource_request_refresh(self): 373 | driver = 'neutronv2' 374 | 375 | arglist = [driver] 376 | verifylist = [('datasource', driver), ] 377 | 378 | mocker = mock.Mock(return_value=None) 379 | self.app.client_manager.congressclient.request_refresh = mocker 380 | self.app.client_manager.congressclient.list_datasources = mock.Mock() 381 | cmd = datasource.DatasourceRequestRefresh(self.app, self.namespace) 382 | parsed_args = self.check_parser(cmd, arglist, verifylist) 383 | with mock.patch.object(utils, "get_resource_id_from_name", 384 | return_value="id"): 385 | result = cmd.take_action(parsed_args) 386 | mocker.assert_called_with("id", {}) 387 | self.assertIsNone(result) 388 | -------------------------------------------------------------------------------- /congressclient/tests/v1/test_drivers.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | # 13 | 14 | import mock 15 | 16 | from congressclient.osc.v1 import driver 17 | from congressclient.tests import common 18 | 19 | 20 | class TestListDrivers(common.TestCongressBase): 21 | 22 | def test_list_drivers(self): 23 | arglist = [ 24 | ] 25 | verifylist = [ 26 | ] 27 | response = { 28 | "results": [{"id": "neutronv2", 29 | "description": "this does blah.."}] 30 | } 31 | lister = mock.Mock(return_value=response) 32 | self.app.client_manager.congressclient.list_drivers = lister 33 | cmd = driver.ListDrivers(self.app, self.namespace) 34 | 35 | parsed_args = self.check_parser(cmd, arglist, verifylist) 36 | result = cmd.take_action(parsed_args) 37 | 38 | lister.assert_called_with() 39 | self.assertEqual(['id', 'description'], result[0]) 40 | 41 | 42 | class TestShowDriverSchema(common.TestCongressBase): 43 | 44 | def test_show_driver_shema(self): 45 | arglist = [ 46 | "neutronv2" 47 | ] 48 | verifylist = [ 49 | ('driver', "neutronv2") 50 | ] 51 | 52 | response = { 53 | "tables": 54 | [{'table_id': 'ports', 55 | 'columns': [{"name": "name", "description": "None"}, 56 | {"name": "status", "description": "None"}, 57 | {"name": "id", "description": "None"}]}, 58 | {'table_id': 'routers', 59 | 'columns': [{"name": "name", "description": "None"}, 60 | {"name": "floating_ip", "description": "None"}, 61 | {"name": "id", "description": "None"}]}] 62 | } 63 | lister = mock.Mock(return_value=response) 64 | self.app.client_manager.congressclient.show_driver = lister 65 | cmd = driver.ShowDriverSchema(self.app, self.namespace) 66 | 67 | parsed_args = self.check_parser(cmd, arglist, verifylist) 68 | result = cmd.take_action(parsed_args) 69 | 70 | lister.assert_called_with("neutronv2") 71 | self.assertEqual(['table', 'columns'], result[0]) 72 | 73 | 74 | class TestShowDriverConfig(common.TestCongressBase): 75 | 76 | def test_show_driver_config(self): 77 | arglist = [ 78 | "neutronv2" 79 | ] 80 | verifylist = [ 81 | ('driver', "neutronv2") 82 | ] 83 | 84 | response = { 85 | "tables": [], 86 | 'id': 'aabbcc', 87 | 'description': 'foobar', 88 | 'config': {'password': 'password'}, 89 | } 90 | mocker = mock.Mock(return_value=response) 91 | self.app.client_manager.congressclient.show_driver = mocker 92 | cmd = driver.ShowDriverConfig(self.app, self.namespace) 93 | 94 | parsed_args = self.check_parser(cmd, arglist, verifylist) 95 | result = list(cmd.take_action(parsed_args)) 96 | 97 | mocker.assert_called_with("neutronv2") 98 | filtered = [('config', 'description', 'id'), 99 | (response['config'], response['description'], 100 | response['id'])] 101 | self.assertEqual(filtered, result) 102 | -------------------------------------------------------------------------------- /congressclient/tests/v1/test_policy.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 2 | # not use this file except in compliance with the License. You may obtain 3 | # 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, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | # 13 | import os 14 | 15 | import mock 16 | 17 | from congressclient.common import utils 18 | from congressclient.osc.v1 import policy 19 | from congressclient.tests import common 20 | 21 | 22 | class TestCreatePolicy(common.TestCongressBase): 23 | 24 | def test_create_policy(self): 25 | policy_name = 'test1' 26 | policy_id = "e531f2b3-3d97-42c0-b3b5-b7b6ab532018" 27 | response = {"description": "", 28 | "id": policy_id, 29 | "name": policy_name, 30 | "kind": "nonrecursive", 31 | "owner": "system", 32 | "abbreviation": "test1"} 33 | 34 | arglist = [policy_name] 35 | verifylist = [ 36 | ('policy_name', policy_name), 37 | ] 38 | 39 | mocker = mock.Mock(return_value=response) 40 | self.app.client_manager.congressclient.create_policy = mocker 41 | cmd = policy.CreatePolicy(self.app, self.namespace) 42 | parsed_args = self.check_parser(cmd, arglist, verifylist) 43 | result = list(cmd.take_action(parsed_args)) 44 | filtered = [('abbreviation', 'description', 'id', 'kind', 'name', 45 | 'owner'), 46 | (policy_name, '', policy_id, 'nonrecursive', 47 | policy_name, 'system')] 48 | self.assertEqual(filtered, result) 49 | 50 | 51 | class TestCreatePolicyFromFile(common.TestCongressBase): 52 | 53 | def test_create_policy(self): 54 | policy_path = os.path.dirname( 55 | os.path.abspath(__file__)) + '/test_policy_file.yaml' 56 | policy_id = "e531f2b3-3d97-42c0-b3b5-b7b6ab532018" 57 | response = {"description": "", 58 | "id": policy_id, 59 | "name": "test_policy", 60 | "kind": "nonrecursive", 61 | "owner": "system", 62 | "abbreviation": "abbr", 63 | "rules": [ 64 | {'comment': 'test comment', 'name': 'test name', 65 | 'rule': 'p(x) :- q(x)'}, 66 | {'comment': 'test comment2', 'name': 'test name2', 67 | 'rule': 'p(x) :- q2(x)'}]} 68 | 69 | arglist = [policy_path] 70 | verifylist = [ 71 | ('policy_file_path', policy_path), 72 | ] 73 | 74 | mocker = mock.Mock(return_value=response) 75 | self.app.client_manager.congressclient.create_policy = mocker 76 | cmd = policy.CreatePolicyFromFile(self.app, self.namespace) 77 | parsed_args = self.check_parser(cmd, arglist, verifylist) 78 | result = list(cmd.take_action(parsed_args)) 79 | filtered = [('abbreviation', 'description', 'id', 'kind', 'name', 80 | 'owner', 'rules'), 81 | ('abbr', '', policy_id, 'nonrecursive', 82 | 'test_policy', 'system', 83 | 'p(x) :- q(x)\n' 84 | 'p(x) :- q2(x)')] 85 | self.assertEqual(filtered, result) 86 | 87 | 88 | class TestShowPolicy(common.TestCongressBase): 89 | def test_show_policy(self): 90 | policy_id = "14f2897a-155a-4c9d-b3de-ef85c0a171d8" 91 | policy_name = "test1" 92 | arglist = [policy_id] 93 | verifylist = [ 94 | ('policy_name', policy_id), 95 | ] 96 | response = {"description": "", 97 | "id": policy_id, 98 | "name": policy_name, 99 | "kind": "nonrecursive", 100 | "owner": "system", 101 | "abbreviation": "test1"} 102 | 103 | mocker = mock.Mock(return_value=response) 104 | self.app.client_manager.congressclient.show_policy = mocker 105 | self.app.client_manager.congressclient.list_policy = mock.Mock() 106 | cmd = policy.ShowPolicy(self.app, self.namespace) 107 | parsed_args = self.check_parser(cmd, arglist, verifylist) 108 | with mock.patch.object(utils, "get_resource_id_from_name", 109 | return_value="name"): 110 | result = list(cmd.take_action(parsed_args)) 111 | filtered = [('abbreviation', 'description', 'id', 'kind', 'name', 112 | 'owner'), 113 | (policy_name, '', policy_id, 'nonrecursive', 114 | policy_name, 'system')] 115 | self.assertEqual(filtered, result) 116 | 117 | 118 | class TestDeletePolicy(common.TestCongressBase): 119 | def test_delete_policy(self): 120 | policy_id = 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018' 121 | arglist = [ 122 | policy_id 123 | ] 124 | verifylist = [ 125 | ('policy', policy_id) 126 | ] 127 | mocker = mock.Mock(return_value=None) 128 | self.app.client_manager.congressclient.delete_policy = mocker 129 | self.app.client_manager.congressclient.list_policy = mock.Mock() 130 | cmd = policy.DeletePolicy(self.app, self.namespace) 131 | 132 | parsed_args = self.check_parser(cmd, arglist, verifylist) 133 | with mock.patch.object(utils, "get_resource_id_from_name", 134 | return_value="id"): 135 | result = cmd.take_action(parsed_args) 136 | 137 | mocker.assert_called_with(policy_id) 138 | self.assertIsNone(result) 139 | 140 | 141 | class TestCreatePolicyRule(common.TestCongressBase): 142 | 143 | def test_create_policy_rule(self): 144 | policy_name = 'classification' 145 | rule = "p(x) :- q(x)" 146 | response = {"comment": "Comment", 147 | "id": "e531f2b3-3d97-42c0-b3b5-b7b6ab532018", 148 | "rule": rule} 149 | 150 | arglist = [policy_name, rule] 151 | verifylist = [ 152 | ('policy_name', policy_name), 153 | ('rule', rule), 154 | ] 155 | 156 | mocker = mock.Mock(return_value=response) 157 | self.app.client_manager.congressclient.create_policy_rule = mocker 158 | cmd = policy.CreatePolicyRule(self.app, self.namespace) 159 | parsed_args = self.check_parser(cmd, arglist, verifylist) 160 | result = list(cmd.take_action(parsed_args)) 161 | filtered = [('comment', 'id', 'rule'), 162 | ('Comment', 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018', rule)] 163 | self.assertEqual(filtered, result) 164 | 165 | def test_create_policy_rule_with_name(self): 166 | policy_name = "classification" 167 | rule = "p(x) :- q(x)" 168 | rule_name = "classification_rule" 169 | response = {"comment": "None", 170 | "id": "e531f2b3-3d97-42c0-b3b5-b7b6ab532018", 171 | "rule": rule, 172 | "name": rule_name} 173 | 174 | arglist = ["--name", rule_name, policy_name, rule] 175 | verifylist = [ 176 | ('policy_name', policy_name), 177 | ('rule', rule), 178 | ("rule_name", rule_name) 179 | ] 180 | 181 | mocker = mock.Mock(return_value=response) 182 | self.app.client_manager.congressclient.create_policy_rule = mocker 183 | cmd = policy.CreatePolicyRule(self.app, self.namespace) 184 | parsed_args = self.check_parser(cmd, arglist, verifylist) 185 | result = list(cmd.take_action(parsed_args)) 186 | filtered = [('comment', 'id', 'name', 'rule'), 187 | ('None', 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018', rule_name, 188 | rule)] 189 | self.assertEqual(filtered, result) 190 | 191 | 192 | class TestDeletePolicyRule(common.TestCongressBase): 193 | def test_delete_policy_rule(self): 194 | policy_name = 'classification' 195 | rule_id = 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018' 196 | arglist = [ 197 | policy_name, rule_id 198 | ] 199 | verifylist = [ 200 | ('policy_name', policy_name), 201 | ('rule_id', rule_id) 202 | ] 203 | mocker = mock.Mock(return_value=None) 204 | self.app.client_manager.congressclient.delete_policy_rule = mocker 205 | self.app.client_manager.congressclient.list_policy_rules = mock.Mock() 206 | cmd = policy.DeletePolicyRule(self.app, self.namespace) 207 | 208 | parsed_args = self.check_parser(cmd, arglist, verifylist) 209 | with mock.patch.object(utils, "get_resource_id_from_name", 210 | return_value=rule_id): 211 | result = cmd.take_action(parsed_args) 212 | 213 | mocker.assert_called_with(policy_name, rule_id) 214 | self.assertIsNone(result) 215 | 216 | 217 | class TestListPolicyRules(common.TestCongressBase): 218 | def test_list_policy_rules(self): 219 | policy_name = 'classification' 220 | rule_id = 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018' 221 | arglist = [ 222 | policy_name 223 | ] 224 | verifylist = [ 225 | ('policy_name', policy_name) 226 | ] 227 | response = { 228 | "results": [{"comment": "None", 229 | "id": rule_id, 230 | "rule": "security_group(port, security_group_name)" 231 | }] 232 | } 233 | lister = mock.Mock(return_value=response) 234 | self.app.client_manager.congressclient.list_policy_rules = lister 235 | cmd = policy.ListPolicyRules(self.app, self.namespace) 236 | 237 | parsed_args = self.check_parser(cmd, arglist, verifylist) 238 | cmd.take_action(parsed_args) 239 | 240 | lister.assert_called_with(policy_name) 241 | 242 | 243 | class TestListPolicy(common.TestCongressBase): 244 | def test_list_policy_rules(self): 245 | policy_name = 'classification' 246 | policy_id = 'e531f2b3-3d97-42c0-b3b5-b7b6ab532018' 247 | arglist = [ 248 | ] 249 | verifylist = [ 250 | ] 251 | response = { 252 | "results": [{"id": policy_id, 253 | "owner_id": "system", 254 | "name": policy_name, 255 | "kind": "nonrecursive", 256 | "description": "my description" 257 | }]} 258 | lister = mock.Mock(return_value=response) 259 | self.app.client_manager.congressclient.list_policy = lister 260 | cmd = policy.ListPolicy(self.app, self.namespace) 261 | 262 | parsed_args = self.check_parser(cmd, arglist, verifylist) 263 | result = cmd.take_action(parsed_args) 264 | 265 | lister.assert_called_with() 266 | self.assertEqual(['id', 'name', 'owner_id', 'kind', 'description'], 267 | result[0]) 268 | 269 | 270 | class TestListPolicyTables(common.TestCongressBase): 271 | def test_list_policy_tables(self): 272 | policy_name = 'classification' 273 | arglist = [ 274 | policy_name 275 | ] 276 | verifylist = [ 277 | ('policy_name', policy_name) 278 | ] 279 | response = { 280 | "results": [{"id": "ports"}, 281 | {"id": "virtual_machines"}] 282 | } 283 | lister = mock.Mock(return_value=response) 284 | self.app.client_manager.congressclient.list_policy_tables = lister 285 | cmd = policy.ListPolicyTables(self.app, self.namespace) 286 | 287 | parsed_args = self.check_parser(cmd, arglist, verifylist) 288 | result = cmd.take_action(parsed_args) 289 | 290 | lister.assert_called_with(policy_name) 291 | self.assertEqual(['id'], result[0]) 292 | 293 | 294 | class TestListPolicyRows(common.TestCongressBase): 295 | 296 | def test_list_policy_rules(self): 297 | policy_name = 'classification' 298 | table_name = 'port_security_group' 299 | arglist = [ 300 | policy_name, table_name 301 | ] 302 | verifylist = [ 303 | ('policy_name', policy_name), 304 | ('table', table_name) 305 | ] 306 | response = {"results": 307 | [{"data": ["69abc88b-c950-4625-801b-542e84381509", 308 | "default"]}]} 309 | 310 | lister = mock.Mock(return_value=response) 311 | self.app.client_manager.congressclient.list_policy_rows = lister 312 | cmd = policy.ListPolicyRows(self.app, self.namespace) 313 | 314 | parsed_args = self.check_parser(cmd, arglist, verifylist) 315 | cmd.take_action(parsed_args) 316 | 317 | lister.assert_called_with(policy_name, table_name, False) 318 | 319 | def test_list_policy_rules_trace(self): 320 | policy_name = 'classification' 321 | table_name = 'p' 322 | arglist = [ 323 | policy_name, table_name, "--trace" 324 | ] 325 | verifylist = [ 326 | ('policy_name', policy_name), 327 | ('table', table_name) 328 | ] 329 | response = {"results": 330 | [{"data": ["69abc88b-c950-4625-801b-542e84381509", 331 | "default"]}], 332 | "trace": "Call p(x, y)\n " 333 | "Exit p('69abc88b-c950-4625-801b-542e84381509', " 334 | "'default')\n"} 335 | 336 | lister = mock.Mock(return_value=response) 337 | self.app.client_manager.congressclient.list_policy_rows = lister 338 | cmd = policy.ListPolicyRows(self.app, self.namespace) 339 | 340 | parsed_args = self.check_parser(cmd, arglist, verifylist) 341 | cmd.take_action(parsed_args) 342 | 343 | lister.assert_called_with(policy_name, table_name, True) 344 | 345 | 346 | class TestSimulatePolicy(common.TestCongressBase): 347 | 348 | def test_simulate_policy(self): 349 | policy_name = 'classification' 350 | action_name = 'action' 351 | sequence = 'q(1)' 352 | query = 'error(x)' 353 | arglist = [ 354 | policy_name, query, sequence, action_name 355 | ] 356 | verifylist = [ 357 | ('policy', policy_name), 358 | ('action_policy', action_name), 359 | ('sequence', sequence), 360 | ('query', query), 361 | ('delta', False) 362 | ] 363 | response = {'result': ['error(1)', 'error(2)']} 364 | 365 | lister = mock.Mock(return_value=response) 366 | self.app.client_manager.congressclient.execute_policy_action = lister 367 | cmd = policy.SimulatePolicy(self.app, self.namespace) 368 | 369 | parsed_args = self.check_parser(cmd, arglist, verifylist) 370 | cmd.take_action(parsed_args) 371 | 372 | body = {'action_policy': action_name, 373 | 'sequence': sequence, 374 | 'query': query} 375 | lister.assert_called_with(policy_name=policy_name, 376 | action='simulate', 377 | trace=False, 378 | delta=False, 379 | body=body) 380 | 381 | def test_simulate_policy_delta(self): 382 | policy_name = 'classification' 383 | action_name = 'action' 384 | sequence = 'q(1)' 385 | query = 'error(x)' 386 | arglist = [ 387 | policy_name, query, sequence, action_name, "--delta" 388 | ] 389 | verifylist = [ 390 | ('policy', policy_name), 391 | ('action_policy', action_name), 392 | ('sequence', sequence), 393 | ('query', query), 394 | ('delta', True) 395 | ] 396 | response = {'result': ['error(1)', 'error(2)']} 397 | 398 | lister = mock.Mock(return_value=response) 399 | self.app.client_manager.congressclient.execute_policy_action = lister 400 | cmd = policy.SimulatePolicy(self.app, self.namespace) 401 | 402 | parsed_args = self.check_parser(cmd, arglist, verifylist) 403 | cmd.take_action(parsed_args) 404 | 405 | body = {'action_policy': action_name, 406 | 'sequence': sequence, 407 | 'query': query} 408 | lister.assert_called_with(policy_name=policy_name, 409 | action='simulate', 410 | trace=False, 411 | delta=True, 412 | body=body) 413 | 414 | def test_simulate_policy_trace(self): 415 | policy_name = 'classification' 416 | action_name = 'action' 417 | sequence = 'q(1)' 418 | query = 'error(x)' 419 | arglist = [ 420 | policy_name, query, sequence, action_name, "--trace" 421 | ] 422 | verifylist = [ 423 | ('policy', policy_name), 424 | ('action_policy', action_name), 425 | ('sequence', sequence), 426 | ('query', query), 427 | ('trace', True) 428 | ] 429 | response = {'result': ['error(1)', 'error(2)'], 'trace': 'Call'} 430 | 431 | lister = mock.Mock(return_value=response) 432 | self.app.client_manager.congressclient.execute_policy_action = lister 433 | cmd = policy.SimulatePolicy(self.app, self.namespace) 434 | 435 | parsed_args = self.check_parser(cmd, arglist, verifylist) 436 | cmd.take_action(parsed_args) 437 | 438 | body = {'action_policy': action_name, 439 | 'sequence': sequence, 440 | 'query': query} 441 | lister.assert_called_with(policy_name=policy_name, 442 | action='simulate', 443 | trace=True, 444 | delta=False, 445 | body=body) 446 | 447 | 448 | class TestGet(common.TestCongressBase): 449 | 450 | def test_create_policy_rule(self): 451 | policy_name = 'classification' 452 | rule = "p(x) :- q(x)" 453 | id = "e531f2b3-3d97-42c0-b3b5-b7b6ab532018" 454 | response = {"comment": "None", 455 | "id": id, 456 | "rule": rule} 457 | 458 | arglist = [policy_name, id] 459 | verifylist = [ 460 | ('policy_name', policy_name), 461 | ('rule_id', id), 462 | ] 463 | 464 | mocker = mock.Mock(return_value=response) 465 | self.app.client_manager.congressclient.show_policy_rule = mocker 466 | self.app.client_manager.congressclient.list_policy_rules = mock.Mock() 467 | cmd = policy.ShowPolicyRule(self.app, self.namespace) 468 | parsed_args = self.check_parser(cmd, arglist, verifylist) 469 | with mock.patch.object(utils, "get_resource_id_from_name", 470 | return_value="id"): 471 | result = list(cmd.take_action(parsed_args)) 472 | filtered = [('comment', 'id', 'rule'), 473 | ('None', id, rule)] 474 | self.assertEqual(filtered, result) 475 | -------------------------------------------------------------------------------- /congressclient/tests/v1/test_policy_file.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: PauseBadFlavors 3 | description: "Pause any server using a flavor that is not permitted" 4 | rules: 5 | - 6 | comment: "User should customize this. Permitted flavors." 7 | rule: permitted_flavor('m1.tiny') 8 | - 9 | comment: "User should customize this. Permitted flavors." 10 | rule: permitted_flavor('m1.large') 11 | - 12 | rule: > 13 | server_with_bad_flavor(id) :- nova:servers(id=id,flavor_id=flavor_id), 14 | nova:flavors(id=flavor_id, name=flavor), not permitted_flavor(flavor) 15 | - 16 | comment: "Remediation: Pause any VM that shows up in the server_with_bad_flavor table" 17 | rule: "execute[nova:servers.pause(id)] :- server_with_bad_flavor(id), nova:servers(id,status='ACTIVE')" -------------------------------------------------------------------------------- /congressclient/v1/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/congressclient/v1/__init__.py -------------------------------------------------------------------------------- /congressclient/v1/client.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 VMWare. 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 | 15 | from keystoneauth1 import adapter 16 | 17 | 18 | class Client(object): 19 | """Client for the Congress v1 API. 20 | 21 | Example 22 | :: 23 | 24 | from keystoneauth1.identity import v2 25 | from keystoneauth1 import session 26 | from congressclient.v1 import client 27 | auth = v2.Password(auth_url=AUTH_URL, username=USERNAME, 28 | password=PASSWORD, project_name=TENANT_NAME) 29 | sess = session.Session(auth=auth) 30 | congress = client.Client(session=sess, 31 | auth=None, 32 | interface='publicURL', 33 | service_type='policy', 34 | region_name='RegionOne') 35 | congress.create_policy_rule(..) 36 | 37 | """ 38 | policy_path = '/v1/policies/%s' 39 | policy_rules = '/v1/policies/%s/rules' 40 | policy_rules_path = '/v1/policies/%s/rules/%s' 41 | policy_tables = '/v1/policies/%s/tables' 42 | policy_table_path = '/v1/policies/%s/tables/%s' 43 | policy_rows = '/v1/policies/%s/tables/%s/rows' 44 | policy_rows_trace = '/v1/policies/%s/tables/%s/rows?trace=True' 45 | policies = '/v1/policies' 46 | policy_action = '/v1/policies/%s?%s' 47 | library_policy_path = '/v1/librarypolicies/%s' 48 | library_policies = '/v1/librarypolicies' 49 | datasources = '/v1/data-sources' 50 | datasource_path = '/v1/data-sources/%s' 51 | datasource_tables = '/v1/data-sources/%s/tables' 52 | datasource_table_path = '/v1/data-sources/%s/tables/%s' 53 | datasource_status = '/v1/data-sources/%s/status' 54 | datasource_actions = '/v1/data-sources/%s/actions' 55 | datasource_schema = '/v1/data-sources/%s/schema' 56 | datasource_table_schema = '/v1/data-sources/%s/tables/%s/spec' 57 | datasource_rows = '/v1/data-sources/%s/tables/%s/rows' 58 | driver = '/v1/system/drivers' 59 | driver_path = '/v1/system/drivers/%s' 60 | policy_api_versions = '/' 61 | 62 | def __init__(self, **kwargs): 63 | super(Client, self).__init__() 64 | 65 | kwargs.setdefault('user_agent', 'python-congressclient') 66 | self.httpclient = adapter.LegacyJsonAdapter(**kwargs) 67 | 68 | def create_policy(self, body, library_policy_id=None): 69 | url = self.policies 70 | if library_policy_id: 71 | url = url + "?library_policy=%s" % library_policy_id 72 | resp, body = self.httpclient.post(url, body=body) 73 | return body 74 | 75 | def delete_policy(self, policy): 76 | resp, body = self.httpclient.delete(self.policy_path % policy) 77 | return body 78 | 79 | def show_policy(self, policy): 80 | resp, body = self.httpclient.get(self.policy_path % policy) 81 | return body 82 | 83 | def create_library_policy(self, body): 84 | resp, body = self.httpclient.post(self.library_policies, body=body) 85 | return body 86 | 87 | def delete_library_policy(self, policy): 88 | resp, body = self.httpclient.delete( 89 | self.library_policy_path % policy) 90 | return body 91 | 92 | def show_library_policy(self, policy, include_rules=True): 93 | query = "?include_rules=%s" % include_rules 94 | resp, body = self.httpclient.get( 95 | (self.library_policy_path % policy) + query) 96 | return body 97 | 98 | def create_policy_rule(self, policy_name, body=None): 99 | resp, body = self.httpclient.post( 100 | self.policy_rules % policy_name, body=body) 101 | return body 102 | 103 | def delete_policy_rule(self, policy_name, rule_id): 104 | resp, body = self.httpclient.delete( 105 | self.policy_rules_path % (policy_name, rule_id)) 106 | return body 107 | 108 | def show_policy_rule(self, policy_name, rule_id): 109 | resp, body = self.httpclient.get( 110 | self.policy_rules_path % (policy_name, rule_id)) 111 | return body 112 | 113 | def list_policy_rows(self, policy_name, table, trace=None): 114 | if trace: 115 | query = self.policy_rows_trace 116 | else: 117 | query = self.policy_rows 118 | resp, body = self.httpclient.get(query % (policy_name, table)) 119 | return body 120 | 121 | def list_policy_rules(self, policy_name): 122 | resp, body = self.httpclient.get(self.policy_rules % (policy_name)) 123 | return body 124 | 125 | def list_policy(self): 126 | resp, body = self.httpclient.get(self.policies) 127 | return body 128 | 129 | def list_library_policy(self, include_rules=True): 130 | query = "?include_rules=%s" % include_rules 131 | resp, body = self.httpclient.get(self.library_policies + query) 132 | return body 133 | 134 | def list_policy_tables(self, policy_name): 135 | resp, body = self.httpclient.get(self.policy_tables % (policy_name)) 136 | return body 137 | 138 | def execute_policy_action(self, policy_name, action, trace, delta, body): 139 | uri = "?action=%s&trace=%s&delta=%s" % (action, trace, delta) 140 | resp, body = self.httpclient.post( 141 | (self.policy_path % policy_name) + str(uri), body=body) 142 | return body 143 | 144 | def show_policy_table(self, policy_name, table_id): 145 | resp, body = self.httpclient.get(self.policy_table_path % 146 | (policy_name, table_id)) 147 | return body 148 | 149 | def list_datasources(self): 150 | resp, body = self.httpclient.get(self.datasources) 151 | return body 152 | 153 | def show_datasource(self, datasource_name): 154 | """Get a single datasource 155 | 156 | Intended for use by Horizon. Not available in CLI 157 | """ 158 | resp, body = self.httpclient.get(self.datasource_path % 159 | (datasource_name)) 160 | return body 161 | 162 | def list_datasource_tables(self, datasource_name): 163 | resp, body = self.httpclient.get(self.datasource_tables % 164 | (datasource_name)) 165 | return body 166 | 167 | def list_datasource_rows(self, datasource_name, table_name): 168 | resp, body = self.httpclient.get(self.datasource_rows % 169 | (datasource_name, table_name)) 170 | return body 171 | 172 | def update_datasource_rows(self, datasource_name, table_name, body=None): 173 | """Update rows in a table of a datasource. 174 | 175 | Args: 176 | datasource_name: Name or id of the datasource 177 | table_name: Table name for updating 178 | body: Rows for update. 179 | """ 180 | resp, body = self.httpclient.put(self.datasource_rows % 181 | (datasource_name, table_name), 182 | body=body) 183 | return body 184 | 185 | def list_datasource_status(self, datasource_name): 186 | resp, body = self.httpclient.get(self.datasource_status % 187 | datasource_name) 188 | return body 189 | 190 | def list_datasource_actions(self, datasource_name): 191 | resp, body = self.httpclient.get(self.datasource_actions % 192 | datasource_name) 193 | return body 194 | 195 | def show_datasource_schema(self, datasource_name): 196 | resp, body = self.httpclient.get(self.datasource_schema % 197 | datasource_name) 198 | return body 199 | 200 | def show_datasource_table_schema(self, datasource_name, table_name): 201 | resp, body = self.httpclient.get(self.datasource_table_schema % 202 | (datasource_name, table_name)) 203 | return body 204 | 205 | def show_datasource_table(self, datasource_name, table_id): 206 | resp, body = self.httpclient.get(self.datasource_table_path % 207 | (datasource_name, table_id)) 208 | return body 209 | 210 | def create_datasource(self, body=None): 211 | resp, body = self.httpclient.post( 212 | self.datasources, body=body) 213 | return body 214 | 215 | def delete_datasource(self, datasource): 216 | resp, body = self.httpclient.delete( 217 | self.datasource_path % datasource) 218 | return body 219 | 220 | def execute_datasource_action(self, service_name, action, body): 221 | uri = "?action=%s" % (action) 222 | resp, body = self.httpclient.post( 223 | (self.datasource_path % service_name) + str(uri), body=body) 224 | return body 225 | 226 | def list_drivers(self): 227 | resp, body = self.httpclient.get(self.driver) 228 | return body 229 | 230 | def show_driver(self, driver): 231 | resp, body = self.httpclient.get(self.driver_path % 232 | (driver)) 233 | return body 234 | 235 | def request_refresh(self, driver, body=None): 236 | resp, body = self.httpclient.post(self.datasource_path % 237 | (driver) + "?action=request-refresh", 238 | body=body) 239 | return body 240 | 241 | def list_api_versions(self): 242 | resp, body = self.httpclient.get(self.policy_api_versions) 243 | return body 244 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx>=1.8.0,!=2.1.0 # BSD 2 | sphinxcontrib-apidoc>=0.2.0 # BSD 3 | openstackdocstheme>=1.32.1 # Apache-2.0 4 | 5 | # releasenotes 6 | reno>=2.5.0 # Apache-2.0 7 | -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 11 | # implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | import sys 17 | 18 | sys.path.insert(0, os.path.abspath('../..')) 19 | # -- General configuration ---------------------------------------------------- 20 | 21 | # Add any Sphinx extension module names here, as strings. They can be 22 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 23 | extensions = [ 24 | 'openstackdocstheme', 25 | 'sphinxcontrib.apidoc' 26 | ] 27 | 28 | # openstackdocstheme options 29 | repository_name = 'openstack/python-congressclient' 30 | bug_project = 'python-congressclient' 31 | bug_tag = '' 32 | 33 | # sphinxcontrib.apidoc options 34 | apidoc_module_dir = '../../congressclient' 35 | apidoc_output_dir = 'reference/api' 36 | apidoc_excluded_paths = ['tests/*'] 37 | 38 | apidoc_separate_modules = True 39 | 40 | html_last_updated_fmt = '%Y-%m-%d %H:%M' 41 | 42 | # autodoc generation is a bit aggressive and a nuisance when doing heavy 43 | # text edit cycles. 44 | # execute "export SPHINX_DEBUG=1" in your terminal to disable 45 | 46 | # The suffix of source filenames. 47 | source_suffix = '.rst' 48 | 49 | # The master toctree document. 50 | master_doc = 'index' 51 | 52 | # General information about the project. 53 | project = u'python-congressclient' 54 | copyright = u'2013, OpenStack Foundation' 55 | 56 | # If true, '()' will be appended to :func: etc. cross-reference text. 57 | add_function_parentheses = True 58 | 59 | # If true, the current module name will be prepended to all description 60 | # unit titles (such as .. function::). 61 | add_module_names = True 62 | 63 | # The name of the Pygments (syntax highlighting) style to use. 64 | pygments_style = 'sphinx' 65 | 66 | # A list of glob-style patterns that should be excluded when looking for 67 | # source files. They are matched against the source file names relative to the 68 | # source directory, using slashes as directory separators on all platforms. 69 | exclude_patterns = ['reference/api/congressclient.tests.*'] 70 | 71 | # -- Options for HTML output -------------------------------------------------- 72 | 73 | # The theme to use for HTML and HTML Help pages. Major themes that come with 74 | # Sphinx are currently 'default' and 'sphinxdoc'. 75 | # html_theme_path = ["."] 76 | html_theme = 'openstackdocs' 77 | # html_static_path = ['static'] 78 | 79 | # Output file base name for HTML help builder. 80 | htmlhelp_basename = '%sdoc' % project 81 | 82 | # A list of ignored prefixes for module index sorting. 83 | modindex_common_prefix = ['congressclient.'] 84 | 85 | # Disable usage of xindy https://bugzilla.redhat.com/show_bug.cgi?id=1643664 86 | latex_use_xindy = False 87 | 88 | latex_domain_indices = False 89 | 90 | latex_elements = { 91 | 'makeindex': '', 92 | 'printindex': '', 93 | 'preamble': r'\setcounter{tocdepth}{3}', 94 | } 95 | 96 | # Grouping the document tree into LaTeX files. List of tuples 97 | # (source start file, target name, title, author, documentclass 98 | # [howto/manual]). 99 | # NOTE: Specify toctree_only=True for a better document structure of 100 | # the generated PDF file. 101 | latex_documents = [ 102 | ('index', 103 | 'doc-%s.tex' % project, 104 | u'Congress Client Documentation', 105 | u'OpenStack Foundation', 'manual', True), 106 | ] 107 | 108 | # Example configuration for intersphinx: refer to the Python standard library. 109 | #intersphinx_mapping = {'http://docs.python.org/': None} 110 | -------------------------------------------------------------------------------- /doc/source/contributor/index.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | .. include:: ../../../CONTRIBUTING.rst -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. python-congressclient documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to python-congressclient's documentation! 7 | ======================================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 1 13 | 14 | user/readme 15 | install/index 16 | user/index 17 | contributor/index 18 | reference/index 19 | 20 | * :ref:`genindex` 21 | * :ref:`search` 22 | 23 | .. # Below are items we don't want to show doc consumers but need to be 24 | # included to avoid sphinx warning/error. 25 | # api/modules hidden because the information is already in modindex above 26 | .. toctree:: 27 | :hidden: 28 | 29 | reference/api/modules 30 | -------------------------------------------------------------------------------- /doc/source/install/index.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ pip install python-congressclient 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv python-congressclient 12 | $ pip install python-congressclient -------------------------------------------------------------------------------- /doc/source/reference/index.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | References 3 | ========== 4 | 5 | * :ref:`modindex` -------------------------------------------------------------------------------- /doc/source/user/index.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | To use python-congressclient in a project:: 6 | 7 | import congressclient -------------------------------------------------------------------------------- /doc/source/user/readme.rst: -------------------------------------------------------------------------------- 1 | ########## 2 | README 3 | ########## 4 | 5 | .. include:: ../../../README.rst 6 | -------------------------------------------------------------------------------- /lower-constraints.txt: -------------------------------------------------------------------------------- 1 | alabaster==0.7.10 2 | Babel==2.3.4 3 | certifi==2018.1.18 4 | chardet==3.0.4 5 | cliff==2.8.0 6 | cmd2==0.8.2 7 | coverage==4.0 8 | debtcollector==1.19.0 9 | docutils==0.11 10 | dulwich==0.15.0 11 | extras==1.0.0 12 | fixtures==3.0.0 13 | flake8==2.5.5 14 | hacking==0.12.0 15 | idna==2.6 16 | imagesize==0.7.1 17 | iso8601==0.1.12 18 | Jinja2==2.10 19 | keystoneauth1==3.4.0 20 | linecache2==1.0.0 21 | MarkupSafe==1.0 22 | mccabe==0.2.1 23 | mock==2.0.0 24 | monotonic==1.4 25 | msgpack-python==0.4.0 26 | msgpack==0.5.6 27 | netaddr==0.7.19 28 | netifaces==0.10.6 29 | openstackdocstheme==1.32.1 30 | oslo.config==5.2.0 31 | oslo.context==2.20.0 32 | oslo.i18n==3.15.3 33 | oslo.log==3.36.0 34 | oslo.serialization==2.18.0 35 | oslo.utils==3.36.0 36 | pbr==2.0.0 37 | pep8==1.5.7 38 | prettytable==0.7.2 39 | pyflakes==0.8.1 40 | Pygments==2.2.0 41 | pyinotify==0.9.6 42 | pyparsing==2.2.0 43 | pyperclip==1.6.0 44 | python-dateutil==2.7.0 45 | python-mimeparse==1.6.0 46 | python-subunit==1.0.0 47 | pytz==2018.3 48 | PyYAML==3.12 49 | requests==2.18.4 50 | rfc3986==1.1.0 51 | six==1.10.0 52 | snowballstemmer==1.2.1 53 | Sphinx==1.8.0 54 | sphinxcontrib-websupport==1.0.1 55 | stevedore==1.28.0 56 | stestr==2.0.0 57 | testtools==2.2.0 58 | traceback2==1.4.0 59 | unittest2==1.1.0 60 | urllib3==1.22 61 | wrapt==1.10.11 62 | -------------------------------------------------------------------------------- /releasenotes/notes/add-datasource-push-d92854a72b4d6480.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | features: 3 | - Now supports 'datasource row update' for those 4 | datasource drivers that allow you to push data 5 | into them over HTTP. 6 | issues: 7 | - The 'datasource row update' command sometimes returns 8 | unfriendly error messages. 9 | -------------------------------------------------------------------------------- /releasenotes/notes/drop-py-2-7-0991cef98d96593e.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | upgrade: 3 | - | 4 | Python 2.7 support has been dropped. Last release of python-congressclient 5 | to support python 2.7 is OpenStack Train. The minimum version of Python now 6 | supported is Python 3.6. 7 | -------------------------------------------------------------------------------- /releasenotes/source/_static/.placeholder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/releasenotes/source/_static/.placeholder -------------------------------------------------------------------------------- /releasenotes/source/_templates/.placeholder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openstack-archive/python-congressclient/5863c2bdf6b9aef016d55f9f07105aee60416246/releasenotes/source/_templates/.placeholder -------------------------------------------------------------------------------- /releasenotes/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software 9 | # distributed under the License is distributed on an "AS IS" BASIS, 10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 11 | # implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # This file is execfile()d with the current directory set to its 16 | # containing dir. 17 | # 18 | # Note that not all possible configuration values are present in this 19 | # autogenerated file. 20 | # 21 | # All configuration values have a default; values that are commented out 22 | # serve to show the default. 23 | 24 | # If extensions (or modules to document with autodoc) are in another directory, 25 | # add these directories to sys.path here. If the directory is relative to the 26 | # documentation root, use os.path.abspath to make it absolute, like shown here. 27 | # sys.path.insert(0, os.path.abspath('.')) 28 | 29 | # -- General configuration ------------------------------------------------ 30 | 31 | # If your documentation needs a minimal Sphinx version, state it here. 32 | # needs_sphinx = '1.0' 33 | 34 | # Add any Sphinx extension module names here, as strings. They can be 35 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 36 | # ones. 37 | extensions = [ 38 | 'openstackdocstheme', 39 | 'reno.sphinxext', 40 | ] 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ['_templates'] 44 | 45 | # The suffix of source filenames. 46 | source_suffix = '.rst' 47 | 48 | # The encoding of source files. 49 | # source_encoding = 'utf-8-sig' 50 | 51 | # The master toctree document. 52 | master_doc = 'index' 53 | 54 | # General information about the project. 55 | project = u'congress_tempest_plugin Release Notes' 56 | copyright = u'2017, OpenStack Developers' 57 | 58 | # openstackdocstheme options 59 | repository_name = 'openstack/congress-tempest-plugin' 60 | bug_project = 'congress' 61 | bug_tag = '' 62 | 63 | # The version info for the project you're documenting, acts as replacement for 64 | # |version| and |release|, also used in various other places throughout the 65 | # built documents. 66 | # 67 | # The short X.Y version. 68 | # The full version, including alpha/beta/rc tags. 69 | release = '' 70 | # The short X.Y version. 71 | version = '' 72 | 73 | # The language for content autogenerated by Sphinx. Refer to documentation 74 | # for a list of supported languages. 75 | # language = None 76 | 77 | # There are two options for replacing |today|: either, you set today to some 78 | # non-false value, then it is used: 79 | # today = '' 80 | # Else, today_fmt is used as the format for a strftime call. 81 | # today_fmt = '%B %d, %Y' 82 | 83 | # List of patterns, relative to source directory, that match files and 84 | # directories to ignore when looking for source files. 85 | exclude_patterns = [] 86 | 87 | # The reST default role (used for this markup: `text`) to use for all 88 | # documents. 89 | # default_role = None 90 | 91 | # If true, '()' will be appended to :func: etc. cross-reference text. 92 | # add_function_parentheses = True 93 | 94 | # If true, the current module name will be prepended to all description 95 | # unit titles (such as .. function::). 96 | # add_module_names = True 97 | 98 | # If true, sectionauthor and moduleauthor directives will be shown in the 99 | # output. They are ignored by default. 100 | # show_authors = False 101 | 102 | # The name of the Pygments (syntax highlighting) style to use. 103 | pygments_style = 'sphinx' 104 | 105 | # A list of ignored prefixes for module index sorting. 106 | # modindex_common_prefix = [] 107 | 108 | # If true, keep warnings as "system message" paragraphs in the built documents. 109 | # keep_warnings = False 110 | 111 | 112 | # -- Options for HTML output ---------------------------------------------- 113 | 114 | # The theme to use for HTML and HTML Help pages. See the documentation for 115 | # a list of builtin themes. 116 | html_theme = 'openstackdocs' 117 | 118 | # Theme options are theme-specific and customize the look and feel of a theme 119 | # further. For a list of options available for each theme, see the 120 | # documentation. 121 | # html_theme_options = {} 122 | 123 | # Add any paths that contain custom themes here, relative to this directory. 124 | # html_theme_path = [] 125 | 126 | # The name for this set of Sphinx documents. If None, it defaults to 127 | # " v documentation". 128 | # html_title = None 129 | 130 | # A shorter title for the navigation bar. Default is the same as html_title. 131 | # html_short_title = None 132 | 133 | # The name of an image file (relative to this directory) to place at the top 134 | # of the sidebar. 135 | # html_logo = None 136 | 137 | # The name of an image file (within the static path) to use as favicon of the 138 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 139 | # pixels large. 140 | # html_favicon = None 141 | 142 | # Add any paths that contain custom static files (such as style sheets) here, 143 | # relative to this directory. They are copied after the builtin static files, 144 | # so a file named "default.css" will overwrite the builtin "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # Add any extra paths that contain custom files (such as robots.txt or 148 | # .htaccess) here, relative to this directory. These files are copied 149 | # directly to the root of the documentation. 150 | # html_extra_path = [] 151 | 152 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 153 | # using the given strftime format. 154 | # html_last_updated_fmt = '%b %d, %Y' 155 | 156 | # If true, SmartyPants will be used to convert quotes and dashes to 157 | # typographically correct entities. 158 | # html_use_smartypants = True 159 | 160 | # Custom sidebar templates, maps document names to template names. 161 | # html_sidebars = {} 162 | 163 | # Additional templates that should be rendered to pages, maps page names to 164 | # template names. 165 | # html_additional_pages = {} 166 | 167 | # If false, no module index is generated. 168 | # html_domain_indices = True 169 | 170 | # If false, no index is generated. 171 | # html_use_index = True 172 | 173 | # If true, the index is split into individual pages for each letter. 174 | # html_split_index = False 175 | 176 | # If true, links to the reST sources are added to the pages. 177 | # html_show_sourcelink = True 178 | 179 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 180 | # html_show_sphinx = True 181 | 182 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 183 | # html_show_copyright = True 184 | 185 | # If true, an OpenSearch description file will be output, and all pages will 186 | # contain a tag referring to it. The value of this option must be the 187 | # base URL from which the finished HTML is served. 188 | # html_use_opensearch = '' 189 | 190 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 191 | # html_file_suffix = None 192 | 193 | # Output file base name for HTML help builder. 194 | htmlhelp_basename = 'congress_tempest_pluginReleaseNotesdoc' 195 | 196 | 197 | # -- Options for LaTeX output --------------------------------------------- 198 | 199 | latex_elements = { 200 | # The paper size ('letterpaper' or 'a4paper'). 201 | # 'papersize': 'letterpaper', 202 | 203 | # The font size ('10pt', '11pt' or '12pt'). 204 | # 'pointsize': '10pt', 205 | 206 | # Additional stuff for the LaTeX preamble. 207 | # 'preamble': '', 208 | } 209 | 210 | # Grouping the document tree into LaTeX files. List of tuples 211 | # (source start file, target name, title, 212 | # author, documentclass [howto, manual, or own class]). 213 | latex_documents = [ 214 | ('index', 'congress_tempest_pluginReleaseNotes.tex', 215 | u'congress_tempest_plugin Release Notes Documentation', 216 | u'OpenStack Foundation', 'manual'), 217 | ] 218 | 219 | # The name of an image file (relative to this directory) to place at the top of 220 | # the title page. 221 | # latex_logo = None 222 | 223 | # For "manual" documents, if this is true, then toplevel headings are parts, 224 | # not chapters. 225 | # latex_use_parts = False 226 | 227 | # If true, show page references after internal links. 228 | # latex_show_pagerefs = False 229 | 230 | # If true, show URL addresses after external links. 231 | # latex_show_urls = False 232 | 233 | # Documents to append as an appendix to all manuals. 234 | # latex_appendices = [] 235 | 236 | # If false, no module index is generated. 237 | # latex_domain_indices = True 238 | 239 | 240 | # -- Options for manual page output --------------------------------------- 241 | 242 | # One entry per manual page. List of tuples 243 | # (source start file, name, description, authors, manual section). 244 | man_pages = [ 245 | ('index', 'congress_tempest_pluginrereleasenotes', 246 | u'congress_tempest_plugin Release Notes Documentation', 247 | [u'OpenStack Foundation'], 1) 248 | ] 249 | 250 | # If true, show URL addresses after external links. 251 | # man_show_urls = False 252 | 253 | 254 | # -- Options for Texinfo output ------------------------------------------- 255 | 256 | # Grouping the document tree into Texinfo files. List of tuples 257 | # (source start file, target name, title, author, 258 | # dir menu entry, description, category) 259 | texinfo_documents = [ 260 | ('index', 'congress_tempest_plugin ReleaseNotes', 261 | u'congress_tempest_plugin Release Notes Documentation', 262 | u'OpenStack Foundation', 'congress_tempest_pluginReleaseNotes', 263 | 'One line description of project.', 264 | 'Miscellaneous'), 265 | ] 266 | 267 | # Documents to append as an appendix to all manuals. 268 | # texinfo_appendices = [] 269 | 270 | # If false, no module index is generated. 271 | # texinfo_domain_indices = True 272 | 273 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 274 | # texinfo_show_urls = 'footnote' 275 | 276 | # If true, do not generate a @detailmenu in the "Top" node's menu. 277 | # texinfo_no_detailmenu = False 278 | 279 | # -- Options for Internationalization output ------------------------------ 280 | locale_dirs = ['locale/'] 281 | -------------------------------------------------------------------------------- /releasenotes/source/index.rst: -------------------------------------------------------------------------------- 1 | .. 2 | Licensed under the Apache License, Version 2.0 (the "License"); you may 3 | not use this file except in compliance with the License. You may obtain 4 | a copy of the License at 5 | 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software 9 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 10 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 11 | License for the specific language governing permissions and limitations 12 | under the License. 13 | 14 | ======================================== 15 | Welcome to Congress Client Release Notes 16 | ======================================== 17 | 18 | Contents 19 | ======== 20 | 21 | .. toctree:: 22 | :maxdepth: 2 23 | 24 | train 25 | 26 | 27 | Indices and tables 28 | ================== 29 | 30 | * :ref:`genindex` 31 | * :ref:`search` 32 | -------------------------------------------------------------------------------- /releasenotes/source/train.rst: -------------------------------------------------------------------------------- 1 | =================================== 2 | Train Series Release Notes 3 | =================================== 4 | 5 | .. release-notes:: 6 | :branch: stable/train 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # The order of packages is significant, because pip processes them in the order 2 | # of appearance. Changing the order has an impact on the overall integration 3 | # process, which may cause wedges in the gate later. 4 | pbr!=2.1.0,>=2.0.0 # Apache-2.0 5 | Babel!=2.4.0,>=2.3.4 # BSD 6 | cliff!=2.9.0,>=2.8.0 # Apache-2.0 7 | keystoneauth1>=3.4.0 # Apache-2.0 8 | oslo.i18n>=3.15.3 # Apache-2.0 9 | oslo.log>=3.36.0 # Apache-2.0 10 | oslo.serialization!=2.19.1,>=2.18.0 # Apache-2.0 11 | six>=1.10.0 # MIT 12 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = python-congressclient 3 | summary = Client for Congress 4 | description-file = 5 | README.rst 6 | author = OpenStack 7 | author-email = openstack-discuss@lists.openstack.org 8 | home-page = https://docs.openstack.org/python-congressclient/latest/ 9 | python-requires = >=3.6 10 | classifier = 11 | Environment :: OpenStack 12 | Intended Audience :: Information Technology 13 | Intended Audience :: System Administrators 14 | License :: OSI Approved :: Apache Software License 15 | Operating System :: POSIX :: Linux 16 | Programming Language :: Python 17 | Programming Language :: Python :: Implementation :: CPython 18 | Programming Language :: Python :: 3 :: Only 19 | Programming Language :: Python :: 3 20 | Programming Language :: Python :: 3.6 21 | Programming Language :: Python :: 3.7 22 | 23 | [files] 24 | packages = 25 | congressclient 26 | 27 | [entry_points] 28 | openstack.cli.extension = 29 | congressclient = congressclient.osc.osc_plugin 30 | 31 | openstack.congressclient.v1 = 32 | congress_policy_create = congressclient.osc.v1.policy:CreatePolicy 33 | congress_policy_create-from-file = congressclient.osc.v1.policy:CreatePolicyFromFile 34 | congress_policy_delete = congressclient.osc.v1.policy:DeletePolicy 35 | congress_policy_show = congressclient.osc.v1.policy:ShowPolicy 36 | congress_policy_rule_create = congressclient.osc.v1.policy:CreatePolicyRule 37 | congress_policy_rule_delete = congressclient.osc.v1.policy:DeletePolicyRule 38 | congress_policy_rule_show = congressclient.osc.v1.policy:ShowPolicyRule 39 | congress_policy_rule_list = congressclient.osc.v1.policy:ListPolicyRules 40 | congress_policy_list = congressclient.osc.v1.policy:ListPolicy 41 | congress_policy_row_list = congressclient.osc.v1.policy:ListPolicyRows 42 | congress_policy_table_list = congressclient.osc.v1.policy:ListPolicyTables 43 | congress_policy_simulate = congressclient.osc.v1.policy:SimulatePolicy 44 | congress_datasource_list = congressclient.osc.v1.datasource:ListDatasources 45 | congress_datasource_create = congressclient.osc.v1.datasource:CreateDatasource 46 | congress_datasource_delete = congressclient.osc.v1.datasource:DeleteDatasource 47 | congress_datasource_request-refresh = congressclient.osc.v1.datasource:DatasourceRequestRefresh 48 | congress_datasource_table_list = congressclient.osc.v1.datasource:ListDatasourceTables 49 | congress_datasource_row_list = congressclient.osc.v1.datasource:ListDatasourceRows 50 | congress_datasource_row_update = congressclient.osc.v1.datasource:UpdateDatasourceRow 51 | congress_datasource_status_show = congressclient.osc.v1.datasource:ShowDatasourceStatus 52 | congress_datasource_actions_show= congressclient.osc.v1.datasource:ShowDatasourceActions 53 | congress_datasource_schema_show = congressclient.osc.v1.datasource:ShowDatasourceSchema 54 | congress_datasource_table_schema_show = congressclient.osc.v1.datasource:ShowDatasourceTableSchema 55 | congress_policy_table_show = congressclient.osc.v1.policy:ShowPolicyTable 56 | congress_datasource_table_show = congressclient.osc.v1.datasource:ShowDatasourceTable 57 | congress_driver_config_show = congressclient.osc.v1.driver:ShowDriverConfig 58 | congress_driver_schema_show = congressclient.osc.v1.driver:ShowDriverSchema 59 | congress_driver_list = congressclient.osc.v1.driver:ListDrivers 60 | congress_version_list = congressclient.osc.v1.api_versions:ListAPIVersions 61 | 62 | [compile_catalog] 63 | directory = congressclient/locale 64 | domain = python-congressclient 65 | 66 | [update_catalog] 67 | domain = python-congressclient 68 | output_dir = congressclient/locale 69 | input_file = congressclient/locale/python-congressclient.pot 70 | 71 | [extract_messages] 72 | keywords = _ gettext ngettext l_ lazy_gettext 73 | mapping_file = babel.cfg 74 | output_file = congressclient/locale/python-congressclient.pot 75 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain 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, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | # implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import setuptools 17 | 18 | setuptools.setup( 19 | setup_requires=['pbr>=2.0.0'], 20 | pbr=True) 21 | -------------------------------------------------------------------------------- /tenant-list.log: -------------------------------------------------------------------------------- 1 | +----------------------------------+--------------------+---------+ 2 | | id | name | enabled | 3 | +----------------------------------+--------------------+---------+ 4 | | 8918ef508b3a48a1ad963cec1d7bec18 | admin | True | 5 | | e41ef6f35dab448699a5ca69eff60692 | demo | True | 6 | | c01bea38e55d44d3a87bb018b050338c | invisible_to_admin | True | 7 | | 3a1208bc143a4ed589288057ea8e0735 | service | True | 8 | +----------------------------------+--------------------+---------+ 9 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | # The order of packages is significant, because pip processes them in the order 2 | # of appearance. Changing the order has an impact on the overall integration 3 | # process, which may cause wedges in the gate later. 4 | hacking>=1.1.0,<1.2.0 # Apache-2.0 5 | 6 | coverage!=4.4,>=4.0 # Apache-2.0 7 | fixtures>=3.0.0 # Apache-2.0/BSD 8 | stestr>=2.0.0 # Apache-2.0 9 | testtools>=2.2.0 # MIT 10 | mock>=2.0.0 # BSD 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | minversion = 3.1.1 3 | envlist = py37,py36,pep8 4 | skipsdist = True 5 | ignore_basepython_conflict = True 6 | 7 | [testenv] 8 | basepython = python3 9 | usedevelop = True 10 | install_command = pip install -U {opts} {packages} 11 | whitelist_externals = find 12 | deps = 13 | -c{env:UPPER_CONSTRAINTS_FILE:https://opendev.org/openstack/requirements/raw/branch/master/upper-constraints.txt} 14 | -r{toxinidir}/requirements.txt 15 | -r{toxinidir}/test-requirements.txt 16 | commands = 17 | find . -type f -name "*.pyc" -delete 18 | stestr run --slowest {posargs} 19 | 20 | [testenv:pep8] 21 | commands = flake8 22 | 23 | [testenv:venv] 24 | commands = {posargs} 25 | 26 | [testenv:cover] 27 | commands = stestr run {posargs} 28 | 29 | [testenv:docs] 30 | deps = -r{toxinidir}/doc/requirements.txt 31 | commands = sphinx-build -W --keep-going -b html doc/source doc/build/html 32 | 33 | [testenv:pdf-docs] 34 | envdir = {toxworkdir}/docs 35 | deps = {[testenv:docs]deps} 36 | whitelist_externals = 37 | make 38 | commands = 39 | sphinx-build -W --keep-going -b latex doc/source doc/build/pdf 40 | make -C doc/build/pdf 41 | 42 | [testenv:releasenotes] 43 | deps = {[testenv:docs]deps} 44 | commands = sphinx-build -a -E -W -d releasenotes/build/doctrees --keep-going -b html releasenotes/source releasenotes/build/html 45 | 46 | [hacking] 47 | import_exceptions = congressclient.i18n 48 | 49 | [flake8] 50 | show-source = True 51 | builtins = _ 52 | exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build 53 | 54 | [testenv:lower-constraints] 55 | deps = 56 | -c{toxinidir}/lower-constraints.txt 57 | -r{toxinidir}/test-requirements.txt 58 | -r{toxinidir}/requirements.txt 59 | --------------------------------------------------------------------------------