diff --git a/orm/common/client/keystone/mock_keystone/keystoneclient/exceptions.py b/orm/common/client/keystone/mock_keystone/keystoneclient/exceptions.py deleted file mode 100644 index f88096f8..00000000 --- a/orm/common/client/keystone/mock_keystone/keystoneclient/exceptions.py +++ /dev/null @@ -1,2 +0,0 @@ -class NotFound(Exception): - pass diff --git a/orm/common/orm_common/injector/injector.py b/orm/common/orm_common/injector/injector.py index 4ba90e2e..05f225ee 100755 --- a/orm/common/orm_common/injector/injector.py +++ b/orm/common/orm_common/injector/injector.py @@ -16,7 +16,7 @@ def register_providers(env_variable, providers_dir_path, _logger): env = None if not (env_variable in os.environ): - LOG.warning('No {0} variable found using prod injector'.format(env_variable)) + LOG.info('No {0} variable found using prod injector'.format(env_variable)) env = 'prod' elif os.environ[env_variable] == '__TEST__': LOG.info('__TEST__ variable found, explicitly skipping provider registration!') diff --git a/orm/common/orm_common/utils/api_error_utils.py b/orm/common/orm_common/utils/api_error_utils.py index 9f3e9c83..f9727648 100755 --- a/orm/common/orm_common/utils/api_error_utils.py +++ b/orm/common/orm_common/utils/api_error_utils.py @@ -1,6 +1,5 @@ -import json +from orm.common.orm_common.utils.error_base import ClientSideError from orm.common.orm_common.utils import utils -from wsme.exc import ClientSideError # This method creates a ClientSideError with given parameters @@ -11,7 +10,7 @@ def get_error(transaction_id, status_code=400): err = get_error_dict(status_code, transaction_id, message, error_details) - return ClientSideError(json.dumps(err), status_code) + return ClientSideError(message=err['message'], status_code=status_code) def get_error_dict(status_code, transaction_id, message, error_details=""): diff --git a/orm/common/orm_common/utils/error_base.py b/orm/common/orm_common/utils/error_base.py index 0f2413f9..c28106b4 100755 --- a/orm/common/orm_common/utils/error_base.py +++ b/orm/common/orm_common/utils/error_base.py @@ -1,14 +1,79 @@ -class Error(Exception): - pass +"""Exceptions.""" +import wsme -class ErrorStatus(Error): - def __init__(self, status_code, message=""): +class ClientSideError(wsme.exc.ClientSideError): + def __init__(self, message=None, status_code=400): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class InputValueError(wsme.exc.ClientSideError): + def __init__(self, message="Bad input value", status_code=400): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class NotFoundError(wsme.exc.ClientSideError): + def __init__(self, message="Query not found", status_code=404): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class LockedEntity(wsme.exc.ClientSideError): + def __init__(self, message="Entity locked", status_code=409): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class NotAllowedError(wsme.exc.ClientSideError): + def __init__(self, message="Method not allowed", status_code=405): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class NoContentError(wsme.exc.ClientSideError): + def __init__(self, message="Main json body empty", status_code=204): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class UnauthorizedError(wsme.exc.ClientSideError): + def __init__(self, message="Not allowed to perform this operation", status_code=401): + self.message = message + self.status_code = status_code + super().__init__(msg=message, status_code=status_code) + + +class ErrorStatus(Exception): + def __init__(self, message=None, status_code=400): self.status_code = status_code self.message = message + super().__init__(message) -class NotFound(Error): - def __init__(self, status_code=404, message=None): +class ConflictError(Exception): + def __init__(self, message="Item already exists", status_code=409): self.status_code = status_code self.message = message + super().__init__(message) + + +class SQLDBError(Exception): + def __init__(self, message="DB Error", status_code=409): + self.status_code = status_code + self.message = message + super().__init__(message) + + +class EntityNotFound(Exception): + def __init__(self, message="Entity not found in DB", status_code=404): + self.status_code = status_code + self.message = message + super().__init__(message) diff --git a/orm/services/audit_trail_manager/audit_server/controllers/v1/base.py b/orm/services/audit_trail_manager/audit_server/controllers/v1/base.py deleted file mode 100644 index 61218964..00000000 --- a/orm/services/audit_trail_manager/audit_server/controllers/v1/base.py +++ /dev/null @@ -1,49 +0,0 @@ -"""base module for base wsme types and client side errors.""" - - -import wsme -from wsme import types as wtypes - - -class ClientSideError(wsme.exc.ClientSideError): - """base client side error.""" - - def __init__(self, error, status_code=400): - """init method.. - - :param error: error message to show to the client. - :param status_code: status code to show to the client. - """ - super(ClientSideError, self).__init__(error, status_code) - - -class InputValueError(ClientSideError): - """input value error.""" - - def __init__(self, name, value, status_code=400): - """init method.. - - :param name: the input name for which an error was raised. - :param value: the input value for which an error was raised. - :param status_code: status code to show to the client. - """ - super(InputValueError, self).__init__( - "Invalid value for input {} : {}".format(name, value), status_code) - - -class EntityNotFoundError(ClientSideError): - """entity not found error.""" - - def __init__(self, entity_id): - """init method.. - - :param entity_id: the id for which an entity was not found. - """ - super(EntityNotFoundError, self).__init__( - "Entity not found for {}".format(entity_id), status_code=404) - - -class Base(wtypes.DynamicBase): - """base class for wsme types.""" - - pass diff --git a/orm/services/audit_trail_manager/audit_server/controllers/v1/transaction.py b/orm/services/audit_trail_manager/audit_server/controllers/v1/transaction.py index bc4007d3..882daf62 100755 --- a/orm/services/audit_trail_manager/audit_server/controllers/v1/transaction.py +++ b/orm/services/audit_trail_manager/audit_server/controllers/v1/transaction.py @@ -1,6 +1,5 @@ """transaction controller module.""" -from . import base import logging import wsme @@ -14,7 +13,7 @@ from wsmeext.pecan import wsexpose logger = logging.getLogger(__name__) -class Transaction(base.Base): +class Transaction(wtypes.DynamicBase): """transaction type.""" timestamp = wsme.wsattr(int, mandatory=True) @@ -69,7 +68,7 @@ class Transaction(base.Base): self.service_name) -class Query(base.Base): +class Query(wtypes.DynamicBase): """query type.""" timestamp_from = wsme.wsattr(int, mandatory=False, default=None) @@ -128,7 +127,7 @@ class Query(base.Base): self.service_name) -class QueryResult(base.Base): +class QueryResult(wtypes.DynamicBase): """query result type.""" transactions = wsme.wsattr([Transaction], mandatory=False, default=None) diff --git a/orm/services/audit_trail_manager/audit_server/services/base.py b/orm/services/audit_trail_manager/audit_server/services/base.py deleted file mode 100644 index ab9e5311..00000000 --- a/orm/services/audit_trail_manager/audit_server/services/base.py +++ /dev/null @@ -1,7 +0,0 @@ -"""base module for all services, holds errors.""" - - -class Error(Exception): - """base error class.""" - - pass diff --git a/orm/services/audit_trail_manager/audit_server/storage/mysql/transaction.py b/orm/services/audit_trail_manager/audit_server/storage/mysql/transaction.py index a9c8c84c..40f3904e 100755 --- a/orm/services/audit_trail_manager/audit_server/storage/mysql/transaction.py +++ b/orm/services/audit_trail_manager/audit_server/storage/mysql/transaction.py @@ -3,10 +3,10 @@ import logging from orm.services.audit_trail_manager.audit_server.model.transaction import Model -from orm.services.audit_trail_manager.audit_server.storage import transaction from sqlalchemy import BigInteger, Column, Integer, Text, asc, create_engine from sqlalchemy.ext.declarative.api import declarative_base from sqlalchemy.orm import sessionmaker +from wsme import types as wtypes Base = declarative_base() logger = logging.getLogger(__name__) @@ -30,7 +30,7 @@ class Record(Base): service_name = Column(Text) -class Connection(transaction.Base): +class Connection(wtypes.DynamicBase): """Implements mysql DB.""" def __init__(self, url, echo_statements): diff --git a/orm/services/audit_trail_manager/audit_server/storage/transaction.py b/orm/services/audit_trail_manager/audit_server/storage/transaction.py deleted file mode 100644 index 9b007c6c..00000000 --- a/orm/services/audit_trail_manager/audit_server/storage/transaction.py +++ /dev/null @@ -1,17 +0,0 @@ -"""transaction interface module.""" - - -class Base(object): - """transaction base class.""" - - def __init__(self, url): - """init method.""" - pass - - def add_record(self, transaction): - """add new transaction record to the db.""" - raise NotImplementedError("Please Implement this method") - - def get_records(self, query): - """get transactions that meet the given query from the db.""" - raise NotImplementedError("Please Implement this method") diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/base.py b/orm/services/customer_manager/cms_rest/controllers/v1/base.py deleted file mode 100644 index 66c80fa8..00000000 --- a/orm/services/customer_manager/cms_rest/controllers/v1/base.py +++ /dev/null @@ -1,47 +0,0 @@ -from pecan import response -import wsme -from wsme import types as wtypes - - -class ClientSideError(wsme.exc.ClientSideError): - def __init__(self, error, status_code=400): - response.translatable_error = error - super(ClientSideError, self).__init__(error, status_code) - - -class InputValueError(ClientSideError): - def __init__(self, name, value, status_code=400): - super(InputValueError, self).__init__("Invalid value for input {} : {}".format(name, value), status_code) - - -class EntityNotFoundError(ClientSideError): - def __init__(self, id): - super(EntityNotFoundError, self).__init__("Entity not found for {}".format(id), status_code=404) - - -class Base(wtypes.DynamicBase): - pass - - ''' - @classmethod - def from_model(cls, m): - return cls(**(m.as_dict())) - - def as_dict(self, model): - valid_keys = inspect.getargspec(model.__init__)[0] - if 'self' in valid_keys: - valid_keys.remove('self') - return self.as_dict_from_keys(valid_keys) - - - def as_dict_from_keys(self, keys): - return dict((k, getattr(self, k)) - for k in keys - if hasattr(self, k) and - getattr(self, k) != wsme.Unset) - - @classmethod - def from_db_and_links(cls, m, links): - return cls(links=links, **(m.as_dict())) - - ''' diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/enabled.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/enabled.py index f658b0f9..76705b76 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/enabled.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/enabled.py @@ -2,10 +2,10 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger from orm.services.customer_manager.cms_rest.logic.customer_logic import CustomerLogic -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model.Models import CustomerResultWrapper, Enabled from orm.services.customer_manager.cms_rest.utils import authentication diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/metadata.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/metadata.py index 6ba59f40..a4d494d8 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/metadata.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/metadata.py @@ -2,10 +2,10 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.data.sql_alchemy.models import CustomerMetadata from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus import orm.services.customer_manager.cms_rest.logic.metadata_logic as logic from orm.services.customer_manager.cms_rest.model.Models import CustomerResultWrapper, MetadataWrapper from orm.services.customer_manager.cms_rest.utils import authentication diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/regions.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/regions.py index 631a68fa..022156f8 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/regions.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/regions.py @@ -3,11 +3,11 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer.users import UserController from orm.services.customer_manager.cms_rest.logger import get_logger from orm.services.customer_manager.cms_rest.logic.customer_logic import CustomerLogic -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model.Models import Region, RegionResultWrapper from orm.services.customer_manager.cms_rest.utils import authentication diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/root.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/root.py index 89e4e7e6..ee858b5f 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/root.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/root.py @@ -2,6 +2,7 @@ from pecan import rest, request, response from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotAllowedError, NotFoundError from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer.enabled import EnabledController from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer.metadata import MetadataController @@ -9,7 +10,6 @@ from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer.regions from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer.users import DefaultUserController from orm.services.customer_manager.cms_rest.logger import get_logger from orm.services.customer_manager.cms_rest.logic.customer_logic import CustomerLogic -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model.Models import Customer, CustomerResultWrapper, CustomerSummaryResponse from orm.services.customer_manager.cms_rest.utils import authentication @@ -31,7 +31,7 @@ class CustomerController(rest.RestController): result = customer_logic.get_customer(customer_uuid) LOG.info("CustomerController - GetCustomerDetails finished well: " + str(result)) - except ErrorStatus as exception: + except (ErrorStatus, NotFoundError) as exception: LOG.log_exception("CustomerController - Failed to GetCustomerDetails", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), @@ -104,7 +104,7 @@ class CustomerController(rest.RestController): request.headers, customer_id, event_details=event_details) - except ErrorStatus as exception: + except (ErrorStatus, NotFoundError) as exception: LOG.log_exception("Failed in UpdateCustomer", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), @@ -164,12 +164,12 @@ class CustomerController(rest.RestController): request.headers, customer_id, event_details=event_details) - except ErrorStatus as exception: + except (ErrorStatus, NotAllowedError, NotFoundError) as exception: LOG.log_exception("CustomerController - Failed to DeleteCustomer", exception) raise err_utils.get_error(request.transaction_id, - message=str(exception), - status_code=exception.status_code) + status_code=exception.status_code, + message=str(exception)) except Exception as exception: LOG.log_exception("CustomerController - Failed to DeleteCustomer", diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/users.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/users.py index fe053bf8..240ff6cc 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/users.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/customer/users.py @@ -2,10 +2,10 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger from orm.services.customer_manager.cms_rest.logic.customer_logic import CustomerLogic -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus, NotFound from orm.services.customer_manager.cms_rest.model.Models import User, UserResultWrapper from orm.services.customer_manager.cms_rest.utils import authentication @@ -102,7 +102,7 @@ class DefaultUserController(rest.RestController): message=exception.message, status_code=404) - except NotFound as e: + except NotFoundError as e: raise err_utils.get_error(request.transaction_id, message=e.message, status_code=404) @@ -242,7 +242,7 @@ class UserController(rest.RestController): message=exception.message, status_code=404) - except NotFound as e: + except NotFoundError as e: raise err_utils.get_error(request.transaction_id, message=e.message, status_code=404) diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_roles.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_roles.py index e18dbdb6..53a8baa0 100644 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_roles.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_roles.py @@ -3,9 +3,9 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels import \ RoleAssignment, RoleResultWrapper diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_users.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_users.py index 42fd14a8..157898d2 100644 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_users.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/region_users.py @@ -5,8 +5,8 @@ from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import \ - ErrorStatus, NotFound +from orm.common.orm_common.utils.error_base import \ + ErrorStatus, NotFoundError from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels import \ RegionUser, RegionUserResultWrapper @@ -105,7 +105,7 @@ class RegionUserController(rest.RestController): message=exception.message, status_code=exception.status_code) - except NotFound as e: + except NotFoundError as e: raise err_utils.get_error(request.transaction_id, message=e.message, status_code=404) diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/regions.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/regions.py index 6af9febf..5040c6c0 100644 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/regions.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/regions.py @@ -3,13 +3,13 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.controllers.v1.orm.group.\ region_roles import RegionRoleController from orm.services.customer_manager.cms_rest.controllers.v1.orm.group.\ region_users import RegionUserController from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels import \ Region, RegionResultWrapper diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/roles.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/roles.py index 26d064d0..846b3d87 100644 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/roles.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/roles.py @@ -3,9 +3,9 @@ from pecan import request, rest from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels import \ RoleAssignment, RoleResult, RoleResultWrapper diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/root.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/root.py index b094d82b..adef0210 100755 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/root.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/root.py @@ -3,6 +3,7 @@ import oslo_db from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.controllers.v1.orm.group.regions \ import RegionController @@ -11,7 +12,6 @@ from orm.services.customer_manager.cms_rest.controllers.v1.orm.group.roles \ from orm.services.customer_manager.cms_rest.controllers.v1.orm.group.users \ import UserController from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels \ import Group, GroupResultWrapper, GroupSummaryResponse diff --git a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/users.py b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/users.py index 975eef5a..e08577ec 100644 --- a/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/users.py +++ b/orm/services/customer_manager/cms_rest/controllers/v1/orm/group/users.py @@ -5,7 +5,7 @@ from wsmeext.pecan import wsexpose from orm.common.orm_common.utils import api_error_utils as err_utils from orm.common.orm_common.utils import utils from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus, NotFound +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.services.customer_manager.cms_rest.logic.group_logic import GroupLogic from orm.services.customer_manager.cms_rest.model.GroupModels import \ User, UserResultWrapper @@ -101,7 +101,7 @@ class UserController(rest.RestController): message=exception.message, status_code=exception.status_code) - except NotFound as e: + except NotFoundError as e: raise err_utils.get_error(request.transaction_id, message=e.message, status_code=404) diff --git a/orm/services/customer_manager/cms_rest/data/data_manager.py b/orm/services/customer_manager/cms_rest/data/data_manager.py index 7ae20c09..071ba29f 100755 --- a/orm/services/customer_manager/cms_rest/data/data_manager.py +++ b/orm/services/customer_manager/cms_rest/data/data_manager.py @@ -1,5 +1,6 @@ import logging +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.data.sql_alchemy.customer_record \ import CustomerRecord from orm.services.customer_manager.cms_rest.data.sql_alchemy.\ @@ -24,7 +25,6 @@ from orm.services.customer_manager.cms_rest.data.sql_alchemy.models \ UserRole) from orm.services.customer_manager.cms_rest.data.sql_alchemy.user_role_record \ import UserRoleRecord -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from oslo_db.sqlalchemy.enginefacade import LegacyEngineFacade from pecan import conf from sqlalchemy.event import listen diff --git a/orm/services/customer_manager/cms_rest/data/sql_alchemy/base.py b/orm/services/customer_manager/cms_rest/data/sql_alchemy/base.py deleted file mode 100644 index 860e5425..00000000 --- a/orm/services/customer_manager/cms_rest/data/sql_alchemy/base.py +++ /dev/null @@ -1,3 +0,0 @@ -from sqlalchemy.ext.declarative import declarative_base - -Base = declarative_base() diff --git a/orm/services/customer_manager/cms_rest/data/sql_alchemy/groups_user_record.py b/orm/services/customer_manager/cms_rest/data/sql_alchemy/groups_user_record.py index 02fa5922..8302d3ad 100644 --- a/orm/services/customer_manager/cms_rest/data/sql_alchemy/groups_user_record.py +++ b/orm/services/customer_manager/cms_rest/data/sql_alchemy/groups_user_record.py @@ -1,3 +1,4 @@ +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.customer_manager.cms_rest.data.sql_alchemy.cms_user_record \ import CmsUserRecord from orm.services.customer_manager.cms_rest.data.sql_alchemy.models \ @@ -5,7 +6,6 @@ from orm.services.customer_manager.cms_rest.data.sql_alchemy.models \ from orm.services.customer_manager.cms_rest.data.sql_alchemy.region_record \ import RegionRecord from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import NotFound LOG = get_logger(__name__) @@ -106,7 +106,7 @@ class GroupsUserRecord: region_record = RegionRecord(self.session) region_id = region_record.get_region_id_from_name(region_id) if region_id is None: - raise NotFound("region {} ".format(region_query)) + raise NotFoundError("region {} ".format(region_query)) # get cms_user id value for user_id (contains user name) # to query/delete the corresponding group user record @@ -114,7 +114,7 @@ class GroupsUserRecord: cms_user_record = CmsUserRecord(self.session) user_id = cms_user_record.get_cms_user_id_from_name(user_id) if user_id is None: - raise NotFound("user {} ".format(user_name)) + raise NotFoundError("user {} ".format(user_name)) # when deleting user from a specific region, verify that user # is associated with the group and region in the delete request @@ -128,7 +128,7 @@ class GroupsUserRecord: region_id, user_id, domain) if result.rowcount == 0: - raise NotFound("user {}@{} domain".format(user_name, domain)) + raise NotFoundError("user {}@{} domain".format(user_name, domain)) if region_id == -1: cmd = "DELETE ur FROM groups_user ur,groups_user u \ diff --git a/orm/services/customer_manager/cms_rest/data/sql_alchemy/models.py b/orm/services/customer_manager/cms_rest/data/sql_alchemy/models.py index 954e21ab..29b38954 100755 --- a/orm/services/customer_manager/cms_rest/data/sql_alchemy/models.py +++ b/orm/services/customer_manager/cms_rest/data/sql_alchemy/models.py @@ -1,15 +1,18 @@ -from orm.services.customer_manager.cms_rest.data.sql_alchemy.base import Base -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus +from orm.common.orm_common.utils.error_base import ErrorStatus import orm.services.customer_manager.cms_rest.model.GroupModels as GroupWsmeModels import orm.services.customer_manager.cms_rest.model.Models as WsmeModels from oslo_db.sqlalchemy import models import re from sqlalchemy import Column, ForeignKey, Integer, SmallInteger, String +from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship import wsme +Base = declarative_base() + + class CMSBaseModel(models.ModelBase): """Base class from CMS Models.""" diff --git a/orm/services/customer_manager/cms_rest/data/sql_alchemy/user_role_record.py b/orm/services/customer_manager/cms_rest/data/sql_alchemy/user_role_record.py index c5324ca0..398d660a 100755 --- a/orm/services/customer_manager/cms_rest/data/sql_alchemy/user_role_record.py +++ b/orm/services/customer_manager/cms_rest/data/sql_alchemy/user_role_record.py @@ -1,9 +1,9 @@ +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.customer_manager.cms_rest.data.sql_alchemy.cms_user_record import CmsUserRecord from orm.services.customer_manager.cms_rest.data.sql_alchemy.customer_record import CustomerRecord from orm.services.customer_manager.cms_rest.data.sql_alchemy.models import UserRole from orm.services.customer_manager.cms_rest.data.sql_alchemy.region_record import RegionRecord from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import NotFound LOG = get_logger(__name__) @@ -53,14 +53,14 @@ class UserRoleRecord: region_record = RegionRecord(self.session) region_id = region_record.get_region_id_from_name(region_id) if region_id is None: - raise NotFound("region {} ".format(region_query)) + raise NotFoundError("region {} ".format(region_query)) if isinstance(user_id, str): user_query = user_id cms_user_record = CmsUserRecord(self.session) user_id = cms_user_record.get_cms_user_id_from_name(user_id) if user_id is None: - raise NotFound("user {} ".format(user_query)) + raise NotFoundError("user {} ".format(user_query)) # additional logic for delete_user only: check if the provided user id # is associated with the customer and region in cms delete_user request @@ -72,7 +72,7 @@ class UserRoleRecord: result = self.session.connection().execute(user_check) if result.rowcount == 0: - raise NotFound("user {} ".format(user_query)) + raise NotFoundError("user {} ".format(user_query)) if region_id == -1: delete_query = "DELETE ur FROM user_role ur,user_role u " \ diff --git a/orm/services/customer_manager/cms_rest/logic/customer_logic.py b/orm/services/customer_manager/cms_rest/logic/customer_logic.py index 715f6635..a0ccbf98 100755 --- a/orm/services/customer_manager/cms_rest/logic/customer_logic.py +++ b/orm/services/customer_manager/cms_rest/logic/customer_logic.py @@ -8,8 +8,8 @@ from orm.common.orm_common.utils.cross_api_utils import (get_regions_of_group, from orm.services.customer_manager.cms_rest.data.data_manager import DataManager from orm.services.customer_manager.cms_rest.data.sql_alchemy.models import CustomerMetadata from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import (DuplicateEntryError, ErrorStatus, - NotFound) +from orm.common.orm_common.utils.error_base import (ConflictError, ErrorStatus, + NotFoundError, NotAllowedError) from orm.services.customer_manager.cms_rest.model.Models import (CustomerResultWrapper, CustomerSummary, CustomerSummaryResponse, RegionResultWrapper, UserResultWrapper) @@ -22,10 +22,10 @@ class CustomerLogic(object): def build_full_customer(self, customer, uuid, datamanager): cust_metadata = CustomerMetadata() if any(char in ":" for char in customer.name): - raise ErrorStatus(400, "Customer Name does not allow colon(:).") + raise NotAllowedError("Customer Name does not allow colon(:)") if customer.name.strip() == '': - raise ErrorStatus(400, "Customer Name can not be blank.") + raise NotAllowedError("Customer Name can not be blank") if not customer.customerDomain: customer.customerDomain = conf.rds.customer_domain @@ -34,9 +34,10 @@ class CustomerLogic(object): sql_customer = datamanager.add_customer(customer, uuid) except oslo_db.exception.DBDuplicateEntry as exception: - raise ErrorStatus( - 409.2, "Customer name '{}' already exists".format( - customer.name)) + raise ConflictError( + "Customer name '{}' already exists".format( + customer.name), + 409.2) except Exception as exp: LOG.log_exception("CustomerLogic - Failed to CreateCustomer", exp) @@ -71,7 +72,7 @@ class CustomerLogic(object): datamanager.add_customer_region(sql_customer_id, sql_region.id) except Exception as ex: if hasattr(ex, 'orig') and ex.orig[0] == 1062: - raise DuplicateEntryError( + raise ConflictError( 'Error, duplicate entry, region ' + region.name + ' already associated with customer') raise ex @@ -201,7 +202,7 @@ class CustomerLogic(object): sql_customer = customer_record.read_customer_by_uuid(customer_uuid) if not sql_customer: - raise ErrorStatus(404, 'customer {0} was not found'.format(customer_uuid)) + raise NotFoundError('customer {0} was not found'.format(customer_uuid)) old_customer_dict = sql_customer.get_proxy_dict() customer_record.delete_by_primary_key(cutomer_id) datamanager.flush() @@ -254,10 +255,10 @@ class CustomerLogic(object): customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) if region_id is None: - raise ErrorStatus(404, "region {} not found".format(region_name)) + raise NotFoundError("region {} not found".format(region_name)) customer_record = datamanager.get_record('customer') customer = customer_record.read_customer(customer_id) @@ -290,7 +291,7 @@ class CustomerLogic(object): return user_result_wrapper except Exception as exception: if 'Duplicate' in str(exception): - raise ErrorStatus(409, str(exception)) + raise ConflictError(str(exception), 409) datamanager.rollback() LOG.log_exception("Failed to add_users", exception) raise exception @@ -303,11 +304,11 @@ class CustomerLogic(object): customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) region_id = datamanager.get_region_id_by_name(region_name) if region_id is None: - raise ErrorStatus(404, "region {} not found".format(region_name)) + raise NotFoundError("region {} not found".format(region_name)) # delete older default user user_role_record = datamanager.get_record('user_role') @@ -328,7 +329,7 @@ class CustomerLogic(object): customer = datamanager.get_customer_by_uuid(customer_uuid) if customer is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) result = user_role_record.delete_user_from_region(customer_uuid, region_id, @@ -344,7 +345,7 @@ class CustomerLogic(object): "region levels for customer %s. "\ "Use 'delete_default_user' instead." \ % (user_id, region_id, customer_uuid) - raise ErrorStatus(400, message) + raise NotAllowedError(message) RdsProxy.send_customer(customer, transaction_id, "PUT") datamanager.commit() @@ -352,12 +353,12 @@ class CustomerLogic(object): LOG.info("User {0} from region {1} in customer {2} deleted". format(user_id, region_id, customer_uuid)) - except NotFound as e: + except NotFoundError as e: datamanager.rollback() LOG.log_exception("Failed to delete_users, user not found", e.message) - raise NotFound("Failed to delete users, %s not found" % - e.message) + raise NotFoundError("Failed to delete users, %s not found" % + e.message) except Exception as exception: datamanager.rollback() LOG.log_exception("Failed to delete_users", exception) @@ -375,7 +376,7 @@ class CustomerLogic(object): customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) customer_record = datamanager.get_record('customer') customer = customer_record.read_customer(customer_id) @@ -419,7 +420,7 @@ class CustomerLogic(object): except Exception as exception: datamanager.rollback() if 'Duplicate' in str(exception): - raise ErrorStatus(409, str(exception)) + raise ConflictError(str(exception), 409) LOG.log_exception("Failed to add_default_users", exception) raise @@ -431,7 +432,7 @@ class CustomerLogic(object): customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) # delete older default user user_role_record = datamanager.get_record('user_role') @@ -450,14 +451,14 @@ class CustomerLogic(object): try: customer = datamanager.get_customer_by_uuid(customer_uuid) if customer is None: - raise ErrorStatus(404, "customer {} does not exist".format(customer_uuid)) + raise NotFoundError("customer {} does not exist".format(customer_uuid)) user_role_record = datamanager.get_record('user_role') result = user_role_record.delete_user_from_region(customer_uuid, 'DEFAULT', user_id) if result.rowcount == 0: - raise NotFound("user {} ".format(user_id)) + raise NotFoundError("User {} not found".format(user_id)) datamanager.flush() if len(customer.customer_customer_regions) > 1: @@ -468,12 +469,12 @@ class CustomerLogic(object): LOG.info("User {0} from region {1} in customer {2} deleted". format(user_id, 'DEFAULT', customer_uuid)) - except NotFound as e: + except NotFoundError as e: datamanager.rollback() LOG.log_exception("Failed to delete_users, user not found", - e.message) - raise NotFound("Failed to delete user(s), %s not found" % - e.message) + str(e)) + raise NotFoundError("Failed to delete user(s), %s not found" % + str(e)) except Exception as exp: datamanager.rollback() @@ -486,9 +487,8 @@ class CustomerLogic(object): # TODO DataBase action customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, - "customer with id {} does not exist".format( - customer_uuid)) + raise NotFoundError("Customer with id {} does not exist".format( + customer_uuid)) sql_customer = customer_record.read_customer_by_uuid(customer_uuid) @@ -542,15 +542,13 @@ class CustomerLogic(object): try: customer_id = datamanager.get_customer_id_by_uuid(customer_uuid) if customer_id is None: - raise ErrorStatus(404, - "customer with id {} does not exist".format( - customer_uuid)) + raise NotFoundError("customer with id {} does not exist".format( + customer_uuid)) old_sql_customer = customer_record.read_customer_by_uuid(customer_uuid) if old_sql_customer is None: - raise ErrorStatus(404, - "customer with id {} does not exist".format( - customer_id)) + raise NotFoundError("customer with id {} does not exist".format( + customer_id)) old_customer_dict = old_sql_customer.get_proxy_dict() defaultRegion = old_sql_customer.get_default_customer_region() existing_default_users_roles = defaultRegion.customer_region_user_roles if defaultRegion else [] @@ -600,9 +598,8 @@ class CustomerLogic(object): sql_customer = datamanager.get_customer_by_uuid(customer_id) if sql_customer is None: - raise ErrorStatus(404, - "customer with id {} does not exist".format( - customer_id)) + raise NotFoundError("customer with id {} does not exist".format( + customer_id)) customer_dict = sql_customer.get_proxy_dict() customer_region.delete_region_for_customer(customer_id, region_id) @@ -655,7 +652,7 @@ class CustomerLogic(object): sql_customer = customer_record.read_customer_by_uuid_or_name(customer) if not sql_customer: - raise ErrorStatus(404, 'customer: {0} not found'.format(customer)) + raise NotFoundError('customer: {0} not found'.format(customer)) # if we have regions in sql_customer if sql_customer.get_real_customer_regions(): @@ -704,7 +701,7 @@ class CustomerLogic(object): sql_customer = customer_record.read_customer_by_uuid(customer_uuid) if not sql_customer: - raise ErrorStatus(404, 'customer: {0} not found'.format(customer_uuid)) + raise NotFoundError('customer: {0} not found'.format(customer_uuid)) sql_customer.enabled = 1 if enabled.enabled else 0 @@ -730,15 +727,14 @@ class CustomerLogic(object): sql_customer = customer_record.read_customer_by_uuid(customer_id) if sql_customer is None: - raise ErrorStatus(404, "Customer '{0}' not found".format(customer_id)) + raise NotFoundError("Customer '{0}' not found".format(customer_id)) real_regions = sql_customer.get_real_customer_regions() if len(real_regions) > 0: # Do not delete a customer that still has some regions - raise ErrorStatus(405, - "Cannot delete a customer that has regions. " - "Please delete the regions first and then " - "delete the customer.") + raise NotAllowedError("Cannot delete a customer that has regions. " + "Please delete the regions first and then " + "delete the customer.") else: expected_status = 'Success' @@ -760,8 +756,7 @@ class CustomerLogic(object): 'Resource not found in table, so it is OK to delete') if status != expected_status: - raise ErrorStatus(409, - "The customer has not been deleted " + raise ErrorStatus("The customer has not been deleted " "successfully from all of its regions " "(either the deletion failed on one of the " "regions or it is still in progress)") diff --git a/orm/services/customer_manager/cms_rest/logic/error_base.py b/orm/services/customer_manager/cms_rest/logic/error_base.py deleted file mode 100755 index 48b70590..00000000 --- a/orm/services/customer_manager/cms_rest/logic/error_base.py +++ /dev/null @@ -1,20 +0,0 @@ -class Error(Exception): - pass - - -class ErrorStatus(Error): - def __init__(self, status_code, message=None): - self.status_code = status_code - self.message = message - - -class NotFound(Error): - def __init__(self, message=None, status_code=404): - self.status_code = status_code - self.message = message - - -class DuplicateEntryError(Error): - def __init__(self, message=None, status_code=409): - self.status_code = status_code - self.message = message diff --git a/orm/services/customer_manager/cms_rest/logic/group_logic.py b/orm/services/customer_manager/cms_rest/logic/group_logic.py index d40dcc2a..d0a2abbb 100755 --- a/orm/services/customer_manager/cms_rest/logic/group_logic.py +++ b/orm/services/customer_manager/cms_rest/logic/group_logic.py @@ -9,8 +9,12 @@ from orm.common.orm_common.utils.cross_api_utils import ( from orm.services.customer_manager.cms_rest.data.data_manager import \ DataManager from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ( - DuplicateEntryError, ErrorStatus, NotFound) +from orm.common.orm_common.utils.error_base import ( + ConflictError, + ErrorStatus, + InputValueError, + NotAllowedError, + NotFoundError) from orm.services.customer_manager.cms_rest.model.GroupModels import ( GroupResultWrapper, GroupSummary, @@ -31,18 +35,17 @@ class GroupLogic(object): def build_full_group(self, group, uuid, datamanager): if any(char in ":" for char in group.name): - raise ErrorStatus(400, "Group Name does not allow colon(:).") + raise InputValueError("Group Name does not allow colon(:).") if group.name.strip() == '': - raise ErrorStatus(400, "Group Name can not be blank.") + raise InputValueError("Group Name can not be blank.") try: sql_group = datamanager.add_group(group, uuid) except oslo_db.exception.DBDuplicateEntry as exception: - raise ErrorStatus( - 409.2, "Group name '{}' already exists".format( - group.name)) + raise ConflictError( + "Group name '{}' already exists".format(group.name)) except Exception as exp: LOG.log_exception("CustomerLogic - Failed to CreateCustomer", exp) @@ -90,7 +93,7 @@ class GroupLogic(object): datamanager.add_group_region(sql_group_id, sql_region.id) except Exception as ex: if hasattr(ex, 'orig') and ex.orig[0] == 1062: - raise DuplicateEntryError( + raise ConflictError( 'Error, duplicate entry, region ' + region.name + ' already associated with group') @@ -245,8 +248,8 @@ class GroupLogic(object): group_id = datamanager.get_group_by_uuid_or_name(group_uuid) if group_id is None: - raise ErrorStatus(404, "group {} does not exist".format( - group_uuid)) + raise NotFoundError("group {} does not exist".format( + group_uuid)) group_record = datamanager.get_record('group') group = group_record.read_group_by_uuid(group_uuid) @@ -288,7 +291,7 @@ class GroupLogic(object): except Exception as exception: datamanager.rollback() if 'Duplicate' in str(exception): - raise ErrorStatus(409, str(exception)) + raise ConflictError(409, str(exception)) LOG.log_exception("Failed to add_group_default_users", exception) raise @@ -312,12 +315,12 @@ class GroupLogic(object): region_id = datamanager.get_region_id_by_name(region_id) if group_id is None: - raise ErrorStatus(404, "group {} does not exist".format( - group_uuid)) + raise NotFoundError("group {} does not exist".format( + group_uuid)) if region_id is None: - raise ErrorStatus(404, "region {} does not exist".format( - region_uuid)) + raise NotFoundError("region {} does not exist".format( + region_uuid)) group_record = datamanager.get_record('group') group = group_record.read_group_by_uuid(group_uuid) @@ -359,7 +362,7 @@ class GroupLogic(object): except Exception as exception: datamanager.rollback() if 'Duplicate' in str(exception): - raise ErrorStatus(409, str(exception)) + raise ConflictError(409, str(exception)) LOG.log_exception("Failed to add_group_region_users", exception) raise @@ -373,15 +376,15 @@ class GroupLogic(object): try: group = datamanager.get_group_by_uuid_or_name(group_uuid) if group is None: - raise ErrorStatus(404, "group {} does not exist".format( - group_uuid)) + raise NotFoundError("group {} does not exist".format( + group_uuid)) user_record = datamanager.get_record('groups_user') result = user_record.remove_user_from_group(group_uuid, -1, domain, user) if result.rowcount == 0: - raise NotFound("user {}@{} domain".format(user, domain)) + raise NotFoundError("user {}@{} domain".format(user, domain)) datamanager.flush() group_record = datamanager.get_record('group') @@ -396,12 +399,12 @@ class GroupLogic(object): LOG.info("User {0} from region {1} in group {2} deleted". format(user, 'DEFAULT', group_uuid)) - except NotFound as e: + except NotFoundError as e: datamanager.rollback() LOG.log_exception("Failed to delete default user, user not found", - e.message) - raise NotFound("Failed to delete default user," - "default %s not found" % e.message) + str(e)) + raise NotFoundError("Failed to delete default user," + " default %s not found" % str(e)) raise except Exception as exp: @@ -418,8 +421,8 @@ class GroupLogic(object): try: group = datamanager.get_group_by_uuid_or_name(group_uuid) if group is None: - raise ErrorStatus(404, "group {} does not exist".format( - group_uuid)) + raise NotFoundStatus("group {} does not exist".format( + group_uuid)) user_record = datamanager.get_record('groups_user') result = user_record.remove_user_from_group(group_uuid, region_id, user_domain, user) @@ -448,12 +451,12 @@ class GroupLogic(object): "in group {3} deleted".format(user, user_domain, region_id, group_uuid)) - except NotFound as e: + except NotFoundError as e: datamanager.rollback() LOG.log_exception("Failed to delete region user," - " user not found", e.message) - raise NotFound("Failed to delete region user," - " region %s not found" % e.message) + " user not found", str(e)) + raise NotFoundError("Failed to delete region user," + " region %s not found" % str(e)) except Exception as exception: datamanager.rollback() LOG.log_exception("Failed to delete region user", exception) @@ -475,13 +478,11 @@ class GroupLogic(object): sql_group = datamanager.get_group_by_uuid_or_name(group_uuid) if assignment_type != "customer" and assignment_type != "domain": - raise ErrorStatus(400, - "Role unassignment type must either be " - "domain or project.") + raise InputValueError("Role unassignment type must either be " + "domain or project.") if sql_group is None: - raise ErrorStatus( - 404, + raise NotFoundError( "group with id {} does not exist".format(group_uuid)) role_id = datamanager.get_role_id_by_name(role_name) @@ -499,8 +500,7 @@ class GroupLogic(object): customer_id = datamanager.get_customer_id_by_uuid( assignment_value) if customer_id is None: - raise ErrorStatus( - 404, + raise NotFoundError( "customer uuid [{}] does not exist".format( assignment_value)) @@ -587,8 +587,8 @@ class GroupLogic(object): sql_group = group_record.read_group_by_uuid(group_uuid) if not sql_group: - raise ErrorStatus( - 404, 'group {0} was not found'.format(group_uuid)) + raise NotFoundError( + 'group {0} was not found'.format(group_uuid)) # old_group_dict = sql_group.get_proxy_dict() group_record.delete_by_primary_key(group_id) @@ -625,8 +625,7 @@ class GroupLogic(object): try: sql_group = datamanager.get_group_by_uuid_or_name(group_id) if sql_group is None: - raise ErrorStatus( - 404, + raise NotFoundError( "group with id {} does not exist".format(group_id)) defaultRegion = sql_group.get_default_region() default_users =\ @@ -676,8 +675,7 @@ class GroupLogic(object): group_region = datamanager.get_record('groups_region') sql_group = datamanager.get_group_by_uuid_or_name(group_id) if sql_group is None: - raise ErrorStatus( - 404, + raise NotFoundError( "group with id {} does not exist".format(group_id)) group_dict = sql_group.get_proxy_dict() @@ -714,7 +712,7 @@ class GroupLogic(object): sql_group = datamanager.get_group_by_uuid_or_name(group) if not sql_group: - raise ErrorStatus(404, 'group: {0} not found'.format(group)) + raise NotFoundError('group: {0} not found'.format(group)) ret_group = sql_group.to_wsme() if sql_group.get_group_regions(): @@ -787,11 +785,11 @@ class GroupLogic(object): self, group_uuid, region_name, customer_uuid, domain_name): if region_name is None: - raise ErrorStatus(400, "region must be specified in request " - "uri query.") + raise NotAllowedError(400, "region must be specified in request " + "uri query.") if customer_uuid is not None and domain_name is not None: - raise ErrorStatus(400, "customer and domain cannot be used at " - "the same time for query in request uri.") + raise NotAllowedError(400, "customer and domain cannot be used at " + "the same time for query in request uri.") role_result = [] roles = [] @@ -861,16 +859,17 @@ class GroupLogic(object): sql_group = group_record.read_group_by_uuid(group_id) if sql_group is None: - raise ErrorStatus( - 404, "Group '{0}' not found".format(group_id)) + raise NotFoundError( + "Group '{0}' not found".format(group_id)) regions = sql_group.get_group_regions() if len(regions) > 0: # Do not delete a group that still has region(s) - raise ErrorStatus(405, - "Cannot delete a group that has region(s). " - "Please delete the region(s) first and then " - "delete the group.") + raise NotAllowedError( + 405, + " Cannot delete a group that has region(s)." + " Please delete the region(s) first and then" + " delete the group.") else: expected_status = 'Success' invalid_status = 'N/A' diff --git a/orm/services/customer_manager/cms_rest/model/GroupModels.py b/orm/services/customer_manager/cms_rest/model/GroupModels.py index 449270e1..7c240db6 100755 --- a/orm/services/customer_manager/cms_rest/model/GroupModels.py +++ b/orm/services/customer_manager/cms_rest/model/GroupModels.py @@ -1,4 +1,4 @@ -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model.Model import Model from orm.common.orm_common.utils.cross_api_utils import (get_regions_of_group, set_utils_conf) diff --git a/orm/services/customer_manager/cms_rest/model/Models.py b/orm/services/customer_manager/cms_rest/model/Models.py index 9b0a13a7..84a5d1d3 100755 --- a/orm/services/customer_manager/cms_rest/model/Models.py +++ b/orm/services/customer_manager/cms_rest/model/Models.py @@ -1,4 +1,4 @@ -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model.Model import Model from orm.common.orm_common.utils.cross_api_utils import (get_regions_of_group, set_utils_conf) diff --git a/orm/services/customer_manager/cms_rest/rds_proxy.py b/orm/services/customer_manager/cms_rest/rds_proxy.py index f69a9d54..c3a3a5e1 100755 --- a/orm/services/customer_manager/cms_rest/rds_proxy.py +++ b/orm/services/customer_manager/cms_rest/rds_proxy.py @@ -3,8 +3,8 @@ import pprint import requests +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.logger import get_logger -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from pecan import conf, request LOG = get_logger(__name__) diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/base.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/base.py deleted file mode 100755 index 8e26ac4c..00000000 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/base.py +++ /dev/null @@ -1,64 +0,0 @@ -import wsme - - -class ClientSideError(wsme.exc.ClientSideError): - def __init__(self, error, status_code=400): - super(ClientSideError, self).__init__(error, status_code) - - -class NoContent(ClientSideError): - def __init__(self, status_code=204, message="No Content"): - super(NoContent, self).__init__(message, status_code) - - -class JsonError(wsme.exc.ClientSideError): - def __init__(self, status_code=400, message="incompatible JSON body"): - super(JsonError, self).__init__(message, status_code) - - -class AuthenticationHeaderError(ClientSideError): - def __init__(self, error, status_code=401, message="Missing/expired/incorrect authentication header"): - super(AuthenticationHeaderError, self).__init__(message, status_code) - - -class AuthenticationFailed(ClientSideError): - def __init__(self, status_code=403, message="The authenticated user is not allowed to create customers"): - super(AuthenticationFailed, self).__init__(message, status_code) - - -class NotFound(ClientSideError): - def __init__(self, status_code=404, message="The specific transaction was not found", **kw): - super(NotFound, self).__init__(message, status_code) - - -class MethodNotAllowed(ClientSideError): - def __init__(self, status_code=405, message="This method is not allowed. Please use update flavor instead", **kw): - super(MethodNotAllowed, self).__init__(message, status_code) - - -class BusyError(ClientSideError): - def __init__(self, status_code=409, message="Current resource is busy"): - super(BusyError, self).__init__(message, status_code) - - -class ConflictValueError(ClientSideError): - def __init__(self, message="conflict value error", status_code=409): - super(ConflictValueError, self).__init__(message, status_code) - - -class DuplicateFlavorError(ClientSideError): - def __init__(self, status_code=409): - super(DuplicateFlavorError, self).__init__("Flavor already exists", - status_code) - - -error_strategy = { - '204': NoContent, - '400': JsonError, - '401': AuthenticationHeaderError, - '403': AuthenticationFailed, - '404': NotFound, - '405': MethodNotAllowed, - '409': BusyError, - '409.1': DuplicateFlavorError -} diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/flavors.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/flavors.py index b77fea2a..ba935bd4 100755 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/flavors.py +++ b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/flavors.py @@ -1,5 +1,6 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotAllowedError, NotFoundError from orm.common.orm_common.utils import utils as common_utils from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors.os_extra_specs import OsExtraSpecsController from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors.regions import RegionController @@ -7,7 +8,6 @@ from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors.tags import from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors.tenants import TenantController from orm.services.flavor_manager.fms_rest.data.wsme.models import FlavorListFullResponse, FlavorWrapper from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.utils import authentication from pecan import conf, request, rest @@ -54,20 +54,20 @@ class FlavorController(rest.RestController): event_details=event_details) return result - except ErrorStatus as exception: - LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) + except (ErrorStatus, NotFoundError) as exception: + LOG.error("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), status_code=exception.status_code) except ValueError as exception: - LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) + LOG.error("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, status_code=400, error_details=str(exception)) except Exception as exception: - LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) + LOG.error("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=str(exception)) @@ -89,14 +89,14 @@ class FlavorController(rest.RestController): LOG.info("FlavorController - GetFlavorDetails finished well: " + str(result)) return result - except ErrorStatus as exception: - LOG.log_exception("FlavorController - Failed to GetFlavorDetails", exception) + except (ErrorStatus, NotFoundError) as exception: + LOG.error("FlavorController - Failed to GetFlavorDetails", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), status_code=exception.status_code) except Exception as exception: - LOG.log_exception("FlavorController - Failed to GetFlavorDetails", exception) + LOG.error("FlavorController - Failed to GetFlavorDetails", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=str(exception)) @@ -117,13 +117,13 @@ class FlavorController(rest.RestController): starts_with, contains, alias) return result except ErrorStatus as exception: - LOG.log_exception("FlavorController - Failed to GetFlavorlist", exception) + LOG.error("FlavorController - Failed to GetFlavorlist", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), status_code=exception.status_code) except Exception as exception: - LOG.log_exception("FlavorController - Failed to GetFlavorlist", exception) + LOG.error("FlavorController - Failed to GetFlavorlist", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=str(exception)) @@ -143,14 +143,14 @@ class FlavorController(rest.RestController): request.headers, flavor_uuid, event_details=event_details) - except ErrorStatus as exception: - LOG.log_exception("FlavorController - Failed to delete flavor", exception) + except (ErrorStatus, NotAllowedError, NotFoundError) as exception: + LOG.error("FlavorController - Failed to delete flavor", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), status_code=exception.status_code) except Exception as exception: - LOG.log_exception("FlavorController - Failed to delete flavor", exception) + LOG.error("FlavorController - Failed to delete flavor", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=str(exception)) diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/os_extra_specs.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/os_extra_specs.py index 08658849..1315988e 100755 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/os_extra_specs.py +++ b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/os_extra_specs.py @@ -2,9 +2,9 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.wsme.models import ExtraSpecsWrapper from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.utils import authentication from pecan import request, rest diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/regions.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/regions.py index 6b12409a..4e545fb0 100755 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/regions.py +++ b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/regions.py @@ -1,8 +1,8 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.services.flavor_manager.fms_rest.data.wsme.models import RegionWrapper from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.utils import authentication from pecan import request, rest @@ -72,7 +72,7 @@ class RegionController(rest.RestController): request.headers, flavor_id, event_details=event_details) - except ErrorStatus as exception: + except (ErrorStatus, NotFoundError) as exception: LOG.log_exception("RegionController - Failed to delete region", exception) raise err_utils.get_error(request.transaction_id, diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tags.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tags.py index a9c48f68..bcdccee4 100644 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tags.py +++ b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tags.py @@ -2,9 +2,9 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.wsme.models import TagsWrapper from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.utils import authentication from pecan import request, rest diff --git a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tenants.py b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tenants.py index df2c4d12..5b54c226 100755 --- a/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tenants.py +++ b/orm/services/flavor_manager/fms_rest/controllers/v1/orm/flavors/tenants.py @@ -1,8 +1,8 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.wsme.models import TenantWrapper from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.utils import authentication from pecan import request, rest diff --git a/orm/services/flavor_manager/fms_rest/data/sql_alchemy/data_manager.py b/orm/services/flavor_manager/fms_rest/data/sql_alchemy/data_manager.py index a568d074..3b0cee45 100755 --- a/orm/services/flavor_manager/fms_rest/data/sql_alchemy/data_manager.py +++ b/orm/services/flavor_manager/fms_rest/data/sql_alchemy/data_manager.py @@ -1,6 +1,5 @@ import logging -# from orm.services.flavor_manager.fms_rest.logic.error_base import DuplicateEntityError from orm.services.flavor_manager.fms_rest.data.sql_alchemy.flavor.\ flavor_record import FlavorRecord from oslo_db.sqlalchemy.enginefacade import LegacyEngineFacade diff --git a/orm/services/flavor_manager/fms_rest/data/sql_alchemy/db_models.py b/orm/services/flavor_manager/fms_rest/data/sql_alchemy/db_models.py index d2e65398..2a489370 100755 --- a/orm/services/flavor_manager/fms_rest/data/sql_alchemy/db_models.py +++ b/orm/services/flavor_manager/fms_rest/data/sql_alchemy/db_models.py @@ -1,7 +1,7 @@ from builtins import reversed +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from oslo_config import cfg from oslo_db.sqlalchemy import models @@ -136,13 +136,13 @@ class Flavor(Base, FMSBaseModel): def add_region(self, flavor_region): assert isinstance(flavor_region, FlavorRegion) try: - LOG.debug("add region {0} to flavor {1}".format(str(flavor_region), - str(self))) + LOG.debug("add region {0} to flavor {1}".format(flavor_region, + self)) self.flavor_regions.append(flavor_region) except Exception as exception: LOG.log_exception("Failed to add region {0} to flavor {1}".format( - str(flavor_region), str(self)), exception) + str(flavor_region), str(self), exception)) raise def remove_region(self, region_name): @@ -150,18 +150,22 @@ class Flavor(Base, FMSBaseModel): assert isinstance(region_name, str) try: LOG.debug("remove regions {0} from flavor {1}".format(region_name, - str(self))) + self)) + flavor_regions_names = [] for region in reversed(self.flavor_regions): + flavor_regions_names.append(region.region_name) if region.region_name == region_name: self.flavor_regions.remove(region) region_deleted_flag = True - if not region_deleted_flag: - raise ErrorStatus( - 404, - "Failed to remove region {0} from flavor id {1}".format( - region_name, str(self.id))) + if not region_deleted_flag and region_name not in flavor_regions_names: + raise NotFoundError("Region {0} not found on flavor id {1}".format( + region_name, self.id)) + + elif not region_deleted_flag: + raise ErrorStatus("Failed to remove region {0} from flavor id {1}".format( + region_name, self.id)) except ErrorStatus as e: raise @@ -169,7 +173,7 @@ class Flavor(Base, FMSBaseModel): except Exception as exception: LOG.log_exception( "Failed to remove region {0} from flavor {1}".format( - region_name, str(self)), exception) + region_name, self), exception) raise def add_tags(self, flavor_tags): diff --git a/orm/services/flavor_manager/fms_rest/data/wsme/models.py b/orm/services/flavor_manager/fms_rest/data/wsme/models.py index ced99d93..4b2cd6e1 100755 --- a/orm/services/flavor_manager/fms_rest/data/wsme/models.py +++ b/orm/services/flavor_manager/fms_rest/data/wsme/models.py @@ -3,9 +3,9 @@ import wsme from orm.common.orm_common.utils.cross_api_utils import (set_utils_conf, get_regions_of_group, validate_description) +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.sql_alchemy import db_models from orm.services.flavor_manager.fms_rest.data.wsme.model import Model -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from oslo_config import cfg from pecan import conf, request @@ -128,7 +128,7 @@ class Region(Model): def to_db_model(self): if self.name == '' or self.name.isspace(): - raise ErrorStatus(400, 'Cannot add region with empty name') + raise ErrorStatus('Cannot add region with empty name') region_rec = db_models.FlavorRegion() region_rec.region_name = self.name region_rec.region_type = self.type @@ -238,15 +238,15 @@ class Flavor(Model): if self.series: valid_flavor_series = cfg.CONF.fms.flavor_series if self.series not in valid_flavor_series: - raise ErrorStatus(400, "Series possible values are {}".format( + raise ErrorStatus("Series possible values are {}".format( valid_flavor_series)) else: - raise ErrorStatus(400, "Series not specified.") + raise ErrorStatus("Series not specified.") if self.series in cfg.CONF['flavor_series_metadata']: series_metadata = cfg.CONF['flavor_series_metadata'][self.series] else: - raise ErrorStatus(400, "Cannot retrieve requested flavor" + raise ErrorStatus("Cannot retrieve requested flavor" " series metadata.") if 'valid_options_numa' in series_metadata: @@ -266,7 +266,7 @@ class Flavor(Model): invalid_opt_vals = [x for x in option_values if (x.lower() not in ['true', 'false'])] if invalid_opt_vals: - raise ErrorStatus(400, "All flavor option values must have" + raise ErrorStatus("All flavor option values must have" " a value of 'true' or 'false'") # validate series and set flavor vcpu and vram limits @@ -287,73 +287,67 @@ class Flavor(Model): isValid = validate_description(self.description) if not isValid: - raise ErrorStatus(400, "Flavor description does not allow" + raise ErrorStatus("Flavor description does not allow" " special characters: only dashes," " commas, and period allowed.") if not self.ram.isdigit(): - raise ErrorStatus(400, "ram must be a number") + raise ErrorStatus("ram must be a number") if not self.vcpus.isdigit(): - raise ErrorStatus(400, "vcpus must be a number") + raise ErrorStatus("vcpus must be a number") if not self.validInt(self.disk): - raise ErrorStatus(400, "disk must be a number") + raise ErrorStatus("disk must be a number") if not self.swap.isdigit(): - raise ErrorStatus(400, "swap must be a number") + raise ErrorStatus("swap must be a number") if self.ephemeral and not self.ephemeral.isdigit(): - raise ErrorStatus(400, "ephemeral must be a number") + raise ErrorStatus("ephemeral must be a number") if int(self.ram) not in list(range(1024, vram_limit + 1, 1024)): - raise ErrorStatus(400, - "ram value % is out of range. Expected range" + raise ErrorStatus("ram value % is out of range. Expected range" " is 1024(1GB)-% (% GB) and must be a" " multiple of 1024".format( self.ram, vram_limit, vram_limit // 1024)) if int(self.vcpus) not in list(range(1, vcpu_limit + 1)): - raise ErrorStatus(400, "vcpus value % is out of range. Expected" + raise ErrorStatus("vcpus value % is out of range. Expected" "range is 1-%" % (str(self.vcpus), str(vcpu_limit))) if int(self.disk) < 0: - raise ErrorStatus(400, "disk cannot be less than zero") + raise ErrorStatus("disk cannot be less than zero") if not self.ephemeral: self.ephemeral = "0" elif (self.ephemeral and int(self.ephemeral) not in list(range(0, ephemeral_limit + 1))): - raise ErrorStatus(400, - "ephemeral value {} is out of range. Expected" + raise ErrorStatus("ephemeral value {} is out of range. Expected" " range is 0-{} ({}TB)".format( self.ephemeral, ephemeral_limit, ephemeral_limit // 1000)) if int(self.swap) not in list(range(0, swap_file_limit + 1, 1024)): - raise ErrorStatus(400, - "swap value {} is out of range. Expected" + raise ErrorStatus("Swap value {} is out of range. Expected" " range is 0-{}({}GB) and must be a" " multiple of 1024".format( self.swap, swap_file_limit, swap_file_limit // 1024)) except ValueError: - raise ErrorStatus(400, "ram, vcpus, disk, ephemeral and swap must" + raise ErrorStatus("Ram, vcpus, disk, ephemeral and swap must" " be integers") for symbol, value in self.extra_specs.items(): if symbol == 'numa_override' and value not in valid_numa: - raise ErrorStatus(400, - "Invalid value. numa_override possible" + raise ErrorStatus("Invalid value. numa_override possible" " values: " + str(valid_numa)) if symbol == 'vlan_category' and value not in valid_vnf: - raise ErrorStatus(400, - "Invalid value. vlan_category possible" + raise ErrorStatus("Invalid value. vlan_category possible" " values: " + str(valid_vnf)) # region type can be group only in create flavor!! if not context == "create": for region in self.regions: if region.type == "group": - raise ErrorStatus(400, - "region type \'group\' is invalid in" + raise ErrorStatus("region type \'group\' is invalid in" " this action, \'group\' can be only" " in create flavor action") diff --git a/orm/services/flavor_manager/fms_rest/logic/error_base.py b/orm/services/flavor_manager/fms_rest/logic/error_base.py deleted file mode 100644 index 6cff057d..00000000 --- a/orm/services/flavor_manager/fms_rest/logic/error_base.py +++ /dev/null @@ -1,31 +0,0 @@ - -class Error(Exception): - pass - - -class ErrorStatus(Error): - - def __init__(self, status_code, message=""): - self.status_code = status_code - self.message = message - - -class NotFoundError(ErrorStatus): - - def __init__(self, status_code=404, message="not found"): - self.status_code = status_code - self.message = message - - -class DuplicateEntityError(ErrorStatus): - - def __init__(self, status_code=409, message="item already exist"): - self.status_code = status_code - self.message = message - - -class ConflictError(ErrorStatus): - - def __init__(self, status_code=409, message="conflict error"): - self.status_code = status_code - self.message = message diff --git a/orm/services/flavor_manager/fms_rest/logic/flavor_logic.py b/orm/services/flavor_manager/fms_rest/logic/flavor_logic.py index a35b8672..417aa9d5 100755 --- a/orm/services/flavor_manager/fms_rest/logic/flavor_logic.py +++ b/orm/services/flavor_manager/fms_rest/logic/flavor_logic.py @@ -6,8 +6,8 @@ from orm.services.flavor_manager.fms_rest.data.wsme.models import ( Region, RegionWrapper, TagsWrapper, TenantWrapper) from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ( - ConflictError, ErrorStatus, NotFoundError) +from orm.common.orm_common.utils.error_base import ( + ConflictError, EntityNotFound, ErrorStatus, NotAllowedError, NotFoundError) from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import utils @@ -86,7 +86,7 @@ def create_flavor(flavor, flavor_uuid, transaction_id): # disallow tenant assignment if no flavor region assigned if flavor.flavor.tenants: raise ErrorStatus( - 400, 'Cannot add tenants with no flavor region assigned ') + 'Cannot add tenants with no flavor region assigned ') sql_flavor = flavor.to_db_model() @@ -107,8 +107,8 @@ def create_flavor(flavor, flavor_uuid, transaction_id): except oslo_db.exception.DBDuplicateEntry as exception: utils.delete_uuid(flavor_uuid) - raise ErrorStatus( - 409.2, "Flavor name '{}' already exists".format( + raise ConflictError( + "Flavor name '{}' already exists".format( flavor.flavor.name)) except Exception as exp: @@ -155,7 +155,7 @@ def update_flavor(flavor, flavor_uuid, transaction_id): # pragma: no cover flavor_rec = datamanager.get_record('flavor') db_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if db_flavor is None: - raise Exception("Flavor {0} not found".format(flavor_uuid)) + raise EntityNotFound("Flavor {0} not found in database".format(flavor_uuid)) existing_region_names = db_flavor.get_existing_region_names() @@ -194,7 +194,7 @@ def delete_flavor_by_uuid(flavor_uuid): sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if sql_flavor is None: message_not_found = "Flavor '{}' not found".format(flavor_uuid) - raise ErrorStatus(404, message_not_found) + raise NotFoundError(message_not_found) existing_region_names = sql_flavor.get_existing_region_names() if len(existing_region_names) > 0: @@ -203,7 +203,7 @@ def delete_flavor_by_uuid(flavor_uuid): "Please delete the regions first and then " \ "delete the flavor." LOG.info(msg) - raise ErrorStatus(405, msg) + raise NotAllowedError(msg) else: expected_status = 'Success' @@ -229,7 +229,7 @@ def delete_flavor_by_uuid(flavor_uuid): "(either the deletion failed on one of the " \ "regions or it is still in progress)" LOG.error('Invalid flavor status received from RDS') - raise ErrorStatus(409, msg) + raise ErrorStatus(msg, 409) # OK to delete flavor_rec.delete_by_uuid(flavor_uuid) @@ -258,18 +258,16 @@ def add_regions(flavor_uuid, regions, transaction_id): flavor_rec = datamanager.get_record('flavor') sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus(404, - 'flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError('flavor id {0} not found'.format(flavor_uuid)) existing_region_names = sql_flavor.get_existing_region_names() flvr_tenant_list, flvr_region_list = [], [] for region in regions.regions: if region.name == '' or region.name.isspace(): - raise ErrorStatus(400, 'Cannot add region with an empty name') + raise ErrorStatus('Cannot add region with an empty name') if region.type == "group": - raise ErrorStatus(400, - "Adding \'group\' type region is supported" + raise ErrorStatus("Adding \'group\' type region is supported" " only when creating a flavor") db_region = FlavorRegion(region_name=region.name, region_type='single') @@ -310,14 +308,13 @@ def add_regions(flavor_uuid, regions, transaction_id): except ErrorStatus as exp: LOG.log_exception("FlavorLogic - Failed to add regions", str(exp)) datamanager.rollback() - raise exp + raise except Exception as exp: LOG.log_exception("FlavorLogic - Failed to add regions", str(exp)) datamanager.rollback() if "conflicts with persistent instance" in str(exp): - raise ConflictError(409, - "One or more regions already exists in Flavor") - raise exp + raise ConflictError("One or more regions already exists in Flavor") + raise finally: datamanager.close() @@ -353,15 +350,16 @@ def delete_orphaned_tenants(sql_flavor, remaining_regions, datamanager): datamanager.commit() except ErrorStatus as exp: - LOG.log_exception("FlavorLogic - Failed to remove tenant", str(exp)) + LOG.log_exception("FlavorLogic - Failed to remove tenant - exception:", + str(exp)) datamanager.rollback() - raise exp + raise except Exception as exp: LOG.log_exception( - "FlavorLogic - Failed to remove tenant - exception:", str(exp)) + "FlavorLogic - Failed to remove tenant - exception: ", str(exp)) datamanager.rollback() - raise exp + raise @di.dependsOn('data_manager') @@ -372,8 +370,7 @@ def delete_region(flavor_uuid, region_name, transaction_id, force_delete): flavor_rec = datamanager.get_record('flavor') sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus(404, - 'flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError('flavor id {0} not found'.format(flavor_uuid)) existing_region_names = sql_flavor.get_existing_region_names() sql_flavor.remove_region(region_name) @@ -390,16 +387,16 @@ def delete_region(flavor_uuid, region_name, transaction_id, force_delete): else: datamanager.rollback() - except ErrorStatus as exp: + except (ErrorStatus, NotFoundError) as exp: LOG.log_exception("FlavorLogic - Failed to delete region", str(exp)) datamanager.rollback() - raise exp + raise except Exception as exp: LOG.log_exception( "FlavorLogic - Failed to delete region - exception:", str(exp)) datamanager.rollback() - raise exp + raise else: delete_orphaned_tenants(sql_flavor, remaining_regions, datamanager) @@ -416,11 +413,10 @@ def add_tenants(flavor_uuid, tenants, transaction_id): flavor_rec = datamanager.get_record('flavor') sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus(404, - 'Flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError('Flavor id {0} not found'.format(flavor_uuid)) if sql_flavor.visibility == "public": - raise ErrorStatus(405, 'Cannot add tenant to a public flavor') + raise NotAllowedError('Cannot add tenant to a public flavor') existing_region_list = sql_flavor.get_existing_region_names() @@ -443,7 +439,7 @@ def add_tenants(flavor_uuid, tenants, transaction_id): else: # disallow tenant assignment if no flavor region assigned raise ErrorStatus( - 400, 'Cannot add tenants with no flavor region assigned') + 'Cannot add tenants with no flavor region assigned') if not (tenants.tenants and valid_tenants_list): raise ValueError("At least one valid tenant must be provided") @@ -472,7 +468,7 @@ def add_tenants(flavor_uuid, tenants, transaction_id): datamanager.rollback() LOG.log_exception("FlavorLogic - Failed to add tenants", str(exp)) if "conflicts with persistent instance" in str(exp): - raise ConflictError(409, "One or more tenants already exist") + raise ConflictError("One or more tenants already exist") raise finally: datamanager.close() @@ -486,8 +482,7 @@ def delete_tenant(flavor_uuid, tenant_id, transaction_id): flavor_rec = datamanager.get_record('flavor') sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus(404, - 'flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError('flavor id {0} not found'.format(flavor_uuid)) if sql_flavor.visibility == "public": raise ValueError("{} is a public flavor, delete tenant" @@ -502,17 +497,13 @@ def delete_tenant(flavor_uuid, tenant_id, transaction_id): datamanager.commit() except NotFoundError as exp: datamanager.rollback() - LOG.log_exception("FlavorLogic - Flavor not found", str(exp)) + LOG.log_exception("FlavorLogic - Tenant not found", str(exp)) raise except ErrorStatus as exp: datamanager.rollback() - if exp.status_code == 404: - LOG.log_exception("FlavorLogic - Tenant not found", str(exp)) - raise - else: - LOG.log_exception( - "FlavorLogic - failed to delete tenant", str(exp)) - raise + LOG.log_exception( + "FlavorLogic - failed to delete tenant", str(exp)) + raise except Exception as exp: LOG.log_exception("FlavorLogic - Failed to delete tenant", str(exp)) datamanager.rollback() @@ -541,8 +532,7 @@ def get_extra_specs_uuid(flavor_id, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, 'flavor id {0} not found'.format( - flavor_id)) + raise NotFoundError('flavor id {0} not found'.format(flavor_id)) result = ExtraSpecsWrapper.from_db_model(sql_flavor.flavor_extra_specs) @@ -573,7 +563,7 @@ def delete_extra_specs(flavor_id, transaction_id, extra_spec=None): flavor_rec = datamanager.get_record("flavor") sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, 'flavor id {0} not found'.format( + raise NotFoundError('flavor id {0} not found'.format( flavor_id)) existing_region_names = sql_flavor.get_existing_region_names() @@ -586,7 +576,7 @@ def delete_extra_specs(flavor_id, transaction_id, extra_spec=None): sql_flavor.remove_extra_spec(extra_spec) else: raise ErrorStatus( - 400, "Deletion not allowed for {0}".format(extra_spec)) + "Deletion not allowed for {0}".format(extra_spec)) else: sql_flavor.delete_all_extra_specs() sql_flavor.add_extra_specs(default_extra_specs) @@ -631,7 +621,7 @@ def get_tags(flavor_uuid): sql_flavor = flavor_record.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus(404, 'flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError('flavor id {0} not found'.format(flavor_uuid)) flavor_wrapper = FlavorWrapper.from_db_model(sql_flavor) datamanager.close() @@ -652,8 +642,7 @@ def delete_tags(flavor_id, tag, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, - 'flavor id {0} not found'.format(flavor_id)) + raise NotFoundError('flavor id {0} not found'.format(flavor_id)) if tag: sql_flavor.remove_tag(tag) @@ -696,7 +685,7 @@ def update_tags(flavor_id, tags, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, "flavor id {} not found".format( + raise NotFoundError("flavor id {} not found".format( flavor_id)) tags_models = tags.to_db_model() @@ -735,7 +724,7 @@ def add_extra_specs(flavor_id, extra_specs, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, 'flavor id {0} not found'.format( + raise NotFoundError('flavor id {0} not found'.format( flavor_id)) existing_region_names = sql_flavor.get_existing_region_names() @@ -759,7 +748,6 @@ def add_extra_specs(flavor_id, extra_specs, transaction_id): datamanager.rollback() if "conflicts with persistent instance" in str(exp.args): raise ConflictError( - 409, "one or all extra specs {} already" " exists".format(extra_specs.os_extra_specs)) LOG.log_exception("FlavorLogic - fail to add extra spec", exp) @@ -782,7 +770,7 @@ def update_extra_specs(flavor_id, extra_specs, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, "flavor id {} not found".format( + raise NotFoundError("flavor id {} not found".format( flavor_id)) extra_specs_models = extra_specs.to_db_model() @@ -832,8 +820,8 @@ def get_flavor_by_uuid(flavor_uuid): sql_flavor = flavor_record.get_flavor_by_id(flavor_uuid) if not sql_flavor: - raise ErrorStatus( - 404, 'flavor id {0} not found'.format(flavor_uuid)) + raise NotFoundError( + 'flavor id {0} not found'.format(flavor_uuid)) flavor_wrapper = get_flavor_status( sql_flavor, datamanager.get_session()) @@ -858,7 +846,7 @@ def add_tags(flavor_id, tags, transaction_id): sql_flavor = flavor_rec.get_flavor_by_id(flavor_id) if not sql_flavor: - raise NotFoundError(404, 'flavor id {0} not found'.format( + raise NotFoundError('flavor id {0} not found'.format( flavor_id)) tags_model = tags.to_db_model() @@ -878,7 +866,7 @@ def add_tags(flavor_id, tags, transaction_id): datamanager.rollback() if "conflicts with persistent instance" in str(exp.args): raise ConflictError( - 409, "one or all tags {} already exists".format(tags.tags)) + "one or all tags {} already exists".format(tags.tags)) LOG.log_exception("FlavorLogic - fail to add tags", exp) raise finally: @@ -919,8 +907,7 @@ def get_flavor_by_uuid_or_name(flavor_uuid_or_name): flavor_uuid_or_name) if not sql_flavor: - raise ErrorStatus( - 404, + raise NotFoundError( 'flavor id or name {0} not found'.format(flavor_uuid_or_name)) flavor_wrapper = get_flavor_status( diff --git a/orm/services/flavor_manager/fms_rest/proxies/rds_proxy.py b/orm/services/flavor_manager/fms_rest/proxies/rds_proxy.py index a9207675..472425f0 100755 --- a/orm/services/flavor_manager/fms_rest/proxies/rds_proxy.py +++ b/orm/services/flavor_manager/fms_rest/proxies/rds_proxy.py @@ -3,8 +3,8 @@ import pprint import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.logger import get_logger -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from pecan import conf, request @@ -86,7 +86,7 @@ def send_flavor(flavor_dict, transaction_id, action="put"): if resp.content and 200 <= resp.status_code < 300: content = resp.json() else: - raise ErrorStatus(resp.status_code, "Got error from rds server, code: {0} message: {1}".format(resp.status_code, content)) + raise ErrorStatus("Got error from rds server, code: {0} message: {1}".format(resp.status_code, resp.json()['faultstring']), resp.status_code) return content diff --git a/orm/services/id_generator/uuidgen/controllers/v1/uuid_controller.py b/orm/services/id_generator/uuidgen/controllers/v1/uuid_controller.py index 16479c55..e469d433 100755 --- a/orm/services/id_generator/uuidgen/controllers/v1/uuid_controller.py +++ b/orm/services/id_generator/uuidgen/controllers/v1/uuid_controller.py @@ -6,7 +6,7 @@ import uuid from pecan import expose, request, response from pecan.rest import RestController -from orm.common.orm_common.utils.error_base import NotFound +from orm.common.orm_common.utils.error_base import NotFoundError from orm.common.orm_common.utils import utils from orm.services.id_generator.uuidgen.db.db_manager import DBManager from orm.services.id_generator.uuidgen.utils import authentication @@ -35,7 +35,7 @@ class UUIDController(RestController): response.status = 404 message = "UUID {} not found".format(uuid) messageToReturn = respond( - "NotFound", response.status, message) + "NotFoundError", response.status, message) return messageToReturn return results.get_dict() @@ -63,7 +63,7 @@ class UUIDController(RestController): db_session, auth_region, 'identity') if keystone_ep is None: - raise NotFound + raise NotFoundError authentication.authorize(request, 'uuid:delete', keystone_ep) @@ -74,12 +74,12 @@ class UUIDController(RestController): "MissingParams", response.status, message) return messageToReturn - except NotFound as e: + except NotFoundError as e: response.status = 404 message = "EP for region:{} type:identity not found".format( auth_region) messageToReturn = respond( - "EndpointNotFound", response.status, message) + "NotFoundError", response.status, message) return messageToReturn except Exception as e: diff --git a/orm/services/image_manager/data_manager_test.py b/orm/services/image_manager/data_manager_test.py deleted file mode 100755 index 5de4eeb8..00000000 --- a/orm/services/image_manager/data_manager_test.py +++ /dev/null @@ -1,229 +0,0 @@ -import os -import traceback - -from .ims.logger import get_logger -from .ims.persistency.sql_alchemy.data_manager import DataManager -from .ims.persistency.sql_alchemy.db_models import (Image, ImageCustomer, - ImageProperty, ImageRegion) -from pecan import conf -from pecan.testing import load_test_app - -# conf = imp.load_source('config.py', '../config.py') - - -image_id = "Id 11" # image id - -LOG = get_logger(__name__) - - -def main(): - try: - # prepare_service() - - print(conf.database) - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - image = image_record.get_image(image_id) - - print(image.regions) - print(image.properties) - - all_images = image_record.get_all_images(start=0, limit=50) - print(all_images) - - # LOG.debug("TestDatabase finished well") - - except Exception as exception: - print(("Exception" + str(exception))) - # LOG.error("Exception in TestDatabase: " + str(exception)) - - -def delete(): - try: - # prepare_service() - - print(conf.database) - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - data_manager.begin_transaction() - - result = image_record.delete_by_id(image_id) - - data_manager.commit() - print("Nm records deleted: " + str(result.rowcount)) - # LOG.debug("TestDatabase finished well") - - except Exception as exception: - print(("Exception" + str(exception))) - - # LOG.error("Exception in TestDatabase: " + str(exception)) - - -def main2(): - # get customer by id of 1 - try: - # prepare_service() - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - criterias = {"visibility": "public", "region": "North", "tenant": "Tenanat-1", "start": 0, "limit": 10, - "profile": "NS"} - images = image_record.get_images_by_criteria(**criterias) - - print(len(images)) - - except Exception as exception: - LOG.log_exception("Failed to get_images_by_criteria: ", exception) - # log_exception(LOG, "Failed to read customer: 10", exception) - # log_exception("Failed to read customer: 10", exception) - # LOG.error("Exception in TestDatabase: " + str(exception)) - # print_exception(exception) - - -def main3(): - try: - # prepare_service() - - print(conf.database) - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - image = image_record.get_image(image_id) - - print(image.image_extra_specs) - print(image.image_regions) - print(image.image_tenants) - - region = ImageRegion(region_name="Israel") - image.add_region(region) - - region = ImageRegion(region_name="Israel2") - image.add_region(region) - - tenant = ImageCustomer(tenant_id="Zion") - image.add_tenant(tenant) - - tenant = ImageCustomer(tenant_id="Zion2") - image.add_tenant(tenant) - - data_manager.commit() - - # LOG.debug("TestDatabase finished well") - - except Exception as exception: - print(("Exception" + str(exception))) - # LOG.error("Exception in TestDatabase: " + str(exception)) - - -def main4(): - try: - # prepare_service() - - print(conf.database) - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - image = image_record.get_image(image_id) - - print(image.image_extra_specs) - print(image.image_regions) - print(image.image_tenants) - - image.remove_region("Israel") - image.remove_region("Israel2") - - image.remove_tenant("Zion") - image.remove_tenant("Zion2") - - data_manager.commit() - - # LOG.debug("TestDatabase finished well") - - except Exception as exception: - print(("Exception" + str(exception))) - # LOG.error("Exception in TestDatabase: " + str(exception)) - - -def insert_data(): - try: - # prepare_service() - - print(conf.database) - - data_manager = DataManager() - - image_record = data_manager.get_record("Image") - - image_property1 = ImageProperty(key_name="key_1", key_value="key_valu1") - image_property2 = ImageProperty(key_name="key_2", key_value="key_valu2") - image_property3 = ImageProperty(key_name="key_3", key_value="key_valu3") - - image_region1 = ImageRegion(region_name="region1", region_type="single") - image_region2 = ImageRegion(region_name="region2", region_type="single") - - image = Image(name="Name1", - id="Id 10", - enabled=1, - protected="protected", - url="Http:\\zion.com", - visibility="puplic", - disk_format="disk format", - container_format="container_format", - min_disk=512, - owner="zion", - schema="big_data", - min_ram=1) - - image.properties.append(image_property1) - image.properties.append(image_property2) - image.properties.append(image_property3) - image.regions.append(image_region1) - image.regions.append(image_region2) - image_record.insert(image) - - data_manager.commit() - - # LOG.debug("TestDatabase finished well") - - except Exception as exception: - print(("Exception" + str(exception))) - # LOG.error("Exception in TestDatabase: " + str(exception)) - - -def print_exception(): - try: - print("*** print_exc:") - traceback.print_exc() - print("*** format_exception:") - print(traceback.format_exc()) - print("*** extract_tb:") - print(traceback.extract_tb()) - print("*** format_tb:") - print(traceback.format_tb()) - except Exception as exception1: - print("*** print_exc:") - traceback.print_exc() - - -if __name__ == "__main__": - app = load_test_app(os.path.join( - os.path.dirname(__file__), - './config.py' - )) - - # main() - insert_data() - delete() - # main4() diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/base.py b/orm/services/image_manager/ims/controllers/v1/orm/images/base.py deleted file mode 100755 index 3032e9b7..00000000 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/base.py +++ /dev/null @@ -1,49 +0,0 @@ -import wsme - - -class ClientSideError(wsme.exc.ClientSideError): - def __init__(self, error, status_code=400): - super(ClientSideError, self).__init__(error, status_code) - - -class JsonError(wsme.exc.ClientSideError): - def __init__(self, status_code=400, message='incompatible JSON body'): - super(JsonError, self).__init__(message, status_code) - - -class AuthenticationHeaderError(ClientSideError): - def __init__(self, error, status_code=401, - message='Missing/expired/incorrect authentication header'): - super(AuthenticationHeaderError, self).__init__(message, status_code) - - -class AuthenticationFailed(ClientSideError): - def __init__(self, status_code=403, - message='The authenticated user is not allowed to create' - ' customers'): - super(AuthenticationFailed, self).__init__(message, status_code) - - -class NotFound(ClientSideError): - def __init__(self, status_code=404, message="Not Found"): - super(NotFound, self).__init__(message, status_code) - - -class NoContent(ClientSideError): - def __init__(self, status_code=204, message="Not Content"): - super(NoContent, self).__init__(message, status_code) - - -class BusyError(ClientSideError): - def __init__(self, status_code=409, message='Current resource is busy'): - super(BusyError, self).__init__(message, status_code) - - -error_strategy = { - '400': JsonError, - '401': AuthenticationHeaderError, - '403': AuthenticationFailed, - '404': NotFound, - '204': NoContent, - '409': BusyError -} diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/customers.py b/orm/services/image_manager/ims/controllers/v1/orm/images/customers.py index 0e5ad066..be859b2a 100755 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/customers.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/images/customers.py @@ -1,7 +1,7 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import CustomerWrapper, ImageWrapper from orm.services.image_manager.ims.utils import authentication as auth diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/enabled.py b/orm/services/image_manager/ims/controllers/v1/orm/images/enabled.py index 8106dc50..65f98f2f 100755 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/enabled.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/images/enabled.py @@ -2,8 +2,8 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import Enabled, ImageWrapper from orm.services.image_manager.ims.utils import authentication as auth diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/images.py b/orm/services/image_manager/ims/controllers/v1/orm/images/images.py index 9b94ac91..c29810c3 100755 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/images.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/images/images.py @@ -2,11 +2,11 @@ import oslo_db from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images.customers import CustomerController from orm.services.image_manager.ims.controllers.v1.orm.images.enabled import EnabledController from orm.services.image_manager.ims.controllers.v1.orm.images.regions import RegionController from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import ImageSummaryResponse, ImageWrapper from orm.services.image_manager.ims.utils import authentication as auth diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/metadata.py b/orm/services/image_manager/ims/controllers/v1/orm/images/metadata.py index 0a859c68..b4a2497e 100644 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/metadata.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/images/metadata.py @@ -1,7 +1,7 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import MetadataWrapper from orm.services.image_manager.ims.utils import authentication as auth @@ -29,13 +29,19 @@ class MetadataController(rest.RestController): LOG.info("MetadataController - metadata added") return "OK" + except NotFoundError as exception: + LOG.error("MetadataController - failed to add metadata: ", exception) + raise err_utils.get_error(request.transaction_id, + message=str(exception), + status_code=exception.status_code) + except ErrorStatus as exception: - LOG.log_exception("MetadataController - Failed to add metadata", exception) + LOG.error("MetadataController - Failed to add metadata", exception) raise err_utils.get_error(request.transaction_id, message=str(exception), status_code=exception.status_code) except Exception as exception: - LOG.log_exception("MetadataController - Failed to add metadata", exception) + LOG.error("MetadataController - Failed to add metadata", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=str(exception)) diff --git a/orm/services/image_manager/ims/controllers/v1/orm/images/regions.py b/orm/services/image_manager/ims/controllers/v1/orm/images/regions.py index 1bcf68d4..6e54181d 100755 --- a/orm/services/image_manager/ims/controllers/v1/orm/images/regions.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/images/regions.py @@ -1,8 +1,8 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images.metadata import MetadataController from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import RegionWrapper from orm.services.image_manager.ims.utils import authentication as auth diff --git a/orm/services/image_manager/ims/controllers/v1/orm/logs.py b/orm/services/image_manager/ims/controllers/v1/orm/logs.py index cebfafc3..c552b67a 100755 --- a/orm/services/image_manager/ims/controllers/v1/orm/logs.py +++ b/orm/services/image_manager/ims/controllers/v1/orm/logs.py @@ -1,5 +1,5 @@ import logging - +from orm.common.orm_common.utils.error_base import ClientSideError from pecan import rest import wsme from wsmeext.pecan import wsexpose @@ -7,11 +7,6 @@ from wsmeext.pecan import wsexpose logger = logging.getLogger(__name__) -class ClientSideError(wsme.exc.ClientSideError): - def __init__(self, error, status_code=400): - super(ClientSideError, self).__init__(error, status_code) - - class LogChangeResultWSME(wsme.types.DynamicBase): """log change result wsme type.""" @@ -55,7 +50,7 @@ class LogsController(rest.RestController): result = "Fail to change log_level. Reason: {}".format( str(e)) logger.error(result) - raise ClientSideError(error=str(e)) + raise ClientSideError(message=str(e)) return LogChangeResult(result) @staticmethod diff --git a/orm/services/image_manager/ims/logic/error_base.py b/orm/services/image_manager/ims/logic/error_base.py deleted file mode 100755 index 7cc7e13c..00000000 --- a/orm/services/image_manager/ims/logic/error_base.py +++ /dev/null @@ -1,38 +0,0 @@ - -class Error(Exception): - pass - - -class ErrorStatus(Error): - - def __init__(self, status_code, message=""): - self.status_code = status_code - self.message = message - - -class NoContentError(ErrorStatus): - - def __init__(self, message='', status_code=204): - self.status_code = status_code - self.message = message - - -class NotFoundError(ErrorStatus): - - def __init__(self, message='', status_code=404): - self.status_code = status_code - self.message = message - - -class DuplicateEntityError(ErrorStatus): - - def __init__(self, status_code=409, message="item already exist"): - self.status_code = status_code - self.message = message - - -class ConflictError(ErrorStatus): - - def __init__(self, status_code=409, message="conflict error"): - self.status_code = status_code - self.message = message diff --git a/orm/services/image_manager/ims/logic/image_logic.py b/orm/services/image_manager/ims/logic/image_logic.py index b499849e..a33c6218 100755 --- a/orm/services/image_manager/ims/logic/image_logic.py +++ b/orm/services/image_manager/ims/logic/image_logic.py @@ -3,7 +3,7 @@ import time from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import utils from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import \ +from orm.common.orm_common.utils.error_base import \ ErrorStatus, NotFoundError from orm.services.image_manager.ims.persistency.sql_alchemy.db_models import \ ImageCustomer, ImageRegion @@ -49,8 +49,9 @@ def create_image(image_wrapper, image_uuid, transaction_id): except oslo_db.exception.DBDuplicateEntry as exception: utils.delete_uuid(image_uuid) raise ErrorStatus( - 409.2, "Image name '{}' already exists".format( - image_wrapper.image.name)) + "Image name '{}' already exists".format( + image_wrapper.image.name), + 409) except Exception as exp: LOG.log_exception("ImageLogic - Failed to CreateImage", exp) @@ -138,15 +139,15 @@ def delete_image_by_uuid(image_uuid, transaction_id): sql_image = image_rec.get_image_by_id(image_uuid) if sql_image is None: message_not_found = "Image '{}' not found".format(image_uuid) - raise ErrorStatus(404, message_not_found) + raise NotFoundError(message_not_found) image_existing_region_names = sql_image.get_existing_region_names() if len(image_existing_region_names) > 0: # Do not delete an image that still has region(s) - raise ErrorStatus(405, - "Cannot delete a image with regions. " + raise ErrorStatus("Cannot delete a image with regions. " "Please delete the regions first and then " - "delete the image. ") + "delete the image.", + 405) # Get status from resource status table uuid = [sql_image.id] @@ -164,10 +165,11 @@ def delete_image_by_uuid(image_uuid, transaction_id): LOG.debug('Resource not found in table, so it is OK to delete') if status != 'Success': - raise ErrorStatus(405, "not allowed as aggregate status " + raise ErrorStatus("not allowed as aggregate status " "have to be Success (either the deletion " "failed on one of the regions or it is " - "still in progress)") + "still in progress)", + 405) image_rec.delete_image_by_id(image_uuid) datamanager.flush() # i want to get any exception created by this @@ -193,7 +195,7 @@ def add_regions(image_uuid, regions, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image with id: {0} not found'.format( + raise NotFoundError('image with id: {0} not found'.format( image_uuid)) existing_region_names = sql_image.get_existing_region_names() @@ -218,11 +220,12 @@ def add_regions(image_uuid, regions, transaction_id): except ErrorStatus as exp: LOG.log_exception("ImageLogic - Failed to add regions", exp) datamanager.rollback() - raise exp + raise + except Exception as exp: LOG.log_exception("ImageLogic - Failed to add regions", exp) datamanager.rollback() - raise exp + raise @di.dependsOn('data_manager') @@ -234,7 +237,7 @@ def replace_regions(image_uuid, regions, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image with id: {0} not found'.format( + raise NotFoundError('image with id: {0} not found'.format( image_uuid)) existing_region_names = sql_image.get_existing_region_names() @@ -259,13 +262,13 @@ def replace_regions(image_uuid, regions, transaction_id): return ret except ErrorStatus as exp: - LOG.log_exception("ImageLogic - Failed to replace regions", exp) + LOG.error("ImageLogic - Failed to replace regions", exp) datamanager.rollback() - raise exp + raise except Exception as exp: - LOG.log_exception("ImageLogic - Failed to repalce regions", exp) + LOG.error("ImageLogic - Failed to repalce regions", exp) datamanager.rollback() - raise exp + raise @di.dependsOn('data_manager') @@ -277,13 +280,13 @@ def delete_region(image_uuid, region_name, transaction_id, force_delete): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image with id: {0} not found'.format( - image_uuid)) + raise NotFoundError('image with id: {0} not found'.format( + image_uuid)) # do not allow delete_region for protected images if sql_image.protected: protect_msg = "Protected image {} cannot be deleted. Please " \ "update image with protected=false and try again" - raise ErrorStatus(400, protect_msg.format(image_uuid)) + raise ErrorStatus(protect_msg.format(image_uuid), 400) existing_region_names = sql_image.get_existing_region_names() sql_image.remove_region(region_name) @@ -321,12 +324,11 @@ def add_customers(image_uuid, customers, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image with id: {0} not found'.format( + raise NotFoundError('image with id: {0} not found'.format( image_uuid)) if sql_image.visibility != "shared": - raise ErrorStatus(400, - 'Customer can only be added to shared image.') + raise ErrorStatus('Customer can only be added to shared image.') existing_region_names = sql_image.get_existing_region_names() @@ -346,7 +348,7 @@ def add_customers(image_uuid, customers, transaction_id): except Exception as exp: if 'conflicts with persistent instance' in str(exp) or \ 'Duplicate entry' in str(exp): - raise ErrorStatus(409, "Duplicate Customer for Image") + raise ErrorStatus("Duplicate Customer for Image") LOG.log_exception("ImageLogic - Failed to add Customers", exp) datamanager.rollback() raise @@ -361,7 +363,7 @@ def replace_customers(image_uuid, customers, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image {0} not found'.format(image_uuid)) + raise NotFoundError('image {0} not found'.format(image_uuid)) if sql_image.visibility != "shared": raise ValueError('Customer can only be replaced with shared Image') @@ -385,7 +387,7 @@ def replace_customers(image_uuid, customers, transaction_id): except Exception as exp: if 'conflicts with persistent instance' in str(exp) or \ 'Duplicate entry' in str(exp): - raise ErrorStatus(409, "Duplicate Customer for Image") + raise ErrorStatus("Duplicate Customer for Image", 409) LOG.log_exception("ImageLogic - Failed to add Customers", exp) datamanager.rollback() raise @@ -400,7 +402,7 @@ def delete_customer(image_uuid, customer_id, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'image {0} not found'.format(image_uuid)) + raise NotFoundError('image {0} not found'.format(image_uuid)) if sql_image.visibility != "shared": raise ValueError( @@ -490,7 +492,7 @@ def get_image_by_uuid(image_uuid, query_by_id_or_name=False): except NotFoundError as exp: datamanager.rollback() LOG.log_exception("ImageLogic - Failed to update image", exp) - raise exp + raise except Exception as exp: datamanager.rollback() @@ -576,7 +578,7 @@ def enable_image(image_uuid, int_enabled, transaction_id): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_uuid) if not sql_image: - raise ErrorStatus(404, 'Image with id: {0} not found'.format( + raise NotFoundError('Image with id: {0} not found'.format( image_uuid)) sql_image.enabled = int_enabled @@ -598,9 +600,9 @@ def enable_image(image_uuid, int_enabled, transaction_id): LOG.log_exception( "ImageLogic - Failed to change image activation value", exp) datamanager.rollback() - raise exp + raise except Exception as exp: LOG.log_exception( "ImageLogic - Failed to change image activation value", exp) datamanager.rollback() - raise exp + raise diff --git a/orm/services/image_manager/ims/logic/metadata_logic.py b/orm/services/image_manager/ims/logic/metadata_logic.py index 38feb0bb..bdc783a5 100644 --- a/orm/services/image_manager/ims/logic/metadata_logic.py +++ b/orm/services/image_manager/ims/logic/metadata_logic.py @@ -1,6 +1,6 @@ from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus LOG = get_logger(__name__) @@ -16,7 +16,7 @@ def add_metadata(image_id, region_name, metadata_wrapper): image_rec = datamanager.get_record('image') sql_image = image_rec.get_image_by_id(image_id) if not sql_image: - raise ErrorStatus(404, 'image {0} not found'.format(image_id)) + raise NotFoundError('image {0} not found'.format(image_id)) for region in sql_image.regions: if region.region_name == region_name: @@ -26,8 +26,7 @@ def add_metadata(image_id, region_name, metadata_wrapper): datamanager.flush() datamanager.commit() - except Exception as exp: - LOG.log_exception("ImageLogic - Failed to add regions", exp) + LOG.error("ImageLogic - Failed to add regions", exp) datamanager.rollback() raise diff --git a/orm/services/image_manager/ims/persistency/sql_alchemy/db_models.py b/orm/services/image_manager/ims/persistency/sql_alchemy/db_models.py index 87175dac..43428b9c 100755 --- a/orm/services/image_manager/ims/persistency/sql_alchemy/db_models.py +++ b/orm/services/image_manager/ims/persistency/sql_alchemy/db_models.py @@ -10,7 +10,7 @@ ### from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus, NotFoundError +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.common.orm_common.utils.cross_api_utils import (get_regions_of_group, set_utils_conf) from oslo_db.sqlalchemy import models diff --git a/orm/services/image_manager/ims/persistency/wsme/models.py b/orm/services/image_manager/ims/persistency/wsme/models.py index b3c1a81d..fdf8e7b2 100755 --- a/orm/services/image_manager/ims/persistency/wsme/models.py +++ b/orm/services/image_manager/ims/persistency/wsme/models.py @@ -1,5 +1,5 @@ """Image model module.""" -from orm.services.image_manager.ims.logic.error_base import ErrorStatus +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.sql_alchemy import db_models from orm.services.image_manager.ims.persistency.wsme.base import Model from orm.common.orm_common.utils.cross_api_utils import (get_regions_of_group, diff --git a/orm/services/image_manager/ims/proxies/rds_proxy.py b/orm/services/image_manager/ims/proxies/rds_proxy.py index d6532348..307a1d19 100755 --- a/orm/services/image_manager/ims/proxies/rds_proxy.py +++ b/orm/services/image_manager/ims/proxies/rds_proxy.py @@ -3,8 +3,8 @@ import pprint import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.logger import get_logger -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from pecan import conf, request diff --git a/orm/services/region_manager/csv2db.py b/orm/services/region_manager/csv2db.py index 52ab9b60..de49851b 100755 --- a/orm/services/region_manager/csv2db.py +++ b/orm/services/region_manager/csv2db.py @@ -2,7 +2,7 @@ import csv import logging from . import config -from .rms.storage.base_data_manager import SQLDBError +from .rms.storage.data_manager import SQLDBError from .rms.storage.my_sql.data_manager import DataManager logger = logging.getLogger(__name__) diff --git a/orm/services/region_manager/rms/controllers/lcp_controller.py b/orm/services/region_manager/rms/controllers/lcp_controller.py index 9e82be2f..6435ed33 100755 --- a/orm/services/region_manager/rms/controllers/lcp_controller.py +++ b/orm/services/region_manager/rms/controllers/lcp_controller.py @@ -1,8 +1,8 @@ import logging from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.region_manager.rms.model import url_parm -from orm.services.region_manager.rms.services.error_base import ErrorStatus from orm.services.region_manager.rms.services import services from orm.services.region_manager.rms.utils import authentication diff --git a/orm/services/region_manager/rms/controllers/v2/orm/resources/groups.py b/orm/services/region_manager/rms/controllers/v2/orm/resources/groups.py index 3e44c244..60a6f9d9 100755 --- a/orm/services/region_manager/rms/controllers/v2/orm/resources/groups.py +++ b/orm/services/region_manager/rms/controllers/v2/orm/resources/groups.py @@ -3,9 +3,9 @@ import logging import wsme from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError from orm.common.orm_common.utils import utils from orm.services.region_manager.rms.model import model as PythonModel -from orm.services.region_manager.rms.services import error_base from orm.services.region_manager.rms.services import services as GroupService from orm.services.region_manager.rms.utils import authentication @@ -126,10 +126,10 @@ class GroupsController(rest.RestController): logger.debug('Returning group, regions: {}'.format(result.regions)) return result - except error_base.NotFoundError as e: + except NotFoundError as e: logger.error("GroupsController - Group not found") raise err_utils.get_error(request.transaction_id, - message=e.message, + message=str(e), status_code=404) except Exception as exception: logger.error(exception.message) @@ -192,8 +192,8 @@ class GroupsController(rest.RestController): event_details=event_details) return Result(group) - except error_base.ErrorStatus as e: - logger.error("GroupsController - {}".format(e.message)) + except (NotFoundError, ErrorStatus) as e: + logger.error("GroupsController :- {}".format(e.message)) raise err_utils.get_error(request.transaction_id, message=e.message, status_code=e.status_code) @@ -220,15 +220,15 @@ class GroupsController(rest.RestController): event_details=event_details) # issue NotFoundError for "delete group" when group_id not found - except error_base.NotFoundError as e: + except NotFoundError as e: logger.error("GroupsController - Group not found") raise err_utils.get_error(request.transaction_id, - message="Cannot delete - " + e.message, + message="Cannot delete - " + str(e), status_code=404) except Exception as exp: - logger.exception("fail to delete group :- {}".format(exp)) + logger.exception("Failed to delete group :- {}".format(exp)) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=exp.message) @@ -237,13 +237,13 @@ class GroupsController(rest.RestController): @wsexpose(Result, str, body=Groups, status_code=201, rest_content_types='json') def put(self, group_id, group): - logger.info("update group") + logger.info("Update group called") authentication.authorize(request, 'group:update') try: - logger.debug("update group - id {}".format(group_id)) + logger.debug("Update group :- id {}".format(group_id)) result = GroupService.update_group(group, group_id) - logger.debug("group updated to :- {}".format(result)) + logger.debug("Group updated :- {}".format(result)) result = GroupService.get_groups_data(group_id) # build result group_result = OutputResource(result.id, result.name, @@ -259,14 +259,14 @@ class GroupsController(rest.RestController): request.headers, group_id, event_details=event_details) - except error_base.ErrorStatus as exp: - logger.error("group to update not found {}".format(exp)) + except (ErrorStatus, NotFoundError) as exp: + logger.error("group to update not found :- {}".format(exp)) logger.exception(exp) raise err_utils.get_error(request.transaction_id, message=exp.message, status_code=exp.status_code) except Exception as exp: - logger.error("fail to update groupt -- id {}".format(group_id)) + logger.error("fail to update group :- id {}".format(group_id)) logger.exception(exp) raise diff --git a/orm/services/region_manager/rms/controllers/v2/orm/resources/metadata.py b/orm/services/region_manager/rms/controllers/v2/orm/resources/metadata.py index 6c7cd2c8..63216fb3 100755 --- a/orm/services/region_manager/rms/controllers/v2/orm/resources/metadata.py +++ b/orm/services/region_manager/rms/controllers/v2/orm/resources/metadata.py @@ -2,8 +2,8 @@ import json import logging from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils import error_base from orm.common.orm_common.utils import utils -from orm.services.region_manager.rms.services import error_base from orm.services.region_manager.rms.services import services as RegionService from orm.services.region_manager.rms.utils import authentication diff --git a/orm/services/region_manager/rms/controllers/v2/orm/resources/regions.py b/orm/services/region_manager/rms/controllers/v2/orm/resources/regions.py index 66c4da23..a71e6754 100755 --- a/orm/services/region_manager/rms/controllers/v2/orm/resources/regions.py +++ b/orm/services/region_manager/rms/controllers/v2/orm/resources/regions.py @@ -2,6 +2,8 @@ import logging from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils.error_base import (ErrorStatus, ConflictError, + InputValueError, NotFoundError) from orm.common.orm_common.utils import utils from orm.services.region_manager.rms.controllers.v2.orm.resources.metadata \ import RegionMetadataController @@ -11,7 +13,6 @@ from orm.services.region_manager.rms.controllers.v2.orm.resources.status \ from orm.services.region_manager import config from orm.services.region_manager.rms.model import model as PythonModel from orm.services.region_manager.rms.model import url_parm -from orm.services.region_manager.rms.services import error_base from orm.services.region_manager.rms.services import services as RegionService from orm.services.region_manager.rms.utils import authentication @@ -213,7 +214,7 @@ class RegionsController(rest.RestController): :param zip: query field :param vlcp_name query field :return: json from db - :exception: EntityNotFoundError 404 + :exception: NotFoundError 404 """ logger.info("Entered Get Regions") authentication.authorize(request, 'region:get_all') @@ -237,17 +238,17 @@ class RegionsController(rest.RestController): return result - except error_base.ErrorStatus as e: - logger.error("RegionsController {}".format(e.message)) + except ErrorStatus as exp: + logger.error("RegionsController {}".format(exp.message)) raise err_utils.get_error(request.transaction_id, - message=e.message, - status_code=e.status_code) + message=exp.message, + status_code=exp.status_code) - except Exception as exception: - logger.error(str(exception)) + except Exception as exp: + logger.error(str(exp)) raise err_utils.get_error(request.transaction_id, status_code=500, - message=str(exception)) + message=str(exp)) @wsexpose(RegionsData, str, status_code=200, rest_content_types='json') def get_one(self, id_or_name): @@ -259,16 +260,23 @@ class RegionsController(rest.RestController): result = RegionService.get_region_by_id_or_name(id_or_name) logger.debug( "API: Got region {} success: {}".format(id_or_name, result)) - except error_base.ErrorStatus as exp: + except ErrorStatus as exp: logger.error("RegionsController {}".format(exp.message)) raise err_utils.get_error(request.transaction_id, message=exp.message, status_code=exp.status_code) - except Exception as exp: - logger.exception(str(exp)) + + except NotFoundError as exp: + logger.error("Region {} not found".format(id_or_name)) raise err_utils.get_error(request.transaction_id, - status_code=500, - error_details=str(exp)) + message=exp.message, + status_code=exp.status_code) + + except Exception as exp: + logger.error(str(exp)) + raise err_utils.get_error(request.transaction_id, + message=str(exp), + status_code=500) return result @@ -295,13 +303,13 @@ class RegionsController(rest.RestController): utils.audit_trail('create region', request.transaction_id, request.headers, full_region_input.id, event_details=event_details) - except error_base.InputValueError as exp: - logger.exception("Error in save region {}".format(exp.message)) + except InputValueError as exp: + logger.exception("Error in save region {}".format(str(exp))) raise err_utils.get_error(request.transaction_id, status_code=exp.status_code, - message=exp.message) + message=str(exp)) - except error_base.ConflictError as exp: + except ConflictError as exp: logger.exception("Conflict error {}".format(exp.message)) raise err_utils.get_error(request.transaction_id, message=exp.message, @@ -333,14 +341,14 @@ class RegionsController(rest.RestController): # issue NotFoundError for "Delete Region" when group_id not found # which is returned by RegionService.delete_region function - except error_base.NotFoundError as exp: + except NotFoundError as exp: logger.error("RegionsController - Region not found") raise err_utils.get_error( request.transaction_id, - message="Cannot delete - " + exp.message, + message="Cannot delete - " + str(exp), status_code=exp.status_code) - except error_base.ConflictError as exp: + except ConflictError as exp: logger.error("Region with resources cannot be deleted") raise err_utils.get_error(request.transaction_id, status_code=400, @@ -376,17 +384,17 @@ class RegionsController(rest.RestController): request.headers, region_id, event_details=event_details) - except error_base.NotFoundError as exp: + except NotFoundError as exp: logger.exception("region {} not found".format(region_id)) raise err_utils.get_error(request.transaction_id, status_code=exp.status_code, - message=exp.message) + message=str(exp)) - except error_base.InputValueError as exp: - logger.exception("not valid input {}".format(exp.message)) + except InputValueError as exp: + logger.exception("not valid input {}".format(str(exp))) raise err_utils.get_error(request.transaction_id, status_code=exp.status_code, - message=exp.message) + message=str(exp)) except Exception as exp: logger.exception( "API: error in updating region {}.. " diff --git a/orm/services/region_manager/rms/controllers/v2/orm/resources/status.py b/orm/services/region_manager/rms/controllers/v2/orm/resources/status.py index 02cb718f..a2b26bff 100755 --- a/orm/services/region_manager/rms/controllers/v2/orm/resources/status.py +++ b/orm/services/region_manager/rms/controllers/v2/orm/resources/status.py @@ -1,8 +1,8 @@ import logging from orm.common.orm_common.utils import api_error_utils as err_utils +from orm.common.orm_common.utils import error_base from orm.common.orm_common.utils import utils -from orm.services.region_manager.rms.services import error_base from orm.services.region_manager.rms.services import services as RegionService from orm.services.region_manager.rms.utils import authentication @@ -77,11 +77,16 @@ class RegionStatusController(rest.RestController): raise err_utils.get_error(request.transaction_id, message=e.message, status_code=e.status_code) - except Exception as exception: - logger.error(str(exception)) + except error_base.InputValueError as e: + logger.error(e.message) + raise err_utils.get_error(request.transaction_id, + message=e.message, + status_code=e.status_code) + except Exception as e: + logger.error(str(e)) raise err_utils.get_error(request.transaction_id, status_code=500, - error_details=str(exception)) + error_details=str(e)) @wsexpose(str, str, rest_content_types='json') def get(self, region_id): diff --git a/orm/services/region_manager/rms/model/model.py b/orm/services/region_manager/rms/model/model.py index 8d25e6a2..133df04d 100755 --- a/orm/services/region_manager/rms/model/model.py +++ b/orm/services/region_manager/rms/model/model.py @@ -1,6 +1,6 @@ """model module.""" +from orm.common.orm_common.utils import error_base from orm.services.region_manager.rms.logger import get_logger -from orm.services.region_manager.rms.services import error_base from pecan import conf logger = get_logger(__name__) diff --git a/orm/services/region_manager/rms/services/error_base.py b/orm/services/region_manager/rms/services/error_base.py deleted file mode 100755 index a39268de..00000000 --- a/orm/services/region_manager/rms/services/error_base.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Exceptions module.""" - - -class Error(Exception): - pass - - -class ErrorStatus(Error): - - def __init__(self, status_code, message=""): - super(ErrorStatus, self).__init__(message) - self.status_code = status_code - self.message = message - - -class NotFoundError(ErrorStatus): - - def __init__(self, status_code=404, message="Not found"): - super(NotFoundError, self).__init__(message) - self.status_code = status_code - self.message = message - - -class ConflictError(ErrorStatus): - - def __init__(self, status_code=409, message="Conflict error"): - self.status_code = status_code - self.message = message - - -class InputValueError(ErrorStatus): - - def __init__(self, status_code=400, message="value not allowed"): - self.status_code = status_code - self.message = message diff --git a/orm/services/region_manager/rms/services/services.py b/orm/services/region_manager/rms/services/services.py index 9f367933..58975664 100755 --- a/orm/services/region_manager/rms/services/services.py +++ b/orm/services/region_manager/rms/services/services.py @@ -1,9 +1,10 @@ """DB actions wrapper module.""" import logging +from orm.common.orm_common.utils.error_base import (ConflictError, InputValueError, + NotFoundError) from orm.services.region_manager.rms.model.model import Groups, Regions -from orm.services.region_manager.rms.services import error_base -from orm.services.region_manager.rms.storage import base_data_manager, data_manager_factory +from orm.services.region_manager.rms.storage import data_manager_factory LOG = logging.getLogger(__name__) @@ -19,7 +20,9 @@ def get_regions_data(url_parms): db = data_manager_factory.get_data_manager() regions = db.get_regions(region_dict, metadata_dict, end_point) if not regions: - raise error_base.NotFoundError(message="No regions found for the given search parameters") + message = "No regions found for the given search parameters" + LOG.error(message) + raise NotFoundError(message) return Regions(regions) @@ -35,10 +38,10 @@ def get_region_by_id_or_name(region_id_or_name): region = db.get_region_by_id_or_name(region_id_or_name) if not region: - raise error_base.NotFoundError(message="Region {} not found".format(region_id_or_name)) + raise NotFoundError(message="Region {} not found".format(region_id_or_name)) except Exception as exp: - LOG.exception("error in get region by id/name") + LOG.error("Error in get region by id/name") raise return region @@ -61,11 +64,11 @@ def update_region(region_id, region): LOG.debug("region {} updated".format(region_id)) result = get_region_by_id_or_name(region_id) - except error_base.NotFoundError as exp: - LOG.exception("fail to update region {}".format(str(exp))) + except NotFoundError as exp: + LOG.error("fail to update region {}".format(str(exp))) raise except Exception as exp: - LOG.exception("fail to update region {}".format(str(exp))) + LOG.error("fail to update region {}".format(str(exp))) raise return result @@ -83,20 +86,20 @@ def delete_region(region_id): # logic to allow 'delete_region' to issue NotFoundError when region_id is non-existent region = db.get_region_by_id_or_name(region_id) if not region: - raise error_base.NotFoundError(message="Region '{}' not found".format(region_id)) + raise NotFoundError("Region '{}' not found".format(region_id)) # Region with resources cannnot be deleted resource_exist = db.query_region_resources(region_id) if resource_exist: region_resources_exist_msg = "Region {} cannot be deleted as " \ "resources are assigned.".format(region_id) - raise error_base.ConflictError(message=region_resources_exist_msg) + raise ConflictError(region_resources_exist_msg) db.delete_region(region_id) LOG.debug("region deleted") except Exception as exp: - LOG.exception("fail to delete region {}".format(str(exp))) + LOG.error("fail to delete region {}".format(str(exp))) raise return @@ -121,14 +124,11 @@ def create_full_region(full_region): LOG.debug("region added") result = get_region_by_id_or_name(full_region.id) - except error_base.InputValueError as exp: - LOG.exception("error in save region {}".format(str(exp))) + except (ConflictError, InputValueError) as exp: + LOG.error("Error in save region: {}".format(str(exp))) raise - except base_data_manager.DuplicateEntryError as exp: - LOG.exception("error in save region {}".format(str(exp))) - raise error_base.ConflictError(message=str(exp)) except Exception as exp: - LOG.exception("error in save region {}".format(str(exp))) + LOG.error("Error in save region: {}".format(str(exp))) raise return result @@ -141,12 +141,12 @@ def add_region_metadata(region_id, metadata_dict): db = data_manager_factory.get_data_manager() result = db.add_meta_data_to_region(region_id, metadata_dict) if not result: - raise error_base.NotFoundError(message="Region {} not found".format(region_id)) + raise NotFoundError("Region {} not found".format(region_id)) else: return result.metadata except Exception as exp: - LOG.exception("Error getting metadata for region id:".format(region_id)) + LOG.error("Error getting metadata for region id:".format(region_id)) raise @@ -157,13 +157,12 @@ def update_region_metadata(region_id, metadata_dict): db = data_manager_factory.get_data_manager() result = db.update_region_meta_data(region_id, metadata_dict) if not result: - raise error_base.NotFoundError(message="Region {} not " - "found".format(region_id)) + raise NotFoundError("Region {} not found".format(region_id)) else: return result.metadata except Exception as exp: - LOG.exception("Error getting metadata for region id:".format(region_id)) + LOG.error("Error getting metadata for region id:".format(region_id)) raise @@ -175,7 +174,7 @@ def delete_metadata_from_region(region_id, metadata_key): db.delete_region_metadata(region_id, metadata_key) except Exception as exp: - LOG.exception("Error getting metadata for region id:".format(region_id)) + LOG.error("Error getting metadata for region id:".format(region_id)) raise @@ -189,7 +188,7 @@ def get_groups_data(name): db = data_manager_factory.get_data_manager() groups = db.get_group(name) if not groups: - raise error_base.NotFoundError(message="Group {} not found".format(name)) + raise NotFoundError("Group {} not found".format(name)) return Groups(**groups) @@ -206,7 +205,6 @@ def get_all_groups(): except Exception as exp: LOG.error("fail to get all groups") - LOG.exception(str(exp)) raise return all_groups @@ -224,13 +222,13 @@ def delete_group(group_id): # logic to allow 'delete_group' to issue NotFoundError when group_id is non-existent groups = db.get_group(group_id) if not groups: - raise error_base.NotFoundError(message="Group '{}' not found".format(group_id)) + raise NotFoundError("Group '{}' not found".format(group_id)) LOG.debug("delete group id {} from db".format(group_id)) db.delete_group(group_id) except Exception as exp: - LOG.exception(str(exp)) + LOG.error(str(exp)) raise return @@ -250,12 +248,12 @@ def create_group_in_db(group): manager = data_manager_factory.get_data_manager() manager.add_group(group.id, group.name, group.description, group.regions) - except error_base.ConflictError: - LOG.exception("Group {} already exists".format(group.id)) - raise error_base.ConflictError( + except ConflictError: + LOG.error("Group {} already exists".format(group.id)) + raise ConflictError( message="Group {} already exists".format(group.id)) - except error_base.InputValueError as e: - LOG.exception(str(e)) + except (NotFoundError, InputValueError) as e: + LOG.error(str(e)) raise @@ -271,16 +269,14 @@ def update_group(group, group_id): # make sure it updated groups = db_manager.get_group(group_id) - except error_base.NotFoundError: + except NotFoundError: LOG.error("Group {} not found") raise - except error_base.InputValueError: - LOG.exception("Some of the regions not found") - raise error_base.NotFoundError( - message="Some of the regions not found") + except InputValueError: + LOG.error("Regions not found") + raise except Exception as exp: LOG.error("Failed to update group {}".format(group.group_id)) - LOG.exception(str(exp)) raise return Groups(**groups) @@ -301,5 +297,5 @@ def update_region_status(region_id, new_status): return result except Exception as exp: - LOG.exception("Error updating status for region id:".format(region_id)) + LOG.error("Error updating status for region id: {}".format(region_id)) raise diff --git a/orm/services/region_manager/rms/storage/base_data_manager.py b/orm/services/region_manager/rms/storage/base_data_manager.py deleted file mode 100755 index 3b2cfd07..00000000 --- a/orm/services/region_manager/rms/storage/base_data_manager.py +++ /dev/null @@ -1,120 +0,0 @@ - - -class BaseDataManager(object): - - def __init__(self, url, - max_retries, - retry_interval): - pass - - def add_region(self, - region_id, - name, - address_state, - address_country, - address_city, - address_street, - address_zip, - region_status, - ranger_agent_version, - open_stack_version, - design_type, - location_type, - domain_name, - vlcp_name, - clli, - description, - meta_data_list, - end_point_list): - raise NotImplementedError("Please Implement this method") - - """ - def delete_region(self, - region_id): - raise NotImplementedError("Please Implement this method") - """ - - def get_regions(self, - region_filters_dict, - meta_data_dict, - end_point_dict): - raise NotImplementedError("Please Implement this method") - - def get_all_regions(self): - raise NotImplementedError("Please Implement this method") - - """ - def add_meta_data_to_region(self, - region_id, - key, - value, - description): - raise NotImplementedError("Please Implement this method") - - def remove_meta_data_from_region(self, - region_id, - key): - raise NotImplementedError("Please Implement this method") - - def add_end_point_to_region(self, - region_id, - end_point_type, - end_point_url, - description): - raise NotImplementedError("Please Implement this method") - - def remove_end_point_from_region(self, - region_id, - end_point_type): - raise NotImplementedError("Please Implement this method") - """ - - def add_group(self, - group_id, - group_name, - group_description, - region_ids_list): - raise NotImplementedError("Please Implement this method") - - """ - def delete_group(self, - group_name): - raise NotImplementedError("Please Implement this method") - """ - - def get_group(self, group_id): - raise NotImplementedError("Please Implement this method") - - def get_all_groups(self): - raise NotImplementedError("Please Implement this method") - - """ - def add_region_to_group(self, - group_id, - region_id): - raise NotImplementedError("Please Implement this method") - - def remove_region_from_group(self, - group_id, - region_id): - raise NotImplementedError("Please Implement this method") - """ - - -class SQLDBError(Exception): - pass - - -class EntityNotFound(Exception): - """if item not found in DB.""" - pass - - -class DuplicateEntryError(Exception): - """A group already exists.""" - pass - - -class InputValueError(Exception): - """ unvalid input from user""" - pass diff --git a/orm/services/region_manager/rms/storage/data_manager_factory.py b/orm/services/region_manager/rms/storage/data_manager_factory.py index 7a901c40..921e8c10 100644 --- a/orm/services/region_manager/rms/storage/data_manager_factory.py +++ b/orm/services/region_manager/rms/storage/data_manager_factory.py @@ -1,5 +1,6 @@ import logging +from orm.common.orm_common.utils.error_base import SQLDBError from orm.services.region_manager.rms.storage.my_sql.data_manager import DataManager from pecan import conf @@ -18,4 +19,4 @@ def get_data_manager(): nagios_message = "CRITICAL|CONDB001 - Could not establish " \ "database connection" LOG.error(nagios_message) - raise Exception("Could not establish database connection") + raise SQLDBError("Could not establish database connection") diff --git a/orm/services/region_manager/rms/storage/my_sql/data_manager.py b/orm/services/region_manager/rms/storage/my_sql/data_manager.py index dc5cd1d1..bd79f203 100755 --- a/orm/services/region_manager/rms/storage/my_sql/data_manager.py +++ b/orm/services/region_manager/rms/storage/my_sql/data_manager.py @@ -10,10 +10,9 @@ from orm.services.flavor_manager.fms_rest.data.sql_alchemy.db_models import ( from orm.services.image_manager.ims.persistency.sql_alchemy.db_models import ( Image, ImageRegion) +from orm.common.orm_common.utils.error_base import (ConflictError, EntityNotFound, + NotFoundError) from orm.services.region_manager.rms.model import model as PythonModels -from orm.services.region_manager.rms.services import error_base -from orm.services.region_manager.rms.storage.base_data_manager import ( - BaseDataManager, DuplicateEntryError, EntityNotFound) import oslo_db from .data_models import (Group, GroupRegion, Region, RegionEndPoint, @@ -26,7 +25,7 @@ Base = declarative_base() logger = logging.getLogger(__name__) -class DataManager(BaseDataManager): +class DataManager(object): def __init__(self, url, max_retries, retries_interval): self._engine_facade = LegacyEngineFacade(url, @@ -99,9 +98,8 @@ class DataManager(BaseDataManager): session.add(region) except oslo_db.exception.DBDuplicateEntry as e: - logger.warning("Duplicate entry: {}".format(str(e))) - raise DuplicateEntryError("Region {} already " - "exist".format(region_id)) + logger.error("Duplicate entry: {}".format(str(e))) + raise ConflictError("Region {} already exists".format(region_id)) def update_region(self, region_to_update, @@ -174,15 +172,15 @@ class DataManager(BaseDataManager): meta_data_key=k, meta_data_value=list_item)) else: - raise EntityNotFound("Region {} not found".format( + raise NotFoundError("Region {} not found".format( region_to_update)) except EntityNotFound as exp: - logger.exception( - "fail to update entity with id {} not found".format( + logger.error( + "fail to update entity with id {}, entity not found".format( region_to_update)) - raise error_base.NotFoundError(message=str(exp)) + raise except Exception as exp: - logger.exception("fail to update region {}".format(str(exp))) + logger.error("fail to update region {}".format(str(exp))) raise def query_region_resources(self, region_id): @@ -218,7 +216,7 @@ class DataManager(BaseDataManager): return resource_exist except Exception as exp: - logger.exception( + logger.error( "fail to verify if region {} has resources".format(region_id)) raise @@ -339,8 +337,8 @@ class DataManager(BaseDataManager): except oslo_db.exception.DBDuplicateEntry as e: logger.warning("Duplicate entry: {}".format(str(e))) - raise error_base.ConflictError(message="Duplicate metadata value " - "in region {}".format(region_id)) + raise ConflictError(message="Duplicate metadata value " + "in region {}".format(region_id)) def update_region_meta_data(self, region_id, metadata_dict): @@ -357,7 +355,7 @@ class DataManager(BaseDataManager): if not record: msg = "Region {} not found".format(region_id) logger.info(msg) - raise error_base.NotFoundError(message=msg) + raise NotFoundError(msg) session.query(RegionMetaData).\ filter_by(region_id=region_id).delete() @@ -381,7 +379,7 @@ class DataManager(BaseDataManager): if not record: msg = "Region {} not found".format(region_id) logger.info(msg) - raise error_base.NotFoundError(message=msg) + raise NotFoundError(msg) session.query(RegionMetaData).filter_by(region_id=region_id, meta_data_key=key).delete() @@ -397,11 +395,11 @@ class DataManager(BaseDataManager): else: msg = "Region {} not found".format(region_id) logger.info(msg) - raise error_base.NotFoundError(message=msg) + raise NotFoundError(msg) return record.region_status except Exception as exp: - logger.exception("failed to update region {}".format(str(exp))) + logger.error("failed to update region {}".format(str(exp))) raise """ def add_end_point_to_region(self, @@ -462,11 +460,10 @@ class DataManager(BaseDataManager): session.add_all(group_regions) except oslo_db.exception.DBReferenceError as e: logger.error("Reference error: {}".format(str(e))) - raise error_base.InputValueError( - message="One or more regions not found") + raise NotFoundError("One or more regions not found") except oslo_db.exception.DBDuplicateEntry as e: logger.error("Duplicate entry: {}".format(str(e))) - raise error_base.ConflictError("Duplicate entry error") + raise ConflictError("Duplicate entry error") def delete_group(self, group_id): session = self._engine_facade.get_session() @@ -508,7 +505,7 @@ class DataManager(BaseDataManager): group_record = session.query(Group).filter_by( group_id=group_id).first() if group_record is None: - raise error_base.NotFoundError( + raise NotFoundError( message="Group {} not found".format(group_id)) # only desc and regions can be changed group_record.description = group_description @@ -519,12 +516,12 @@ class DataManager(BaseDataManager): group_id=group_id)) session.add_all(regions) - except error_base.NotFoundError as exp: - logger.error(exp.message) + except NotFoundError as exp: + logger.error(str(exp)) raise except oslo_db.exception.DBReferenceError as e: logger.error("Reference error: {}".format(str(e))) - raise error_base.InputValueError("Reference error") + raise except Exception as exp: logger.error("failed to update group {}".format(group_id)) logger.exception(str(exp)) diff --git a/orm/services/resource_distributor/rds/controllers/v1/base.py b/orm/services/resource_distributor/rds/controllers/v1/base.py deleted file mode 100644 index 56637b9b..00000000 --- a/orm/services/resource_distributor/rds/controllers/v1/base.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Exceptions.""" -import wsme -from wsme import types as wtypes - - -class ClientSideError(wsme.exc.ClientSideError): - """return 400 with error message.""" - - def __init__(self, error, status_code=400): - """init function.. - - :param error: error message - :param status_code: returned code - """ - super(ClientSideError, self).__init__(error, status_code) - - -class InputValueError(ClientSideError): - """return 400 for invalid input.""" - - def __init__(self, name, value, status_code=400): - """init function. - - :param name: inavlid input field name - :param value: invalid value - :param status_code: returned code - """ - super(InputValueError, self).__init__("Invalid " - "value for input {} : " - "{}".format(name, value), - status_code) - - -class EntityNotFoundError(ClientSideError): - """return 404 entity not found.""" - - def __init__(self, id): - """init func. - - :param id: Entity id - """ - super(EntityNotFoundError, self).__init__("Entity not found " - "for {}".format(id), - status_code=404) - - -class LockedEntity(ClientSideError): - """return 409 locked.""" - - def __init__(self, msg): - """init func. - - :param name: locked message - """ - super(LockedEntity, self).__init__("Entity is " - "locked: {}".format(msg), - status_code=409) - - -class NotAllowedError(ClientSideError): - """return 405 not allowed operation.""" - - def __init__(self, name): - """init func. - - :param name: name of method - """ - super(NotAllowedError, self).__init__("not allowed : " - "{}".format(name), - status_code=405) - - -class Base(wtypes.DynamicBase): - """not implemented.""" - - pass - - ''' - @classmethod - def from_model(cls, m): - return cls(**(m.as_dict())) - - def as_dict(self, model): - valid_keys = inspect.getargspec(model.__init__)[0] - if 'self' in valid_keys: - valid_keys.remove('self') - return self.as_dict_from_keys(valid_keys) - - - def as_dict_from_keys(self, keys): - return dict((k, getattr(self, k)) - for k in keys - if hasattr(self, k) and - getattr(self, k) != wsme.Unset) - - @classmethod - def from_db_and_links(cls, m, links): - return cls(links=links, **(m.as_dict())) - - ''' diff --git a/orm/services/resource_distributor/rds/controllers/v1/resources/root.py b/orm/services/resource_distributor/rds/controllers/v1/resources/root.py index e063638d..f1d30343 100755 --- a/orm/services/resource_distributor/rds/controllers/v1/resources/root.py +++ b/orm/services/resource_distributor/rds/controllers/v1/resources/root.py @@ -4,9 +4,8 @@ import ast import logging.handlers import time -from orm.services.resource_distributor.rds.controllers.v1.base import (ClientSideError, LockedEntity, - NotAllowedError) -from orm.services.resource_distributor.rds.services.base import ConflictValue +from orm.common.orm_common.utils.error_base import (ClientSideError, ConflictError, + LockedEntity, NotAllowedError) from orm.services.resource_distributor.rds.services import resource as ResourceService import pecan @@ -196,10 +195,10 @@ class CreateNewResource(rest.RestController): created='%d' % (time.time() * 1000), links=Links(site_link))}) return res - except ConflictValue as e: + except ConflictError as e: my_logger.error("The request blocked, need to wait " "for previous operation to be done ") - raise LockedEntity(str(e)) + raise LockedEntity("Entity currently locked, wait for previous operation to complete.") except Exception as e: my_logger.error("error :- %s " % str(e)) raise ClientSideError(str(e)) @@ -219,7 +218,7 @@ class CreateNewResource(rest.RestController): """ my_logger.info("modify resource") jsondata = resource.service_template.model - my_logger.debug("parse json & get yaml file!!! {}".format(jsondata)) + my_logger.debug("parse json and get yaml file: {}".format(jsondata)) uuid = resource.service_template.tracking.tracking_id resource_type = resource.service_template.resource.resource_type base_url = pecan.request.application_url @@ -240,10 +239,10 @@ class CreateNewResource(rest.RestController): updated='%d' % (time.time() * 1000), links=Links(site_link))}) return res - except ConflictValue as e: + except ConflictError as e: my_logger.error("The request blocked, need to wait " "for previous operation to be done ") - raise LockedEntity(str(e)) + raise LockedEntity("Entity currently locked, wait for previous operation to complete.") except Exception as e: my_logger.error("error :- %s " % str(e)) raise ClientSideError(str(e)) @@ -261,14 +260,14 @@ class CreateNewResource(rest.RestController): operation = 'delete' my_logger.info("delete resource ") jsondata = resource.service_template.model - my_logger.debug("parse json & get yaml file!!! {}".format(jsondata)) + my_logger.debug("parse json and get yaml file: {}".format(jsondata)) jsondata = ast.literal_eval(jsondata) resource_uuid = resource.service_template.tracking.tracking_id resource_type = resource.service_template.resource.resource_type if resource_type not in resources_operation_list or operation not in \ resources_operation_list[resource_type]: - raise NotAllowedError("delete Not allowed for this" + raise NotAllowedError("Delete not allowed for this" " resource %s" % resource_type) try: resource_id = ResourceService.main(jsondata, @@ -276,10 +275,10 @@ class CreateNewResource(rest.RestController): resource_type, operation) return resource_id - except ConflictValue as e: + except ConflictError as e: my_logger.error("The request blocked, need to wait" - " for previous operation to be done ") - raise LockedEntity(str(e)) + " for previous operation to be done") + raise LockedEntity("Entity currently locked, wait for previous operation to complete.") except Exception as e: my_logger.error("error :- %s " % str(e)) raise ClientSideError(str(e)) diff --git a/orm/services/resource_distributor/rds/controllers/v1/status/get_resource.py b/orm/services/resource_distributor/rds/controllers/v1/status/get_resource.py index 634ae333..e3432e8e 100755 --- a/orm/services/resource_distributor/rds/controllers/v1/status/get_resource.py +++ b/orm/services/resource_distributor/rds/controllers/v1/status/get_resource.py @@ -1,7 +1,7 @@ """handle get resource module.""" import logging -from orm.services.resource_distributor.rds.controllers.v1.base import EntityNotFoundError +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.resource_distributor.rds.services import region_resource_id_status as regionResourceIdStatus from pecan import rest @@ -106,6 +106,6 @@ class GetResource(rest.RestController): if result is None or not result.regions: logger.error("no content for id %s " % id) - raise EntityNotFoundError("resourceid %s" % id) + raise NotFoundError("Resource id %s not found" % id) logger.debug("items number : %s" % len(result.status)) return result diff --git a/orm/services/resource_distributor/rds/controllers/v1/status/resource_status.py b/orm/services/resource_distributor/rds/controllers/v1/status/resource_status.py index 6828a3ce..0de055c1 100755 --- a/orm/services/resource_distributor/rds/controllers/v1/status/resource_status.py +++ b/orm/services/resource_distributor/rds/controllers/v1/status/resource_status.py @@ -2,9 +2,8 @@ import logging import time -from orm.services.resource_distributor.rds.controllers.v1.base import InputValueError +from orm.common.orm_common.utils.error_base import InputValueError from orm.services.resource_distributor.rds.controllers.v1.status import get_resource -from orm.services.resource_distributor.rds.services.base import ErrorMessage, InputError from orm.services.resource_distributor.rds.services import region_resource_id_status as regionResourceIdStatus from orm.services.resource_distributor.rds.utils import utils @@ -138,20 +137,21 @@ class Status(rest.RestController): resource_type=status_input.rds_listener.resource_type, ord_notifier_id=status_input.rds_listener.ord_notifier_id) - if status_input.rds_listener.resource_type == 'image' and status_input.rds_listener.resource_extra_metadata != wsme.Unset: + if status_input.rds_listener.resource_type == 'image' \ + and status_input.rds_listener.resource_extra_metadata != wsme.Unset: data_to_save['resource_extra_metadata'] =\ status_input.rds_listener.resource_extra_metadata.to_dict() - logger.debug("save data to database.. data :- %s" % data_to_save) + logger.debug("Saving data to database.. data :- %s" % data_to_save) try: regionResourceIdStatus.add_status(data_to_save) # invoke region data to delete on sucess utils.invoke_delete_region(data_to_save) # send data to ims utils.post_data_to_image(data_to_save) - except ErrorMessage as exp: - logger.error(exp.message) - except InputError as e: - logger.error("Invalid value for input {}: {}".format(str(e.name), - str(e.value))) - raise InputValueError(e.name, e.value) + except InputValueError as e: + logger.error(str(e)) + raise + except Exception as e: + logger.error(str(e)) + raise diff --git a/orm/services/resource_distributor/rds/proxies/rds_resource_service_proxy.py b/orm/services/resource_distributor/rds/proxies/rds_resource_service_proxy.py index e1802ec2..dace1484 100755 --- a/orm/services/resource_distributor/rds/proxies/rds_resource_service_proxy.py +++ b/orm/services/resource_distributor/rds/proxies/rds_resource_service_proxy.py @@ -3,13 +3,13 @@ import logging from pecan import conf import requests +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.data.data_manager \ import DataManager as CmsDataManager from orm.services.flavor_manager.fms_rest.data.sql_alchemy.data_manager \ import DataManager as FmsDataManager from orm.services.image_manager.ims.persistency.sql_alchemy.data_manager \ import DataManager as ImsDataManager -from orm.services.resource_distributor.rds.services.base import ErrorMessage from orm.services.resource_distributor.rds.utils import \ authentication as AuthService @@ -47,8 +47,7 @@ def invoke_resources_region_delete(resource_type, region, resource_id): except Exception as exp: logger.error(exp) - logger.exception(exp) - raise ErrorMessage( + raise ErrorStatus( "Fail to delete {} resource {}".format(resource_type, str(exp))) return @@ -73,7 +72,6 @@ def delete_customer_region(customer_id, region_id): datamanager.commit() except Exception as exp: logger.error("RDS CMS resource - Failed to delete region") - logger.exception(exp) datamanager.rollback() raise exp finally: @@ -89,7 +87,6 @@ def delete_group_region(group_uuid, region_name): datamanager.commit() except Exception as exp: logger.error("RDS Group resource - Failed to delete region") - logger.exception(exp) datamanager.rollback() raise exp finally: @@ -113,7 +110,6 @@ def delete_flavor_region(flavor_uuid, region_name): datamanager.commit() except Exception as exp: logger.error("RDS FMS resource - Failed to delete region") - logger.exception(exp) datamanager.rollback() raise exp finally: @@ -137,7 +133,6 @@ def delete_image_region(image_uuid, region_name): datamanager.commit() except Exception as exp: logger.error("RDS IMS resource - Failed to delete region") - logger.exception(exp) datamanager.rollback() raise exp finally: @@ -172,12 +167,11 @@ def send_image_metadata(meta_data, region, resource_id, action='post'): logger.debug("got response from ims {}".format(response)) except requests.ConnectionError as exp: logger.error(exp) - logger.exception(exp) - raise ErrorMessage( + raise ErrorStatus( "fail to connect to server {}".format(exp.message)) if response.status_code != 200: - raise ErrorMessage( + raise ErrorStatus( "Got error from rds server, code: {0} message: {1}".format( response.status_code, response.content)) return diff --git a/orm/services/resource_distributor/rds/services/base.py b/orm/services/resource_distributor/rds/services/base.py deleted file mode 100644 index b30daff6..00000000 --- a/orm/services/resource_distributor/rds/services/base.py +++ /dev/null @@ -1,18 +0,0 @@ -class Error(Exception): - pass - - -class InputError(Error): - def __init__(self, name, value): - self.name = name - self.value = value - - -class ErrorMessage(Error): - def __init__(self, message=None): - self.message = message - - -class ConflictValue(Error): - """block values if operation still in progress""" - pass diff --git a/orm/services/resource_distributor/rds/services/region_resource_id_status.py b/orm/services/resource_distributor/rds/services/region_resource_id_status.py index aea1eece..30dd30b1 100755 --- a/orm/services/resource_distributor/rds/services/region_resource_id_status.py +++ b/orm/services/resource_distributor/rds/services/region_resource_id_status.py @@ -1,8 +1,7 @@ import logging import sys -from orm.services.resource_distributor.rds.services.base \ - import Error, InputError +from orm.common.orm_common.utils.error_base import InputValueError from orm.services.resource_distributor.rds.storage import factory logger = logging.getLogger(__name__) @@ -86,7 +85,7 @@ def add_status(data): data['error_code'], data['resource_operation'], data.get('resource_extra_metadata')) - except Error as e: + except InputValueError: logger.exception("invalid inputs error") raise except Exception: @@ -96,7 +95,6 @@ def add_status(data): def get_status_by_resource_id(resource_id): logger.debug("get status by resource id %s " % resource_id) - conn = factory.get_region_resource_id_status_connection() result = conn.get_records_by_resource_id(resource_id) return result @@ -117,18 +115,21 @@ def validate_resource_type(resource_type): allowed_resource_type = config['allowed_resource_type'] if resource_type not in allowed_resource_type: logger.exception("status value is invalid: {}".format(resource_type)) - raise InputError("operation_type", resource_type) + message = "{} not an allowed resource type".format(resource_type) + raise InputValueError(message) def validate_operation_type(operation_type): allowed_operation_type = config['allowed_operation_type'] if operation_type not in allowed_operation_type: logger.exception("status value is invalid: {}".format(operation_type)) - raise InputError("operation_type", operation_type) + message = "{} not an allowed operation type".format(operation_type) + raise InputValueError(message) def validate_status_value(status): allowed_status_values = config['allowed_status_values'] if status not in allowed_status_values: logger.exception("status value is invalid: {}".format(status)) - raise InputError("status", status) + message = "{} not an allowed status value".format(status) + raise InputValueError(message) diff --git a/orm/services/resource_distributor/rds/services/resource.py b/orm/services/resource_distributor/rds/services/resource.py index 75baa688..3afd6256 100755 --- a/orm/services/resource_distributor/rds/services/resource.py +++ b/orm/services/resource_distributor/rds/services/resource.py @@ -3,6 +3,7 @@ import logging import threading import time +from orm.common.orm_common.utils.error_base import ConflictError, ErrorStatus from orm.services.flavor_manager.fms_rest.data.sql_alchemy.data_manager \ import DataManager from orm.services.resource_distributor.rds.ordupdate.ord_notifier \ @@ -12,13 +13,10 @@ from orm.services.resource_distributor.rds.services \ from orm.services.resource_distributor.rds.services \ import (yaml_customer_builder, yaml_flavor_builder, yaml_group_builder, yaml_image_builder) -from orm.services.resource_distributor.rds.services.base \ - import ConflictValue, ErrorMessage from orm.services.resource_distributor.rds.services.model.resource_input \ import ResourceData as InputData from orm.services.resource_distributor.rds.utils import utils, uuid_utils - from pecan import conf, request my_logger = logging.getLogger(__name__) @@ -43,7 +41,7 @@ def _get_inputs_from_resource_type(jsondata, model=jsondata, external_transaction_id=external_transaction_id) else: - raise ErrorMessage("no support for resource %s" % resource_type) + raise ErrorStatus("no support for resource %s" % resource_type) return input_data @@ -61,8 +59,8 @@ def _create_or_update_resource_status(input_data, target, error_msg='', status = 'Error' error_msg = "Not sent to ord as status equal to " + \ target['rms_status'] - raise ErrorMessage("Not sent to ord as status equal to %s" - % target['rms_status']) + raise ErrorStatus("Not sent to ord as status equal to %s" + % target['rms_status']) my_logger.debug("save status as %s" % status) data_to_save = dict( @@ -201,8 +199,7 @@ def send_data_to_ord(tracking_id, transaction_id, resource_list, resource["region_id"])) except Exception as e: my_logger.error("Error in updating ORD! Error: {}".format( - str(e) - )) + str(e))) def _save_resource_to_ord(tracking_id, transaction_id, @@ -255,7 +252,7 @@ def _check_resource_status(input_data): regions_in_error = [reg.region for reg in regions_by_resource.regions] msg = "Previous operation still in %s state for regions: %s " % ( status, regions_in_error) - raise ConflictValue(msg) + raise ConflictError(msg) def _generate_resource_data(input_data): @@ -291,15 +288,13 @@ def main(jsondata, external_transaction_id, resource_type, operation): input_data.targets = utils.add_rms_status_to_regions( input_data.targets, input_data.resource_type) _generate_resource_data(input_data) - except ConflictValue: + except ConflictError: raise - except ErrorMessage as exp: + except ErrorStatus as exp: my_logger.error(str(exp)) - my_logger.exception(str(exp)) raise except Exception as e: - my_logger.exception(str(e)) _set_all_statuses_to_error(input_data) - my_logger.error("deleting fails ,Error : {}".format(str(e))) - raise ErrorMessage(str(e)) + my_logger.error("deleting failed, Error: {}".format(str(e))) + raise return input_data.resource_id diff --git a/orm/services/resource_distributor/rds/utils/utils.py b/orm/services/resource_distributor/rds/utils/utils.py index f334c6c2..0943af50 100755 --- a/orm/services/resource_distributor/rds/utils/utils.py +++ b/orm/services/resource_distributor/rds/utils/utils.py @@ -3,10 +3,9 @@ import logging import re import requests +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.resource_distributor.rds.proxies import \ rds_resource_service_proxy -from orm.services.resource_distributor.rds.services.base \ - import ErrorMessage from orm.services.resource_distributor.rds.services import \ region_resource_id_status as regionResourceIdStatus @@ -56,9 +55,9 @@ def _get_all_rms_regions(): headers=headers, verify=conf.verify) if response.status_code != 200: # fail to get regions - error = "got bad response from rms {}".format(response) + error = "Received bad response from RMS: {}".format(response) logger.error(error) - raise ErrorMessage(message="got bad response from rms ") + raise ErrorStatus(error) return response.json() @@ -94,7 +93,7 @@ def add_rms_status_to_regions(resource_regions, resource_type): region['rangerAgentVersion'] = _validate_version(rms_regions[region['name']], supported_resource_version) if not region['rangerAgentVersion']: - raise ErrorMessage( + raise ErrorStatus( message="ranger agent version for region {} must be >={} ".format( region['name'], supported_resource_version[0] if supported_resource_version else '0')) diff --git a/orm/tests/unit/audit_server/controllers/v1/test_base.py b/orm/tests/unit/audit_server/controllers/v1/test_base.py deleted file mode 100644 index 813353b3..00000000 --- a/orm/tests/unit/audit_server/controllers/v1/test_base.py +++ /dev/null @@ -1,39 +0,0 @@ -"""test_base module.""" - - -import unittest - -from orm.services.audit_trail_manager.audit_server.controllers.v1.base import (ClientSideError, - EntityNotFoundError, - InputValueError) - - -class Test(unittest.TestCase): - """test case class.""" - - def test_init_ClientSideError(self): - """test the init method.""" - expected_msg = "This is an error" - expected_code = 400 - error = ClientSideError(expected_msg) - self.assertEqual(error.msg, expected_msg) - self.assertEqual(error.code, expected_code) - - def test_init_InputValueError(self): - """test the init method.""" - name = "name1" - value = "value1" - expected_msg = "Invalid value for input {} : {}".format(name, value) - expected_code = 400 - error = InputValueError(name, value) - self.assertEqual(error.msg, expected_msg) - self.assertEqual(error.code, expected_code) - - def test_init_EntityNotFoundError(self): - """test the init method.""" - id = "id1" - expected_msg = "Entity not found for {}".format(id) - expected_code = 404 - error = EntityNotFoundError(id) - self.assertEqual(error.msg, expected_msg) - self.assertEqual(error.code, expected_code) diff --git a/orm/tests/unit/audit_server/services/test_base.py b/orm/tests/unit/audit_server/services/test_base.py deleted file mode 100644 index 85a377e8..00000000 --- a/orm/tests/unit/audit_server/services/test_base.py +++ /dev/null @@ -1,15 +0,0 @@ -"""test_base module.""" - - -import unittest - -from orm.services.audit_trail_manager.audit_server.services.base import Error - - -class Test(unittest.TestCase): - """test base class.""" - - def test_init_Error(self): - """Test that init of Error succeeded.""" - Error("test") - pass diff --git a/orm/tests/unit/audit_server/storage/test_transaction.py b/orm/tests/unit/audit_server/storage/test_transaction.py deleted file mode 100644 index 8d13b271..00000000 --- a/orm/tests/unit/audit_server/storage/test_transaction.py +++ /dev/null @@ -1,22 +0,0 @@ -"""test_transaction module.""" - - -import unittest - -from orm.services.audit_trail_manager.audit_server.storage.transaction import Base - - -class Test(unittest.TestCase): - """test transaction class.""" - - def test_add_record(self): - """test that add_record throws an NotImplementedError exception.""" - baseConn = Base("test_url") - self.assertRaises(NotImplementedError, baseConn.add_record, - transaction=None) - - def test_get_latest_record(self): - """test that add_record throws an NotImplementedError exception.""" - baseConn = Base("test_url") - self.assertRaises(NotImplementedError, baseConn.get_records, - query=None) diff --git a/orm/tests/unit/cms/config.py b/orm/tests/unit/cms/config.py index ff005eda..006e0dba 100755 --- a/orm/tests/unit/cms/config.py +++ b/orm/tests/unit/cms/config.py @@ -102,12 +102,9 @@ api_options = { cms_mode = None if not ('CMS_ENV' in os.environ) or not (os.environ['CMS_ENV'] in api_options): - print('!!! NO ENVIRONMENT VARIABLE CMS_ENV SPECIFIED OR NO ENV VARIABLE ' - 'WITH THIS NAME AVAILABLE, RUNNING WITH DEFAULT ') cms_mode = 'dev' else: cms_mode = os.environ['CMS_ENV'] - print(('Environment variable found, running under <{0}> environment'.format(cms_mode))) api = api_options[cms_mode] diff --git a/orm/tests/unit/cms/test_customer.py b/orm/tests/unit/cms/test_customer.py index 1546dcd0..0b817432 100755 --- a/orm/tests/unit/cms/test_customer.py +++ b/orm/tests/unit/cms/test_customer.py @@ -1,8 +1,8 @@ import requests import sqlalchemy +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer import root -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model import Models from orm.tests.unit.cms import FunctionalTest, test_utils from unittest import mock diff --git a/orm/tests/unit/cms/test_customer_logic.py b/orm/tests/unit/cms/test_customer_logic.py index 72ec6791..ee76dc24 100755 --- a/orm/tests/unit/cms/test_customer_logic.py +++ b/orm/tests/unit/cms/test_customer_logic.py @@ -1,6 +1,6 @@ +from orm.common.orm_common.utils.error_base import ErrorStatus, NotFoundError, NotAllowedError from orm.services.customer_manager.cms_rest.data.sql_alchemy import models as sql_models from orm.services.customer_manager.cms_rest.logic import customer_logic -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus import orm.services.customer_manager.cms_rest.model.Models as models from orm.tests.unit.cms import FunctionalTest @@ -127,7 +127,7 @@ class TestCustomerLogic(FunctionalTest): customer.name = '' logic = customer_logic.CustomerLogic() - self.assertRaises(customer_logic.ErrorStatus, + self.assertRaises(NotAllowedError, logic.create_customer, customer, 'some_uuid', 'some_trans_id') @@ -231,7 +231,7 @@ class TestCustomerLogic(FunctionalTest): global rowcount rowcount = 0 logic = customer_logic.CustomerLogic() - with self.assertRaises(customer_logic.ErrorStatus): + with self.assertRaises(NotAllowedError): logic.delete_users('customer_id', 'region_id', 'user_id', 'transaction_is') rowcount = 1 @@ -320,7 +320,7 @@ class TestCustomerLogic(FunctionalTest): global rowcount rowcount = 0 logic = customer_logic.CustomerLogic() - with self.assertRaises(customer_logic.NotFound): + with self.assertRaises(customer_logic.NotFoundError): logic.delete_default_users('customer_id', 'user_id', 'transaction_is') rowcount = 1 @@ -420,7 +420,7 @@ class TestCustomerLogic(FunctionalTest): logic = customer_logic.CustomerLogic() # test that ErrorStatus exception is raised when no customer found - with self.assertRaises(customer_logic.ErrorStatus): + with self.assertRaises(NotFoundError): logic.delete_customer_by_uuid('customer_id') def test_delete_customer_by_uuid_errors(self): @@ -436,7 +436,7 @@ class TestCustomerLogic(FunctionalTest): customer_logic.utils.get_resource_status_from_db.return_value = \ {'1337': StatusModel(status='Error')} - self.assertRaises(customer_logic.ErrorStatus, + self.assertRaises(ErrorStatus, logic.delete_customer_by_uuid, 'customer_id') @@ -446,7 +446,7 @@ class TestCustomerLogic(FunctionalTest): global flow_type flow_type = 2 logic = customer_logic.CustomerLogic() - self.assertRaises(customer_logic.ErrorStatus, logic.delete_customer_by_uuid, + self.assertRaises(NotAllowedError, logic.delete_customer_by_uuid, 'customer_id') def test_enable_success(self): @@ -475,7 +475,7 @@ class TestCustomerLogic(FunctionalTest): flow_type = 1 logic = customer_logic.CustomerLogic() - self.assertRaises(ErrorStatus, logic.get_customer, 'id') + self.assertRaises(NotFoundError, logic.get_customer, 'id') def get_mock_datamanager(): diff --git a/orm/tests/unit/cms/test_enable.py b/orm/tests/unit/cms/test_enable.py index bef738b6..4e72c1c5 100755 --- a/orm/tests/unit/cms/test_enable.py +++ b/orm/tests/unit/cms/test_enable.py @@ -1,8 +1,8 @@ import mock import requests +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer import enabled -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model import Models from orm.tests.unit.cms import FunctionalTest diff --git a/orm/tests/unit/cms/test_metadata.py b/orm/tests/unit/cms/test_metadata.py index 2b801753..b713e684 100755 --- a/orm/tests/unit/cms/test_metadata.py +++ b/orm/tests/unit/cms/test_metadata.py @@ -1,8 +1,8 @@ import mock import requests +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer import metadata -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model import Models from orm.tests.unit.cms import FunctionalTest diff --git a/orm/tests/unit/cms/test_rds_proxy.py b/orm/tests/unit/cms/test_rds_proxy.py index 4c100a5e..ae8eafba 100755 --- a/orm/tests/unit/cms/test_rds_proxy.py +++ b/orm/tests/unit/cms/test_rds_proxy.py @@ -1,8 +1,7 @@ import mock -from testfixtures import log_capture +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.data.sql_alchemy import models -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest import rds_proxy from orm.tests.unit.cms import FunctionalTest @@ -21,33 +20,24 @@ class TestUtil(FunctionalTest): FunctionalTest.setUp(self) self.rp = rds_proxy.RdsProxy() - @log_capture('orm.services.customer_manager.cms_rest.rds_proxy') @mock.patch.object(rds_proxy, 'request') @mock.patch('requests.post') - def testsend_good(self, mock_post, mock_request, l): + def testsend_good(self, mock_post, mock_request): resp = Response(200, 'my content') mock_post.return_value = resp - # send_res = self.rp.send_customer(models.Customer(), "1234", "POST") - # self.assertRegexpMatches(l.records[-3].getMessage(), 'Wrapper JSON before sending action') - # self.assertRegexpMatches(l.records[-1].getMessage(), 'Response Content from rds server') - # self.assertEqual(send_res, 'my content') + send_res = self.rp.send_customer(models.Customer(), "1234", "POST") + self.assertEqual(send_res, 'my content') - @log_capture('orm.services.customer_manager.cms_rest.rds_proxy') @mock.patch.object(rds_proxy, 'request') @mock.patch('requests.post') - def test_bad_status(self, mock_post, mock_request, l): + def test_bad_status(self, mock_post, mock_request): resp = Response(400, 'my content') mock_post.return_value = resp self.assertRaises(ErrorStatus, self.rp.send_customer, models.Customer(), "1234", "POST") - # self.assertRegexpMatches(l.records[-3].getMessage(), 'Wrapper JSON before sending action') - # self.assertRegexpMatches(l.records[-1].getMessage(), 'Response Content from rds server') - @log_capture('orm.services.customer_manager.cms_rest.rds_proxy') @mock.patch.object(rds_proxy, 'request') @mock.patch('requests.post') - def test_no_content(self, mock_post, mock_request, l): + def test_no_content(self, mock_post, mock_request): resp = Response(200, None) mock_post.return_value = resp self.assertRaises(ErrorStatus, self.rp.send_customer, models.Customer(), "1234", "POST") - for r in l.records: - self.assertNotRegexpMatches(r.getMessage(), 'Response Content from rds server') diff --git a/orm/tests/unit/cms/test_regions.py b/orm/tests/unit/cms/test_regions.py index c097f0e3..32f82a7e 100755 --- a/orm/tests/unit/cms/test_regions.py +++ b/orm/tests/unit/cms/test_regions.py @@ -3,8 +3,8 @@ import requests from wsme.exc import ClientSideError +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer import regions -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model import Models from orm.tests.unit.cms import FunctionalTest diff --git a/orm/tests/unit/cms/test_users.py b/orm/tests/unit/cms/test_users.py index 54166c2e..20146c24 100755 --- a/orm/tests/unit/cms/test_users.py +++ b/orm/tests/unit/cms/test_users.py @@ -2,8 +2,8 @@ import mock import requests from wsme.exc import ClientSideError +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.controllers.v1.orm.customer import users -from orm.services.customer_manager.cms_rest.logic.error_base import ErrorStatus from orm.services.customer_manager.cms_rest.model import Models from orm.tests.unit.cms import FunctionalTest diff --git a/orm/tests/unit/common/test_api_error_utils.py b/orm/tests/unit/common/test_api_error_utils.py index e76c7c3a..5c11f3df 100755 --- a/orm/tests/unit/common/test_api_error_utils.py +++ b/orm/tests/unit/common/test_api_error_utils.py @@ -1,4 +1,3 @@ -import json from unittest import TestCase import mock @@ -9,7 +8,5 @@ class TestCrossApiUtil(TestCase): @mock.patch.object(api_error_utils.utils, 'get_time_human', return_value=1.337) def test_get_error_default_message(self, mock_time): self.assertEqual( - json.loads(str(api_error_utils.get_error('test', 'a'))), - {"details": "a", "message": "Incompatible JSON body", - "created": "1.337", "code": 400, "type": "Bad Request", - "transaction_id": "test"}) + str(api_error_utils.get_error('test', 'a')), + "Incompatible JSON body") diff --git a/orm/tests/unit/common/test_tokens.py b/orm/tests/unit/common/test_tokens.py index 024c343d..2016ba74 100755 --- a/orm/tests/unit/common/test_tokens.py +++ b/orm/tests/unit/common/test_tokens.py @@ -1,10 +1,9 @@ """keystone_utils token validator unittests.""" +import mock import unittest from orm.common.client.keystone.keystone_utils import tokens -from orm.common.client.keystone.mock_keystone.keystoneclient import exceptions - -import mock +from orm.common.orm_common.utils import error_base class MyResponse(object): @@ -18,10 +17,10 @@ class MyResponse(object): class MyKeystone(object): def validate(self, a): - raise exceptions.NotFound('test') + raise error_base.NotFoundError('test') def find(self, **kwargs): - raise exceptions.NotFound('test') + raise error_base.NotFoundError('test') class MyClient(object): @@ -71,7 +70,7 @@ class TokensTest(unittest.TestCase): # @mock.patch.object(tokens, '_get_keystone_client') # def test_get_token_user_token_not_found(self, mock_get_keystone_client): # ks = mock.MagicMock() - # ks.tokens.validate.side_effect = exceptions.NotFound() + # ks.tokens.validate.side_effect = error_base.NotFoundError() # mock_get_keystone_client.return_value = ks # conf = tokens.TokenConf(*('3',) * 7) # self.assertIsNone(tokens.get_token_user('a', conf, 'c', 'd')) diff --git a/orm/tests/unit/fms/test_flavor_logic.py b/orm/tests/unit/fms/test_flavor_logic.py index 40458753..e99c3d82 100755 --- a/orm/tests/unit/fms/test_flavor_logic.py +++ b/orm/tests/unit/fms/test_flavor_logic.py @@ -1,11 +1,12 @@ from orm.common.orm_common.injector import injector from orm.common.orm_common.utils import utils +from orm.common.orm_common.utils.error_base import \ + ConflictError, ErrorStatus, NotAllowedError, NotFoundError from orm.services.flavor_manager.fms_rest.data.sql_alchemy import db_models from orm.services.flavor_manager.fms_rest.data.wsme import models from orm.services.flavor_manager.fms_rest.data.wsme.models import ( ExtraSpecsWrapper, Flavor, FlavorWrapper, Region, RegionWrapper, TagsWrapper, TenantWrapper) -from orm.services.flavor_manager.fms_rest.logic.error_base import NotFoundError from orm.services.flavor_manager.fms_rest.logic import flavor_logic from orm.tests.unit.fms import FunctionalTest @@ -54,8 +55,8 @@ class TestFlavorLogic(FunctionalTest): ('rds_proxy', get_rds_proxy_mock())) flavor = get_flavor_mock() flavor.flavor.validate_model = MagicMock( - side_effect=flavor_logic.ErrorStatus(400, 'Invalid model')) - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.create_flavor, + side_effect=ErrorStatus(400, 'Invalid model')) + self.assertRaises(ErrorStatus, flavor_logic.create_flavor, flavor, 'uuid', 'transaction') @patch.object(utils, 'delete_uuid') @@ -84,7 +85,7 @@ class TestFlavorLogic(FunctionalTest): # Test that flavor validate model works by passing bad swap value flavor = get_flavor_mock() flavor.flavor.swap = '1024000' - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.create_flavor, + self.assertRaises(ErrorStatus, flavor_logic.create_flavor, flavor, 'uuid', 'transaction') # Flavor is private - test success @@ -123,7 +124,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('flavor_logic', get_datamanager_mock())) - with self.assertRaises(flavor_logic.NotFoundError): + with self.assertRaises(NotFoundError): flavor_logic.get_extra_specs_uuid(123, "transaction_id") @patch.object(flavor_logic, 'ExtraSpecsWrapper', return_value=MagicMock()) @@ -147,7 +148,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('flavor_logic', get_datamanager_mock())) - with self.assertRaises(flavor_logic.NotFoundError): + with self.assertRaises(NotFoundError): flavor_logic.delete_extra_specs(123, "transaction_id") @patch.object(flavor_logic, 'FlavorWrapper', return_value=MagicMock()) @@ -158,7 +159,7 @@ class TestFlavorLogic(FunctionalTest): get_extra_spec_needed = MagicMock() get_extra_spec_needed.get_extra_spec_needed.return_value = [extra_spec_needed] mock_flavorwrapper.from_db_model.return_value = get_extra_spec_needed - with self.assertRaises(flavor_logic.ErrorStatus): + with self.assertRaises(ErrorStatus): flavor_logic.delete_extra_specs(123, "transaction_id", "key1") @patch.object(flavor_logic, 'FlavorWrapper', return_value=MagicMock()) @@ -192,7 +193,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('flavor_logic', get_datamanager_mock())) - with self.assertRaises(flavor_logic.NotFoundError): + with self.assertRaises(NotFoundError): flavor_logic.add_extra_specs(123, OES(), "transaction_id") def test_add_extra_specs_gen_exp(self): @@ -221,7 +222,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('flavor_logic', get_datamanager_mock())) - with self.assertRaises(flavor_logic.NotFoundError): + with self.assertRaises(NotFoundError): flavor_logic.update_extra_specs(123, OES(), "transaction_id") @patch.object(flavor_logic, 'FlavorWrapper', return_value=MagicMock()) @@ -281,7 +282,7 @@ class TestFlavorLogic(FunctionalTest): injector.override_injected_dependency(('data_manager', get_datamanager_mock)) - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.get_tags, + self.assertRaises(NotFoundError, flavor_logic.get_tags, 'some_id') def test_get_tags_error(self): @@ -332,12 +333,12 @@ class TestFlavorLogic(FunctionalTest): flavor_logic.delete_tags('some_id', None, 'trans_id') error = 7 - self.assertRaises(flavor_logic.NotFoundError, flavor_logic.delete_tags, + self.assertRaises(NotFoundError, flavor_logic.delete_tags, 'some_id', None, 'trans_id') error = 8 # assertRaise ErrorStatus on delete_tags when tag not found - with self.assertRaises(flavor_logic.ErrorStatus): + with self.assertRaises(ErrorStatus): flavor_logic.delete_tags('some_id', None, 'trans_id') def test_delete_tags_error(self): @@ -348,7 +349,7 @@ class TestFlavorLogic(FunctionalTest): self.assertRaises(Exception, flavor_logic.delete_tags, 'a', None, 'a') error = 9 - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.delete_tags, + self.assertRaises(ErrorStatus, flavor_logic.delete_tags, 'a', None, 'a') @patch.object(utils, 'delete_uuid') @@ -392,7 +393,7 @@ class TestFlavorLogic(FunctionalTest): try: flavor_logic.delete_flavor_by_uuid('some_uuid') self.fail('ErrorStatus not raised!') - except flavor_logic.ErrorStatus as e: + except ErrorStatus as e: self.assertEqual(e.status_code, 409) def test_delete_flavor_by_uuid_flavor_not_found(self): @@ -402,7 +403,7 @@ class TestFlavorLogic(FunctionalTest): ('data_manager', get_datamanager_mock)) # assertRaises NotFoundError when deleting a flavor that doesn't exist - with self.assertRaises(flavor_logic.ErrorStatus): + with self.assertRaises(NotFoundError): flavor_logic.delete_flavor_by_uuid('some_id') def test_delete_flavor_by_uuid_flavor_has_regions(self): @@ -414,7 +415,7 @@ class TestFlavorLogic(FunctionalTest): try: flavor_logic.delete_flavor_by_uuid('some_id') self.fail('ErrorStatus not raised!') - except flavor_logic.ErrorStatus as e: + except NotAllowedError as e: self.assertEqual(e.status_code, 405) @patch.object(flavor_logic, 'send_to_rds_if_needed') @@ -441,7 +442,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency(('data_manager', get_datamanager_mock)) - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.add_regions, + self.assertRaises(NotFoundError, flavor_logic.add_regions, 'uuid', RegionWrapper([Region(name='test_region')]), 'transaction') @@ -455,7 +456,7 @@ class TestFlavorLogic(FunctionalTest): 'transaction') mock_strin.side_effect = exc.FlushError( 'conflicts with persistent instance') - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.add_regions, + self.assertRaises(ConflictError, flavor_logic.add_regions, 'uuid', RegionWrapper([Region(name='test_region')]), 'transaction') mock_strin.side_effect = ValueError() @@ -464,14 +465,14 @@ class TestFlavorLogic(FunctionalTest): 'transaction') mock_strin.side_effect = ValueError( 'conflicts with persistent instance') - self.assertRaises(flavor_logic.ConflictError, flavor_logic.add_regions, + self.assertRaises(ConflictError, flavor_logic.add_regions, 'uuid', RegionWrapper([Region(name='test_region')]), 'transaction') - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.add_regions, + self.assertRaises(ErrorStatus, flavor_logic.add_regions, 'uuid', RegionWrapper([Region(name='')]), 'transaction') - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.add_regions, + self.assertRaises(ErrorStatus, flavor_logic.add_regions, 'uuid', RegionWrapper([Region(name='test_region', type='group')]), 'transaction') @@ -500,7 +501,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('data_manager', get_datamanager_mock)) - self.assertRaises(flavor_logic.ErrorStatus, flavor_logic.delete_region, + self.assertRaises(NotFoundError, flavor_logic.delete_region, 'uuid', 'test_region', 'transaction', False) error = 2 @@ -543,14 +544,14 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('data_manager', get_datamanager_mock)) - self.assertRaises(flavor_logic.ErrorStatus, + self.assertRaises(NotFoundError, flavor_logic.add_tenants, 'uuid', TenantWrapper(tenants), 'transaction') # Flavor is public error = 5 - self.assertRaises(flavor_logic.ErrorStatus, + self.assertRaises(NotAllowedError, flavor_logic.add_tenants, 'uuid', TenantWrapper(tenants), 'transaction') @@ -566,7 +567,7 @@ class TestFlavorLogic(FunctionalTest): mock_val.return_value = ['test_tenant'], ['test_region'] mock_strin.side_effect = exc.FlushError( 'conflicts with persistent instance') - self.assertRaises(flavor_logic.ConflictError, + self.assertRaises(ConflictError, flavor_logic.add_tenants, 'uuid', TenantWrapper(tenants), 'transaction') @@ -599,7 +600,7 @@ class TestFlavorLogic(FunctionalTest): error = 1 injector.override_injected_dependency( ('data_manager', get_datamanager_mock)) - self.assertRaises(flavor_logic.ErrorStatus, + self.assertRaises(NotFoundError, flavor_logic.delete_tenant, 'uuid', 'tenant_id', 'transaction') @@ -643,7 +644,7 @@ class TestFlavorLogic(FunctionalTest): error = 31 injector.override_injected_dependency( ('rds_proxy', get_rds_proxy_mock())) - self.assertRaises(flavor_logic.ConflictError, + self.assertRaises(ConflictError, flavor_logic.add_extra_specs, 'uuid', extra_specs, 'transaction') @@ -694,12 +695,12 @@ def get_datamanager_mock(): elif error == 6: record.get_flavor_by_id.return_value = FLAVOR_MOCK elif error == 7: - record.get_flavor_by_id.side_effect = flavor_logic.NotFoundError() + record.get_flavor_by_id.side_effect = NotFoundError() elif error == 8: - record.get_flavor_by_id.side_effect = flavor_logic.ErrorStatus( + record.get_flavor_by_id.side_effect = ErrorStatus( 404) elif error == 9: - record.get_flavor_by_id.side_effect = flavor_logic.ErrorStatus( + record.get_flavor_by_id.side_effect = ErrorStatus( 500) elif error == 10: record.get_flavor_by_id.return_value = db_models.Flavor( diff --git a/orm/tests/unit/fms/test_flavors.py b/orm/tests/unit/fms/test_flavors.py index 92ced40a..30069c9f 100755 --- a/orm/tests/unit/fms/test_flavors.py +++ b/orm/tests/unit/fms/test_flavors.py @@ -2,9 +2,9 @@ import copy import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors import flavors from orm.services.flavor_manager.fms_rest.data.wsme import models -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.tests.unit.fms import FunctionalTest from orm.tests.unit.fms import test_utils diff --git a/orm/tests/unit/fms/test_os_extra_specs.py b/orm/tests/unit/fms/test_os_extra_specs.py index 578895ab..f16efc94 100755 --- a/orm/tests/unit/fms/test_os_extra_specs.py +++ b/orm/tests/unit/fms/test_os_extra_specs.py @@ -1,6 +1,6 @@ +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors import os_extra_specs as es from orm.services.flavor_manager.fms_rest.data.wsme import models -from orm.services.flavor_manager.fms_rest.logic.error_base import NotFoundError from orm.tests.unit.fms import FunctionalTest from mock import MagicMock, patch @@ -43,8 +43,9 @@ class TestOsExtraSpecsController(FunctionalTest): def test_create_os_flavor_specs_flavor_not_found(self, mock_di): flavor_mock, utils_mock = \ get_utils_flavor_logic_mock(flavor_extra_specs_json) - flavor_mock.add_extra_specs.side_effect = NotFoundError(404, - "not found") + flavor_mock.add_extra_specs.side_effect = NotFoundError( + "not found", + 404) mock_di.resolver.unpack.return_value = flavor_mock, utils_mock response = self.app.post_json('/v1/orm/flavors/123/os_extra_specs', flavor_extra_specs_json, @@ -90,8 +91,9 @@ class TestOsExtraSpecsController(FunctionalTest): def test_update_os_flavor_specs_flavor_not_found(self, mock_di): flavor_mock, utils_mock = \ get_utils_flavor_logic_mock(flavor_extra_specs_json) - flavor_mock.update_extra_specs.side_effect = NotFoundError(404, - "not found") + flavor_mock.update_extra_specs.side_effect = NotFoundError( + "not found", + 404) mock_di.resolver.unpack.return_value = flavor_mock, utils_mock response = self.app.put_json('/v1/orm/flavors/123/os_extra_specs', flavor_extra_specs_json, @@ -107,8 +109,9 @@ class TestOsExtraSpecsController(FunctionalTest): def test_get_os_flavor_specs_flavor_not_found(self, mock_di): flavor_mock, utils_mock = \ get_utils_flavor_logic_mock(flavor_extra_specs_json) - flavor_mock.get_extra_specs_uuid.side_effect = NotFoundError(404, - "not found") + flavor_mock.get_extra_specs_uuid.side_effect = NotFoundError( + "not found", + 404) mock_di.resolver.unpack.return_value = flavor_mock, utils_mock response = self.app.get('/v1/orm/flavors/123/os_extra_specs', expect_errors=True) @@ -159,8 +162,9 @@ class TestOsExtraSpecsController(FunctionalTest): def test_delete_os_flavor_specs_flavor_not_found(self, mock_di): flavor_mock, utils_mock = \ get_utils_flavor_logic_mock(flavor_extra_specs_json) - flavor_mock.delete_extra_specs.side_effect = NotFoundError(404, - "not found") + flavor_mock.delete_extra_specs.side_effect = NotFoundError( + "not found", + 404) mock_di.resolver.unpack.return_value = flavor_mock, utils_mock response = self.app.delete('/v1/orm/flavors/123/os_extra_specs', expect_errors=True) diff --git a/orm/tests/unit/fms/test_regions.py b/orm/tests/unit/fms/test_regions.py index e1efdd0a..268c1ad0 100755 --- a/orm/tests/unit/fms/test_regions.py +++ b/orm/tests/unit/fms/test_regions.py @@ -1,9 +1,9 @@ import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.controllers.v1.orm.flavors import regions from orm.services.flavor_manager.fms_rest.data.wsme import models -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.tests.unit.fms import FunctionalTest from orm.tests.unit.fms import test_utils diff --git a/orm/tests/unit/fms/test_tags.py b/orm/tests/unit/fms/test_tags.py index dad07245..ff409c9c 100644 --- a/orm/tests/unit/fms/test_tags.py +++ b/orm/tests/unit/fms/test_tags.py @@ -1,8 +1,8 @@ import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.wsme import models -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.tests.unit.fms import FunctionalTest from mock import MagicMock @@ -37,7 +37,7 @@ class TestTagsController(FunctionalTest): response = self.app.post_json('/v1/orm/flavors/test/tags', FLAVOR_JSON) # assert - self.assertEqual(response.status_int, 201) + self.assertEqual(response.status_code, 201) def test_create_tags_exception_raised(self): # given @@ -53,7 +53,7 @@ class TestTagsController(FunctionalTest): expect_errors=True) # assert - self.assertEqual(response.status_int, 500) + self.assertEqual(response.status_code, 500) # assert utils_mock.audit_trail.called def test_create_tags_errorstatus_raised(self): @@ -70,7 +70,7 @@ class TestTagsController(FunctionalTest): expect_errors=True) # assert - # self.assertEqual(response.status_int, 404) + self.assertEqual(response.status_code, 404) # assert utils_mock.audit_trail.called def test_update_tags_success(self): @@ -153,7 +153,7 @@ class TestTagsController(FunctionalTest): expect_errors=True) # assert - self.assertEqual(response.status_int, 500) + self.assertEqual(response.status_code, 500) # assert utils_mock.audit_trail.called def test_delete_tags_error_raised(self): @@ -169,7 +169,7 @@ class TestTagsController(FunctionalTest): response = self.app.delete('/v1/orm/flavors/test/tags', expect_errors=True) # assert - self.assertEqual(response.status_int, 500) + self.assertEqual(response.status_code, 500) def test_get_tags_success(self): # given diff --git a/orm/tests/unit/fms/test_tenants.py b/orm/tests/unit/fms/test_tenants.py index eb455d92..22357be5 100755 --- a/orm/tests/unit/fms/test_tenants.py +++ b/orm/tests/unit/fms/test_tenants.py @@ -1,8 +1,8 @@ import requests from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.flavor_manager.fms_rest.data.wsme import models -from orm.services.flavor_manager.fms_rest.logic.error_base import ErrorStatus from orm.tests.unit.fms import FunctionalTest from mock import MagicMock diff --git a/orm/tests/unit/ims/controllers/v1/orm/images/test_customers.py b/orm/tests/unit/ims/controllers/v1/orm/images/test_customers.py index d2c3a327..411416c7 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/images/test_customers.py +++ b/orm/tests/unit/ims/controllers/v1/orm/images/test_customers.py @@ -1,8 +1,8 @@ import json from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images import customers -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import ImageWrapper from orm.tests.unit.ims import FunctionalTest diff --git a/orm/tests/unit/ims/controllers/v1/orm/images/test_enabled.py b/orm/tests/unit/ims/controllers/v1/orm/images/test_enabled.py index 19c26ff7..0c13ed30 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/images/test_enabled.py +++ b/orm/tests/unit/ims/controllers/v1/orm/images/test_enabled.py @@ -1,8 +1,8 @@ import json from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images import enabled -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import ImageWrapper from orm.tests.unit.ims import FunctionalTest diff --git a/orm/tests/unit/ims/controllers/v1/orm/images/test_images.py b/orm/tests/unit/ims/controllers/v1/orm/images/test_images.py index 6af0425a..1e5ac765 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/images/test_images.py +++ b/orm/tests/unit/ims/controllers/v1/orm/images/test_images.py @@ -2,8 +2,8 @@ import json from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images import images -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import ImageSummaryResponse, ImageWrapper from orm.tests.unit.ims import FunctionalTest diff --git a/orm/tests/unit/ims/controllers/v1/orm/images/test_metadata.py b/orm/tests/unit/ims/controllers/v1/orm/images/test_metadata.py index fcad159e..2cb5a008 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/images/test_metadata.py +++ b/orm/tests/unit/ims/controllers/v1/orm/images/test_metadata.py @@ -1,10 +1,8 @@ -import json - +from orm.common.orm_common.utils.error_base import ClientSideError, NotFoundError from orm.services.image_manager.ims.controllers.v1.orm.images import metadata from orm.tests.unit.ims import FunctionalTest import mock -from wsme.exc import ClientSideError metadata_input = { "metadata": { @@ -21,11 +19,7 @@ class TestMetaDataController(FunctionalTest): @staticmethod def get_error(transaction_id, status_code, error_details=None, message=None): - return ClientSideError(json.dumps( - {'code': status_code, 'type': 'test', 'created': '0.0', - 'transaction_id': transaction_id, - 'message': message if message else error_details, - 'details': 'test'}), status_code=status_code) + return ClientSideError(message or error_details, status_code) def setUp(self): FunctionalTest.setUp(self) @@ -50,8 +44,8 @@ class TestMetaDataController(FunctionalTest): '/v1/orm/images/image_id/regions/region_name/metadata', metadata_input, expect_errors=True) self.assertEqual(404, response.status_code) - self.assertEqual(json.loads(response.json['faultstring'])['message'], - "(404, 'not found')") + self.assertEqual(response.json['faultstring'], + 'not found') @mock.patch.object(metadata, 'err_utils') @mock.patch.object(metadata, 'di') @@ -62,7 +56,7 @@ class TestMetaDataController(FunctionalTest): '/v1/orm/images/image_id/regions/region_name/metadata', metadata_input, expect_errors=True) self.assertEqual(500, response.status_code) - self.assertEqual(json.loads(response.json['faultstring'])['message'], + self.assertEqual(response.json['faultstring'], 'unknown error') @@ -72,6 +66,6 @@ def get_mocks(error=None): utils = mock.MagicMock() metadata_logic.add_metadata.return_value = mock.MagicMock() if error: - metadata_logic.add_metadata.side_effect = {404: metadata.ErrorStatus(error, 'not found'), + metadata_logic.add_metadata.side_effect = {404: NotFoundError('not found'), 500: Exception("unknown error")}[error] return metadata_logic, utils diff --git a/orm/tests/unit/ims/controllers/v1/orm/images/test_regions.py b/orm/tests/unit/ims/controllers/v1/orm/images/test_regions.py index cb31b8be..ce7d5b5b 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/images/test_regions.py +++ b/orm/tests/unit/ims/controllers/v1/orm/images/test_regions.py @@ -1,8 +1,8 @@ import json from orm.common.orm_common.injector import injector +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.image_manager.ims.controllers.v1.orm.images import regions -from orm.services.image_manager.ims.logic.error_base import ErrorStatus from orm.services.image_manager.ims.persistency.wsme.models import RegionWrapper from orm.tests.unit.ims import FunctionalTest diff --git a/orm/tests/unit/ims/controllers/v1/orm/test_logs.py b/orm/tests/unit/ims/controllers/v1/orm/test_logs.py index 1727863c..63a1a8f9 100755 --- a/orm/tests/unit/ims/controllers/v1/orm/test_logs.py +++ b/orm/tests/unit/ims/controllers/v1/orm/test_logs.py @@ -25,7 +25,6 @@ class TestLogsController(FunctionalTest): level = "not_valid_level" response = self.app.put('/v1/orm/logs/{}'.format(level), expect_errors=True) - print(response) self.assertEqual(response.status_code, 400) self.assertEqual(response.json['faultstring'], "The given log level [{}] doesn't exist.".format( @@ -35,9 +34,7 @@ class TestLogsController(FunctionalTest): level = "not_valid_level" response = self.app.put('/v1/orm/logs/{}'.format(level), expect_errors=True) - print(response) self.assertEqual(response.status_code, 400) - print(response.json['faultstring']) self.assertEqual(response.json['faultstring'], "The given log level [{}] doesn't exist.".format( level)) diff --git a/orm/tests/unit/ims/logic/test_image_logic.py b/orm/tests/unit/ims/logic/test_image_logic.py index dbbc38e4..e152afd1 100755 --- a/orm/tests/unit/ims/logic/test_image_logic.py +++ b/orm/tests/unit/ims/logic/test_image_logic.py @@ -1,3 +1,4 @@ +from orm.common.orm_common.utils.error_base import NotFoundError from orm.common.orm_common.utils import utils from orm.services.image_manager.ims.logic import image_logic from orm.services.image_manager.ims.persistency.sql_alchemy.db_models import Image @@ -88,7 +89,7 @@ class TestImageLogic(FunctionalTest): try: image_logic.get_image_by_uuid('te') - except image_logic.ErrorStatus as e: + except image_logic.NotFoundError as e: self.assertEqual(e.status_code, 404) @mock.patch.object(utils, 'get_resource_status_from_db') @@ -165,7 +166,7 @@ class TestDeleteImageLogic(FunctionalTest): try: image_logic.delete_image_by_uuid("image_uuid", "transaction_id") - except Exception as e: + except NotFoundError as e: self.assertEqual(404, e.status_code) @mock.patch.object(image_logic, 'di') @@ -283,7 +284,7 @@ class TestActivateImageLogic(FunctionalTest): mock_di.resolver.unpack.return_value = my_dm try: image_logic.enable_image("test_id", 1, "transaction_id") - except image_logic.ErrorStatus as e: + except NotFoundError as e: self.assertEqual(e.status_code, 404) @mock.patch.object(image_logic, 'LOG') @@ -313,13 +314,13 @@ class TestListImageLogic(FunctionalTest): my_get_image = mock.MagicMock() my_get_image.get_image.return_value = None my_get_record = mock.MagicMock() - my_get_record.get_record.side_effect = image_logic.ErrorStatus(404, 'a') + my_get_record.get_record.side_effect = NotFoundError('a') my_dm = mock.MagicMock(return_value=my_get_record) mock_di.resolver.unpack.return_value = my_dm try: image_logic.get_image_list_by_params('a', 'b', 'c') - except image_logic.ErrorStatus as e: + except NotFoundError as e: self.assertEqual(e.status_code, 404) @mock.patch.object(image_logic, 'di') @@ -408,7 +409,7 @@ class TestAddRegions(FunctionalTest): mock_di.resolver.unpack.return_value = mock_data_manager regions_wrapper = mock.MagicMock() regions_wrapper.regions = [mock.MagicMock()] - self.assertRaises(image_logic.ErrorStatus, image_logic.add_regions, + self.assertRaises(NotFoundError, image_logic.add_regions, 'uuid', regions_wrapper, 'transaction') @mock.patch.object(image_logic, 'get_image_by_uuid', @@ -452,7 +453,7 @@ class TestReplaceRegions(FunctionalTest): mock_di.resolver.unpack.return_value = mock_data_manager regions_wrapper = mock.MagicMock() regions_wrapper.regions = [mock.MagicMock()] - self.assertRaises(image_logic.ErrorStatus, image_logic.replace_regions, + self.assertRaises(NotFoundError, image_logic.replace_regions, 'uuid', regions_wrapper, 'transaction') @mock.patch.object(image_logic, 'get_image_by_uuid', @@ -496,7 +497,7 @@ class TestDeleteRegion(FunctionalTest): rds_proxy, mock_data_manager = get_data_manager_mock( mock_sql_image=None) mock_di.resolver.unpack.return_value = mock_data_manager - self.assertRaises(image_logic.ErrorStatus, image_logic.delete_region, + self.assertRaises(NotFoundError, image_logic.delete_region, 'uuid', mock.MagicMock(), 'transaction', False) @mock.patch.object(image_logic, 'send_to_rds_if_needed', return_value=True) @@ -552,7 +553,7 @@ class TestAddCustomers(FunctionalTest): rds_proxy, mock_data_manager = get_data_manager_mock( mock_sql_image=None) mock_di.resolver.unpack.return_value = mock_data_manager - self.assertRaises(image_logic.ErrorStatus, image_logic.add_customers, + self.assertRaises(NotFoundError, image_logic.add_customers, 'uuid', mock.MagicMock(), 'transaction') @@ -624,7 +625,7 @@ class TestReplaceCustomers(FunctionalTest): rds_proxy, mock_data_manager = get_data_manager_mock( mock_sql_image=None) mock_di.resolver.unpack.return_value = mock_data_manager - self.assertRaises(image_logic.ErrorStatus, + self.assertRaises(NotFoundError, image_logic.replace_customers, 'uuid', mock.MagicMock(), 'transaction') diff --git a/orm/tests/unit/ims/logic/test_meta_data.py b/orm/tests/unit/ims/logic/test_meta_data.py index d5ec6ef0..dfc7b5e6 100755 --- a/orm/tests/unit/ims/logic/test_meta_data.py +++ b/orm/tests/unit/ims/logic/test_meta_data.py @@ -1,3 +1,4 @@ +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.image_manager.ims.logic import metadata_logic from orm.services.image_manager.ims.persistency.sql_alchemy.db_models import ImageRegion from orm.services.image_manager.ims.persistency.wsme.models import Metadata, MetadataWrapper @@ -16,28 +17,28 @@ class TestMetaData(FunctionalTest): FunctionalTest.tearDown(self) @mock.patch.object(metadata_logic, 'di') - def test_add_metadtat_sucess(self, metadta_mock): - data_manager = get_data_maneger_mock_metadata(image_rec=True) + def test_add_metadata_sucess(self, metadta_mock): + data_manager = get_data_manager_mock_metadata(image_rec=True) metadta_mock.resolver.unpack.return_value = data_manager result = metadata_logic.add_metadata("id", "region", {}) @mock.patch.object(metadata_logic, 'di') - def test_add_metadtat_notfound(self, metadta_mock): - data_manager = get_data_maneger_mock_metadata() + def test_add_metadata_notfound(self, metadta_mock): + data_manager = get_data_manager_mock_metadata() metadta_mock.resolver.unpack.return_value = data_manager - with self.assertRaises(metadata_logic.ErrorStatus): + with self.assertRaises(NotFoundError): metadata_logic.add_metadata("id", "region", {}) @mock.patch.object(metadata_logic, 'di') - def test_add_metadtat_with_regions_success(self, metadta_mock): - data_manager = get_data_maneger_mock_metadata(image_rec=True, + def test_add_metadata_with_regions_success(self, metadta_mock): + data_manager = get_data_manager_mock_metadata(image_rec=True, regions=[ImageRegion(region_name="region")]) metadta_mock.resolver.unpack.return_value = data_manager metadata_logic.add_metadata("id", "region", MetadataWrapper(Metadata("1", "2", "3"))) -def get_data_maneger_mock_metadata(image_rec=None, regions=[]): +def get_data_manager_mock_metadata(image_rec=None, regions=[]): data_manager = mock.MagicMock() DataManager = mock.MagicMock() diff --git a/orm/tests/unit/rds/controllers/v1/resources/test_create_resource.py b/orm/tests/unit/rds/controllers/v1/resources/test_create_resource.py index bf4c49c9..5a06a1f8 100755 --- a/orm/tests/unit/rds/controllers/v1/resources/test_create_resource.py +++ b/orm/tests/unit/rds/controllers/v1/resources/test_create_resource.py @@ -39,9 +39,9 @@ class TestCreateResource(FunctionalTest): assert response.status_int == 400 @patch.object(root.ResourceService, 'main', - side_effect=root.ConflictValue("region")) + side_effect=root.ConflictError("region")) def test_create_resource_conflict_except(self, input): - """test creatte resource to catch ConflictValue exception.""" + """test creatte resource to catch ConflictError exception.""" headers = {'User-Domain': 'default', 'X-Ranger-Client': 'user1'} response = self.app.post_json('/v1/rds/resources', good_data, headers=headers, expect_errors=True) @@ -67,7 +67,7 @@ class TestCreateResource(FunctionalTest): flavor_data["service_template"]["resource"]['resource_type'] = "flavor" @patch.object(root.ResourceService, 'main', - side_effect=root.ConflictValue("region")) + side_effect=root.ConflictError("region")) def test_delete_resource_flavor_con(self, input): """test delete flavor while previous process still in progress.""" headers = {'User-Domain': 'default', 'X-Ranger-Client': 'user1'} @@ -116,9 +116,9 @@ class TestCreateResource(FunctionalTest): self.fail('error') @patch.object(root.ResourceService, 'main', - side_effect=root.ConflictValue("region")) + side_effect=root.ConflictError("region")) def test_modify_resource_conflict_except(self, input): - """test modify resource to catch ConflictValue exception.""" + """test modify resource to catch ConflictError exception.""" headers = {'User-Domain': 'default', 'X-Ranger-Client': 'user1'} response = self.app.put_json('/v1/rds/resources', good_data, headers=headers, expect_errors=True) diff --git a/orm/tests/unit/rds/controllers/v1/status/test_base.py b/orm/tests/unit/rds/controllers/v1/status/test_base.py deleted file mode 100644 index 240a746e..00000000 --- a/orm/tests/unit/rds/controllers/v1/status/test_base.py +++ /dev/null @@ -1,13 +0,0 @@ -import unittest - -from orm.services.resource_distributor.rds.controllers.v1.base import ClientSideError - - -class Test(unittest.TestCase): - - # Test the creation of ClientSideError - def test_ClientSideError(self): - error_str = "This is an error message" - clientSideError = ClientSideError(error=error_str) - self.assertEqual(clientSideError.msg, error_str) - self.assertEqual(clientSideError.code, 400) diff --git a/orm/tests/unit/rds/controllers/v1/status/test_resource_status.py b/orm/tests/unit/rds/controllers/v1/status/test_resource_status.py index 536c96fd..73a7eb77 100644 --- a/orm/tests/unit/rds/controllers/v1/status/test_resource_status.py +++ b/orm/tests/unit/rds/controllers/v1/status/test_resource_status.py @@ -1,5 +1,6 @@ """unittest for post resource.""" from mock import patch +from orm.common.orm_common.utils.error_base import InputValueError import orm.services.resource_distributor.rds.controllers.v1.status.resource_status as resource from orm.tests.unit.rds.controllers.v1.functional_test import FunctionalTest @@ -15,7 +16,7 @@ class PostResourceStatus(FunctionalTest): assert response.status_int == 201 @patch.object(resource.regionResourceIdStatus, 'add_status', - side_effect=resource.InputError("no input", 'request_id')) + side_effect=InputValueError()) def test_valid_Post_status_database_error(self, input): """Post valid json return database error.""" response = self.app.post_json('/v1/rds/status/', data, diff --git a/orm/tests/unit/rds/services/test_create_resource.py b/orm/tests/unit/rds/services/test_create_resource.py index 825fa99b..26914c6b 100755 --- a/orm/tests/unit/rds/services/test_create_resource.py +++ b/orm/tests/unit/rds/services/test_create_resource.py @@ -1,10 +1,12 @@ """create resource unittest module.""" +from pecan import conf import unittest from unittest.mock import patch from orm.common.orm_common.model.models import (ResourceStatusModel, ResourceMetaData, StatusModel) +from orm.common.orm_common.utils.error_base import ErrorStatus from orm.services.resource_distributor.rds.services import resource as ResourceService result = ResourceStatusModel( @@ -46,21 +48,23 @@ class InputData(object): class CreateResource(unittest.TestCase): """create resource test.""" - @patch.object(ResourceService.regionResourceIdStatus, 'add_status', - return_value=None) + @patch.object(ResourceService.regionResourceIdStatus, + 'add_status', return_value=None) @patch.object(ResourceService, '_submit_template_data', return_value=[1, 2]) @patch.object(ResourceService, '_create_template_data', return_value=[1, 2]) @patch.object(ResourceService.regionResourceIdStatus, 'get_regions_by_status_resource_id', return_value=None) @patch.object(ResourceService.uuid_utils, 'get_random_uuid', - side_effect=Exception("uuid general exception")) + side_effect=ErrorStatus("uuid general exception")) def test_create_customer_not_valid_uuid_gen(self, tranid, result, sotdata, sotupload, database): """uuid gen raise an error.""" + conf.block_by_status = 'Submitted' + ResourceService.conf = conf status_model = StatusModel(status=[result]) status_model.regions = None result.return_value = status_model - with self.assertRaises(ResourceService.ErrorMessage): + with self.assertRaises(ErrorStatus): resource_id = ResourceService.main(jsondata, uuid, 'customer', 'create') @@ -95,7 +99,7 @@ class CreateResource(unittest.TestCase): # return_value=StatusModel(status=[result])) # def test_delete_flavor_conflict(self, databasemock): # """check delete flavor with conflict.""" - # with self.assertRaises(ResourceService.ConflictValue): + # with self.assertRaises(ConflictError): # ResourceService.main(flavorjsondata, uuid, 'flavor', 'delete') @patch.object(ResourceService.regionResourceIdStatus, @@ -105,14 +109,16 @@ class CreateResource(unittest.TestCase): @patch.object(ResourceService.regionResourceIdStatus, 'get_regions_by_status_resource_id', return_value=None) @patch.object(ResourceService.uuid_utils, 'get_random_uuid', - side_effect=Exception("uuid general exception")) + side_effect=ErrorStatus("uuid general exception")) def test_delete_flavor_not_valid_uuid_gen(self, tranid, result, sotdata, sotupload, database): """delete flavor uuid gen raise an error.""" status_model = StatusModel(status=[result]) status_model.regions = None result.return_value = status_model - with self.assertRaises(ResourceService.ErrorMessage): + conf.block_by_status = 'Submitted' + ResourceService.conf = conf + with self.assertRaises(ErrorStatus): resource_id = ResourceService.main(flavorjsondata, uuid, 'flavor', 'delete') @@ -129,7 +135,7 @@ class CreateResource(unittest.TestCase): assert (input_data.__dict__ == expected_image_input_data) def test_unknown_resource_type(self): - with self.assertRaises(ResourceService.ErrorMessage): + with self.assertRaises(ErrorStatus): input_data = ResourceService._get_inputs_from_resource_type(jsondata, 'unknown', 'uuid-12345') diff --git a/orm/tests/unit/rds/services/test_region_resource_id_status.py b/orm/tests/unit/rds/services/test_region_resource_id_status.py index 31e3574c..c514d8c1 100755 --- a/orm/tests/unit/rds/services/test_region_resource_id_status.py +++ b/orm/tests/unit/rds/services/test_region_resource_id_status.py @@ -1,6 +1,7 @@ import unittest import mock +from orm.common.orm_common.utils.error_base import InputValueError from orm.services.resource_distributor.rds.services import region_resource_id_status from orm.tests.unit.rds import config as conf @@ -53,7 +54,7 @@ class TestModel(unittest.TestCase): if test_status in region_resource_id_status.config['allowed_status_values']: region_resource_id_status.config['allowed_status_values'].remove(test_status) - self.assertRaises(region_resource_id_status.InputError, + self.assertRaises(InputValueError, region_resource_id_status.validate_status_value, test_status) @@ -67,7 +68,7 @@ class TestModel(unittest.TestCase): test_operation = 'test' region_resource_id_status.config['allowed_operation_type'] = {} - self.assertRaises(region_resource_id_status.InputError, + self.assertRaises(InputValueError, region_resource_id_status.validate_operation_type, test_operation) @@ -81,7 +82,7 @@ class TestModel(unittest.TestCase): test_resource = 'test' region_resource_id_status.config['allowed_resource_type'] = {} - self.assertRaises(region_resource_id_status.InputError, + self.assertRaises(InputValueError, region_resource_id_status.validate_resource_type, test_resource) @@ -149,7 +150,7 @@ class TestModel(unittest.TestCase): temp_mock = MockClass([]) region_resource_id_status.factory.get_region_resource_id_status_connection = temp_mock - self.assertRaises(region_resource_id_status.InputError, + self.assertRaises(InputValueError, region_resource_id_status.add_status, {'timestamp': 1, 'region': 2, 'status': 3, 'transaction_id': 4, 'resource_id': 5, diff --git a/orm/tests/unit/rms/controllers/v1/orm/resources/test_region.py b/orm/tests/unit/rms/controllers/v1/orm/resources/test_region.py index 480849b6..7eb2840f 100755 --- a/orm/tests/unit/rms/controllers/v1/orm/resources/test_region.py +++ b/orm/tests/unit/rms/controllers/v1/orm/resources/test_region.py @@ -1,6 +1,8 @@ import json from unittest.mock import patch, MagicMock +from orm.common.orm_common.utils.error_base import \ + ErrorStatus, InputValueError, NotFoundError from orm.services.region_manager.rms.controllers.v2.orm.resources import regions from orm.services.region_manager.rms.model import model as PyModels from orm.tests.unit.rms import FunctionalTest @@ -211,7 +213,7 @@ class TestAddRegion(FunctionalTest): mock_get_error, request_mock): mock_get_error.get_error = self.get_error request_mock.transaction_id = "555" - mock_create_logic.side_effect = regions.error_base.InputValueError(message="value error") + mock_create_logic.side_effect = InputValueError(message="value error") response = self.app.post_json('/v2/orm/regions', full_region, expect_errors=True) self.assertEqual(response.status_code, 400) @@ -235,7 +237,7 @@ class TestAddRegion(FunctionalTest): mock_get_error, mock_request): mock_get_error.get_error = self.get_error mock_request.transaction_id = "555" - mock_get_logic.side_effect = regions.error_base.NotFoundError(message="not found", status_code=404) + mock_get_logic.side_effect = NotFoundError(message="not found", status_code=404) response = self.app.get('/v2/orm/regions/id', expect_errors=True) self.assertEqual(json.loads(response.json['faultstring'])['message'], 'not found') @@ -262,7 +264,7 @@ class TestAddRegion(FunctionalTest): mock_get_error, mock_request): mock_get_error.get_error = self.get_error mock_request.transaction_id = "555" - mock_delete_logic.side_effect = regions.error_base.ErrorStatus(message="unknown error", status_code=500) + mock_delete_logic.side_effect = ErrorStatus(message="unknown error", status_code=500) response = self.app.delete('/v2/orm/regions/id', expect_errors=True) self.assertEqual(response.status_code, 500) @@ -300,13 +302,12 @@ class TestAddRegion(FunctionalTest): mock_get_error, mock_request): mock_get_error.get_error = self.get_error mock_request.transaction_id = "555" - mock_update_logic.side_effect = regions.error_base.NotFoundError( - message="not found", status_code=404) + mock_update_logic.side_effect = NotFoundError( + message="not found") response = self.app.put_json('/v2/orm/regions/id', full_region, expect_errors=True) self.assertEqual(json.loads(response.json['faultstring'])['message'], 'not found') - self.assertEqual(response.status_code, 404) class TestWsmeModelFunctions(TestAddRegion): @@ -360,7 +361,7 @@ class TestGetRegionsController(FunctionalTest): @patch.object(regions.RegionService, 'get_regions_data', side_effect=Exception("unknown error")) @patch.object(regions.err_utils, 'get_error', return_value=ClientSideError(json.dumps({ - 'code': 500, + 'status_code': 500, 'type': 'test', 'created': '0.0', 'transaction_id': '111', @@ -375,14 +376,13 @@ class TestGetRegionsController(FunctionalTest): response = self.app.get('/v2/orm/regions', expect_errors=True) regions.request = temp_request - dict_body = json.loads(response.body) - result_json = json.loads(dict_body['faultstring']) + result_json = json.loads(response.json['faultstring']) self.assertEqual('111', result_json['transaction_id']) - self.assertEqual(500, result_json['code']) + self.assertEqual(500, result_json['status_code']) @patch.object(regions.RegionService, 'get_regions_data', - side_effect=regions.error_base.NotFoundError("no content !!!?")) + side_effect=NotFoundError("no content !!!?")) @patch.object(regions.err_utils, 'get_error', return_value=ClientSideError(json.dumps({ 'code': 404, @@ -417,7 +417,7 @@ class TestGetRegionsController(FunctionalTest): side_effect=Exception("unknown error")) @patch.object(regions.err_utils, 'get_error', return_value=ClientSideError(json.dumps({ - 'code': 500, + 'status_code': 500, 'type': 'test', 'created': '0.0', 'transaction_id': '111', @@ -432,8 +432,7 @@ class TestGetRegionsController(FunctionalTest): response = self.app.get('/v2/orm/regions/id', expect_errors=True) regions.request = temp_request - dict_body = json.loads(response.body) - result_json = json.loads(dict_body['faultstring']) + dict_body = json.loads(response.json['faultstring']) - self.assertEqual('111', result_json['transaction_id']) - self.assertEqual(500, result_json['code']) + self.assertEqual('111', dict_body['transaction_id']) + self.assertEqual(500, dict_body['status_code']) diff --git a/orm/tests/unit/rms/services/test_services.py b/orm/tests/unit/rms/services/test_services.py index a834df40..69990040 100755 --- a/orm/tests/unit/rms/services/test_services.py +++ b/orm/tests/unit/rms/services/test_services.py @@ -3,6 +3,8 @@ import mock from mock import patch from pecan import conf +from orm.common.orm_common.utils.error_base import (ConflictError, InputValueError, + NotFoundError) from orm.services.region_manager.rms.controllers.v2.orm.resources import groups from orm.services.region_manager.rms.controllers.v2.orm.resources import regions from orm.services.region_manager.rms.services import services @@ -32,7 +34,7 @@ class db(object): def add_group(self, *items): if items[3] and "bad_region" in items[3]: - raise services.error_base.InputValueError() + raise InputValueError() def get_regions(self, region_dict=None, metadata_dict=None, end_point=None): @@ -61,7 +63,7 @@ class db(object): def update_region(self, id=None, **kw): if self.exp == "not found": - raise services.error_base.NotFoundError(message="id not found") + raise NotFoundError(message="id not found") elif self.exp: raise Exception("error") return True @@ -143,14 +145,14 @@ class TestServices(FunctionalTest): @patch.object(services.data_manager_factory, 'get_data_manager', return_value=db()) def test_get_groups_empty_data(self, mock_db_get_group): - self.assertRaises(services.error_base.NotFoundError, + self.assertRaises(NotFoundError, services.get_groups_data, None) @patch.object(services.data_manager_factory, 'get_data_manager', return_value=db()) def test_get_regions_empty_data(self, mock_db_get_group): url_parm = URlParm() - self.assertRaises(services.error_base.NotFoundError, + self.assertRaises(NotFoundError, services.get_regions_data, url_parm) @patch.object(services.data_manager_factory, 'get_data_manager', @@ -165,17 +167,17 @@ class TestServices(FunctionalTest): @patch.object(services.data_manager_factory, 'get_data_manager') def test_create_group_no_name_or_id(self, mock_get_data_manager): - with self.assertRaises(services.error_base.InputValueError) as exp: + with self.assertRaises(InputValueError) as exp: services.create_group_in_db(groups.Groups('', '', 'b', ['c'])) @patch.object(services.data_manager_factory, 'get_data_manager') def test_create_group_no_description(self, mock_get_data_manager): - with self.assertRaises(services.error_base.InputValueError) as exp: + with self.assertRaises(InputValueError) as exp: services.create_group_in_db(groups.Groups('d', 'a', '', ['c'])) @patch.object(services.data_manager_factory, 'get_data_manager', return_value=db()) def test_create_group_in_db_not_valid_regions(self, mock_get_data_manager): - with self.assertRaises(services.error_base.InputValueError) as exp: + with self.assertRaises(InputValueError) as exp: services.create_group_in_db(groups.Groups('d', 'd', 'b', ['bad_region'])) @@ -183,10 +185,9 @@ class TestServices(FunctionalTest): def test_create_group_in_db_duplicate_entry(self, mock_get_data_manager): my_manager = mock.MagicMock() my_manager.add_group = mock.MagicMock( - side_effect=services.error_base.ConflictError( - 'test')) + side_effect=ConflictError('test')) mock_get_data_manager.return_value = my_manager - with self.assertRaises(services.error_base.ConflictError) as exp: + with self.assertRaises(ConflictError) as exp: services.create_group_in_db(groups.Groups('d', 'd', 'b', ['c'])) @patch.object(services.data_manager_factory, 'get_data_manager', @@ -199,7 +200,7 @@ class TestServices(FunctionalTest): return_value=db()) def test_get_region_by_id_or_name_no_content(self, mock_data_manager_factory): - self.assertRaises(services.error_base.NotFoundError, + self.assertRaises(NotFoundError, services.get_region_by_id_or_name, None) @patch.object(services.data_manager_factory, 'get_data_manager', @@ -223,9 +224,9 @@ class TestServices(FunctionalTest): def test_create_region_duplicate(self, mock_db_create_region, mock_get_region_id_name): duplicate = mock.MagicMock() - duplicate.side_effect = services.base_data_manager.DuplicateEntryError() + duplicate.side_effect = ConflictError() mock_db_create_region.return_value.add_region = duplicate - with self.assertRaises(services.error_base.ConflictError) as exp: + with self.assertRaises(ConflictError) as exp: result = services.create_full_region( self._to_wsme_from_input(full_region)) @@ -238,7 +239,7 @@ class TestServices(FunctionalTest): orig_status = full_region['status'] full_region['status'] = "123" allowed_status = conf.region_options.allowed_status_values[:] - with self.assertRaises(services.error_base.InputValueError) as exp: + with self.assertRaises(InputValueError) as exp: result = services.create_full_region(self._to_wsme_from_input(full_region)) test_ok = str(allowed_status) in exp.expected.message self.assertEqual(test_ok, True) @@ -261,8 +262,8 @@ class TestServices(FunctionalTest): try: result = services.create_full_region( self._to_wsme_from_input(full_region)) - except services.error_base.InputValueError as exp: - message = exp.message + except InputValueError as exp: + message = str(exp) full_region['endpoints'] = orig_endpoint self.assertEqual(str(endpoints_types_must_have) in str(message), True) @@ -312,8 +313,8 @@ class TestServices(FunctionalTest): try: result = services.update_region('id', self._to_wsme_from_input(full_region)) - except services.error_base.NotFoundError as exp: - message = exp.message + except NotFoundError as exp: + message = str(exp) self.assertEqual(message, "id not found") @patch.object(services.data_manager_factory, 'get_data_manager', diff --git a/orm/tests/unit/rms/storage/my_sql/test_data_manager.py b/orm/tests/unit/rms/storage/my_sql/test_data_manager.py index 99480855..711c6b10 100755 --- a/orm/tests/unit/rms/storage/my_sql/test_data_manager.py +++ b/orm/tests/unit/rms/storage/my_sql/test_data_manager.py @@ -2,9 +2,8 @@ import unittest import mock -from orm.services.region_manager.rms.services import error_base +from orm.common.orm_common.utils import error_base from orm.services.region_manager.rms.storage.my_sql import data_manager, data_models -from orm.services.region_manager.rms.storage.base_data_manager import DuplicateEntryError end_point_list = [{"type": "ord", "url": "http://ord.com"}] @@ -82,7 +81,7 @@ class TestDataManager(unittest.TestCase): def test_add_region_duplicate_error(self, mock_engine): """Test that duplicate exception is raised when calling add_status_record.""" my_data_manager = data_manager.DataManager("url", "", "") - with self.assertRaises(DuplicateEntryError): + with self.assertRaises(error_base.ConflictError): my_data_manager.add_region("reg1", "region1", "a_state", "a_country", "a_city", "a_street", "a_zip", "a_status", "aic_ver", "os_ver", "design_type", "loc_type", "default", "vlcp", @@ -106,7 +105,7 @@ class TestDataManager(unittest.TestCase): def test_add_group_reference_error(self, mock_engine): """Test that reference exception is raised when calling add_group.""" my_data_manager = data_manager.DataManager("url", "", "") - with self.assertRaises(error_base.InputValueError): + with self.assertRaises(error_base.NotFoundError): my_data_manager.add_group("group1", "group 1", "bla bla", ["region1"]) @mock.patch.object(data_manager, 'LegacyEngineFacade', @@ -179,7 +178,7 @@ class TestDataManager(unittest.TestCase): def test_update_region_region_not_found(self, mock_engine): """Test that NotFoundError is raised when calling update_region.""" my_data_manager = data_manager.DataManager("url", "", "") - self.assertRaises(data_manager.error_base.NotFoundError, + self.assertRaises(error_base.NotFoundError, my_data_manager.update_region, "reg1", "region1", "region_name", "a_state", "a_country", @@ -236,7 +235,7 @@ class TestDataManager(unittest.TestCase): my_data_manager = data_manager.DataManager("url", "", "") - self.assertRaises(data_manager.error_base.ConflictError, + self.assertRaises(error_base.ConflictError, my_data_manager.add_meta_data_to_region, 'region', {'meta': 'data'}) @@ -250,7 +249,7 @@ class TestDataManager(unittest.TestCase): query=QueryObject(ret=None))) def test_update_region_meta_data_region_not_found(self, mock_engine): my_data_manager = data_manager.DataManager("url", "", "") - self.assertRaises(data_manager.error_base.NotFoundError, + self.assertRaises(error_base.NotFoundError, my_data_manager.update_region_meta_data, 'region', {'meta': 'data'}) @@ -264,7 +263,7 @@ class TestDataManager(unittest.TestCase): query=QueryObject(ret=None))) def test_delete_region_metadata_region_not_found(self, mock_engine): my_data_manager = data_manager.DataManager("url", "", "") - self.assertRaises(data_manager.error_base.NotFoundError, + self.assertRaises(error_base.NotFoundError, my_data_manager.delete_region_metadata, 'region', {'meta': 'data'}) @@ -278,7 +277,7 @@ class TestDataManager(unittest.TestCase): query=QueryObject(ret=None))) def test_update_region_status_region_not_found(self, mock_facade): my_data_manager = data_manager.DataManager("url", "", "") - self.assertRaises(data_manager.error_base.NotFoundError, + self.assertRaises(error_base.NotFoundError, my_data_manager.update_region_status, 'region', 'status') diff --git a/orm/tests/unit/rms/storage/test_base_data_manager.py b/orm/tests/unit/rms/storage/test_base_data_manager.py deleted file mode 100644 index 895a5a83..00000000 --- a/orm/tests/unit/rms/storage/test_base_data_manager.py +++ /dev/null @@ -1,50 +0,0 @@ -import unittest - -from orm.services.region_manager.rms.storage.base_data_manager import BaseDataManager - - -class BaseDataManagerTests(unittest.TestCase): - - def test_base_data_manager_add_region_not_implemented(self): - """ Check if creating an instance and calling add_region - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").add_region('1', '2', '3', '4', '5', '6', '7', - '8', '9', '10', '11', '12', '13', - '14', '15', '16', '17', '18') - - def test_base_data_manager_get_regions_not_implemented(self): - """ Check if creating an instance and calling get_regions - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").get_regions('1', '2', '3') - - def test_base_data_manager_get_all_regions_not_implemented(self): - """ Check if creating an instance and calling get_all_regions - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").get_all_regions() - - def test_base_data_manager_add_group_not_implemented(self): - """ Check if creating an instance and calling add_group - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").add_group("1", "2", "3", "4") - - def test_base_data_manager_get_group_not_implemented(self): - """ Check if creating an instance and calling get_group - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").get_group("1") - - def test_base_data_manager_get_all_groups_not_implemented(self): - """ Check if creating an instance and calling get_all_groups - method fail - """ - with self.assertRaises(NotImplementedError): - BaseDataManager("", "", "").get_all_groups() diff --git a/orm/tests/unit/rms/tests_lcp_controller.py b/orm/tests/unit/rms/tests_lcp_controller.py index 6c939355..fc5789c0 100755 --- a/orm/tests/unit/rms/tests_lcp_controller.py +++ b/orm/tests/unit/rms/tests_lcp_controller.py @@ -1,9 +1,9 @@ from unittest.mock import patch, MagicMock from wsme.exc import ClientSideError +from orm.common.orm_common.utils.error_base import NotFoundError from orm.services.region_manager.rms.controllers import lcp_controller from orm.services.region_manager.rms.model.model import RegionData, Regions, EndPoint -from orm.services.region_manager.rms.services.error_base import NotFoundError from orm.services.region_manager.rms.services import services import json @@ -83,7 +83,7 @@ class TestLcpController(FunctionalTest): self.assertEqual(zones, TEST_REGIONS_DATA) @patch.object(services, 'get_regions_data', - side_effect=NotFoundError(message="No regions found!")) + side_effect=NotFoundError("No regions found!")) def test_get_zones_get_regions_data_error(self, regions_data): zones = lcp_controller.get_zones() self.assertEqual(zones, []) diff --git a/orm/tests/unit/uuidgen/test_uuid.py b/orm/tests/unit/uuidgen/test_uuid.py index c986c97b..4698a51a 100644 --- a/orm/tests/unit/uuidgen/test_uuid.py +++ b/orm/tests/unit/uuidgen/test_uuid.py @@ -1,3 +1,4 @@ +from orm.common.orm_common.utils.error_base import NotFoundError, UnauthorizedError from orm.services.id_generator.uuidgen.controllers.v1 import uuid_controller from orm.tests.unit.uuidgen import FunctionalTest @@ -52,7 +53,7 @@ class TestUuidController(FunctionalTest): mock_dbmanager, mock_utils): mock_request.headers.get.return_value = 'value' - mock_utils.get_region_end_point_from_db.return_value = None + mock_utils.get_region_end_point_from_db.side_effect = NotFoundError() response = self.app.delete('/v1/uuids/test_uuid', expect_errors=True) self.assertEqual(response.status_code, 404) @@ -65,7 +66,7 @@ class TestUuidController(FunctionalTest): mock_request.headers.get.return_value = 'value' mock_utils.get_region_end_point_from_db.return_value = 'ep' - uuid_controller.authentication.authorize.side_effect = SystemError() + uuid_controller.authentication.authorize.side_effect = UnauthorizedError(status_code=401) response = self.app.delete('/v1/uuids/test_uuid', expect_errors=True) self.assertEqual(response.status_code, 401) diff --git a/tox.ini b/tox.ini index 4031c98c..205676e7 100644 --- a/tox.ini +++ b/tox.ini @@ -7,7 +7,7 @@ skipsdist = True basepython=python3 usedevelop = True passenv = http_proxy HTTP_PROXY https_proxy HTTPS_PROXY no_proxy NO_PROXY -install_command = pip install -c{env:UPPER_CONSTRAINTS_FILE:https://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt} {opts} {packages} +install_command = pip install {opts} {packages} --trusted-host pypi.org --trusted-host files.pythonhosted.org setenv = VIRTUAL_ENV={envdir} PYTHONWARNINGS=default::DeprecationWarning