def load_paste_app(app_name=None): """Builds and returns a WSGI app from a paste config file. We assume the last config file specified in the supplied ConfigOpts object is the paste config file. :param app_name: name of the application to load :raises RuntimeError when config file cannot be located or application cannot be loaded from config file """ if app_name is None: app_name = cfg.CONF.prog # append the deployment flavor to the application name, # in order to identify the appropriate paste pipeline app_name += _get_deployment_flavor() conf_file = _get_deployment_config_file() if conf_file is None: raise RuntimeError(_("Unable to locate config file [%s]") % cfg.CONF.paste_deploy["api_paste_config"]) try: app = wsgi.paste_deploy_app(conf_file, app_name, cfg.CONF) # Log the options used when starting if we're in debug mode... if cfg.CONF.debug: cfg.CONF.log_opt_values(logging.getLogger(app_name), sys_logging.DEBUG) return app except (LookupError, ImportError) as e: raise RuntimeError( _("Unable to load %(app_name)s from " "configuration file %(conf_file)s." "\nGot: %(e)r") % {"app_name": app_name, "conf_file": conf_file, "e": e} )
def check_delete_complete(self, *args): if not self.resource_id: return True try: share = self._request_share() except Exception as ex: self.client_plugin().ignore_not_found(ex) return True else: # when share creation is not finished proceed listening if share.status == self.STATUS_DELETING: return False elif share.status in (self.STATUS_ERROR, self.STATUS_ERROR_DELETING): raise exception.ResourceInError( status_reason=_( 'Error during deleting share "{0}".' ).format(self.resource_id), resource_status=share.status) else: reason = _('Unknown status during deleting share ' '"{0}"').format(self.resource_id) raise exception.ResourceUnknownStatus( status_reason=reason, resource_status=share.status)
def validate_section(self, section, sub_section, data, allowed_keys): obj_name = section[:-1] err_msg = _('"%%s" is not a valid keyword inside a %s ' 'definition') % obj_name args = {'object_name': obj_name, 'sub_section': sub_section} message = _('Each %(object_name)s must contain a ' '%(sub_section)s key.') % args for name, attrs in sorted(data.items()): if not attrs: raise exception.StackValidationFailed(message=message) try: for attr, attr_value in six.iteritems(attrs): if attr not in allowed_keys: raise KeyError(err_msg % attr) if sub_section not in attrs: raise exception.StackValidationFailed(message=message) except AttributeError: message = _('"%(section)s" must contain a map of ' '%(obj_name)s maps. Found a [%(_type)s] ' 'instead') % {'section': section, '_type': type(attrs), 'obj_name': obj_name} raise exception.StackValidationFailed(message=message) except KeyError as e: # an invalid keyword was found raise exception.StackValidationFailed(message=e.args[0])
def __init__(self, data_type, description=None, default=None, schema=None, required=False, constraints=None, label=None): self._len = None self.label = label self.type = data_type if self.type not in self.TYPES: raise exception.InvalidSchemaError( message=_('Invalid type (%s)') % self.type) self.description = description self.required = required if isinstance(schema, type(self)): if self.type != self.LIST: msg = _('Single schema valid only for ' '%(ltype)s, not %(utype)s') % dict(ltype=self.LIST, utype=self.type) raise exception.InvalidSchemaError(message=msg) self.schema = AnyIndexDict(schema) else: self.schema = schema if self.schema is not None and self.type not in (self.LIST, self.MAP): msg = _('Schema valid only for %(ltype)s or ' '%(mtype)s, not %(utype)s') % dict(ltype=self.LIST, mtype=self.MAP, utype=self.type) raise exception.InvalidSchemaError(message=msg) self.constraints = constraints or [] self.default = default
def check_create_complete(self, *args): share_status = self._request_share().status if share_status == self.STATUS_CREATING: return False elif share_status == self.STATUS_AVAILABLE: LOG.info(_LI('Applying access rules to created Share.')) # apply access rules to created share. please note that it is not # possible to define rules for share with share_status = creating access_rules = self.properties.get(self.ACCESS_RULES) try: if access_rules: for rule in access_rules: self.client().shares.allow( share=self.resource_id, access_type=rule.get(self.ACCESS_TYPE), access=rule.get(self.ACCESS_TO), access_level=rule.get(self.ACCESS_LEVEL)) return True except Exception as ex: reason = _( 'Error during applying access rules to share "{0}". ' 'The root cause of the problem is the following: {1}.' ).format(self.resource_id, ex.message) raise exception.ResourceInError(status_reason=reason) elif share_status == self.STATUS_ERROR: reason = _('Error during creation of share "{0}"').format( self.resource_id) raise exception.ResourceInError(status_reason=reason, resource_status=share_status) else: reason = _('Unknown share_status during creation of share "{0}"' ).format(self.resource_id) raise exception.ResourceUnknownStatus( status_reason=reason, resource_status=share_status)
def validate(self): """Validate any of the provided params.""" super(LaunchConfiguration, self).validate() # now we don't support without snapshot_id in bdm bdm = self.properties.get(self.BLOCK_DEVICE_MAPPINGS) if bdm: for mapping in bdm: ebs = mapping.get(self.EBS) if ebs: snapshot_id = ebs.get(self.SNAPSHOT_ID) if not snapshot_id: msg = _("SnapshotId is missing, this is required " "when specifying BlockDeviceMappings.") raise exception.StackValidationFailed(message=msg) else: msg = _("Ebs is missing, this is required " "when specifying BlockDeviceMappings.") raise exception.StackValidationFailed(message=msg) # validate the 'InstanceId', 'ImageId' and 'InstanceType', # if without 'InstanceId', 'ImageId' and 'InstanceType' are required instance_id = self.properties.get(self.INSTANCE_ID) if not instance_id: image_id = self.properties.get(self.IMAGE_ID) instance_type = self.properties.get(self.INSTANCE_TYPE) if not image_id or not instance_type: msg = _('If without InstanceId, ' 'ImageId and InstanceType are required.') raise exception.StackValidationFailed(message=msg)
def _translate_section(self, section, sub_section, data, mapping): cfn_objects = {} obj_name = section[:-1] err_msg = _('"%%s" is not a valid keyword inside a %s ' 'definition') % obj_name for name, attrs in six.iteritems(data): cfn_object = {} if not attrs: args = {'object_name': obj_name, 'sub_section': sub_section} message = _('Each %(object_name)s must contain a ' '%(sub_section)s key.') % args raise exception.StackValidationFailed(message=message) try: for attr, attr_value in six.iteritems(attrs): cfn_attr = self._translate(attr, mapping, err_msg) cfn_object[cfn_attr] = attr_value cfn_objects[name] = cfn_object except AttributeError: message = _('"%(section)s" must contain a map of ' '%(obj_name)s maps. Found a [%(_type)s] ' 'instead') % {'section': section, '_type': type(attrs), 'obj_name': obj_name} raise exception.StackValidationFailed(message=message) except KeyError as e: # an invalid keyword was found raise exception.StackValidationFailed(message=six.text_type(e)) return cfn_objects
def validate(self): """Validate provided params.""" res = super(CinderVolume, self).validate() if res is not None: return res # Scheduler hints are only supported from Cinder API v2 if self.properties[self.CINDER_SCHEDULER_HINTS] and self.client().volume_api_version == 1: raise exception.StackValidationFailed( message=_("Scheduler hints are not supported by the current " "volume API.") ) # Multi attach is only supported from Cinder API v2 if self.properties[self.MULTI_ATTACH] and self.client().volume_api_version == 1: raise exception.StackValidationFailed( message=_( "Multiple attach is not supported by the current " "volume API. Use this property since " "Cinder API v2." ) ) # can not specify both image and imageRef image = self.properties.get(self.IMAGE) imageRef = self.properties.get(self.IMAGE_REF) if image and imageRef: raise exception.ResourcePropertyConflict(self.IMAGE, self.IMAGE_REF) # if not create from backup, need to check other create sources if not self.properties.get(self.BACKUP_ID): self._validate_create_sources()
def template(self): """ Get template file contents, either inline, from stack adopt data or from a URL, in JSON or YAML format. """ template_data = None if rpc_api.PARAM_ADOPT_STACK_DATA in self.data: adopt_data = self.data[rpc_api.PARAM_ADOPT_STACK_DATA] try: adopt_data = template_format.simple_parse(adopt_data) return adopt_data['template'] except (ValueError, KeyError) as ex: err_reason = _('Invalid adopt data: %s') % ex raise exc.HTTPBadRequest(err_reason) elif self.PARAM_TEMPLATE in self.data: template_data = self.data[self.PARAM_TEMPLATE] if isinstance(template_data, dict): return template_data elif self.PARAM_TEMPLATE_URL in self.data: url = self.data[self.PARAM_TEMPLATE_URL] LOG.debug('TemplateUrl %s' % url) try: template_data = urlfetch.get(url) except IOError as ex: err_reason = _('Could not retrieve template: %s') % ex raise exc.HTTPBadRequest(err_reason) if template_data is None: if self.patch: return None else: raise exc.HTTPBadRequest(_("No template specified")) with self.parse_error_check('Template'): return template_format.parse(template_data)
def validate(self): '''Validate the template. Validates the top-level sections of the template as well as syntax inside select sections. Some sections are not checked here but in code parts that are responsible for working with the respective sections (e.g. parameters are check by parameters schema class). ''' # check top-level sections for k in self.t.keys(): if k not in self.SECTIONS: raise exception.InvalidTemplateSection(section=k) # check resources for res in self[self.RESOURCES].values(): try: if not res or not res.get('Type'): message = _('Each Resource must contain ' 'a Type key.') raise exception.StackValidationFailed(message=message) except AttributeError: message = _('Resources must contain Resource. ' 'Found a [%s] instead') % type(res) raise exception.StackValidationFailed(message=message)
def _validate_create_sources(self): exclusive_options = self._build_exclusive_options() size = self.properties.get(self.SIZE) if size is None and len(exclusive_options) != 1: msg = _( 'If neither "%(backup_id)s" nor "%(size)s" is ' "provided, one and only one of " '"%(image)s", "%(image_ref)s", "%(source_vol)s", ' '"%(snapshot_id)s" must be specified, but currently ' "specified options: %(exclusive_options)s." ) % { "backup_id": self.BACKUP_ID, "size": self.SIZE, "image": self.IMAGE, "image_ref": self.IMAGE_REF, "source_vol": self.SOURCE_VOLID, "snapshot_id": self.SNAPSHOT_ID, "exclusive_options": exclusive_options, } raise exception.StackValidationFailed(message=msg) elif size and len(exclusive_options) > 1: msg = _( 'If "%(size)s" is provided, only one of ' '"%(image)s", "%(image_ref)s", "%(source_vol)s", ' '"%(snapshot_id)s" can be specified, but currently ' "specified options: %(exclusive_options)s." ) % { "size": self.SIZE, "image": self.IMAGE, "image_ref": self.IMAGE_REF, "source_vol": self.SOURCE_VOLID, "snapshot_id": self.SNAPSHOT_ID, "exclusive_options": exclusive_options, } raise exception.StackValidationFailed(message=msg)
def validate(self): super(Subnet, self).validate() subnetpool = self.properties[self.SUBNETPOOL] prefixlen = self.properties[self.PREFIXLEN] cidr = self.properties[self.CIDR] if subnetpool and cidr: raise exception.ResourcePropertyConflict(self.SUBNETPOOL, self.CIDR) if not subnetpool and not cidr: raise exception.PropertyUnspecifiedError(self.SUBNETPOOL, self.CIDR) if prefixlen and cidr: raise exception.ResourcePropertyConflict(self.PREFIXLEN, self.CIDR) ra_mode = self.properties[self.IPV6_RA_MODE] address_mode = self.properties[self.IPV6_ADDRESS_MODE] if (self.properties[self.IP_VERSION] == 4) and ( ra_mode or address_mode): msg = _('ipv6_ra_mode and ipv6_address_mode are not supported ' 'for ipv4.') raise exception.StackValidationFailed(message=msg) if ra_mode and address_mode and (ra_mode != address_mode): msg = _('When both ipv6_ra_mode and ipv6_address_mode are set, ' 'they must be equal.') raise exception.StackValidationFailed(message=msg) gateway_ip = self.properties.get(self.GATEWAY_IP) if (gateway_ip and gateway_ip not in ['~', ''] and not netutils.is_valid_ip(gateway_ip)): msg = (_('Gateway IP address "%(gateway)s" is in ' 'invalid format.'), gateway_ip) raise exception.StackValidationFailed(message=msg)
def check_create_complete(self, data): attributes = self._show_resource() status = attributes['status'] if status == 'PENDING_CREATE': return False elif status == 'ACTIVE': vip_attributes = self.client().show_vip( self.metadata_get()['vip'])['vip'] vip_status = vip_attributes['status'] if vip_status == 'PENDING_CREATE': return False if vip_status == 'ACTIVE': return True if vip_status == 'ERROR': raise exception.ResourceInError( resource_status=vip_status, status_reason=_('error in vip')) raise exception.ResourceUnknownStatus( resource_status=vip_status, result=_('Pool creation failed due to vip')) elif status == 'ERROR': raise exception.ResourceInError( resource_status=status, status_reason=_('error in pool')) else: raise exception.ResourceUnknownStatus( resource_status=status, result=_('Pool creation failed'))
def validate(self): """Validate for Rackspace Cloud specific parameters""" super(CloudServer, self).validate() # check if image, flavor combination is valid flavor = self.properties[self.FLAVOR] flavor_obj = self.client_plugin().get_flavor(flavor) fl_xtra_specs = flavor_obj.to_dict().get(self.FLAVOR_EXTRA_SPECS, {}) flavor_type = fl_xtra_specs.get(self.FLAVOR_CLASS, None) image = self.properties.get(self.IMAGE) if not image: if flavor_type in self.NON_BFV: msg = _('Flavor %s cannot be booted from volume.') % flavor raise exception.StackValidationFailed(message=msg) else: # we cannot determine details of the attached volume, so this # is all the validation possible return image_obj = self.client_plugin('glance').get_image(image) if not self._image_flavor_class_match(flavor_type, image_obj): msg = _('Flavor %(flavor)s cannot be used with image ' '%(image)s.') % {'image': image, 'flavor': flavor} raise exception.StackValidationFailed(message=msg) if flavor_type in self.BFV_VOLUME_REQUIRED: msg = _('Flavor %(flavor)s must be booted from volume, ' 'but image %(image)s was also specified.') % { 'flavor': flavor, 'image': image} raise exception.StackValidationFailed(message=msg)
def _validate_against_facade(self, facade_cls): facade_schemata = properties.schemata(facade_cls.properties_schema) for n, fs in facade_schemata.items(): if fs.required and n not in self.properties_schema: msg = (_("Required property %(n)s for facade %(type)s " "missing in provider") % {'n': n, 'type': self.type()}) raise exception.StackValidationFailed(message=msg) ps = self.properties_schema.get(n) if (n in self.properties_schema and (fs.allowed_param_prop_type() != ps.type)): # Type mismatch msg = (_("Property %(n)s type mismatch between facade %(type)s" " (%(fs_type)s) and provider (%(ps_type)s)") % { 'n': n, 'type': self.type(), 'fs_type': fs.type, 'ps_type': ps.type}) raise exception.StackValidationFailed(message=msg) for n, ps in self.properties_schema.items(): if ps.required and n not in facade_schemata: # Required property for template not present in facade msg = (_("Provider requires property %(n)s " "unknown in facade %(type)s") % { 'n': n, 'type': self.type()}) raise exception.StackValidationFailed(message=msg) facade_attrs = facade_cls.attributes_schema.copy() facade_attrs.update(facade_cls.base_attributes_schema) for attr in facade_attrs: if attr not in self.attributes_schema: msg = (_("Attribute %(attr)s for facade %(type)s " "missing in provider") % { 'attr': attr, 'type': self.type()}) raise exception.StackValidationFailed(message=msg)
def validate(self): """Validate the provided params.""" super(RBACPolicy, self).validate() action = self.properties[self.ACTION] obj_type = self.properties[self.OBJECT_TYPE] obj_id_or_name = self.properties[self.OBJECT_ID] # Validate obj_type and action per SUPPORTED_TYPES_ACTIONS. if obj_type not in self.SUPPORTED_TYPES_ACTIONS: msg = (_("Invalid object_type: %(obj_type)s. " "Valid object_type :%(value)s") % {'obj_type': obj_type, 'value': self.SUPPORTED_TYPES_ACTIONS.keys()}) raise exception.StackValidationFailed(message=msg) if action not in self.SUPPORTED_TYPES_ACTIONS[obj_type]: msg = (_("Invalid action %(action)s for object type " "%(obj_type)s. Valid actions :%(value)s") % {'action': action, 'obj_type': obj_type, 'value': self.SUPPORTED_TYPES_ACTIONS[obj_type]}) raise exception.StackValidationFailed(message=msg) # Make sure the value of object_id is correct. neutronV20.find_resourceid_by_name_or_id(self.client(), obj_type, obj_id_or_name)
def _check_rax_automation_complete(self, server): if not self._managed_cloud_started_event_sent: msg = _("Waiting for Rackspace Cloud automation to complete") self._add_event(self.action, self.status, msg) self._managed_cloud_started_event_sent = True if 'rax_service_level_automation' not in server.metadata: LOG.debug("Cloud server does not have the " "rax_service_level_automation metadata tag yet") return False mc_status = server.metadata['rax_service_level_automation'] LOG.debug("Rackspace Cloud automation status: %s" % mc_status) if mc_status == self.SM_STATUS_IN_PROGRESS: return False elif mc_status == self.SM_STATUS_COMPLETE: msg = _("Rackspace Cloud automation has completed") self._add_event(self.action, self.status, msg) return True elif mc_status == self.SM_STATUS_BUILD_ERROR: raise exception.Error(_("Rackspace Cloud automation failed")) else: raise exception.Error(_("Unknown Rackspace Cloud automation " "status: %s") % mc_status)
def validate(self): ''' Validate any of the provided params ''' res = super(Instance, self).validate() if res: return res # check validity of security groups vs. network interfaces security_groups = self._get_security_groups() if security_groups and self.properties.get(self.NETWORK_INTERFACES): raise exception.ResourcePropertyConflict( '/'.join([self.SECURITY_GROUPS, self.SECURITY_GROUP_IDS]), self.NETWORK_INTERFACES) # check bdm property # now we don't support without snapshot_id in bdm bdm = self.properties.get(self.BLOCK_DEVICE_MAPPINGS) if bdm: for mapping in bdm: ebs = mapping.get(self.EBS) if ebs: snapshot_id = ebs.get(self.SNAPSHOT_ID) if not snapshot_id: msg = _("SnapshotId is missing, this is required " "when specifying BlockDeviceMappings.") raise exception.StackValidationFailed(message=msg) else: msg = _("Ebs is missing, this is required " "when specifying BlockDeviceMappings.") raise exception.StackValidationFailed(message=msg)
def handle_resume(self): ''' Resume an instance - note we do not wait for the ACTIVE state, this is polled for by check_resume_complete in a similar way to the create logic so we can take advantage of coroutines ''' if self.resource_id is None: raise exception.Error(_('Cannot resume %s, resource_id not set') % self.name) try: server = self.nova().servers.get(self.resource_id) except Exception as e: if self.client_plugin().is_not_found(e): raise exception.NotFound(_('Failed to find instance %s') % self.resource_id) else: raise else: # if the instance has been resumed successful, # no need to resume again if self.client_plugin().get_status(server) != 'ACTIVE': LOG.debug("resuming instance %s" % self.resource_id) server.resume() return server.id
def _parse_args(self): if not isinstance(self.args, collections.Mapping): raise TypeError(_('Arguments to "%s" must be a map') % self.fn_name) try: for_each = self.args['for_each'] template = self.args['template'] except (KeyError, TypeError): example = ('''repeat: template: This is %var% for_each: %var%: ['a', 'b', 'c']''') raise KeyError(_('"repeat" syntax should be %s') % example) if not isinstance(for_each, collections.Mapping): raise TypeError(_('The "for_each" argument to "%s" must contain ' 'a map') % self.fn_name) for v in six.itervalues(for_each): if not isinstance(v, list): raise TypeError(_('The values of the "for_each" argument to ' '"%s" must be lists') % self.fn_name) return for_each, template
def check_trailing_spaces(self): for cls in self.resources_classes: cls_file = open(cls.__module__.replace('.', '/') + '.py') lines = [line.strip() for line in cls_file.readlines()] idx = 0 kwargs = {'path': cls.__module__} while idx < len(lines): if ('properties_schema' in lines[idx] or 'attributes_schema' in lines[idx]): level = len(re.findall('(\{|\()', lines[idx])) level -= len(re.findall('(\}|\))', lines[idx])) idx += 1 while level != 0: level += len(re.findall('(\{|\()', lines[idx])) level -= len(re.findall('(\}|\))', lines[idx])) if re.search("^((\'|\") )", lines[idx]): kwargs.update( {'details': 'line %s' % idx, 'message': _('Trailing whitespace should ' 'be on previous line'), 'snippet': lines[idx]}) self.print_guideline_error(**kwargs) elif (re.search("(\S(\'|\"))$", lines[idx - 1]) and re.search("^((\'|\")\S)", lines[idx])): kwargs.update( {'details': 'line %s' % (idx - 1), 'message': _('Omitted whitespace at the ' 'end of the line'), 'snippet': lines[idx - 1]}) self.print_guideline_error(**kwargs) idx += 1 idx += 1
def contribute_properties(self, parent): if not self.props_schemata: return props = dict((k, v) for k, v in self.props_schemata.items() if v.support_status.status != support.HIDDEN) required_props = dict((k, v) for k, v in props.items() if v.required) if required_props: section = self._section( parent, _('Required Properties'), '%s-props-req') for prop_key, prop in sorted(required_props.items(), self.cmp_prop): self.contribute_property(section, prop_key, prop) optional_props = dict((k, v) for k, v in props.items() if not v.required) if optional_props: section = self._section( parent, _('Optional Properties'), '%s-props-opt') for prop_key, prop in sorted(optional_props.items(), self.cmp_prop): self.contribute_property(section, prop_key, prop)
def template_data(self): # we want to have the latest possible template. # 1. look in files # 2. try download # 3. look in the db reported_excp = None t_data = self.stack.t.files.get(self.template_name) if not t_data and self.template_name.endswith((".yaml", ".template")): try: t_data = urlfetch.get(self.template_name, allowed_schemes=self.allowed_schemes) except (exceptions.RequestException, IOError) as r_exc: reported_excp = ValueError(_("Could not fetch remote template " "'%(name)s': %(exc)s") % { 'name': self.template_name, 'exc': str(r_exc)}) if t_data is None: if self.nested() is not None: t_data = json.dumps(self.nested().t.t) if t_data is not None: self.stack.t.files[self.template_name] = t_data return t_data if reported_excp is None: reported_excp = ValueError(_('Unknown error retrieving %s') % self.template_name) raise reported_excp
def result(self): LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ result ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ result ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ result ")) template = function.resolve(self._string) mapping = function.resolve(self._mapping) if not isinstance(template, six.string_types): raise TypeError(_('"%s" template must be a string') % self.fn_name) if not isinstance(mapping, collections.Mapping): raise TypeError(_('"%s" params must be a map') % self.fn_name) def replace(string, change): LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ replace ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ replace ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Replace/ replace ")) placeholder, value = change if not isinstance(placeholder, six.string_types): raise TypeError(_('"%s" param placeholders must be strings') % self.fn_name) if value is None: value = '' if not isinstance(value, (six.string_types, six.integer_types, float, bool)): raise TypeError(_('"%s" params must be strings or numbers') % self.fn_name) return string.replace(placeholder, unicode(value)) return reduce(replace, six.iteritems(mapping), template)
def validate(self): super(RemoteStack, self).validate() try: self.heat() except Exception as ex: exc_info = dict(region=self._region_name, exc=six.text_type(ex)) msg = _('Cannot establish connection to Heat endpoint at region ' '"%(region)s" due to "%(exc)s"') % exc_info raise exception.StackValidationFailed(message=msg) try: params = self.properties[self.PARAMETERS] env = environment.get_child_environment(self.stack.env, params) tmpl = template_format.parse(self.properties[self.TEMPLATE]) args = { 'template': tmpl, 'files': self.stack.t.files, 'environment': env.user_env_as_dict(), } self.heat().stacks.validate(**args) except Exception as ex: exc_info = dict(region=self._region_name, exc=six.text_type(ex)) LOG.error(_LE('exception: %s'), type(ex)) msg = _('Failed validating stack template using Heat endpoint at ' 'region "%(region)s" due to "%(exc)s"') % exc_info raise exception.StackValidationFailed(message=msg)
def get_template_class(template_data): global _template_classes if _template_classes is None: mgr = _get_template_extension_manager() _template_classes = dict((tuple(name.split('.')), mgr[name].plugin) for name in mgr.names()) available_versions = _template_classes.keys() version = get_version(template_data, available_versions) version_type = version[0] try: return _template_classes[version] except KeyError: av_list = [v for k, v in available_versions if k == version_type] msg_data = {'version': ': '.join(version), 'version_type': version_type, 'available': ', '.join(v for v in av_list)} if len(av_list) > 1: explanation = _('"%(version)s". "%(version_type)s" ' 'should be one of: %(available)s') % msg_data else: explanation = _('"%(version)s". "%(version_type)s" ' 'should be: %(available)s') % msg_data raise exception.InvalidTemplateVersion(explanation=explanation)
def result(self): LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ result ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ result ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ result ")) strings = function.resolve(self._strings) if strings is None: strings = [] if (isinstance(strings, six.string_types) or not isinstance(strings, collections.Sequence)): raise TypeError(_('"%s" must operate on a list') % self.fn_name) delim = function.resolve(self._delim) if not isinstance(delim, six.string_types): raise TypeError(_('"%s" delimiter must be a string') % self.fn_name) def ensure_string(s): LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ ensure_string ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ ensure_string ")) LOG.info(_LI("soumiyajit:: /home/pankaj/python_program/logs/cfn/functions.py/Class Join/ ensure_string ")) if s is None: return '' if not isinstance(s, six.string_types): raise TypeError( _('Items to join must be strings %s') % (repr(s)[:200])) return s return delim.join(ensure_string(s) for s in strings)
def handle_update(self, json_snippet, tmpl_diff, prop_diff): try: obj_0 = self.vnc_lib().virtual_DNS_read( id=self.resource_id ) except: raise Exception(_('virtual-DNS %s not found.') % self.name) if prop_diff.get(self.DISPLAY_NAME) is not None: obj_0.set_display_name(prop_diff.get(self.DISPLAY_NAME)) if prop_diff.get(self.VIRTUAL_DNS_DATA) is not None: obj_1 = vnc_api.VirtualDnsType() if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DOMAIN_NAME) is not None: obj_1.set_domain_name(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DOMAIN_NAME)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DYNAMIC_RECORDS_FROM_CLIENT) is not None: obj_1.set_dynamic_records_from_client(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DYNAMIC_RECORDS_FROM_CLIENT)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_RECORD_ORDER) is not None: obj_1.set_record_order(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_RECORD_ORDER)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DEFAULT_TTL_SECONDS) is not None: obj_1.set_default_ttl_seconds(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_DEFAULT_TTL_SECONDS)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_NEXT_VIRTUAL_DNS) is not None: obj_1.set_next_virtual_DNS(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_NEXT_VIRTUAL_DNS)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_FLOATING_IP_RECORD) is not None: obj_1.set_floating_ip_record(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_FLOATING_IP_RECORD)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_EXTERNAL_VISIBLE) is not None: obj_1.set_external_visible(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_EXTERNAL_VISIBLE)) if prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_REVERSE_RESOLUTION) is not None: obj_1.set_reverse_resolution(prop_diff.get(self.VIRTUAL_DNS_DATA, {}).get(self.VIRTUAL_DNS_DATA_REVERSE_RESOLUTION)) obj_0.set_virtual_DNS_data(obj_1) try: self.vnc_lib().virtual_DNS_update(obj_0) except: raise Exception(_('virtual-DNS %s could not be updated.') % self.name)
def validate(self): ''' Validate that a parameter belongs to only one Parameter Group and that each parameter name references a valid parameter. ''' LOG.debug('Validating Parameter Groups.') LOG.debug(self.parameter_names) if self.parameter_groups is not None: #Loop through groups and validate parameters grouped_parameters = [] for group in self.parameter_groups: parameters = group.get(PARAMETERS) if parameters is None: raise StackValidationFailed(message=_( 'Parameters must be provided for ' 'each Parameter Group.')) for param in parameters: #Check if param has been added to a previous group if param in grouped_parameters: raise StackValidationFailed(message=_( 'The %s parameter must be assigned to one ' 'Parameter Group only.') % param) else: grouped_parameters.append(param) #Check that grouped parameter references a valid Parameter if param not in self.parameter_names: raise StackValidationFailed(message=_( 'The Parameter name (%s) does not reference ' 'an existing parameter.') % param)
def _validate_create_sources(self): exclusive_options, allow_no_size_ops = self._build_exclusive_options() size = self.properties.get(self.SIZE) if (size is None and (len(allow_no_size_ops) != 1 or len(exclusive_options) != 1)): msg = (_('If neither "%(backup_id)s" nor "%(size)s" is ' 'provided, one and only one of "%(source_vol)s", ' '"%(snapshot_id)s" must be specified, but currently ' 'specified options: %(exclusive_options)s.') % {'backup_id': self.BACKUP_ID, 'size': self.SIZE, 'source_vol': self.SOURCE_VOLID, 'snapshot_id': self.SNAPSHOT_ID, 'exclusive_options': exclusive_options}) raise exception.StackValidationFailed(message=msg) elif size and len(exclusive_options) > 1: msg = (_('If "%(size)s" is provided, only one of ' '"%(image)s", "%(image_ref)s", "%(source_vol)s", ' '"%(snapshot_id)s" can be specified, but currently ' 'specified options: %(exclusive_options)s.') % {'size': self.SIZE, 'image': self.IMAGE, 'image_ref': self.IMAGE_REF, 'source_vol': self.SOURCE_VOLID, 'snapshot_id': self.SNAPSHOT_ID, 'exclusive_options': exclusive_options}) raise exception.StackValidationFailed(message=msg)
class InvalidContentType(HeatException): msg_fmt = _("Invalid content type %(content_type)s")
class InterfaceAttachFailed(HeatException): msg_fmt = _("Failed to attach interface (%(port)s) " "to server (%(server)s)")
class EventSendFailed(HeatException): msg_fmt = _("Failed to send message to stack (%(stack_name)s) " "on other engine (%(engine_id)s)")
class StopActionFailed(HeatException): msg_fmt = _("Failed to stop stack (%(stack_name)s) on other engine " "(%(engine_id)s)")
class ActionInProgress(HeatException): msg_fmt = _("Stack %(stack_name)s already has an action (%(action)s) " "in progress.")
class StackResourceLimitExceeded(HeatException): msg_fmt = _('Maximum resources per stack exceeded.')
class RequestLimitExceeded(HeatException): msg_fmt = _('Request limit exceeded: %(message)s')
class EgressRuleNotAllowed(HeatException): msg_fmt = _("Egress rules are only allowed when " "Neutron is used and the 'VpcId' property is set.")
def __init__(self, status_reason=_('Unknown'), **kwargs): super(ResourceInError, self).__init__(status_reason=status_reason, **kwargs)
def __init__(self, msg_fmt=_('Not found')): self.msg_fmt = msg_fmt super(NotFound, self).__init__()
def __init__(self, resource_name='Unknown'): msg = _("The Resource %s requires replacement.") % resource_name super(Exception, self).__init__(six.text_type(msg))
def __init__(self, resource_name='Unknown'): msg = _("The resource %s is already being updated.") % resource_name super(Exception, self).__init__(six.text_type(msg))
class ResourcePropertyDependency(HeatException): msg_fmt = _('%(prop1)s cannot be specified without %(prop2)s.')
def __init__(self, result=_('Resource failed'), status_reason=_('Unknown'), **kwargs): super(ResourceUnknownStatus, self).__init__( result=result, status_reason=status_reason, **kwargs)
class ResourceActionNotSupported(HeatException): msg_fmt = _("%(action)s is not supported for resource.")
class ResourcePropertyValueDependency(HeatException): msg_fmt = _('%(prop1)s property should only be specified ' 'for %(prop2)s with value %(value)s.')
class WatchRuleNotFound(EntityNotFound): """Keep this for AWS compatibility.""" msg_fmt = _("The Watch Rule (%(watch_name)s) could not be found.")
class ResourceActionRestricted(HeatException): msg_fmt = _("%(action)s is restricted for resource.")
class ResourceNotAvailable(HeatException): msg_fmt = _("The Resource (%(resource_name)s) is not available.")
class NotSupported(HeatException): msg_fmt = _("%(feature)s is not supported.")
class InvalidBreakPointHook(HeatException): msg_fmt = _("%(message)s")
class ClientNotAvailable(HeatException): msg_fmt = _("The client (%(client_name)s) is not available.")
class SnapshotNotFound(EntityNotFound): msg_fmt = _("The Snapshot (%(snapshot)s) for Stack (%(stack)s) " "could not be found.")
class InvalidRestrictedAction(HeatException): msg_fmt = _("%(message)s")
class InvalidSchemaError(HeatException): msg_fmt = _("%(message)s")
class InvalidGlobalResource(HeatException): msg_fmt = _("There was an error loading the definition of the global " "resource type %(type_name)s.")
class InvalidTenant(HeatException): msg_fmt = _("Searching Tenant %(target)s " "from Tenant %(actual)s forbidden.")
class ResourceNotFound(EntityNotFound): msg_fmt = _("The Resource (%(resource_name)s) could not be found " "in Stack %(stack_name)s.")
class PhysicalResourceNameAmbiguity(HeatException): msg_fmt = _( "Multiple physical resources were found with name (%(name)s).")
class StackExists(HeatException): msg_fmt = _("The Stack (%(stack_name)s) already exists.")