def get_region_logic_mock(): global region_logic_mock region_logic_mock = MagicMock() if return_error == 0: region_logic_mock.add_regions.return_value = RET_REGION_JSON elif return_error == 1: region_logic_mock.add_regions.side_effect = SystemError() region_logic_mock.delete_region.side_effect = SystemError() else: region_logic_mock.add_regions.side_effect = ErrorStatus(status_code=404) region_logic_mock.delete_region.side_effect = ErrorStatus(status_code=404) return region_logic_mock
def get_flavor_logic_mock(): global flavor_logic_mock flavor_logic_mock = MagicMock() if return_error == 0: flavor_logic_mock.get_tags.return_value = FLAVOR_JSON['tags'] flavor_logic_mock.add_tags.return_value = RET_FLAVOR_JSON flavor_logic_mock.delete_tags.return_value = RET_FLAVOR_JSON flavor_logic_mock.update_tags.return_value = RET_FLAVOR_JSON flavor_logic_mock.update_flavor.return_value = RET_FLAVOR_JSON flavor_logic_mock.create_flavor.return_value = RET_FLAVOR_JSON flavor_logic_mock.get_flavor_by_uuid.return_value = RET_FLAVOR_JSON flavor_logic_mock.get_flavor_by_uuid_or_name.return_value = \ RET_FLAVOR_JSON flavor_logic_mock.get_flavor_list_by_params.return_value = FILTER_RET elif return_error == 1: flavor_logic_mock.get_tags.side_effect = SystemError() flavor_logic_mock.add_tags.side_effect = SystemError() flavor_logic_mock.delete_tags.side_effect = SystemError() flavor_logic_mock.update_tags.side_effect = SystemError() flavor_logic_mock.update_flavor.side_effect = SystemError() flavor_logic_mock.create_flavor.side_effect = SystemError() flavor_logic_mock.get_flavor_by_uuid.side_effect = SystemError() flavor_logic_mock.get_flavor_by_uuid_or_name.side_effect = \ SystemError() flavor_logic_mock.get_flavor_list_by_params.side_effect = SystemError() flavor_logic_mock.delete_flavor_by_uuid.side_effect = SystemError() else: flavor_logic_mock.get_tags.side_effect = ErrorStatus(status_code=404) flavor_logic_mock.add_tags.side_effect = ErrorStatus(status_code=404) flavor_logic_mock.delete_tags.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.update_tags.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.update_flavor.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.create_flavor.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.get_flavor_by_uuid.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.get_flavor_list_by_params.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.delete_flavor_by_uuid.side_effect = ErrorStatus( status_code=404) flavor_logic_mock.get_flavor_by_uuid_or_name.side_effect = ErrorStatus( status_code=404) return flavor_logic_mock
def delete_region(flavor_uuid, region_name, transaction_id): DataManager = di.resolver.unpack(delete_region) datamanager = DataManager() try: 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)) existing_region_names = sql_flavor.get_existing_region_names() sql_flavor.remove_region(region_name) datamanager.flush() # i want to get any exception created by previous actions against the database send_to_rds_if_needed(sql_flavor, existing_region_names, "put", transaction_id) datamanager.commit() except ErrorStatus as exp: LOG.log_exception("FlavorLogic - Failed to update flavor", exp) datamanager.rollback() raise exp except Exception as exp: LOG.log_exception("FlavorLogic - Failed to delete region", exp) datamanager.rollback() raise exp finally: datamanager.close()
def remove_tag(self, tag_name): deleted_flag = False assert isinstance(tag_name, basestring) try: LOG.debug("remove tag {0} from flavor {1}".format( tag_name, str(self))) for tag in reversed(self.flavor_tags): if tag.key_name == tag_name: self.flavor_tags.remove(tag) deleted_flag = True if not deleted_flag: raise ErrorStatus( 404, "Failed to remove tag {0} from flavor id {1}".format( tag_name, str(self.id))) except ErrorStatus as e: raise except Exception as exception: LOG.log_exception( "Failed to remove tag {0} from flavor {1}".format( tag_name, str(self)), exception) raise
def remove_region(self, region_name): region_deleted_flag = False assert isinstance(region_name, basestring) try: LOG.debug("remove regions {0} from flavor {1}".format( region_name, str(self))) for region in reversed(self.flavor_regions): 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))) except ErrorStatus as e: raise except Exception as exception: LOG.log_exception( "Failed to remove region {0} from flavor {1}".format( region_name, str(self)), exception) raise
def get_tenant_logic_mock(): global tenant_logic_mock tenant_logic_mock = MagicMock() if return_error == 0: tenant_logic_mock.add_tenants.return_value = RET_TENANT_JSON elif return_error == 1: tenant_logic_mock.add_tenants.side_effect = SystemError() tenant_logic_mock.delete_tenant.side_effect = SystemError() else: tenant_logic_mock.add_tenants.side_effect = ErrorStatus( status_code=404) tenant_logic_mock.delete_tenant.side_effect = ErrorStatus( status_code=404) return tenant_logic_mock
def delete_tenant(flavor_uuid, tenant_id, transaction_id): DataManager = di.resolver.unpack(delete_tenant) datamanager = DataManager() try: 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)) # if trying to delete the only one tenant then return value error if sql_flavor.visibility == "public": raise ValueError("{} is a public flavor, delete tenant action is not relevant".format(flavor_uuid)) if len(sql_flavor.flavor_tenants) == 1 and sql_flavor.flavor_tenants[0].tenant_id == tenant_id: raise ValueError( 'Private flavor must have at least one tenant') existing_region_names = sql_flavor.get_existing_region_names() sql_flavor.remove_tenant(tenant_id) datamanager.flush() # i want to get any exception created by previous actions against the database send_to_rds_if_needed(sql_flavor, existing_region_names, "put", transaction_id) datamanager.commit() except ErrorStatus as exp: LOG.log_exception("FlavorLogic - Failed to update flavor", exp) datamanager.rollback() raise except Exception as exp: LOG.log_exception("FlavorLogic - Failed to delete tenant", exp) datamanager.rollback() raise finally: datamanager.close()
def add_tenants(flavor_uuid, tenants, transaction_id): DataManager = di.resolver.unpack(add_tenants) datamanager = DataManager() try: 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)) if sql_flavor.visibility == "public": raise ErrorStatus(405, 'Cannot add tenant to a public flavor') existing_region_names = sql_flavor.get_existing_region_names() for tenant in tenants.tenants: if not isinstance(tenant, basestring): raise ValueError("tenant type must be a string type, got {} type".format(type(tenant))) db_tenant = FlavorTenant(tenant_id=tenant) sql_flavor.add_tenant(db_tenant) datamanager.flush() # i want to get any exception created by previous actions against the database send_to_rds_if_needed(sql_flavor, existing_region_names, "put", transaction_id) datamanager.commit() flavor = get_flavor_by_uuid(flavor_uuid) ret = TenantWrapper(tenants=flavor.flavor.tenants) return ret except (ErrorStatus, ValueError) as exp: LOG.log_exception("FlavorLogic - Failed to update flavor", exp) datamanager.rollback() raise except Exception as exp: datamanager.rollback() LOG.log_exception("FlavorLogic - Failed to add tenants", exp) if "conflicts with persistent instance" in str(exp.message): raise ConflictError(409, "One or more tenants already exist") raise finally: datamanager.close()
def add_regions(flavor_uuid, regions, transaction_id): DataManager = di.resolver.unpack(add_regions) datamanager = DataManager() try: 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)) existing_region_names = sql_flavor.get_existing_region_names() for region in regions.regions: if region.name == '' or region.name.isspace(): raise ErrorStatus(400, 'Cannot add region with an empty name') if region.type == "group": raise ErrorStatus(400, 'Adding \'group\' type region is supported only when creating a flavor') db_region = FlavorRegion(region_name=region.name, region_type='single') sql_flavor.add_region(db_region) datamanager.flush() # i want to get any exception created by previous actions against the database send_to_rds_if_needed(sql_flavor, existing_region_names, "put", transaction_id) datamanager.commit() flavor = get_flavor_by_uuid(flavor_uuid) ret = RegionWrapper(regions=flavor.flavor.regions) return ret except ErrorStatus as exp: LOG.log_exception("FlavorLogic - Failed to update flavor", exp) datamanager.rollback() raise exp except Exception as exp: LOG.log_exception("FlavorLogic - Failed to add regions", exp) datamanager.rollback() if "conflicts with persistent instance" in str(exp.message): raise ConflictError(409, "One or more regions already exists in Flavor") raise exp finally: datamanager.close()
def get_fixed_uuid(uuid_to_fix): """Fix a version 4 UUID.""" try: new_uuid = uuid.UUID(uuid_to_fix, version=4) if (uuid_to_fix == new_uuid.hex) or (uuid_to_fix == str(new_uuid)): # It is a version 4 UUID, remove its dashes return new_uuid.hex except ValueError: # Not a UUID (of any version) pass raise ErrorStatus(400, 'Flavor ID must be a version 4 UUID!')
def delete_extra_specs(flavor_id, transaction_id, extra_spec=None): DataManager = di.resolver.unpack(delete_extra_specs) datamanager = DataManager() try: LOG.debug("LOGIC - delete extra specs") datamanager.begin_transaction() 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( flavor_id)) existing_region_names = sql_flavor.get_existing_region_names() # calculate default flavor extra flavor_wrapper = FlavorWrapper.from_db_model(sql_flavor) default_extra_specs = flavor_wrapper.get_extra_spec_needed() # check if delete all or one if extra_spec: if not extra_spec_in_default(extra_spec, default_extra_specs): sql_flavor.remove_extra_spec(extra_spec) else: raise ErrorStatus(400, "Bad request, this key cannot be deleted") else: sql_flavor.delete_all_extra_specs() sql_flavor.add_extra_specs(default_extra_specs) datamanager.flush() # i want to get any exception created by previous actions against the database send_to_rds_if_needed(sql_flavor, existing_region_names, "put", transaction_id) datamanager.commit() except NotFoundError as exp: datamanager.rollback() LOG.log_exception("FlavorLogic - Flavor not found", exp) raise except ErrorStatus as exp: datamanager.rollback() LOG.log_exception("error in adding extra specs", exp) raise except Exception as exp: datamanager.rollback() LOG.log_exception("FlavorLogic - fail to delete extra spec", exp) raise finally: datamanager.close() return
def post(self, flavors): flavor_logic, utils = di.resolver.unpack(FlavorController) uuid = "FailedToGetFromUUIDGen" LOG.info("FlavorController - Createflavor: " + str(flavors)) authentication.authorize(request, 'flavor:create') try: if not flavors.flavor.id: uuid = utils.make_uuid() else: try: uuid = utils.create_existing_uuid( flavor_logic.get_fixed_uuid(flavors.flavor.id)) except TypeError: LOG.error("UUID already exist") raise ErrorStatus(409, 'UUID already exists') result = flavor_logic.create_flavor(flavors, uuid, request.transaction_id) LOG.info("FlavorController - Flavor Created: " + str(result)) event_details = 'Flavor {} created in regions: {}, tenants: {} with visibility: {}'.format( uuid, [r.name for r in flavors.flavor.regions], flavors.flavor.tenants, flavors.flavor.visibility) utils.audit_trail('create flavor', request.transaction_id, request.headers, uuid, event_details=event_details) return result except ErrorStatus as exception: LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, message=exception.message, status_code=exception.status_code) except ValueError as exception: LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, status_code=400, error_details=exception.message) except Exception as exception: LOG.log_exception("FlavorController - Failed to CreateFlavor", exception) raise err_utils.get_error(request.transaction_id, status_code=500, error_details=exception.message)
def _extra_specs_redefined(self, extra_specs_wrapper): # make sure at least one exit and not both at same time valid_json = not extra_specs_wrapper.extra_specs and not \ extra_specs_wrapper.os_extra_specs or \ extra_specs_wrapper.os_extra_specs and\ extra_specs_wrapper.extra_specs if valid_json: raise ErrorStatus( message="Invalid json. please provide supported json", status_code=400) if extra_specs_wrapper.extra_specs: extra_specs_wrapper.os_extra_specs = extra_specs_wrapper.extra_specs return extra_specs_wrapper
def get_flavor_by_uuid(flavor_uuid): DataManager, rds_proxy = di.resolver.unpack(get_flavor_by_uuid) datamanager = DataManager() flavor_record = datamanager.get_record('flavor') 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)) flavor_wrapper = FlavorWrapper.from_db_model(sql_flavor) update_region_statuses(flavor_wrapper.flavor, sql_flavor) return flavor_wrapper
def get_flavor_by_uuid_or_name(flavor_uuid_or_name): DataManager, rds_proxy = di.resolver.unpack(get_flavor_by_uuid) datamanager = DataManager() try: flavor_record = datamanager.get_record('flavor') sql_flavor = flavor_record.get_flavor_by_id_or_name(flavor_uuid_or_name) if not sql_flavor: raise ErrorStatus(404, 'flavor with id or name {0} not found'.format(flavor_uuid_or_name)) flavor_wrapper = FlavorWrapper.from_db_model(sql_flavor) update_region_statuses(flavor_wrapper.flavor, sql_flavor) except Exception as exp: LOG.log_exception("Failed to get_flavor_by_uuid_or_name", exp) raise finally: datamanager.close() return flavor_wrapper
def delete_flavor_by_uuid(flavor_uuid): # , transaction_id): rds_proxy, DataManager = di.resolver.unpack(delete_flavor_by_uuid) datamanager = DataManager() try: datamanager.begin_transaction() flavor_rec = datamanager.get_record('flavor') sql_flavor = flavor_rec.get_flavor_by_id(flavor_uuid) if sql_flavor is None: # The flavor does not exist, so the delete operation is # considered successful return existing_region_names = sql_flavor.get_existing_region_names() if len(existing_region_names) > 0: # Do not delete a flavor that still has some regions msg = "Cannot delete a flavor that has regions. " \ "Please delete the regions first and then " \ "delete the flavor." LOG.info(msg) raise ErrorStatus(405, msg) else: expected_status = 'Success' invalid_status = 'N/A' # Get status from RDS resp = rds_proxy.get_status(sql_flavor.id) if resp.status_code == 200: status_resp = resp.json() if 'status' in status_resp.keys(): LOG.debug( 'RDS returned status: {}'.format(status_resp['status'])) status = status_resp['status'] else: # Invalid response from RDS LOG.warning('Response from RDS did not contain status') status = invalid_status elif resp.status_code == 404: # Flavor not found in RDS, that means it never had any regions # So it is OK to delete it LOG.debug('Resource not found in RDS, so it is OK to delete') status = expected_status else: # Invalid status code from RDS LOG.warning('Invalid response code from RDS: {}'.format( resp.status_code)) status = invalid_status if status == invalid_status: LOG.error('Invalid flavor status received from RDS') raise ErrorStatus(500, "Invalid flavor status received from RDS") elif status != expected_status: msg = "The flavor 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)" LOG.error('Invalid flavor status received from RDS') raise ErrorStatus(409, msg) # OK to delete flavor_rec.delete_by_uuid(flavor_uuid) datamanager.flush() # i want to get any exception created by this delete datamanager.commit() except Exception as exp: LOG.log_exception("FlavorLogic - Failed to delete flavor", exp) datamanager.rollback() raise finally: datamanager.close()
def send_flavor(flavor_dict, transaction_id, action="put"): # action can be "post" for creating flavor or "delete" for deleting flavor requests = di.resolver.unpack(send_flavor) data = { "service_template": { "resource": { "resource_type": "flavor" }, "model": str(json.dumps(flavor_dict)), "tracking": { "external_id": "", "tracking_id": transaction_id } } } data_to_display = { "service_template": { "resource": { "resource_type": "flavor" }, "model": flavor_dict, "tracking": { "external_id": "", "tracking_id": transaction_id } } } pp = pprint.PrettyPrinter(width=30) pretty_text = pp.pformat(data_to_display) wrapper_json = json.dumps(data) headers['X-RANGER-Client'] = request.headers[ 'X-RANGER-Client'] if 'X-RANGER-Client' in request.headers else \ 'NA' headers['X-RANGER-Requester'] = request.headers[ 'X-RANGER-Requester'] if 'X-RANGER-Requester' in request.headers else \ '' LOG.debug( "Wrapper JSON before sending action: {0} to Rds Proxy {1}".format( action, pretty_text)) LOG.info("Sending to RDS Server: " + conf.api.rds_server.base + conf.api.rds_server.resources) if action == "post": resp = requests.post(conf.api.rds_server.base + conf.api.rds_server.resources, data=wrapper_json, headers=headers, verify=conf.verify) elif action == "put": resp = requests.put(conf.api.rds_server.base + conf.api.rds_server.resources, data=wrapper_json, headers=headers, verify=conf.verify) elif action == "delete": resp = requests.delete(conf.api.rds_server.base + conf.api.rds_server.resources, data=wrapper_json, headers=headers, verify=conf.verify) else: raise Exception( "Invalid action in RdxProxy.send_flavor(flavor_dict, transaction_id, action) action can be post or delete, got {0}" .format(action)) content = resp.content LOG.debug("return from rds server status code: {0} content: {1}".format( resp.status_code, resp.content)) 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)) return content