diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 1717b2f..0000000 --- a/.gitignore +++ /dev/null @@ -1,47 +0,0 @@ -*.py[cod] - -# C extensions -*.so - -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -lib -lib64 - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox -nosetests.xml - -# Translations -*.mo - -# Mr Developer -.mr.developer.cfg -.project -.pydevproject -.venv - -doc/source/api/* -doc/build/* -AUTHORS -TAGS -ChangeLog - -# Project specific -etc/billingstack/*.ini -etc/billingstack/*.conf -billingstack/versioninfo diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 67db858..0000000 --- a/LICENSE +++ /dev/null @@ -1,175 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index d2bad60..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,11 +0,0 @@ -include AUTHORS -include ChangeLog -include billingstack/versioninfo -include *.txt *.ini *.cfg *.rst *.md -include etc/billingstack/*.sample -include etc/billingstack/policy.json - -exclude .gitignore -exclude .gitreview -exclude *.sublime-project -global-exclude *.pyc diff --git a/README.md b/README.md deleted file mode 100644 index 4632584..0000000 --- a/README.md +++ /dev/null @@ -1,34 +0,0 @@ -billingstack -============ - -What is Billingstack? -BillingStack is a convergence of efforts done in the previous started Bufunfa -project and the BillingStack Grails (Java) version by Luis Gervaso. - -The goal is to provide a free alternative to anyone that has a need for a -subscription based billingsystem with features compared to other popular ones. - - -Features include: -* Plans - Collections of Products like Compute Gold or similar -* Products - A Compute server for example -* Merchants - Multi-Tenancy via Merchants where the Merchant is the Tenant of - the application and can have multiple Customers, it's own - settings etc. - -* Plugin based Storage API - The Storage API is pluggable and other backends - can be added. -* REST API - Currently based on Pecan for V1. - - -Installing -========== - -1. git clone https://github.com/billingstack/billingstack -2. virtualenv .venv -3. pip install -r tools/test-requires -r tools/pip-options -r tools/pip-requires -4. python setup.py develop -5. Edit the config to your liking - vi etc/billingstack/billingstack.conf -6. Run the API - billingstack-api --config-file etc/billingstack/billingstack.conf diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..9006052 --- /dev/null +++ b/README.rst @@ -0,0 +1,7 @@ +This project is no longer maintained. + +The contents of this repository are still available in the Git source code +management system. To see the contents of this repository before it reached +its end of life, please check out the previous commit with +"git checkout HEAD^1". + diff --git a/billingstack/__init__.py b/billingstack/__init__.py deleted file mode 100644 index b45cd58..0000000 --- a/billingstack/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -import os -from oslo.config import cfg - -from billingstack.openstack.common import rpc - -cfg.CONF.register_opts([ - cfg.StrOpt('pybasedir', - default=os.path.abspath(os.path.join(os.path.dirname(__file__), - '../')), - help='Directory where the nova python module is installed'), - cfg.StrOpt('state-path', default='$pybasedir', - help='Top-level directory for maintaining billingstack\'s state') -]) - - -rpc.set_defaults(control_exchange='billingstack') diff --git a/billingstack/api/__init__.py b/billingstack/api/__init__.py deleted file mode 100644 index 663af26..0000000 --- a/billingstack/api/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2013 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from oslo.config import cfg - -API_SERVICE_OPTS = [ - cfg.IntOpt('api_port', default=9091, - help='The port for the billing API server'), - cfg.IntOpt('api_listen', default='0.0.0.0', help='Bind to address'), - cfg.StrOpt('storage_driver', default='sqlalchemy', help='Storage driver to use'), -] - -cfg.CONF.register_opts(API_SERVICE_OPTS, 'service:api') diff --git a/billingstack/api/app.py b/billingstack/api/app.py deleted file mode 100644 index ee3682a..0000000 --- a/billingstack/api/app.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from pecan import configuration -from pecan import make_app - -from billingstack.api import config as api_config -from billingstack.api import hooks - - -def get_pecan_config(): - # Set up the pecan configuration - filename = api_config.__file__.replace('.pyc', '.py') - return configuration.conf_from_file(filename) - - -def setup_app(pecan_config=None, extra_hooks=None): - - app_hooks = [hooks.ConfigHook(), - hooks.RPCHook() - ] - - if extra_hooks: - app_hooks.extend(extra_hooks) - - if not pecan_config: - pecan_config = get_pecan_config() - - app_hooks.append(hooks.NoAuthHook()) - - configuration.set_config(dict(pecan_config), overwrite=True) - - app = make_app( - pecan_config.app.root, - static_root=pecan_config.app.static_root, - template_path=pecan_config.app.template_path, - logging=getattr(pecan_config, 'logging', {}), - debug=getattr(pecan_config.app, 'debug', False), - force_canonical=getattr(pecan_config.app, 'force_canonical', True), - hooks=app_hooks, - guess_content_type_from_ext=getattr( - pecan_config.app, - 'guess_content_type_from_ext', - True), - ) - - return app diff --git a/billingstack/api/base.py b/billingstack/api/base.py deleted file mode 100644 index 52e90b6..0000000 --- a/billingstack/api/base.py +++ /dev/null @@ -1,95 +0,0 @@ -import inspect -import pecan -from pecan import request -from pecan.rest import RestController -from wsme.types import Base, UserType, Unset - -from billingstack.openstack.common import log - - -LOG = log.getLogger(__name__) - - -class Property(UserType): - """ - A Property that just passes the value around... - """ - def tonativetype(self, value): - return value - - def fromnativetype(self, value): - return value - - -property_type = Property() - - -class RestBase(RestController): - __resource__ = None - __id__ = None - - def __init__(self, parent=None, id_=None): - self.parent = parent - if self.__id__: - request.context[self.__id__ + '_id'] = id_ - self.id_ = id_ - - @pecan.expose() - def _lookup(self, *url_data): - """ - A fun approach to _lookup - checks self.__resource__ for the "id" - """ - id_ = None - if len(url_data) >= 1: - id_ = url_data[0] - parts = url_data[1:] if len(url_data) > 1 else () - LOG.debug("Lookup: id '%s' parts '%s'", id_, parts) - - resource = self.__resource__ - if inspect.isclass(resource) and issubclass(resource, RestBase): - return resource(parent=self, id_=id_), parts - - def __getattr__(self, name): - """ - Overload this to look in self.__resource__ if name is defined as a - Controller - """ - if name in self.__dict__: - return self.__dict__[name] - elif isinstance(self.__resource__, dict) and name in self.__resource__: - return self.__resource__[name](parent=self) - else: - raise AttributeError - - -class ModelBase(Base): - def as_dict(self): - """ - Return this model as a dict - """ - data = {} - - for attr in self._wsme_attributes: - value = attr.__get__(self, self.__class__) - if value is not Unset: - if isinstance(value, Base) and hasattr(value, "as_dict"): - value = value.as_dict() - data[attr.name] = value - return data - - def to_db(self): - """ - Returns this Model object as it's DB form - - Example - 'currency' vs 'currency_name' - """ - return self.as_dict() - - @classmethod - def from_db(cls, values): - """ - Return a class of this object from values in the from_db - """ - return cls(**values) - diff --git a/billingstack/api/config.py b/billingstack/api/config.py deleted file mode 100644 index ea8ca91..0000000 --- a/billingstack/api/config.py +++ /dev/null @@ -1,43 +0,0 @@ -# Server Specific Configurations -server = { - 'port': '9001', - 'host': '0.0.0.0' -} - -# Pecan Application Configurations -app = { - 'root': 'billingstack.api.root.RootController', - 'modules': ['billingstack.api'], - 'static_root': '%(confdir)s/public', - 'template_path': '%(confdir)s/templates', - 'debug': False, - 'enable_acl': True, -} - -logging = { - 'loggers': { - 'root': {'level': 'INFO', 'handlers': ['console']}, - 'billingstack': {'level': 'DEBUG', 'handlers': ['console']}, - 'wsme': {'level': 'DEBUG', 'handlers': ['console']} - }, - 'handlers': { - 'console': { - 'level': 'DEBUG', - 'class': 'logging.StreamHandler', - 'formatter': 'simple' - } - }, - 'formatters': { - 'simple': { - 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' - '[%(threadName)s] %(message)s') - } - }, -} - -# Custom Configurations must be in Python dictionary format:: -# -# foo = {'bar':'baz'} -# -# All configurations are accessible at:: -# pecan.conf diff --git a/billingstack/api/hooks.py b/billingstack/api/hooks.py deleted file mode 100644 index 123eedc..0000000 --- a/billingstack/api/hooks.py +++ /dev/null @@ -1,42 +0,0 @@ -from pecan import hooks -from oslo.config import cfg - -from billingstack import storage -from billingstack.central.rpcapi import CentralAPI -from billingstack.openstack.common import log -from billingstack.openstack.common.context import RequestContext - - - -class NoAuthHook(hooks.PecanHook): - """ - Simple auth - all requests will be is_admin=True - """ - def before(self, state): - state.request.ctxt = RequestContext(is_admin=True) - - -class ConfigHook(hooks.PecanHook): - """Attach the configuration object to the request - so controllers can get to it. - """ - - def before(self, state): - state.request.cfg = cfg.CONF - - -class DBHook(hooks.PecanHook): - def before(self, state): - storage_engine = storage.get_engine( - state.request.cfg['service:api'].storage_driver) - state.request.storage_engine = storage_engine - state.request.storage_conn = storage_engine.get_connection() - - # def after(self, state): - # print 'method:', state.request.method - # print 'response:', state.response.status - - -class RPCHook(hooks.PecanHook): - def before(self, state): - state.request.central_api = CentralAPI() \ No newline at end of file diff --git a/billingstack/api/root.py b/billingstack/api/root.py deleted file mode 100644 index 3379301..0000000 --- a/billingstack/api/root.py +++ /dev/null @@ -1,31 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from pecan import expose, redirect -from webob.exc import status_map - -from . import v1 - -class RootController(object): - - v1 = v1.V1Controller() - - @expose(generic=True, template='index.html') - def index(self): - # FIXME: Return version information - return dict() diff --git a/billingstack/api/templates/error.html b/billingstack/api/templates/error.html deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/api/templates/index.html b/billingstack/api/templates/index.html deleted file mode 100644 index 27ae7ff..0000000 --- a/billingstack/api/templates/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - BillingStack Diagnostics - - -

Diagnostics

-

Here you'll find some basic information about your BillingStack server

- - diff --git a/billingstack/api/v1/__init__.py b/billingstack/api/v1/__init__.py deleted file mode 100644 index b508599..0000000 --- a/billingstack/api/v1/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .controllers import V1Controller \ No newline at end of file diff --git a/billingstack/api/v1/controllers.py b/billingstack/api/v1/controllers.py deleted file mode 100644 index 6848225..0000000 --- a/billingstack/api/v1/controllers.py +++ /dev/null @@ -1,315 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from pecan import request - -import wsmeext.pecan as wsme_pecan - -from billingstack.openstack.common import log -from billingstack.api.base import RestBase -from billingstack.api.v1 import models - -LOG = log.getLogger(__name__) - - -class CurrenciesController(RestBase): - """Currsencies controller""" - - @wsme_pecan.wsexpose([models.Currency]) - def get_all(self): - rows = request.central_api.currency_list(request.ctxt) - - return [models.Currency.from_db(r) for r in rows] - - -class LanguagesController(RestBase): - """Languages controller""" - - @wsme_pecan.wsexpose([models.Language]) - def get_all(self): - rows = request.central_api.language_list(request.ctxt) - - return [models.Language.from_db(r) for r in rows] - - -class PGProvidersController(RestBase): - """ - PaymentGatewayProviders - """ - @wsme_pecan.wsexpose([models.PGProvider]) - def get_all(self): - rows = request.central_api.pg_provider_list(request.ctxt) - - return [models.PGProvider.from_db(r) for r in rows] - - -class PGMethodsController(RestBase): - """ - PGMethods lister... - """ - @wsme_pecan.wsexpose([models.PGMethod]) - def get_all(self): - rows = request.central_api.pg_method_list(request.ctxt) - - return [models.PGMethod.from_db(r) for r in rows] - - -# Plans -class PlanController(RestBase): - __id__ = 'plan' - - @wsme_pecan.wsexpose(models.Plan) - def get_all(self): - row = request.central_api.plan_get(request.ctxt, self.id_) - - return models.Plan.from_db(row) - - @wsme_pecan.wsexpose(models.Plan, body=models.Plan) - def put(self, body): - row = request.central_api.plan_update( - request.ctxt, - self.id_, - body.to_db()) - - return models.Plan.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.central_api.plan_delete(request.ctxt, self.id_) - - -class PlansController(RestBase): - __resource__ = PlanController - - @wsme_pecan.wsexpose([models.Plan]) - def get_all(self): - rows = request.central_api.plan_list(request.ctxt) - - return [models.Plan.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(models.Plan, body=models.Plan) - def post(self, body): - row = request.central_api.plan_add( - request.ctxt, - request.context['merchant_id'], - body.to_db()) - - return models.Plan.from_db(row) - - -class PaymentMethodController(RestBase): - """PaymentMethod controller""" - __id__ = 'payment_method' - - @wsme_pecan.wsexpose(models.PaymentMethod, unicode) - def get_all(self): - row = request.central_api.payment_method_get(request.ctxt, self.id_) - - return models.PaymentMethod.from_db(row) - - @wsme_pecan.wsexpose(models.PaymentMethod, body=models.PaymentMethod) - def put(self, body): - row = request.central_api.payment_method_update( - request.ctxt, - self.id_, - body.to_db()) - - return models.PaymentMethod.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.central_api.payment_method_delete(request.ctxt, self.id_) - - -class PaymentMethodsController(RestBase): - """PaymentMethods controller""" - __resource__ = PaymentMethodController - - @wsme_pecan.wsexpose([models.PaymentMethod], unicode) - def get_all(self): - criterion = { - 'customer_id': request.context['customer_id'] - } - - rows = request.central_api.payment_method_list( - request.ctxt, - criterion=criterion) - - return [models.PaymentMethod.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(models.PaymentMethod, body=models.PaymentMethod) - def post(self, body): - row = request.central_api.payment_method_add( - request.ctxt, - request.context['customer_id'], - body.to_db()) - - return models.PaymentMethod.from_db(row) - - -# Products -class ProductController(RestBase): - __id__ = 'product' - - @wsme_pecan.wsexpose(models.Product) - def get_all(self): - row = request.central_api.product_get(request.ctxt, self.id_) - - return models.Product.from_db(row) - - @wsme_pecan.wsexpose(models.Product, body=models.Product) - def put(self, body): - row = request.central_api.product_update( - request.ctxt, - self.id_, - body.to_db()) - - return models.Product.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.central_api.product_delete(request.ctxt, self.id_) - - -class ProductsController(RestBase): - __resource__ = ProductController - - @wsme_pecan.wsexpose([models.Product]) - def get_all(self): - rows = request.central_api.product_list(request.ctxt) - - return [models.Product.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(models.Product, body=models.Product) - def post(self, body): - row = request.central_api.product_add( - request.ctxt, - request.context['merchant_id'], - body.to_db()) - - return models.Product.from_db(row) - - -# Customers -class CustomerController(RestBase): - """Customer controller""" - __id__ = 'customer' - __resource__ = { - "payment-methods": PaymentMethodsController, - } - - @wsme_pecan.wsexpose(models.Customer, unicode) - def get_all(self): - row = request.central_api.customer_get(request.ctxt, self.id_) - - return models.Customer.from_db(row) - - @wsme_pecan.wsexpose(models.Customer, body=models.Customer) - def put(self, body): - row = request.central_api.customer_update( - request.ctxt, - self.id_, - body.to_db()) - - return models.Customer.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.central_api.customer_delete(request.ctxt, self.id_) - - -class CustomersController(RestBase): - """Customers controller""" - __resource__ = CustomerController - - @wsme_pecan.wsexpose([models.Customer]) - def get_all(self): - rows = request.central_api.customer_list( - request.ctxt, criterion={"merchant_id": self.parent.id_}) - - return [models.Customer.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(models.Customer, body=models.Customer) - def post(self, body): - row = request.central_api.customer_add( - request.ctxt, - request.context['merchant_id'], - body.to_db()) - - return models.Customer.from_db(row) - - -class MerchantController(RestBase): - __id__ = 'merchant' - __resource__ = { - "customers": CustomersController, - "plans": PlansController, - "products": ProductsController, - } - - @wsme_pecan.wsexpose(models.Merchant) - def get_all(self): - row = request.central_api.merchant_get(request.ctxt, self.id_) - - return models.Merchant.from_db(row) - - @wsme_pecan.wsexpose(models.Merchant, body=models.Merchant) - def put(self, body): - row = request.central_api.merchant_update( - request.ctxt, - self.id_, - body.to_db()) - - return models.Merchant.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.central_api.merchant_delete(request.ctxt, self.id_) - - -class MerchantsController(RestBase): - """Merchants controller""" - __resource__ = MerchantController - - @wsme_pecan.wsexpose([models.Merchant]) - def get_all(self): - rows = request.central_api.merchant_list(request.ctxt) - - return [models.Merchant.from_db(i) for i in rows] - - @wsme_pecan.wsexpose(models.Merchant, body=models.Merchant) - def post(self, body): - row = request.central_api.merchant_add( - request.ctxt, - body.to_db()) - - return models.Merchant.from_db(row) - - -class V1Controller(RestBase): - """Version 1 API controller.""" - - __resource__ = { - 'payment-gateway-providers': PGProvidersController, - 'payment-gateway-methods': PGMethodsController - } - - currencies = CurrenciesController() - languages = LanguagesController() - - merchants = MerchantsController() diff --git a/billingstack/api/v1/models.py b/billingstack/api/v1/models.py deleted file mode 100644 index c2fb504..0000000 --- a/billingstack/api/v1/models.py +++ /dev/null @@ -1,122 +0,0 @@ -from wsme.types import text, Unset, DictType - - -from billingstack.api.base import ModelBase, property_type - - -class Base(ModelBase): - id = text - - -class DescribedBase(Base): - name = text - title = text - description = text - - -def change_suffixes(data, keys, shorten=True, suffix='_name'): - """ - Loop thro the keys foreach key setting for example - 'currency_name' > 'currency' - """ - for key in keys: - if shorten: - new, old = key, key + suffix - else: - new, old = key + suffix, key - if old in data: - if new in data: - raise RuntimeError("Can't override old key with new key") - - data[new] = data.pop(old) - - -class Currency(Base): - id = text - name = text - title = text - -class Language(Base): - id = text - name = text - title = text - - -class PaymentMethod(Base): - name = text - identifier = text - expires = text - - properties = DictType(key_type=text, value_type=property_type) - - -class PGMethod(DescribedBase): - type = text - - -class PGProvider(DescribedBase): - def __init__(self, **kw): - kw['methods'] = [PGMethod(**m) for m in kw.get('methods', {})] - super(PGProvider, self).__init__(**kw) - - methods = [PGMethod] - properties = DictType(key_type=text, value_type=property_type) - - -class ContactInfo(Base): - id = text - first_name = text - last_name = text - company = text - address1 = text - address2 = text - address3 = text - locality = text - region = text - country_name = text - postal_code = text - - phone = text - email = text - website = text - - -class Product(DescribedBase): - measure = text - type = text - - properties = DictType(key_type=text, value_type=property_type) - - -class Plan(DescribedBase): - properties = DictType(key_type=text, value_type=property_type) - - -class Account(Base): - currency = text - language = text - - name = text - - def to_db(self): - values = self.as_dict() - change_suffixes(values, ['currency', 'language'], shorten=False) - return values - - @classmethod - def from_db(cls, values): - change_suffixes(values, ['currency', 'language']) - return cls(**values) - - -class Merchant(Account): - pass - - -class Customer(Account): - def __init__(self, **kw): - kw['contact_info'] = [ContactInfo(**i) for i in kw.get('contact_info', {})] - super(Customer, self).__init__(**kw) - - merchant_id = text - contact_info = [ContactInfo] diff --git a/billingstack/central/__init__.py b/billingstack/central/__init__.py deleted file mode 100644 index ecdf98b..0000000 --- a/billingstack/central/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -from oslo.config import cfg - -cfg.CONF.register_group(cfg.OptGroup( - name='service:central', title="Configuration for Central Service" -)) - -cfg.CONF.register_opts([ - cfg.IntOpt('workers', default=None, - help='Number of worker processes to spawn'), - cfg.StrOpt('storage-driver', default='sqlalchemy', - help='The storage driver to use'), -], group='service:central') diff --git a/billingstack/central/rpcapi.py b/billingstack/central/rpcapi.py deleted file mode 100644 index 3273f76..0000000 --- a/billingstack/central/rpcapi.py +++ /dev/null @@ -1,233 +0,0 @@ -from oslo.config import cfg - -from billingstack.openstack.common.rpc import proxy - -rpcapi_opts = [ - cfg.StrOpt('central_topic', - default='central', - help='the topic central nodes listen on') -] - -cfg.CONF.register_opts(rpcapi_opts) - - -class CentralAPI(proxy.RpcProxy): - BASE_RPC_VERSION = '1.0' - - def __init__(self): - super(CentralAPI, self).__init__( - topic=cfg.CONF.central_topic, - default_version=self.BASE_RPC_VERSION) - - # Currency - def currency_add(self, ctxt, values): - return self.call(ctxt, self.make_msg('currency_add', values=values)) - - def currency_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('currency_list', criterion=criterion)) - - def currency_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('currency_get', - id_=id_)) - - def currency_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('currency_update', - id_=id_, values=values)) - - def currency_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('currency_delete', - id_=id_)) - - # Language - def language_add(self, ctxt, values): - return self.call(ctxt, self.make_msg('language_add', values=values)) - - def language_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('language_list', criterion=criterion)) - - def language_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('language_get', id_=id_)) - - def language_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('language_update', - language_id, values)) - - def language_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('language_delete', id_=id_)) - - # Contact Info - def contact_info_add(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('contact_info_add', id_=id_, - values=values)) - - def contact_info_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('contact_info_get', id_)) - - def contact_info_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('contact_info_update', id_=id_, - values=values)) - - def contact_info_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('contact_info_delete', id_=id_)) - - # PGP - def pg_provider_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('pg_provider_list', - criterion=criterion)) - - def pg_provider_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('pg_provider_get', id_=id_)) - - # PGM - def pg_method_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('pg_method_list', - criterion=criterion)) - - def pg_method_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('pg_method_list', id_=id_)) - - # PGC - def pg_config_add(self, ctxt, merchant_id, provider_id, values): - return self.call(ctxt, self.make_msg('pg_config_add', - merchant_id=merchant_id, provider_id=provider_id, - values=values)) - - def pg_config_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('pg_config_list', criterion=criterion)) - - def pg_config_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('pg_config_get', id_=id_)) - - def pg_config_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('pg_config_update', id_=id_, - values=values)) - - def pg_config_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('pg_config_delete', id_=id_)) - - # PaymentMethod - def payment_method_add(self, ctxt, customer_id, pg_method_id, values): - return self.call(ctxt, self.make_msg('payment_method_add', - customer_id=customer_id, pg_method_id=pg_method_id, - values=values)) - - def payment_method_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('payment_method_list', - criterion=criterion)) - - def payment_method_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('payment_method_get', id_=id_)) - - def payment_method_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('payment_method_update', id_=id_, - values=values)) - - def payment_method_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('payment_method_delete', id_=id_)) - - # Merchant - def merchant_add(self, ctxt, values): - return self.call(ctxt, self.make_msg('merchant_add', values=values)) - - def merchant_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('merchant_list', criterion=criterion)) - - def merchant_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('merchant_get', id_=id_)) - - def merchant_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('merchant_update', - id_=id_, values=values)) - - def merchant_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('merchant_delete', - id_=id_)) - - # Customer - def customer_add(self, ctxt, merchant_id, values): - return self.call(ctxt, self.make_msg('customer_add', - merchant_id=merchant_id, values=values)) - - def customer_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('customer_list', criterion=criterion)) - - def customer_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('customer_get', id_=id_)) - - def customer_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('customer_update', - id_=id_, values=values)) - - def customer_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('customer_delete', id_=id_)) - - # User - def user_add(self, ctxt, merchant_id, values): - return self.call(ctxt, self.make_msg('user_add', - merchant_id=merchant_id, values=values)) - - def user_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('user_list', criterion=criterion)) - - def user_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('user_get', id_=id_)) - - def user_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('user_update', id_=id_, - values=values)) - - def user_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('user_delete', id_=id_)) - - # Products - def product_add(self, ctxt, merchant_id, values): - return self.call(ctxt, self.make_msg('product_add', - merchant_id=merchant_id, values=values)) - - def product_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('product_list', criterion=criterion)) - - def product_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('product_get', id_=id_)) - - def product_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('product_update', id_=id_, - values=values)) - - def product_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('product_delete', id_=id_)) - - # PlanItems - def plan_item_add(self, ctxt, values): - return self.call(ctxt, self.make_msg('plan_item_add', values=values)) - - def plan_item_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('plan_item_list', criterion=criterion)) - - def plan_item_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('plan_item_get', id_=id_)) - - def plan_item_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('plan_item_update', id_=id_, - values=values)) - - def plan_item_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('plan_item_delete', id_=id_)) - - # Plans - def plan_add(self, ctxt, merchant_id, values): - return self.call(ctxt, self.make_msg('plan_add', - merchant_id=merchant_id, values=values)) - - def plan_list(self, ctxt, criterion=None): - return self.call(ctxt, self.make_msg('plan_list', criterion=criterion)) - - def plan_get(self, ctxt, id_): - return self.call(ctxt, self.make_msg('plan_get', id_=id_)) - - def plan_update(self, ctxt, id_, values): - return self.call(ctxt, self.make_msg('plan_update', id_=id_, - values=values)) - - def plan_delete(self, ctxt, id_): - return self.call(ctxt, self.make_msg('plan_delete', id_=id_)) \ No newline at end of file diff --git a/billingstack/central/service.py b/billingstack/central/service.py deleted file mode 100644 index 12d277b..0000000 --- a/billingstack/central/service.py +++ /dev/null @@ -1,48 +0,0 @@ -import functools -import re -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc -from billingstack.openstack.common.rpc import service as rpc_service -from stevedore.named import NamedExtensionManager -from billingstack import exceptions -from billingstack import storage -from billingstack import utils - - -cfg.CONF.import_opt('host', 'billingstack.netconf') -cfg.CONF.import_opt('central_topic', 'billingstack.central.rpcapi') - -LOG = logging.getLogger(__name__) - - -class Service(rpc_service.Service): - def __init__(self, *args, **kwargs): - kwargs.update( - host=cfg.CONF.host, - topic=cfg.CONF.central_topic, - ) - - super(Service, self).__init__(*args, **kwargs) - - # Get a storage connection - self.storage_conn = storage.get_connection() - - def __getattr__(self, name): - """ - Proxy onto the storage api if there is no local method present.. - - For now to avoid to have to write up every method once more here... - """ - if hasattr(self, name): - return getattr(self, name) - - f = getattr(self.storage_conn, name) - if not f: - raise AttributeError - - @functools.wraps(f) - def _wrapper(*args, **kw): - return f(*args, **kw) - setattr(self, name, _wrapper) - return _wrapper diff --git a/billingstack/exceptions.py b/billingstack/exceptions.py deleted file mode 100644 index 4b4e2f8..0000000 --- a/billingstack/exceptions.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -class Base(Exception): - pass - - -class NotImplemented(Base, NotImplementedError): - pass - - -class ConfigurationError(Base): - pass - - -class InvalidObject(Base): - def __init__(self, *args, **kwargs): - self.errors = kwargs.pop('errors', None) - super(InvalidObject, self).__init__(*args, **kwargs) - - -class BadRequest(Base): - pass - - -class Forbidden(Base): - pass - - -class InvalidSortKey(Base): - pass - - -class Duplicate(Base): - pass - - -class NotFound(Base): - pass - diff --git a/billingstack/identity/__init__.py b/billingstack/identity/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/identity/api/__init__.py b/billingstack/identity/api/__init__.py deleted file mode 100644 index 0d0ea3d..0000000 --- a/billingstack/identity/api/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2013 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from oslo.config import cfg - -API_SERVICE_OPTS = [ - cfg.IntOpt('api_port', default=9092, - help='The port for the BS Identity API server'), - cfg.IntOpt('api_listen', default='0.0.0.0', help='Bind to address'), - cfg.StrOpt('storage_driver', default='sqlalchemy', help='Storage driver to use'), -] - -cfg.CONF.register_opts(API_SERVICE_OPTS, 'service:identity_api') \ No newline at end of file diff --git a/billingstack/identity/api/app.py b/billingstack/identity/api/app.py deleted file mode 100644 index 381b9a7..0000000 --- a/billingstack/identity/api/app.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 Woorea Solutions, S.L -# -# Author: Luis Gervaso -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from pecan import configuration -from pecan import make_app - -from billingstack.api.hooks import ConfigHook, NoAuthHook -from billingstack.identity.api import config as api_config -from billingstack.identity.api.hooks import DBHook - - -def get_pecan_config(): - # Set up the pecan configuration - filename = api_config.__file__.replace('.pyc', '.py') - return configuration.conf_from_file(filename) - - -def setup_app(pecan_config=None, extra_hooks=None): - - app_hooks = [ConfigHook(), DBHook()] - - if extra_hooks: - app_hooks.extend(extra_hooks) - - if not pecan_config: - pecan_config = get_pecan_config() - - app_hooks.append(NoAuthHook()) - - configuration.set_config(dict(pecan_config), overwrite=True) - - app = make_app( - pecan_config.app.root, - static_root=pecan_config.app.static_root, - template_path=pecan_config.app.template_path, - logging=getattr(pecan_config, 'logging', {}), - debug=getattr(pecan_config.app, 'debug', False), - force_canonical=getattr(pecan_config.app, 'force_canonical', True), - hooks=app_hooks, - guess_content_type_from_ext=getattr( - pecan_config.app, - 'guess_content_type_from_ext', - True), - ) - - return app \ No newline at end of file diff --git a/billingstack/identity/api/config.py b/billingstack/identity/api/config.py deleted file mode 100644 index c2b9e52..0000000 --- a/billingstack/identity/api/config.py +++ /dev/null @@ -1,43 +0,0 @@ -# Server Specific Configurations -server = { - 'port': '9001', - 'host': '0.0.0.0' -} - -# Pecan Application Configurations -app = { - 'root': 'billingstack.identity.api.v1.RootController', - 'modules': ['billingstack.identity.api'], - 'static_root': '%(confdir)s/public', - 'template_path': '%(confdir)s/templates', - 'debug': False, - 'enable_acl': True, -} - -logging = { - 'loggers': { - 'root': {'level': 'INFO', 'handlers': ['console']}, - 'billingstack': {'level': 'DEBUG', 'handlers': ['console']}, - 'wsme': {'level': 'DEBUG', 'handlers': ['console']} - }, - 'handlers': { - 'console': { - 'level': 'DEBUG', - 'class': 'logging.StreamHandler', - 'formatter': 'simple' - } - }, - 'formatters': { - 'simple': { - 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' - '[%(threadName)s] %(message)s') - } - }, -} - -# Custom Configurations must be in Python dictionary format:: -# -# foo = {'bar':'baz'} -# -# All configurations are accessible at:: -# pecan.conf diff --git a/billingstack/identity/api/hooks.py b/billingstack/identity/api/hooks.py deleted file mode 100644 index b9a0037..0000000 --- a/billingstack/identity/api/hooks.py +++ /dev/null @@ -1,11 +0,0 @@ -from pecan import hooks -from oslo.config import cfg - -from billingstack.identity.base import IdentityPlugin - - -class DBHook(hooks.PecanHook): - def before(self, state): - plugin = IdentityPlugin.get_plugin( - cfg.CONF['service:identity_api'].storage_driver) - state.request.storage_conn = plugin() diff --git a/billingstack/identity/api/v1.py b/billingstack/identity/api/v1.py deleted file mode 100644 index f911162..0000000 --- a/billingstack/identity/api/v1.py +++ /dev/null @@ -1,216 +0,0 @@ -from oslo.config import cfg -from pecan import hooks, request, expose, rest -import wsmeext.pecan as wsme_pecan -from wsme.types import text, wsattr - -from billingstack.api.base import ModelBase, RestBase - - -class LoginCredentials(ModelBase): - name = wsattr(text, mandatory=True) - password = text - merchant = text - - -class LoginResponse(ModelBase): - """ - The response of the login - """ - token = text - - -class User(ModelBase): - def __init__(self, **kw): - #kw['contact_info'] = ContactInfo(**kw.get('contact_info', {})) - super(User, self).__init__(**kw) - - id = text - name = text - password = text - - @classmethod - def from_db(cls, values): - """ - Remove the password and anything else that's private. - """ - del values['password'] - return cls(**values) - - -class Account(ModelBase): - id = text - name = text - type = text - - -class Role(ModelBase): - id = text - name = text - type = text - - -class UserController(RestBase): - """User controller""" - __id__ = 'user' - - @wsme_pecan.wsexpose(User) - def get_all(self): - row = request.storage_conn.get_user(request.ctxt, self.id_) - return User.from_db(row) - - @wsme_pecan.wsexpose(User, body=User) - def put(self, body): - row = request.storage_conn.update_user( - request.ctxt, - self.id_, - body.to_db()) - - return User.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.storage_conn.delete_user(request.ctxt, self.id_) - - -class UsersController(RestBase): - """Users controller""" - __resource__ = UserController - - @wsme_pecan.wsexpose([User]) - def get_all(self): - criterion = {} - rows = request.storage_conn.list_users( - request.ctxt, - criterion=criterion) - - return [User.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(User, body=User) - def post(self, body): - row = request.storage_conn.create_user( - request.ctxt, - body.to_db()) - - return User.from_db(row) - - -class AccountRolesController(rest.RestController): - def __init__(self, account_id, user_id, role_id): - self.account_id = account_id - self.user_id = user_id - self.role_id = role_id - - @wsme_pecan.wsexpose() - def put(self): - return request.storage_conn.create_grant(request.ctxt, self.user_id, - self.account_id, self.role_id) - - @wsme_pecan.wsexpose() - def delete(self): - request.storage_conn.revoke_grant(request.ctxt, self.user_id, - self.account_id, self.role_id) - - -class AccountController(RestBase): - @expose() - def _lookup(self, *remainder): - if remainder[0] == 'users' and remainder[2] == 'roles': - return AccountRolesController(self.id_, remainder[1], remainder[3]), () - return super(AccountController, self)._lookup(remainder) - - @wsme_pecan.wsexpose(Account) - def get_all(self): - row = request.storage_conn.get_account(request.ctxt, self.id_) - return Account.from_db(row) - - @wsme_pecan.wsexpose(Account, body=Account) - def put(self, body): - row = request.storage_conn.update_account( - request.ctxt, - self.id_, - body.to_db()) - - return Account.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.storage_conn.delete_account(request.ctxt, self.id_) - - -class AccountsController(RestBase): - __resource__ = AccountController - - @wsme_pecan.wsexpose([Account]) - def get_all(self): - rows = request.storage_conn.list_accounts(request.ctxt) - return [Account.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(Account, body=Account) - def post(self, body): - row = request.storage_conn.create_account( - request.ctxt, - body.to_db()) - return Account.from_db(row) - - -class RoleController(RestBase): - @wsme_pecan.wsexpose(Role, unicode) - def get_all(self): - row = request.storage_conn.get_role(request.ctxt, self.id_) - return Role.from_db(row) - - @wsme_pecan.wsexpose(Role, body=Role) - def put(self, body): - row = request.storage_conn.update_role( - request.ctxt, - self.id_, - body.to_db()) - - return Role.from_db(row) - - @wsme_pecan.wsexpose() - def delete(self): - request.storage_conn.delete_role(request.ctxt, self.id_) - - -class RolesController(RestBase): - __resource__ = RoleController - - @wsme_pecan.wsexpose([Role]) - def get_all(self): - rows = request.storage_conn.list_roles(request.ctxt,) - return [Role.from_db(r) for r in rows] - - @wsme_pecan.wsexpose(Role, body=Role) - def post(self, body): - row = request.storage_conn.create_role( - request.ctxt, - body.to_db()) - return Role.from_db(row) - - -class TokensController(RestBase): - """ - controller that authenticates a user... - """ - - @wsme_pecan.wsexpose(LoginResponse, body=LoginCredentials) - def post(self, body): - data = { - 'user_id': body.name, - 'password': body.password} - - auth_response = request.storage_conn.authenticate(request.ctxt, **data) - return LoginResponse(**auth_response) - - -class V1Controller(RestBase): - accounts = AccountsController() - roles = RolesController() - users = UsersController() - - tokens = TokensController() - - -class RootController(RestBase): - v1 = V1Controller() diff --git a/billingstack/identity/base.py b/billingstack/identity/base.py deleted file mode 100644 index afa4817..0000000 --- a/billingstack/identity/base.py +++ /dev/null @@ -1,172 +0,0 @@ -from oslo.config import cfg - -from billingstack.plugin import Plugin - -cfg.CONF.import_opt('storage_driver', 'billingstack.identity.api', - group='service:identity_api') - - -class IdentityPlugin(Plugin): - """ - A base IdentityPlugin - """ - __plugin_ns__ = 'billingstack.identity_plugin' - __plugin_type__ = 'identity' - - @classmethod - def get_plugin(self, name=cfg.CONF['service:identity_api'].storage_driver, - **kw): - return super(IdentityPlugin, self).get_plugin(name, **kw) - - def authenticate(self, context, user_id=None, password=None, account_id=None): - """ - Authenticate a User - - :param user_id: User ID - :param password: User Password - :param account_id: User ID - """ - raise NotImplementedError - - def create_user(self, context, values): - """ - Create a User. - - :param values: The values to create the User from. - """ - raise NotImplementedError - - def list_users(self, context, criterion=None): - """ - List users. - - :param criterion: Criterion to filter on. - """ - raise NotImplementedError - - def get_user(self, context, id_): - """ - Get a User by ID. - - :param id_: User id. - """ - raise NotImplementedError - - def update_user(self, context, id, values): - """ - Update a User. - - :param id_: User ID. - :param values: Values to update the User with. - """ - raise NotImplementedError - - def delete_user(self, context, id_): - """ - Delete User. - - :param id_: User ID to delete. - """ - raise NotImplementedError - - def create_account(self, context, values): - """ - Create an Account. - - :param values: Values to create Account from. - """ - raise NotImplementedError - - def list_accounts(self, context, criterion=None): - """ - List Accounts. - - :param criterion: Criterion to filter on. - """ - raise NotImplementedError - - def get_account(self, context, id_): - """ - Get Account - - :param id_: Account ID. - """ - raise NotImplementedError - - def update_account(self, context, id_, values): - """ - Update Account. - - :param id_: Account ID. - :param values: Account values. - """ - raise NotImplementedError - - def delete_account(self, context, id_): - """ - Delete Account. - - :param id_: Account ID - """ - raise NotImplementedError - - def create_role(self, context, values): - """ - Create an Role. - - :param values: Values to create Role from. - """ - raise NotImplementedError - - def list_roles(self, context, criterion=None): - """ - List Accounts. - - :param criterion: Criterion to filter on. - """ - raise NotImplementedError - - def get_role(self, context, id_): - """ - Get Role. - - :param id_: Role ID. - """ - raise NotImplementedError - - def update_role(self, context, id_, values): - """ - Update Role. - - :param id_: Role ID. - :param values: Role values. - """ - raise NotImplementedError - - def delete_role(self, context, id_): - """ - Delete Role. - - :param id_: Role ID - """ - raise NotImplementedError - - def create_grant(self, context, user_id, account_id, role_id): - """ - Create a Grant - - :param user_id: User ID. - :param account_id: Account ID. - :param role_id: Role ID. - """ - raise NotImplementedError - - def remove_grant(self, context, user_id, account_id, role_id): - """ - Remove a Users Role grant on a Account - - :param user_id: User ID. - :param account_id: Account ID. - :param role_id: Role ID. - """ - raise NotImplementedError diff --git a/billingstack/identity/impl_sqlalchemy.py b/billingstack/identity/impl_sqlalchemy.py deleted file mode 100644 index 8b3d70f..0000000 --- a/billingstack/identity/impl_sqlalchemy.py +++ /dev/null @@ -1,215 +0,0 @@ -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -A Identity plugin... -""" -from oslo.config import cfg -from sqlalchemy import Column, ForeignKey, UniqueConstraint -from sqlalchemy import Unicode -from sqlalchemy.orm import exc -from sqlalchemy.ext.declarative import declarative_base - -from billingstack import exceptions -from billingstack.openstack.common import log as logging -from billingstack.sqlalchemy.types import JSON, UUID -from billingstack.sqlalchemy import api, model_base, session -from billingstack.identity.base import IdentityPlugin -from billingstack.identity import utils as identity_utils - - -LOG = logging.getLogger(__name__) - - -# DB SCHEMA -BASE = declarative_base(cls=model_base.ModelBase) - - -cfg.CONF.register_group(cfg.OptGroup( - name='identity:sqlalchemy', title='Config for internal identity plugin')) - - -cfg.CONF.register_opts(session.SQLOPTS, group='identity:sqlalchemy') - - -class Role(BASE, model_base.BaseMixin): - name = Column(Unicode(64), unique=True, nullable=False) - extra = Column(JSON) - - -class UserAccountGrant(BASE): - user_id = Column(UUID, ForeignKey('user.id', ondelete='CASCADE', - onupdate='CASCADE'), primary_key=True) - account_id = Column(UUID, ForeignKey('account.id', ondelete='CASCADE', - onupdate='CASCADE'), primary_key=True) - data = Column(JSON) - - -class Account(BASE, model_base.BaseMixin): - type = Column(Unicode(10), nullable=False) - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(100)) - - -class User(BASE, model_base.BaseMixin): - """ - A User that can login. - """ - name = Column(Unicode(20), nullable=False) - password = Column(Unicode(255), nullable=False) - - -class SQLAlchemyPlugin(IdentityPlugin, api.HelpersMixin): - """ - A Internal IdentityPlugin that currently relies on SQLAlchemy as - the "Backend" - """ - def __init__(self): - self.setup('identity:sqlalchemy') - - def base(self): - return BASE - - def authenticate(self, context, user_id=None, password=None, account_id=None): - #self._get_by_name(models. - pass - - def create_user(self, context, values): - row = User(**values) - row.password = identity_utils.hash_password(row.password) - self._save(row) - return dict(row) - - def list_users(self, context, criterion=None): - rows = self._list(User, criterion=criterion) - return map(dict, rows) - - def get_user(self, context, id_): - row = self._get(User, id_) - return dict(row) - - def update_user(self, context, id_, values): - row = self._update(User, id_, values) - return dict(row) - - def delete_user(self, context, id_): - self._delete(User, id_) - - def create_account(self, context, values): - row = Account(**values) - self._save(row) - return dict(row) - - def list_accounts(self, context, criterion=None): - rows = self._list(Account, criterion=criterion) - return map(dict, rows) - - def get_account(self, context, id_): - row = self._get(Account, id_) - return dict(row) - - def update_account(self, context, id_, values): - row = self._update(Account, id_, values) - return dict(row) - - def delete_account(self, context, id_): - self._delete(Account, id_) - - def create_role(self, context, values): - row = Role(**values) - self._save(row) - return dict(row) - - def list_roles(self, context, criterion=None): - rows = self._list(Role, criterion=criterion) - return map(dict, rows) - - def get_role(self, context, id_): - row = self._get(Role, id_) - return dict(row) - - def update_role(self, context, id_, values): - row = self._update(Role, id_, values) - return dict(row) - - def delete_role(self, context, id_): - self._delete(Role, id_) - - def get_metadata(self, user_id=None, account_id=None): - q = self.session.query(UserAccountGrant)\ - .filter_by(user_id=user_id, account_id=account_id) - try: - return q.one().data - except exc.NoResultFound: - raise exceptions.NotFound - - def create_metadata(self, user_id, account_id, metadata): - ref = UserAccountGrant( - account_id=account_id, - user_id=user_id, - data=metadata) - ref.save(self.session) - return metadata - - def update_metadata(self, user_id, account_id, metadata): - q = self.session.query(UserAccountGrant)\ - .filter_by(user_id=user_id, account_id=account_id) - ref = q.first() - data = ref.data.copy() - data.update(metadata) - ref.data = data - ref.save(self.session) - return ref - - def create_grant(self, context, user_id, account_id, role_id): - self._get(Role, role_id) - - try: - ref = self.get_metadata(user_id=user_id, account_id=account_id) - is_new = False - except exceptions.NotFound: - ref = {} - is_new = True - - roles = set(ref.get('roles', [])) - roles.add(role_id) - ref['roles'] = list(roles) - - if is_new: - self.create_metadata(user_id, account_id, ref) - else: - self.update_metadata(user_id, account_id, ref) - - def revoke_grant(self, context, user_id, account_id, role_id): - self._get(Role, role_id) - - try: - ref = self.get_metadata(user_id=user_id, account_id=account_id) - is_new = False - except exceptions.NotFound: - ref = {} - is_new = True - - roles = set(ref.get('roles', [])) - - try: - roles.remove(role_id) - except KeyError: - raise exceptions.NotFound(role_id=role_id) - - ref['roles'] = list(roles) - - if is_new: - self.create_metadata(user_id, account_id, ref) - else: - self.update_metadata(user_id, account_id, ref) diff --git a/billingstack/identity/utils.py b/billingstack/identity/utils.py deleted file mode 100644 index 3d9b1d1..0000000 --- a/billingstack/identity/utils.py +++ /dev/null @@ -1,51 +0,0 @@ -import passlib.hash -from oslo.config import cfg -import random -import string - -from billingstack import exceptions - -cfg.CONF.register_opt( - cfg.IntOpt('crypt_strength', default=40000)) - - -MAX_PASSWORD_LENGTH = 4096 - - -def generate_random_string(chars=7): - return u''.join(random.sample(string.ascii_letters * 2 + string.digits, - chars)) - - -def trunc_password(password): - """Truncate passwords to the MAX_PASSWORD_LENGTH.""" - try: - if len(password) > MAX_PASSWORD_LENGTH: - return password[:MAX_PASSWORD_LENGTH] - else: - return password - except TypeError: - raise exceptions.ValidationError(attribute='string', target='password') - - -def hash_password(password): - """Hash a password. Hard.""" - password_utf8 = trunc_password(password).encode('utf-8') - if passlib.hash.sha512_crypt.identify(password_utf8): - return password_utf8 - h = passlib.hash.sha512_crypt.encrypt(password_utf8, - rounds=cfg.CONF.crypt_strength) - return h - - -def check_password(password, hashed): - """Check that a plaintext password matches hashed. - - hashpw returns the salt value concatenated with the actual hash value. - It extracts the actual salt if this value is then passed as the salt. - - """ - if password is None: - return False - password_utf8 = trunc_password(password).encode('utf-8') - return passlib.hash.sha512_crypt.verify(password_utf8, hashed) diff --git a/billingstack/manage/__init__.py b/billingstack/manage/__init__.py deleted file mode 100644 index 5f57c92..0000000 --- a/billingstack/manage/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from cliff.app import App -from cliff.commandmanager import CommandManager -from billingstack.version import version_info as version - - -class Shell(App): - def __init__(self): - super(Shell, self).__init__( - description='BillingStack Management CLI', - version=version.version_string(), - command_manager=CommandManager('billingstack.manage') - ) diff --git a/billingstack/manage/base.py b/billingstack/manage/base.py deleted file mode 100644 index 76402e7..0000000 --- a/billingstack/manage/base.py +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from cliff.command import Command as CliffCommand -from cliff.lister import Lister -from cliff.show import ShowOne -from billingstack import utils - - -class Command(CliffCommand): - - def run(self, parsed_args): - #self.context = billingstackContext.get_admin_context() - - return super(Command, self).run(parsed_args) - - def execute(self, parsed_args): - """ - Execute something, this is since we overload self.take_action() - in order to format the data - - This method __NEEDS__ to be overloaded! - - :param parsed_args: The parsed args that are given by take_action() - """ - raise NotImplementedError - - def post_execute(self, data): - """ - Format the results locally if needed, by default we just return data - - :param data: Whatever is returned by self.execute() - """ - return data - - def setup(self, parsed_args): - pass - - def take_action(self, parsed_args): - # TODO: Common Exception Handling Here - self.setup(parsed_args) - results = self.execute(parsed_args) - return self.post_execute(results) - - -class ListCommand(Command, Lister): - def post_execute(self, results): - if len(results) > 0: - columns = utils.get_columns(results) - data = [utils.get_item_properties(i, columns) for i in results] - return columns, data - else: - return [], () - - -class GetCommand(Command, ShowOne): - def post_execute(self, results): - return results.keys(), results.values() - - -class CreateCommand(Command, ShowOne): - def post_execute(self, results): - return results.keys(), results.values() - - -class UpdateCommand(Command, ShowOne): - def post_execute(self, results): - return results.keys(), results.values() - - -class DeleteCommand(Command): - pass diff --git a/billingstack/manage/database.py b/billingstack/manage/database.py deleted file mode 100644 index a4f064e..0000000 --- a/billingstack/manage/database.py +++ /dev/null @@ -1,36 +0,0 @@ -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -from oslo.config import cfg -from billingstack.openstack.common import log -from billingstack.manage.base import Command -from billingstack.storage import get_connection - - -LOG = log.getLogger(__name__) - - -cfg.CONF.import_opt('storage_driver', 'billingstack.central', - group='service:central') -cfg.CONF.import_opt('database_connection', 'billingstack.storage.impl_sqlalchemy', - group='storage:sqlalchemy') - - -class DatabaseCommand(Command): - """ - A Command that uses a storage connection to do some stuff - """ - def setup(self, parsed_args): - self.conn = get_connection() diff --git a/billingstack/manage/provider.py b/billingstack/manage/provider.py deleted file mode 100644 index 1ec0b0b..0000000 --- a/billingstack/manage/provider.py +++ /dev/null @@ -1,25 +0,0 @@ -from billingstack.openstack.common.context import get_admin_context -from billingstack.payment_gateway import register_providers -from billingstack.manage.base import ListCommand -from billingstack.manage.database import DatabaseCommand - - -class ProvidersRegister(DatabaseCommand): - """ - Register Payment Gateway Providers - """ - def execute(self, parsed_args): - context = get_admin_context() - register_providers(context) - - -class ProvidersList(DatabaseCommand, ListCommand): - def execute(self, parsed_args): - context = get_admin_context() - data = self.conn.pg_provider_list(context) - - for p in data: - p['methods'] = ", ".join( - [":".join([m[k] for k in ['type', 'name']])\ - for m in p['methods']]) - return data diff --git a/billingstack/netconf.py b/billingstack/netconf.py deleted file mode 100644 index 21233f6..0000000 --- a/billingstack/netconf.py +++ /dev/null @@ -1,59 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# Copyright 2012 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import socket - -from oslo.config import cfg - -CONF = cfg.CONF - - -def _get_my_ip(): - """ - Returns the actual ip of the local machine. - - This code figures out what source address would be used if some traffic - were to be sent out to some well known address on the Internet. In this - case, a Google DNS server is used, but the specific address does not - matter much. No traffic is actually sent. - """ - try: - csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - csock.connect(('8.8.8.8', 80)) - (addr, port) = csock.getsockname() - csock.close() - return addr - except socket.error: - return "127.0.0.1" - - -netconf_opts = [ - cfg.StrOpt('my_ip', - default=_get_my_ip(), - help='ip address of this host'), - cfg.StrOpt('host', - default=socket.getfqdn(), - help='Name of this node. This can be an opaque identifier. ' - 'It is not necessarily a hostname, FQDN, or IP address. ' - 'However, the node name must be valid within ' - 'an AMQP key, and if using ZeroMQ, a valid ' - 'hostname, FQDN, or IP address') -] - -CONF.register_opts(netconf_opts) diff --git a/billingstack/openstack/__init__.py b/billingstack/openstack/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/openstack/common/__init__.py b/billingstack/openstack/common/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/openstack/common/context.py b/billingstack/openstack/common/context.py deleted file mode 100644 index dd7dd04..0000000 --- a/billingstack/openstack/common/context.py +++ /dev/null @@ -1,81 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Simple class that stores security context information in the web request. - -Projects should subclass this class if they wish to enhance the request -context or provide additional information in their specific WSGI pipeline. -""" - -import itertools -import uuid - - -def generate_request_id(): - return 'req-' + str(uuid.uuid4()) - - -class RequestContext(object): - - """ - Stores information about the security context under which the user - accesses the system, as well as additional request information. - """ - - def __init__(self, auth_tok=None, user=None, tenant=None, is_admin=False, - read_only=False, show_deleted=False, request_id=None): - self.auth_tok = auth_tok - self.user = user - self.tenant = tenant - self.is_admin = is_admin - self.read_only = read_only - self.show_deleted = show_deleted - if not request_id: - request_id = generate_request_id() - self.request_id = request_id - - def to_dict(self): - return {'user': self.user, - 'tenant': self.tenant, - 'is_admin': self.is_admin, - 'read_only': self.read_only, - 'show_deleted': self.show_deleted, - 'auth_token': self.auth_tok, - 'request_id': self.request_id} - - -def get_admin_context(show_deleted="no"): - context = RequestContext(None, - tenant=None, - is_admin=True, - show_deleted=show_deleted) - return context - - -def get_context_from_function_and_args(function, args, kwargs): - """Find an arg of type RequestContext and return it. - - This is useful in a couple of decorators where we don't - know much about the function we're wrapping. - """ - - for arg in itertools.chain(kwargs.values(), args): - if isinstance(arg, RequestContext): - return arg - - return None diff --git a/billingstack/openstack/common/db/__init__.py b/billingstack/openstack/common/db/__init__.py deleted file mode 100644 index 1b9b60d..0000000 --- a/billingstack/openstack/common/db/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Cloudscaling Group, Inc -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. diff --git a/billingstack/openstack/common/db/api.py b/billingstack/openstack/common/db/api.py deleted file mode 100644 index 703527c..0000000 --- a/billingstack/openstack/common/db/api.py +++ /dev/null @@ -1,101 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright (c) 2013 Rackspace Hosting -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Multiple DB API backend support. - -Supported configuration options: - -`db_backend`: DB backend name or full module path to DB backend module. -`dbapi_use_tpool`: Enable thread pooling of DB API calls. - -A DB backend module should implement a method named 'get_backend' which -takes no arguments. The method can return any object that implements DB -API methods. - -*NOTE*: There are bugs in eventlet when using tpool combined with -threading locks. The python logging module happens to use such locks. To -work around this issue, be sure to specify thread=False with -eventlet.monkey_patch(). - -A bug for eventlet has been filed here: - -https://bitbucket.org/eventlet/eventlet/issue/137/ -""" -import functools - -from oslo.config import cfg - -from billingstack.openstack.common import importutils -from billingstack.openstack.common import lockutils - - -db_opts = [ - cfg.StrOpt('db_backend', - default='sqlalchemy', - help='The backend to use for db'), - cfg.BoolOpt('dbapi_use_tpool', - default=False, - help='Enable the experimental use of thread pooling for ' - 'all DB API calls') -] - -CONF = cfg.CONF -CONF.register_opts(db_opts) - - -class DBAPI(object): - def __init__(self, backend_mapping=None): - if backend_mapping is None: - backend_mapping = {} - self.__backend = None - self.__backend_mapping = backend_mapping - - @lockutils.synchronized('dbapi_backend', 'billingstack-') - def __get_backend(self): - """Get the actual backend. May be a module or an instance of - a class. Doesn't matter to us. We do this synchronized as it's - possible multiple greenthreads started very quickly trying to do - DB calls and eventlet can switch threads before self.__backend gets - assigned. - """ - if self.__backend: - # Another thread assigned it - return self.__backend - backend_name = CONF.db_backend - self.__use_tpool = CONF.dbapi_use_tpool - if self.__use_tpool: - from eventlet import tpool - self.__tpool = tpool - # Import the untranslated name if we don't have a - # mapping. - backend_path = self.__backend_mapping.get(backend_name, - backend_name) - backend_mod = importutils.import_module(backend_path) - self.__backend = backend_mod.get_backend() - return self.__backend - - def __getattr__(self, key): - backend = self.__backend or self.__get_backend() - attr = getattr(backend, key) - if not self.__use_tpool or not hasattr(attr, '__call__'): - return attr - - def tpool_wrapper(*args, **kwargs): - return self.__tpool.execute(attr, *args, **kwargs) - - functools.update_wrapper(tpool_wrapper, attr) - return tpool_wrapper diff --git a/billingstack/openstack/common/db/exception.py b/billingstack/openstack/common/db/exception.py deleted file mode 100644 index a1fe3a3..0000000 --- a/billingstack/openstack/common/db/exception.py +++ /dev/null @@ -1,45 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""DB related custom exceptions.""" - -from billingstack.openstack.common.gettextutils import _ - - -class DBError(Exception): - """Wraps an implementation specific exception.""" - def __init__(self, inner_exception=None): - self.inner_exception = inner_exception - super(DBError, self).__init__(str(inner_exception)) - - -class DBDuplicateEntry(DBError): - """Wraps an implementation specific exception.""" - def __init__(self, columns=[], inner_exception=None): - self.columns = columns - super(DBDuplicateEntry, self).__init__(inner_exception) - - -class DBDeadlock(DBError): - def __init__(self, inner_exception=None): - super(DBDeadlock, self).__init__(inner_exception) - - -class DBInvalidUnicodeParameter(Exception): - message = _("Invalid Parameter: " - "Unicode is not supported by the current database.") diff --git a/billingstack/openstack/common/db/sqlalchemy/__init__.py b/billingstack/openstack/common/db/sqlalchemy/__init__.py deleted file mode 100644 index 1b9b60d..0000000 --- a/billingstack/openstack/common/db/sqlalchemy/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Cloudscaling Group, Inc -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. diff --git a/billingstack/openstack/common/db/sqlalchemy/models.py b/billingstack/openstack/common/db/sqlalchemy/models.py deleted file mode 100644 index a188a7a..0000000 --- a/billingstack/openstack/common/db/sqlalchemy/models.py +++ /dev/null @@ -1,103 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# Copyright 2011 Piston Cloud Computing, Inc. -# Copyright 2012 Cloudscaling Group, Inc. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -SQLAlchemy models. -""" - -from sqlalchemy import Column, Integer -from sqlalchemy import DateTime -from sqlalchemy.orm import object_mapper - -from billingstack.openstack.common.db.sqlalchemy.session import get_session -from billingstack.openstack.common import timeutils - - -class ModelBase(object): - """Base class for models.""" - __table_initialized__ = False - created_at = Column(DateTime, default=timeutils.utcnow) - updated_at = Column(DateTime, onupdate=timeutils.utcnow) - metadata = None - - def save(self, session=None): - """Save this object.""" - if not session: - session = get_session() - # NOTE(boris-42): This part of code should be look like: - # sesssion.add(self) - # session.flush() - # But there is a bug in sqlalchemy and eventlet that - # raises NoneType exception if there is no running - # transaction and rollback is called. As long as - # sqlalchemy has this bug we have to create transaction - # explicity. - with session.begin(subtransactions=True): - session.add(self) - session.flush() - - def __setitem__(self, key, value): - setattr(self, key, value) - - def __getitem__(self, key): - return getattr(self, key) - - def get(self, key, default=None): - return getattr(self, key, default) - - def __iter__(self): - columns = dict(object_mapper(self).columns).keys() - # NOTE(russellb): Allow models to specify other keys that can be looked - # up, beyond the actual db columns. An example would be the 'name' - # property for an Instance. - if hasattr(self, '_extra_keys'): - columns.extend(self._extra_keys()) - self._i = iter(columns) - return self - - def next(self): - n = self._i.next() - return n, getattr(self, n) - - def update(self, values): - """Make the model object behave like a dict.""" - for k, v in values.iteritems(): - setattr(self, k, v) - - def iteritems(self): - """Make the model object behave like a dict. - - Includes attributes from joins.""" - local = dict(self) - joined = dict([(k, v) for k, v in self.__dict__.iteritems() - if not k[0] == '_']) - local.update(joined) - return local.iteritems() - - -class SoftDeleteMixin(object): - deleted_at = Column(DateTime) - deleted = Column(Integer, default=0) - - def soft_delete(self, session=None): - """Mark this object as deleted.""" - self.deleted = self.id - self.deleted_at = timeutils.utcnow() - self.save(session=session) diff --git a/billingstack/openstack/common/db/sqlalchemy/utils.py b/billingstack/openstack/common/db/sqlalchemy/utils.py deleted file mode 100644 index c8ab93e..0000000 --- a/billingstack/openstack/common/db/sqlalchemy/utils.py +++ /dev/null @@ -1,132 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# Copyright 2010-2011 OpenStack LLC. -# Copyright 2012 Justin Santa Barbara -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Implementation of paginate query.""" - -import sqlalchemy - -from openstack.common.gettextutils import _ -from openstack.common import log as logging - - -LOG = logging.getLogger(__name__) - - -class InvalidSortKey(Exception): - message = _("Sort key supplied was not valid.") - - -# copy from glance/db/sqlalchemy/api.py -def paginate_query(query, model, limit, sort_keys, marker=None, - sort_dir=None, sort_dirs=None): - """Returns a query with sorting / pagination criteria added. - - Pagination works by requiring a unique sort_key, specified by sort_keys. - (If sort_keys is not unique, then we risk looping through values.) - We use the last row in the previous page as the 'marker' for pagination. - So we must return values that follow the passed marker in the order. - With a single-valued sort_key, this would be easy: sort_key > X. - With a compound-values sort_key, (k1, k2, k3) we must do this to repeat - the lexicographical ordering: - (k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3) - - We also have to cope with different sort_directions. - - Typically, the id of the last row is used as the client-facing pagination - marker, then the actual marker object must be fetched from the db and - passed in to us as marker. - - :param query: the query object to which we should add paging/sorting - :param model: the ORM model class - :param limit: maximum number of items to return - :param sort_keys: array of attributes by which results should be sorted - :param marker: the last item of the previous page; we returns the next - results after this value. - :param sort_dir: direction in which results should be sorted (asc, desc) - :param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys - - :rtype: sqlalchemy.orm.query.Query - :return: The query with sorting/pagination added. - """ - - if 'id' not in sort_keys: - # TODO(justinsb): If this ever gives a false-positive, check - # the actual primary key, rather than assuming its id - LOG.warn(_('Id not in sort_keys; is sort_keys unique?')) - - assert(not (sort_dir and sort_dirs)) - - # Default the sort direction to ascending - if sort_dirs is None and sort_dir is None: - sort_dir = 'asc' - - # Ensure a per-column sort direction - if sort_dirs is None: - sort_dirs = [sort_dir for _sort_key in sort_keys] - - assert(len(sort_dirs) == len(sort_keys)) - - # Add sorting - for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs): - sort_dir_func = { - 'asc': sqlalchemy.asc, - 'desc': sqlalchemy.desc, - }[current_sort_dir] - - try: - sort_key_attr = getattr(model, current_sort_key) - except AttributeError: - raise InvalidSortKey() - query = query.order_by(sort_dir_func(sort_key_attr)) - - # Add pagination - if marker is not None: - marker_values = [] - for sort_key in sort_keys: - v = getattr(marker, sort_key) - marker_values.append(v) - - # Build up an array of sort criteria as in the docstring - criteria_list = [] - for i in xrange(0, len(sort_keys)): - crit_attrs = [] - for j in xrange(0, i): - model_attr = getattr(model, sort_keys[j]) - crit_attrs.append((model_attr == marker_values[j])) - - model_attr = getattr(model, sort_keys[i]) - if sort_dirs[i] == 'desc': - crit_attrs.append((model_attr < marker_values[i])) - elif sort_dirs[i] == 'asc': - crit_attrs.append((model_attr > marker_values[i])) - else: - raise ValueError(_("Unknown sort direction, " - "must be 'desc' or 'asc'")) - - criteria = sqlalchemy.sql.and_(*crit_attrs) - criteria_list.append(criteria) - - f = sqlalchemy.sql.or_(*criteria_list) - query = query.filter(f) - - if limit is not None: - query = query.limit(limit) - - return query diff --git a/billingstack/openstack/common/eventlet_backdoor.py b/billingstack/openstack/common/eventlet_backdoor.py deleted file mode 100644 index 8b81ebf..0000000 --- a/billingstack/openstack/common/eventlet_backdoor.py +++ /dev/null @@ -1,87 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright (c) 2012 Openstack, LLC. -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import gc -import pprint -import sys -import traceback - -import eventlet -import eventlet.backdoor -import greenlet -from oslo.config import cfg - -eventlet_backdoor_opts = [ - cfg.IntOpt('backdoor_port', - default=None, - help='port for eventlet backdoor to listen') -] - -CONF = cfg.CONF -CONF.register_opts(eventlet_backdoor_opts) - - -def _dont_use_this(): - print "Don't use this, just disconnect instead" - - -def _find_objects(t): - return filter(lambda o: isinstance(o, t), gc.get_objects()) - - -def _print_greenthreads(): - for i, gt in enumerate(_find_objects(greenlet.greenlet)): - print i, gt - traceback.print_stack(gt.gr_frame) - print - - -def _print_nativethreads(): - for threadId, stack in sys._current_frames().items(): - print threadId - traceback.print_stack(stack) - print - - -def initialize_if_enabled(): - backdoor_locals = { - 'exit': _dont_use_this, # So we don't exit the entire process - 'quit': _dont_use_this, # So we don't exit the entire process - 'fo': _find_objects, - 'pgt': _print_greenthreads, - 'pnt': _print_nativethreads, - } - - if CONF.backdoor_port is None: - return None - - # NOTE(johannes): The standard sys.displayhook will print the value of - # the last expression and set it to __builtin__._, which overwrites - # the __builtin__._ that gettext sets. Let's switch to using pprint - # since it won't interact poorly with gettext, and it's easier to - # read the output too. - def displayhook(val): - if val is not None: - pprint.pprint(val) - sys.displayhook = displayhook - - sock = eventlet.listen(('localhost', CONF.backdoor_port)) - port = sock.getsockname()[1] - eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock, - locals=backdoor_locals) - return port diff --git a/billingstack/openstack/common/exception.py b/billingstack/openstack/common/exception.py deleted file mode 100644 index 96a7bd0..0000000 --- a/billingstack/openstack/common/exception.py +++ /dev/null @@ -1,142 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Exceptions common to OpenStack projects -""" - -import logging - -from billingstack.openstack.common.gettextutils import _ - -_FATAL_EXCEPTION_FORMAT_ERRORS = False - - -class Error(Exception): - def __init__(self, message=None): - super(Error, self).__init__(message) - - -class ApiError(Error): - def __init__(self, message='Unknown', code='Unknown'): - self.message = message - self.code = code - super(ApiError, self).__init__('%s: %s' % (code, message)) - - -class NotFound(Error): - pass - - -class UnknownScheme(Error): - - msg = "Unknown scheme '%s' found in URI" - - def __init__(self, scheme): - msg = self.__class__.msg % scheme - super(UnknownScheme, self).__init__(msg) - - -class BadStoreUri(Error): - - msg = "The Store URI %s was malformed. Reason: %s" - - def __init__(self, uri, reason): - msg = self.__class__.msg % (uri, reason) - super(BadStoreUri, self).__init__(msg) - - -class Duplicate(Error): - pass - - -class NotAuthorized(Error): - pass - - -class NotEmpty(Error): - pass - - -class Invalid(Error): - pass - - -class BadInputError(Exception): - """Error resulting from a client sending bad input to a server""" - pass - - -class MissingArgumentError(Error): - pass - - -class DatabaseMigrationError(Error): - pass - - -class ClientConnectionError(Exception): - """Error resulting from a client connecting to a server""" - pass - - -def wrap_exception(f): - def _wrap(*args, **kw): - try: - return f(*args, **kw) - except Exception, e: - if not isinstance(e, Error): - #exc_type, exc_value, exc_traceback = sys.exc_info() - logging.exception(_('Uncaught exception')) - #logging.error(traceback.extract_stack(exc_traceback)) - raise Error(str(e)) - raise - _wrap.func_name = f.func_name - return _wrap - - -class OpenstackException(Exception): - """ - Base Exception - - To correctly use this class, inherit from it and define - a 'message' property. That message will get printf'd - with the keyword arguments provided to the constructor. - """ - message = "An unknown exception occurred" - - def __init__(self, **kwargs): - try: - self._error_string = self.message % kwargs - - except Exception as e: - if _FATAL_EXCEPTION_FORMAT_ERRORS: - raise e - else: - # at least get the core message out if something happened - self._error_string = self.message - - def __str__(self): - return self._error_string - - -class MalformedRequestBody(OpenstackException): - message = "Malformed message body: %(reason)s" - - -class InvalidContentType(OpenstackException): - message = "Invalid content type %(content_type)s" diff --git a/billingstack/openstack/common/excutils.py b/billingstack/openstack/common/excutils.py deleted file mode 100644 index 0c9e1b4..0000000 --- a/billingstack/openstack/common/excutils.py +++ /dev/null @@ -1,51 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# Copyright 2012, Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Exception related utilities. -""" - -import contextlib -import logging -import sys -import traceback - -from billingstack.openstack.common.gettextutils import _ - - -@contextlib.contextmanager -def save_and_reraise_exception(): - """Save current exception, run some code and then re-raise. - - In some cases the exception context can be cleared, resulting in None - being attempted to be re-raised after an exception handler is run. This - can happen when eventlet switches greenthreads or when running an - exception handler, code raises and catches an exception. In both - cases the exception context will be cleared. - - To work around this, we save the exception state, run handler code, and - then re-raise the original exception. If another exception occurs, the - saved exception is logged and the new exception is re-raised. - """ - type_, value, tb = sys.exc_info() - try: - yield - except Exception: - logging.error(_('Original exception being dropped: %s'), - traceback.format_exception(type_, value, tb)) - raise - raise type_, value, tb diff --git a/billingstack/openstack/common/gettextutils.py b/billingstack/openstack/common/gettextutils.py deleted file mode 100644 index ea6f085..0000000 --- a/billingstack/openstack/common/gettextutils.py +++ /dev/null @@ -1,33 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Red Hat, Inc. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -gettext for openstack-common modules. - -Usual usage in an openstack.common module: - - from billingstack.openstack.common.gettextutils import _ -""" - -import gettext - - -t = gettext.translation('openstack-common', 'locale', fallback=True) - - -def _(msg): - return t.ugettext(msg) diff --git a/billingstack/openstack/common/importutils.py b/billingstack/openstack/common/importutils.py deleted file mode 100644 index 9dec764..0000000 --- a/billingstack/openstack/common/importutils.py +++ /dev/null @@ -1,67 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Import related utilities and helper functions. -""" - -import sys -import traceback - - -def import_class(import_str): - """Returns a class from a string including module and class""" - mod_str, _sep, class_str = import_str.rpartition('.') - try: - __import__(mod_str) - return getattr(sys.modules[mod_str], class_str) - except (ValueError, AttributeError): - raise ImportError('Class %s cannot be found (%s)' % - (class_str, - traceback.format_exception(*sys.exc_info()))) - - -def import_object(import_str, *args, **kwargs): - """Import a class and return an instance of it.""" - return import_class(import_str)(*args, **kwargs) - - -def import_object_ns(name_space, import_str, *args, **kwargs): - """ - Import a class and return an instance of it, first by trying - to find the class in a default namespace, then failing back to - a full path if not found in the default namespace. - """ - import_value = "%s.%s" % (name_space, import_str) - try: - return import_class(import_value)(*args, **kwargs) - except ImportError: - return import_class(import_str)(*args, **kwargs) - - -def import_module(import_str): - """Import a module.""" - __import__(import_str) - return sys.modules[import_str] - - -def try_import(import_str, default=None): - """Try to import a module and if it fails return default.""" - try: - return import_module(import_str) - except ImportError: - return default diff --git a/billingstack/openstack/common/iniparser.py b/billingstack/openstack/common/iniparser.py deleted file mode 100644 index 9bf399f..0000000 --- a/billingstack/openstack/common/iniparser.py +++ /dev/null @@ -1,130 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 OpenStack LLC. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -class ParseError(Exception): - def __init__(self, message, lineno, line): - self.msg = message - self.line = line - self.lineno = lineno - - def __str__(self): - return 'at line %d, %s: %r' % (self.lineno, self.msg, self.line) - - -class BaseParser(object): - lineno = 0 - parse_exc = ParseError - - def _assignment(self, key, value): - self.assignment(key, value) - return None, [] - - def _get_section(self, line): - if line[-1] != ']': - return self.error_no_section_end_bracket(line) - if len(line) <= 2: - return self.error_no_section_name(line) - - return line[1:-1] - - def _split_key_value(self, line): - colon = line.find(':') - equal = line.find('=') - if colon < 0 and equal < 0: - return self.error_invalid_assignment(line) - - if colon < 0 or (equal >= 0 and equal < colon): - key, value = line[:equal], line[equal + 1:] - else: - key, value = line[:colon], line[colon + 1:] - - value = value.strip() - if ((value and value[0] == value[-1]) and - (value[0] == "\"" or value[0] == "'")): - value = value[1:-1] - return key.strip(), [value] - - def parse(self, lineiter): - key = None - value = [] - - for line in lineiter: - self.lineno += 1 - - line = line.rstrip() - if not line: - # Blank line, ends multi-line values - if key: - key, value = self._assignment(key, value) - continue - elif line[0] in (' ', '\t'): - # Continuation of previous assignment - if key is None: - self.error_unexpected_continuation(line) - else: - value.append(line.lstrip()) - continue - - if key: - # Flush previous assignment, if any - key, value = self._assignment(key, value) - - if line[0] == '[': - # Section start - section = self._get_section(line) - if section: - self.new_section(section) - elif line[0] in '#;': - self.comment(line[1:].lstrip()) - else: - key, value = self._split_key_value(line) - if not key: - return self.error_empty_key(line) - - if key: - # Flush previous assignment, if any - self._assignment(key, value) - - def assignment(self, key, value): - """Called when a full assignment is parsed""" - raise NotImplementedError() - - def new_section(self, section): - """Called when a new section is started""" - raise NotImplementedError() - - def comment(self, comment): - """Called when a comment is parsed""" - pass - - def error_invalid_assignment(self, line): - raise self.parse_exc("No ':' or '=' found in assignment", - self.lineno, line) - - def error_empty_key(self, line): - raise self.parse_exc('Key cannot be empty', self.lineno, line) - - def error_unexpected_continuation(self, line): - raise self.parse_exc('Unexpected continuation line', - self.lineno, line) - - def error_no_section_end_bracket(self, line): - raise self.parse_exc('Invalid section (must end with ])', - self.lineno, line) - - def error_no_section_name(self, line): - raise self.parse_exc('Empty section name', self.lineno, line) diff --git a/billingstack/openstack/common/jsonutils.py b/billingstack/openstack/common/jsonutils.py deleted file mode 100644 index d457b6c..0000000 --- a/billingstack/openstack/common/jsonutils.py +++ /dev/null @@ -1,147 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# Copyright 2011 Justin Santa Barbara -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -''' -JSON related utilities. - -This module provides a few things: - - 1) A handy function for getting an object down to something that can be - JSON serialized. See to_primitive(). - - 2) Wrappers around loads() and dumps(). The dumps() wrapper will - automatically use to_primitive() for you if needed. - - 3) This sets up anyjson to use the loads() and dumps() wrappers if anyjson - is available. -''' - - -import datetime -import functools -import inspect -import itertools -import json -import logging -import xmlrpclib - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import timeutils - -LOG = logging.getLogger(__name__) - - -def to_primitive(value, convert_instances=False, convert_datetime=True, - level=0, max_depth=3): - """Convert a complex object into primitives. - - Handy for JSON serialization. We can optionally handle instances, - but since this is a recursive function, we could have cyclical - data structures. - - To handle cyclical data structures we could track the actual objects - visited in a set, but not all objects are hashable. Instead we just - track the depth of the object inspections and don't go too deep. - - Therefore, convert_instances=True is lossy ... be aware. - - """ - nasty = [inspect.ismodule, inspect.isclass, inspect.ismethod, - inspect.isfunction, inspect.isgeneratorfunction, - inspect.isgenerator, inspect.istraceback, inspect.isframe, - inspect.iscode, inspect.isbuiltin, inspect.isroutine, - inspect.isabstract] - for test in nasty: - if test(value): - return unicode(value) - - # value of itertools.count doesn't get caught by inspects - # above and results in infinite loop when list(value) is called. - if type(value) == itertools.count: - return unicode(value) - - # FIXME(vish): Workaround for LP bug 852095. Without this workaround, - # tests that raise an exception in a mocked method that - # has a @wrap_exception with a notifier will fail. If - # we up the dependency to 0.5.4 (when it is released) we - # can remove this workaround. - if getattr(value, '__module__', None) == 'mox': - return 'mock' - - if level > max_depth: - LOG.error(_('Max serialization depth exceeded on object: %d %s'), - level, value) - return '?' - - # The try block may not be necessary after the class check above, - # but just in case ... - try: - recursive = functools.partial(to_primitive, - convert_instances=convert_instances, - convert_datetime=convert_datetime, - level=level, - max_depth=max_depth) - # It's not clear why xmlrpclib created their own DateTime type, but - # for our purposes, make it a datetime type which is explicitly - # handled - if isinstance(value, xmlrpclib.DateTime): - value = datetime.datetime(*tuple(value.timetuple())[:6]) - - if isinstance(value, (list, tuple)): - return [recursive(v) for v in value] - elif isinstance(value, dict): - return dict((k, recursive(v)) for k, v in value.iteritems()) - elif convert_datetime and isinstance(value, datetime.datetime): - return timeutils.strtime(value) - elif hasattr(value, 'iteritems'): - return recursive(dict(value.iteritems()), level=level + 1) - elif hasattr(value, '__iter__'): - return recursive(list(value)) - elif convert_instances and hasattr(value, '__dict__'): - # Likely an instance of something. Watch for cycles. - # Ignore class member vars. - return recursive(value.__dict__, level=level + 1) - else: - return value - except TypeError: - # Class objects are tricky since they may define something like - # __iter__ defined but it isn't callable as list(). - return unicode(value) - - -def dumps(value, default=to_primitive, **kwargs): - return json.dumps(value, default=default, **kwargs) - - -def loads(s): - return json.loads(s) - - -def load(s): - return json.load(s) - - -try: - import anyjson -except ImportError: - pass -else: - anyjson._modules.append((__name__, 'dumps', TypeError, - 'loads', ValueError, 'load')) - anyjson.force_implementation(__name__) diff --git a/billingstack/openstack/common/local.py b/billingstack/openstack/common/local.py deleted file mode 100644 index 8bdc837..0000000 --- a/billingstack/openstack/common/local.py +++ /dev/null @@ -1,48 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Greenthread local storage of variables using weak references""" - -import weakref - -from eventlet import corolocal - - -class WeakLocal(corolocal.local): - def __getattribute__(self, attr): - rval = corolocal.local.__getattribute__(self, attr) - if rval: - # NOTE(mikal): this bit is confusing. What is stored is a weak - # reference, not the value itself. We therefore need to lookup - # the weak reference and return the inner value here. - rval = rval() - return rval - - def __setattr__(self, attr, value): - value = weakref.ref(value) - return corolocal.local.__setattr__(self, attr, value) - - -# NOTE(mikal): the name "store" should be deprecated in the future -store = WeakLocal() - -# A "weak" store uses weak references and allows an object to fall out of scope -# when it falls out of scope in the code that uses the thread local storage. A -# "strong" store will hold a reference to the object so that it never falls out -# of scope. -weak_store = WeakLocal() -strong_store = corolocal.local diff --git a/billingstack/openstack/common/log.py b/billingstack/openstack/common/log.py deleted file mode 100644 index e010517..0000000 --- a/billingstack/openstack/common/log.py +++ /dev/null @@ -1,521 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Openstack logging handler. - -This module adds to logging functionality by adding the option to specify -a context object when calling the various log methods. If the context object -is not specified, default formatting is used. Additionally, an instance uuid -may be passed as part of the log message, which is intended to make it easier -for admins to find messages related to a specific instance. - -It also allows setting of formatting information through conf. - -""" - -import cStringIO -import inspect -import itertools -import logging -import logging.config -import logging.handlers -import os -import stat -import sys -import traceback - -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import local -from billingstack.openstack.common import notifier - - -_DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s" -_DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" - -common_cli_opts = [ - cfg.BoolOpt('debug', - short='d', - default=False, - help='Print debugging output (set logging level to ' - 'DEBUG instead of default WARNING level).'), - cfg.BoolOpt('verbose', - short='v', - default=False, - help='Print more verbose output (set logging level to ' - 'INFO instead of default WARNING level).'), -] - -logging_cli_opts = [ - cfg.StrOpt('log-config', - metavar='PATH', - help='If this option is specified, the logging configuration ' - 'file specified is used and overrides any other logging ' - 'options specified. Please see the Python logging module ' - 'documentation for details on logging configuration ' - 'files.'), - cfg.StrOpt('log-format', - default=_DEFAULT_LOG_FORMAT, - metavar='FORMAT', - help='A logging.Formatter log message format string which may ' - 'use any of the available logging.LogRecord attributes. ' - 'Default: %(default)s'), - cfg.StrOpt('log-date-format', - default=_DEFAULT_LOG_DATE_FORMAT, - metavar='DATE_FORMAT', - help='Format string for %%(asctime)s in log records. ' - 'Default: %(default)s'), - cfg.StrOpt('log-file', - metavar='PATH', - deprecated_name='logfile', - help='(Optional) Name of log file to output to. ' - 'If not set, logging will go to stdout.'), - cfg.StrOpt('log-dir', - deprecated_name='logdir', - help='(Optional) The directory to keep log files in ' - '(will be prepended to --log-file)'), - cfg.BoolOpt('use-syslog', - default=False, - help='Use syslog for logging.'), - cfg.StrOpt('syslog-log-facility', - default='LOG_USER', - help='syslog facility to receive log lines') -] - -generic_log_opts = [ - cfg.BoolOpt('use_stderr', - default=True, - help='Log output to standard error'), - cfg.StrOpt('logfile_mode', - default='0644', - help='Default file mode used when creating log files'), -] - -log_opts = [ - cfg.StrOpt('logging_context_format_string', - default='%(asctime)s.%(msecs)03d %(levelname)s %(name)s ' - '[%(request_id)s %(user)s %(tenant)s] %(instance)s' - '%(message)s', - help='format string to use for log messages with context'), - cfg.StrOpt('logging_default_format_string', - default='%(asctime)s.%(msecs)03d %(process)d %(levelname)s ' - '%(name)s [-] %(instance)s%(message)s', - help='format string to use for log messages without context'), - cfg.StrOpt('logging_debug_format_suffix', - default='%(funcName)s %(pathname)s:%(lineno)d', - help='data to append to log format when level is DEBUG'), - cfg.StrOpt('logging_exception_prefix', - default='%(asctime)s.%(msecs)03d %(process)d TRACE %(name)s ' - '%(instance)s', - help='prefix each line of exception output with this format'), - cfg.ListOpt('default_log_levels', - default=[ - 'amqplib=WARN', - 'sqlalchemy=WARN', - 'boto=WARN', - 'suds=INFO', - 'keystone=INFO', - 'eventlet.wsgi.server=WARN' - ], - help='list of logger=LEVEL pairs'), - cfg.BoolOpt('publish_errors', - default=False, - help='publish error events'), - cfg.BoolOpt('fatal_deprecations', - default=False, - help='make deprecations fatal'), - - # NOTE(mikal): there are two options here because sometimes we are handed - # a full instance (and could include more information), and other times we - # are just handed a UUID for the instance. - cfg.StrOpt('instance_format', - default='[instance: %(uuid)s] ', - help='If an instance is passed with the log message, format ' - 'it like this'), - cfg.StrOpt('instance_uuid_format', - default='[instance: %(uuid)s] ', - help='If an instance UUID is passed with the log message, ' - 'format it like this'), -] - -CONF = cfg.CONF -CONF.register_cli_opts(common_cli_opts) -CONF.register_cli_opts(logging_cli_opts) -CONF.register_opts(generic_log_opts) -CONF.register_opts(log_opts) - -# our new audit level -# NOTE(jkoelker) Since we synthesized an audit level, make the logging -# module aware of it so it acts like other levels. -logging.AUDIT = logging.INFO + 1 -logging.addLevelName(logging.AUDIT, 'AUDIT') - - -try: - NullHandler = logging.NullHandler -except AttributeError: # NOTE(jkoelker) NullHandler added in Python 2.7 - class NullHandler(logging.Handler): - def handle(self, record): - pass - - def emit(self, record): - pass - - def createLock(self): - self.lock = None - - -def _dictify_context(context): - if context is None: - return None - if not isinstance(context, dict) and getattr(context, 'to_dict', None): - context = context.to_dict() - return context - - -def _get_binary_name(): - return os.path.basename(inspect.stack()[-1][1]) - - -def _get_log_file_path(binary=None): - logfile = CONF.log_file - logdir = CONF.log_dir - - if logfile and not logdir: - return logfile - - if logfile and logdir: - return os.path.join(logdir, logfile) - - if logdir: - binary = binary or _get_binary_name() - return '%s.log' % (os.path.join(logdir, binary),) - - -class ContextAdapter(logging.LoggerAdapter): - warn = logging.LoggerAdapter.warning - - def __init__(self, logger, project_name, version_string): - self.logger = logger - self.project = project_name - self.version = version_string - - def audit(self, msg, *args, **kwargs): - self.log(logging.AUDIT, msg, *args, **kwargs) - - def deprecated(self, msg, *args, **kwargs): - stdmsg = _("Deprecated: %s") % msg - if CONF.fatal_deprecations: - self.critical(stdmsg, *args, **kwargs) - raise DeprecatedConfig(msg=stdmsg) - else: - self.warn(stdmsg, *args, **kwargs) - - def process(self, msg, kwargs): - if 'extra' not in kwargs: - kwargs['extra'] = {} - extra = kwargs['extra'] - - context = kwargs.pop('context', None) - if not context: - context = getattr(local.store, 'context', None) - if context: - extra.update(_dictify_context(context)) - - instance = kwargs.pop('instance', None) - instance_extra = '' - if instance: - instance_extra = CONF.instance_format % instance - else: - instance_uuid = kwargs.pop('instance_uuid', None) - if instance_uuid: - instance_extra = (CONF.instance_uuid_format - % {'uuid': instance_uuid}) - extra.update({'instance': instance_extra}) - - extra.update({"project": self.project}) - extra.update({"version": self.version}) - extra['extra'] = extra.copy() - return msg, kwargs - - -class JSONFormatter(logging.Formatter): - def __init__(self, fmt=None, datefmt=None): - # NOTE(jkoelker) we ignore the fmt argument, but its still there - # since logging.config.fileConfig passes it. - self.datefmt = datefmt - - def formatException(self, ei, strip_newlines=True): - lines = traceback.format_exception(*ei) - if strip_newlines: - lines = [itertools.ifilter( - lambda x: x, - line.rstrip().splitlines()) for line in lines] - lines = list(itertools.chain(*lines)) - return lines - - def format(self, record): - message = {'message': record.getMessage(), - 'asctime': self.formatTime(record, self.datefmt), - 'name': record.name, - 'msg': record.msg, - 'args': record.args, - 'levelname': record.levelname, - 'levelno': record.levelno, - 'pathname': record.pathname, - 'filename': record.filename, - 'module': record.module, - 'lineno': record.lineno, - 'funcname': record.funcName, - 'created': record.created, - 'msecs': record.msecs, - 'relative_created': record.relativeCreated, - 'thread': record.thread, - 'thread_name': record.threadName, - 'process_name': record.processName, - 'process': record.process, - 'traceback': None} - - if hasattr(record, 'extra'): - message['extra'] = record.extra - - if record.exc_info: - message['traceback'] = self.formatException(record.exc_info) - - return jsonutils.dumps(message) - - -class PublishErrorsHandler(logging.Handler): - def emit(self, record): - if ('billingstack.openstack.common.notifier.log_notifier' in - CONF.notification_driver): - return - notifier.api.notify(None, 'error.publisher', - 'error_notification', - notifier.api.ERROR, - dict(error=record.msg)) - - -def _create_logging_excepthook(product_name): - def logging_excepthook(type, value, tb): - extra = {} - if CONF.verbose: - extra['exc_info'] = (type, value, tb) - getLogger(product_name).critical(str(value), **extra) - return logging_excepthook - - -def setup(product_name): - """Setup logging.""" - if CONF.log_config: - logging.config.fileConfig(CONF.log_config) - else: - _setup_logging_from_conf(product_name) - sys.excepthook = _create_logging_excepthook(product_name) - - -def set_defaults(logging_context_format_string): - cfg.set_defaults(log_opts, - logging_context_format_string= - logging_context_format_string) - - -def _find_facility_from_conf(): - facility_names = logging.handlers.SysLogHandler.facility_names - facility = getattr(logging.handlers.SysLogHandler, - CONF.syslog_log_facility, - None) - - if facility is None and CONF.syslog_log_facility in facility_names: - facility = facility_names.get(CONF.syslog_log_facility) - - if facility is None: - valid_facilities = facility_names.keys() - consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON', - 'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS', - 'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP', - 'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3', - 'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7'] - valid_facilities.extend(consts) - raise TypeError(_('syslog facility must be one of: %s') % - ', '.join("'%s'" % fac - for fac in valid_facilities)) - - return facility - - -def _setup_logging_from_conf(product_name): - log_root = getLogger(product_name).logger - for handler in log_root.handlers: - log_root.removeHandler(handler) - - if CONF.use_syslog: - facility = _find_facility_from_conf() - syslog = logging.handlers.SysLogHandler(address='/dev/log', - facility=facility) - log_root.addHandler(syslog) - - logpath = _get_log_file_path() - if logpath: - filelog = logging.handlers.WatchedFileHandler(logpath) - log_root.addHandler(filelog) - - mode = int(CONF.logfile_mode, 8) - st = os.stat(logpath) - if st.st_mode != (stat.S_IFREG | mode): - os.chmod(logpath, mode) - - if CONF.use_stderr: - streamlog = ColorHandler() - log_root.addHandler(streamlog) - - elif not CONF.log_file: - # pass sys.stdout as a positional argument - # python2.6 calls the argument strm, in 2.7 it's stream - streamlog = logging.StreamHandler(sys.stdout) - log_root.addHandler(streamlog) - - if CONF.publish_errors: - log_root.addHandler(PublishErrorsHandler(logging.ERROR)) - - for handler in log_root.handlers: - datefmt = CONF.log_date_format - if CONF.log_format: - handler.setFormatter(logging.Formatter(fmt=CONF.log_format, - datefmt=datefmt)) - handler.setFormatter(LegacyFormatter(datefmt=datefmt)) - - if CONF.debug: - log_root.setLevel(logging.DEBUG) - elif CONF.verbose: - log_root.setLevel(logging.INFO) - else: - log_root.setLevel(logging.WARNING) - - level = logging.NOTSET - for pair in CONF.default_log_levels: - mod, _sep, level_name = pair.partition('=') - level = logging.getLevelName(level_name) - logger = logging.getLogger(mod) - logger.setLevel(level) - for handler in log_root.handlers: - logger.addHandler(handler) - -_loggers = {} - - -def getLogger(name='unknown', version='unknown'): - if name not in _loggers: - _loggers[name] = ContextAdapter(logging.getLogger(name), - name, - version) - return _loggers[name] - - -class WritableLogger(object): - """A thin wrapper that responds to `write` and logs.""" - - def __init__(self, logger, level=logging.INFO): - self.logger = logger - self.level = level - - def write(self, msg): - self.logger.log(self.level, msg) - - -class LegacyFormatter(logging.Formatter): - """A context.RequestContext aware formatter configured through flags. - - The flags used to set format strings are: logging_context_format_string - and logging_default_format_string. You can also specify - logging_debug_format_suffix to append extra formatting if the log level is - debug. - - For information about what variables are available for the formatter see: - http://docs.python.org/library/logging.html#formatter - - """ - - def format(self, record): - """Uses contextstring if request_id is set, otherwise default.""" - # NOTE(sdague): default the fancier formating params - # to an empty string so we don't throw an exception if - # they get used - for key in ('instance', 'color'): - if key not in record.__dict__: - record.__dict__[key] = '' - - if record.__dict__.get('request_id', None): - self._fmt = CONF.logging_context_format_string - else: - self._fmt = CONF.logging_default_format_string - - if (record.levelno == logging.DEBUG and - CONF.logging_debug_format_suffix): - self._fmt += " " + CONF.logging_debug_format_suffix - - # Cache this on the record, Logger will respect our formated copy - if record.exc_info: - record.exc_text = self.formatException(record.exc_info, record) - return logging.Formatter.format(self, record) - - def formatException(self, exc_info, record=None): - """Format exception output with CONF.logging_exception_prefix.""" - if not record: - return logging.Formatter.formatException(self, exc_info) - - stringbuffer = cStringIO.StringIO() - traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], - None, stringbuffer) - lines = stringbuffer.getvalue().split('\n') - stringbuffer.close() - - if CONF.logging_exception_prefix.find('%(asctime)') != -1: - record.asctime = self.formatTime(record, self.datefmt) - - formatted_lines = [] - for line in lines: - pl = CONF.logging_exception_prefix % record.__dict__ - fl = '%s%s' % (pl, line) - formatted_lines.append(fl) - return '\n'.join(formatted_lines) - - -class ColorHandler(logging.StreamHandler): - LEVEL_COLORS = { - logging.DEBUG: '\033[00;32m', # GREEN - logging.INFO: '\033[00;36m', # CYAN - logging.AUDIT: '\033[01;36m', # BOLD CYAN - logging.WARN: '\033[01;33m', # BOLD YELLOW - logging.ERROR: '\033[01;31m', # BOLD RED - logging.CRITICAL: '\033[01;31m', # BOLD RED - } - - def format(self, record): - record.color = self.LEVEL_COLORS[record.levelno] - return logging.StreamHandler.format(self, record) - - -class DeprecatedConfig(Exception): - message = _("Fatal call to deprecated config: %(msg)s") - - def __init__(self, msg): - super(Exception, self).__init__(self.message % dict(msg=msg)) diff --git a/billingstack/openstack/common/loopingcall.py b/billingstack/openstack/common/loopingcall.py deleted file mode 100644 index 7f76db6..0000000 --- a/billingstack/openstack/common/loopingcall.py +++ /dev/null @@ -1,95 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# Copyright 2011 Justin Santa Barbara -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import sys - -from eventlet import event -from eventlet import greenthread - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import timeutils - -LOG = logging.getLogger(__name__) - - -class LoopingCallDone(Exception): - """Exception to break out and stop a LoopingCall. - - The poll-function passed to LoopingCall can raise this exception to - break out of the loop normally. This is somewhat analogous to - StopIteration. - - An optional return-value can be included as the argument to the exception; - this return-value will be returned by LoopingCall.wait() - - """ - - def __init__(self, retvalue=True): - """:param retvalue: Value that LoopingCall.wait() should return.""" - self.retvalue = retvalue - - -class LoopingCall(object): - def __init__(self, f=None, *args, **kw): - self.args = args - self.kw = kw - self.f = f - self._running = False - - def start(self, interval, initial_delay=None): - self._running = True - done = event.Event() - - def _inner(): - if initial_delay: - greenthread.sleep(initial_delay) - - try: - while self._running: - start = timeutils.utcnow() - self.f(*self.args, **self.kw) - end = timeutils.utcnow() - if not self._running: - break - delay = interval - timeutils.delta_seconds(start, end) - if delay <= 0: - LOG.warn(_('task run outlasted interval by %s sec') % - -delay) - greenthread.sleep(delay if delay > 0 else 0) - except LoopingCallDone, e: - self.stop() - done.send(e.retvalue) - except Exception: - LOG.exception(_('in looping call')) - done.send_exception(*sys.exc_info()) - return - else: - done.send(True) - - self.done = done - - greenthread.spawn_n(_inner) - return self.done - - def stop(self): - self._running = False - - def wait(self): - return self.done.wait() diff --git a/billingstack/openstack/common/network_utils.py b/billingstack/openstack/common/network_utils.py deleted file mode 100644 index 69f6732..0000000 --- a/billingstack/openstack/common/network_utils.py +++ /dev/null @@ -1,68 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Network-related utilities and helper functions. -""" - -import logging - -LOG = logging.getLogger(__name__) - - -def parse_host_port(address, default_port=None): - """ - Interpret a string as a host:port pair. - An IPv6 address MUST be escaped if accompanied by a port, - because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334 - means both [2001:db8:85a3::8a2e:370:7334] and - [2001:db8:85a3::8a2e:370]:7334. - - >>> parse_host_port('server01:80') - ('server01', 80) - >>> parse_host_port('server01') - ('server01', None) - >>> parse_host_port('server01', default_port=1234) - ('server01', 1234) - >>> parse_host_port('[::1]:80') - ('::1', 80) - >>> parse_host_port('[::1]') - ('::1', None) - >>> parse_host_port('[::1]', default_port=1234) - ('::1', 1234) - >>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234) - ('2001:db8:85a3::8a2e:370:7334', 1234) - - """ - if address[0] == '[': - # Escaped ipv6 - _host, _port = address[1:].split(']') - host = _host - if ':' in _port: - port = _port.split(':')[1] - else: - port = default_port - else: - if address.count(':') == 1: - host, port = address.split(':') - else: - # 0 means ipv4, >1 means ipv6. - # We prohibit unescaped ipv6 addresses with port. - host = address - port = default_port - - return (host, None if port is None else int(port)) diff --git a/billingstack/openstack/common/notifier/__init__.py b/billingstack/openstack/common/notifier/__init__.py deleted file mode 100644 index 482d54e..0000000 --- a/billingstack/openstack/common/notifier/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. diff --git a/billingstack/openstack/common/notifier/api.py b/billingstack/openstack/common/notifier/api.py deleted file mode 100644 index cd9c259..0000000 --- a/billingstack/openstack/common/notifier/api.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import uuid - -from oslo.config import cfg - -from billingstack.openstack.common import context -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import timeutils - - -LOG = logging.getLogger(__name__) - -notifier_opts = [ - cfg.MultiStrOpt('notification_driver', - default=[], - deprecated_name='list_notifier_drivers', - help='Driver or drivers to handle sending notifications'), - cfg.StrOpt('default_notification_level', - default='INFO', - help='Default notification level for outgoing notifications'), - cfg.StrOpt('default_publisher_id', - default='$host', - help='Default publisher_id for outgoing notifications'), -] - -CONF = cfg.CONF -CONF.register_opts(notifier_opts) - -WARN = 'WARN' -INFO = 'INFO' -ERROR = 'ERROR' -CRITICAL = 'CRITICAL' -DEBUG = 'DEBUG' - -log_levels = (DEBUG, WARN, INFO, ERROR, CRITICAL) - - -class BadPriorityException(Exception): - pass - - -def notify_decorator(name, fn): - """ decorator for notify which is used from utils.monkey_patch() - - :param name: name of the function - :param function: - object of the function - :returns: function -- decorated function - - """ - def wrapped_func(*args, **kwarg): - body = {} - body['args'] = [] - body['kwarg'] = {} - for arg in args: - body['args'].append(arg) - for key in kwarg: - body['kwarg'][key] = kwarg[key] - - ctxt = context.get_context_from_function_and_args(fn, args, kwarg) - notify(ctxt, - CONF.default_publisher_id, - name, - CONF.default_notification_level, - body) - return fn(*args, **kwarg) - return wrapped_func - - -def publisher_id(service, host=None): - if not host: - host = CONF.host - return "%s.%s" % (service, host) - - -def notify(context, publisher_id, event_type, priority, payload): - """Sends a notification using the specified driver - - :param publisher_id: the source worker_type.host of the message - :param event_type: the literal type of event (ex. Instance Creation) - :param priority: patterned after the enumeration of Python logging - levels in the set (DEBUG, WARN, INFO, ERROR, CRITICAL) - :param payload: A python dictionary of attributes - - Outgoing message format includes the above parameters, and appends the - following: - - message_id - a UUID representing the id for this notification - - timestamp - the GMT timestamp the notification was sent at - - The composite message will be constructed as a dictionary of the above - attributes, which will then be sent via the transport mechanism defined - by the driver. - - Message example:: - - {'message_id': str(uuid.uuid4()), - 'publisher_id': 'compute.host1', - 'timestamp': timeutils.utcnow(), - 'priority': 'WARN', - 'event_type': 'compute.create_instance', - 'payload': {'instance_id': 12, ... }} - - """ - if priority not in log_levels: - raise BadPriorityException( - _('%s not in valid priorities') % priority) - - # Ensure everything is JSON serializable. - payload = jsonutils.to_primitive(payload, convert_instances=True) - - msg = dict(message_id=str(uuid.uuid4()), - publisher_id=publisher_id, - event_type=event_type, - priority=priority, - payload=payload, - timestamp=str(timeutils.utcnow())) - - for driver in _get_drivers(): - try: - driver.notify(context, msg) - except Exception as e: - LOG.exception(_("Problem '%(e)s' attempting to " - "send to notification system. " - "Payload=%(payload)s") - % dict(e=e, payload=payload)) - - -_drivers = None - - -def _get_drivers(): - """Instantiate, cache, and return drivers based on the CONF.""" - global _drivers - if _drivers is None: - _drivers = {} - for notification_driver in CONF.notification_driver: - add_driver(notification_driver) - - return _drivers.values() - - -def add_driver(notification_driver): - """Add a notification driver at runtime.""" - # Make sure the driver list is initialized. - _get_drivers() - if isinstance(notification_driver, basestring): - # Load and add - try: - driver = importutils.import_module(notification_driver) - _drivers[notification_driver] = driver - except ImportError: - LOG.exception(_("Failed to load notifier %s. " - "These notifications will not be sent.") % - notification_driver) - else: - # Driver is already loaded; just add the object. - _drivers[notification_driver] = notification_driver - - -def _reset_drivers(): - """Used by unit tests to reset the drivers.""" - global _drivers - _drivers = None diff --git a/billingstack/openstack/common/notifier/log_notifier.py b/billingstack/openstack/common/notifier/log_notifier.py deleted file mode 100644 index cbf5734..0000000 --- a/billingstack/openstack/common/notifier/log_notifier.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from oslo.config import cfg - -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import log as logging - - -CONF = cfg.CONF - - -def notify(_context, message): - """Notifies the recipient of the desired event given the model. - Log notifications using openstack's default logging system""" - - priority = message.get('priority', - CONF.default_notification_level) - priority = priority.lower() - logger = logging.getLogger( - 'billingstack.openstack.common.notification.%s' % - message['event_type']) - getattr(logger, priority)(jsonutils.dumps(message)) diff --git a/billingstack/openstack/common/notifier/no_op_notifier.py b/billingstack/openstack/common/notifier/no_op_notifier.py deleted file mode 100644 index ee1ddbd..0000000 --- a/billingstack/openstack/common/notifier/no_op_notifier.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -def notify(_context, message): - """Notifies the recipient of the desired event given the model""" - pass diff --git a/billingstack/openstack/common/notifier/rabbit_notifier.py b/billingstack/openstack/common/notifier/rabbit_notifier.py deleted file mode 100644 index 1d43922..0000000 --- a/billingstack/openstack/common/notifier/rabbit_notifier.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2012 Red Hat, Inc. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.notifier import rpc_notifier - -LOG = logging.getLogger(__name__) - - -def notify(context, message): - """Deprecated in Grizzly. Please use rpc_notifier instead.""" - - LOG.deprecated(_("The rabbit_notifier is now deprecated." - " Please use rpc_notifier instead.")) - rpc_notifier.notify(context, message) diff --git a/billingstack/openstack/common/notifier/rpc_notifier.py b/billingstack/openstack/common/notifier/rpc_notifier.py deleted file mode 100644 index fd96184..0000000 --- a/billingstack/openstack/common/notifier/rpc_notifier.py +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from oslo.config import cfg - -from billingstack.openstack.common import context as req_context -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc - -LOG = logging.getLogger(__name__) - -notification_topic_opt = cfg.ListOpt( - 'notification_topics', default=['notifications', ], - help='AMQP topic used for openstack notifications') - -CONF = cfg.CONF -CONF.register_opt(notification_topic_opt) - - -def notify(context, message): - """Sends a notification via RPC""" - if not context: - context = req_context.get_admin_context() - priority = message.get('priority', - CONF.default_notification_level) - priority = priority.lower() - for topic in CONF.notification_topics: - topic = '%s.%s' % (topic, priority) - try: - rpc.notify(context, topic, message) - except Exception: - LOG.exception(_("Could not send notification to %(topic)s. " - "Payload=%(message)s"), locals()) diff --git a/billingstack/openstack/common/notifier/rpc_notifier2.py b/billingstack/openstack/common/notifier/rpc_notifier2.py deleted file mode 100644 index a959f74..0000000 --- a/billingstack/openstack/common/notifier/rpc_notifier2.py +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -'''messaging based notification driver, with message envelopes''' - -from oslo.config import cfg - -from billingstack.openstack.common import context as req_context -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc - -LOG = logging.getLogger(__name__) - -notification_topic_opt = cfg.ListOpt( - 'topics', default=['notifications', ], - help='AMQP topic(s) used for openstack notifications') - -opt_group = cfg.OptGroup(name='rpc_notifier2', - title='Options for rpc_notifier2') - -CONF = cfg.CONF -CONF.register_group(opt_group) -CONF.register_opt(notification_topic_opt, opt_group) - - -def notify(context, message): - """Sends a notification via RPC""" - if not context: - context = req_context.get_admin_context() - priority = message.get('priority', - CONF.default_notification_level) - priority = priority.lower() - for topic in CONF.rpc_notifier2.topics: - topic = '%s.%s' % (topic, priority) - try: - rpc.notify(context, topic, message, envelope=True) - except Exception: - LOG.exception(_("Could not send notification to %(topic)s. " - "Payload=%(message)s"), locals()) diff --git a/billingstack/openstack/common/notifier/test_notifier.py b/billingstack/openstack/common/notifier/test_notifier.py deleted file mode 100644 index 5e34880..0000000 --- a/billingstack/openstack/common/notifier/test_notifier.py +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - - -NOTIFICATIONS = [] - - -def notify(_context, message): - """Test notifier, stores notifications in memory for unittests.""" - NOTIFICATIONS.append(message) diff --git a/billingstack/openstack/common/processutils.py b/billingstack/openstack/common/processutils.py deleted file mode 100644 index 899d112..0000000 --- a/billingstack/openstack/common/processutils.py +++ /dev/null @@ -1,135 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -System-level utilities and helper functions. -""" - -import logging -import random -import shlex - -from eventlet.green import subprocess -from eventlet import greenthread - -from billingstack.openstack.common.gettextutils import _ - - -LOG = logging.getLogger(__name__) - - -class UnknownArgumentError(Exception): - def __init__(self, message=None): - super(UnknownArgumentError, self).__init__(message) - - -class ProcessExecutionError(Exception): - def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None, - description=None): - if description is None: - description = "Unexpected error while running command." - if exit_code is None: - exit_code = '-' - message = ("%s\nCommand: %s\nExit code: %s\nStdout: %r\nStderr: %r" - % (description, cmd, exit_code, stdout, stderr)) - super(ProcessExecutionError, self).__init__(message) - - -def execute(*cmd, **kwargs): - """ - Helper method to shell out and execute a command through subprocess with - optional retry. - - :param cmd: Passed to subprocess.Popen. - :type cmd: string - :param process_input: Send to opened process. - :type proces_input: string - :param check_exit_code: Defaults to 0. Will raise - :class:`ProcessExecutionError` - if the command exits without returning this value - as a returncode - :type check_exit_code: int - :param delay_on_retry: True | False. Defaults to True. If set to True, - wait a short amount of time before retrying. - :type delay_on_retry: boolean - :param attempts: How many times to retry cmd. - :type attempts: int - :param run_as_root: True | False. Defaults to False. If set to True, - the command is prefixed by the command specified - in the root_helper kwarg. - :type run_as_root: boolean - :param root_helper: command to prefix all cmd's with - :type root_helper: string - :returns: (stdout, stderr) from process execution - :raises: :class:`UnknownArgumentError` on - receiving unknown arguments - :raises: :class:`ProcessExecutionError` - """ - - process_input = kwargs.pop('process_input', None) - check_exit_code = kwargs.pop('check_exit_code', 0) - delay_on_retry = kwargs.pop('delay_on_retry', True) - attempts = kwargs.pop('attempts', 1) - run_as_root = kwargs.pop('run_as_root', False) - root_helper = kwargs.pop('root_helper', '') - if len(kwargs): - raise UnknownArgumentError(_('Got unknown keyword args ' - 'to utils.execute: %r') % kwargs) - if run_as_root: - cmd = shlex.split(root_helper) + list(cmd) - cmd = map(str, cmd) - - while attempts > 0: - attempts -= 1 - try: - LOG.debug(_('Running cmd (subprocess): %s'), ' '.join(cmd)) - _PIPE = subprocess.PIPE # pylint: disable=E1101 - obj = subprocess.Popen(cmd, - stdin=_PIPE, - stdout=_PIPE, - stderr=_PIPE, - close_fds=True) - result = None - if process_input is not None: - result = obj.communicate(process_input) - else: - result = obj.communicate() - obj.stdin.close() # pylint: disable=E1101 - _returncode = obj.returncode # pylint: disable=E1101 - if _returncode: - LOG.debug(_('Result was %s') % _returncode) - if (isinstance(check_exit_code, int) and - not isinstance(check_exit_code, bool) and - _returncode != check_exit_code): - (stdout, stderr) = result - raise ProcessExecutionError(exit_code=_returncode, - stdout=stdout, - stderr=stderr, - cmd=' '.join(cmd)) - return result - except ProcessExecutionError: - if not attempts: - raise - else: - LOG.debug(_('%r failed. Retrying.'), cmd) - if delay_on_retry: - greenthread.sleep(random.randint(20, 200) / 100.0) - finally: - # NOTE(termie): this appears to be necessary to let the subprocess - # call clean something up in between calls, without - # it two execute calls in a row hangs the second one - greenthread.sleep(0) diff --git a/billingstack/openstack/common/rpc/__init__.py b/billingstack/openstack/common/rpc/__init__.py deleted file mode 100644 index f178214..0000000 --- a/billingstack/openstack/common/rpc/__init__.py +++ /dev/null @@ -1,307 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# Copyright 2011 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -A remote procedure call (rpc) abstraction. - -For some wrappers that add message versioning to rpc, see: - rpc.dispatcher - rpc.proxy -""" - -import inspect -import logging - -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import local - - -LOG = logging.getLogger(__name__) - - -rpc_opts = [ - cfg.StrOpt('rpc_backend', - default='%s.impl_kombu' % __package__, - help="The messaging module to use, defaults to kombu."), - cfg.IntOpt('rpc_thread_pool_size', - default=64, - help='Size of RPC thread pool'), - cfg.IntOpt('rpc_conn_pool_size', - default=30, - help='Size of RPC connection pool'), - cfg.IntOpt('rpc_response_timeout', - default=60, - help='Seconds to wait for a response from call or multicall'), - cfg.IntOpt('rpc_cast_timeout', - default=30, - help='Seconds to wait before a cast expires (TTL). ' - 'Only supported by impl_zmq.'), - cfg.ListOpt('allowed_rpc_exception_modules', - default=['billingstack.openstack.common.exception', - 'nova.exception', - 'cinder.exception', - 'exceptions', - ], - help='Modules of exceptions that are permitted to be recreated' - 'upon receiving exception data from an rpc call.'), - cfg.BoolOpt('fake_rabbit', - default=False, - help='If passed, use a fake RabbitMQ provider'), - cfg.StrOpt('control_exchange', - default='openstack', - help='AMQP exchange to connect to if using RabbitMQ or Qpid'), -] - -CONF = cfg.CONF -CONF.register_opts(rpc_opts) - - -def set_defaults(control_exchange): - cfg.set_defaults(rpc_opts, - control_exchange=control_exchange) - - -def create_connection(new=True): - """Create a connection to the message bus used for rpc. - - For some example usage of creating a connection and some consumers on that - connection, see nova.service. - - :param new: Whether or not to create a new connection. A new connection - will be created by default. If new is False, the - implementation is free to return an existing connection from a - pool. - - :returns: An instance of openstack.common.rpc.common.Connection - """ - return _get_impl().create_connection(CONF, new=new) - - -def _check_for_lock(): - if not CONF.debug: - return None - - if ((hasattr(local.strong_store, 'locks_held') - and local.strong_store.locks_held)): - stack = ' :: '.join([frame[3] for frame in inspect.stack()]) - LOG.warn(_('A RPC is being made while holding a lock. The locks ' - 'currently held are %(locks)s. This is probably a bug. ' - 'Please report it. Include the following: [%(stack)s].'), - {'locks': local.strong_store.locks_held, - 'stack': stack}) - return True - - return False - - -def call(context, topic, msg, timeout=None, check_for_lock=False): - """Invoke a remote method that returns something. - - :param context: Information that identifies the user that has made this - request. - :param topic: The topic to send the rpc message to. This correlates to the - topic argument of - openstack.common.rpc.common.Connection.create_consumer() - and only applies when the consumer was created with - fanout=False. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - :param timeout: int, number of seconds to use for a response timeout. - If set, this overrides the rpc_response_timeout option. - :param check_for_lock: if True, a warning is emitted if a RPC call is made - with a lock held. - - :returns: A dict from the remote method. - - :raises: openstack.common.rpc.common.Timeout if a complete response - is not received before the timeout is reached. - """ - if check_for_lock: - _check_for_lock() - return _get_impl().call(CONF, context, topic, msg, timeout) - - -def cast(context, topic, msg): - """Invoke a remote method that does not return anything. - - :param context: Information that identifies the user that has made this - request. - :param topic: The topic to send the rpc message to. This correlates to the - topic argument of - openstack.common.rpc.common.Connection.create_consumer() - and only applies when the consumer was created with - fanout=False. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - - :returns: None - """ - return _get_impl().cast(CONF, context, topic, msg) - - -def fanout_cast(context, topic, msg): - """Broadcast a remote method invocation with no return. - - This method will get invoked on all consumers that were set up with this - topic name and fanout=True. - - :param context: Information that identifies the user that has made this - request. - :param topic: The topic to send the rpc message to. This correlates to the - topic argument of - openstack.common.rpc.common.Connection.create_consumer() - and only applies when the consumer was created with - fanout=True. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - - :returns: None - """ - return _get_impl().fanout_cast(CONF, context, topic, msg) - - -def multicall(context, topic, msg, timeout=None, check_for_lock=False): - """Invoke a remote method and get back an iterator. - - In this case, the remote method will be returning multiple values in - separate messages, so the return values can be processed as the come in via - an iterator. - - :param context: Information that identifies the user that has made this - request. - :param topic: The topic to send the rpc message to. This correlates to the - topic argument of - openstack.common.rpc.common.Connection.create_consumer() - and only applies when the consumer was created with - fanout=False. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - :param timeout: int, number of seconds to use for a response timeout. - If set, this overrides the rpc_response_timeout option. - :param check_for_lock: if True, a warning is emitted if a RPC call is made - with a lock held. - - :returns: An iterator. The iterator will yield a tuple (N, X) where N is - an index that starts at 0 and increases by one for each value - returned and X is the Nth value that was returned by the remote - method. - - :raises: openstack.common.rpc.common.Timeout if a complete response - is not received before the timeout is reached. - """ - if check_for_lock: - _check_for_lock() - return _get_impl().multicall(CONF, context, topic, msg, timeout) - - -def notify(context, topic, msg, envelope=False): - """Send notification event. - - :param context: Information that identifies the user that has made this - request. - :param topic: The topic to send the notification to. - :param msg: This is a dict of content of event. - :param envelope: Set to True to enable message envelope for notifications. - - :returns: None - """ - return _get_impl().notify(cfg.CONF, context, topic, msg, envelope) - - -def cleanup(): - """Clean up resoruces in use by implementation. - - Clean up any resources that have been allocated by the RPC implementation. - This is typically open connections to a messaging service. This function - would get called before an application using this API exits to allow - connections to get torn down cleanly. - - :returns: None - """ - return _get_impl().cleanup() - - -def cast_to_server(context, server_params, topic, msg): - """Invoke a remote method that does not return anything. - - :param context: Information that identifies the user that has made this - request. - :param server_params: Connection information - :param topic: The topic to send the notification to. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - - :returns: None - """ - return _get_impl().cast_to_server(CONF, context, server_params, topic, - msg) - - -def fanout_cast_to_server(context, server_params, topic, msg): - """Broadcast to a remote method invocation with no return. - - :param context: Information that identifies the user that has made this - request. - :param server_params: Connection information - :param topic: The topic to send the notification to. - :param msg: This is a dict in the form { "method" : "method_to_invoke", - "args" : dict_of_kwargs } - - :returns: None - """ - return _get_impl().fanout_cast_to_server(CONF, context, server_params, - topic, msg) - - -def queue_get_for(context, topic, host): - """Get a queue name for a given topic + host. - - This function only works if this naming convention is followed on the - consumer side, as well. For example, in nova, every instance of the - nova-foo service calls create_consumer() for two topics: - - foo - foo. - - Messages sent to the 'foo' topic are distributed to exactly one instance of - the nova-foo service. The services are chosen in a round-robin fashion. - Messages sent to the 'foo.' topic are sent to the nova-foo service on - . - """ - return '%s.%s' % (topic, host) if host else topic - - -_RPCIMPL = None - - -def _get_impl(): - """Delay import of rpc_backend until configuration is loaded.""" - global _RPCIMPL - if _RPCIMPL is None: - try: - _RPCIMPL = importutils.import_module(CONF.rpc_backend) - except ImportError: - # For backwards compatibility with older nova config. - impl = CONF.rpc_backend.replace('nova.rpc', - 'nova.openstack.common.rpc') - _RPCIMPL = importutils.import_module(impl) - return _RPCIMPL diff --git a/billingstack/openstack/common/rpc/amqp.py b/billingstack/openstack/common/rpc/amqp.py deleted file mode 100644 index 8dd6f7f..0000000 --- a/billingstack/openstack/common/rpc/amqp.py +++ /dev/null @@ -1,676 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# Copyright 2011 - 2012, Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Shared code between AMQP based openstack.common.rpc implementations. - -The code in this module is shared between the rpc implemenations based on AMQP. -Specifically, this includes impl_kombu and impl_qpid. impl_carrot also uses -AMQP, but is deprecated and predates this code. -""" - -import collections -import inspect -import sys -import uuid - -from eventlet import greenpool -from eventlet import pools -from eventlet import queue -from eventlet import semaphore -# TODO(pekowsk): Remove import cfg and below comment in Havana. -# This import should no longer be needed when the amqp_rpc_single_reply_queue -# option is removed. -from oslo.config import cfg - -from billingstack.openstack.common import excutils -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import local -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.rpc import common as rpc_common - - -# TODO(pekowski): Remove this option in Havana. -amqp_opts = [ - cfg.BoolOpt('amqp_rpc_single_reply_queue', - default=False, - help='Enable a fast single reply queue if using AMQP based ' - 'RPC like RabbitMQ or Qpid.'), -] - -cfg.CONF.register_opts(amqp_opts) - -UNIQUE_ID = '_unique_id' -LOG = logging.getLogger(__name__) - - -class Pool(pools.Pool): - """Class that implements a Pool of Connections.""" - def __init__(self, conf, connection_cls, *args, **kwargs): - self.connection_cls = connection_cls - self.conf = conf - kwargs.setdefault("max_size", self.conf.rpc_conn_pool_size) - kwargs.setdefault("order_as_stack", True) - super(Pool, self).__init__(*args, **kwargs) - self.reply_proxy = None - - # TODO(comstud): Timeout connections not used in a while - def create(self): - LOG.debug(_('Pool creating new connection')) - return self.connection_cls(self.conf) - - def empty(self): - while self.free_items: - self.get().close() - # Force a new connection pool to be created. - # Note that this was added due to failing unit test cases. The issue - # is the above "while loop" gets all the cached connections from the - # pool and closes them, but never returns them to the pool, a pool - # leak. The unit tests hang waiting for an item to be returned to the - # pool. The unit tests get here via the teatDown() method. In the run - # time code, it gets here via cleanup() and only appears in service.py - # just before doing a sys.exit(), so cleanup() only happens once and - # the leakage is not a problem. - self.connection_cls.pool = None - - -_pool_create_sem = semaphore.Semaphore() - - -def get_connection_pool(conf, connection_cls): - with _pool_create_sem: - # Make sure only one thread tries to create the connection pool. - if not connection_cls.pool: - connection_cls.pool = Pool(conf, connection_cls) - return connection_cls.pool - - -class ConnectionContext(rpc_common.Connection): - """The class that is actually returned to the caller of - create_connection(). This is essentially a wrapper around - Connection that supports 'with'. It can also return a new - Connection, or one from a pool. The function will also catch - when an instance of this class is to be deleted. With that - we can return Connections to the pool on exceptions and so - forth without making the caller be responsible for catching - them. If possible the function makes sure to return a - connection to the pool. - """ - - def __init__(self, conf, connection_pool, pooled=True, server_params=None): - """Create a new connection, or get one from the pool""" - self.connection = None - self.conf = conf - self.connection_pool = connection_pool - if pooled: - self.connection = connection_pool.get() - else: - self.connection = connection_pool.connection_cls( - conf, - server_params=server_params) - self.pooled = pooled - - def __enter__(self): - """When with ConnectionContext() is used, return self""" - return self - - def _done(self): - """If the connection came from a pool, clean it up and put it back. - If it did not come from a pool, close it. - """ - if self.connection: - if self.pooled: - # Reset the connection so it's ready for the next caller - # to grab from the pool - self.connection.reset() - self.connection_pool.put(self.connection) - else: - try: - self.connection.close() - except Exception: - pass - self.connection = None - - def __exit__(self, exc_type, exc_value, tb): - """End of 'with' statement. We're done here.""" - self._done() - - def __del__(self): - """Caller is done with this connection. Make sure we cleaned up.""" - self._done() - - def close(self): - """Caller is done with this connection.""" - self._done() - - def create_consumer(self, topic, proxy, fanout=False): - self.connection.create_consumer(topic, proxy, fanout) - - def create_worker(self, topic, proxy, pool_name): - self.connection.create_worker(topic, proxy, pool_name) - - def join_consumer_pool(self, callback, pool_name, topic, exchange_name): - self.connection.join_consumer_pool(callback, - pool_name, - topic, - exchange_name) - - def consume_in_thread(self): - self.connection.consume_in_thread() - - def consume_in_thread_group(self, thread_group): - self.connection.consume_in_thread_group(thread_group) - - def __getattr__(self, key): - """Proxy all other calls to the Connection instance""" - if self.connection: - return getattr(self.connection, key) - else: - raise rpc_common.InvalidRPCConnectionReuse() - - -class ReplyProxy(ConnectionContext): - """ Connection class for RPC replies / callbacks """ - def __init__(self, conf, connection_pool): - self._call_waiters = {} - self._num_call_waiters = 0 - self._num_call_waiters_wrn_threshhold = 10 - self._reply_q = 'reply_' + uuid.uuid4().hex - super(ReplyProxy, self).__init__(conf, connection_pool, pooled=False) - self.declare_direct_consumer(self._reply_q, self._process_data) - self.consume_in_thread() - - def _process_data(self, message_data): - msg_id = message_data.pop('_msg_id', None) - waiter = self._call_waiters.get(msg_id) - if not waiter: - LOG.warn(_('no calling threads waiting for msg_id : %s' - ', message : %s') % (msg_id, message_data)) - else: - waiter.put(message_data) - - def add_call_waiter(self, waiter, msg_id): - self._num_call_waiters += 1 - if self._num_call_waiters > self._num_call_waiters_wrn_threshhold: - LOG.warn(_('Number of call waiters is greater than warning ' - 'threshhold: %d. There could be a MulticallProxyWaiter ' - 'leak.') % self._num_call_waiters_wrn_threshhold) - self._num_call_waiters_wrn_threshhold *= 2 - self._call_waiters[msg_id] = waiter - - def del_call_waiter(self, msg_id): - self._num_call_waiters -= 1 - del self._call_waiters[msg_id] - - def get_reply_q(self): - return self._reply_q - - -def msg_reply(conf, msg_id, reply_q, connection_pool, reply=None, - failure=None, ending=False, log_failure=True): - """Sends a reply or an error on the channel signified by msg_id. - - Failure should be a sys.exc_info() tuple. - - """ - with ConnectionContext(conf, connection_pool) as conn: - if failure: - failure = rpc_common.serialize_remote_exception(failure, - log_failure) - - try: - msg = {'result': reply, 'failure': failure} - except TypeError: - msg = {'result': dict((k, repr(v)) - for k, v in reply.__dict__.iteritems()), - 'failure': failure} - if ending: - msg['ending'] = True - _add_unique_id(msg) - # If a reply_q exists, add the msg_id to the reply and pass the - # reply_q to direct_send() to use it as the response queue. - # Otherwise use the msg_id for backward compatibilty. - if reply_q: - msg['_msg_id'] = msg_id - conn.direct_send(reply_q, rpc_common.serialize_msg(msg)) - else: - conn.direct_send(msg_id, rpc_common.serialize_msg(msg)) - - -class RpcContext(rpc_common.CommonRpcContext): - """Context that supports replying to a rpc.call""" - def __init__(self, **kwargs): - self.msg_id = kwargs.pop('msg_id', None) - self.reply_q = kwargs.pop('reply_q', None) - self.conf = kwargs.pop('conf') - super(RpcContext, self).__init__(**kwargs) - - def deepcopy(self): - values = self.to_dict() - values['conf'] = self.conf - values['msg_id'] = self.msg_id - values['reply_q'] = self.reply_q - return self.__class__(**values) - - def reply(self, reply=None, failure=None, ending=False, - connection_pool=None, log_failure=True): - if self.msg_id: - msg_reply(self.conf, self.msg_id, self.reply_q, connection_pool, - reply, failure, ending, log_failure) - if ending: - self.msg_id = None - - -def unpack_context(conf, msg): - """Unpack context from msg.""" - context_dict = {} - for key in list(msg.keys()): - # NOTE(vish): Some versions of python don't like unicode keys - # in kwargs. - key = str(key) - if key.startswith('_context_'): - value = msg.pop(key) - context_dict[key[9:]] = value - context_dict['msg_id'] = msg.pop('_msg_id', None) - context_dict['reply_q'] = msg.pop('_reply_q', None) - context_dict['conf'] = conf - ctx = RpcContext.from_dict(context_dict) - rpc_common._safe_log(LOG.debug, _('unpacked context: %s'), ctx.to_dict()) - return ctx - - -def pack_context(msg, context): - """Pack context into msg. - - Values for message keys need to be less than 255 chars, so we pull - context out into a bunch of separate keys. If we want to support - more arguments in rabbit messages, we may want to do the same - for args at some point. - - """ - context_d = dict([('_context_%s' % key, value) - for (key, value) in context.to_dict().iteritems()]) - msg.update(context_d) - - -class _MsgIdCache(object): - """This class checks any duplicate messages.""" - - # NOTE: This value is considered can be a configuration item, but - # it is not necessary to change its value in most cases, - # so let this value as static for now. - DUP_MSG_CHECK_SIZE = 16 - - def __init__(self, **kwargs): - self.prev_msgids = collections.deque([], - maxlen=self.DUP_MSG_CHECK_SIZE) - - def check_duplicate_message(self, message_data): - """AMQP consumers may read same message twice when exceptions occur - before ack is returned. This method prevents doing it. - """ - if UNIQUE_ID in message_data: - msg_id = message_data[UNIQUE_ID] - if msg_id not in self.prev_msgids: - self.prev_msgids.append(msg_id) - else: - raise rpc_common.DuplicateMessageError(msg_id=msg_id) - - -def _add_unique_id(msg): - """Add unique_id for checking duplicate messages.""" - unique_id = uuid.uuid4().hex - msg.update({UNIQUE_ID: unique_id}) - LOG.debug(_('UNIQUE_ID is %s.') % (unique_id)) - - -class _ThreadPoolWithWait(object): - """Base class for a delayed invocation manager used by - the Connection class to start up green threads - to handle incoming messages. - """ - - def __init__(self, conf, connection_pool): - self.pool = greenpool.GreenPool(conf.rpc_thread_pool_size) - self.connection_pool = connection_pool - self.conf = conf - - def wait(self): - """Wait for all callback threads to exit.""" - self.pool.waitall() - - -class CallbackWrapper(_ThreadPoolWithWait): - """Wraps a straight callback to allow it to be invoked in a green - thread. - """ - - def __init__(self, conf, callback, connection_pool): - """ - :param conf: cfg.CONF instance - :param callback: a callable (probably a function) - :param connection_pool: connection pool as returned by - get_connection_pool() - """ - super(CallbackWrapper, self).__init__( - conf=conf, - connection_pool=connection_pool, - ) - self.callback = callback - - def __call__(self, message_data): - self.pool.spawn_n(self.callback, message_data) - - -class ProxyCallback(_ThreadPoolWithWait): - """Calls methods on a proxy object based on method and args.""" - - def __init__(self, conf, proxy, connection_pool): - super(ProxyCallback, self).__init__( - conf=conf, - connection_pool=connection_pool, - ) - self.proxy = proxy - self.msg_id_cache = _MsgIdCache() - - def __call__(self, message_data): - """Consumer callback to call a method on a proxy object. - - Parses the message for validity and fires off a thread to call the - proxy object method. - - Message data should be a dictionary with two keys: - method: string representing the method to call - args: dictionary of arg: value - - Example: {'method': 'echo', 'args': {'value': 42}} - - """ - # It is important to clear the context here, because at this point - # the previous context is stored in local.store.context - if hasattr(local.store, 'context'): - del local.store.context - rpc_common._safe_log(LOG.debug, _('received %s'), message_data) - self.msg_id_cache.check_duplicate_message(message_data) - ctxt = unpack_context(self.conf, message_data) - method = message_data.get('method') - args = message_data.get('args', {}) - version = message_data.get('version', None) - if not method: - LOG.warn(_('no method for message: %s') % message_data) - ctxt.reply(_('No method for message: %s') % message_data, - connection_pool=self.connection_pool) - return - self.pool.spawn_n(self._process_data, ctxt, version, method, args) - - def _process_data(self, ctxt, version, method, args): - """Process a message in a new thread. - - If the proxy object we have has a dispatch method - (see rpc.dispatcher.RpcDispatcher), pass it the version, - method, and args and let it dispatch as appropriate. If not, use - the old behavior of magically calling the specified method on the - proxy we have here. - """ - ctxt.update_store() - try: - rval = self.proxy.dispatch(ctxt, version, method, **args) - # Check if the result was a generator - if inspect.isgenerator(rval): - for x in rval: - ctxt.reply(x, None, connection_pool=self.connection_pool) - else: - ctxt.reply(rval, None, connection_pool=self.connection_pool) - # This final None tells multicall that it is done. - ctxt.reply(ending=True, connection_pool=self.connection_pool) - except rpc_common.ClientException as e: - LOG.debug(_('Expected exception during message handling (%s)') % - e._exc_info[1]) - ctxt.reply(None, e._exc_info, - connection_pool=self.connection_pool, - log_failure=False) - except Exception: - LOG.exception(_('Exception during message handling')) - ctxt.reply(None, sys.exc_info(), - connection_pool=self.connection_pool) - - -class MulticallProxyWaiter(object): - def __init__(self, conf, msg_id, timeout, connection_pool): - self._msg_id = msg_id - self._timeout = timeout or conf.rpc_response_timeout - self._reply_proxy = connection_pool.reply_proxy - self._done = False - self._got_ending = False - self._conf = conf - self._dataqueue = queue.LightQueue() - # Add this caller to the reply proxy's call_waiters - self._reply_proxy.add_call_waiter(self, self._msg_id) - self.msg_id_cache = _MsgIdCache() - - def put(self, data): - self._dataqueue.put(data) - - def done(self): - if self._done: - return - self._done = True - # Remove this caller from reply proxy's call_waiters - self._reply_proxy.del_call_waiter(self._msg_id) - - def _process_data(self, data): - result = None - self.msg_id_cache.check_duplicate_message(data) - if data['failure']: - failure = data['failure'] - result = rpc_common.deserialize_remote_exception(self._conf, - failure) - elif data.get('ending', False): - self._got_ending = True - else: - result = data['result'] - return result - - def __iter__(self): - """Return a result until we get a reply with an 'ending" flag""" - if self._done: - raise StopIteration - while True: - try: - data = self._dataqueue.get(timeout=self._timeout) - result = self._process_data(data) - except queue.Empty: - LOG.exception(_('Timed out waiting for RPC response.')) - self.done() - raise rpc_common.Timeout() - except Exception: - with excutils.save_and_reraise_exception(): - self.done() - if self._got_ending: - self.done() - raise StopIteration - if isinstance(result, Exception): - self.done() - raise result - yield result - - -#TODO(pekowski): Remove MulticallWaiter() in Havana. -class MulticallWaiter(object): - def __init__(self, conf, connection, timeout): - self._connection = connection - self._iterator = connection.iterconsume(timeout=timeout or - conf.rpc_response_timeout) - self._result = None - self._done = False - self._got_ending = False - self._conf = conf - self.msg_id_cache = _MsgIdCache() - - def done(self): - if self._done: - return - self._done = True - self._iterator.close() - self._iterator = None - self._connection.close() - - def __call__(self, data): - """The consume() callback will call this. Store the result.""" - self.msg_id_cache.check_duplicate_message(data) - if data['failure']: - failure = data['failure'] - self._result = rpc_common.deserialize_remote_exception(self._conf, - failure) - - elif data.get('ending', False): - self._got_ending = True - else: - self._result = data['result'] - - def __iter__(self): - """Return a result until we get a 'None' response from consumer""" - if self._done: - raise StopIteration - while True: - try: - self._iterator.next() - except Exception: - with excutils.save_and_reraise_exception(): - self.done() - if self._got_ending: - self.done() - raise StopIteration - result = self._result - if isinstance(result, Exception): - self.done() - raise result - yield result - - -def create_connection(conf, new, connection_pool): - """Create a connection""" - return ConnectionContext(conf, connection_pool, pooled=not new) - - -_reply_proxy_create_sem = semaphore.Semaphore() - - -def multicall(conf, context, topic, msg, timeout, connection_pool): - """Make a call that returns multiple times.""" - # TODO(pekowski): Remove all these comments in Havana. - # For amqp_rpc_single_reply_queue = False, - # Can't use 'with' for multicall, as it returns an iterator - # that will continue to use the connection. When it's done, - # connection.close() will get called which will put it back into - # the pool - # For amqp_rpc_single_reply_queue = True, - # The 'with' statement is mandatory for closing the connection - LOG.debug(_('Making synchronous call on %s ...'), topic) - msg_id = uuid.uuid4().hex - msg.update({'_msg_id': msg_id}) - LOG.debug(_('MSG_ID is %s') % (msg_id)) - _add_unique_id(msg) - pack_context(msg, context) - - # TODO(pekowski): Remove this flag and the code under the if clause - # in Havana. - if not conf.amqp_rpc_single_reply_queue: - conn = ConnectionContext(conf, connection_pool) - wait_msg = MulticallWaiter(conf, conn, timeout) - conn.declare_direct_consumer(msg_id, wait_msg) - conn.topic_send(topic, rpc_common.serialize_msg(msg), timeout) - else: - with _reply_proxy_create_sem: - if not connection_pool.reply_proxy: - connection_pool.reply_proxy = ReplyProxy(conf, connection_pool) - msg.update({'_reply_q': connection_pool.reply_proxy.get_reply_q()}) - wait_msg = MulticallProxyWaiter(conf, msg_id, timeout, connection_pool) - with ConnectionContext(conf, connection_pool) as conn: - conn.topic_send(topic, rpc_common.serialize_msg(msg), timeout) - return wait_msg - - -def call(conf, context, topic, msg, timeout, connection_pool): - """Sends a message on a topic and wait for a response.""" - rv = multicall(conf, context, topic, msg, timeout, connection_pool) - # NOTE(vish): return the last result from the multicall - rv = list(rv) - if not rv: - return - return rv[-1] - - -def cast(conf, context, topic, msg, connection_pool): - """Sends a message on a topic without waiting for a response.""" - LOG.debug(_('Making asynchronous cast on %s...'), topic) - _add_unique_id(msg) - pack_context(msg, context) - with ConnectionContext(conf, connection_pool) as conn: - conn.topic_send(topic, rpc_common.serialize_msg(msg)) - - -def fanout_cast(conf, context, topic, msg, connection_pool): - """Sends a message on a fanout exchange without waiting for a response.""" - LOG.debug(_('Making asynchronous fanout cast...')) - _add_unique_id(msg) - pack_context(msg, context) - with ConnectionContext(conf, connection_pool) as conn: - conn.fanout_send(topic, rpc_common.serialize_msg(msg)) - - -def cast_to_server(conf, context, server_params, topic, msg, connection_pool): - """Sends a message on a topic to a specific server.""" - _add_unique_id(msg) - pack_context(msg, context) - with ConnectionContext(conf, connection_pool, pooled=False, - server_params=server_params) as conn: - conn.topic_send(topic, rpc_common.serialize_msg(msg)) - - -def fanout_cast_to_server(conf, context, server_params, topic, msg, - connection_pool): - """Sends a message on a fanout exchange to a specific server.""" - _add_unique_id(msg) - pack_context(msg, context) - with ConnectionContext(conf, connection_pool, pooled=False, - server_params=server_params) as conn: - conn.fanout_send(topic, rpc_common.serialize_msg(msg)) - - -def notify(conf, context, topic, msg, connection_pool, envelope): - """Sends a notification event on a topic.""" - LOG.debug(_('Sending %(event_type)s on %(topic)s'), - dict(event_type=msg.get('event_type'), - topic=topic)) - _add_unique_id(msg) - pack_context(msg, context) - with ConnectionContext(conf, connection_pool) as conn: - if envelope: - msg = rpc_common.serialize_msg(msg, force_envelope=True) - conn.notify_send(topic, msg) - - -def cleanup(connection_pool): - if connection_pool: - connection_pool.empty() - - -def get_control_exchange(conf): - return conf.control_exchange diff --git a/billingstack/openstack/common/rpc/common.py b/billingstack/openstack/common/rpc/common.py deleted file mode 100644 index f15d641..0000000 --- a/billingstack/openstack/common/rpc/common.py +++ /dev/null @@ -1,512 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# Copyright 2011 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import copy -import sys -import traceback - -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import local -from billingstack.openstack.common import log as logging - - -CONF = cfg.CONF -LOG = logging.getLogger(__name__) - - -'''RPC Envelope Version. - -This version number applies to the top level structure of messages sent out. -It does *not* apply to the message payload, which must be versioned -independently. For example, when using rpc APIs, a version number is applied -for changes to the API being exposed over rpc. This version number is handled -in the rpc proxy and dispatcher modules. - -This version number applies to the message envelope that is used in the -serialization done inside the rpc layer. See serialize_msg() and -deserialize_msg(). - -The current message format (version 2.0) is very simple. It is: - - { - 'oslo.version': , - 'oslo.message': - } - -Message format version '1.0' is just considered to be the messages we sent -without a message envelope. - -So, the current message envelope just includes the envelope version. It may -eventually contain additional information, such as a signature for the message -payload. - -We will JSON encode the application message payload. The message envelope, -which includes the JSON encoded application message body, will be passed down -to the messaging libraries as a dict. -''' -_RPC_ENVELOPE_VERSION = '2.0' - -_VERSION_KEY = 'oslo.version' -_MESSAGE_KEY = 'oslo.message' - - -# TODO(russellb) Turn this on after Grizzly. -_SEND_RPC_ENVELOPE = False - - -class RPCException(Exception): - message = _("An unknown RPC related exception occurred.") - - def __init__(self, message=None, **kwargs): - self.kwargs = kwargs - - if not message: - try: - message = self.message % kwargs - - except Exception: - # kwargs doesn't match a variable in the message - # log the issue and the kwargs - LOG.exception(_('Exception in string format operation')) - for name, value in kwargs.iteritems(): - LOG.error("%s: %s" % (name, value)) - # at least get the core message out if something happened - message = self.message - - super(RPCException, self).__init__(message) - - -class RemoteError(RPCException): - """Signifies that a remote class has raised an exception. - - Contains a string representation of the type of the original exception, - the value of the original exception, and the traceback. These are - sent to the parent as a joined string so printing the exception - contains all of the relevant info. - - """ - message = _("Remote error: %(exc_type)s %(value)s\n%(traceback)s.") - - def __init__(self, exc_type=None, value=None, traceback=None): - self.exc_type = exc_type - self.value = value - self.traceback = traceback - super(RemoteError, self).__init__(exc_type=exc_type, - value=value, - traceback=traceback) - - -class Timeout(RPCException): - """Signifies that a timeout has occurred. - - This exception is raised if the rpc_response_timeout is reached while - waiting for a response from the remote side. - """ - message = _("Timeout while waiting on RPC response.") - - -class DuplicateMessageError(RPCException): - message = _("Found duplicate message(%(msg_id)s). Skipping it.") - - -class InvalidRPCConnectionReuse(RPCException): - message = _("Invalid reuse of an RPC connection.") - - -class UnsupportedRpcVersion(RPCException): - message = _("Specified RPC version, %(version)s, not supported by " - "this endpoint.") - - -class UnsupportedRpcEnvelopeVersion(RPCException): - message = _("Specified RPC envelope version, %(version)s, " - "not supported by this endpoint.") - - -class Connection(object): - """A connection, returned by rpc.create_connection(). - - This class represents a connection to the message bus used for rpc. - An instance of this class should never be created by users of the rpc API. - Use rpc.create_connection() instead. - """ - def close(self): - """Close the connection. - - This method must be called when the connection will no longer be used. - It will ensure that any resources associated with the connection, such - as a network connection, and cleaned up. - """ - raise NotImplementedError() - - def create_consumer(self, topic, proxy, fanout=False): - """Create a consumer on this connection. - - A consumer is associated with a message queue on the backend message - bus. The consumer will read messages from the queue, unpack them, and - dispatch them to the proxy object. The contents of the message pulled - off of the queue will determine which method gets called on the proxy - object. - - :param topic: This is a name associated with what to consume from. - Multiple instances of a service may consume from the same - topic. For example, all instances of nova-compute consume - from a queue called "compute". In that case, the - messages will get distributed amongst the consumers in a - round-robin fashion if fanout=False. If fanout=True, - every consumer associated with this topic will get a - copy of every message. - :param proxy: The object that will handle all incoming messages. - :param fanout: Whether or not this is a fanout topic. See the - documentation for the topic parameter for some - additional comments on this. - """ - raise NotImplementedError() - - def create_worker(self, topic, proxy, pool_name): - """Create a worker on this connection. - - A worker is like a regular consumer of messages directed to a - topic, except that it is part of a set of such consumers (the - "pool") which may run in parallel. Every pool of workers will - receive a given message, but only one worker in the pool will - be asked to process it. Load is distributed across the members - of the pool in round-robin fashion. - - :param topic: This is a name associated with what to consume from. - Multiple instances of a service may consume from the same - topic. - :param proxy: The object that will handle all incoming messages. - :param pool_name: String containing the name of the pool of workers - """ - raise NotImplementedError() - - def join_consumer_pool(self, callback, pool_name, topic, exchange_name): - """Register as a member of a group of consumers for a given topic from - the specified exchange. - - Exactly one member of a given pool will receive each message. - - A message will be delivered to multiple pools, if more than - one is created. - - :param callback: Callable to be invoked for each message. - :type callback: callable accepting one argument - :param pool_name: The name of the consumer pool. - :type pool_name: str - :param topic: The routing topic for desired messages. - :type topic: str - :param exchange_name: The name of the message exchange where - the client should attach. Defaults to - the configured exchange. - :type exchange_name: str - """ - raise NotImplementedError() - - def consume_in_thread(self): - """Spawn a thread to handle incoming messages. - - Spawn a thread that will be responsible for handling all incoming - messages for consumers that were set up on this connection. - - Message dispatching inside of this is expected to be implemented in a - non-blocking manner. An example implementation would be having this - thread pull messages in for all of the consumers, but utilize a thread - pool for dispatching the messages to the proxy objects. - """ - raise NotImplementedError() - - def consume_in_thread_group(self, thread_group): - """ - Spawn a thread to handle incoming messages in the supplied - ThreadGroup. - - Spawn a thread that will be responsible for handling all incoming - messages for consumers that were set up on this connection. - - Message dispatching inside of this is expected to be implemented in a - non-blocking manner. An example implementation would be having this - thread pull messages in for all of the consumers, but utilize a thread - pool for dispatching the messages to the proxy objects. - """ - raise NotImplementedError() - - -def _safe_log(log_func, msg, msg_data): - """Sanitizes the msg_data field before logging.""" - SANITIZE = {'set_admin_password': [('args', 'new_pass')], - 'run_instance': [('args', 'admin_password')], - 'route_message': [('args', 'message', 'args', 'method_info', - 'method_kwargs', 'password'), - ('args', 'message', 'args', 'method_info', - 'method_kwargs', 'admin_password')]} - - has_method = 'method' in msg_data and msg_data['method'] in SANITIZE - has_context_token = '_context_auth_token' in msg_data - has_token = 'auth_token' in msg_data - - if not any([has_method, has_context_token, has_token]): - return log_func(msg, msg_data) - - msg_data = copy.deepcopy(msg_data) - - if has_method: - for arg in SANITIZE.get(msg_data['method'], []): - try: - d = msg_data - for elem in arg[:-1]: - d = d[elem] - d[arg[-1]] = '' - except KeyError, e: - LOG.info(_('Failed to sanitize %(item)s. Key error %(err)s'), - {'item': arg, - 'err': e}) - - if has_context_token: - msg_data['_context_auth_token'] = '' - - if has_token: - msg_data['auth_token'] = '' - - return log_func(msg, msg_data) - - -def serialize_remote_exception(failure_info, log_failure=True): - """Prepares exception data to be sent over rpc. - - Failure_info should be a sys.exc_info() tuple. - - """ - tb = traceback.format_exception(*failure_info) - failure = failure_info[1] - if log_failure: - LOG.error(_("Returning exception %s to caller"), unicode(failure)) - LOG.error(tb) - - kwargs = {} - if hasattr(failure, 'kwargs'): - kwargs = failure.kwargs - - data = { - 'class': str(failure.__class__.__name__), - 'module': str(failure.__class__.__module__), - 'message': unicode(failure), - 'tb': tb, - 'args': failure.args, - 'kwargs': kwargs - } - - json_data = jsonutils.dumps(data) - - return json_data - - -def deserialize_remote_exception(conf, data): - failure = jsonutils.loads(str(data)) - - trace = failure.get('tb', []) - message = failure.get('message', "") + "\n" + "\n".join(trace) - name = failure.get('class') - module = failure.get('module') - - # NOTE(ameade): We DO NOT want to allow just any module to be imported, in - # order to prevent arbitrary code execution. - if module not in conf.allowed_rpc_exception_modules: - return RemoteError(name, failure.get('message'), trace) - - try: - mod = importutils.import_module(module) - klass = getattr(mod, name) - if not issubclass(klass, Exception): - raise TypeError("Can only deserialize Exceptions") - - failure = klass(**failure.get('kwargs', {})) - except (AttributeError, TypeError, ImportError): - return RemoteError(name, failure.get('message'), trace) - - ex_type = type(failure) - str_override = lambda self: message - new_ex_type = type(ex_type.__name__ + "_Remote", (ex_type,), - {'__str__': str_override, '__unicode__': str_override}) - try: - # NOTE(ameade): Dynamically create a new exception type and swap it in - # as the new type for the exception. This only works on user defined - # Exceptions and not core python exceptions. This is important because - # we cannot necessarily change an exception message so we must override - # the __str__ method. - failure.__class__ = new_ex_type - except TypeError: - # NOTE(ameade): If a core exception then just add the traceback to the - # first exception argument. - failure.args = (message,) + failure.args[1:] - return failure - - -class CommonRpcContext(object): - def __init__(self, **kwargs): - self.values = kwargs - - def __getattr__(self, key): - try: - return self.values[key] - except KeyError: - raise AttributeError(key) - - def to_dict(self): - return copy.deepcopy(self.values) - - @classmethod - def from_dict(cls, values): - return cls(**values) - - def deepcopy(self): - return self.from_dict(self.to_dict()) - - def update_store(self): - local.store.context = self - - def elevated(self, read_deleted=None, overwrite=False): - """Return a version of this context with admin flag set.""" - # TODO(russellb) This method is a bit of a nova-ism. It makes - # some assumptions about the data in the request context sent - # across rpc, while the rest of this class does not. We could get - # rid of this if we changed the nova code that uses this to - # convert the RpcContext back to its native RequestContext doing - # something like nova.context.RequestContext.from_dict(ctxt.to_dict()) - - context = self.deepcopy() - context.values['is_admin'] = True - - context.values.setdefault('roles', []) - - if 'admin' not in context.values['roles']: - context.values['roles'].append('admin') - - if read_deleted is not None: - context.values['read_deleted'] = read_deleted - - return context - - -class ClientException(Exception): - """This encapsulates some actual exception that is expected to be - hit by an RPC proxy object. Merely instantiating it records the - current exception information, which will be passed back to the - RPC client without exceptional logging.""" - def __init__(self): - self._exc_info = sys.exc_info() - - -def catch_client_exception(exceptions, func, *args, **kwargs): - try: - return func(*args, **kwargs) - except Exception, e: - if type(e) in exceptions: - raise ClientException() - else: - raise - - -def client_exceptions(*exceptions): - """Decorator for manager methods that raise expected exceptions. - Marking a Manager method with this decorator allows the declaration - of expected exceptions that the RPC layer should not consider fatal, - and not log as if they were generated in a real error scenario. Note - that this will cause listed exceptions to be wrapped in a - ClientException, which is used internally by the RPC layer.""" - def outer(func): - def inner(*args, **kwargs): - return catch_client_exception(exceptions, func, *args, **kwargs) - return inner - return outer - - -def version_is_compatible(imp_version, version): - """Determine whether versions are compatible. - - :param imp_version: The version implemented - :param version: The version requested by an incoming message. - """ - version_parts = version.split('.') - imp_version_parts = imp_version.split('.') - if int(version_parts[0]) != int(imp_version_parts[0]): # Major - return False - if int(version_parts[1]) > int(imp_version_parts[1]): # Minor - return False - return True - - -def serialize_msg(raw_msg, force_envelope=False): - if not _SEND_RPC_ENVELOPE and not force_envelope: - return raw_msg - - # NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more - # information about this format. - msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION, - _MESSAGE_KEY: jsonutils.dumps(raw_msg)} - - return msg - - -def deserialize_msg(msg): - # NOTE(russellb): Hang on to your hats, this road is about to - # get a little bumpy. - # - # Robustness Principle: - # "Be strict in what you send, liberal in what you accept." - # - # At this point we have to do a bit of guessing about what it - # is we just received. Here is the set of possibilities: - # - # 1) We received a dict. This could be 2 things: - # - # a) Inspect it to see if it looks like a standard message envelope. - # If so, great! - # - # b) If it doesn't look like a standard message envelope, it could either - # be a notification, or a message from before we added a message - # envelope (referred to as version 1.0). - # Just return the message as-is. - # - # 2) It's any other non-dict type. Just return it and hope for the best. - # This case covers return values from rpc.call() from before message - # envelopes were used. (messages to call a method were always a dict) - - if not isinstance(msg, dict): - # See #2 above. - return msg - - base_envelope_keys = (_VERSION_KEY, _MESSAGE_KEY) - if not all(map(lambda key: key in msg, base_envelope_keys)): - # See #1.b above. - return msg - - # At this point we think we have the message envelope - # format we were expecting. (#1.a above) - - if not version_is_compatible(_RPC_ENVELOPE_VERSION, msg[_VERSION_KEY]): - raise UnsupportedRpcEnvelopeVersion(version=msg[_VERSION_KEY]) - - raw_msg = jsonutils.loads(msg[_MESSAGE_KEY]) - - return raw_msg diff --git a/billingstack/openstack/common/rpc/dispatcher.py b/billingstack/openstack/common/rpc/dispatcher.py deleted file mode 100644 index b22de6a..0000000 --- a/billingstack/openstack/common/rpc/dispatcher.py +++ /dev/null @@ -1,140 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Code for rpc message dispatching. - -Messages that come in have a version number associated with them. RPC API -version numbers are in the form: - - Major.Minor - -For a given message with version X.Y, the receiver must be marked as able to -handle messages of version A.B, where: - - A = X - - B >= Y - -The Major version number would be incremented for an almost completely new API. -The Minor version number would be incremented for backwards compatible changes -to an existing API. A backwards compatible change could be something like -adding a new method, adding an argument to an existing method (but not -requiring it), or changing the type for an existing argument (but still -handling the old type as well). - -The conversion over to a versioned API must be done on both the client side and -server side of the API at the same time. However, as the code stands today, -there can be both versioned and unversioned APIs implemented in the same code -base. - -EXAMPLES -======== - -Nova was the first project to use versioned rpc APIs. Consider the compute rpc -API as an example. The client side is in nova/compute/rpcapi.py and the server -side is in nova/compute/manager.py. - - -Example 1) Adding a new method. -------------------------------- - -Adding a new method is a backwards compatible change. It should be added to -nova/compute/manager.py, and RPC_API_VERSION should be bumped from X.Y to -X.Y+1. On the client side, the new method in nova/compute/rpcapi.py should -have a specific version specified to indicate the minimum API version that must -be implemented for the method to be supported. For example:: - - def get_host_uptime(self, ctxt, host): - topic = _compute_topic(self.topic, ctxt, host, None) - return self.call(ctxt, self.make_msg('get_host_uptime'), topic, - version='1.1') - -In this case, version '1.1' is the first version that supported the -get_host_uptime() method. - - -Example 2) Adding a new parameter. ----------------------------------- - -Adding a new parameter to an rpc method can be made backwards compatible. The -RPC_API_VERSION on the server side (nova/compute/manager.py) should be bumped. -The implementation of the method must not expect the parameter to be present.:: - - def some_remote_method(self, arg1, arg2, newarg=None): - # The code needs to deal with newarg=None for cases - # where an older client sends a message without it. - pass - -On the client side, the same changes should be made as in example 1. The -minimum version that supports the new parameter should be specified. -""" - -from billingstack.openstack.common.rpc import common as rpc_common - - -class RpcDispatcher(object): - """Dispatch rpc messages according to the requested API version. - - This class can be used as the top level 'manager' for a service. It - contains a list of underlying managers that have an API_VERSION attribute. - """ - - def __init__(self, callbacks): - """Initialize the rpc dispatcher. - - :param callbacks: List of proxy objects that are an instance - of a class with rpc methods exposed. Each proxy - object should have an RPC_API_VERSION attribute. - """ - self.callbacks = callbacks - super(RpcDispatcher, self).__init__() - - def dispatch(self, ctxt, version, method, **kwargs): - """Dispatch a message based on a requested version. - - :param ctxt: The request context - :param version: The requested API version from the incoming message - :param method: The method requested to be called by the incoming - message. - :param kwargs: A dict of keyword arguments to be passed to the method. - - :returns: Whatever is returned by the underlying method that gets - called. - """ - if not version: - version = '1.0' - - had_compatible = False - for proxyobj in self.callbacks: - if hasattr(proxyobj, 'RPC_API_VERSION'): - rpc_api_version = proxyobj.RPC_API_VERSION - else: - rpc_api_version = '1.0' - is_compatible = rpc_common.version_is_compatible(rpc_api_version, - version) - - had_compatible = had_compatible or is_compatible - func = getattr(proxyobj, method) - if not func: - continue - if is_compatible: - return func(ctxt, **kwargs) - - if had_compatible: - raise AttributeError("No such RPC function '%s'" % method) - else: - raise rpc_common.UnsupportedRpcVersion(version=version) diff --git a/billingstack/openstack/common/rpc/impl_fake.py b/billingstack/openstack/common/rpc/impl_fake.py deleted file mode 100644 index 044ab3f..0000000 --- a/billingstack/openstack/common/rpc/impl_fake.py +++ /dev/null @@ -1,194 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -"""Fake RPC implementation which calls proxy methods directly with no -queues. Casts will block, but this is very useful for tests. -""" - -import inspect -# NOTE(russellb): We specifically want to use json, not our own jsonutils. -# jsonutils has some extra logic to automatically convert objects to primitive -# types so that they can be serialized. We want to catch all cases where -# non-primitive types make it into this code and treat it as an error. -import json -import time - -import eventlet - -from billingstack.openstack.common.rpc import common as rpc_common - -CONSUMERS = {} - - -class RpcContext(rpc_common.CommonRpcContext): - def __init__(self, **kwargs): - super(RpcContext, self).__init__(**kwargs) - self._response = [] - self._done = False - - def deepcopy(self): - values = self.to_dict() - new_inst = self.__class__(**values) - new_inst._response = self._response - new_inst._done = self._done - return new_inst - - def reply(self, reply=None, failure=None, ending=False): - if ending: - self._done = True - if not self._done: - self._response.append((reply, failure)) - - -class Consumer(object): - def __init__(self, topic, proxy): - self.topic = topic - self.proxy = proxy - - def call(self, context, version, method, args, timeout): - done = eventlet.event.Event() - - def _inner(): - ctxt = RpcContext.from_dict(context.to_dict()) - try: - rval = self.proxy.dispatch(context, version, method, **args) - res = [] - # Caller might have called ctxt.reply() manually - for (reply, failure) in ctxt._response: - if failure: - raise failure[0], failure[1], failure[2] - res.append(reply) - # if ending not 'sent'...we might have more data to - # return from the function itself - if not ctxt._done: - if inspect.isgenerator(rval): - for val in rval: - res.append(val) - else: - res.append(rval) - done.send(res) - except rpc_common.ClientException as e: - done.send_exception(e._exc_info[1]) - except Exception as e: - done.send_exception(e) - - thread = eventlet.greenthread.spawn(_inner) - - if timeout: - start_time = time.time() - while not done.ready(): - eventlet.greenthread.sleep(1) - cur_time = time.time() - if (cur_time - start_time) > timeout: - thread.kill() - raise rpc_common.Timeout() - - return done.wait() - - -class Connection(object): - """Connection object.""" - - def __init__(self): - self.consumers = [] - - def create_consumer(self, topic, proxy, fanout=False): - consumer = Consumer(topic, proxy) - self.consumers.append(consumer) - if topic not in CONSUMERS: - CONSUMERS[topic] = [] - CONSUMERS[topic].append(consumer) - - def close(self): - for consumer in self.consumers: - CONSUMERS[consumer.topic].remove(consumer) - self.consumers = [] - - def consume_in_thread(self): - pass - - def consume_in_thread_group(self, thread_group): - pass - - -def create_connection(conf, new=True): - """Create a connection""" - return Connection() - - -def check_serialize(msg): - """Make sure a message intended for rpc can be serialized.""" - json.dumps(msg) - - -def multicall(conf, context, topic, msg, timeout=None): - """Make a call that returns multiple times.""" - - check_serialize(msg) - - method = msg.get('method') - if not method: - return - args = msg.get('args', {}) - version = msg.get('version', None) - - try: - consumer = CONSUMERS[topic][0] - except (KeyError, IndexError): - return iter([None]) - else: - return consumer.call(context, version, method, args, timeout) - - -def call(conf, context, topic, msg, timeout=None): - """Sends a message on a topic and wait for a response.""" - rv = multicall(conf, context, topic, msg, timeout) - # NOTE(vish): return the last result from the multicall - rv = list(rv) - if not rv: - return - return rv[-1] - - -def cast(conf, context, topic, msg): - check_serialize(msg) - try: - call(conf, context, topic, msg) - except Exception: - pass - - -def notify(conf, context, topic, msg, envelope): - check_serialize(msg) - - -def cleanup(): - pass - - -def fanout_cast(conf, context, topic, msg): - """Cast to all consumers of a topic""" - check_serialize(msg) - method = msg.get('method') - if not method: - return - args = msg.get('args', {}) - version = msg.get('version', None) - - for consumer in CONSUMERS.get(topic, []): - try: - consumer.call(context, version, method, args, None) - except Exception: - pass diff --git a/billingstack/openstack/common/rpc/impl_kombu.py b/billingstack/openstack/common/rpc/impl_kombu.py deleted file mode 100644 index 0bd8df5..0000000 --- a/billingstack/openstack/common/rpc/impl_kombu.py +++ /dev/null @@ -1,846 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import functools -import itertools -import socket -import ssl -import sys -import time -import uuid - -import eventlet -import greenlet -import kombu -import kombu.connection -import kombu.entity -import kombu.messaging -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import network_utils -from billingstack.openstack.common.rpc import amqp as rpc_amqp -from billingstack.openstack.common.rpc import common as rpc_common - -kombu_opts = [ - cfg.StrOpt('kombu_ssl_version', - default='', - help='SSL version to use (valid only if SSL enabled)'), - cfg.StrOpt('kombu_ssl_keyfile', - default='', - help='SSL key file (valid only if SSL enabled)'), - cfg.StrOpt('kombu_ssl_certfile', - default='', - help='SSL cert file (valid only if SSL enabled)'), - cfg.StrOpt('kombu_ssl_ca_certs', - default='', - help=('SSL certification authority file ' - '(valid only if SSL enabled)')), - cfg.StrOpt('rabbit_host', - default='localhost', - help='The RabbitMQ broker address where a single node is used'), - cfg.IntOpt('rabbit_port', - default=5672, - help='The RabbitMQ broker port where a single node is used'), - cfg.ListOpt('rabbit_hosts', - default=['$rabbit_host:$rabbit_port'], - help='RabbitMQ HA cluster host:port pairs'), - cfg.BoolOpt('rabbit_use_ssl', - default=False, - help='connect over SSL for RabbitMQ'), - cfg.StrOpt('rabbit_userid', - default='guest', - help='the RabbitMQ userid'), - cfg.StrOpt('rabbit_password', - default='guest', - help='the RabbitMQ password', - secret=True), - cfg.StrOpt('rabbit_virtual_host', - default='/', - help='the RabbitMQ virtual host'), - cfg.IntOpt('rabbit_retry_interval', - default=1, - help='how frequently to retry connecting with RabbitMQ'), - cfg.IntOpt('rabbit_retry_backoff', - default=2, - help='how long to backoff for between retries when connecting ' - 'to RabbitMQ'), - cfg.IntOpt('rabbit_max_retries', - default=0, - help='maximum retries with trying to connect to RabbitMQ ' - '(the default of 0 implies an infinite retry count)'), - cfg.BoolOpt('rabbit_durable_queues', - default=False, - help='use durable queues in RabbitMQ'), - cfg.BoolOpt('rabbit_ha_queues', - default=False, - help='use H/A queues in RabbitMQ (x-ha-policy: all).' - 'You need to wipe RabbitMQ database when ' - 'changing this option.'), - -] - -cfg.CONF.register_opts(kombu_opts) - -LOG = rpc_common.LOG - - -def _get_queue_arguments(conf): - """Construct the arguments for declaring a queue. - - If the rabbit_ha_queues option is set, we declare a mirrored queue - as described here: - - http://www.rabbitmq.com/ha.html - - Setting x-ha-policy to all means that the queue will be mirrored - to all nodes in the cluster. - """ - return {'x-ha-policy': 'all'} if conf.rabbit_ha_queues else {} - - -class ConsumerBase(object): - """Consumer base class.""" - - def __init__(self, channel, callback, tag, **kwargs): - """Declare a queue on an amqp channel. - - 'channel' is the amqp channel to use - 'callback' is the callback to call when messages are received - 'tag' is a unique ID for the consumer on the channel - - queue name, exchange name, and other kombu options are - passed in here as a dictionary. - """ - self.callback = callback - self.tag = str(tag) - self.kwargs = kwargs - self.queue = None - self.reconnect(channel) - - def reconnect(self, channel): - """Re-declare the queue after a rabbit reconnect""" - self.channel = channel - self.kwargs['channel'] = channel - self.queue = kombu.entity.Queue(**self.kwargs) - self.queue.declare() - - def consume(self, *args, **kwargs): - """Actually declare the consumer on the amqp channel. This will - start the flow of messages from the queue. Using the - Connection.iterconsume() iterator will process the messages, - calling the appropriate callback. - - If a callback is specified in kwargs, use that. Otherwise, - use the callback passed during __init__() - - If kwargs['nowait'] is True, then this call will block until - a message is read. - - Messages will automatically be acked if the callback doesn't - raise an exception - """ - - options = {'consumer_tag': self.tag} - options['nowait'] = kwargs.get('nowait', False) - callback = kwargs.get('callback', self.callback) - if not callback: - raise ValueError("No callback defined") - - def _callback(raw_message): - message = self.channel.message_to_python(raw_message) - try: - msg = rpc_common.deserialize_msg(message.payload) - callback(msg) - except Exception: - LOG.exception(_("Failed to process message... skipping it.")) - finally: - message.ack() - - self.queue.consume(*args, callback=_callback, **options) - - def cancel(self): - """Cancel the consuming from the queue, if it has started""" - try: - self.queue.cancel(self.tag) - except KeyError, e: - # NOTE(comstud): Kludge to get around a amqplib bug - if str(e) != "u'%s'" % self.tag: - raise - self.queue = None - - -class DirectConsumer(ConsumerBase): - """Queue/consumer class for 'direct'""" - - def __init__(self, conf, channel, msg_id, callback, tag, **kwargs): - """Init a 'direct' queue. - - 'channel' is the amqp channel to use - 'msg_id' is the msg_id to listen on - 'callback' is the callback to call when messages are received - 'tag' is a unique ID for the consumer on the channel - - Other kombu options may be passed - """ - # Default options - options = {'durable': False, - 'queue_arguments': _get_queue_arguments(conf), - 'auto_delete': True, - 'exclusive': False} - options.update(kwargs) - exchange = kombu.entity.Exchange(name=msg_id, - type='direct', - durable=options['durable'], - auto_delete=options['auto_delete']) - super(DirectConsumer, self).__init__(channel, - callback, - tag, - name=msg_id, - exchange=exchange, - routing_key=msg_id, - **options) - - -class TopicConsumer(ConsumerBase): - """Consumer class for 'topic'""" - - def __init__(self, conf, channel, topic, callback, tag, name=None, - exchange_name=None, **kwargs): - """Init a 'topic' queue. - - :param channel: the amqp channel to use - :param topic: the topic to listen on - :paramtype topic: str - :param callback: the callback to call when messages are received - :param tag: a unique ID for the consumer on the channel - :param name: optional queue name, defaults to topic - :paramtype name: str - - Other kombu options may be passed as keyword arguments - """ - # Default options - options = {'durable': conf.rabbit_durable_queues, - 'queue_arguments': _get_queue_arguments(conf), - 'auto_delete': False, - 'exclusive': False} - options.update(kwargs) - exchange_name = exchange_name or rpc_amqp.get_control_exchange(conf) - exchange = kombu.entity.Exchange(name=exchange_name, - type='topic', - durable=options['durable'], - auto_delete=options['auto_delete']) - super(TopicConsumer, self).__init__(channel, - callback, - tag, - name=name or topic, - exchange=exchange, - routing_key=topic, - **options) - - -class FanoutConsumer(ConsumerBase): - """Consumer class for 'fanout'""" - - def __init__(self, conf, channel, topic, callback, tag, **kwargs): - """Init a 'fanout' queue. - - 'channel' is the amqp channel to use - 'topic' is the topic to listen on - 'callback' is the callback to call when messages are received - 'tag' is a unique ID for the consumer on the channel - - Other kombu options may be passed - """ - unique = uuid.uuid4().hex - exchange_name = '%s_fanout' % topic - queue_name = '%s_fanout_%s' % (topic, unique) - - # Default options - options = {'durable': False, - 'queue_arguments': _get_queue_arguments(conf), - 'auto_delete': True, - 'exclusive': False} - options.update(kwargs) - exchange = kombu.entity.Exchange(name=exchange_name, type='fanout', - durable=options['durable'], - auto_delete=options['auto_delete']) - super(FanoutConsumer, self).__init__(channel, callback, tag, - name=queue_name, - exchange=exchange, - routing_key=topic, - **options) - - -class Publisher(object): - """Base Publisher class""" - - def __init__(self, channel, exchange_name, routing_key, **kwargs): - """Init the Publisher class with the exchange_name, routing_key, - and other options - """ - self.exchange_name = exchange_name - self.routing_key = routing_key - self.kwargs = kwargs - self.reconnect(channel) - - def reconnect(self, channel): - """Re-establish the Producer after a rabbit reconnection""" - self.exchange = kombu.entity.Exchange(name=self.exchange_name, - **self.kwargs) - self.producer = kombu.messaging.Producer(exchange=self.exchange, - channel=channel, - routing_key=self.routing_key) - - def send(self, msg, timeout=None): - """Send a message""" - if timeout: - # - # AMQP TTL is in milliseconds when set in the header. - # - self.producer.publish(msg, headers={'ttl': (timeout * 1000)}) - else: - self.producer.publish(msg) - - -class DirectPublisher(Publisher): - """Publisher class for 'direct'""" - def __init__(self, conf, channel, msg_id, **kwargs): - """init a 'direct' publisher. - - Kombu options may be passed as keyword args to override defaults - """ - - options = {'durable': False, - 'auto_delete': True, - 'exclusive': False} - options.update(kwargs) - super(DirectPublisher, self).__init__(channel, msg_id, msg_id, - type='direct', **options) - - -class TopicPublisher(Publisher): - """Publisher class for 'topic'""" - def __init__(self, conf, channel, topic, **kwargs): - """init a 'topic' publisher. - - Kombu options may be passed as keyword args to override defaults - """ - options = {'durable': conf.rabbit_durable_queues, - 'auto_delete': False, - 'exclusive': False} - options.update(kwargs) - exchange_name = rpc_amqp.get_control_exchange(conf) - super(TopicPublisher, self).__init__(channel, - exchange_name, - topic, - type='topic', - **options) - - -class FanoutPublisher(Publisher): - """Publisher class for 'fanout'""" - def __init__(self, conf, channel, topic, **kwargs): - """init a 'fanout' publisher. - - Kombu options may be passed as keyword args to override defaults - """ - options = {'durable': False, - 'auto_delete': True, - 'exclusive': False} - options.update(kwargs) - super(FanoutPublisher, self).__init__(channel, '%s_fanout' % topic, - None, type='fanout', **options) - - -class NotifyPublisher(TopicPublisher): - """Publisher class for 'notify'""" - - def __init__(self, conf, channel, topic, **kwargs): - self.durable = kwargs.pop('durable', conf.rabbit_durable_queues) - self.queue_arguments = _get_queue_arguments(conf) - super(NotifyPublisher, self).__init__(conf, channel, topic, **kwargs) - - def reconnect(self, channel): - super(NotifyPublisher, self).reconnect(channel) - - # NOTE(jerdfelt): Normally the consumer would create the queue, but - # we do this to ensure that messages don't get dropped if the - # consumer is started after we do - queue = kombu.entity.Queue(channel=channel, - exchange=self.exchange, - durable=self.durable, - name=self.routing_key, - routing_key=self.routing_key, - queue_arguments=self.queue_arguments) - queue.declare() - - -class Connection(object): - """Connection object.""" - - pool = None - - def __init__(self, conf, server_params=None): - self.consumers = [] - self.consumer_thread = None - self.proxy_callbacks = [] - self.conf = conf - self.max_retries = self.conf.rabbit_max_retries - # Try forever? - if self.max_retries <= 0: - self.max_retries = None - self.interval_start = self.conf.rabbit_retry_interval - self.interval_stepping = self.conf.rabbit_retry_backoff - # max retry-interval = 30 seconds - self.interval_max = 30 - self.memory_transport = False - - if server_params is None: - server_params = {} - # Keys to translate from server_params to kombu params - server_params_to_kombu_params = {'username': 'userid'} - - ssl_params = self._fetch_ssl_params() - params_list = [] - for adr in self.conf.rabbit_hosts: - hostname, port = network_utils.parse_host_port( - adr, default_port=self.conf.rabbit_port) - - params = { - 'hostname': hostname, - 'port': port, - 'userid': self.conf.rabbit_userid, - 'password': self.conf.rabbit_password, - 'virtual_host': self.conf.rabbit_virtual_host, - } - - for sp_key, value in server_params.iteritems(): - p_key = server_params_to_kombu_params.get(sp_key, sp_key) - params[p_key] = value - - if self.conf.fake_rabbit: - params['transport'] = 'memory' - if self.conf.rabbit_use_ssl: - params['ssl'] = ssl_params - - params_list.append(params) - - self.params_list = params_list - - self.memory_transport = self.conf.fake_rabbit - - self.connection = None - self.reconnect() - - def _fetch_ssl_params(self): - """Handles fetching what ssl params - should be used for the connection (if any)""" - ssl_params = dict() - - # http://docs.python.org/library/ssl.html - ssl.wrap_socket - if self.conf.kombu_ssl_version: - ssl_params['ssl_version'] = self.conf.kombu_ssl_version - if self.conf.kombu_ssl_keyfile: - ssl_params['keyfile'] = self.conf.kombu_ssl_keyfile - if self.conf.kombu_ssl_certfile: - ssl_params['certfile'] = self.conf.kombu_ssl_certfile - if self.conf.kombu_ssl_ca_certs: - ssl_params['ca_certs'] = self.conf.kombu_ssl_ca_certs - # We might want to allow variations in the - # future with this? - ssl_params['cert_reqs'] = ssl.CERT_REQUIRED - - if not ssl_params: - # Just have the default behavior - return True - else: - # Return the extended behavior - return ssl_params - - def _connect(self, params): - """Connect to rabbit. Re-establish any queues that may have - been declared before if we are reconnecting. Exceptions should - be handled by the caller. - """ - if self.connection: - LOG.info(_("Reconnecting to AMQP server on " - "%(hostname)s:%(port)d") % params) - try: - self.connection.release() - except self.connection_errors: - pass - # Setting this in case the next statement fails, though - # it shouldn't be doing any network operations, yet. - self.connection = None - self.connection = kombu.connection.BrokerConnection(**params) - self.connection_errors = self.connection.connection_errors - if self.memory_transport: - # Kludge to speed up tests. - self.connection.transport.polling_interval = 0.0 - self.consumer_num = itertools.count(1) - self.connection.connect() - self.channel = self.connection.channel() - # work around 'memory' transport bug in 1.1.3 - if self.memory_transport: - self.channel._new_queue('ae.undeliver') - for consumer in self.consumers: - consumer.reconnect(self.channel) - LOG.info(_('Connected to AMQP server on %(hostname)s:%(port)d') % - params) - - def reconnect(self): - """Handles reconnecting and re-establishing queues. - Will retry up to self.max_retries number of times. - self.max_retries = 0 means to retry forever. - Sleep between tries, starting at self.interval_start - seconds, backing off self.interval_stepping number of seconds - each attempt. - """ - - attempt = 0 - while True: - params = self.params_list[attempt % len(self.params_list)] - attempt += 1 - try: - self._connect(params) - return - except (IOError, self.connection_errors) as e: - pass - except Exception, e: - # NOTE(comstud): Unfortunately it's possible for amqplib - # to return an error not covered by its transport - # connection_errors in the case of a timeout waiting for - # a protocol response. (See paste link in LP888621) - # So, we check all exceptions for 'timeout' in them - # and try to reconnect in this case. - if 'timeout' not in str(e): - raise - - log_info = {} - log_info['err_str'] = str(e) - log_info['max_retries'] = self.max_retries - log_info.update(params) - - if self.max_retries and attempt == self.max_retries: - LOG.error(_('Unable to connect to AMQP server on ' - '%(hostname)s:%(port)d after %(max_retries)d ' - 'tries: %(err_str)s') % log_info) - # NOTE(comstud): Copied from original code. There's - # really no better recourse because if this was a queue we - # need to consume on, we have no way to consume anymore. - sys.exit(1) - - if attempt == 1: - sleep_time = self.interval_start or 1 - elif attempt > 1: - sleep_time += self.interval_stepping - if self.interval_max: - sleep_time = min(sleep_time, self.interval_max) - - log_info['sleep_time'] = sleep_time - LOG.error(_('AMQP server on %(hostname)s:%(port)d is ' - 'unreachable: %(err_str)s. Trying again in ' - '%(sleep_time)d seconds.') % log_info) - time.sleep(sleep_time) - - def ensure(self, error_callback, method, *args, **kwargs): - while True: - try: - return method(*args, **kwargs) - except (self.connection_errors, socket.timeout, IOError), e: - if error_callback: - error_callback(e) - except Exception, e: - # NOTE(comstud): Unfortunately it's possible for amqplib - # to return an error not covered by its transport - # connection_errors in the case of a timeout waiting for - # a protocol response. (See paste link in LP888621) - # So, we check all exceptions for 'timeout' in them - # and try to reconnect in this case. - if 'timeout' not in str(e): - raise - if error_callback: - error_callback(e) - self.reconnect() - - def get_channel(self): - """Convenience call for bin/clear_rabbit_queues""" - return self.channel - - def close(self): - """Close/release this connection""" - self.cancel_consumer_thread() - self.wait_on_proxy_callbacks() - self.connection.release() - self.connection = None - - def reset(self): - """Reset a connection so it can be used again""" - self.cancel_consumer_thread() - self.wait_on_proxy_callbacks() - self.channel.close() - self.channel = self.connection.channel() - # work around 'memory' transport bug in 1.1.3 - if self.memory_transport: - self.channel._new_queue('ae.undeliver') - self.consumers = [] - - def declare_consumer(self, consumer_cls, topic, callback): - """Create a Consumer using the class that was passed in and - add it to our list of consumers - """ - - def _connect_error(exc): - log_info = {'topic': topic, 'err_str': str(exc)} - LOG.error(_("Failed to declare consumer for topic '%(topic)s': " - "%(err_str)s") % log_info) - - def _declare_consumer(): - consumer = consumer_cls(self.conf, self.channel, topic, callback, - self.consumer_num.next()) - self.consumers.append(consumer) - return consumer - - return self.ensure(_connect_error, _declare_consumer) - - def iterconsume(self, limit=None, timeout=None): - """Return an iterator that will consume from all queues/consumers""" - - info = {'do_consume': True} - - def _error_callback(exc): - if isinstance(exc, socket.timeout): - LOG.exception(_('Timed out waiting for RPC response: %s') % - str(exc)) - raise rpc_common.Timeout() - else: - LOG.exception(_('Failed to consume message from queue: %s') % - str(exc)) - info['do_consume'] = True - - def _consume(): - if info['do_consume']: - queues_head = self.consumers[:-1] - queues_tail = self.consumers[-1] - for queue in queues_head: - queue.consume(nowait=True) - queues_tail.consume(nowait=False) - info['do_consume'] = False - return self.connection.drain_events(timeout=timeout) - - for iteration in itertools.count(0): - if limit and iteration >= limit: - raise StopIteration - yield self.ensure(_error_callback, _consume) - - def cancel_consumer_thread(self): - """Cancel a consumer thread""" - if self.consumer_thread is not None: - self.consumer_thread.kill() - try: - self.consumer_thread.wait() - except greenlet.GreenletExit: - pass - self.consumer_thread = None - - def wait_on_proxy_callbacks(self): - """Wait for all proxy callback threads to exit.""" - for proxy_cb in self.proxy_callbacks: - proxy_cb.wait() - - def publisher_send(self, cls, topic, msg, timeout=None, **kwargs): - """Send to a publisher based on the publisher class""" - - def _error_callback(exc): - log_info = {'topic': topic, 'err_str': str(exc)} - LOG.exception(_("Failed to publish message to topic " - "'%(topic)s': %(err_str)s") % log_info) - - def _publish(): - publisher = cls(self.conf, self.channel, topic, **kwargs) - publisher.send(msg, timeout) - - self.ensure(_error_callback, _publish) - - def declare_direct_consumer(self, topic, callback): - """Create a 'direct' queue. - In nova's use, this is generally a msg_id queue used for - responses for call/multicall - """ - self.declare_consumer(DirectConsumer, topic, callback) - - def declare_topic_consumer(self, topic, callback=None, queue_name=None, - exchange_name=None): - """Create a 'topic' consumer.""" - self.declare_consumer(functools.partial(TopicConsumer, - name=queue_name, - exchange_name=exchange_name, - ), - topic, callback) - - def declare_fanout_consumer(self, topic, callback): - """Create a 'fanout' consumer""" - self.declare_consumer(FanoutConsumer, topic, callback) - - def direct_send(self, msg_id, msg): - """Send a 'direct' message""" - self.publisher_send(DirectPublisher, msg_id, msg) - - def topic_send(self, topic, msg, timeout=None): - """Send a 'topic' message""" - self.publisher_send(TopicPublisher, topic, msg, timeout) - - def fanout_send(self, topic, msg): - """Send a 'fanout' message""" - self.publisher_send(FanoutPublisher, topic, msg) - - def notify_send(self, topic, msg, **kwargs): - """Send a notify message on a topic""" - self.publisher_send(NotifyPublisher, topic, msg, None, **kwargs) - - def consume(self, limit=None): - """Consume from all queues/consumers""" - it = self.iterconsume(limit=limit) - while True: - try: - it.next() - except StopIteration: - return - - def _consumer_thread_callback(self): - """ Consumer thread callback used by consume_in_* """ - try: - self.consume() - except greenlet.GreenletExit: - return - - def consume_in_thread(self): - """Consumer from all queues/consumers in a greenthread""" - - if self.consumer_thread is None: - self.consumer_thread = eventlet.spawn( - self._consumer_thread_callback) - return self.consumer_thread - - def consume_in_thread_group(self, thread_group): - """ Consume from all queues/consumers in the supplied ThreadGroup""" - thread_group.add_thread(self._consumer_thread_callback) - - def create_consumer(self, topic, proxy, fanout=False): - """Create a consumer that calls a method in a proxy object""" - proxy_cb = rpc_amqp.ProxyCallback( - self.conf, proxy, - rpc_amqp.get_connection_pool(self.conf, Connection)) - self.proxy_callbacks.append(proxy_cb) - - if fanout: - self.declare_fanout_consumer(topic, proxy_cb) - else: - self.declare_topic_consumer(topic, proxy_cb) - - def create_worker(self, topic, proxy, pool_name): - """Create a worker that calls a method in a proxy object""" - proxy_cb = rpc_amqp.ProxyCallback( - self.conf, proxy, - rpc_amqp.get_connection_pool(self.conf, Connection)) - self.proxy_callbacks.append(proxy_cb) - self.declare_topic_consumer(topic, proxy_cb, pool_name) - - def join_consumer_pool(self, callback, pool_name, topic, - exchange_name=None): - """Register as a member of a group of consumers for a given topic from - the specified exchange. - - Exactly one member of a given pool will receive each message. - - A message will be delivered to multiple pools, if more than - one is created. - """ - callback_wrapper = rpc_amqp.CallbackWrapper( - conf=self.conf, - callback=callback, - connection_pool=rpc_amqp.get_connection_pool(self.conf, - Connection), - ) - self.proxy_callbacks.append(callback_wrapper) - self.declare_topic_consumer( - queue_name=pool_name, - topic=topic, - exchange_name=exchange_name, - callback=callback_wrapper, - ) - - -def create_connection(conf, new=True): - """Create a connection""" - return rpc_amqp.create_connection( - conf, new, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def multicall(conf, context, topic, msg, timeout=None): - """Make a call that returns multiple times.""" - return rpc_amqp.multicall( - conf, context, topic, msg, timeout, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def call(conf, context, topic, msg, timeout=None): - """Sends a message on a topic and wait for a response.""" - return rpc_amqp.call( - conf, context, topic, msg, timeout, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def cast(conf, context, topic, msg): - """Sends a message on a topic without waiting for a response.""" - return rpc_amqp.cast( - conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def fanout_cast(conf, context, topic, msg): - """Sends a message on a fanout exchange without waiting for a response.""" - return rpc_amqp.fanout_cast( - conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def cast_to_server(conf, context, server_params, topic, msg): - """Sends a message on a topic to a specific server.""" - return rpc_amqp.cast_to_server( - conf, context, server_params, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def fanout_cast_to_server(conf, context, server_params, topic, msg): - """Sends a message on a fanout exchange to a specific server.""" - return rpc_amqp.fanout_cast_to_server( - conf, context, server_params, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def notify(conf, context, topic, msg, envelope): - """Sends a notification event on a topic.""" - return rpc_amqp.notify( - conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection), - envelope) - - -def cleanup(): - return rpc_amqp.cleanup(Connection.pool) diff --git a/billingstack/openstack/common/rpc/impl_qpid.py b/billingstack/openstack/common/rpc/impl_qpid.py deleted file mode 100644 index 9e58da0..0000000 --- a/billingstack/openstack/common/rpc/impl_qpid.py +++ /dev/null @@ -1,657 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC -# Copyright 2011 - 2012, Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import functools -import itertools -import time -import uuid - -import eventlet -import greenlet -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.rpc import amqp as rpc_amqp -from billingstack.openstack.common.rpc import common as rpc_common - -qpid_messaging = importutils.try_import("qpid.messaging") -qpid_exceptions = importutils.try_import("qpid.messaging.exceptions") - -LOG = logging.getLogger(__name__) - -qpid_opts = [ - cfg.StrOpt('qpid_hostname', - default='localhost', - help='Qpid broker hostname'), - cfg.StrOpt('qpid_port', - default='5672', - help='Qpid broker port'), - cfg.ListOpt('qpid_hosts', - default=['$qpid_hostname:$qpid_port'], - help='Qpid HA cluster host:port pairs'), - cfg.StrOpt('qpid_username', - default='', - help='Username for qpid connection'), - cfg.StrOpt('qpid_password', - default='', - help='Password for qpid connection', - secret=True), - cfg.StrOpt('qpid_sasl_mechanisms', - default='', - help='Space separated list of SASL mechanisms to use for auth'), - cfg.IntOpt('qpid_heartbeat', - default=60, - help='Seconds between connection keepalive heartbeats'), - cfg.StrOpt('qpid_protocol', - default='tcp', - help="Transport to use, either 'tcp' or 'ssl'"), - cfg.BoolOpt('qpid_tcp_nodelay', - default=True, - help='Disable Nagle algorithm'), -] - -cfg.CONF.register_opts(qpid_opts) - - -class ConsumerBase(object): - """Consumer base class.""" - - def __init__(self, session, callback, node_name, node_opts, - link_name, link_opts): - """Declare a queue on an amqp session. - - 'session' is the amqp session to use - 'callback' is the callback to call when messages are received - 'node_name' is the first part of the Qpid address string, before ';' - 'node_opts' will be applied to the "x-declare" section of "node" - in the address string. - 'link_name' goes into the "name" field of the "link" in the address - string - 'link_opts' will be applied to the "x-declare" section of "link" - in the address string. - """ - self.callback = callback - self.receiver = None - self.session = None - - addr_opts = { - "create": "always", - "node": { - "type": "topic", - "x-declare": { - "durable": True, - "auto-delete": True, - }, - }, - "link": { - "name": link_name, - "durable": True, - "x-declare": { - "durable": False, - "auto-delete": True, - "exclusive": False, - }, - }, - } - addr_opts["node"]["x-declare"].update(node_opts) - addr_opts["link"]["x-declare"].update(link_opts) - - self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts)) - - self.reconnect(session) - - def reconnect(self, session): - """Re-declare the receiver after a qpid reconnect""" - self.session = session - self.receiver = session.receiver(self.address) - self.receiver.capacity = 1 - - def consume(self): - """Fetch the message and pass it to the callback object""" - message = self.receiver.fetch() - try: - msg = rpc_common.deserialize_msg(message.content) - self.callback(msg) - except Exception: - LOG.exception(_("Failed to process message... skipping it.")) - finally: - self.session.acknowledge(message) - - def get_receiver(self): - return self.receiver - - -class DirectConsumer(ConsumerBase): - """Queue/consumer class for 'direct'""" - - def __init__(self, conf, session, msg_id, callback): - """Init a 'direct' queue. - - 'session' is the amqp session to use - 'msg_id' is the msg_id to listen on - 'callback' is the callback to call when messages are received - """ - - super(DirectConsumer, self).__init__(session, callback, - "%s/%s" % (msg_id, msg_id), - {"type": "direct"}, - msg_id, - {"exclusive": True}) - - -class TopicConsumer(ConsumerBase): - """Consumer class for 'topic'""" - - def __init__(self, conf, session, topic, callback, name=None, - exchange_name=None): - """Init a 'topic' queue. - - :param session: the amqp session to use - :param topic: is the topic to listen on - :paramtype topic: str - :param callback: the callback to call when messages are received - :param name: optional queue name, defaults to topic - """ - - exchange_name = exchange_name or rpc_amqp.get_control_exchange(conf) - super(TopicConsumer, self).__init__(session, callback, - "%s/%s" % (exchange_name, topic), - {}, name or topic, {}) - - -class FanoutConsumer(ConsumerBase): - """Consumer class for 'fanout'""" - - def __init__(self, conf, session, topic, callback): - """Init a 'fanout' queue. - - 'session' is the amqp session to use - 'topic' is the topic to listen on - 'callback' is the callback to call when messages are received - """ - - super(FanoutConsumer, self).__init__( - session, callback, - "%s_fanout" % topic, - {"durable": False, "type": "fanout"}, - "%s_fanout_%s" % (topic, uuid.uuid4().hex), - {"exclusive": True}) - - -class Publisher(object): - """Base Publisher class""" - - def __init__(self, session, node_name, node_opts=None): - """Init the Publisher class with the exchange_name, routing_key, - and other options - """ - self.sender = None - self.session = session - - addr_opts = { - "create": "always", - "node": { - "type": "topic", - "x-declare": { - "durable": False, - # auto-delete isn't implemented for exchanges in qpid, - # but put in here anyway - "auto-delete": True, - }, - }, - } - if node_opts: - addr_opts["node"]["x-declare"].update(node_opts) - - self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts)) - - self.reconnect(session) - - def reconnect(self, session): - """Re-establish the Sender after a reconnection""" - self.sender = session.sender(self.address) - - def send(self, msg): - """Send a message""" - self.sender.send(msg) - - -class DirectPublisher(Publisher): - """Publisher class for 'direct'""" - def __init__(self, conf, session, msg_id): - """Init a 'direct' publisher.""" - super(DirectPublisher, self).__init__(session, msg_id, - {"type": "Direct"}) - - -class TopicPublisher(Publisher): - """Publisher class for 'topic'""" - def __init__(self, conf, session, topic): - """init a 'topic' publisher. - """ - exchange_name = rpc_amqp.get_control_exchange(conf) - super(TopicPublisher, self).__init__(session, - "%s/%s" % (exchange_name, topic)) - - -class FanoutPublisher(Publisher): - """Publisher class for 'fanout'""" - def __init__(self, conf, session, topic): - """init a 'fanout' publisher. - """ - super(FanoutPublisher, self).__init__( - session, - "%s_fanout" % topic, {"type": "fanout"}) - - -class NotifyPublisher(Publisher): - """Publisher class for notifications""" - def __init__(self, conf, session, topic): - """init a 'topic' publisher. - """ - exchange_name = rpc_amqp.get_control_exchange(conf) - super(NotifyPublisher, self).__init__(session, - "%s/%s" % (exchange_name, topic), - {"durable": True}) - - -class Connection(object): - """Connection object.""" - - pool = None - - def __init__(self, conf, server_params=None): - if not qpid_messaging: - raise ImportError("Failed to import qpid.messaging") - - self.session = None - self.consumers = {} - self.consumer_thread = None - self.proxy_callbacks = [] - self.conf = conf - - if server_params and 'hostname' in server_params: - # NOTE(russellb) This enables support for cast_to_server. - server_params['qpid_hosts'] = [ - '%s:%d' % (server_params['hostname'], - server_params.get('port', 5672)) - ] - - params = { - 'qpid_hosts': self.conf.qpid_hosts, - 'username': self.conf.qpid_username, - 'password': self.conf.qpid_password, - } - params.update(server_params or {}) - - self.brokers = params['qpid_hosts'] - self.username = params['username'] - self.password = params['password'] - self.connection_create(self.brokers[0]) - self.reconnect() - - def connection_create(self, broker): - # Create the connection - this does not open the connection - self.connection = qpid_messaging.Connection(broker) - - # Check if flags are set and if so set them for the connection - # before we call open - self.connection.username = self.username - self.connection.password = self.password - - self.connection.sasl_mechanisms = self.conf.qpid_sasl_mechanisms - # Reconnection is done by self.reconnect() - self.connection.reconnect = False - self.connection.heartbeat = self.conf.qpid_heartbeat - self.connection.protocol = self.conf.qpid_protocol - self.connection.tcp_nodelay = self.conf.qpid_tcp_nodelay - - def _register_consumer(self, consumer): - self.consumers[str(consumer.get_receiver())] = consumer - - def _lookup_consumer(self, receiver): - return self.consumers[str(receiver)] - - def reconnect(self): - """Handles reconnecting and re-establishing sessions and queues""" - if self.connection.opened(): - try: - self.connection.close() - except qpid_exceptions.ConnectionError: - pass - - attempt = 0 - delay = 1 - while True: - broker = self.brokers[attempt % len(self.brokers)] - attempt += 1 - - try: - self.connection_create(broker) - self.connection.open() - except qpid_exceptions.ConnectionError, e: - msg_dict = dict(e=e, delay=delay) - msg = _("Unable to connect to AMQP server: %(e)s. " - "Sleeping %(delay)s seconds") % msg_dict - LOG.error(msg) - time.sleep(delay) - delay = min(2 * delay, 60) - else: - LOG.info(_('Connected to AMQP server on %s'), broker) - break - - self.session = self.connection.session() - - if self.consumers: - consumers = self.consumers - self.consumers = {} - - for consumer in consumers.itervalues(): - consumer.reconnect(self.session) - self._register_consumer(consumer) - - LOG.debug(_("Re-established AMQP queues")) - - def ensure(self, error_callback, method, *args, **kwargs): - while True: - try: - return method(*args, **kwargs) - except (qpid_exceptions.Empty, - qpid_exceptions.ConnectionError), e: - if error_callback: - error_callback(e) - self.reconnect() - - def close(self): - """Close/release this connection""" - self.cancel_consumer_thread() - self.wait_on_proxy_callbacks() - self.connection.close() - self.connection = None - - def reset(self): - """Reset a connection so it can be used again""" - self.cancel_consumer_thread() - self.wait_on_proxy_callbacks() - self.session.close() - self.session = self.connection.session() - self.consumers = {} - - def declare_consumer(self, consumer_cls, topic, callback): - """Create a Consumer using the class that was passed in and - add it to our list of consumers - """ - def _connect_error(exc): - log_info = {'topic': topic, 'err_str': str(exc)} - LOG.error(_("Failed to declare consumer for topic '%(topic)s': " - "%(err_str)s") % log_info) - - def _declare_consumer(): - consumer = consumer_cls(self.conf, self.session, topic, callback) - self._register_consumer(consumer) - return consumer - - return self.ensure(_connect_error, _declare_consumer) - - def iterconsume(self, limit=None, timeout=None): - """Return an iterator that will consume from all queues/consumers""" - - def _error_callback(exc): - if isinstance(exc, qpid_exceptions.Empty): - LOG.exception(_('Timed out waiting for RPC response: %s') % - str(exc)) - raise rpc_common.Timeout() - else: - LOG.exception(_('Failed to consume message from queue: %s') % - str(exc)) - - def _consume(): - nxt_receiver = self.session.next_receiver(timeout=timeout) - try: - self._lookup_consumer(nxt_receiver).consume() - except Exception: - LOG.exception(_("Error processing message. Skipping it.")) - - for iteration in itertools.count(0): - if limit and iteration >= limit: - raise StopIteration - yield self.ensure(_error_callback, _consume) - - def cancel_consumer_thread(self): - """Cancel a consumer thread""" - if self.consumer_thread is not None: - self.consumer_thread.kill() - try: - self.consumer_thread.wait() - except greenlet.GreenletExit: - pass - self.consumer_thread = None - - def wait_on_proxy_callbacks(self): - """Wait for all proxy callback threads to exit.""" - for proxy_cb in self.proxy_callbacks: - proxy_cb.wait() - - def publisher_send(self, cls, topic, msg): - """Send to a publisher based on the publisher class""" - - def _connect_error(exc): - log_info = {'topic': topic, 'err_str': str(exc)} - LOG.exception(_("Failed to publish message to topic " - "'%(topic)s': %(err_str)s") % log_info) - - def _publisher_send(): - publisher = cls(self.conf, self.session, topic) - publisher.send(msg) - - return self.ensure(_connect_error, _publisher_send) - - def declare_direct_consumer(self, topic, callback): - """Create a 'direct' queue. - In nova's use, this is generally a msg_id queue used for - responses for call/multicall - """ - self.declare_consumer(DirectConsumer, topic, callback) - - def declare_topic_consumer(self, topic, callback=None, queue_name=None, - exchange_name=None): - """Create a 'topic' consumer.""" - self.declare_consumer(functools.partial(TopicConsumer, - name=queue_name, - exchange_name=exchange_name, - ), - topic, callback) - - def declare_fanout_consumer(self, topic, callback): - """Create a 'fanout' consumer""" - self.declare_consumer(FanoutConsumer, topic, callback) - - def direct_send(self, msg_id, msg): - """Send a 'direct' message""" - self.publisher_send(DirectPublisher, msg_id, msg) - - def topic_send(self, topic, msg, timeout=None): - """Send a 'topic' message""" - # - # We want to create a message with attributes, e.g. a TTL. We - # don't really need to keep 'msg' in its JSON format any longer - # so let's create an actual qpid message here and get some - # value-add on the go. - # - # WARNING: Request timeout happens to be in the same units as - # qpid's TTL (seconds). If this changes in the future, then this - # will need to be altered accordingly. - # - qpid_message = qpid_messaging.Message(content=msg, ttl=timeout) - self.publisher_send(TopicPublisher, topic, qpid_message) - - def fanout_send(self, topic, msg): - """Send a 'fanout' message""" - self.publisher_send(FanoutPublisher, topic, msg) - - def notify_send(self, topic, msg, **kwargs): - """Send a notify message on a topic""" - self.publisher_send(NotifyPublisher, topic, msg) - - def _consumer_thread_callback(self): - """ Consumer thread callback used by consume_in_* """ - try: - self.consume() - except greenlet.GreenletExit: - return - - def consume(self, limit=None): - """Consume from all queues/consumers""" - it = self.iterconsume(limit=limit) - while True: - try: - it.next() - except StopIteration: - return - - def consume_in_thread(self): - """Consumer from all queues/consumers in a greenthread""" - - if self.consumer_thread is None: - self.consumer_thread = eventlet.spawn( - self._consumer_thread_callback) - return self.consumer_thread - - def consume_in_thread_group(self, thread_group): - """ Consume from all queues/consumers in the supplied ThreadGroup""" - thread_group.add_thread(self._consumer_thread_callback) - - def create_consumer(self, topic, proxy, fanout=False): - """Create a consumer that calls a method in a proxy object""" - proxy_cb = rpc_amqp.ProxyCallback( - self.conf, proxy, - rpc_amqp.get_connection_pool(self.conf, Connection)) - self.proxy_callbacks.append(proxy_cb) - - if fanout: - consumer = FanoutConsumer(self.conf, self.session, topic, proxy_cb) - else: - consumer = TopicConsumer(self.conf, self.session, topic, proxy_cb) - - self._register_consumer(consumer) - - return consumer - - def create_worker(self, topic, proxy, pool_name): - """Create a worker that calls a method in a proxy object""" - proxy_cb = rpc_amqp.ProxyCallback( - self.conf, proxy, - rpc_amqp.get_connection_pool(self.conf, Connection)) - self.proxy_callbacks.append(proxy_cb) - - consumer = TopicConsumer(self.conf, self.session, topic, proxy_cb, - name=pool_name) - - self._register_consumer(consumer) - - return consumer - - def join_consumer_pool(self, callback, pool_name, topic, - exchange_name=None): - """Register as a member of a group of consumers for a given topic from - the specified exchange. - - Exactly one member of a given pool will receive each message. - - A message will be delivered to multiple pools, if more than - one is created. - """ - callback_wrapper = rpc_amqp.CallbackWrapper( - conf=self.conf, - callback=callback, - connection_pool=rpc_amqp.get_connection_pool(self.conf, - Connection), - ) - self.proxy_callbacks.append(callback_wrapper) - - consumer = TopicConsumer(conf=self.conf, - session=self.session, - topic=topic, - callback=callback_wrapper, - name=pool_name, - exchange_name=exchange_name) - - self._register_consumer(consumer) - return consumer - - -def create_connection(conf, new=True): - """Create a connection""" - return rpc_amqp.create_connection( - conf, new, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def multicall(conf, context, topic, msg, timeout=None): - """Make a call that returns multiple times.""" - return rpc_amqp.multicall( - conf, context, topic, msg, timeout, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def call(conf, context, topic, msg, timeout=None): - """Sends a message on a topic and wait for a response.""" - return rpc_amqp.call( - conf, context, topic, msg, timeout, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def cast(conf, context, topic, msg): - """Sends a message on a topic without waiting for a response.""" - return rpc_amqp.cast( - conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def fanout_cast(conf, context, topic, msg): - """Sends a message on a fanout exchange without waiting for a response.""" - return rpc_amqp.fanout_cast( - conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def cast_to_server(conf, context, server_params, topic, msg): - """Sends a message on a topic to a specific server.""" - return rpc_amqp.cast_to_server( - conf, context, server_params, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def fanout_cast_to_server(conf, context, server_params, topic, msg): - """Sends a message on a fanout exchange to a specific server.""" - return rpc_amqp.fanout_cast_to_server( - conf, context, server_params, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection)) - - -def notify(conf, context, topic, msg, envelope): - """Sends a notification event on a topic.""" - return rpc_amqp.notify(conf, context, topic, msg, - rpc_amqp.get_connection_pool(conf, Connection), - envelope) - - -def cleanup(): - return rpc_amqp.cleanup(Connection.pool) diff --git a/billingstack/openstack/common/rpc/impl_zmq.py b/billingstack/openstack/common/rpc/impl_zmq.py deleted file mode 100644 index bf7fdc7..0000000 --- a/billingstack/openstack/common/rpc/impl_zmq.py +++ /dev/null @@ -1,844 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 Cloudscaling Group, Inc -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import os -import pprint -import socket -import sys -import types -import uuid - -import eventlet -import greenlet -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import jsonutils -from billingstack.openstack.common import processutils as utils -from billingstack.openstack.common.rpc import common as rpc_common - -zmq = importutils.try_import('eventlet.green.zmq') - -# for convenience, are not modified. -pformat = pprint.pformat -Timeout = eventlet.timeout.Timeout -LOG = rpc_common.LOG -RemoteError = rpc_common.RemoteError -RPCException = rpc_common.RPCException - -zmq_opts = [ - cfg.StrOpt('rpc_zmq_bind_address', default='*', - help='ZeroMQ bind address. Should be a wildcard (*), ' - 'an ethernet interface, or IP. ' - 'The "host" option should point or resolve to this ' - 'address.'), - - # The module.Class to use for matchmaking. - cfg.StrOpt( - 'rpc_zmq_matchmaker', - default=('billingstack.openstack.common.rpc.' - 'matchmaker.MatchMakerLocalhost'), - help='MatchMaker driver', - ), - - # The following port is unassigned by IANA as of 2012-05-21 - cfg.IntOpt('rpc_zmq_port', default=9501, - help='ZeroMQ receiver listening port'), - - cfg.IntOpt('rpc_zmq_contexts', default=1, - help='Number of ZeroMQ contexts, defaults to 1'), - - cfg.IntOpt('rpc_zmq_topic_backlog', default=None, - help='Maximum number of ingress messages to locally buffer ' - 'per topic. Default is unlimited.'), - - cfg.StrOpt('rpc_zmq_ipc_dir', default='/var/run/openstack', - help='Directory for holding IPC sockets'), - - cfg.StrOpt('rpc_zmq_host', default=socket.gethostname(), - help='Name of this node. Must be a valid hostname, FQDN, or ' - 'IP address. Must match "host" option, if running Nova.') -] - - -CONF = cfg.CONF -CONF.register_opts(zmq_opts) - -ZMQ_CTX = None # ZeroMQ Context, must be global. -matchmaker = None # memoized matchmaker object - - -def _serialize(data): - """ - Serialization wrapper - We prefer using JSON, but it cannot encode all types. - Error if a developer passes us bad data. - """ - try: - return jsonutils.dumps(data, ensure_ascii=True) - except TypeError: - LOG.error(_("JSON serialization failed.")) - raise - - -def _deserialize(data): - """ - Deserialization wrapper - """ - LOG.debug(_("Deserializing: %s"), data) - return jsonutils.loads(data) - - -class ZmqSocket(object): - """ - A tiny wrapper around ZeroMQ to simplify the send/recv protocol - and connection management. - - Can be used as a Context (supports the 'with' statement). - """ - - def __init__(self, addr, zmq_type, bind=True, subscribe=None): - self.sock = _get_ctxt().socket(zmq_type) - self.addr = addr - self.type = zmq_type - self.subscriptions = [] - - # Support failures on sending/receiving on wrong socket type. - self.can_recv = zmq_type in (zmq.PULL, zmq.SUB) - self.can_send = zmq_type in (zmq.PUSH, zmq.PUB) - self.can_sub = zmq_type in (zmq.SUB, ) - - # Support list, str, & None for subscribe arg (cast to list) - do_sub = { - list: subscribe, - str: [subscribe], - type(None): [] - }[type(subscribe)] - - for f in do_sub: - self.subscribe(f) - - str_data = {'addr': addr, 'type': self.socket_s(), - 'subscribe': subscribe, 'bind': bind} - - LOG.debug(_("Connecting to %(addr)s with %(type)s"), str_data) - LOG.debug(_("-> Subscribed to %(subscribe)s"), str_data) - LOG.debug(_("-> bind: %(bind)s"), str_data) - - try: - if bind: - self.sock.bind(addr) - else: - self.sock.connect(addr) - except Exception: - raise RPCException(_("Could not open socket.")) - - def socket_s(self): - """Get socket type as string.""" - t_enum = ('PUSH', 'PULL', 'PUB', 'SUB', 'REP', 'REQ', 'ROUTER', - 'DEALER') - return dict(map(lambda t: (getattr(zmq, t), t), t_enum))[self.type] - - def subscribe(self, msg_filter): - """Subscribe.""" - if not self.can_sub: - raise RPCException("Cannot subscribe on this socket.") - LOG.debug(_("Subscribing to %s"), msg_filter) - - try: - self.sock.setsockopt(zmq.SUBSCRIBE, msg_filter) - except Exception: - return - - self.subscriptions.append(msg_filter) - - def unsubscribe(self, msg_filter): - """Unsubscribe.""" - if msg_filter not in self.subscriptions: - return - self.sock.setsockopt(zmq.UNSUBSCRIBE, msg_filter) - self.subscriptions.remove(msg_filter) - - def close(self): - if self.sock is None or self.sock.closed: - return - - # We must unsubscribe, or we'll leak descriptors. - if len(self.subscriptions) > 0: - for f in self.subscriptions: - try: - self.sock.setsockopt(zmq.UNSUBSCRIBE, f) - except Exception: - pass - self.subscriptions = [] - - try: - # Default is to linger - self.sock.close() - except Exception: - # While this is a bad thing to happen, - # it would be much worse if some of the code calling this - # were to fail. For now, lets log, and later evaluate - # if we can safely raise here. - LOG.error("ZeroMQ socket could not be closed.") - self.sock = None - - def recv(self): - if not self.can_recv: - raise RPCException(_("You cannot recv on this socket.")) - return self.sock.recv_multipart() - - def send(self, data): - if not self.can_send: - raise RPCException(_("You cannot send on this socket.")) - self.sock.send_multipart(data) - - -class ZmqClient(object): - """Client for ZMQ sockets.""" - - def __init__(self, addr, socket_type=None, bind=False): - if socket_type is None: - socket_type = zmq.PUSH - self.outq = ZmqSocket(addr, socket_type, bind=bind) - - def cast(self, msg_id, topic, data, envelope=False): - msg_id = msg_id or 0 - - if not (envelope or rpc_common._SEND_RPC_ENVELOPE): - self.outq.send(map(bytes, - (msg_id, topic, 'cast', _serialize(data)))) - return - - rpc_envelope = rpc_common.serialize_msg(data[1], envelope) - zmq_msg = reduce(lambda x, y: x + y, rpc_envelope.items()) - self.outq.send(map(bytes, - (msg_id, topic, 'impl_zmq_v2', data[0]) + zmq_msg)) - - def close(self): - self.outq.close() - - -class RpcContext(rpc_common.CommonRpcContext): - """Context that supports replying to a rpc.call.""" - def __init__(self, **kwargs): - self.replies = [] - super(RpcContext, self).__init__(**kwargs) - - def deepcopy(self): - values = self.to_dict() - values['replies'] = self.replies - return self.__class__(**values) - - def reply(self, reply=None, failure=None, ending=False): - if ending: - return - self.replies.append(reply) - - @classmethod - def marshal(self, ctx): - ctx_data = ctx.to_dict() - return _serialize(ctx_data) - - @classmethod - def unmarshal(self, data): - return RpcContext.from_dict(_deserialize(data)) - - -class InternalContext(object): - """Used by ConsumerBase as a private context for - methods.""" - - def __init__(self, proxy): - self.proxy = proxy - self.msg_waiter = None - - def _get_response(self, ctx, proxy, topic, data): - """Process a curried message and cast the result to topic.""" - LOG.debug(_("Running func with context: %s"), ctx.to_dict()) - data.setdefault('version', None) - data.setdefault('args', {}) - - try: - result = proxy.dispatch( - ctx, data['version'], data['method'], **data['args']) - return ConsumerBase.normalize_reply(result, ctx.replies) - except greenlet.GreenletExit: - # ignore these since they are just from shutdowns - pass - except rpc_common.ClientException, e: - LOG.debug(_("Expected exception during message handling (%s)") % - e._exc_info[1]) - return {'exc': - rpc_common.serialize_remote_exception(e._exc_info, - log_failure=False)} - except Exception: - LOG.error(_("Exception during message handling")) - return {'exc': - rpc_common.serialize_remote_exception(sys.exc_info())} - - def reply(self, ctx, proxy, - msg_id=None, context=None, topic=None, msg=None): - """Reply to a casted call.""" - # Our real method is curried into msg['args'] - - child_ctx = RpcContext.unmarshal(msg[0]) - response = ConsumerBase.normalize_reply( - self._get_response(child_ctx, proxy, topic, msg[1]), - ctx.replies) - - LOG.debug(_("Sending reply")) - _multi_send(_cast, ctx, topic, { - 'method': '-process_reply', - 'args': { - 'msg_id': msg_id, # Include for Folsom compat. - 'response': response - } - }, _msg_id=msg_id) - - -class ConsumerBase(object): - """Base Consumer.""" - - def __init__(self): - self.private_ctx = InternalContext(None) - - @classmethod - def normalize_reply(self, result, replies): - #TODO(ewindisch): re-evaluate and document this method. - if isinstance(result, types.GeneratorType): - return list(result) - elif replies: - return replies - else: - return [result] - - def process(self, proxy, ctx, data): - data.setdefault('version', None) - data.setdefault('args', {}) - - # Method starting with - are - # processed internally. (non-valid method name) - method = data.get('method') - if not method: - LOG.error(_("RPC message did not include method.")) - return - - # Internal method - # uses internal context for safety. - if method == '-reply': - self.private_ctx.reply(ctx, proxy, **data['args']) - return - - proxy.dispatch(ctx, data['version'], - data['method'], **data['args']) - - -class ZmqBaseReactor(ConsumerBase): - """ - A consumer class implementing a - centralized casting broker (PULL-PUSH) - for RoundRobin requests. - """ - - def __init__(self, conf): - super(ZmqBaseReactor, self).__init__() - - self.mapping = {} - self.proxies = {} - self.threads = [] - self.sockets = [] - self.subscribe = {} - - self.pool = eventlet.greenpool.GreenPool(conf.rpc_thread_pool_size) - - def register(self, proxy, in_addr, zmq_type_in, out_addr=None, - zmq_type_out=None, in_bind=True, out_bind=True, - subscribe=None): - - LOG.info(_("Registering reactor")) - - if zmq_type_in not in (zmq.PULL, zmq.SUB): - raise RPCException("Bad input socktype") - - # Items push in. - inq = ZmqSocket(in_addr, zmq_type_in, bind=in_bind, - subscribe=subscribe) - - self.proxies[inq] = proxy - self.sockets.append(inq) - - LOG.info(_("In reactor registered")) - - if not out_addr: - return - - if zmq_type_out not in (zmq.PUSH, zmq.PUB): - raise RPCException("Bad output socktype") - - # Items push out. - outq = ZmqSocket(out_addr, zmq_type_out, bind=out_bind) - - self.mapping[inq] = outq - self.mapping[outq] = inq - self.sockets.append(outq) - - LOG.info(_("Out reactor registered")) - - def _consumer_thread_callback(self, sock): - """ Consumer thread callback used by consume_in_* """ - - LOG.info(_("Consuming socket")) - while True: - self.consume(sock) - - def consume_in_thread(self): - for k in self.proxies.keys(): - self.threads.append( - self.pool.spawn(self._consumer_thread_callback, k) - ) - - def consume_in_thread_group(self, thread_group): - """ Consume from all queues/consumers in the supplied ThreadGroup""" - for k in self.proxies.keys(): - thread_group.add_thread(self._consumer_thread_callback, k) - - def wait(self): - for t in self.threads: - t.wait() - - def close(self): - for s in self.sockets: - s.close() - - for t in self.threads: - t.kill() - - -class ZmqProxy(ZmqBaseReactor): - """ - A consumer class implementing a - topic-based proxy, forwarding to - IPC sockets. - """ - - def __init__(self, conf): - super(ZmqProxy, self).__init__(conf) - - self.topic_proxy = {} - - def consume(self, sock): - ipc_dir = CONF.rpc_zmq_ipc_dir - - #TODO(ewindisch): use zero-copy (i.e. references, not copying) - data = sock.recv() - topic = data[1] - - LOG.debug(_("CONSUMER GOT %s"), ' '.join(map(pformat, data))) - - if topic.startswith('fanout~'): - sock_type = zmq.PUB - topic = topic.split('.', 1)[0] - elif topic.startswith('zmq_replies'): - sock_type = zmq.PUB - else: - sock_type = zmq.PUSH - - if topic not in self.topic_proxy: - def publisher(waiter): - LOG.info(_("Creating proxy for topic: %s"), topic) - - try: - out_sock = ZmqSocket("ipc://%s/zmq_topic_%s" % - (ipc_dir, topic), - sock_type, bind=True) - except RPCException: - waiter.send_exception(*sys.exc_info()) - return - - self.topic_proxy[topic] = eventlet.queue.LightQueue( - CONF.rpc_zmq_topic_backlog) - self.sockets.append(out_sock) - - # It takes some time for a pub socket to open, - # before we can have any faith in doing a send() to it. - if sock_type == zmq.PUB: - eventlet.sleep(.5) - - waiter.send(True) - - while(True): - data = self.topic_proxy[topic].get() - out_sock.send(data) - LOG.debug(_("ROUTER RELAY-OUT SUCCEEDED %(data)s") % - {'data': data}) - - wait_sock_creation = eventlet.event.Event() - eventlet.spawn(publisher, wait_sock_creation) - - try: - wait_sock_creation.wait() - except RPCException: - LOG.error(_("Topic socket file creation failed.")) - return - - try: - self.topic_proxy[topic].put_nowait(data) - LOG.debug(_("ROUTER RELAY-OUT QUEUED %(data)s") % - {'data': data}) - except eventlet.queue.Full: - LOG.error(_("Local per-topic backlog buffer full for topic " - "%(topic)s. Dropping message.") % {'topic': topic}) - - def consume_in_thread(self): - """Runs the ZmqProxy service""" - ipc_dir = CONF.rpc_zmq_ipc_dir - consume_in = "tcp://%s:%s" % \ - (CONF.rpc_zmq_bind_address, - CONF.rpc_zmq_port) - consumption_proxy = InternalContext(None) - - if not os.path.isdir(ipc_dir): - try: - utils.execute('mkdir', '-p', ipc_dir, run_as_root=True) - utils.execute('chown', "%s:%s" % (os.getuid(), os.getgid()), - ipc_dir, run_as_root=True) - utils.execute('chmod', '750', ipc_dir, run_as_root=True) - except utils.ProcessExecutionError: - LOG.error(_("Could not create IPC directory %s") % - (ipc_dir, )) - raise - - try: - self.register(consumption_proxy, - consume_in, - zmq.PULL, - out_bind=True) - except zmq.ZMQError: - LOG.error(_("Could not create ZeroMQ receiver daemon. " - "Socket may already be in use.")) - raise - - super(ZmqProxy, self).consume_in_thread() - - -def unflatten_envelope(packenv): - """Unflattens the RPC envelope. - Takes a list and returns a dictionary. - i.e. [1,2,3,4] => {1: 2, 3: 4} - """ - i = iter(packenv) - h = {} - try: - while True: - k = i.next() - h[k] = i.next() - except StopIteration: - return h - - -class ZmqReactor(ZmqBaseReactor): - """ - A consumer class implementing a - consumer for messages. Can also be - used as a 1:1 proxy - """ - - def __init__(self, conf): - super(ZmqReactor, self).__init__(conf) - - def consume(self, sock): - #TODO(ewindisch): use zero-copy (i.e. references, not copying) - data = sock.recv() - LOG.debug(_("CONSUMER RECEIVED DATA: %s"), data) - if sock in self.mapping: - LOG.debug(_("ROUTER RELAY-OUT %(data)s") % { - 'data': data}) - self.mapping[sock].send(data) - return - - proxy = self.proxies[sock] - - if data[2] == 'cast': # Legacy protocol - packenv = data[3] - - ctx, msg = _deserialize(packenv) - request = rpc_common.deserialize_msg(msg) - ctx = RpcContext.unmarshal(ctx) - elif data[2] == 'impl_zmq_v2': - packenv = data[4:] - - msg = unflatten_envelope(packenv) - request = rpc_common.deserialize_msg(msg) - - # Unmarshal only after verifying the message. - ctx = RpcContext.unmarshal(data[3]) - else: - LOG.error(_("ZMQ Envelope version unsupported or unknown.")) - return - - self.pool.spawn_n(self.process, proxy, ctx, request) - - def consume_in_thread_group(self, thread_group): - self.reactor.consume_in_thread_group(thread_group) - - -class Connection(rpc_common.Connection): - """Manages connections and threads.""" - - def __init__(self, conf): - self.topics = [] - self.reactor = ZmqReactor(conf) - - def create_consumer(self, topic, proxy, fanout=False): - # Register with matchmaker. - _get_matchmaker().register(topic, CONF.rpc_zmq_host) - - # Subscription scenarios - if fanout: - sock_type = zmq.SUB - subscribe = ('', fanout)[type(fanout) == str] - topic = 'fanout~' + topic.split('.', 1)[0] - else: - sock_type = zmq.PULL - subscribe = None - topic = '.'.join((topic.split('.', 1)[0], CONF.rpc_zmq_host)) - - if topic in self.topics: - LOG.info(_("Skipping topic registration. Already registered.")) - return - - # Receive messages from (local) proxy - inaddr = "ipc://%s/zmq_topic_%s" % \ - (CONF.rpc_zmq_ipc_dir, topic) - - LOG.debug(_("Consumer is a zmq.%s"), - ['PULL', 'SUB'][sock_type == zmq.SUB]) - - self.reactor.register(proxy, inaddr, sock_type, - subscribe=subscribe, in_bind=False) - self.topics.append(topic) - - def close(self): - _get_matchmaker().stop_heartbeat() - for topic in self.topics: - _get_matchmaker().unregister(topic, CONF.rpc_zmq_host) - - self.reactor.close() - self.topics = [] - - def wait(self): - self.reactor.wait() - - def consume_in_thread(self): - _get_matchmaker().start_heartbeat() - self.reactor.consume_in_thread() - - -def _cast(addr, context, topic, msg, timeout=None, envelope=False, - _msg_id=None): - timeout_cast = timeout or CONF.rpc_cast_timeout - payload = [RpcContext.marshal(context), msg] - - with Timeout(timeout_cast, exception=rpc_common.Timeout): - try: - conn = ZmqClient(addr) - - # assumes cast can't return an exception - conn.cast(_msg_id, topic, payload, envelope) - except zmq.ZMQError: - raise RPCException("Cast failed. ZMQ Socket Exception") - finally: - if 'conn' in vars(): - conn.close() - - -def _call(addr, context, topic, msg, timeout=None, - envelope=False): - # timeout_response is how long we wait for a response - timeout = timeout or CONF.rpc_response_timeout - - # The msg_id is used to track replies. - msg_id = uuid.uuid4().hex - - # Replies always come into the reply service. - reply_topic = "zmq_replies.%s" % CONF.rpc_zmq_host - - LOG.debug(_("Creating payload")) - # Curry the original request into a reply method. - mcontext = RpcContext.marshal(context) - payload = { - 'method': '-reply', - 'args': { - 'msg_id': msg_id, - 'context': mcontext, - 'topic': reply_topic, - 'msg': [mcontext, msg] - } - } - - LOG.debug(_("Creating queue socket for reply waiter")) - - # Messages arriving async. - # TODO(ewindisch): have reply consumer with dynamic subscription mgmt - with Timeout(timeout, exception=rpc_common.Timeout): - try: - msg_waiter = ZmqSocket( - "ipc://%s/zmq_topic_zmq_replies.%s" % - (CONF.rpc_zmq_ipc_dir, - CONF.rpc_zmq_host), - zmq.SUB, subscribe=msg_id, bind=False - ) - - LOG.debug(_("Sending cast")) - _cast(addr, context, topic, payload, envelope) - - LOG.debug(_("Cast sent; Waiting reply")) - # Blocks until receives reply - msg = msg_waiter.recv() - LOG.debug(_("Received message: %s"), msg) - LOG.debug(_("Unpacking response")) - - if msg[2] == 'cast': # Legacy version - raw_msg = _deserialize(msg[-1])[-1] - elif msg[2] == 'impl_zmq_v2': - rpc_envelope = unflatten_envelope(msg[4:]) - raw_msg = rpc_common.deserialize_msg(rpc_envelope) - else: - raise rpc_common.UnsupportedRpcEnvelopeVersion( - _("Unsupported or unknown ZMQ envelope returned.")) - - responses = raw_msg['args']['response'] - # ZMQError trumps the Timeout error. - except zmq.ZMQError: - raise RPCException("ZMQ Socket Error") - except (IndexError, KeyError): - raise RPCException(_("RPC Message Invalid.")) - finally: - if 'msg_waiter' in vars(): - msg_waiter.close() - - # It seems we don't need to do all of the following, - # but perhaps it would be useful for multicall? - # One effect of this is that we're checking all - # responses for Exceptions. - for resp in responses: - if isinstance(resp, types.DictType) and 'exc' in resp: - raise rpc_common.deserialize_remote_exception(CONF, resp['exc']) - - return responses[-1] - - -def _multi_send(method, context, topic, msg, timeout=None, - envelope=False, _msg_id=None): - """ - Wraps the sending of messages, - dispatches to the matchmaker and sends - message to all relevant hosts. - """ - conf = CONF - LOG.debug(_("%(msg)s") % {'msg': ' '.join(map(pformat, (topic, msg)))}) - - queues = _get_matchmaker().queues(topic) - LOG.debug(_("Sending message(s) to: %s"), queues) - - # Don't stack if we have no matchmaker results - if len(queues) == 0: - LOG.warn(_("No matchmaker results. Not casting.")) - # While not strictly a timeout, callers know how to handle - # this exception and a timeout isn't too big a lie. - raise rpc_common.Timeout, "No match from matchmaker." - - # This supports brokerless fanout (addresses > 1) - for queue in queues: - (_topic, ip_addr) = queue - _addr = "tcp://%s:%s" % (ip_addr, conf.rpc_zmq_port) - - if method.__name__ == '_cast': - eventlet.spawn_n(method, _addr, context, - _topic, msg, timeout, envelope, - _msg_id) - return - return method(_addr, context, _topic, msg, timeout, - envelope) - - -def create_connection(conf, new=True): - return Connection(conf) - - -def multicall(conf, *args, **kwargs): - """Multiple calls.""" - return _multi_send(_call, *args, **kwargs) - - -def call(conf, *args, **kwargs): - """Send a message, expect a response.""" - data = _multi_send(_call, *args, **kwargs) - return data[-1] - - -def cast(conf, *args, **kwargs): - """Send a message expecting no reply.""" - _multi_send(_cast, *args, **kwargs) - - -def fanout_cast(conf, context, topic, msg, **kwargs): - """Send a message to all listening and expect no reply.""" - # NOTE(ewindisch): fanout~ is used because it avoid splitting on . - # and acts as a non-subtle hint to the matchmaker and ZmqProxy. - _multi_send(_cast, context, 'fanout~' + str(topic), msg, **kwargs) - - -def notify(conf, context, topic, msg, envelope): - """ - Send notification event. - Notifications are sent to topic-priority. - This differs from the AMQP drivers which send to topic.priority. - """ - # NOTE(ewindisch): dot-priority in rpc notifier does not - # work with our assumptions. - topic = topic.replace('.', '-') - cast(conf, context, topic, msg, envelope=envelope) - - -def cleanup(): - """Clean up resources in use by implementation.""" - global ZMQ_CTX - if ZMQ_CTX: - ZMQ_CTX.term() - ZMQ_CTX = None - - global matchmaker - matchmaker = None - - -def _get_ctxt(): - if not zmq: - raise ImportError("Failed to import eventlet.green.zmq") - - global ZMQ_CTX - if not ZMQ_CTX: - ZMQ_CTX = zmq.Context(CONF.rpc_zmq_contexts) - return ZMQ_CTX - - -def _get_matchmaker(*args, **kwargs): - global matchmaker - if not matchmaker: - matchmaker = importutils.import_object( - CONF.rpc_zmq_matchmaker, *args, **kwargs) - return matchmaker diff --git a/billingstack/openstack/common/rpc/matchmaker.py b/billingstack/openstack/common/rpc/matchmaker.py deleted file mode 100644 index 65da043..0000000 --- a/billingstack/openstack/common/rpc/matchmaker.py +++ /dev/null @@ -1,425 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 Cloudscaling Group, Inc -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -The MatchMaker classes should except a Topic or Fanout exchange key and -return keys for direct exchanges, per (approximate) AMQP parlance. -""" - -import contextlib -import itertools -import json - -import eventlet -from oslo.config import cfg - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging - - -matchmaker_opts = [ - # Matchmaker ring file - cfg.StrOpt('matchmaker_ringfile', - default='/etc/nova/matchmaker_ring.json', - help='Matchmaker ring file (JSON)'), - cfg.IntOpt('matchmaker_heartbeat_freq', - default='300', - help='Heartbeat frequency'), - cfg.IntOpt('matchmaker_heartbeat_ttl', - default='600', - help='Heartbeat time-to-live.'), -] - -CONF = cfg.CONF -CONF.register_opts(matchmaker_opts) -LOG = logging.getLogger(__name__) -contextmanager = contextlib.contextmanager - - -class MatchMakerException(Exception): - """Signified a match could not be found.""" - message = _("Match not found by MatchMaker.") - - -class Exchange(object): - """ - Implements lookups. - Subclass this to support hashtables, dns, etc. - """ - def __init__(self): - pass - - def run(self, key): - raise NotImplementedError() - - -class Binding(object): - """ - A binding on which to perform a lookup. - """ - def __init__(self): - pass - - def test(self, key): - raise NotImplementedError() - - -class MatchMakerBase(object): - """ - Match Maker Base Class. - Build off HeartbeatMatchMakerBase if building a - heartbeat-capable MatchMaker. - """ - def __init__(self): - # Array of tuples. Index [2] toggles negation, [3] is last-if-true - self.bindings = [] - - self.no_heartbeat_msg = _('Matchmaker does not implement ' - 'registration or heartbeat.') - - def register(self, key, host): - """ - Register a host on a backend. - Heartbeats, if applicable, may keepalive registration. - """ - pass - - def ack_alive(self, key, host): - """ - Acknowledge that a key.host is alive. - Used internally for updating heartbeats, - but may also be used publically to acknowledge - a system is alive (i.e. rpc message successfully - sent to host) - """ - pass - - def is_alive(self, topic, host): - """ - Checks if a host is alive. - """ - pass - - def expire(self, topic, host): - """ - Explicitly expire a host's registration. - """ - pass - - def send_heartbeats(self): - """ - Send all heartbeats. - Use start_heartbeat to spawn a heartbeat greenthread, - which loops this method. - """ - pass - - def unregister(self, key, host): - """ - Unregister a topic. - """ - pass - - def start_heartbeat(self): - """ - Spawn heartbeat greenthread. - """ - pass - - def stop_heartbeat(self): - """ - Destroys the heartbeat greenthread. - """ - pass - - def add_binding(self, binding, rule, last=True): - self.bindings.append((binding, rule, False, last)) - - #NOTE(ewindisch): kept the following method in case we implement the - # underlying support. - #def add_negate_binding(self, binding, rule, last=True): - # self.bindings.append((binding, rule, True, last)) - - def queues(self, key): - workers = [] - - # bit is for negate bindings - if we choose to implement it. - # last stops processing rules if this matches. - for (binding, exchange, bit, last) in self.bindings: - if binding.test(key): - workers.extend(exchange.run(key)) - - # Support last. - if last: - return workers - return workers - - -class HeartbeatMatchMakerBase(MatchMakerBase): - """ - Base for a heart-beat capable MatchMaker. - Provides common methods for registering, - unregistering, and maintaining heartbeats. - """ - def __init__(self): - self.hosts = set() - self._heart = None - self.host_topic = {} - - super(HeartbeatMatchMakerBase, self).__init__() - - def send_heartbeats(self): - """ - Send all heartbeats. - Use start_heartbeat to spawn a heartbeat greenthread, - which loops this method. - """ - for key, host in self.host_topic: - self.ack_alive(key, host) - - def ack_alive(self, key, host): - """ - Acknowledge that a host.topic is alive. - Used internally for updating heartbeats, - but may also be used publically to acknowledge - a system is alive (i.e. rpc message successfully - sent to host) - """ - raise NotImplementedError("Must implement ack_alive") - - def backend_register(self, key, host): - """ - Implements registration logic. - Called by register(self,key,host) - """ - raise NotImplementedError("Must implement backend_register") - - def backend_unregister(self, key, key_host): - """ - Implements de-registration logic. - Called by unregister(self,key,host) - """ - raise NotImplementedError("Must implement backend_unregister") - - def register(self, key, host): - """ - Register a host on a backend. - Heartbeats, if applicable, may keepalive registration. - """ - self.hosts.add(host) - self.host_topic[(key, host)] = host - key_host = '.'.join((key, host)) - - self.backend_register(key, key_host) - - self.ack_alive(key, host) - - def unregister(self, key, host): - """ - Unregister a topic. - """ - if (key, host) in self.host_topic: - del self.host_topic[(key, host)] - - self.hosts.discard(host) - self.backend_unregister(key, '.'.join((key, host))) - - LOG.info(_("Matchmaker unregistered: %s, %s" % (key, host))) - - def start_heartbeat(self): - """ - Implementation of MatchMakerBase.start_heartbeat - Launches greenthread looping send_heartbeats(), - yielding for CONF.matchmaker_heartbeat_freq seconds - between iterations. - """ - if len(self.hosts) == 0: - raise MatchMakerException( - _("Register before starting heartbeat.")) - - def do_heartbeat(): - while True: - self.send_heartbeats() - eventlet.sleep(CONF.matchmaker_heartbeat_freq) - - self._heart = eventlet.spawn(do_heartbeat) - - def stop_heartbeat(self): - """ - Destroys the heartbeat greenthread. - """ - if self._heart: - self._heart.kill() - - -class DirectBinding(Binding): - """ - Specifies a host in the key via a '.' character - Although dots are used in the key, the behavior here is - that it maps directly to a host, thus direct. - """ - def test(self, key): - if '.' in key: - return True - return False - - -class TopicBinding(Binding): - """ - Where a 'bare' key without dots. - AMQP generally considers topic exchanges to be those *with* dots, - but we deviate here in terminology as the behavior here matches - that of a topic exchange (whereas where there are dots, behavior - matches that of a direct exchange. - """ - def test(self, key): - if '.' not in key: - return True - return False - - -class FanoutBinding(Binding): - """Match on fanout keys, where key starts with 'fanout.' string.""" - def test(self, key): - if key.startswith('fanout~'): - return True - return False - - -class StubExchange(Exchange): - """Exchange that does nothing.""" - def run(self, key): - return [(key, None)] - - -class RingExchange(Exchange): - """ - Match Maker where hosts are loaded from a static file containing - a hashmap (JSON formatted). - - __init__ takes optional ring dictionary argument, otherwise - loads the ringfile from CONF.mathcmaker_ringfile. - """ - def __init__(self, ring=None): - super(RingExchange, self).__init__() - - if ring: - self.ring = ring - else: - fh = open(CONF.matchmaker_ringfile, 'r') - self.ring = json.load(fh) - fh.close() - - self.ring0 = {} - for k in self.ring.keys(): - self.ring0[k] = itertools.cycle(self.ring[k]) - - def _ring_has(self, key): - if key in self.ring0: - return True - return False - - -class RoundRobinRingExchange(RingExchange): - """A Topic Exchange based on a hashmap.""" - def __init__(self, ring=None): - super(RoundRobinRingExchange, self).__init__(ring) - - def run(self, key): - if not self._ring_has(key): - LOG.warn( - _("No key defining hosts for topic '%s', " - "see ringfile") % (key, ) - ) - return [] - host = next(self.ring0[key]) - return [(key + '.' + host, host)] - - -class FanoutRingExchange(RingExchange): - """Fanout Exchange based on a hashmap.""" - def __init__(self, ring=None): - super(FanoutRingExchange, self).__init__(ring) - - def run(self, key): - # Assume starts with "fanout~", strip it for lookup. - nkey = key.split('fanout~')[1:][0] - if not self._ring_has(nkey): - LOG.warn( - _("No key defining hosts for topic '%s', " - "see ringfile") % (nkey, ) - ) - return [] - return map(lambda x: (key + '.' + x, x), self.ring[nkey]) - - -class LocalhostExchange(Exchange): - """Exchange where all direct topics are local.""" - def __init__(self, host='localhost'): - self.host = host - super(Exchange, self).__init__() - - def run(self, key): - return [('.'.join((key.split('.')[0], self.host)), self.host)] - - -class DirectExchange(Exchange): - """ - Exchange where all topic keys are split, sending to second half. - i.e. "compute.host" sends a message to "compute.host" running on "host" - """ - def __init__(self): - super(Exchange, self).__init__() - - def run(self, key): - e = key.split('.', 1)[1] - return [(key, e)] - - -class MatchMakerRing(MatchMakerBase): - """ - Match Maker where hosts are loaded from a static hashmap. - """ - def __init__(self, ring=None): - super(MatchMakerRing, self).__init__() - self.add_binding(FanoutBinding(), FanoutRingExchange(ring)) - self.add_binding(DirectBinding(), DirectExchange()) - self.add_binding(TopicBinding(), RoundRobinRingExchange(ring)) - - -class MatchMakerLocalhost(MatchMakerBase): - """ - Match Maker where all bare topics resolve to localhost. - Useful for testing. - """ - def __init__(self, host='localhost'): - super(MatchMakerLocalhost, self).__init__() - self.add_binding(FanoutBinding(), LocalhostExchange(host)) - self.add_binding(DirectBinding(), DirectExchange()) - self.add_binding(TopicBinding(), LocalhostExchange(host)) - - -class MatchMakerStub(MatchMakerBase): - """ - Match Maker where topics are untouched. - Useful for testing, or for AMQP/brokered queues. - Will not work where knowledge of hosts is known (i.e. zeromq) - """ - def __init__(self): - super(MatchMakerLocalhost, self).__init__() - - self.add_binding(FanoutBinding(), StubExchange()) - self.add_binding(DirectBinding(), StubExchange()) - self.add_binding(TopicBinding(), StubExchange()) diff --git a/billingstack/openstack/common/rpc/matchmaker_redis.py b/billingstack/openstack/common/rpc/matchmaker_redis.py deleted file mode 100644 index 4247d6d..0000000 --- a/billingstack/openstack/common/rpc/matchmaker_redis.py +++ /dev/null @@ -1,149 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2013 Cloudscaling Group, Inc -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -The MatchMaker classes should accept a Topic or Fanout exchange key and -return keys for direct exchanges, per (approximate) AMQP parlance. -""" - -from oslo.config import cfg - -from billingstack.openstack.common import importutils -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.rpc import matchmaker as mm_common - -redis = importutils.try_import('redis') - - -matchmaker_redis_opts = [ - cfg.StrOpt('host', - default='127.0.0.1', - help='Host to locate redis'), - cfg.IntOpt('port', - default=6379, - help='Use this port to connect to redis host.'), - cfg.StrOpt('password', - default=None, - help='Password for Redis server. (optional)'), -] - -CONF = cfg.CONF -opt_group = cfg.OptGroup(name='matchmaker_redis', - title='Options for Redis-based MatchMaker') -CONF.register_group(opt_group) -CONF.register_opts(matchmaker_redis_opts, opt_group) -LOG = logging.getLogger(__name__) - - -class RedisExchange(mm_common.Exchange): - def __init__(self, matchmaker): - self.matchmaker = matchmaker - self.redis = matchmaker.redis - super(RedisExchange, self).__init__() - - -class RedisTopicExchange(RedisExchange): - """ - Exchange where all topic keys are split, sending to second half. - i.e. "compute.host" sends a message to "compute" running on "host" - """ - def run(self, topic): - while True: - member_name = self.redis.srandmember(topic) - - if not member_name: - # If this happens, there are no - # longer any members. - break - - if not self.matchmaker.is_alive(topic, member_name): - continue - - host = member_name.split('.', 1)[1] - return [(member_name, host)] - return [] - - -class RedisFanoutExchange(RedisExchange): - """ - Return a list of all hosts. - """ - def run(self, topic): - topic = topic.split('~', 1)[1] - hosts = self.redis.smembers(topic) - good_hosts = filter( - lambda host: self.matchmaker.is_alive(topic, host), hosts) - - return [(x, x.split('.', 1)[1]) for x in good_hosts] - - -class MatchMakerRedis(mm_common.HeartbeatMatchMakerBase): - """ - MatchMaker registering and looking-up hosts with a Redis server. - """ - def __init__(self): - super(MatchMakerRedis, self).__init__() - - if not redis: - raise ImportError("Failed to import module redis.") - - self.redis = redis.StrictRedis( - host=CONF.matchmaker_redis.host, - port=CONF.matchmaker_redis.port, - password=CONF.matchmaker_redis.password) - - self.add_binding(mm_common.FanoutBinding(), RedisFanoutExchange(self)) - self.add_binding(mm_common.DirectBinding(), mm_common.DirectExchange()) - self.add_binding(mm_common.TopicBinding(), RedisTopicExchange(self)) - - def ack_alive(self, key, host): - topic = "%s.%s" % (key, host) - if not self.redis.expire(topic, CONF.matchmaker_heartbeat_ttl): - # If we could not update the expiration, the key - # might have been pruned. Re-register, creating a new - # key in Redis. - self.register(self.topic_host[host], host) - - def is_alive(self, topic, host): - if self.redis.ttl(host) == -1: - self.expire(topic, host) - return False - return True - - def expire(self, topic, host): - with self.redis.pipeline() as pipe: - pipe.multi() - pipe.delete(host) - pipe.srem(topic, host) - pipe.execute() - - def backend_register(self, key, key_host): - with self.redis.pipeline() as pipe: - pipe.multi() - pipe.sadd(key, key_host) - - # No value is needed, we just - # care if it exists. Sets aren't viable - # because only keys can expire. - pipe.set(key_host, '') - - pipe.execute() - - def backend_unregister(self, key, key_host): - with self.redis.pipeline() as pipe: - pipe.multi() - pipe.srem(key, key_host) - pipe.delete(key_host) - pipe.execute() diff --git a/billingstack/openstack/common/rpc/proxy.py b/billingstack/openstack/common/rpc/proxy.py deleted file mode 100644 index 0eaa968..0000000 --- a/billingstack/openstack/common/rpc/proxy.py +++ /dev/null @@ -1,165 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -A helper class for proxy objects to remote APIs. - -For more information about rpc API version numbers, see: - rpc/dispatcher.py -""" - - -from billingstack.openstack.common import rpc - - -class RpcProxy(object): - """A helper class for rpc clients. - - This class is a wrapper around the RPC client API. It allows you to - specify the topic and API version in a single place. This is intended to - be used as a base class for a class that implements the client side of an - rpc API. - """ - - def __init__(self, topic, default_version): - """Initialize an RpcProxy. - - :param topic: The topic to use for all messages. - :param default_version: The default API version to request in all - outgoing messages. This can be overridden on a per-message - basis. - """ - self.topic = topic - self.default_version = default_version - super(RpcProxy, self).__init__() - - def _set_version(self, msg, vers): - """Helper method to set the version in a message. - - :param msg: The message having a version added to it. - :param vers: The version number to add to the message. - """ - msg['version'] = vers if vers else self.default_version - - def _get_topic(self, topic): - """Return the topic to use for a message.""" - return topic if topic else self.topic - - @staticmethod - def make_msg(method, **kwargs): - return {'method': method, 'args': kwargs} - - def call(self, context, msg, topic=None, version=None, timeout=None): - """rpc.call() a remote method. - - :param context: The request context - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param timeout: (Optional) A timeout to use when waiting for the - response. If no timeout is specified, a default timeout will be - used that is usually sufficient. - :param version: (Optional) Override the requested API version in this - message. - - :returns: The return value from the remote method. - """ - self._set_version(msg, version) - return rpc.call(context, self._get_topic(topic), msg, timeout) - - def multicall(self, context, msg, topic=None, version=None, timeout=None): - """rpc.multicall() a remote method. - - :param context: The request context - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param timeout: (Optional) A timeout to use when waiting for the - response. If no timeout is specified, a default timeout will be - used that is usually sufficient. - :param version: (Optional) Override the requested API version in this - message. - - :returns: An iterator that lets you process each of the returned values - from the remote method as they arrive. - """ - self._set_version(msg, version) - return rpc.multicall(context, self._get_topic(topic), msg, timeout) - - def cast(self, context, msg, topic=None, version=None): - """rpc.cast() a remote method. - - :param context: The request context - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param version: (Optional) Override the requested API version in this - message. - - :returns: None. rpc.cast() does not wait on any return value from the - remote method. - """ - self._set_version(msg, version) - rpc.cast(context, self._get_topic(topic), msg) - - def fanout_cast(self, context, msg, topic=None, version=None): - """rpc.fanout_cast() a remote method. - - :param context: The request context - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param version: (Optional) Override the requested API version in this - message. - - :returns: None. rpc.fanout_cast() does not wait on any return value - from the remote method. - """ - self._set_version(msg, version) - rpc.fanout_cast(context, self._get_topic(topic), msg) - - def cast_to_server(self, context, server_params, msg, topic=None, - version=None): - """rpc.cast_to_server() a remote method. - - :param context: The request context - :param server_params: Server parameters. See rpc.cast_to_server() for - details. - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param version: (Optional) Override the requested API version in this - message. - - :returns: None. rpc.cast_to_server() does not wait on any - return values. - """ - self._set_version(msg, version) - rpc.cast_to_server(context, server_params, self._get_topic(topic), msg) - - def fanout_cast_to_server(self, context, server_params, msg, topic=None, - version=None): - """rpc.fanout_cast_to_server() a remote method. - - :param context: The request context - :param server_params: Server parameters. See rpc.cast_to_server() for - details. - :param msg: The message to send, including the method and args. - :param topic: Override the topic for this message. - :param version: (Optional) Override the requested API version in this - message. - - :returns: None. rpc.fanout_cast_to_server() does not wait on any - return values. - """ - self._set_version(msg, version) - rpc.fanout_cast_to_server(context, server_params, - self._get_topic(topic), msg) diff --git a/billingstack/openstack/common/rpc/service.py b/billingstack/openstack/common/rpc/service.py deleted file mode 100644 index c38e3c2..0000000 --- a/billingstack/openstack/common/rpc/service.py +++ /dev/null @@ -1,75 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# Copyright 2011 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc -from billingstack.openstack.common.rpc import dispatcher as rpc_dispatcher -from billingstack.openstack.common import service - - -LOG = logging.getLogger(__name__) - - -class Service(service.Service): - """Service object for binaries running on hosts. - - A service enables rpc by listening to queues based on topic and host.""" - def __init__(self, host, topic, manager=None): - super(Service, self).__init__() - self.host = host - self.topic = topic - if manager is None: - self.manager = self - else: - self.manager = manager - - def start(self): - super(Service, self).start() - - self.conn = rpc.create_connection(new=True) - LOG.debug(_("Creating Consumer connection for Service %s") % - self.topic) - - dispatcher = rpc_dispatcher.RpcDispatcher([self.manager]) - - # Share this same connection for these Consumers - self.conn.create_consumer(self.topic, dispatcher, fanout=False) - - node_topic = '%s.%s' % (self.topic, self.host) - self.conn.create_consumer(node_topic, dispatcher, fanout=False) - - self.conn.create_consumer(self.topic, dispatcher, fanout=True) - - # Hook to allow the manager to do other initializations after - # the rpc connection is created. - if callable(getattr(self.manager, 'initialize_service_hook', None)): - self.manager.initialize_service_hook(self) - - # Consume from all consumers in a thread - self.conn.consume_in_thread_group(self.tg) - - def stop(self): - # Try to shut the connection down, but if we get any sort of - # errors, go ahead and ignore them.. as we're shutting down anyway - try: - self.conn.close() - except Exception: - pass - super(Service, self).stop() diff --git a/billingstack/openstack/common/service.py b/billingstack/openstack/common/service.py deleted file mode 100644 index 535e65c..0000000 --- a/billingstack/openstack/common/service.py +++ /dev/null @@ -1,332 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# Copyright 2011 Justin Santa Barbara -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Generic Node base class for all workers that run on hosts.""" - -import errno -import os -import random -import signal -import sys -import time - -import eventlet -import logging as std_logging -from oslo.config import cfg - -from billingstack.openstack.common import eventlet_backdoor -from billingstack.openstack.common.gettextutils import _ -from billingstack.openstack.common import importutils -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import threadgroup - - -rpc = importutils.try_import('billingstack.openstack.common.rpc') -CONF = cfg.CONF -LOG = logging.getLogger(__name__) - - -class Launcher(object): - """Launch one or more services and wait for them to complete.""" - - def __init__(self): - """Initialize the service launcher. - - :returns: None - - """ - self._services = threadgroup.ThreadGroup() - eventlet_backdoor.initialize_if_enabled() - - @staticmethod - def run_service(service): - """Start and wait for a service to finish. - - :param service: service to run and wait for. - :returns: None - - """ - service.start() - service.wait() - - def launch_service(self, service): - """Load and start the given service. - - :param service: The service you would like to start. - :returns: None - - """ - self._services.add_thread(self.run_service, service) - - def stop(self): - """Stop all services which are currently running. - - :returns: None - - """ - self._services.stop() - - def wait(self): - """Waits until all services have been stopped, and then returns. - - :returns: None - - """ - self._services.wait() - - -class SignalExit(SystemExit): - def __init__(self, signo, exccode=1): - super(SignalExit, self).__init__(exccode) - self.signo = signo - - -class ServiceLauncher(Launcher): - def _handle_signal(self, signo, frame): - # Allow the process to be killed again and die from natural causes - signal.signal(signal.SIGTERM, signal.SIG_DFL) - signal.signal(signal.SIGINT, signal.SIG_DFL) - - raise SignalExit(signo) - - def wait(self): - signal.signal(signal.SIGTERM, self._handle_signal) - signal.signal(signal.SIGINT, self._handle_signal) - - LOG.debug(_('Full set of CONF:')) - CONF.log_opt_values(LOG, std_logging.DEBUG) - - status = None - try: - super(ServiceLauncher, self).wait() - except SignalExit as exc: - signame = {signal.SIGTERM: 'SIGTERM', - signal.SIGINT: 'SIGINT'}[exc.signo] - LOG.info(_('Caught %s, exiting'), signame) - status = exc.code - except SystemExit as exc: - status = exc.code - finally: - if rpc: - rpc.cleanup() - self.stop() - return status - - -class ServiceWrapper(object): - def __init__(self, service, workers): - self.service = service - self.workers = workers - self.children = set() - self.forktimes = [] - - -class ProcessLauncher(object): - def __init__(self): - self.children = {} - self.sigcaught = None - self.running = True - rfd, self.writepipe = os.pipe() - self.readpipe = eventlet.greenio.GreenPipe(rfd, 'r') - - signal.signal(signal.SIGTERM, self._handle_signal) - signal.signal(signal.SIGINT, self._handle_signal) - - def _handle_signal(self, signo, frame): - self.sigcaught = signo - self.running = False - - # Allow the process to be killed again and die from natural causes - signal.signal(signal.SIGTERM, signal.SIG_DFL) - signal.signal(signal.SIGINT, signal.SIG_DFL) - - def _pipe_watcher(self): - # This will block until the write end is closed when the parent - # dies unexpectedly - self.readpipe.read() - - LOG.info(_('Parent process has died unexpectedly, exiting')) - - sys.exit(1) - - def _child_process(self, service): - # Setup child signal handlers differently - def _sigterm(*args): - signal.signal(signal.SIGTERM, signal.SIG_DFL) - raise SignalExit(signal.SIGTERM) - - signal.signal(signal.SIGTERM, _sigterm) - # Block SIGINT and let the parent send us a SIGTERM - signal.signal(signal.SIGINT, signal.SIG_IGN) - - # Reopen the eventlet hub to make sure we don't share an epoll - # fd with parent and/or siblings, which would be bad - eventlet.hubs.use_hub() - - # Close write to ensure only parent has it open - os.close(self.writepipe) - # Create greenthread to watch for parent to close pipe - eventlet.spawn_n(self._pipe_watcher) - - # Reseed random number generator - random.seed() - - launcher = Launcher() - launcher.run_service(service) - - def _start_child(self, wrap): - if len(wrap.forktimes) > wrap.workers: - # Limit ourselves to one process a second (over the period of - # number of workers * 1 second). This will allow workers to - # start up quickly but ensure we don't fork off children that - # die instantly too quickly. - if time.time() - wrap.forktimes[0] < wrap.workers: - LOG.info(_('Forking too fast, sleeping')) - time.sleep(1) - - wrap.forktimes.pop(0) - - wrap.forktimes.append(time.time()) - - pid = os.fork() - if pid == 0: - # NOTE(johannes): All exceptions are caught to ensure this - # doesn't fallback into the loop spawning children. It would - # be bad for a child to spawn more children. - status = 0 - try: - self._child_process(wrap.service) - except SignalExit as exc: - signame = {signal.SIGTERM: 'SIGTERM', - signal.SIGINT: 'SIGINT'}[exc.signo] - LOG.info(_('Caught %s, exiting'), signame) - status = exc.code - except SystemExit as exc: - status = exc.code - except BaseException: - LOG.exception(_('Unhandled exception')) - status = 2 - finally: - wrap.service.stop() - - os._exit(status) - - LOG.info(_('Started child %d'), pid) - - wrap.children.add(pid) - self.children[pid] = wrap - - return pid - - def launch_service(self, service, workers=1): - wrap = ServiceWrapper(service, workers) - - LOG.info(_('Starting %d workers'), wrap.workers) - while self.running and len(wrap.children) < wrap.workers: - self._start_child(wrap) - - def _wait_child(self): - try: - # Don't block if no child processes have exited - pid, status = os.waitpid(0, os.WNOHANG) - if not pid: - return None - except OSError as exc: - if exc.errno not in (errno.EINTR, errno.ECHILD): - raise - return None - - if os.WIFSIGNALED(status): - sig = os.WTERMSIG(status) - LOG.info(_('Child %(pid)d killed by signal %(sig)d'), - dict(pid=pid, sig=sig)) - else: - code = os.WEXITSTATUS(status) - LOG.info(_('Child %(pid)s exited with status %(code)d'), - dict(pid=pid, code=code)) - - if pid not in self.children: - LOG.warning(_('pid %d not in child list'), pid) - return None - - wrap = self.children.pop(pid) - wrap.children.remove(pid) - return wrap - - def wait(self): - """Loop waiting on children to die and respawning as necessary""" - - LOG.debug(_('Full set of CONF:')) - CONF.log_opt_values(LOG, std_logging.DEBUG) - - while self.running: - wrap = self._wait_child() - if not wrap: - # Yield to other threads if no children have exited - # Sleep for a short time to avoid excessive CPU usage - # (see bug #1095346) - eventlet.greenthread.sleep(.01) - continue - - while self.running and len(wrap.children) < wrap.workers: - self._start_child(wrap) - - if self.sigcaught: - signame = {signal.SIGTERM: 'SIGTERM', - signal.SIGINT: 'SIGINT'}[self.sigcaught] - LOG.info(_('Caught %s, stopping children'), signame) - - for pid in self.children: - try: - os.kill(pid, signal.SIGTERM) - except OSError as exc: - if exc.errno != errno.ESRCH: - raise - - # Wait for children to die - if self.children: - LOG.info(_('Waiting on %d children to exit'), len(self.children)) - while self.children: - self._wait_child() - - -class Service(object): - """Service object for binaries running on hosts.""" - - def __init__(self, threads=1000): - self.tg = threadgroup.ThreadGroup(threads) - - def start(self): - pass - - def stop(self): - self.tg.stop() - - def wait(self): - self.tg.wait() - - -def launch(service, workers=None): - if workers: - launcher = ProcessLauncher() - launcher.launch_service(service, workers=workers) - else: - launcher = ServiceLauncher() - launcher.launch_service(service) - return launcher diff --git a/billingstack/openstack/common/setup.py b/billingstack/openstack/common/setup.py deleted file mode 100644 index 80a0ece..0000000 --- a/billingstack/openstack/common/setup.py +++ /dev/null @@ -1,359 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# Copyright 2012-2013 Hewlett-Packard Development Company, L.P. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Utilities with minimum-depends for use in setup.py -""" - -import email -import os -import re -import subprocess -import sys - -from setuptools.command import sdist - - -def parse_mailmap(mailmap='.mailmap'): - mapping = {} - if os.path.exists(mailmap): - with open(mailmap, 'r') as fp: - for l in fp: - try: - canonical_email, alias = re.match( - r'[^#]*?(<.+>).*(<.+>).*', l).groups() - except AttributeError: - continue - mapping[alias] = canonical_email - return mapping - - -def _parse_git_mailmap(git_dir, mailmap='.mailmap'): - mailmap = os.path.join(os.path.dirname(git_dir), mailmap) - return parse_mailmap(mailmap) - - -def canonicalize_emails(changelog, mapping): - """Takes in a string and an email alias mapping and replaces all - instances of the aliases in the string with their real email. - """ - for alias, email_address in mapping.iteritems(): - changelog = changelog.replace(alias, email_address) - return changelog - - -# Get requirements from the first file that exists -def get_reqs_from_files(requirements_files): - for requirements_file in requirements_files: - if os.path.exists(requirements_file): - with open(requirements_file, 'r') as fil: - return fil.read().split('\n') - return [] - - -def parse_requirements(requirements_files=['requirements.txt', - 'tools/pip-requires']): - requirements = [] - for line in get_reqs_from_files(requirements_files): - # For the requirements list, we need to inject only the portion - # after egg= so that distutils knows the package it's looking for - # such as: - # -e git://github.com/openstack/nova/master#egg=nova - if re.match(r'\s*-e\s+', line): - requirements.append(re.sub(r'\s*-e\s+.*#egg=(.*)$', r'\1', - line)) - # such as: - # http://github.com/openstack/nova/zipball/master#egg=nova - elif re.match(r'\s*https?:', line): - requirements.append(re.sub(r'\s*https?:.*#egg=(.*)$', r'\1', - line)) - # -f lines are for index locations, and don't get used here - elif re.match(r'\s*-f\s+', line): - pass - # argparse is part of the standard library starting with 2.7 - # adding it to the requirements list screws distro installs - elif line == 'argparse' and sys.version_info >= (2, 7): - pass - else: - requirements.append(line) - - return requirements - - -def parse_dependency_links(requirements_files=['requirements.txt', - 'tools/pip-requires']): - dependency_links = [] - # dependency_links inject alternate locations to find packages listed - # in requirements - for line in get_reqs_from_files(requirements_files): - # skip comments and blank lines - if re.match(r'(\s*#)|(\s*$)', line): - continue - # lines with -e or -f need the whole line, minus the flag - if re.match(r'\s*-[ef]\s+', line): - dependency_links.append(re.sub(r'\s*-[ef]\s+', '', line)) - # lines that are only urls can go in unmolested - elif re.match(r'\s*https?:', line): - dependency_links.append(line) - return dependency_links - - -def _run_shell_command(cmd, throw_on_error=False): - if os.name == 'nt': - output = subprocess.Popen(["cmd.exe", "/C", cmd], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - else: - output = subprocess.Popen(["/bin/sh", "-c", cmd], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - out = output.communicate() - if output.returncode and throw_on_error: - raise Exception("%s returned %d" % cmd, output.returncode) - if len(out) == 0: - return None - if len(out[0].strip()) == 0: - return None - return out[0].strip() - - -def _get_git_directory(): - parent_dir = os.path.dirname(__file__) - while True: - git_dir = os.path.join(parent_dir, '.git') - if os.path.exists(git_dir): - return git_dir - parent_dir, child = os.path.split(parent_dir) - if not child: # reached to root dir - return None - - -def write_git_changelog(): - """Write a changelog based on the git changelog.""" - new_changelog = 'ChangeLog' - git_dir = _get_git_directory() - if not os.getenv('SKIP_WRITE_GIT_CHANGELOG'): - if git_dir: - git_log_cmd = 'git --git-dir=%s log --stat' % git_dir - changelog = _run_shell_command(git_log_cmd) - mailmap = _parse_git_mailmap(git_dir) - with open(new_changelog, "w") as changelog_file: - changelog_file.write(canonicalize_emails(changelog, mailmap)) - else: - open(new_changelog, 'w').close() - - -def generate_authors(): - """Create AUTHORS file using git commits.""" - jenkins_email = 'jenkins@review.(openstack|stackforge).org' - old_authors = 'AUTHORS.in' - new_authors = 'AUTHORS' - git_dir = _get_git_directory() - if not os.getenv('SKIP_GENERATE_AUTHORS'): - if git_dir: - # don't include jenkins email address in AUTHORS file - git_log_cmd = ("git --git-dir=" + git_dir + - " log --format='%aN <%aE>' | sort -u | " - "egrep -v '" + jenkins_email + "'") - changelog = _run_shell_command(git_log_cmd) - mailmap = _parse_git_mailmap(git_dir) - with open(new_authors, 'w') as new_authors_fh: - new_authors_fh.write(canonicalize_emails(changelog, mailmap)) - if os.path.exists(old_authors): - with open(old_authors, "r") as old_authors_fh: - new_authors_fh.write('\n' + old_authors_fh.read()) - else: - open(new_authors, 'w').close() - - -_rst_template = """%(heading)s -%(underline)s - -.. automodule:: %(module)s - :members: - :undoc-members: - :show-inheritance: -""" - - -def get_cmdclass(): - """Return dict of commands to run from setup.py.""" - - cmdclass = dict() - - def _find_modules(arg, dirname, files): - for filename in files: - if filename.endswith('.py') and filename != '__init__.py': - arg["%s.%s" % (dirname.replace('/', '.'), - filename[:-3])] = True - - class LocalSDist(sdist.sdist): - """Builds the ChangeLog and Authors files from VC first.""" - - def run(self): - write_git_changelog() - generate_authors() - # sdist.sdist is an old style class, can't use super() - sdist.sdist.run(self) - - cmdclass['sdist'] = LocalSDist - - # If Sphinx is installed on the box running setup.py, - # enable setup.py to build the documentation, otherwise, - # just ignore it - try: - from sphinx.setup_command import BuildDoc - - class LocalBuildDoc(BuildDoc): - - builders = ['html', 'man'] - - def generate_autoindex(self): - print "**Autodocumenting from %s" % os.path.abspath(os.curdir) - modules = {} - option_dict = self.distribution.get_option_dict('build_sphinx') - source_dir = os.path.join(option_dict['source_dir'][1], 'api') - if not os.path.exists(source_dir): - os.makedirs(source_dir) - for pkg in self.distribution.packages: - if '.' not in pkg: - os.path.walk(pkg, _find_modules, modules) - module_list = modules.keys() - module_list.sort() - autoindex_filename = os.path.join(source_dir, 'autoindex.rst') - with open(autoindex_filename, 'w') as autoindex: - autoindex.write(""".. toctree:: - :maxdepth: 1 - -""") - for module in module_list: - output_filename = os.path.join(source_dir, - "%s.rst" % module) - heading = "The :mod:`%s` Module" % module - underline = "=" * len(heading) - values = dict(module=module, heading=heading, - underline=underline) - - print "Generating %s" % output_filename - with open(output_filename, 'w') as output_file: - output_file.write(_rst_template % values) - autoindex.write(" %s.rst\n" % module) - - def run(self): - if not os.getenv('SPHINX_DEBUG'): - self.generate_autoindex() - - for builder in self.builders: - self.builder = builder - self.finalize_options() - self.project = self.distribution.get_name() - self.version = self.distribution.get_version() - self.release = self.distribution.get_version() - BuildDoc.run(self) - - class LocalBuildLatex(LocalBuildDoc): - builders = ['latex'] - - cmdclass['build_sphinx'] = LocalBuildDoc - cmdclass['build_sphinx_latex'] = LocalBuildLatex - except ImportError: - pass - - return cmdclass - - -def _get_revno(git_dir): - """Return the number of commits since the most recent tag. - - We use git-describe to find this out, but if there are no - tags then we fall back to counting commits since the beginning - of time. - """ - describe = _run_shell_command( - "git --git-dir=%s describe --always" % git_dir) - if "-" in describe: - return describe.rsplit("-", 2)[-2] - - # no tags found - revlist = _run_shell_command( - "git --git-dir=%s rev-list --abbrev-commit HEAD" % git_dir) - return len(revlist.splitlines()) - - -def _get_version_from_git(pre_version): - """Return a version which is equal to the tag that's on the current - revision if there is one, or tag plus number of additional revisions - if the current revision has no tag.""" - - git_dir = _get_git_directory() - if git_dir: - if pre_version: - try: - return _run_shell_command( - "git --git-dir=" + git_dir + " describe --exact-match", - throw_on_error=True).replace('-', '.') - except Exception: - sha = _run_shell_command( - "git --git-dir=" + git_dir + " log -n1 --pretty=format:%h") - return "%s.a%s.g%s" % (pre_version, _get_revno(git_dir), sha) - else: - return _run_shell_command( - "git --git-dir=" + git_dir + " describe --always").replace( - '-', '.') - return None - - -def _get_version_from_pkg_info(package_name): - """Get the version from PKG-INFO file if we can.""" - try: - pkg_info_file = open('PKG-INFO', 'r') - except (IOError, OSError): - return None - try: - pkg_info = email.message_from_file(pkg_info_file) - except email.MessageError: - return None - # Check to make sure we're in our own dir - if pkg_info.get('Name', None) != package_name: - return None - return pkg_info.get('Version', None) - - -def get_version(package_name, pre_version=None): - """Get the version of the project. First, try getting it from PKG-INFO, if - it exists. If it does, that means we're in a distribution tarball or that - install has happened. Otherwise, if there is no PKG-INFO file, pull the - version from git. - - We do not support setup.py version sanity in git archive tarballs, nor do - we support packagers directly sucking our git repo into theirs. We expect - that a source tarball be made from our git repo - or that if someone wants - to make a source tarball from a fork of our repo with additional tags in it - that they understand and desire the results of doing that. - """ - version = os.environ.get("OSLO_PACKAGE_VERSION", None) - if version: - return version - version = _get_version_from_pkg_info(package_name) - if version: - return version - version = _get_version_from_git(pre_version) - if version: - return version - raise Exception("Versioning for this project requires either an sdist" - " tarball, or access to an upstream git repository.") diff --git a/billingstack/openstack/common/threadgroup.py b/billingstack/openstack/common/threadgroup.py deleted file mode 100644 index 6895775..0000000 --- a/billingstack/openstack/common/threadgroup.py +++ /dev/null @@ -1,114 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Red Hat, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from eventlet import greenlet -from eventlet import greenpool -from eventlet import greenthread - -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import loopingcall - - -LOG = logging.getLogger(__name__) - - -def _thread_done(gt, *args, **kwargs): - """ Callback function to be passed to GreenThread.link() when we spawn() - Calls the :class:`ThreadGroup` to notify if. - - """ - kwargs['group'].thread_done(kwargs['thread']) - - -class Thread(object): - """ Wrapper around a greenthread, that holds a reference to the - :class:`ThreadGroup`. The Thread will notify the :class:`ThreadGroup` when - it has done so it can be removed from the threads list. - """ - def __init__(self, thread, group): - self.thread = thread - self.thread.link(_thread_done, group=group, thread=self) - - def stop(self): - self.thread.kill() - - def wait(self): - return self.thread.wait() - - -class ThreadGroup(object): - """ The point of the ThreadGroup classis to: - - * keep track of timers and greenthreads (making it easier to stop them - when need be). - * provide an easy API to add timers. - """ - def __init__(self, thread_pool_size=10): - self.pool = greenpool.GreenPool(thread_pool_size) - self.threads = [] - self.timers = [] - - def add_timer(self, interval, callback, initial_delay=None, - *args, **kwargs): - pulse = loopingcall.LoopingCall(callback, *args, **kwargs) - pulse.start(interval=interval, - initial_delay=initial_delay) - self.timers.append(pulse) - - def add_thread(self, callback, *args, **kwargs): - gt = self.pool.spawn(callback, *args, **kwargs) - th = Thread(gt, self) - self.threads.append(th) - - def thread_done(self, thread): - self.threads.remove(thread) - - def stop(self): - current = greenthread.getcurrent() - for x in self.threads: - if x is current: - # don't kill the current thread. - continue - try: - x.stop() - except Exception as ex: - LOG.exception(ex) - - for x in self.timers: - try: - x.stop() - except Exception as ex: - LOG.exception(ex) - self.timers = [] - - def wait(self): - for x in self.timers: - try: - x.wait() - except greenlet.GreenletExit: - pass - except Exception as ex: - LOG.exception(ex) - current = greenthread.getcurrent() - for x in self.threads: - if x is current: - continue - try: - x.wait() - except greenlet.GreenletExit: - pass - except Exception as ex: - LOG.exception(ex) diff --git a/billingstack/openstack/common/timeutils.py b/billingstack/openstack/common/timeutils.py deleted file mode 100644 index e2c2740..0000000 --- a/billingstack/openstack/common/timeutils.py +++ /dev/null @@ -1,182 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Time related utilities and helper functions. -""" - -import calendar -import datetime - -import iso8601 - - -TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" -PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" - - -def isotime(at=None): - """Stringify time in ISO 8601 format""" - if not at: - at = utcnow() - str = at.strftime(TIME_FORMAT) - tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' - str += ('Z' if tz == 'UTC' else tz) - return str - - -def parse_isotime(timestr): - """Parse time from ISO 8601 format""" - try: - return iso8601.parse_date(timestr) - except iso8601.ParseError as e: - raise ValueError(e.message) - except TypeError as e: - raise ValueError(e.message) - - -def strtime(at=None, fmt=PERFECT_TIME_FORMAT): - """Returns formatted utcnow.""" - if not at: - at = utcnow() - return at.strftime(fmt) - - -def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT): - """Turn a formatted time back into a datetime.""" - return datetime.datetime.strptime(timestr, fmt) - - -def normalize_time(timestamp): - """Normalize time in arbitrary timezone to UTC naive object""" - offset = timestamp.utcoffset() - if offset is None: - return timestamp - return timestamp.replace(tzinfo=None) - offset - - -def is_older_than(before, seconds): - """Return True if before is older than seconds.""" - if isinstance(before, basestring): - before = parse_strtime(before).replace(tzinfo=None) - return utcnow() - before > datetime.timedelta(seconds=seconds) - - -def is_newer_than(after, seconds): - """Return True if after is newer than seconds.""" - if isinstance(after, basestring): - after = parse_strtime(after).replace(tzinfo=None) - return after - utcnow() > datetime.timedelta(seconds=seconds) - - -def utcnow_ts(): - """Timestamp version of our utcnow function.""" - return calendar.timegm(utcnow().timetuple()) - - -def utcnow(): - """Overridable version of utils.utcnow.""" - if utcnow.override_time: - try: - return utcnow.override_time.pop(0) - except AttributeError: - return utcnow.override_time - return datetime.datetime.utcnow() - - -def iso8601_from_timestamp(timestamp): - """Returns a iso8601 formated date from timestamp""" - return isotime(datetime.datetime.utcfromtimestamp(timestamp)) - - -utcnow.override_time = None - - -def set_time_override(override_time=datetime.datetime.utcnow()): - """ - Override utils.utcnow to return a constant time or a list thereof, - one at a time. - """ - utcnow.override_time = override_time - - -def advance_time_delta(timedelta): - """Advance overridden time using a datetime.timedelta.""" - assert(not utcnow.override_time is None) - try: - for dt in utcnow.override_time: - dt += timedelta - except TypeError: - utcnow.override_time += timedelta - - -def advance_time_seconds(seconds): - """Advance overridden time by seconds.""" - advance_time_delta(datetime.timedelta(0, seconds)) - - -def clear_time_override(): - """Remove the overridden time.""" - utcnow.override_time = None - - -def marshall_now(now=None): - """Make an rpc-safe datetime with microseconds. - - Note: tzinfo is stripped, but not required for relative times.""" - if not now: - now = utcnow() - return dict(day=now.day, month=now.month, year=now.year, hour=now.hour, - minute=now.minute, second=now.second, - microsecond=now.microsecond) - - -def unmarshall_time(tyme): - """Unmarshall a datetime dict.""" - return datetime.datetime(day=tyme['day'], - month=tyme['month'], - year=tyme['year'], - hour=tyme['hour'], - minute=tyme['minute'], - second=tyme['second'], - microsecond=tyme['microsecond']) - - -def delta_seconds(before, after): - """ - Compute the difference in seconds between two date, time, or - datetime objects (as a float, to microsecond resolution). - """ - delta = after - before - try: - return delta.total_seconds() - except AttributeError: - return ((delta.days * 24 * 3600) + delta.seconds + - float(delta.microseconds) / (10 ** 6)) - - -def is_soon(dt, window): - """ - Determines if time is going to happen in the next window seconds. - - :params dt: the time - :params window: minimum seconds to remain to consider the time not soon - - :return: True if expiration is within the given duration - """ - soon = (utcnow() + datetime.timedelta(seconds=window)) - return normalize_time(dt) <= soon diff --git a/billingstack/openstack/common/uuidutils.py b/billingstack/openstack/common/uuidutils.py deleted file mode 100644 index 7608acb..0000000 --- a/billingstack/openstack/common/uuidutils.py +++ /dev/null @@ -1,39 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright (c) 2012 Intel Corporation. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -UUID related utilities and helper functions. -""" - -import uuid - - -def generate_uuid(): - return str(uuid.uuid4()) - - -def is_uuid_like(val): - """Returns validation of a value as a UUID. - - For our purposes, a UUID is a canonical form string: - aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa - - """ - try: - return str(uuid.UUID(val)) == val - except (TypeError, ValueError, AttributeError): - return False diff --git a/billingstack/openstack/common/version.py b/billingstack/openstack/common/version.py deleted file mode 100644 index 007829c..0000000 --- a/billingstack/openstack/common/version.py +++ /dev/null @@ -1,94 +0,0 @@ - -# Copyright 2012 OpenStack LLC -# Copyright 2012-2013 Hewlett-Packard Development Company, L.P. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -""" -Utilities for consuming the version from pkg_resources. -""" - -import pkg_resources - - -class VersionInfo(object): - - def __init__(self, package): - """Object that understands versioning for a package - :param package: name of the python package, such as glance, or - python-glanceclient - """ - self.package = package - self.release = None - self.version = None - self._cached_version = None - - def __str__(self): - """Make the VersionInfo object behave like a string.""" - return self.version_string() - - def __repr__(self): - """Include the name.""" - return "VersionInfo(%s:%s)" % (self.package, self.version_string()) - - def _get_version_from_pkg_resources(self): - """Get the version of the package from the pkg_resources record - associated with the package.""" - try: - requirement = pkg_resources.Requirement.parse(self.package) - provider = pkg_resources.get_provider(requirement) - return provider.version - except pkg_resources.DistributionNotFound: - # The most likely cause for this is running tests in a tree - # produced from a tarball where the package itself has not been - # installed into anything. Revert to setup-time logic. - from billingstack.openstack.common import setup - return setup.get_version(self.package) - - def release_string(self): - """Return the full version of the package including suffixes indicating - VCS status. - """ - if self.release is None: - self.release = self._get_version_from_pkg_resources() - - return self.release - - def version_string(self): - """Return the short version minus any alpha/beta tags.""" - if self.version is None: - parts = [] - for part in self.release_string().split('.'): - if part[0].isdigit(): - parts.append(part) - else: - break - self.version = ".".join(parts) - - return self.version - - # Compatibility functions - canonical_version_string = version_string - version_string_with_vcs = release_string - - def cached_version_string(self, prefix=""): - """Generate an object which will expand in a string context to - the results of version_string(). We do this so that don't - call into pkg_resources every time we start up a program when - passing version information into the CONF constructor, but - rather only do the calculation when and if a version is requested - """ - if not self._cached_version: - self._cached_version = "%s%s" % (prefix, - self.version_string()) - return self._cached_version diff --git a/billingstack/payment_gateway/__init__.py b/billingstack/payment_gateway/__init__.py deleted file mode 100644 index f776e70..0000000 --- a/billingstack/payment_gateway/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -from stevedore.extension import ExtensionManager - -from billingstack import exceptions -from billingstack.openstack.common import log -from billingstack.payment_gateway.base import Provider -from billingstack.storage import get_connection - - -LOG = log.getLogger(__name__) - - -def _register(ep, context, conn): - provider = ep.plugin - - values = provider.values() - - LOG.debug("Attempting registration of PGP %s" % ep.plugin.get_plugin_name()) - try: - methods = provider.methods() - except NotImplementedError: - msg = "PaymentGatewayProvider %s doesn't provide any methods - Skipped" - LOG.warn(msg, provider.get_plugin_name()) - return - - try: - conn.pg_provider_register(context, values, methods=methods) - except exceptions.ConfigurationError: - return - - LOG.debug("Registered PGP %s with methods %s", values, methods) - - -def register_providers(context): - conn = get_connection() - em = ExtensionManager(Provider.__plugin_ns__) - em.map(_register, context, conn) - - -def get_provider(name): - return Provider.get_plugin(name) diff --git a/billingstack/payment_gateway/base.py b/billingstack/payment_gateway/base.py deleted file mode 100644 index 085b94b..0000000 --- a/billingstack/payment_gateway/base.py +++ /dev/null @@ -1,158 +0,0 @@ -from billingstack.storage import get_connection -from billingstack.plugin import Plugin - - -class Provider(Plugin): - __plugin_ns__ = 'billingstack.payment_gateway' - __plugin_type__ = 'payment_gateway' - - __title__ = '' - __description__ = '' - - def __init__(self, config): - self.config = config - self.client = self.get_client() - - @classmethod - def methods(cls): - """ - The methods supported by the Provider - """ - raise NotImplementedError - - @classmethod - def properties(cls): - """ - Some extra data about the Provider if any, will be stored as - JSON in the DB - """ - return {} - - @classmethod - def values(cls): - return dict( - name=cls.get_plugin_name(), - title=cls.__title__, - description=cls.__description__, - properties=cls.properties()) - - def get_client(self): - """ - Return a Client - """ - raise NotImplementedError - - def get_connection(self): - """ - Helper to get a storage conncection in BS - """ - return get_connection() - - @classmethod - def account_add(self, values): - """ - Create a new Account - - :param values: A Customer as dict - """ - raise NotImplementedError - - def account_get(self, id_): - """ - List Accounts - - :param id_: Account ID to get - """ - raise NotImplementedError - - def account_list(self): - """ - List Accounts - """ - raise NotImplementedError - - def account_delete(self, id_): - """ - Delete Account - - :param id_: Account ID to delete - """ - raise NotImplementedError - - def payment_method_add(self, account_id, values): - """ - Create a new Credit Card or similar - - :param account_d: The Account ID to add this PM to - :param values: Values to create the PM from - """ - raise NotImplementedError - - def payment_method_get(self, id_): - """ - Get a PaymentMethod - - :param id_: The ID of the PM to get - """ - raise NotImplementedError - - def payment_method_list(self, account_id): - """ - List PaymentMethods - - :param account_id: The Account ID to list Pms for - """ - raise NotImplementedError - - def payment_method_delete(self, id_): - """ - Delete a PaymentMethod - """ - raise NotImplementedError - - def transaction_add(self, account, values): - """ - Create a new Transaction - - :param account: The Account entity to create it on - :param values: Values to create it with - """ - raise NotImplementedError - - def transaction_get(self, id_): - """ - Get a Transaction - - :param id_: The ID of the Transaction - """ - raise NotImplementedError - - def transaction_list(self): - """ - List Transactions - """ - raise NotImplementedError - - def transaction_settle(self, id_): - """ - Settle a Transaction - - :param id_: The ID of the Transaction - """ - raise NotImplementedError - - def transaction_void(self, id_): - """ - Void a Transaction - - :param id_: The ID of the Transaction - """ - raise NotImplementedError - - def transaction_refund(self, id_): - """ - Refund a Transaction - - :param id_: The ID of the Transaction - """ - raise NotImplementedError diff --git a/billingstack/payment_gateway/dummy.py b/billingstack/payment_gateway/dummy.py deleted file mode 100644 index 3cc2997..0000000 --- a/billingstack/payment_gateway/dummy.py +++ /dev/null @@ -1,19 +0,0 @@ -from billingstack.payment_gateway.base import Provider - - -class DummyProvider(Provider): - """ - A Stupid Provider that does nothing - """ - __plugin_name__ = 'dummy' - __title__ = 'Dummy Provider' - __description__ = 'Noop Dummy' - - @classmethod - def methods(cls): - return [ - {"name": "visa", "type": "creditcard"}] - - @classmethod - def properties(cls): - return {"enabled": 0} diff --git a/billingstack/payment_gateway/service.py b/billingstack/payment_gateway/service.py deleted file mode 100644 index 2ca72ff..0000000 --- a/billingstack/payment_gateway/service.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -A service that does calls towards the PGP web endpoint or so -""" - -import functools -import re -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc -from billingstack.openstack.common.rpc import service as rpc_service -from stevedore.named import NamedExtensionManager -from billingstack import exceptions -from billingstack import utils -from billingstack.central.rpcapi import CentralAPI - - -cfg.CONF.import_opt('host', 'billingstack.netconf') -cfg.CONF.import_opt('host', 'billingstack.payment_gateway.rpcapi') - -LOG = logging.getLogger(__name__) - - -class Service(rpc_service.Service): - def __init__(self, *args, **kwargs): - kwargs.update( - host=cfg.CONF.host, - topic=cfg.CONF.central_topic, - ) - - super(Service, self).__init__(*args, **kwargs) - - # Get a storage connection - self.central_api = CentralAPI() - - def pg_provider_get(self, ctxt, pg_info): - """ - Work out a PGC config either from pg_info or via ctxt fetching it from central. - Return the appropriate PGP for this info. - - :param ctxt: Request context - :param pg_info: Payment Gateway Config... - """ - - def account_add(self, ctxt, values, pg_config=None): - """ - Create an Account on the underlying provider - - :param values: The account values - """ - - def __getattr__(self, name): - """ - Proxy onto the storage api if there is no local method present.. - - For now to avoid to have to write up every method once more here... - """ - if hasattr(self, name): - return getattr(self, name) - - f = getattr(self.provider, name) - if not f: - raise AttributeError - - @functools.wraps(f) - def _wrapper(*args, **kw): - return f(*args, **kw) - setattr(self, name, _wrapper) - return _wrapper diff --git a/billingstack/plugin.py b/billingstack/plugin.py deleted file mode 100644 index 31560ab..0000000 --- a/billingstack/plugin.py +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright 2012 Bouvet ASA -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from stevedore import driver -from billingstack.openstack.common import log as logging - - -LOG = logging.getLogger(__name__) - - -class Plugin(object): - __plugin_ns__ = None - - __plugin_name__ = None - __plugin_type__ = None - - def __init__(self): - self.name = self.get_canonical_name() - LOG.debug("Loaded plugin %s", self.name) - - def is_enabled(self): - """ - Is this Plugin enabled? - - :retval: Boolean - """ - return True - - @classmethod - def get_plugin(cls, name, ns=None, invoke_on_load=False, - invoke_args=(), invoke_kwds={}): - """ - Load a plugin from namespace - """ - ns = ns or cls.__plugin_ns__ - if ns is None: - raise RuntimeError('No namespace provided or __plugin_ns__ unset') - - LOG.debug('Looking for plugin %s in %s', name, ns) - mgr = driver.DriverManager(ns, name) - - return mgr.driver(*invoke_args, **invoke_kwds) if invoke_on_load \ - else mgr.driver - - @classmethod - def get_canonical_name(cls): - """ - Return the plugin name - """ - type_ = cls.get_plugin_type() - name = cls.get_plugin_name() - return "%s:%s" % (type_, name) - - @classmethod - def get_plugin_name(cls): - return cls.__plugin_name__ - - @classmethod - def get_plugin_type(cls): - return cls.__plugin_type__ - - def start(self): - """ - Start this plugin - """ - - def stop(self): - """ - Stop this plugin from doing anything - """ diff --git a/billingstack/samples.py b/billingstack/samples.py deleted file mode 100644 index 333d134..0000000 --- a/billingstack/samples.py +++ /dev/null @@ -1,28 +0,0 @@ -import glob -import os.path - -import anyjson as json - - -DIR = os.path.join(os.path.dirname(__file__), 'samples_data') - - -def get_sample(name): - """ - Get a sample file .json, for example user.json - - :param name: The name of the sample type - """ - f = open('%s/%s.json' % (DIR, name)) - return json.loads(f.read()) - - -def get_samples(): - """ - Read the samples and return it as a dict where the filename is the key - """ - samples = {} - for f in glob.glob(DIR + '/*.json'): - name = os.path.basename(f)[:-(len(".json"))] - samples[name] = get_sample(name) - return samples diff --git a/billingstack/samples_data/contact_info.json b/billingstack/samples_data/contact_info.json deleted file mode 100644 index efbab3b..0000000 --- a/billingstack/samples_data/contact_info.json +++ /dev/null @@ -1,15 +0,0 @@ -[ - { - "first_name": "Mr Bill", - "last_name": "Biller", - "company": "Company X", - "address1": "SomeStreet 1", - "address2": "Apartment 10", - "locality": "Stavanger", - "region": "Rogaland", - "postal_code": "4000", - "country_name": "Norway", - "phone": "22 22 22 22", - "email": "bill.biller@comp-x.com" - } -] diff --git a/billingstack/samples_data/currency.json b/billingstack/samples_data/currency.json deleted file mode 100644 index 209d1c4..0000000 --- a/billingstack/samples_data/currency.json +++ /dev/null @@ -1,8 +0,0 @@ -[ - { - "name": "nok" - }, - { - "name": "sek" - } -] diff --git a/billingstack/samples_data/customer.json b/billingstack/samples_data/customer.json deleted file mode 100644 index 5e43d77..0000000 --- a/billingstack/samples_data/customer.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - { - "name": "Customer X" - } -] diff --git a/billingstack/samples_data/fixtures/currencies_get_response.json b/billingstack/samples_data/fixtures/currencies_get_response.json deleted file mode 100644 index 82f4d07..0000000 --- a/billingstack/samples_data/fixtures/currencies_get_response.json +++ /dev/null @@ -1,9 +0,0 @@ -[{ - "id": "402881a33ce9cac2013ce9cb33e10002", - "letter": "usd", - "name": "US Dollar" -}, { - "id": "402881a33ce9cac2013ce9cb33f90003", - "letter": "eur", - "name": "Euro" -}] diff --git a/billingstack/samples_data/fixtures/currencies_post_request.json b/billingstack/samples_data/fixtures/currencies_post_request.json deleted file mode 100644 index 9e806cd..0000000 --- a/billingstack/samples_data/fixtures/currencies_post_request.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "letter" : "usd", - "name" : "US Dollar" -} diff --git a/billingstack/samples_data/fixtures/currencies_post_response.json b/billingstack/samples_data/fixtures/currencies_post_response.json deleted file mode 100644 index 5b5c510..0000000 --- a/billingstack/samples_data/fixtures/currencies_post_response.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "402881a33ce9cac2013ce9cb33e10002", - "letter": "usd", - "name": "US Dollar" -} diff --git a/billingstack/samples_data/fixtures/languages_get_response.json b/billingstack/samples_data/fixtures/languages_get_response.json deleted file mode 100644 index 03f29a3..0000000 --- a/billingstack/samples_data/fixtures/languages_get_response.json +++ /dev/null @@ -1,9 +0,0 @@ -[{ - "id": "402881a33ce9cac2013ce9cb32290000", - "letter": "en", - "name": "English" -}, { - "id": "402881a33ce9cac2013ce9cb32ae0001", - "letter": "es", - "name": "Spanish" -}] diff --git a/billingstack/samples_data/fixtures/languages_post_request.json b/billingstack/samples_data/fixtures/languages_post_request.json deleted file mode 100644 index 766740e..0000000 --- a/billingstack/samples_data/fixtures/languages_post_request.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "letter" : "en", - "name" : "English" -} \ No newline at end of file diff --git a/billingstack/samples_data/fixtures/languages_post_response.json b/billingstack/samples_data/fixtures/languages_post_response.json deleted file mode 100644 index ed949ce..0000000 --- a/billingstack/samples_data/fixtures/languages_post_response.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "402881a33ce9cac2013ce9cb32290000", - "letter": "en", - "name": "English" -} diff --git a/billingstack/samples_data/fixtures/merchant_products_get_response.json b/billingstack/samples_data/fixtures/merchant_products_get_response.json deleted file mode 100644 index b17a874..0000000 --- a/billingstack/samples_data/fixtures/merchant_products_get_response.json +++ /dev/null @@ -1,9 +0,0 @@ -[{ - "id": "402881a33cf4568b013cf45796360008", - "name": "instance:m1.tiny", - "title": "instance:m1.tiny" -}, { - "id": "402881a33cf4568b013cf45796510009", - "name": "instance:m1.small", - "title": "instance:m1.small" -}] diff --git a/billingstack/samples_data/fixtures/merchant_products_post_request.json b/billingstack/samples_data/fixtures/merchant_products_post_request.json deleted file mode 100644 index cb2d6c4..0000000 --- a/billingstack/samples_data/fixtures/merchant_products_post_request.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name" : "instance:m1.tiny", - "title" : "instance:m1.tiny" -} \ No newline at end of file diff --git a/billingstack/samples_data/fixtures/merchant_products_post_response.json b/billingstack/samples_data/fixtures/merchant_products_post_response.json deleted file mode 100644 index b4611bb..0000000 --- a/billingstack/samples_data/fixtures/merchant_products_post_response.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id" : "402881a33cf44515013cf4515fa50008" - "name" : "instance:m1.tiny", - "title" : "instance:m1.tiny" -} \ No newline at end of file diff --git a/billingstack/samples_data/fixtures/merchant_users_get_response.json b/billingstack/samples_data/fixtures/merchant_users_get_response.json deleted file mode 100644 index 446de3d..0000000 --- a/billingstack/samples_data/fixtures/merchant_users_get_response.json +++ /dev/null @@ -1,6 +0,0 @@ -[{ - "id": "402881a33cf42afd013cf42c156b0007", - "merchant": "402881a33cf42afd013cf42c13a30005", - "username": "luis", - "password": "secret0" -}] diff --git a/billingstack/samples_data/fixtures/merchant_users_post_request.json b/billingstack/samples_data/fixtures/merchant_users_post_request.json deleted file mode 100644 index bf78176..0000000 --- a/billingstack/samples_data/fixtures/merchant_users_post_request.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "username": "luis", - "password": "secret0" -} diff --git a/billingstack/samples_data/fixtures/merchant_users_post_response.json b/billingstack/samples_data/fixtures/merchant_users_post_response.json deleted file mode 100644 index 72b9731..0000000 --- a/billingstack/samples_data/fixtures/merchant_users_post_response.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "id": "402881a33cf42afd013cf42c156b0007", - "merchant": "402881a33cf42afd013cf42c13a30005", - "username": "luis", - "password": "secret0" -} \ No newline at end of file diff --git a/billingstack/samples_data/fixtures/merchants_get_response.json b/billingstack/samples_data/fixtures/merchants_get_response.json deleted file mode 100644 index cbccc0c..0000000 --- a/billingstack/samples_data/fixtures/merchants_get_response.json +++ /dev/null @@ -1,13 +0,0 @@ -[{ - "id": "402881a33ce9cac2013ce9cb36380004", - "name": "billingstack", - "title": "BillingStack", - "language": "en", - "currency": "usd" -}, { - "id": "402881a33ce9cac2013ce9cb36950005", - "name": "openstackbiller", - "title": "OpenStack Biller", - "language": "es", - "currency": "eur" -}] diff --git a/billingstack/samples_data/fixtures/merchants_post_request.json b/billingstack/samples_data/fixtures/merchants_post_request.json deleted file mode 100644 index 6e41893..0000000 --- a/billingstack/samples_data/fixtures/merchants_post_request.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name" : "billingstack", - "title" : "BillingStack", - "language" : "en", - "currency" : "usd" -} \ No newline at end of file diff --git a/billingstack/samples_data/fixtures/merchants_post_response.json b/billingstack/samples_data/fixtures/merchants_post_response.json deleted file mode 100644 index b3408da..0000000 --- a/billingstack/samples_data/fixtures/merchants_post_response.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "402881a33ce9cac2013ce9cb36380004", - "name": "billingstack", - "title": "BillingStack", - "language": "en", - "currency": "usd" -} diff --git a/billingstack/samples_data/fixtures/payment_gateway_providers_get_response.json b/billingstack/samples_data/fixtures/payment_gateway_providers_get_response.json deleted file mode 100644 index 9498cc9..0000000 --- a/billingstack/samples_data/fixtures/payment_gateway_providers_get_response.json +++ /dev/null @@ -1,9 +0,0 @@ -[{ - "id": "402881a33cf3fe47013cf404d3ac0004", - "title": "Braintree", - "description": "Braintree Payments", - "is_default": true, - "metadata": { - "key.1": "value.1" - } -}] diff --git a/billingstack/samples_data/fixtures/payment_gateway_providers_post_request.json b/billingstack/samples_data/fixtures/payment_gateway_providers_post_request.json deleted file mode 100644 index 8bef177..0000000 --- a/billingstack/samples_data/fixtures/payment_gateway_providers_post_request.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name" : "braintree", - "title" : "Braintree", - "description" : "Braintree Payments", - "metadata" : { - "key.1": "value.1" - }, - "is_default" : true -} diff --git a/billingstack/samples_data/fixtures/payment_gateway_providers_post_response.json b/billingstack/samples_data/fixtures/payment_gateway_providers_post_response.json deleted file mode 100644 index 3ca6106..0000000 --- a/billingstack/samples_data/fixtures/payment_gateway_providers_post_response.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "402881a33cf3fe47013cf404d3ac0004", - "title": "Braintree", - "description": "Braintree Payments", - "is_default": true, - "metadata": { - "key.1": "value.1" - } -} \ No newline at end of file diff --git a/billingstack/samples_data/language.json b/billingstack/samples_data/language.json deleted file mode 100644 index b47f39d..0000000 --- a/billingstack/samples_data/language.json +++ /dev/null @@ -1,8 +0,0 @@ -[ - { - "name": "nor" - }, - { - "name": "swe" - } -] diff --git a/billingstack/samples_data/merchant.json b/billingstack/samples_data/merchant.json deleted file mode 100644 index a17adf0..0000000 --- a/billingstack/samples_data/merchant.json +++ /dev/null @@ -1,6 +0,0 @@ -[ - { - "name": "Merchant X", - "title": "Merchant" - } -] diff --git a/billingstack/samples_data/payment_method.json b/billingstack/samples_data/payment_method.json deleted file mode 100644 index e4686f7..0000000 --- a/billingstack/samples_data/payment_method.json +++ /dev/null @@ -1,8 +0,0 @@ -[ - { - "name": "Visa", - "identifier": "5105105105105100", - "expires": "05/2012", - "properties": {"cardholder": "Mr Holder", "cvv": "007"} - } -] diff --git a/billingstack/samples_data/pg_config.json b/billingstack/samples_data/pg_config.json deleted file mode 100644 index 02b1d9c..0000000 --- a/billingstack/samples_data/pg_config.json +++ /dev/null @@ -1,6 +0,0 @@ -[ - { - "name": "Braintree Config", - "configuration" : "braintree" - } -] diff --git a/billingstack/samples_data/pg_method.json b/billingstack/samples_data/pg_method.json deleted file mode 100644 index 366d737..0000000 --- a/billingstack/samples_data/pg_method.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "name": "visa", - "title": "Visa Credit Card", - "description": "Credit Card version of Visa", - "type": "creditcard" - }, - { - "name": "mastercard", - "title": "MasterCard", - "description": "Credit Card version of MasterCard", - "type": "creditcard" - }, - { - "name": "amex", - "title": "American Express Credit Card", - "description": "AMEX Card", - "type": "creditcard" - } -] diff --git a/billingstack/samples_data/pg_provider.json b/billingstack/samples_data/pg_provider.json deleted file mode 100644 index 7e65230..0000000 --- a/billingstack/samples_data/pg_provider.json +++ /dev/null @@ -1,7 +0,0 @@ -[ - { - "name" : "braintree", - "title" : "BrainTree Payment Gateway", - "description" : "www.braintree.com integration provider" - } -] diff --git a/billingstack/samples_data/plan.json b/billingstack/samples_data/plan.json deleted file mode 100644 index 7ec4076..0000000 --- a/billingstack/samples_data/plan.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { - "name": "Compute Server", - "title": "Compute Server that has vCPU and so on", - "properties": { - "random": 1 - } - } -] diff --git a/billingstack/samples_data/product.json b/billingstack/samples_data/product.json deleted file mode 100644 index 4e110c3..0000000 --- a/billingstack/samples_data/product.json +++ /dev/null @@ -1,182 +0,0 @@ -[ - { - "name": "instance", - "type": "gauge", - "measure": "unit", - "description": "Duration of instance", - "properties": { - "resource": "instance_id" - } - }, - { - "name": "memory", - "type": "gauge", - "measure": "mb", - "properties": { - "resource": "instance_id" - }, - "description": "Volume of RAM in MB" - }, - { - "name": "vcpus", - "type": "gauge", - "measure": "vcpu", - "properties": { - "resource": "instance_id" - }, - "description": "Number of VCPUs" - }, - { - "name": "root_disk_size", - "type": "gauge", - "measure": "gb", - "properties": { - "resource": "instance_id" - }, - "description": "Size of root disk in GB" - }, - { - "name": "ephemeral_disk_size", - "type": "gauge", - "measure": "gb", - "properties": { - "resource": "instance_id" - }, - "description": "Size of ephemeral disk in GB" - }, - { - "name": "disk.read.requests", - "type": "cumulative", - "measure": "unit", - "properties": { - "resource": "instance_id" - }, - "description": "Number of disk read requests" - }, - { - "name": "disk.read.bytes", - "type": "cumulative", - "measure": "bytes", - "properties": { - "resource": "instance_id" - }, - "description": "Volume of disk read in bytes" - }, - { - "name": "disk.write.requests", - "type": "cumulative", - "measure": "unit", - "properties": { - "resource": "instance_id" - }, - "description": "Number of disk write requests" - }, - { - "name": "disk.write.bytes", - "type": "cumulative", - "measure": "bytes", - "properties": { - "resource": "instance_id" - }, - "description": "Volume of disk write in bytes" - }, - { - "name": "cpu", - "type": "cumulative", - "measure": "unit", - "properties": { - "resource": "seconds" - }, - "description": "CPU time used" - }, - { - "name": "network.incoming.bytes", - "type": "cumulative", - "measure": "bytes", - "properties": { - "resource": "instance_id" - }, - "description": "number of incoming bytes on the network" - }, - { - "name": "network.outgoing.bytes", - "type": "cumulative", - "measure": "bytes", - "properties": { - "resource": "instance_id" - }, - "description": "number of outgoing bytes on the network" - }, - { - "name": "network.incoming.packets", - "type": "cumulative", - "measure": "packets", - "properties": { - "resource": "instance_id" - }, - "description": "number of incoming packets" - }, - { - "name": "network.outgoing.packets", - "type": "cumulative", - "measure": "packets", - "properties": { - "resource": "instance_id" - }, - "description": "number of outgoing packets" - }, - { - "name": "image", - "type": "gauge", - "measure": "unit", - "properties": { - "resource": "image_id" - }, - "description": "Image polling -> it (still) exists" - }, - { - "name": "image_size", - "type": "gauge", - "measure": "bytes", - "properties": { - "resource": "image_id" - }, - "description": "Uploaded image size" - }, - { - "name": "image_download", - "type": "gauge", - "measure": "bytes", - "properties": { - "resource": "image_id" - }, - "description": "Image is downloaded" - }, - { - "name": "image_serve", - "type": "gauge", - "measure": "bytes", - "properties": { - "resource": "image_id" - }, - "description": "Image is served out" - }, - { - "name": "volume", - "type": "gauge", - "measure": "unit", - "properties": { - "resource": "measure_id" - }, - "description": "Duration of volume" - }, - { - "name": "volume_size", - "type": "gauge", - "measure": "gb", - "properties": { - "resource": "measure_id" - }, - "description": "Size of measure" - } -] diff --git a/billingstack/samples_data/user.json b/billingstack/samples_data/user.json deleted file mode 100644 index 8044673..0000000 --- a/billingstack/samples_data/user.json +++ /dev/null @@ -1,6 +0,0 @@ -[ - { - "name": "demo", - "password": "secret" - } -] diff --git a/billingstack/service.py b/billingstack/service.py deleted file mode 100644 index ce3bfaa..0000000 --- a/billingstack/service.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 eNovance -# -# Author: Julien Danjou -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from oslo.config import cfg -from billingstack.openstack.common import rpc -from billingstack.openstack.common import context -from billingstack.openstack.common import log -from billingstack.openstack.common.rpc import service as rpc_service - - -cfg.CONF.register_opts([ - cfg.IntOpt('periodic_interval', - default=600, - help='seconds between running periodic tasks') -]) - -cfg.CONF.import_opt('host', 'billingstack.netconf') - - -class PeriodicService(rpc_service.Service): - - def start(self): - super(PeriodicService, self).start() - admin_context = context.RequestContext('admin', 'admin', is_admin=True) - self.tg.add_timer(cfg.CONF.periodic_interval, - self.manager.periodic_tasks, - context=admin_context) - - -def prepare_service(argv=[]): - rpc.set_defaults(control_exchange='billingstack') - cfg.CONF(argv[1:], project='billingstack') - log.setup('billingstack') diff --git a/billingstack/sqlalchemy/__init__.py b/billingstack/sqlalchemy/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/sqlalchemy/api.py b/billingstack/sqlalchemy/api.py deleted file mode 100644 index 5743857..0000000 --- a/billingstack/sqlalchemy/api.py +++ /dev/null @@ -1,168 +0,0 @@ -from sqlalchemy import or_ -from sqlalchemy.orm import exc - -from billingstack import exceptions -from billingstack.openstack.common import log -from billingstack.sqlalchemy import model_base, session - - -LOG = log.getLogger(__name__) - - -class HelpersMixin(object): - def setup(self, config_group): - self.session = session.get_session(config_group) - self.engine = session.get_engine(config_group) - - def setup_schema(self): - """ Semi-Private Method to create the database schema """ - LOG.debug('Setting up schema') - base = self.base() - base.metadata.create_all(self.session.bind) - - def teardown_schema(self): - """ Semi-Private Method to reset the database schema """ - LOG.debug('Tearing down schema') - base = self.base() - base.metadata.drop_all(self.session.bind) - - def _save(self, obj, save=True): - if not save: - return obj - try: - obj.save(self.session) - except exceptions.Duplicate: - raise - - def _list(self, cls=None, query=None, criterion=None): - """ - A generic list method - - :param cls: The model to try to delete - :param criterion: Criterion to match objects with - """ - if not cls and not query: - raise ValueError("Need either cls or query") - - query = query or self.session.query(cls) - - if criterion: - query = query.filter_by(**criterion) - - try: - result = query.all() - except exc.NoResultFound: - LOG.debug('No results found querying for %s: %s' % - (cls, criterion)) - return [] - else: - return result - - def _get(self, cls, identifier, by_name=False): - """ - Get an instance of a Model matching ID - - :param cls: The model to try to get - :param identifier: The ID to get - :param by_name: Search by name as well as ID - """ - filters = [cls.id == identifier] - if by_name: - filters.append(cls.name == identifier) - - query = self.session.query(cls)\ - .filter(or_(*filters)) - - try: - obj = query.one() - except exc.NoResultFound: - raise exceptions.NotFound(identifier) - return obj - - def _get_id_or_name(self, *args, **kw): - """ - Same as _get but with by_name on ass default - """ - kw['by_name'] = True - return self._get(*args, **kw) - - def _update(self, cls, id_, values): - """ - Update an instance of a Model matching an ID with values - - :param cls: The model to try to update - :param id_: The ID to update - :param values: The values to update the model instance with - """ - obj = self._get(cls, id_) - if 'id' in values and id_ != values['id']: - msg = 'Not allowed to change id' - errors = {'id': id_} - raise exceptions.InvalidObject(msg, errors=errors) - obj.update(values) - try: - obj.save(self.session) - except exceptions.Duplicate: - raise - return obj - - def _delete(self, cls, id_): - """ - Delete an instance of a Model matching an ID - - :param cls: The model to try to delete - :param id_: The ID to delete - """ - obj = self._get(cls, id_) - obj.delete(self.session) - - def _get_row(self, obj, cls=None, **kw): - """ - Used to either check that passed 'obj' is a ModelBase inheriting object - and just return it - - :param obj: ID or instance / ref of the object - :param cls: The class to run self._get on if obj is not a ref - """ - if isinstance(obj, model_base.ModelBase): - return obj - elif isinstance(obj, basestring) and cls: - return self._get(cls, obj) - else: - msg = 'Missing obj and/or obj and cls...' - raise exceptions.BadRequest(msg) - - def _make_rel_row(self, row, rel_attr, values): - """ - Get the class of the relation attribute in 'rel_attr' and make a - row from values with it. - - :param row: A instance of ModelBase - :param rel_attr: The relation attribute - :param values: The values to create the new row from - """ - cls = row.__mapper__.get_property(rel_attr).mapper.class_ - return cls(**values) - - def _dict(self, row, extra=[]): - data = dict(row) - for key in extra: - if isinstance(row[key], list): - data[key] = map(dict, row[key]) - else: - data[key] = dict(row[key]) - return data - - def _kv_rows(self, rows, key='name', func=lambda i: i): - """ - Return a Key, Value dict where the "key" will be the key and the row as value - """ - data = {} - for row in rows: - if callable(key): - data_key = key(row) - else: - data_key = row[key] - data[data_key] = func(row) - return data - diff --git a/billingstack/sqlalchemy/model_base.py b/billingstack/sqlalchemy/model_base.py deleted file mode 100644 index b860981..0000000 --- a/billingstack/sqlalchemy/model_base.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright 2012 Hewlett-Packard Development Company, L.P. -# -# Author: Patrick Galbraith -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from sqlalchemy import Column, DateTime, Unicode, UnicodeText -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import object_mapper -from sqlalchemy.ext.hybrid import hybrid_property -from sqlalchemy.ext.declarative import declared_attr - -from billingstack import exceptions, utils -from billingstack.sqlalchemy.types import UUID -from billingstack.openstack.common.uuidutils import generate_uuid -from billingstack.openstack.common import timeutils - - -class ModelBase(object): - __abstract__ = True - __table_initialized__ = False - - @declared_attr - def __tablename__(cls): - return utils.capital_to_underscore(cls.__name__) - - def save(self, session): - """ Save this object """ - session.add(self) - - try: - session.flush() - except IntegrityError, e: - non_unique_strings = ( - 'duplicate entry', - 'not unique' - ) - - for non_unique_string in non_unique_strings: - if non_unique_string in str(e).lower(): - raise exceptions.Duplicate(str(e)) - - # Not a Duplicate error.. Re-raise. - raise - - def delete(self, session): - """ Delete this object """ - session.delete(self) - session.flush() - - def __setitem__(self, key, value): - setattr(self, key, value) - - def __getitem__(self, key): - return getattr(self, key) - - def __iter__(self): - columns = dict(object_mapper(self).columns).keys() - # NOTE(russellb): Allow models to specify other keys that can be looked - # up, beyond the actual db columns. An example would be the 'name' - # property for an Instance. - if hasattr(self, '_extra_keys'): - columns.extend(self._extra_keys()) - self._i = iter(columns) - return self - - def next(self): - n = self._i.next() - return n, getattr(self, n) - - def update(self, values): - """ Make the model object behave like a dict """ - for k, v in values.iteritems(): - setattr(self, k, v) - - def iteritems(self): - """ - Make the model object behave like a dict. - - Includes attributes from joins. - """ - local = dict(self) - joined = dict([(k, v) for k, v in self.__dict__.iteritems() - if not k[0] == '_']) - local.update(joined) - return local.iteritems() - - -class BaseMixin(object): - """ - A mixin that provides id, and some dates. - """ - id = Column(UUID, default=generate_uuid, primary_key=True) - created_at = Column(DateTime, default=timeutils.utcnow) - updated_at = Column(DateTime, onupdate=timeutils.utcnow) - - -TYPES = { - "float": float, - "str": unicode, - "unicode": unicode, - "int": int, - "bool": bool -} - - -class PropertyMixin(object): - """ - Helper mixin for Property classes. - - Store the type of the value using type() or the pre-defined data_type - and cast it on value when returning the value. - - Supported types are in the TYPES dict. - """ - id = Column(UUID, default=generate_uuid, primary_key=True) - data_type = Column(Unicode(20), nullable=False, default=u'str') - name = Column(Unicode(60), index=True, nullable=False) - _value = Column('value', UnicodeText) - - @hybrid_property - def value(self): - data_type = TYPES.get(self.data_type, str) - return data_type(self._value) - - @value.setter - def value(self, value): - data_type = type(value).__name__ - self.data_type = data_type - self._value = value \ No newline at end of file diff --git a/billingstack/sqlalchemy/session.py b/billingstack/sqlalchemy/session.py deleted file mode 100644 index 4feb25f..0000000 --- a/billingstack/sqlalchemy/session.py +++ /dev/null @@ -1,247 +0,0 @@ -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""Session Handling for SQLAlchemy backend.""" - -import re -import time - -import sqlalchemy -from sqlalchemy.exc import DisconnectionError, OperationalError -import sqlalchemy.orm -from sqlalchemy.pool import NullPool, StaticPool - -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.gettextutils import _ - -LOG = logging.getLogger(__name__) - -_MAKERS = {} -_ENGINES = {} - - -SQLOPTS = [ - cfg.StrOpt('database_connection', - default='sqlite:///$state_path/billingstack.sqlite', - help='The database driver to use'), - cfg.IntOpt('connection_debug', default=0, - help='Verbosity of SQL debugging information. 0=None,' - ' 100=Everything'), - cfg.BoolOpt('connection_trace', default=False, - help='Add python stack traces to SQL as comment strings'), - cfg.BoolOpt('sqlite_synchronous', default=True, - help='If passed, use synchronous mode for sqlite'), - cfg.IntOpt('idle_timeout', default=3600, - help='timeout before idle sql connections are reaped'), - cfg.IntOpt('max_retries', default=10, - help='maximum db connection retries during startup. ' - '(setting -1 implies an infinite retry count)'), - cfg.IntOpt('retry_interval', default=10, - help='interval between retries of opening a sql connection') -] - - -def get_session(config_group, - autocommit=True, - expire_on_commit=False, - autoflush=True): - """Return a SQLAlchemy session.""" - global _MAKERS - - if config_group not in _MAKERS: - engine = get_engine(config_group) - _MAKERS[config_group] = get_maker(engine, - autocommit, - expire_on_commit, - autoflush) - - session = _MAKERS[config_group]() - return session - - -def pragma_fks(dbapi_conn, connection_rec): - dbapi_conn.execute('pragma foreign_keys=ON') - - -def synchronous_switch_listener(dbapi_conn, connection_rec): - """Switch sqlite connections to non-synchronous mode""" - dbapi_conn.execute("PRAGMA synchronous = OFF") - - -def add_regexp_listener(dbapi_con, con_record): - """Add REGEXP function to sqlite connections.""" - - def regexp(expr, item): - reg = re.compile(expr) - return reg.search(unicode(item)) is not None - dbapi_con.create_function('regexp', 2, regexp) - - -def ping_listener(dbapi_conn, connection_rec, connection_proxy): - """ - Ensures that MySQL connections checked out of the - pool are alive. - - Borrowed from: - http://groups.google.com/group/sqlalchemy/msg/a4ce563d802c929f - """ - try: - dbapi_conn.cursor().execute('select 1') - except dbapi_conn.OperationalError, ex: - if ex.args[0] in (2006, 2013, 2014, 2045, 2055): - LOG.warn('Got mysql server has gone away: %s', ex) - raise DisconnectionError("Database server went away") - else: - raise - - -def is_db_connection_error(args): - """Return True if error in connecting to db.""" - # NOTE(adam_g): This is currently MySQL specific and needs to be extended - # to support Postgres and others. - conn_err_codes = ('2002', '2003', '2006') - for err_code in conn_err_codes: - if args.find(err_code) != -1: - return True - return False - - -def get_engine(config_group): - """Return a SQLAlchemy engine.""" - global _ENGINES - - database_connection = cfg.CONF[config_group].database_connection - - if config_group not in _ENGINES: - connection_dict = sqlalchemy.engine.url.make_url( - database_connection) - - engine_args = { - "pool_recycle": cfg.CONF[config_group].idle_timeout, - "echo": False, - 'convert_unicode': True, - } - - # Map our SQL debug level to SQLAlchemy's options - if cfg.CONF[config_group].connection_debug >= 100: - engine_args['echo'] = 'debug' - elif cfg.CONF[config_group].connection_debug >= 50: - engine_args['echo'] = True - - if "sqlite" in connection_dict.drivername: - engine_args["poolclass"] = NullPool - - if database_connection == "sqlite://": - engine_args["poolclass"] = StaticPool - engine_args["connect_args"] = {'check_same_thread': False} - - _ENGINES[config_group] = sqlalchemy.create_engine(database_connection, - **engine_args) - - if 'mysql' in connection_dict.drivername: - sqlalchemy.event.listen(_ENGINES[config_group], - 'checkout', - ping_listener) - elif "sqlite" in connection_dict.drivername: - if not cfg.CONF[config_group].sqlite_synchronous: - sqlalchemy.event.listen(_ENGINES[config_group], - 'connect', - synchronous_switch_listener) - sqlalchemy.event.listen(_ENGINES[config_group], - 'connect', - add_regexp_listener) - sqlalchemy.event.listen(_ENGINES[config_group], - 'connect', pragma_fks) - - if (cfg.CONF[config_group].connection_trace and - _ENGINES[config_group].dialect.dbapi.__name__ == 'MySQLdb'): - import MySQLdb.cursors - _do_query = debug_mysql_do_query() - setattr(MySQLdb.cursors.BaseCursor, '_do_query', _do_query) - - try: - _ENGINES[config_group].connect() - except OperationalError, e: - if not is_db_connection_error(e.args[0]): - raise - - remaining = cfg.CONF[config_group].max_retries - if remaining == -1: - remaining = 'infinite' - while True: - msg = _('SQL connection failed. %s attempts left.') - LOG.warn(msg % remaining) - if remaining != 'infinite': - remaining -= 1 - time.sleep(cfg.CONF[config_group].retry_interval) - try: - _ENGINES[config_group].connect() - break - except OperationalError, e: - if (remaining != 'infinite' and remaining == 0) or \ - not is_db_connection_error(e.args[0]): - raise - return _ENGINES[config_group] - - -def get_maker(engine, autocommit=True, expire_on_commit=False, autoflush=True): - """Return a SQLAlchemy sessionmaker using the given engine.""" - return sqlalchemy.orm.sessionmaker(bind=engine, - autocommit=autocommit, - autoflush=autoflush, - expire_on_commit=expire_on_commit) - - -def debug_mysql_do_query(): - """Return a debug version of MySQLdb.cursors._do_query""" - import MySQLdb.cursors - import traceback - - old_mysql_do_query = MySQLdb.cursors.BaseCursor._do_query - - def _do_query(self, q): - stack = '' - for file, line, method, function in traceback.extract_stack(): - # exclude various common things from trace - if file.endswith('session.py') and method == '_do_query': - continue - if file.endswith('api.py') and method == 'wrapper': - continue - if file.endswith('utils.py') and method == '_inner': - continue - if file.endswith('exception.py') and method == '_wrap': - continue - # nova/db/api is just a wrapper around nova/db/sqlalchemy/api - if file.endswith('nova/db/api.py'): - continue - # only trace inside nova - index = file.rfind('nova') - if index == -1: - continue - stack += "File:%s:%s Method:%s() Line:%s | " \ - % (file[index:], line, method, function) - - # strip trailing " | " from stack - if stack: - stack = stack[:-3] - qq = "%s /* %s */" % (q, stack) - else: - qq = q - old_mysql_do_query(self, qq) - - # return the new _do_query method - return _do_query diff --git a/billingstack/sqlalchemy/types.py b/billingstack/sqlalchemy/types.py deleted file mode 100644 index 123ae5e..0000000 --- a/billingstack/sqlalchemy/types.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Coped: Moniker -from sqlalchemy.types import TypeDecorator, CHAR, VARCHAR, UnicodeText -from sqlalchemy.dialects.postgresql import UUID as pgUUID -from sqlalchemy.dialects.postgresql import INET as pgINET -import uuid - - -from billingstack.openstack.common import jsonutils - - -class UUID(TypeDecorator): - """Platform-independent UUID type. - - Uses Postgresql's UUID type, otherwise uses - CHAR(32), storing as stringified hex values. - - Copied verbatim from SQLAlchemy documentation. - """ - impl = CHAR - - def load_dialect_impl(self, dialect): - if dialect.name == 'postgresql': - return dialect.type_descriptor(pgUUID()) - else: - return dialect.type_descriptor(CHAR(32)) - - def process_bind_param(self, value, dialect): - if value is None: - return value - elif dialect.name == 'postgresql': - return str(value) - else: - if not isinstance(value, uuid.UUID): - return "%.32x" % uuid.UUID(value) - else: - # hexstring - return "%.32x" % value - - def process_result_value(self, value, dialect): - if value is None: - return value - else: - return str(uuid.UUID(value)) - - -class Inet(TypeDecorator): - impl = VARCHAR - - def load_dialect_impl(self, dialect): - if dialect.name == "postgresql": - return pgINET() - else: - return VARCHAR(39) # IPv6 can be up to 39 chars - - def process_bind_param(self, value, dialect): - if value is None: - return value - else: - return str(value) - - -# Special Fields -class JSON(TypeDecorator): - - impl = UnicodeText - - def process_bind_param(self, value, dialect): - return jsonutils.dumps(value) - - def process_result_value(self, value, dialect): - return jsonutils.loads(value) diff --git a/billingstack/sqlalchemy/utils.py b/billingstack/sqlalchemy/utils.py deleted file mode 100644 index 7c9a67f..0000000 --- a/billingstack/sqlalchemy/utils.py +++ /dev/null @@ -1,12 +0,0 @@ -from sqlalchemy.orm.properties import ColumnProperty, RelationshipProperty - - -def get_prop_names(obj, exclude=[]): - local, remote = [], [] - for p in obj.__mapper__.iterate_properties: - if p.key not in exclude: - if isinstance(p, ColumnProperty): - local.append(p.key) - if isinstance(p, RelationshipProperty): - remote.append(p.key) - return local, remote diff --git a/billingstack/storage/__init__.py b/billingstack/storage/__init__.py deleted file mode 100644 index fb573c5..0000000 --- a/billingstack/storage/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# Copied: Moniker -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.storage.base import StorageEngine - -LOG = logging.getLogger(__name__) - - -def get_engine(engine_name): - """ - Return the engine class from the provided engine name - """ - return StorageEngine.get_plugin(engine_name, invoke_on_load=True) - - -def get_connection(): - engine = get_engine(cfg.CONF['service:central'].storage_driver) - return engine.get_connection() - - -def setup_schema(): - """ Create the DB - Used for testing purposes """ - LOG.debug("Setting up Schema") - connection = get_connection() - connection.setup_schema() - - -def teardown_schema(): - """ Reset the DB to default - Used for testing purposes """ - LOG.debug("Tearing down Schema") - connection = get_connection() - connection.teardown_schema() diff --git a/billingstack/storage/base.py b/billingstack/storage/base.py deleted file mode 100644 index 8f24b25..0000000 --- a/billingstack/storage/base.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Copied: Moniker -import abc -from billingstack.plugin import Plugin - - -class StorageEngine(Plugin): - """ Base class for storage engines """ - - __plugin_ns__ = 'billingstack.storage' - __plugin_type__ = 'storage' - - @abc.abstractmethod - def get_connection(self): - """ - Return a Connection instance based on the configuration settings. - """ - - -class Connection(object): - """ - A Connection - """ - __metaclass__ = abc.ABCMeta - - @abc.abstractmethod - def __init__(self): - """ - Constructor... - """ - - def ping(self, context): - """ Ping the Storage connection """ - return { - 'status': None - } diff --git a/billingstack/storage/impl_sqlalchemy/__init__.py b/billingstack/storage/impl_sqlalchemy/__init__.py deleted file mode 100644 index 9830ce8..0000000 --- a/billingstack/storage/impl_sqlalchemy/__init__.py +++ /dev/null @@ -1,552 +0,0 @@ -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from sqlalchemy.orm import exc -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack import exceptions -from billingstack import utils as common_utils -from billingstack.sqlalchemy import utils as db_utils, api -from billingstack.sqlalchemy.session import SQLOPTS -from billingstack.storage import base -from billingstack.storage.impl_sqlalchemy import models - - -LOG = logging.getLogger(__name__) - -cfg.CONF.register_group(cfg.OptGroup( - name='storage:sqlalchemy', title="Configuration for SQLAlchemy Storage" -)) - -cfg.CONF.register_opts(SQLOPTS, group='storage:sqlalchemy') - - -class SQLAlchemyStorage(base.StorageEngine): - __plugin_name__ = 'sqlalchemy' - - def get_connection(self): - return Connection(self.name) - - -class Connection(base.Connection, api.HelpersMixin): - """ - SQLAlchemy connection - """ - def __init__(self, config_group): - self.setup(config_group) - - def base(self): - return models.BASE - - def set_properties(self, obj, properties, cls=None, rel_attr='properties', purge=False): - """ - Set's a dict with key values on a relation on the row - - :param obj: Either a row object or a id to use in connection with cls - :param properties: Key and Value dict with props to set. 1 row item. - :param cls: The class to use if obj isn't a row to query. - :param rel_attr: The relation attribute name to get the class to use - :param purge: Purge entries that doesn't exist in existing but in DB - """ - row = self._get_row(obj, cls=cls) - - existing = self._kv_rows(row[rel_attr]) - - for key, value in properties.items(): - values = {'name': key, 'value': value} - - if key not in existing: - rel_row = self._make_rel_row(row, rel_attr, values) - row[rel_attr].append(rel_row) - else: - existing[key].update(values) - - if purge: - for key in existing: - if not key in properties: - row[rel_attr].remove(existing[key]) - - # Currency - def currency_add(self, ctxt, values): - """ - Add a supported currency to the database - """ - data = common_utils.get_currency(values['name']) - row = models.Currency(**data) - self._save(row) - return dict(row) - - def currency_list(self, ctxt, **kw): - rows = self._list(models.Currency, **kw) - return map(dict, rows) - - def currency_get(self, ctxt, id_): - row = self._get(models.Currency, id_) - return dict(row) - - def currency_update(self, ctxt, id_, values): - row = self._update(models.Currency, id_, values) - return dict(row) - - def currency_delete(self, ctxt, id_): - self._delete(models.Currency, id_) - - # Language - def language_add(self, ctxt, values): - """ - Add a supported language to the database - """ - data = common_utils.get_language(values['name']) - row = models.Language(**data) - self._save(row) - return dict(row) - - def language_list(self, ctxt, **kw): - rows = self._list(models.Language, **kw) - return map(dict, rows) - - def language_get(self, ctxt, id_): - row = self._get(models.Language, id_) - return dict(row) - - def language_update(self, ctxt, id_, values): - row = self._update(models.Language, id_, values) - return dict(row) - - def language_delete(self, ctxt, id_): - self._delete(models.Language, id_) - - # ContactInfo - def contact_info_add(self, ctxt, obj, values, cls=None, - rel_attr='contact_info'): - """ - :param entity: The object to add the contact_info to - :param values: The values to add - """ - row = self._get_row(obj, cls=cls) - - rel_row = self._make_rel_row(obj, rel_attr, values) - - local, remote = db_utils.get_prop_names(row) - - if rel_attr in remote: - if isinstance(row[rel_attr], list): - row[rel_attr].append(rel_row) - else: - row[rel_attr] = rel_row - else: - msg = 'Attempted to set non-relation %s' % rel_attr - raise exceptions.BadRequest(msg) - - if cls: - self._save(rel_row) - return dict(rel_row) - else: - return rel_row - - def contact_info_get(self, ctxt, id_): - self._get(models.ContactInfo, id_) - - def contact_info_update(self, ctxt, id_, values): - return self._update(models.ContactInfo, id_, values) - - def contact_info_delete(self, ctxt, id_): - self._delete(models.ContactInfo, id_) - - # Payment Gateway Providers - def pg_provider_register(self, ctxt, values, methods=[]): - """ - Register a Provider and it's Methods - """ - query = self.session.query(models.PGProvider)\ - .filter_by(name=values['name']) - - try: - provider = query.one() - except exc.NoResultFound: - provider = models.PGProvider() - - provider.update(values) - - self._set_provider_methods(ctxt, provider, methods) - - self._save(provider) - return self._dict(provider, extra=['methods']) - - def pg_provider_list(self, ctxt, **kw): - """ - List available PG Providers - """ - rows = self._list(models.PGProvider, **kw) - return [self._dict(r, extra=['methods']) for r in rows] - - def pg_provider_get(self, ctxt, pgp_id): - row = self._get(models.PGProvider, pgp_id) - return self._dict(row, extra=['methods']) - - def pg_provider_deregister(self, ctxt, id_): - self._delete(models.PGProvider, id_) - - def _get_provider_methods(self, provider): - """ - Used internally to form a "Map" of the Providers methods - """ - methods = {} - for m in provider.methods: - m_key = m.key() - key = '%s:%s' % (m.owner_id, m_key) if m.owner_id else m_key - methods[key] = m - return methods - - def _set_provider_methods(self, ctxt, provider, config_methods): - """ - Helper method for setting the Methods for a Provider - """ - rows = self.pg_method_list(ctxt, criterion={"owner_id": None}) - system_methods = self._kv_rows(rows, key=models.PGMethod.make_key) - - existing = self._get_provider_methods(provider) - - for method in config_methods: - self._set_method(provider, method, existing, system_methods) - self._save(provider) - - def _set_method(self, provider, method, existing, all_methods): - method_key = models.PGMethod.make_key(method) - key = '%s:%s' % (provider.id, method_key) - - if method.pop('owned', False): - if method_key in existing: - provider.methods.remove(existing[method_key]) - - if key in existing: - existing[key].update(method) - else: - row = models.PGMethod(**method) - provider.methods.append(row) - provider.provider_methods.append(row) - else: - if key in existing: - provider.methods.remove(existing[key]) - - try: - all_methods[method_key].providers.append(provider) - except KeyError: - msg = 'Provider %s tried to associate to non-existing method %s' \ - % (provider.name, method_key) - LOG.error(msg) - raise exceptions.ConfigurationError(msg) - - # PGMethods - def pg_method_add(self, ctxt, values): - row = models.PGMethod(**values) - self._save(row) - return dict(row) - - def pg_method_list(self, ctxt, **kw): - return self._list(models.PGMethod, **kw) - - def pg_method_get(self, ctxt, id_): - return self._get(models.PGMethod, id_) - - def pg_method_update(self, ctxt, id_, values): - row = self._update(models.PGMethod, id_, values) - return dict(row) - - def pg_method_delete(self, ctxt, id_): - return self._delete(models.PGMethod, id_) - - # Payment Gateway Configuration - def pg_config_add(self, ctxt, merchant_id, provider_id, values): - merchant = self._get_id_or_name(models.Merchant, merchant_id) - provider = self._get_id_or_name(models.PGProvider, provider_id) - - row = models.PGAccountConfig(**values) - row.merchant = merchant - row.provider = provider - - self._save(row) - return dict(row) - - def pg_config_list(self, ctxt, **kw): - rows = self._list(models.PGAccountConfig, **kw) - return map(dict, rows) - - def pg_config_get(self, ctxt, id_): - row = self._get(models.PGAccountConfig, id_) - return dict(row) - - def pg_config_update(self, ctxt, id_, values): - row = self._update(models.PGAccountConfig, id_, values) - return dict(row) - - def pg_config_delete(self, ctxt, id_): - self._delete(models.PGAccountConfig, id_) - - # PaymentMethod - def payment_method_add(self, ctxt, customer_id, pg_method_id, values): - """ - Configure a PaymentMethod like a CreditCard - """ - customer = self._get_id_or_name(models.Customer, customer_id) - pg_method = self._get_id_or_name(models.PGMethod, pg_method_id) - - row = models.PaymentMethod(**values) - row.customer = customer - row.provider_method = pg_method - - self._save(row) - return self._dict(row, extra=['provider_method']) - - def payment_method_list(self, ctxt, **kw): - rows = self._list(models.PaymentMethod, **kw) - return [self._dict(row, extra=['provider_method']) for row in rows] - - def payment_method_get(self, ctxt, id_, **kw): - row = self._get_id_or_name(models.PaymentMethod, id_) - return self._dict(row, extra=['provider_method']) - - def payment_method_update(self, ctxt, id_, values): - row = self._update(models.PaymentMethod, id_, values) - return self._dict(row, extra=['provider_method']) - - def payment_method_delete(self, ctxt, id_): - self._delete(models.PaymentMethod, id_) - - # Merchant - def merchant_add(self, ctxt, values): - row = models.Merchant(**values) - - self._save(row) - return dict(row) - - def merchant_list(self, ctxt, **kw): - rows = self._list(models.Merchant, **kw) - return map(dict, rows) - - def merchant_get(self, ctxt, id_): - row = self._get(models.Merchant, id_) - return dict(row) - - def merchant_update(self, ctxt, id_, values): - row = self._update(models.Merchant, id_, values) - return dict(row) - - def merchant_delete(self, ctxt, id_): - self._delete(models.Merchant, id_) - - # Customer - def _customer(self, row): - data = dict(row) - - data['contact_info'] = [dict(i) for i in row.contact_info] - data['default_info'] = dict(row.default_info) if row.default_info\ - else {} - return data - - def customer_add(self, ctxt, merchant_id, values): - merchant = self._get(models.Merchant, merchant_id) - - contact_info = values.pop('contact_info', None) - customer = models.Customer(**values) - merchant.customers.append(customer) - - if contact_info: - info_row = self.contact_info_add(ctxt, customer, contact_info) - customer.default_info = info_row - - self._save(customer) - return self._customer(customer) - - def customer_list(self, ctxt, **kw): - rows = self._list(models.Customer, **kw) - return map(dict, rows) - - def customer_get(self, ctxt, id_): - row = self._get(models.Customer, id_) - return self._customer(row) - - def customer_update(self, ctxt, id_, values): - row = self._update(models.Customer, id_, values) - return self._customer(row) - - def customer_delete(self, ctxt, id_): - return self._delete(models.Customer, id_) - - # Products - def _product(self, row): - product = dict(row) - - product['properties'] = self._kv_rows(row.properties, func=lambda i: i['value']) - return product - - def product_add(self, ctxt, merchant_id, values): - """ - Add a new Product - - :param merchant_id: The Merchant - :param values: Values describing the new Product - """ - merchant = self._get(models.Merchant, merchant_id) - - properties = values.pop('properties', {}) - - product = models.Product(**values) - product.merchant = merchant - - self.set_properties(product, properties) - - self._save(product) - return self._product(product) - - def product_list(self, ctxt, **kw): - """ - List Products - - :param merchant_id: The Merchant to list it for - """ - rows = self._list(models.Product, **kw) - return map(self._product, rows) - - def product_get(self, ctxt, id_): - """ - Get a Product - - :param id_: The Product ID - """ - row = self._get(models.Product, id_) - return self._product(row) - - def product_update(self, ctxt, id_, values): - """ - Update a Product - - :param id_: The Product ID - :param values: Values to update with - """ - properties = values.pop('properties', {}) - - row = self._get(models.Product, id_) - row.update(values) - - self.set_properties(row, properties) - - self._save(row) - return self._product(row) - - def product_delete(self, ctxt, id_): - """ - Delete a Product - - :param id_: Product ID - """ - self._delete(models.Product, id_) - - # PlanItem - def plan_item_add(self, ctxt, values, save=True): - ref = models.PlanItem() - return self._plan_item_update(ref, values, save=save) - - def plan_item_update(self, ctxt, item, values, save=True): - return self._plan_item_update(item, values, save=save) - - def _plan_item_update(self, item, values, save=True): - row = self._get_row(item, models.PlanItem) - row.update(values) - return self._save(row, save=save) - - def plan_item_list(self, ctxt, **kw): - return self._list(models.PlanItem, **kw) - - def plan_item_get(self, ctxt, id_): - row = self._get(models.PlanItem, id_) - return dict(row) - - def plan_item_delete(self, ctxt, id_): - self._delete(models.PlanItem, id_) - - # Plan - def _plan(self, row): - plan = dict(row) - - plan['properties'] = self._kv_rows(row.properties, func=lambda i: i['value']) - plan['plan_items'] = map(dict, row.plan_items) if row.plan_items\ - else [] - return plan - - def plan_add(self, ctxt, merchant_id, values): - """ - Add a new Plan - - :param merchant_id: The Merchant - :param values: Values describing the new Plan - """ - merchant = self._get(models.Merchant, merchant_id) - - items = values.pop('plan_items', []) - properties = values.pop('properties', {}) - - plan = models.Plan(**values) - - plan.merchant = merchant - self.set_properties(plan, properties) - - for i in items: - item_row = self.plan_item_add(ctxt, i, save=False) - plan.plan_items.append(item_row) - - self._save(plan) - return self._plan(plan) - - def plan_list(self, ctxt, **kw): - """ - List Plan - - :param merchant_id: The Merchant to list it for - """ - rows = self._list(models.Plan, **kw) - return map(self._plan, rows) - - def plan_get(self, ctxt, id_): - """ - Get a Plan - - :param id_: The Plan ID - """ - row = self._get(models.Plan, id_) - return self._plan(row) - - def plan_update(self, ctxt, id_, values): - """ - Update a Plan - - :param id_: The Plan ID - :param values: Values to update with - """ - properties = values.pop('properties', {}) - - row = self._get(models.Plan, id_) - row.update(values) - - self.set_properties(row, properties) - - self._save(row) - return self._plan(row) - - def plan_delete(self, ctxt, id_): - """ - Delete a Plan - - :param id_: Plan ID - """ - self._delete(models.Plan, id_) diff --git a/billingstack/storage/impl_sqlalchemy/migration/README.md b/billingstack/storage/impl_sqlalchemy/migration/README.md deleted file mode 100644 index 2867029..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 -# -# Copyright 2012 New Dream Network, LLC (DreamHost) -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author Mark McClain (DreamHost) - -The migrations in the alembic/versions contain the changes needed to migrate -from older billingstack releases to newer versions. A migration occurs by executing -a script that details the changes needed to upgrade/downgrade the database. The -migration scripts are ordered so that multiple scripts can run sequentially to -update the database. The scripts are executed by billingstack's migration wrapper -which uses the Alembic library to manage the migration. billingstack supports -migration from Folsom or later. - - -If you are a deployer or developer and want to migrate from Folsom to Grizzly -or later you must first add version tracking to the database: - -$ billingstack-db-manage -config-file /path/to/quantum.conf \ - --config-file /path/to/plugin/config.ini stamp folsom - -You can then upgrade to the latest database version via: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ - --config-file /path/to/plugin/config.ini upgrade head - -To check the current database version: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ - --config-file /path/to/plugin/config.ini current - -To create a script to run the migration offline: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ - --config-file /path/to/plugin/config.ini upgrade head --sql - -To run the offline migration between specific migration versions: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini upgrade \ -: --sql - -Upgrade the database incrementally: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini upgrade --delta <# of revs> - -Downgrade the database by a certain number of revisions: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini downgrade --delta <# of revs> - - -DEVELOPERS: -A database migration script is required when you submit a change to billingstack -that alters the database model definition. The migration script is a special -python file that includes code to update/downgrade the database to match the -changes in the model definition. Alembic will execute these scripts in order to -provide a linear migration path between revision. The billingstack-db-manage command -can be used to generate migration template for you to complete. The operations -in the template are those supported by the Alembic migration library. - -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini revision \ --m "description of revision" \ ---autogenerate - -This generates a prepopulated template with the changes needed to match the -database state with the models. You should inspect the autogenerated template -to ensure that the proper models have been altered. - -In rare circumstances, you may want to start with an empty migration template -and manually author the changes necessary for an upgrade/downgrade. You can -create a blank file via: - -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini revision \ --m "description of revision" - -The migration timeline should remain linear so that there is a clear path when -upgrading/downgrading. To verify that the timeline does branch, you can run -this command: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini check_migration - -If the migration path does branch, you can find the branch point via: -$ billingstack-db-manage --config-file /path/to/quantum.conf \ ---config-file /path/to/plugin/config.ini history diff --git a/billingstack/storage/impl_sqlalchemy/migration/__init__.py b/billingstack/storage/impl_sqlalchemy/migration/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/storage/impl_sqlalchemy/migration/alembic.ini b/billingstack/storage/impl_sqlalchemy/migration/alembic.ini deleted file mode 100644 index 3b390b7..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/alembic.ini +++ /dev/null @@ -1,52 +0,0 @@ -# A generic, single database configuration. - -[alembic] -# path to migration scripts -script_location = %(here)s/alembic - -# template used to generate migration files -# file_template = %%(rev)s_%%(slug)s - -# set to 'true' to run the environment during -# the 'revision' command, regardless of autogenerate -# revision_environment = false - -# default to an empty string because the Quantum migration cli will -# extract the correct value and set it programatically before alemic is fully -# invoked. -sqlalchemy.url = - -# Logging configuration -[loggers] -keys = root,sqlalchemy,alembic - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = WARN -handlers = console -qualname = - -[logger_sqlalchemy] -level = WARN -handlers = -qualname = sqlalchemy.engine - -[logger_alembic] -level = INFO -handlers = -qualname = alembic - -[handler_console] -class = StreamHandler -args = (sys.stderr,) -level = NOTSET -formatter = generic - -[formatter_generic] -format = %(levelname)-5.5s [%(name)s] %(message)s -datefmt = %H:%M:%S diff --git a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/__init__.py b/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/env.py b/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/env.py deleted file mode 100644 index 31068d9..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/env.py +++ /dev/null @@ -1,91 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 -# -# Copyright 2012 New Dream Network, LLC (DreamHost) -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Mark McClain, DreamHost -# Copied: Quantum - -from logging.config import fileConfig - -from alembic import context -from sqlalchemy import create_engine, pool - -from billingstack.storage.impl_sqlalchemy.models import ModelBase -from billingstack.openstack.common import importutils - - -# this is the Alembic Config object, which provides -# access to the values within the .ini file in use. -config = context.config -billingstack_config = config.billingstack_config - -# Interpret the config file for Python logging. -# This line sets up loggers basically. -fileConfig(config.config_file_name) - -# set the target for 'autogenerate' support -target_metadata = ModelBase.metadata - - -def run_migrations_offline(): - """Run migrations in 'offline' mode. - - This configures the context with just a URL - and not an Engine, though an Engine is acceptable - here as well. By skipping the Engine creation - we don't even need a DBAPI to be available. - - Calls to context.execute() here emit the given string to the - script output. - - """ - context.configure(url=billingstack_config['storage:sqlalchemy'].database_connection) - - with context.begin_transaction(): - context.run_migrations(options=build_options()) - - -def run_migrations_online(): - """Run migrations in 'online' mode. - - In this scenario we need to create an Engine - and associate a connection with the context. - - """ - engine = create_engine( - billingstack_config['storage:sqlalchemy'].database_connection, - poolclass=pool.NullPool) - - connection = engine.connect() - context.configure( - connection=connection, - target_metadata=target_metadata - ) - - try: - with context.begin_transaction(): - context.run_migrations(options=build_options()) - finally: - connection.close() - - -def build_options(): - return {} - - -if context.is_offline_mode(): - run_migrations_offline() -else: - run_migrations_online() diff --git a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/script.py.mako b/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/script.py.mako deleted file mode 100644 index cbb4a7e..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/script.py.mako +++ /dev/null @@ -1,40 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 -# -# Copyright ${create_date.year} OpenStack LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# - -"""${message} - -Revision ID: ${up_revision} -Revises: ${down_revision} -Create Date: ${create_date} - -""" - - -# revision identifiers, used by Alembic. -revision = ${repr(up_revision)} -down_revision = ${repr(down_revision)} - -from alembic import op -import sqlalchemy as sa -${imports if imports else ""} - -def upgrade(options=None): - ${upgrades if upgrades else "pass"} - - -def downgrade(config=None): - ${downgrades if downgrades else "pass"} diff --git a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/versions/README b/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/versions/README deleted file mode 100644 index 4686c76..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/alembic_migrations/versions/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains the migration scripts for the billingstack project. Please -see the README in billinstack/db/migration on how to use and generate new -migrations. diff --git a/billingstack/storage/impl_sqlalchemy/migration/cli.py b/billingstack/storage/impl_sqlalchemy/migration/cli.py deleted file mode 100644 index bbd59cf..0000000 --- a/billingstack/storage/impl_sqlalchemy/migration/cli.py +++ /dev/null @@ -1,124 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 -# -# Copyright 2012 New Dream Network, LLC (DreamHost) -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# @author: Mark McClain, DreamHost -# Copied: Quantum -import os -import sys - -from alembic import command as alembic_command -from alembic import config as alembic_config -from alembic import util as alembic_util - -from oslo.config import cfg -from billingstack.openstack.common.gettextutils import _ - - -_db_opts = [ - cfg.StrOpt('database_connection', - default='', - help=_('URL to database')), -] - -CONF = cfg.ConfigOpts() -CONF.register_opts(_db_opts, 'storage:sqlalchemy') - - -def do_alembic_command(config, cmd, *args, **kwargs): - try: - getattr(alembic_command, cmd)(config, *args, **kwargs) - except alembic_util.CommandError, e: - alembic_util.err(str(e)) - - -def do_check_migration(config, cmd): - do_alembic_command(config, 'branches') - - -def do_upgrade_downgrade(config, cmd): - if not CONF.command.revision and not CONF.command.delta: - raise SystemExit(_('You must provide a revision or relative delta')) - - revision = CONF.command.revision - - if CONF.command.delta: - sign = '+' if CONF.command.name == 'upgrade' else '-' - revision = sign + str(CONF.command.delta) - else: - revision = CONF.command.revision - - do_alembic_command(config, cmd, revision, sql=CONF.command.sql) - - -def do_stamp(config, cmd): - do_alembic_command(config, cmd, - CONF.command.revision, - sql=CONF.command.sql) - - -def do_revision(config, cmd): - do_alembic_command(config, cmd, - message=CONF.command.message, - autogenerate=CONF.command.autogenerate, - sql=CONF.command.sql) - - -def add_command_parsers(subparsers): - for name in ['current', 'history', 'branches']: - parser = subparsers.add_parser(name) - parser.set_defaults(func=do_alembic_command) - - parser = subparsers.add_parser('check_migration') - parser.set_defaults(func=do_check_migration) - - for name in ['upgrade', 'downgrade']: - parser = subparsers.add_parser(name) - parser.add_argument('--delta', type=int) - parser.add_argument('--sql', action='store_true') - parser.add_argument('revision', nargs='?') - parser.set_defaults(func=do_upgrade_downgrade) - - parser = subparsers.add_parser('stamp') - parser.add_argument('--sql', action='store_true') - parser.add_argument('revision') - parser.set_defaults(func=do_stamp) - - parser = subparsers.add_parser('revision') - parser.add_argument('-m', '--message') - parser.add_argument('--autogenerate', action='store_true') - parser.add_argument('--sql', action='store_true') - parser.set_defaults(func=do_revision) - - -command_opt = cfg.SubCommandOpt('command', - title='Command', - help=_('Available commands'), - handler=add_command_parsers) - -CONF.register_cli_opt(command_opt) - - -def main(): - config = alembic_config.Config( - os.path.join(os.path.dirname(__file__), 'alembic.ini') - ) - config.set_main_option('script_location', - 'billingstack.storage.impl_sqlalchemy.migration:alembic_migrations') - # attach the Quantum conf to the Alembic conf - config.billingstack_config = CONF - - CONF() - CONF.command.func(config, CONF.command.name) diff --git a/billingstack/storage/impl_sqlalchemy/models.py b/billingstack/storage/impl_sqlalchemy/models.py deleted file mode 100644 index b26b144..0000000 --- a/billingstack/storage/impl_sqlalchemy/models.py +++ /dev/null @@ -1,446 +0,0 @@ -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -import re - -from sqlalchemy import Column, Table, ForeignKey, UniqueConstraint -from sqlalchemy import Integer, Float, Enum, Boolean -from sqlalchemy import DateTime, Unicode, UnicodeText -from sqlalchemy.orm import relationship, backref -from sqlalchemy.ext.hybrid import hybrid_property -from sqlalchemy.ext.declarative import declarative_base, declared_attr - -from billingstack import utils -from billingstack.openstack.common import log as logging -from billingstack.sqlalchemy.types import JSON, UUID -from billingstack.sqlalchemy.model_base import (ModelBase, BaseMixin, - PropertyMixin) - -LOG = logging.getLogger(__name__) - - -BASE = declarative_base(cls=ModelBase) - - -class Currency(BASE): - """ - Allowed currency - """ - name = Column(Unicode(10), nullable=False, primary_key=True) - title = Column(Unicode(100), nullable=False) - - -class Language(BASE): - """ - A Language - """ - name = Column(Unicode(10), nullable=False, primary_key=True) - title = Column(Unicode(100), nullable=False) - - -pg_provider_methods = Table('pg_provider_methods', BASE.metadata, - Column('provider_id', UUID, ForeignKey('pg_provider.id')), - Column('method_id', UUID, ForeignKey('pg_method.id'))) - - -class PGProvider(BASE, BaseMixin): - """ - A Payment Gateway - The thing that processes a Payment Method - - This is registered either by the Admin or by the PaymentGateway plugin - """ - __tablename__ = 'pg_provider' - - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(100)) - description = Column(Unicode(255)) - - properties = Column(JSON) - - methods = relationship( - 'PGMethod', - backref='providers', - secondary=pg_provider_methods, - primaryjoin="PGProvider.id==pg_provider_methods.c.provider_id", - secondaryjoin="PGMethod.id==pg_provider_methods.c.method_id", - lazy='joined') - - provider_methods = relationship( - 'PGMethod', - backref='owner', - primaryjoin='PGProvider.id == PGMethod.owner_id', - foreign_keys='[PGMethod.owner_id]', - post_update=True, - lazy='joined') - - def method_map(self): - return self.attrs_map(['provider_methods']) - - -class PGMethod(BASE, BaseMixin): - """ - This represents a PaymentGatewayProviders method with some information - like name, type etc to describe what is in other settings known as a - "CreditCard" - - Example: - A Visa card: {"type": "creditcard", "visa"} - """ - __tablename__ = 'pg_method' - - name = Column(Unicode(100), nullable=False) - title = Column(Unicode(100)) - description = Column(Unicode(255)) - - type = Column(Unicode(100), nullable=False) - properties = Column(JSON) - - # NOTE: This is so a PGMethod can be "owned" by a Provider, meaning that - # other Providers should not be able to use it. - owner_id = Column(UUID, ForeignKey( - 'pg_provider_methods.provider_id', - ondelete='CASCADE', - onupdate='CASCADE', - use_alter=True, - name='owner_fk')) - - @staticmethod - def make_key(data): - return '%(type)s:%(name)s' % data - - def key(self): - return self.make_key(self) - - -class ContactInfo(BASE, BaseMixin): - """ - Contact Information about an entity like a User, Customer etc... - """ - - @declared_attr - def __mapper_args__(cls): - name = unicode(utils.capital_to_underscore(cls.__name__)) - return {"polymorphic_on": "info_type", "polymorphic_identity": name} - - info_type = Column(Unicode(20), nullable=False) - - first_name = Column(Unicode(100)) - last_name = Column(Unicode(100)) - company = Column(Unicode(100)) - address1 = Column(Unicode(255)) - address2 = Column(Unicode(255)) - address3 = Column(Unicode(255)) - locality = Column(Unicode(60)) - region = Column(Unicode(60)) - country_name = Column(Unicode(100)) - postal_code = Column(Unicode(40)) - - phone = Column(Unicode(100)) - email = Column(Unicode(100)) - website = Column(Unicode(100)) - - -class CustomerInfo(ContactInfo): - id = Column(UUID, ForeignKey("contact_info.id", - onupdate='CASCADE', ondelete='CASCADE'), - primary_key=True) - - customer_id = Column(UUID, ForeignKey('customer.id'), nullable=False) - - -class Merchant(BASE, BaseMixin): - """ - A Merchant is like a Account in Recurly - """ - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(60)) - - customers = relationship('Customer', backref='merchant') - payment_gateways = relationship('PGAccountConfig', backref='merchant') - - plans = relationship('Plan', backref='merchant') - products = relationship('Product', backref='merchant') - - currency = relationship('Currency', uselist=False, backref='merchants') - currency_name = Column(Unicode(10), ForeignKey('currency.name'), nullable=False) - - language = relationship('Language', uselist=False, backref='merchants') - language_name = Column(Unicode(10), ForeignKey('language.name'), nullable=False) - - -class PGAccountConfig(BASE, BaseMixin): - """ - A Merchant's configuration of a PaymentGateway like api keys, url and more - """ - __tablename__ = 'pg_account_config' - name = Column(Unicode(100), nullable=False) - title = Column(Unicode(100)) - configuration = Column(JSON) - - # Link to the Merchant - merchant_id = Column(UUID, ForeignKey('merchant.id'), nullable=False) - - provider = relationship('PGProvider', - backref='merchant_configurations') - provider_id = Column(UUID, ForeignKey('pg_provider.id', - onupdate='CASCADE'), - nullable=False) - - -class Customer(BASE, BaseMixin): - """ - A Customer is linked to a Merchant and can have Users related to it - """ - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(60)) - - merchant_id = Column(UUID, ForeignKey('merchant.id', ondelete='CASCADE'), - nullable=False) - - invoices = relationship('Invoice', backref='customer') - payment_methods = relationship('PaymentMethod', backref='customer') - - contact_info = relationship( - 'CustomerInfo', - backref='customer', - primaryjoin='Customer.id == CustomerInfo.customer_id', - lazy='joined') - - default_info = relationship( - 'CustomerInfo', - primaryjoin='Customer.default_info_id == CustomerInfo.id', - uselist=False, - post_update=True) - default_info_id = Column( - UUID, - ForeignKey('customer_info.id', use_alter=True, - onupdate='CASCADE', name='default_info')) - - currency = relationship('Currency', uselist=False, backref='customers') - currency_name = Column(Unicode(10), ForeignKey('currency.name')) - - language = relationship('Language', uselist=False, backref='customers') - language_name = Column(Unicode(10), ForeignKey('language.name')) - - -class PaymentMethod(BASE, BaseMixin): - name = Column(Unicode(255), nullable=False) - - identifier = Column(Unicode(255), nullable=False) - expires = Column(Unicode(255)) - - properties = Column(JSON) - - customer_id = Column(UUID, ForeignKey('customer.id', onupdate='CASCADE'), - nullable=False) - - provider_method = relationship('PGMethod', - backref='payment_methods') - provider_method_id = Column(UUID, ForeignKey('pg_method.id', - onupdate='CASCADE')) - - -class InvoiceState(BASE): - """ - A State representing the currented state a Invoice is in - - Example: - Completed, Failed - """ - name = Column(Unicode(60), nullable=False, primary_key=True) - - -class Invoice(BASE, BaseMixin): - """ - An invoice - """ - identifier = Column(Unicode(255), nullable=False) - due = Column(DateTime, ) - - sub_total = Column(Float) - tax_percentage = Column(Float) - tax_total = Column(Float) - total = Column(Float) - - customer_id = Column(UUID, ForeignKey('customer.id', ondelete='CASCADE'), - nullable=False) - - line_items = relationship('InvoiceLine', backref='invoice_lines') - - state = relationship('InvoiceState', backref='invoices') - state_id = Column(Unicode(60), ForeignKey('invoice_state.name'), nullable=False) - - currency = relationship('Currency', backref='invoices') - currency_name = Column(Unicode(10), ForeignKey('currency.name'), nullable=False) - - merchant = relationship('Merchant', backref='invoices') - merchant_id = Column(UUID, ForeignKey('merchant.id', ondelete='CASCADE'), - nullable=False) - - -class InvoiceLine(BASE, BaseMixin): - """ - A Line item in which makes up the Invoice - """ - description = Column(Unicode(255)) - price = Column(Float) - quantity = Column(Float) - sub_total = Column(Float) - - invoice_id = Column(UUID, ForeignKey('invoice.id', ondelete='CASCADE', - onupdate='CASCADE'), nullable=False) - - -class Pricing(BASE, BaseMixin): - """ - Resembles a Price information in some way - """ - __tablename__ = 'product_pricing' - value_from = Column(Float) - value_to = Column(Float) - price = Column(Float, nullable=False) - - plan_item_id = Column(UUID, ForeignKey('plan_item.id', ondelete='CASCADE', - onupdate='CASCADE')) - product_id = Column(UUID, ForeignKey('product.id', ondelete='CASCADE', - onupdate='CASCADE')) - - -class Plan(BASE, BaseMixin): - """ - A Product collection like a "Virtual Web Cluster" with 10 servers - """ - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(100)) - description = Column(Unicode(255)) - #provider = Column(Unicode(255), nullable=False) - - plan_items = relationship('PlanItem', backref='plan') - - merchant_id = Column(UUID, ForeignKey('merchant.id', - ondelete='CASCADE'), nullable=False) - - -class PlanProperty(BASE, PropertyMixin): - __table_args__ = (UniqueConstraint('name', 'plan_id', name='plan'),) - - plan = relationship('Plan', backref='properties', lazy='joined') - plan_id = Column( - UUID, - ForeignKey('plan.id', - ondelete='CASCADE', - onupdate='CASCADE')) - - -class PlanItem(BASE, BaseMixin): - description = Column(Unicode(255)) - - price_rules = relationship( - 'Pricing', - backref=backref('plan_items', uselist=False), - lazy='dynamic', cascade='delete, delete-orphan', - passive_deletes=True) - - plan_id = Column(UUID, ForeignKey('plan.id', ondelete='CASCADE'), - onupdate='CASCADE', nullable=False) - - product = relationship('Product', backref='plan_items', uselist=False) - product_id = Column(UUID, ForeignKey('product.id', onupdate='CASCADE'), - nullable=False) - - -class Product(BASE, BaseMixin): - """ - A sellable Product, like vCPU hours, bandwidth units - """ - name = Column(Unicode(60), nullable=False) - title = Column(Unicode(100)) - description = Column(Unicode(255)) - - measure = Column(Unicode(255)) - source = Column(Unicode(255)) - type = Column(Unicode(255)) - - price = relationship('Pricing', backref='product', uselist=False) - - merchant_id = Column(UUID, ForeignKey('merchant.id', ondelete='CASCADE'), - nullable=False) - - -class ProductProperty(BASE, PropertyMixin): - """ - A Metadata row for something like Product or PlanItem - """ - __table_args__ = (UniqueConstraint('name', 'product_id', name='product'),) - - product = relationship('Product', backref='properties', lazy='joined') - product_id = Column( - UUID, - ForeignKey('product.id', - ondelete='CASCADE', - onupdate='CASCADE')) - - -class Subscription(BASE, BaseMixin): - """ - The thing that ties together stuff that is to be billed - - In other words a Plan which is a collection of Products or a Product. - """ - billing_day = Column(Integer) - - resource_id = Column(Unicode(255)) - resource_type = Column(Unicode(255)) - - usages = relationship( - 'Usage', - backref='subscription', - lazy='dynamic', - cascade='delete, delete-orphan', - passive_deletes=True) - - plan = relationship('Plan', backref='subscriptions', uselist=False) - plan_id = Column(UUID, ForeignKey('plan.id', ondelete='CASCADE'), - nullable=False) - - customer = relationship('Customer', backref='subscriptions') - customer_id = Column(UUID, ForeignKey('customer.id', ondelete='CASCADE'), - nullable=False) - - payment_method = relationship('PaymentMethod', backref='subscriptions') - payment_method_id = Column(UUID, ForeignKey('payment_method.id', - ondelete='CASCADE', - onupdate='CASCADE'), - nullable=False) - - -class Usage(BASE, BaseMixin): - """ - A record of something that's used from for example a Metering system like - Ceilometer - """ - measure = Column(Unicode(255)) - start_timestamp = Column(DateTime) - end_timestamp = Column(DateTime) - - price = Column(Float) - total = Column(Float) - value = Column(Float) - - product = relationship('Product', backref='usages') - prodoct_id = Column(UUID, ForeignKey('product.id', onupdate='CASCADE'), - nullable=False) - - subscription_id = Column(UUID, ForeignKey('subscription.id', - onupdate='CASCADE'), - nullable=False) diff --git a/billingstack/tests/__init__.py b/billingstack/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/tests/api/__init__.py b/billingstack/tests/api/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/billingstack/tests/api/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/billingstack/tests/api/base.py b/billingstack/tests/api/base.py deleted file mode 100644 index 4915039..0000000 --- a/billingstack/tests/api/base.py +++ /dev/null @@ -1,198 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 New Dream Network, LLC (DreamHost) -# -# Author: Doug Hellmann -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -Base classes for API tests. -""" -import os - -from pecan import set_config -from pecan.testing import load_test_app - -from billingstack.openstack.common import jsonutils as json -from billingstack.openstack.common import log -from billingstack.tests.base import TestCase - - -LOG = log.getLogger(__name__) - - -class PecanTestMixin(object): - PATH_PREFIX = '' - - path = "" - - def item_path(self, *args): - url = self.path + '/%s' - return url % args - - def make_path(self, path): - if not path.startswith('/'): - path = '/' + path - return self.PATH_PREFIX + path - - def _query(self, queries): - query_params = {'q.field': [], - 'q.value': [], - 'q.op': [], - } - for query in queries: - for name in ['field', 'op', 'value']: - query_params['q.%s' % name].append(query.get(name, '')) - return query_params - - def _params(self, params, queries): - all_params = {} - all_params.update(params) - if queries: - all_params.update(self._query(queries)) - return all_params - - def get(self, path, headers=None, - q=[], status_code=200, **params): - path = self.make_path(path) - all_params = self._params(params, q) - - LOG.debug('GET: %s %r', path, all_params) - - response = self.app.get(path, - params=all_params, - headers=headers) - - LOG.debug('GOT RESPONSE: %s', response) - - self.assertEqual(response.status_code, status_code) - - return response - - def post(self, path, data, headers=None, content_type="application/json", - q=[], status_code=200): - path = self.make_path(path) - - LOG.debug('POST: %s %s', path, data) - - content = json.dumps(data) - response = self.app.post( - path, - content, - content_type=content_type, - headers=headers) - - LOG.debug('POST RESPONSE: %r' % response.body) - - self.assertEqual(response.status_code, status_code) - - return response - - def put(self, path, data, headers=None, content_type="application/json", - q=[], status_code=200, **params): - path = self.make_path(path) - - LOG.debug('PUT: %s %s', path, data) - - content = json.dumps(data) - response = self.app.put( - path, - content, - content_type=content_type, - headers=headers) - - self.assertEqual(response.status_code, status_code) - - LOG.debug('PUT RESPONSE: %r' % response.body) - - return response - - def delete(self, path, status_code=200, headers=None, q=[], **params): - path = self.make_path(path) - all_params = self._params(params, q) - - LOG.debug('DELETE: %s %r', path, all_params) - - response = self.app.delete(path, params=all_params) - - LOG.debug('DELETE RESPONSE: %r' % response.body) - - self.assertEqual(response.status_code, status_code) - - return response - - def make_app(self, enable_acl=False): - # This is done like this because if you import load_test_app in 2 diff - # modules it will fail with a PECAN_CONFIG error. - return load_test_app(self.make_config(enable_acl=enable_acl)) - - -class FunctionalTest(TestCase, PecanTestMixin): - """ - billingstack.api base test - """ - def setUp(self): - super(FunctionalTest, self).setUp() - - # NOTE: Needs to be started after the db schema is created - self.central_service = self.get_central_service() - self.central_service.start() - - self.setSamples() - - self.app = self.make_app() - - def tearDown(self): - super(FunctionalTest, self).tearDown() - set_config({}, overwrite=True) - - - def make_config(self, enable_acl=True): - root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), - '..', - '..', - ) - ) - - return { - 'app': { - 'root': 'billingstack.api.root.RootController', - 'modules': ['billingstack.api'], - 'static_root': '%s/public' % root_dir, - 'template_path': '%s/billingstack/api/templates' % root_dir, - 'enable_acl': enable_acl, - }, - - 'logging': { - 'loggers': { - 'root': {'level': 'INFO', 'handlers': ['console']}, - 'wsme': {'level': 'INFO', 'handlers': ['console']}, - 'billingstack': {'level': 'DEBUG', - 'handlers': ['console'], - }, - }, - 'handlers': { - 'console': { - 'level': 'DEBUG', - 'class': 'logging.StreamHandler', - 'formatter': 'simple' - } - }, - 'formatters': { - 'simple': { - 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' - '[%(threadName)s] %(message)s') - } - }, - }, - } diff --git a/billingstack/tests/api/v1/__init__.py b/billingstack/tests/api/v1/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/billingstack/tests/api/v1/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/billingstack/tests/api/v1/base.py b/billingstack/tests/api/v1/base.py deleted file mode 100644 index 61d8b14..0000000 --- a/billingstack/tests/api/v1/base.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 New Dream Network, LLC (DreamHost) -# -# Author: Doug Hellmann -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from billingstack.tests.api import base - - -class FunctionalTest(base.FunctionalTest): - PATH_PREFIX = '/v1' diff --git a/billingstack/tests/api/v1/test_customer.py b/billingstack/tests/api/v1/test_customer.py deleted file mode 100644 index 21acb1a..0000000 --- a/billingstack/tests/api/v1/test_customer.py +++ /dev/null @@ -1,82 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -Test Customers. -""" - -from billingstack.tests.api.v1.base import FunctionalTest -from billingstack.api.v1.models import Customer - - -class TestCustomer(FunctionalTest): - __test__ = True - path = "merchants/%s/customers" - - def fixture(self): - fixture = self.get_fixture('customer') - self._account_defaults(fixture) - expected = Customer.from_db(fixture).as_dict() - return expected - - def test_customer_add(self): - expected = self.fixture() - - url = self.path % self.merchant['id'] - - resp = self.post(url, expected) - - self.assertData(expected, resp.json) - - def test_customer_list(self): - url = self.path % self.merchant['id'] - - resp = self.get(url) - self.assertLen(0, resp.json) - - self.customer_add(self.merchant['id']) - - resp = self.get(url) - self.assertLen(1, resp.json) - - def test_customer_get(self): - _, customer = self.customer_add(self.merchant['id']) - - expected = Customer.from_db(customer).as_dict() - - url = self.item_path(self.merchant['id'], customer['id']) - resp = self.get(url) - - self.assertData(expected, resp.json) - - def test_customer_update(self): - _, customer = self.customer_add(self.merchant['id']) - - expected = Customer.from_db(customer).as_dict() - - expected['name'] = 'test' - - url = self.item_path(self.merchant['id'], customer['id']) - resp = self.put(url, customer) - - self.assertData(resp.json, customer) - - def test_customer_delete(self): - _, customer = self.customer_add(self.merchant['id']) - - url = self.item_path(self.merchant['id'], customer['id']) - self.delete(url) - - self.assertLen(0, self.central_service.customer_list(self.admin_ctxt)) diff --git a/billingstack/tests/api/v1/test_merchant.py b/billingstack/tests/api/v1/test_merchant.py deleted file mode 100644 index 977b741..0000000 --- a/billingstack/tests/api/v1/test_merchant.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -Test Merchants -""" - -from billingstack.tests.api.v1.base import FunctionalTest -from billingstack.api.v1.models import Merchant - - -class TestMerchant(FunctionalTest): - __test__ = True - - def fixture(self): - fixture = self.get_fixture('merchant') - self._account_defaults(fixture) - expected = Merchant.from_db(fixture).as_dict() - return expected - - def test_merchant_add(self): - expected = self.fixture() - - resp = self.post('merchants', expected) - - self.assertData(expected, resp.json) - - def test_merchant_list(self): - resp = self.get('merchants') - self.assertLen(1, resp.json) - - def test_merchant_get(self): - expected = Merchant.from_db(self.merchant).as_dict() - - resp = self.get('merchants/' + self.merchant['id']) - - self.assertData(expected, resp.json) - - def test_merchant_update(self): - expected = Merchant.from_db(self.merchant).as_dict() - - resp = self.put('merchants/' + self.merchant['id'], expected) - - self.assertData(expected, resp.json) - - def test_merchant_delete(self): - self.delete('merchants/' + self.merchant['id']) - self.assertLen(0, self.central_service.merchant_list(self.admin_ctxt)) diff --git a/billingstack/tests/api/v1/test_plan.py b/billingstack/tests/api/v1/test_plan.py deleted file mode 100644 index d1fcdf1..0000000 --- a/billingstack/tests/api/v1/test_plan.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -Test Plans -""" - -from billingstack.tests.api.v1.base import FunctionalTest - - -class TestPlan(FunctionalTest): - __test__ = True - path = "merchants/%s/plans" - - def test_plan_add(self): - fixture = self.get_fixture('plan') - - url = self.path % self.merchant['id'] - - resp = self.post(url, fixture) - - self.assertData(fixture, resp.json) - - def test_plan_list(self): - self.plan_add(self.merchant['id']) - - url = self.path % self.merchant['id'] - resp = self.get(url) - - self.assertLen(1, resp.json) - - def test_plan_get(self): - _, plan = self.plan_add(self.merchant['id']) - - url = self.item_path(self.merchant['id'], plan['id']) - resp = self.get(url) - - self.assertData(resp.json, plan) - - def test_plan_update(self): - _, plan = self.plan_add(self.merchant['id']) - plan['name'] = 'test' - - url = self.item_path(self.merchant['id'], plan['id']) - resp = self.put(url, plan) - - self.assertData(resp.json, plan) - - def test_plan_delete(self): - _, plan = self.plan_add(self.merchant['id']) - - url = self.item_path(self.merchant['id'], plan['id']) - self.delete(url) - - self.assertLen(0, self.central_service.plan_list(self.admin_ctxt)) diff --git a/billingstack/tests/api/v1/test_product.py b/billingstack/tests/api/v1/test_product.py deleted file mode 100644 index ad8c92e..0000000 --- a/billingstack/tests/api/v1/test_product.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- encoding: utf-8 -*- -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -""" -Test Products -""" - -import logging - -from billingstack.tests.api.v1.base import FunctionalTest - -LOG = logging.getLogger(__name__) - - -class TestProduct(FunctionalTest): - __test__ = True - path = "merchants/%s/products" - - def test_product_add(self): - fixture = self.get_fixture('product') - - url = self.path % self.merchant['id'] - resp = self.post(url, fixture) - - self.assertData(fixture, resp.json) - - def test_product_list(self): - self.product_add(self.merchant['id']) - - url = self.path % self.merchant['id'] - resp = self.get(url) - - self.assertLen(1, resp.json) - - def test_product_get(self): - _, product = self.product_add(self.merchant['id']) - - url = self.item_path(self.merchant['id'], product['id']) - resp = self.get(url) - - self.assertData(resp.json, product) - - def test_product_update(self): - _, product = self.product_add(self.merchant['id']) - product['name'] = 'test' - - url = self.item_path(self.merchant['id'], product['id']) - resp = self.put(url, product) - - self.assertData(resp.json, product) - - def test_product_delete(self): - _, product = self.product_add(self.merchant['id']) - - url = self.item_path(self.merchant['id'], product['id']) - self.delete(url) - - self.assertLen(0, self.central_service.product_list(self.admin_ctxt)) diff --git a/billingstack/tests/base.py b/billingstack/tests/base.py deleted file mode 100644 index cb715fe..0000000 --- a/billingstack/tests/base.py +++ /dev/null @@ -1,212 +0,0 @@ -import copy -import unittest2 -import mox -from oslo.config import cfg -# NOTE: Currently disabled -# from billingstack.openstack.common import policy -from billingstack import exceptions -from billingstack import samples -from billingstack import storage -from billingstack.central import service as central_service -from billingstack.openstack.common import log as logging -from billingstack.openstack.common.context import RequestContext, get_admin_context - - -cfg.CONF.import_opt('storage_driver', 'billingstack.central', - group='service:central') -cfg.CONF.import_opt('database_connection', - 'billingstack.storage.impl_sqlalchemy', - group='storage:sqlalchemy') - - -class AssertMixin(object): - """ - Mixin to hold assert helpers. - - """ - def assertLen(self, expected_length, obj): - """ - Assert a length of a object - - :param obj: The object ot run len() on - :param expected_length: The length in Int that's expected from len(obj) - """ - self.assertEqual(len(obj), expected_length) - - def assertData(self, expected_data, data): - """ - A simple helper to very that at least fixture data is the same - as returned - - :param expected_data: Data that's expected - :param data: Data to check expected_data against - """ - for key, value in expected_data.items(): - self.assertEqual(data[key], value) - - def assertDuplicate(self, func, *args, **kw): - exception = kw.pop('exception', exceptions.Duplicate) - with self.assertRaises(exception): - func(*args, **kw) - - def assertMissing(self, func, *args, **kw): - exception = kw.pop('exception', exceptions.NotFound) - with self.assertRaises(exception): - func(*args, **kw) - - -class BaseTestCase(unittest2.TestCase, AssertMixin): - """ - A base test class. - """ - def setUp(self): - super(BaseTestCase, self).setUp() - self.mox = mox.Mox() - - def tearDown(self): - cfg.CONF.reset() - self.mox.UnsetStubs() - self.mox.VerifyAll() - super(BaseTestCase, self).tearDown() - - # Config Methods - def config(self, **kwargs): - group = kwargs.pop('group', None) - - for k, v in kwargs.iteritems(): - cfg.CONF.set_override(k, v, group) - - def get_fixture(self, name, fixture=0, values={}): - """ - Get a fixture from self.samples and override values if necassary - """ - _values = copy.copy(self.samples[name][fixture]) - _values.update(values) - return _values - - def get_admin_context(self): - return get_admin_context() - - def get_context(self, **kw): - return RequestContext(**kw) - - -class TestCase(BaseTestCase): - def setUp(self): - super(TestCase, self).setUp() - - self.config( - rpc_backend='billingstack.openstack.common.rpc.impl_fake', - ) - - self.config( - storage_driver='sqlalchemy', - group='service:central' - ) - - self.config( - database_connection='sqlite://', - group='storage:sqlalchemy' - ) - - self.samples = samples.get_samples() - - storage.setup_schema() - - self.admin_ctxt = self.get_admin_context() - - def tearDown(self): - # NOTE: Currently disabled - #policy.reset() - storage.teardown_schema() - super(TestCase, self).tearDown() - - - def get_storage_driver(self): - connection = storage.get_connection() - return connection - - def get_central_service(self): - return central_service.Service() - - def get_api_service(self): - return api_service.Service() - - def setSamples(self): - _, self.pg_method = self.pg_method_add() - _, self.currency = self.currency_add() - _, self.language = self.language_add() - _, self.merchant = self.merchant_add() - - def language_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('language', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.language_add(ctxt, fixture, **kw) - - def currency_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('currency', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.currency_add(ctxt, fixture, **kw) - - def pg_provider_register(self, fixture=0, values={}, methods=[], **kw): - methods = [self.get_fixture('pg_method')] or methods - fixture = self.get_fixture('pg_provider', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - - data = self.central_service.pg_provider_register(ctxt, fixture, methods=methods, **kw) - - fixture['methods'] = methods - return fixture, data - - def pg_method_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('pg_method') - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.pg_method_add(ctxt, fixture) - - def _account_defaults(self, values): - # NOTE: Do defaults - if not 'currency_name' in values: - values['currency_name'] = self.currency['name'] - - if not 'language_name' in values: - values['language_name'] = self.language['name'] - - def merchant_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('merchant', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - - self._account_defaults(fixture) - - return fixture, self.central_service.merchant_add(ctxt, fixture, **kw) - - def pg_config_add(self, provider_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('pg_config', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.pg_config_add(ctxt, self.merchant['id'], provider_id, fixture, **kw) - - def customer_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('customer', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - self._account_defaults(fixture) - return fixture, self.central_service.customer_add(ctxt, merchant_id, fixture, **kw) - - def payment_method_add(self, customer_id, provider_method_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('payment_method', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.payment_method_add( - ctxt, customer_id, provider_method_id, fixture, **kw) - - def user_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('user', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.user_add(ctxt, merchant_id, fixture, **kw) - - def product_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('product', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.product_add(ctxt, merchant_id, fixture, **kw) - - def plan_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('plan', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.central_service.plan_add(ctxt, merchant_id, fixture, **kw) diff --git a/billingstack/tests/identity/__init__.py b/billingstack/tests/identity/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/tests/identity/test_api.py b/billingstack/tests/identity/test_api.py deleted file mode 100644 index 36f7181..0000000 --- a/billingstack/tests/identity/test_api.py +++ /dev/null @@ -1,261 +0,0 @@ -import os - -from pecan import set_config - -from oslo.config import cfg - -from billingstack.samples import get_samples -from billingstack.identity.base import IdentityPlugin -from billingstack.tests.api.base import PecanTestMixin -from billingstack.tests.base import BaseTestCase - - -cfg.CONF.import_opt('database_connection', - 'billingstack.identity.impl_sqlalchemy', - group='identity:sqlalchemy') - - -ROLE = { - 'name': 'Member' -} - - -class IdentityAPITest(BaseTestCase, PecanTestMixin): - """ - billingstack.api base test - """ - PATH_PREFIX = '/v1' - - def setUp(self): - super(IdentityAPITest, self).setUp() - - self.samples = get_samples() - - self.config( - storage_driver='sqlalchemy', - group='service:identity_api' - ) - - self.config( - database_connection='sqlite://', - group='identity:sqlalchemy') - - self.plugin = IdentityPlugin.get_plugin(invoke_on_load=True) - self.plugin.setup_schema() - - self.app = self.make_app() - - def tearDown(self): - self.plugin.teardown_schema() - super(IdentityAPITest, self).tearDown() - set_config({}, overwrite=True) - - - def make_config(self, enable_acl=True): - root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), - '..', - '..', - ) - ) - - return { - 'app': { - 'root': 'billingstack.identity.api.v1.RootController', - 'modules': ['billingstack.identity.api'], - 'static_root': '%s/public' % root_dir, - 'template_path': '%s/api/templates' % root_dir, - 'enable_acl': enable_acl, - }, - - 'logging': { - 'loggers': { - 'root': {'level': 'INFO', 'handlers': ['console']}, - 'wsme': {'level': 'INFO', 'handlers': ['console']}, - 'billingstack': {'level': 'DEBUG', - 'handlers': ['console'], - }, - }, - 'handlers': { - 'console': { - 'level': 'DEBUG', - 'class': 'logging.StreamHandler', - 'formatter': 'simple' - } - }, - 'formatters': { - 'simple': { - 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]' - '[%(threadName)s] %(message)s') - } - }, - }, - } - - # Accounts - def test_create_account(self): - values = self.get_fixture('merchant') - values['type'] = 'merchant' - - self.post('accounts', values) - - def test_list_accounts(self): - resp = self.get('accounts') - self.assertLen(0, resp.json) - - def test_get_account(self): - values = self.get_fixture('merchant') - values['type'] = 'merchant' - - resp = self.post('accounts', values) - - resp_actual = self.get('accounts/%s' % resp.json['id']) - - self.assertData(resp.json, resp_actual.json) - - def test_update_account(self): - values = self.get_fixture('merchant') - values['type'] = 'merchant' - - resp = self.post('accounts', values) - - expected = dict(resp.json, name='Merchant') - - resp = self.put('accounts/%s' % expected['id'], expected) - - self.assertData(expected, resp.json) - - def test_delete_account(self): - values = self.get_fixture('merchant') - values['type'] = 'merchant' - - resp = self.post('accounts', values) - - self.delete('accounts/%s' % resp.json['id']) - - resp = self.get('accounts') - self.assertLen(0, resp.json) - - def test_create_account(self): - values = self.get_fixture('merchant') - values['type'] = 'merchant' - - self.post('accounts', values) - - # Roles - def test_create_role(self): - values = ROLE.copy() - - resp = self.post('roles', values) - - assert resp.json['name'] == values['name'] - assert resp.json['id'] != None - - def test_list_roles(self): - resp = self.get('roles') - self.assertLen(0, resp.json) - - def test_get_role(self): - values = ROLE.copy() - - resp = self.post('roles', values) - - resp_actual = self.get('roles/%s' % resp.json['id']) - - self.assertData(resp.json, resp_actual.json) - - def test_update_role(self): - values = ROLE.copy() - - resp = self.post('roles', values) - - expected = dict(resp.json, name='SuperMember') - - resp = self.put('roles/%s' % expected['id'], expected) - - self.assertData(expected, resp.json) - - def test_delete_role(self): - values = ROLE.copy() - - resp = self.post('roles', values) - - self.delete('roles/%s' % resp.json['id']) - - resp = self.get('roles') - self.assertLen(0, resp.json) - - def test_create_user(self): - values = self.get_fixture('user') - - self.post('users', values) - - def test_list_users(self): - resp = self.get('users') - self.assertLen(0, resp.json) - - def test_get_user(self): - values = self.get_fixture('user') - - resp = self.post('users', values) - - resp_actual = self.get('users/%s' % resp.json['id']) - - self.assertData(resp.json, resp_actual.json) - - def test_update_user(self): - values = self.get_fixture('user') - - resp = self.post('users', values) - - expected = dict(resp.json, name='test') - - resp = self.put('users/%s' % expected['id'], expected) - - self.assertData(expected, resp.json) - - def test_delete_user(self): - values = self.get_fixture('user') - - resp = self.post('users', values) - - self.delete('users/%s' % resp.json['id']) - - resp = self.get('users') - self.assertLen(0, resp.json) - - # Grants - def test_create_grant(self): - account_data = self.get_fixture('merchant') - account_data['type'] = 'merchant' - - account = self.post('accounts', account_data).json - - user_data = self.get_fixture('user') - user = self.post('users', user_data).json - - role_data = ROLE.copy() - role = self.post('roles', role_data).json - - url = 'accounts/%s/users/%s/roles/%s' % ( - account['id'], user['id'], role['id']) - - self.put(url, {}) - - def test_revoke_grant(self): - account_data = self.get_fixture('merchant') - account_data['type'] = 'merchant' - - account = self.post('accounts', account_data).json - - user_data = self.get_fixture('user') - user = self.post('users', user_data).json - - role_data = ROLE.copy() - role = self.post('roles', role_data).json - - url = 'accounts/%s/users/%s/roles/%s' % ( - account['id'], user['id'], role['id']) - - self.put(url, {}) - - self.delete(url) \ No newline at end of file diff --git a/billingstack/tests/payment_gateway/__init__.py b/billingstack/tests/payment_gateway/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/billingstack/tests/payment_gateway/base.py b/billingstack/tests/payment_gateway/base.py deleted file mode 100644 index 3983445..0000000 --- a/billingstack/tests/payment_gateway/base.py +++ /dev/null @@ -1,59 +0,0 @@ -from billingstack.openstack.common import log -from billingstack.tests.base import TestCase - - -LOG = log.getLogger(__name__) - - -class ProviderTestCase(TestCase): - """ - Common set of tests for the API that all Providers should implement - """ - __test__ = False - - def setUp(self): - super(ProviderTestCase, self).setUp() - - info = self.get_fixture('contact_info') - _, self.customer = self.customer_add( - self.merchant['id'], - contact_info=info) - - _, self.provider = self.pg_provider_register() - - def test_account_add(self): - expected = self.pgp.account_add(self.customer) - - def test_account_list(self): - expected = self.pgp.account_add(self.customer) - actual = self.pgp.account_list() - - def test_account_get(self): - expected = self.pgp.account_add(self.customer) - actual = self.pgp.account_get(self.customer['id']) - - def test_account_delete(self): - data = self.pgp.account_add(self.customer) - self.pgp.account_delete(data['id']) - - def pm_create(self): - """ - Create all the necassary things to make a card - """ - fixture, data = self.payment_method_add( - self.customer['id'], - self.provider['methods'][0]['id']) - - self.pgp.account_add(self.customer) - return fixture, self.pgp.payment_method_add(data) - - def test_payment_method_add(self): - fixture, pm = self.pm_create() - - def test_payment_method_list(self): - fixture, pm = self.pm_create() - assert len(self.pgp.payment_method_list(self.customer['id'])) == 1 - - def test_payment_method_get(self): - fixture, pm = self.pm_create() - assert pm == self.pgp.payment_method_get(pm['id']) diff --git a/billingstack/tests/storage/__init__.py b/billingstack/tests/storage/__init__.py deleted file mode 100644 index 9c40bc9..0000000 --- a/billingstack/tests/storage/__init__.py +++ /dev/null @@ -1,454 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Copied: Moniker -from billingstack.openstack.common import log as logging -from billingstack.storage.impl_sqlalchemy import models -from billingstack.tests.base import TestCase - - -LOG = logging.getLogger(__name__) - - -UUID = 'caf771fc-6b05-4891-bee1-c2a48621f57b' - - -class StorageDriverTestCase(TestCase): - __test__ = False - - def setUp(self): - super(StorageDriverTestCase, self).setUp() - self.storage_conn = self.get_storage_driver() - self.setSamples() - - def language_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('language', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.language_add(ctxt, fixture, **kw) - - def currency_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('currency', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.currency_add(ctxt, fixture, **kw) - - def pg_provider_register(self, fixture=0, values={}, methods=[], **kw): - methods = [self.get_fixture('pg_method')] or methods - fixture = self.get_fixture('pg_provider', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - - data = self.storage_conn.pg_provider_register(ctxt, fixture, methods=methods, **kw) - - fixture['methods'] = methods - return fixture, data - - def pg_method_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('pg_method') - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.pg_method_add(ctxt, fixture) - - def merchant_add(self, fixture=0, values={}, **kw): - fixture = self.get_fixture('merchant', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - - self._account_defaults(fixture) - - return fixture, self.storage_conn.merchant_add(ctxt, fixture, **kw) - - def pg_config_add(self, provider_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('pg_config', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.pg_config_add(ctxt, self.merchant['id'], provider_id, fixture, **kw) - - def customer_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('customer', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - self._account_defaults(fixture) - return fixture, self.storage_conn.customer_add(ctxt, merchant_id, fixture, **kw) - - def payment_method_add(self, customer_id, provider_method_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('payment_method', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.payment_method_add( - ctxt, customer_id, provider_method_id, fixture, **kw) - - def product_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('product', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.product_add(ctxt, merchant_id, fixture, **kw) - - def plan_add(self, merchant_id, fixture=0, values={}, **kw): - fixture = self.get_fixture('plan', fixture, values) - ctxt = kw.pop('context', self.admin_ctxt) - return fixture, self.storage_conn.plan_add(ctxt, merchant_id, fixture, **kw) - - # Currencies - def test_currency_add(self): - self.assertDuplicate(self.currency_add) - - # Languages - def test_language_add(self): - self.assertDuplicate(self.language_add) - - def test_set_properties(self): - fixture, data = self.product_add(self.merchant['id']) - - metadata = {"random": True} - self.storage_conn.set_properties(data['id'], metadata, cls=models.Product) - - metadata.update({'foo': 1, 'bar': 2}) - self.storage_conn.set_properties(data['id'], metadata, cls=models.Product) - - actual = self.storage_conn.product_get(self.admin_ctxt, data['id']) - self.assertLen(4, actual['properties']) - - # Payment Gateways - def test_pg_provider_register(self): - fixture, actual = self.pg_provider_register() - self.assertEqual(fixture['name'], actual['name']) - self.assertEqual(fixture['title'], actual['title']) - self.assertEqual(fixture['description'], actual['description']) - self.assertData(fixture['methods'][0], actual['methods'][0]) - - def test_pg_provider_register_different_methods(self): - # Add a Global method - method1 = {'type': 'creditcard', 'name': 'mastercard'} - self.storage_conn.pg_method_add(self.admin_ctxt, method1) - - method2 = {'type': 'creditcard', 'name': 'amex'} - self.storage_conn.pg_method_add(self.admin_ctxt, method2) - - method3 = {'type': 'creditcard', 'name': 'visa', 'owned': 1} - - methods = [method1, method2, method3] - provider = {'name': 'noop'} - - provider = self.storage_conn.pg_provider_register(self.admin_ctxt, provider, methods) - - # TODO(ekarls): Make this more extensive? - self.assertLen(3, provider['methods']) - - def test_pg_provider_register_method_switch_methods(self): - provider_data = {'name': 'noop'} - - system_method = { - 'type': 'creditcard', - 'name': 'mastercard', - 'title': "random"} - self.storage_conn.pg_method_add(self.admin_ctxt, system_method) - - provider = self.storage_conn.pg_provider_register( - self.admin_ctxt, - provider_data, - [system_method]) - self.assertLen(1, provider['methods']) - self.assertData(system_method, provider['methods'][0]) - - provider_method = { - 'type': 'creditcard', - 'name': 'mastercard', - 'title': 'random2', - 'owned': 1} - - provider = self.storage_conn.pg_provider_register( - self.admin_ctxt, - provider_data, - [provider_method]) - self.assertLen(1, provider['methods']) - self.assertData(provider_method, provider['methods'][0]) - - provider = self.storage_conn.pg_provider_register( - self.admin_ctxt, - provider_data, - [system_method]) - self.assertLen(1, provider['methods']) - self.assertData(system_method, provider['methods'][0]) - - def test_pg_provider_get(self): - _, expected = self.pg_provider_register() - actual = self.storage_conn.pg_provider_get(self.admin_ctxt, expected['id']) - self.assertData(expected, actual) - - def test_pg_provider_get_missing(self): - self.assertMissing(self.storage_conn.pg_provider_get, self.admin_ctxt, UUID) - - def test_pg_provider_deregister(self): - _, data = self.pg_provider_register() - self.storage_conn.pg_provider_deregister(self.admin_ctxt, data['id']) - self.assertMissing(self.storage_conn.pg_provider_deregister, self.admin_ctxt, data['id']) - - def test_pg_provider_deregister_missing(self): - self.assertMissing(self.storage_conn.pg_provider_deregister, self.admin_ctxt, UUID) - - # Payment Gateway Configuration - def test_pg_config_add(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - self.assertData(fixture, data) - - def test_pg_config_get(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - - def test_pg_config_get_missing(self): - self.assertMissing(self.storage_conn.pg_config_get, self.admin_ctxt, UUID) - - def test_pg_config_update(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - - fixture['configuration'] = {"api": 1} - updated = self.storage_conn.pg_config_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_pg_config_update_missing(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - - self.assertMissing(self.storage_conn.pg_config_update, self.admin_ctxt, UUID, {}) - - def test_pg_config_delete(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - - self.storage_conn.pg_config_delete(self.admin_ctxt,data['id']) - self.assertMissing(self.storage_conn.pg_config_get, self.admin_ctxt, data['id']) - - def test_pg_config_delete_missing(self): - self.assertMissing(self.storage_conn.pg_config_delete, self.admin_ctxt, UUID) - - # PaymentMethod - def test_payment_method_add(self): - _, provider = self.pg_provider_register() - m_id = provider['methods'][0]['id'] - _, customer = self.customer_add(self.merchant['id']) - - fixture, data = self.payment_method_add(customer['id'], m_id) - self.assertData(fixture, data) - - def test_payment_method_get(self): - _, provider = self.pg_provider_register() - m_id = provider['methods'][0]['id'] - _, customer = self.customer_add(self.merchant['id']) - - _, expected = self.payment_method_add(customer['id'], m_id) - actual = self.storage_conn.payment_method_get(self.admin_ctxt, expected['id']) - self.assertData(expected, actual) - - # TODO(ekarlso): Make this test more extensive? - def test_payment_method_list(self): - # Setup a PGP with it's sample methods - _, provider = self.pg_provider_register() - m_id = provider['methods'][0]['id'] - - # Add two Customers with some methods - _, customer1 = self.customer_add(self.merchant['id']) - self.payment_method_add(customer1['id'], m_id) - rows = self.storage_conn.payment_method_list( - self.admin_ctxt, - criterion={'customer_id': customer1['id']}) - self.assertLen(1, rows) - - _, customer2 = self.customer_add(self.merchant['id']) - self.payment_method_add(customer2['id'], m_id) - self.payment_method_add(customer2['id'], m_id) - - rows = self.storage_conn.payment_method_list( - self.admin_ctxt, - criterion={'customer_id': customer2['id']}) - self.assertLen(2, rows) - - def test_payment_method_get_missing(self): - self.assertMissing(self.storage_conn.payment_method_get, self.admin_ctxt, UUID) - - def test_payment_method_update(self): - _, provider = self.pg_provider_register() - m_id = provider['methods'][0]['id'] - _, customer = self.customer_add(self.merchant['id']) - - fixture, data = self.payment_method_add(customer['id'], m_id) - - fixture['identifier'] = 1 - updated = self.storage_conn.payment_method_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_payment_method_update_missing(self): - self.assertMissing(self.storage_conn.payment_method_update, self.admin_ctxt, UUID, {}) - - def test_payment_method_delete(self): - _, provider = self.pg_provider_register() - fixture, data = self.pg_config_add(provider['id']) - - self.storage_conn.pg_config_delete(self.admin_ctxt, data['id']) - self.assertMissing(self.storage_conn.payment_method_delete, self.admin_ctxt, data['id']) - - def test_payment_method_delete_missing(self): - self.assertMissing(self.storage_conn.payment_method_delete, self.admin_ctxt, UUID) - - # Merchant - def test_merchant_add(self): - fixture, data = self.merchant_add() - self.assertData(fixture, data) - - def test_merchant_get(self): - _, expected = self.merchant_add() - actual = self.storage_conn.merchant_get(self.admin_ctxt, expected['id']) - self.assertData(expected, actual) - - def test_merchant_get_missing(self): - self.assertMissing(self.storage_conn.merchant_get, self.admin_ctxt, UUID) - - def test_merchant_update(self): - fixture, data = self.merchant_add() - - fixture['name'] = 'test' - updated = self.storage_conn.merchant_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_merchant_update_missing(self): - self.assertMissing(self.storage_conn.merchant_update, self.admin_ctxt, UUID, {}) - - def test_merchant_delete(self): - self.storage_conn.merchant_delete(self.admin_ctxt, self.merchant['id']) - self.assertMissing(self.storage_conn.merchant_get, self.admin_ctxt, self.merchant['id']) - - def test_merchant_delete_missing(self): - self.assertMissing(self.storage_conn.merchant_delete, self.admin_ctxt, UUID) - - # Customer - def test_customer_add(self): - fixture, data = self.customer_add(self.merchant['id']) - assert data['default_info'] == {} - assert data['contact_info'] == [] - self.assertData(fixture, data) - - def test_customer_add_with_contact_info(self): - contact_fixture = self.get_fixture('contact_info') - customer_fixture, data = self.customer_add( - self.merchant['id'], - values={'contact_info': contact_fixture}) - self.assertData(customer_fixture, data) - self.assertData(contact_fixture, data['default_info']) - self.assertData(contact_fixture, data['contact_info'][0]) - - def test_customer_get(self): - _, expected = self.customer_add(self.merchant['id']) - actual = self.storage_conn.customer_get(self.admin_ctxt, expected['id']) - self.assertData(expected, actual) - - def test_customer_get_missing(self): - self.assertMissing(self.storage_conn.customer_get, self.admin_ctxt, UUID) - - def test_customer_update(self): - fixture, data = self.customer_add(self.merchant['id']) - - fixture['name'] = 'test' - updated = self.storage_conn.customer_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_customer_update_missing(self): - self.assertMissing(self.storage_conn.customer_update, self.admin_ctxt, UUID, {}) - - def test_customer_delete(self): - _, data = self.customer_add(self.merchant['id']) - self.storage_conn.customer_delete(self.admin_ctxt, data['id']) - self.assertMissing(self.storage_conn.customer_get, self.admin_ctxt, data['id']) - - def test_customer_delete_missing(self): - self.assertMissing(self.storage_conn.customer_delete, self.admin_ctxt, UUID) - - # Products - def test_product_add(self): - f, data = self.product_add(self.merchant['id']) - self.assertData(f, data) - - def test_product_get(self): - f, expected = self.product_add(self.merchant['id']) - actual = self.storage_conn.product_get(self.admin_ctxt, expected['id']) - self.assertData(expected, actual) - - def test_product_get_missing(self): - self.assertMissing(self.storage_conn.product_get, self.admin_ctxt, UUID) - - def test_product_update(self): - fixture, data = self.product_add(self.merchant['id']) - - fixture['name'] = 'test' - updated = self.storage_conn.product_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_product_update_missing(self): - self.assertMissing(self.storage_conn.product_update, self.admin_ctxt, UUID, {}) - - def test_product_delete(self): - fixture, data = self.product_add(self.merchant['id']) - self.storage_conn.product_delete(self.admin_ctxt, data['id']) - self.assertMissing(self.storage_conn.product_get, self.admin_ctxt, data['id']) - - def test_product_delete_missing(self): - self.assertMissing(self.storage_conn.product_delete, self.admin_ctxt, UUID) - - # Plan - def test_plan_add_with_items(self): - _, p1 = self.product_add(self.merchant['id']) - _, p2 = self.product_add(self.merchant['id']) - - values = { - 'plan_items': [{'product_id': p1['id']}, {'product_id': p2['id']}] - } - - fixture, data = self.plan_add(self.merchant['id'], values=values) - self.assertData(fixture, data) - - def test_plan_add_without_items(self): - fixture, data = self.plan_add(self.merchant['id']) - self.assertData(fixture, data) - - def test_plan_get(self): - fixture, data = self.plan_add(self.merchant['id']) - actual = self.storage_conn.plan_get(self.admin_ctxt, data['id']) - - # FIXME(ekarlso): This should test the actual items also? But atm there's an - # error that if the value is int when getting added it's string when returned... - self.assertEqual(data['name'], actual['name']) - self.assertEqual(data['title'], actual['title']) - self.assertEqual(data['description'], actual['description']) - - def test_plan_get_missing(self): - self.assertMissing(self.storage_conn.plan_get, self.admin_ctxt, UUID) - - def test_plan_update(self): - fixture, data = self.plan_add(self.merchant['id']) - - fixture['name'] = 'test' - updated = self.storage_conn.plan_update(self.admin_ctxt, data['id'], fixture) - - self.assertData(fixture, updated) - - def test_plan_update_missing(self): - self.assertMissing(self.storage_conn.plan_update, self.admin_ctxt, UUID, {}) - - def test_plan_delete(self): - fixture, data = self.plan_add(self.merchant['id']) - self.storage_conn.plan_delete(self.admin_ctxt, data['id']) - self.assertMissing(self.storage_conn.plan_get, self.admin_ctxt, data['id']) - - def test_plan_delete_missing(self): - self.assertMissing(self.storage_conn.plan_delete, self.admin_ctxt, UUID) \ No newline at end of file diff --git a/billingstack/tests/storage/test_sqlalchemy.py b/billingstack/tests/storage/test_sqlalchemy.py deleted file mode 100644 index 20a0d7b..0000000 --- a/billingstack/tests/storage/test_sqlalchemy.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Copied: billingstack -from billingstack.openstack.common import log as logging -from billingstack.tests.storage import StorageDriverTestCase - -LOG = logging.getLogger(__name__) - - -class SqlalchemyStorageTest(StorageDriverTestCase): - __test__ = True - - def setUp(self): - self.config(database_connection='sqlite://', - group='storage:sqlalchemy') - super(SqlalchemyStorageTest, self).setUp() \ No newline at end of file diff --git a/billingstack/tests/test_utils.py b/billingstack/tests/test_utils.py deleted file mode 100644 index 308fe95..0000000 --- a/billingstack/tests/test_utils.py +++ /dev/null @@ -1,22 +0,0 @@ -import unittest2 - - -from billingstack import exceptions -from billingstack import utils - - -class UtilsTests(unittest2.TestCase): - def test_get_currency(self): - currency = utils.get_currency('nok') - expected = {'name': u'nok', 'title': u'Norwegian Krone'} - self.assertEqual(expected, currency) - - def test_get_language(self): - lang = utils.get_language('nor') - expected = {'title': u'Norwegian', 'name': u'nor'} - self.assertEqual(expected, lang) - - def test_invalid_raises(self): - with self.assertRaises(exceptions.InvalidObject) as cm: - utils.get_language('random') - self.assertEqual(cm.exception.errors, {'terminology': 'random'}) diff --git a/billingstack/utils.py b/billingstack/utils.py deleted file mode 100644 index c11b80b..0000000 --- a/billingstack/utils.py +++ /dev/null @@ -1,123 +0,0 @@ -import os -import pycountry -import re - -from billingstack import exceptions -from oslo.config import cfg -from billingstack.openstack.common import log - - -LOG = log.getLogger(__name__) - - -def find_config(config_path): - """ - Find a configuration file using the given hint. - - Code nabbed from cinder. - - :param config_path: Full or relative path to the config. - :returns: List of config paths - """ - possible_locations = [ - config_path, - os.path.join(cfg.CONF.state_path, "etc", "billingstack", config_path), - os.path.join(cfg.CONF.state_path, "etc", config_path), - os.path.join(cfg.CONF.state_path, config_path), - "/etc/billingstack/%s" % config_path, - ] - - found_locations = [] - - for path in possible_locations: - LOG.debug('Searching for configuration at path: %s' % path) - if os.path.exists(path): - LOG.debug('Found configuration at path: %s' % path) - found_locations.append(os.path.abspath(path)) - - return found_locations - - -def read_config(prog, argv): - config_files = find_config('%s.conf' % prog) - - cfg.CONF(argv[1:], project='billingstack', prog=prog, - default_config_files=config_files) - - -def capital_to_underscore(string): - return "_".join(l.lower() for l in re.findall('[A-Z][^A-Z]*', - string)) - - -def underscore_to_capital(string): - return ''.join(x.capitalize() or '_' for x in string.split('_')) - - -def get_country(country_obj, **kw): - try: - obj = country_obj.get(**kw) - except KeyError: - raise exceptions.InvalidObject(errors=kw) - return dict([(k, v) for k, v in obj.__dict__.items() \ - if not k.startswith('_')]) - - -def get_currency(name): - obj = get_country(pycountry.currencies, letter=name.upper()) - return { - 'name': obj['letter'].lower(), - 'title': obj['name']} - - -def get_language(name): - obj = get_country(pycountry.languages, terminology=name) - data = {'name': obj['terminology'].lower(), 'title': obj['name']} - return data - - -def get_item_properties(item, fields, mixed_case_fields=[], formatters={}): - """Return a tuple containing the item properties. - - :param item: a single item resource (e.g. Server, Tenant, etc) - :param fields: tuple of strings with the desired field names - :param mixed_case_fields: tuple of field names to preserve case - :param formatters: dictionary mapping field names to callables - to format the values - """ - row = [] - - for field in fields: - if field in formatters: - row.append(formatters[field](item)) - else: - if field in mixed_case_fields: - field_name = field.replace(' ', '_') - else: - field_name = field.lower().replace(' ', '_') - if not hasattr(item, field_name) and \ - (isinstance(item, dict) and field_name in item): - data = item[field_name] - else: - data = getattr(item, field_name, '') - if data is None: - data = '' - row.append(data) - return tuple(row) - - -def get_columns(data): - """ - Some row's might have variable count of columns, ensure that we have the - same. - - :param data: Results in [{}, {]}] - """ - columns = set() - - def _seen(col): - columns.add(str(col)) - - map(lambda item: map(_seen, item.keys()), data) - return list(columns) - diff --git a/billingstack/version.py b/billingstack/version.py deleted file mode 100644 index e7924d7..0000000 --- a/billingstack/version.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Copied: Moniker -from billingstack.openstack.common import version as common_version - -version_info = common_version.VersionInfo('billingstack') diff --git a/bin/billingstack-api b/bin/billingstack-api deleted file mode 100644 index 23fe8aa..0000000 --- a/bin/billingstack-api +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 New Dream Network, LLC (DreamHost) -# -# Author: Doug Hellmann -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -"""Set up the development API server. -""" -import os -import sys -from wsgiref import simple_server - -from oslo.config import cfg - -from billingstack.api import app -from billingstack import service -from billingstack.openstack.common import log as logging - - -if __name__ == '__main__': - # Parse OpenStack config file and command line options, then - # configure logging. - service.prepare_service(sys.argv) - - # Build the WSGI app - root = app.setup_app() - - # Create the WSGI server and start it - host, port = cfg.CONF['service:api'].api_listen, int(cfg.CONF['service:api'].api_port) - srv = simple_server.make_server(host, port, root) - - print 'Starting server in PID %s' % os.getpid() - - print "serving on http://%s:%s" % (host, port) - - try: - srv.serve_forever() - except KeyboardInterrupt: - # allow CTRL+C to shutdown without an error - pass diff --git a/bin/billingstack-central b/bin/billingstack-central deleted file mode 100644 index 2f4eed1..0000000 --- a/bin/billingstack-central +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -import sys -import eventlet -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import service -from billingstack import utils -from billingstack.central import service as central_service - -eventlet.monkey_patch() - -utils.read_config('billingstack', sys.argv) - -logging.setup('billingstack') - -launcher = service.launch(central_service.Service(), - cfg.CONF['service:central'].workers) -launcher.wait() diff --git a/bin/billingstack-db-manage b/bin/billingstack-db-manage deleted file mode 100644 index c80febf..0000000 --- a/bin/billingstack-db-manage +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 New Dream Network, LLC (DreamHost) -# All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# Copied: Quantum -import os -import sys -sys.path.insert(0, os.getcwd()) - -from oslo.config import cfg - -from billingstack.storage.impl_sqlalchemy.migration.cli import main - - -main() diff --git a/bin/billingstack-identity-api b/bin/billingstack-identity-api deleted file mode 100644 index e2c3bb7..0000000 --- a/bin/billingstack-identity-api +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- -# -# Copyright © 2012 New Dream Network, LLC (DreamHost) -# -# Author: Doug Hellmann -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -"""Set up the development API server. -""" -import os -import sys -from wsgiref import simple_server - -from oslo.config import cfg - -from billingstack.identity.api import app -from billingstack import service -from billingstack.openstack.common import log as logging - - -if __name__ == '__main__': - # Parse OpenStack config file and command line options, then - # configure logging. - service.prepare_service(sys.argv) - - # Build the WSGI app - root = app.setup_app() - - # Create the WSGI server and start it - host, port = cfg.CONF['service:identity_api'].api_listen, int(cfg.CONF['service:identity_api'].api_port) - srv = simple_server.make_server(host, port, root) - - print 'Starting server in PID %s' % os.getpid() - - print "serving on http://%s:%s" % (host, port) - - try: - srv.serve_forever() - except KeyboardInterrupt: - # allow CTRL+C to shutdown without an error - pass diff --git a/bin/billingstack-manage b/bin/billingstack-manage deleted file mode 100644 index 484e6c5..0000000 --- a/bin/billingstack-manage +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -# Copied: billingstack -import sys - -from oslo.config import cfg - -from billingstack import utils -from billingstack.manage import Shell - -# TODO: Sypport passing --config-file and --config-dir to read_config -utils.read_config('billingstack', []) - -shell = Shell() -sys.exit(shell.run(sys.argv[1:])) - diff --git a/bin/billingstack-pg-gateway b/bin/billingstack-pg-gateway deleted file mode 100644 index 6ccac43..0000000 --- a/bin/billingstack-pg-gateway +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python -# Copyright 2012 Managed I.T. -# -# Author: Kiall Mac Innes -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -import sys -import eventlet -from oslo.config import cfg -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import service -from billingstack import utils -from billingstack.central import service as central_service - -eventlet.monkey_patch() - -utils.read_config('billingstack', sys.argv) - -logging.setup('billingstack') - -launcher = service.launch(central_service.Service(), - cfg.CONF['service:payment_gateway'].workers) -launcher.wait() diff --git a/bin/billingstack-rpc-zmq-receiver b/bin/billingstack-rpc-zmq-receiver deleted file mode 100755 index 543af5e..0000000 --- a/bin/billingstack-rpc-zmq-receiver +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 OpenStack LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import eventlet -eventlet.monkey_patch() - -import contextlib -import os -import sys - -# If ../billingstack/__init__.py exists, add ../ to Python search path, so that -# it will override what happens to be installed in /usr/(local/)lib/python... -POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), - os.pardir, - os.pardir)) -if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'billingstack', '__init__.py')): - sys.path.insert(0, POSSIBLE_TOPDIR) - -from oslo.config import cfg - -from billingstack.openstack.common import log as logging -from billingstack.openstack.common import rpc -from billingstack.openstack.common.rpc import impl_zmq - -CONF = cfg.CONF -CONF.register_opts(rpc.rpc_opts) -CONF.register_opts(impl_zmq.zmq_opts) - - -def main(): - CONF(sys.argv[1:], project='billingstack') - logging.setup("billingstack") - - with contextlib.closing(impl_zmq.ZmqProxy(CONF)) as reactor: - reactor.consume_in_thread() - reactor.wait() - -if __name__ == '__main__': - main() diff --git a/doc/requirements.txt b/doc/requirements.txt deleted file mode 100644 index 2c32ab1..0000000 --- a/doc/requirements.txt +++ /dev/null @@ -1,75 +0,0 @@ - -alembic -anyjson>=0.2.4 -argparse -Babel>=0.9.6 -cfg.CONF.import_opt('database_connection', 'billingstack.storage.impl_sqlalchemy', -cfg.CONF.import_opt('storage_driver', 'billingstack.api', - conn = get_connection() - conn.setup_schema() - conn.teardown_schema() - contact_info=contact_info, - contact_info = get_fixture('contact_info') - country_data = { -coverage - currencies = {} - currencies[c['letter']] = conn.currency_add(c) - "currency_id": currencies['nok']['id'], - customer = conn.customer_add( - customer_id=customer['id']) - customer_user, - customer_user = conn.user_add( - customer_user = get_fixture('user') - customer_user['username'] = 'demo_customer' -def get_fixture(name, fixture=0, values={}): -docutils==0.9.1 # for bug 1091333, remove after sphinx >1.1.3 is released. --e hg+https://bitbucket.org/cdevienne/wsme/#egg=wsme -eventlet - for c in samples['currency']: - for l in samples['language']: -from billingstack import service -from billingstack.openstack.common import cfg -from billingstack.openstack.common import log as logging -from billingstack.samples import get_samples -from billingstack.storage.impl_sqlalchemy import models -from billingstack.storage import get_connection - f = SAMPLES[name][fixture].copy() - f.update(values) - get_fixture('merchant', values=country_data)) - group='service:api') - group='storage:sqlalchemy') -if __name__ == '__main__': -import sys -iso8601 - "language_id": languages['nor']['id']} - languages = {} - languages[l['letter']] = conn.language_add(l) - LOG.info("Re-Syncing database") -LOG = logging.getLogger(__name__) - merchant = conn.merchant_add( - merchant['id'], - merchant['id'], get_fixture('customer', values=country_data)) - merchant['id'], merchant_user, contact_info=contact_info) - merchant_user = conn.user_add( - merchant_user = get_fixture('user') - merchant_user['username'] = 'demo_merchant' -mock -mox -nose -nosehtmloutput -openstack.nose_plugin -# Optional Stuff that is used by default -pecan - print "ADDING", c -pycountry - return f - samples = get_samples() -SAMPLES = get_samples() - service.prepare_service(sys.argv) -sphinx -sphinxcontrib-httpdomain -SQLAlchemy>=0.7.8,<=0.7.9 -stevedore -unittest2 -#!/usr/bin/env python -WebOb>=1.2 diff --git a/doc/source/api.rst b/doc/source/api.rst deleted file mode 100644 index b4aaa35..0000000 --- a/doc/source/api.rst +++ /dev/null @@ -1,11 +0,0 @@ -API Documenation -================ - -Contents: - -.. toctree:: - :maxdepth: 2 - :glob: - - api/* - diff --git a/doc/source/architecture.rst b/doc/source/architecture.rst deleted file mode 100644 index 503f8ce..0000000 --- a/doc/source/architecture.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. - Copyright 2012 Endre Karlson for Bouvet ASA - - Licensed under the Apache License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may obtain - a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - License for the specific language governing permissions and limitations - under the License. - -.. _architecture: - - -============ -Architecture -============ - -.. index:: - double: architecture; brief - -Brief overview -++++++++++++++ - :term:`pgp` PaymentGatewayProvider - Typically a provider like Braintree. - :term:`pgm` PaymentGatewayMethod - A provider method typically like Visa or - similar. - :term:`api` standard OpenStack alike REST api services diff --git a/doc/source/conf.py b/doc/source/conf.py deleted file mode 100644 index 479cc25..0000000 --- a/doc/source/conf.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# -# billingstackclient documentation build configuration file, created by -# sphinx-quickstart on Wed Oct 31 18:58:17 2012. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'billingstack' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -from billingstack.version import version_info -version = version_info.canonical_version_string() -# The full version, including alpha/beta/rc tags. -release = version_info.version_string_with_vcs() - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'billingstack-doc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'billingstack.tex', u'BillingStack Documentation', - u'Bouvet ASA', 'manual') -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'billingstack', u'BillingStack Documentation', - [u'Bouvet ASA'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'billingstack', u'BillingStack Documentation', - u'Bouvet ASA', 'billingstack', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' diff --git a/doc/source/database.yuml b/doc/source/database.yuml deleted file mode 100644 index bc4a78b..0000000 --- a/doc/source/database.yuml +++ /dev/null @@ -1,37 +0,0 @@ -[PGMethod{bg:green}]1owner-1>[PGProvider] -[PGProvider{bg:green}]1-*>[PGMethod{bg:green}] -[ContactInfo]^-[CustomerInfo] -[Customer]1-*>[CustomerInfo] -[PGConfig]*-1>[PGProvider] -[Merchant]1-*>[User] -[Merchant]1-*>[PGConfig] -[Merchant]1-*>[Customer] -[Merchant]1-*>[Plan] -[Merchant]1-*>[Product] -[Merchant]*-1>[Currency{bg:green}] -[Merchant]*->[Language{bg:green}] -[Customer]1-*>[User] -[Customer]1-*>[Invoice] -[Customer]*-1>[Currency{bg:green}] -[Customer]*-1>[Language{bg:green}] -[Customer]1-*>[PaymentMethod] -[PaymentMethod]1-1>[PGMethod] -[User]1-*>[MerchantRole] -[User]1-*>[CustomerRole] -[User]1-1[ContactInfo] -[MerchantRole]1-1>[Merchant] -[CustomerRole]1-1>[Customer] -[Invoice]1-*>[InvoiceItems] -[Invoice]*-1>[InvoiceState] -[Invoice]*-1>[Currency] -[Invoice]*-1>[Merchant] -[Plan]1-*>[PlanItem] -[PlanItem]*-1>[Merchant] -[PlanItem]1-1>[Product] -[PlanItem]1-*>[Pricing] -[Product]1-*>[Pricing] -[Subscription]1-1>[Plan] -[Subscription]1-1>[Customer] -[Subscription]1-1>[PaymentMethod] -[Usage]*-1>[Subscription] -[Usage]1-1>[Product] diff --git a/doc/source/glossary.rst b/doc/source/glossary.rst deleted file mode 100644 index d736fe8..0000000 --- a/doc/source/glossary.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. - Copyright 2012 Endre Karlson for Bouvet ASA - - Licensed under the Apache License, Version 2.0 (the "License"); you may - not use this file except in compliance with the License. You may obtain - a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - License for the specific language governing permissions and limitations - under the License. - -.. _architecture: - - -============ -Glossary -============ - -.. glossary:: - pgp - PaymentGatewayProvider - pgm - PaymentGatewayMethod - api - Web API diff --git a/doc/source/index.rst b/doc/source/index.rst deleted file mode 100644 index 6657a2f..0000000 --- a/doc/source/index.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. billingstack documentation master file, created by - sphinx-quickstart on Wed Oct 31 18:58:17 2012. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to BillingStack's documentation! -========================================== - -Contents: - -.. toctree:: - :maxdepth: 2 - - architecture - api - glossary - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/doc/source/payment.yuml b/doc/source/payment.yuml deleted file mode 100644 index 187ed04..0000000 --- a/doc/source/payment.yuml +++ /dev/null @@ -1,8 +0,0 @@ -[plugin.Provider]1-1>[models.PGProvider] -[models.PGProvider]*-*>[models.PGMethod] -[models.PGMethod]*-1>[models.PGProvider] -[models.PGConfig]*-1>[models.PGProvider] -[models.Merchant]1-*>[models.PGConfig] -[models.Subscription]1-1>[models.PaymentMethod] -[models.Customer]1-*>[models.PaymentMethod] -[models.PaymentMethod]1-1>[models.PGMethod] diff --git a/etc/billingstack/billingstack.conf.sample b/etc/billingstack/billingstack.conf.sample deleted file mode 100644 index 49e7736..0000000 --- a/etc/billingstack/billingstack.conf.sample +++ /dev/null @@ -1,59 +0,0 @@ -[DEFAULT] -######################## -## General Configuration -######################## -# Show more verbose log output (sets INFO log level output) -verbose = True - -# Show debugging output in logs (sets DEBUG log level output) -debug = True - -# Top-level directory for maintaining billingstack's state -#state_path = /var/lib/billingstack - -# Log directory -#logdir = /var/log/billingstack - -identity_driver = internal - -[service:api] -# Address to bind the API server -# api_host = 0.0.0.0 - -# Port the bind the API server to -#api_port = 9001 - -####################### -## Storage Configuration -######################## -#----------------------- -# SQLAlchemy Storage -#----------------------- -[storage:sqlalchemy] -# Database connection string - to configure options for a given implementation -# like sqlalchemy or other see below -#database_connection = mysql://billingstack:billingstack@localhost:3306/billingstack -#connection_debug = 100 -#connection_trace = False -#sqlite_synchronous = True -#idle_timeout = 3600 -#max_retries = 10 -#retry_interval = 10 - - -################################# -## Identity Storage Configuration -################################# -#----------------------- -# Identity SQLAlchemy Storage -#----------------------- -[identity:sqlalchemy] -# Database connection string - to configure options for a given implementation -# like sqlalchemy or other see below -#database_connection = mysql://billingstack:billingstack@localhost:3306/billingstack -#connection_debug = 100 -#connection_trace = False -#sqlite_synchronous = True -#idle_timeout = 3600 -#max_retries = 10 -#retry_interval = 10 diff --git a/openstack.conf b/openstack.conf deleted file mode 100644 index da110a8..0000000 --- a/openstack.conf +++ /dev/null @@ -1,3 +0,0 @@ -[DEFAULT] -modules=iniparser,importutils,excutils,local,jsonutils,timeutils,service,eventlet_backdoor,loopingcall,utils,exception,setup,version,uuidutils,processutils,db,log,gettextutils,iso8601,notifier,rpc,context,threadgroup,network_utils -base=billingstack diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index a3bac0c..0000000 --- a/setup.cfg +++ /dev/null @@ -1,17 +0,0 @@ -[nosetests] -cover-package=billingstack -cover-html=true -cover-html-dir=../../cover -cover-erase=true -cover-inclusive=true -verbosity=2 -detailed-errors=1 -where=billingstack/tests - -[build_sphinx] -source-dir = doc/source -build-dir = doc/build -all_files = 1 - -[upload_docs] -upload-dir = doc/build/html diff --git a/setup.py b/setup.py deleted file mode 100644 index 9b6eaed..0000000 --- a/setup.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Author: Endre Karlson -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from setuptools import setup, find_packages -import textwrap -from billingstack.openstack.common import setup as common_setup - -install_requires = common_setup.parse_requirements(['tools/pip-requires']) -install_options = common_setup.parse_requirements(['tools/pip-options']) -tests_require = common_setup.parse_requirements(['tools/test-requires']) -setup_require = common_setup.parse_requirements(['tools/setup-requires']) -dependency_links = common_setup.parse_dependency_links([ - 'tools/pip-requires', - 'tools/pip-options', - 'tools/test-requires', - 'tools/setup-requires' -]) - -setup( - name='billingstack', - version=common_setup.get_version('billingstack'), - description='Subscription based Billing in Python', - author='Endre Karlson', - author_email='endre.karlson@gmail.com', - url='https://github/billingstack/billingstack', - packages=find_packages(exclude=['bin']), - include_package_data=True, - test_suite='nose.collector', - setup_requires=setup_require, - install_requires=install_requires, - tests_require=tests_require, - extras_require={ - 'test': tests_require, - 'optional': install_options, - }, - dependency_links=dependency_links, - scripts=[ - 'bin/billingstack-api', - 'bin/billingstack-identity-api', - 'bin/billingstack-db-manage', - 'bin/billingstack-manage', - 'bin/billingstack-central' - ], - cmdclass=common_setup.get_cmdclass(), - entry_points=textwrap.dedent(""" - [billingstack.storage] - sqlalchemy = billingstack.storage.impl_sqlalchemy:SQLAlchemyStorage - - [billingstack.payment_gateway] - dummy = billingstack.payment_gateway.dummy:DummyProvider - - [billingstack.manage] - pg-register = billingstack.manage.provider:ProvidersRegister - pg-list = billingstack.manage.provider:ProvidersList - - [billingstack.identity_plugin] - sqlalchemy = billingstack.identity.impl_sqlalchemy:SQLAlchemyPlugin - """), - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Topic :: Finance :: Subscription Billing', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Environment :: OpenStack', - ], -) diff --git a/tools/dev_samples.py b/tools/dev_samples.py deleted file mode 100644 index 70d14ed..0000000 --- a/tools/dev_samples.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python - -import sys - -from oslo.config import cfg - -from billingstack.openstack.common import log as logging - -from billingstack import service -from billingstack.samples import get_samples -from billingstack.storage import get_connection -from billingstack.openstack.common.context import get_admin_context -from billingstack.storage.impl_sqlalchemy import models - - -cfg.CONF.import_opt('storage_driver', 'billingstack.central', - group='service:central') - -cfg.CONF.import_opt('database_connection', 'billingstack.storage.impl_sqlalchemy', - group='storage:sqlalchemy') - - -SAMPLES = get_samples() - - -def get_fixture(name, fixture=0, values={}): - f = SAMPLES[name][fixture].copy() - f.update(values) - return f - - -if __name__ == '__main__': - service.prepare_service(sys.argv) - conn = get_connection() - - samples = get_samples() - - ctxt = get_admin_context() - - currencies = {} - for c in samples['currency']: - currencies[c['name']] = conn.currency_add(ctxt, c) - - languages = {} - for l in samples['language']: - languages[l['name']] = conn.language_add(ctxt, l) - - for method in samples['pg_method']: - conn.pg_method_add(ctxt, method) - - country_data = { - "currency_name": currencies['nok']['name'], - "language_name": languages['nor']['name']} - - merchant = conn.merchant_add( - ctxt, get_fixture('merchant', values=country_data)) - - customer = conn.customer_add( - ctxt, merchant['id'], get_fixture('customer', values=country_data)) - - contact_info = get_fixture('contact_info') - - merchant_user = get_fixture('user') - merchant_user['username'] = 'demo_merchant' - merchant_user['contact_info'] = contact_info - - merchant_user = conn.user_add( - ctxt, merchant['id'], merchant_user) - - customer_user = get_fixture('user') - customer_user['username'] = 'demo_customer' - customer_user['contact_info'] = contact_info - customer_user['customer_id'] = customer['id'] - - customer_user = conn.user_add( - ctxt, - merchant['id'], - customer_user) - - products = {} - for p in samples['product']: - products[p['name']] = conn.product_add(ctxt, merchant['id'], p) - - values = { - 'plan_items': [ - {'product_id': products['memory']}, - {'product_id': products['vcpus']}, - {'product_id': products['root_disk_size']}, - {'product_id': products['network.incoming.bytes']}, - {'product_id': products['network.outgoing.bytes']} - ]} - - plan = get_fixture('plan', values=values) - - conn.plan_add(ctxt, merchant['id'], get_fixture('plan')) diff --git a/tools/pip-options b/tools/pip-options deleted file mode 100644 index b2089f9..0000000 --- a/tools/pip-options +++ /dev/null @@ -1,4 +0,0 @@ -# Optional Stuff that is used by default -alembic -SQLAlchemy>=0.7.8,<=0.7.9 -kombu diff --git a/tools/pip-requires b/tools/pip-requires deleted file mode 100644 index 02a8827..0000000 --- a/tools/pip-requires +++ /dev/null @@ -1,12 +0,0 @@ -WebOb>=1.2 -eventlet -#pecan --e git://github.com/ryanpetrello/pecan.git@next#egg=pecan -stevedore -argparse --e hg+https://bitbucket.org/cdevienne/wsme/#egg=wsme -anyjson>=0.2.4 -pycountry -iso8601 -cliff -http://tarballs.openstack.org/oslo-config/oslo-config-2013.1b4.tar.gz#egg=oslo-config diff --git a/tools/resync_billingstack.py b/tools/resync_billingstack.py deleted file mode 100644 index a545af9..0000000 --- a/tools/resync_billingstack.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -import sys - -from oslo.config import cfg - -from billingstack.openstack.common import log as logging - -from billingstack import service -from billingstack.storage import get_connection - - -LOG = logging.getLogger(__name__) - - -cfg.CONF.import_opt('storage_driver', 'billingstack.central', - group='service:central') - -cfg.CONF.import_opt('database_connection', 'billingstack.storage.impl_sqlalchemy', - group='storage:sqlalchemy') - - -if __name__ == '__main__': - service.prepare_service(sys.argv) - conn = get_connection() - - LOG.info("Re-Syncing database") - conn.teardown_schema() - conn.setup_schema() diff --git a/tools/resync_identity.py b/tools/resync_identity.py deleted file mode 100644 index a7a304a..0000000 --- a/tools/resync_identity.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -import sys - -from oslo.config import cfg - -from billingstack.openstack.common import log as logging - -from billingstack import service -from billingstack.identity.base import IdentityPlugin - - -LOG = logging.getLogger(__name__) - - -cfg.CONF.import_opt('storage_driver', 'billingstack.identity.api', - group='service:identity_api') - -cfg.CONF.import_opt('database_connection', 'billingstack.identity.impl_sqlalchemy', - group='identity:sqlalchemy') - - -if __name__ == '__main__': - service.prepare_service(sys.argv) - plugin = IdentityPlugin.get_plugin()() - - LOG.info("Re-Syncing database") - plugin.teardown_schema() - plugin.setup_schema() diff --git a/tools/setup-requires b/tools/setup-requires deleted file mode 100644 index e69de29..0000000 diff --git a/tools/test-requires b/tools/test-requires deleted file mode 100644 index 4736efb..0000000 --- a/tools/test-requires +++ /dev/null @@ -1,11 +0,0 @@ -unittest2 -nose -openstack.nose_plugin -nosehtmloutput -coverage -mock -mox -Babel>=0.9.6 -sphinx -sphinxcontrib-httpdomain -docutils==0.9.1 # for bug 1091333, remove after sphinx >1.1.3 is released. diff --git a/tox.ini b/tox.ini deleted file mode 100644 index a56239f..0000000 --- a/tox.ini +++ /dev/null @@ -1,40 +0,0 @@ -[tox] -envlist = py26,py27,pep8,pyflakes -minversion = 1.4.0 - -[tox:jenkins] -downloadcache = ~/cache/pip - -[testenv] -deps = -r{toxinidir}/tools/setup-requires - -r{toxinidir}/tools/pip-requires - -r{toxinidir}/tools/pip-options - -r{toxinidir}/tools/test-requires -setenv = VIRTUAL_ENV={envdir} - NOSE_WITH_OPENSTACK=1 - NOSE_OPENSTACK_COLOR=1 - NOSE_OPENSTACK_RED=0.05 - NOSE_OPENSTACK_YELLOW=0.025 - NOSE_OPENSTACK_SHOW_ELAPSED=1 -commands = nosetests {posargs} -sitepackages = False - -[testenv:cover] -deps = {[testenv]deps} - coverage - nosexcover -setenv = {[testenv]setenv} - NOSE_WITH_COVERAGE=1 - -[testenv:pep8] -deps = {[testenv]deps} - pep8==1.3.3 -commands = pep8 --repeat --show-source --exclude=.venv,.tox,dist,doc,openstack billingstack setup.py bin/billingstack-api bin/billingstack-db-manage - -[testenv:pyflakes] -deps = {[testenv]deps} - pyflakes==0.6.1 -commands = pyflakes billingstack bin setup.py - -[testenv:venv] -commands = {posargs}