Esempio n. 1
0
    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            return 'Resource update already requested'

        if not json_snippet:
            return 'Must specify json snippet for resource update!'

        logger.info('updating %s' % str(self))

        result = self.UPDATE_NOT_IMPLEMENTED
        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data, self.name)
            properties.validate()
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            self.state_set(self.UPDATE_FAILED, str(ex))
            return str(ex) or "Error : %s" % type(ex)
        else:
            # If resource was updated (with or without interruption),
            # then we set the resource to UPDATE_COMPLETE
            if not result == self.UPDATE_REPLACE:
                self.t = self.stack.resolve_static_data(json_snippet)
                self.state_set(self.UPDATE_COMPLETE)
            return result
Esempio n. 2
0
    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            return 'Resource update already requested'

        if not json_snippet:
            return 'Must specify json snippet for resource update!'

        logger.info('updating %s' % str(self))

        result = self.UPDATE_NOT_IMPLEMENTED
        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data,
                                    self.name)
            properties.validate()
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            self.state_set(self.UPDATE_FAILED, str(ex))
            return str(ex) or "Error : %s" % type(ex)
        else:
            # If resource was updated (with or without interruption),
            # then we set the resource to UPDATE_COMPLETE
            if not result == self.UPDATE_REPLACE:
                self.t = self.stack.resolve_static_data(json_snippet)
                self.state_set(self.UPDATE_COMPLETE)
            return result
Esempio n. 3
0
    def update(self, after, before=None):
        """
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        """
        if before is None:
            before = self.parsed_template()

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS), (self.UPDATE, self.IN_PROGRESS)):
            raise exception.ResourceFailure(Exception("Resource update already requested"))

        logger.info("updating %s" % str(self))

        try:
            self.state_set(self.UPDATE, self.IN_PROGRESS)
            properties = Properties(
                self.properties_schema, after.get("Properties", {}), self.stack.resolve_runtime_data, self.name
            )
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, "handle_update", None)):
                result = self.handle_update(after, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception("update %s : %s" % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.UPDATE, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(self.UPDATE, self.COMPLETE)
Esempio n. 4
0
    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        assert json_snippet is not None, 'Must specify update json snippet'

        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            raise exception.ResourceFailure(Exception(
                'Resource update already requested'))

        logger.info('updating %s' % str(self))

        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data,
                                    self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(json_snippet)
            prop_diff = self.update_template_diff_properties(json_snippet)
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.UPDATE_FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(json_snippet)
            self.state_set(self.UPDATE_COMPLETE)
Esempio n. 5
0
    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        assert json_snippet is not None, 'Must specify update json snippet'

        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            raise exception.ResourceFailure(
                Exception('Resource update already requested'))

        logger.info('updating %s' % str(self))

        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data, self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(json_snippet)
            prop_diff = self.update_template_diff_properties(json_snippet)
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.UPDATE_FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(json_snippet)
            self.state_set(self.UPDATE_COMPLETE)
Esempio n. 6
0
    def update(self, after, before=None, prev_resource=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        (cur_class_def, cur_ver) = self.implementation_signature()
        prev_ver = cur_ver
        if prev_resource is not None:
            (prev_class_def,
             prev_ver) = prev_resource.implementation_signature()
            if prev_class_def != cur_class_def:
                raise UpdateReplace(self.name)

        if before is None:
            before = self.parsed_template()
        if prev_ver == cur_ver and before == after:
            return

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS),
                                          (self.ADOPT, self.IN_PROGRESS)):
            exc = Exception(_('Resource update already requested'))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.updated_time = datetime.utcnow()
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data,
                                    self.name,
                                    self.context)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            with excutils.save_and_reraise_exception():
                logger.debug(_("Resource %s update requires replacement") %
                             self.name)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.json_snippet = copy.deepcopy(after)
            self.reparse()
            self.state_set(action, self.COMPLETE)
Esempio n. 7
0
    def update(self, after, before=None, prev_resource=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        (cur_class_def, cur_ver) = self.implementation_signature()
        prev_ver = cur_ver
        if prev_resource is not None:
            (prev_class_def,
             prev_ver) = prev_resource.implementation_signature()
            if prev_class_def != cur_class_def:
                raise UpdateReplace(self.name)

        if before is None:
            before = self.parsed_template()
        if prev_ver == cur_ver and before == after:
            return

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS),
                                          (self.ADOPT, self.IN_PROGRESS)):
            exc = Exception(_('Resource update already requested'))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.updated_time = datetime.utcnow()
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data,
                                    self.name,
                                    self.context)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            with excutils.save_and_reraise_exception():
                logger.debug(_("Resource %s update requires replacement") %
                             self.name)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.json_snippet = copy.deepcopy(after)
            self.reparse()
            self.state_set(action, self.COMPLETE)
Esempio n. 8
0
    def update(self, after, before=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        if before is None:
            before = self.parsed_template()

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS)):
            exc = Exception(_('Resource update already requested'))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data,
                                    self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            logger.debug(_("Resource %s update requires replacement") %
                         self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)
Esempio n. 9
0
    def update(self, after, before=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        if before is None:
            before = self.parsed_template()

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS)):
            exc = Exception('Resource update already requested')
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data, self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)
Esempio n. 10
0
class InstanceGroup(stack_resource.StackResource):
    tags_schema = {
        'Key': {
            'Type': 'String',
            'Required': True
        },
        'Value': {
            'Type': 'String',
            'Required': True
        }
    }
    properties_schema = {
        'AvailabilityZones': {
            'Required': True,
            'Type': 'List',
            'Description': _('Not Implemented.')
        },
        'LaunchConfigurationName': {
            'Required': True,
            'Type': 'String',
            'UpdateAllowed': True,
            'Description': _('Name of LaunchConfiguration resource.')
        },
        'Size': {
            'Required': True,
            'Type': 'Number',
            'UpdateAllowed': True,
            'Description': _('Desired number of instances.')
        },
        'LoadBalancerNames': {
            'Type': 'List',
            'Description': _('List of LoadBalancer resources.')
        },
        'Tags': {
            'Type': 'List',
            'Schema': {
                'Type': 'Map',
                'Schema': tags_schema
            },
            'Description': _('Tags to attach to this group.')
        }
    }
    update_allowed_keys = (
        'Properties',
        'UpdatePolicy',
    )
    attributes_schema = {
        "InstanceList":
        _("A comma-delimited list of server ip addresses. "
          "(Heat extension).")
    }
    rolling_update_schema = {
        'MinInstancesInService':
        properties.Schema(properties.Schema.NUMBER, default=0),
        'MaxBatchSize':
        properties.Schema(properties.Schema.NUMBER, default=1),
        'PauseTime':
        properties.Schema(properties.Schema.STRING, default='PT0S')
    }
    update_policy_schema = {
        'RollingUpdate':
        properties.Schema(properties.Schema.MAP, schema=rolling_update_schema)
    }

    def __init__(self, name, json_snippet, stack):
        """
        UpdatePolicy is currently only specific to InstanceGroup and
        AutoScalingGroup. Therefore, init is overridden to parse for the
        UpdatePolicy.
        """
        super(InstanceGroup, self).__init__(name, json_snippet, stack)
        self.update_policy = Properties(self.update_policy_schema,
                                        self.t.get('UpdatePolicy', {}),
                                        parent_name=self.name)

    def validate(self):
        """
        Add validation for update_policy
        """
        super(InstanceGroup, self).validate()

        if self.update_policy:
            self.update_policy.validate()
            policy_name = self.update_policy_schema.keys()[0]
            if self.update_policy[policy_name]:
                pause_time = self.update_policy[policy_name]['PauseTime']
                if iso8601utils.parse_isoduration(pause_time) > 3600:
                    raise ValueError('Maximum PauseTime is 1 hour.')

    def get_instance_names(self):
        """Get a list of resource names of the instances in this InstanceGroup.

        Failed resources will be ignored.
        """
        return [r.name for r in self.get_instances()]

    def get_instances(self):
        """Get a list of all the instance resources managed by this group.

        Sort the list of instances first by created_time then by name.
        """
        resources = []
        if self.nested():
            resources = [
                resource for resource in self.nested().itervalues()
                if resource.status != resource.FAILED
            ]
        return sorted(resources, key=lambda r: (r.created_time, r.name))

    def handle_create(self):
        """Create a nested stack and add the initial resources to it."""
        num_instances = int(self.properties['Size'])
        initial_template = self._create_template(num_instances)
        return self.create_with_template(initial_template, {})

    def check_create_complete(self, task):
        """
        When stack creation is done, update the load balancer.

        If any instances failed to be created, delete them.
        """
        done = super(InstanceGroup, self).check_create_complete(task)
        if done:
            self._lb_reload()
        return done

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """
        If Properties has changed, update self.properties, so we
        get the new values during any subsequent adjustment.
        """
        if tmpl_diff:
            # parse update policy
            if 'UpdatePolicy' in tmpl_diff:
                self.update_policy = Properties(self.update_policy_schema,
                                                json_snippet.get(
                                                    'UpdatePolicy', {}),
                                                parent_name=self.name)

        if prop_diff:
            self.properties = Properties(self.properties_schema,
                                         json_snippet.get('Properties', {}),
                                         self.stack.resolve_runtime_data,
                                         self.name)

            # Replace instances first if launch configuration has changed
            if (self.update_policy['RollingUpdate']
                    and 'LaunchConfigurationName' in prop_diff):
                policy = self.update_policy['RollingUpdate']
                self._replace(int(policy['MinInstancesInService']),
                              int(policy['MaxBatchSize']), policy['PauseTime'])

            # Get the current capacity, we may need to adjust if
            # Size has changed
            if 'Size' in prop_diff:
                inst_list = self.get_instances()
                if len(inst_list) != int(self.properties['Size']):
                    self.resize(int(self.properties['Size']))

    def _tags(self):
        """
        Make sure that we add a tag that Ceilometer can pick up.
        These need to be prepended with 'metering.'.
        """
        tags = self.properties.get('Tags') or []
        for t in tags:
            if t['Key'].startswith('metering.'):
                # the user has added one, don't add another.
                return tags
        return tags + [{
            'Key': 'metering.groupname',
            'Value': self.FnGetRefId()
        }]

    def handle_delete(self):
        return self.delete_nested()

    def _get_instance_definition(self):
        conf_name = self.properties['LaunchConfigurationName']
        conf = self.stack.resource_by_refid(conf_name)
        instance_definition = copy.deepcopy(conf.t)
        instance_definition['Type'] = 'AWS::EC2::Instance'
        instance_definition['Properties']['Tags'] = self._tags()
        if self.properties.get('VPCZoneIdentifier'):
            instance_definition['Properties']['SubnetId'] = \
                self.properties['VPCZoneIdentifier'][0]
        # resolve references within the context of this stack.
        return self.stack.resolve_runtime_data(instance_definition)

    def _create_template(self, num_instances, num_replace=0):
        """
        Create the template for the nested stack of existing and new instances

        For rolling update, if launch configuration is different, the
        instance definition should come from the existing instance instead
        of using the new launch configuration.
        """
        instances = self.get_instances()[-num_instances:]
        instance_definition = self._get_instance_definition()
        num_create = num_instances - len(instances)
        num_replace -= num_create

        def instance_templates(num_replace):
            for i in range(num_instances):
                if i < len(instances):
                    inst = instances[i]
                    if inst.t != instance_definition and num_replace > 0:
                        num_replace -= 1
                        yield inst.name, instance_definition
                    else:
                        yield inst.name, inst.t
                else:
                    yield short_id.generate_id(), instance_definition

        return {"Resources": dict(instance_templates(num_replace))}

    def _replace(self, min_in_service, batch_size, pause_time):
        """
        Replace the instances in the group using updated launch configuration
        """
        def changing_instances(tmpl):
            instances = self.get_instances()
            current = set((i.name, str(i.t)) for i in instances)
            updated = set((k, str(v)) for k, v in tmpl['Resources'].items())
            # includes instances to be updated and deleted
            affected = set(k for k, v in current ^ updated)
            return set(i.FnGetRefId() for i in instances if i.name in affected)

        def pause_between_batch():
            while True:
                try:
                    yield
                except scheduler.Timeout:
                    return

        capacity = len(self.nested()) if self.nested() else 0
        efft_bat_sz = min(batch_size, capacity)
        efft_min_sz = min(min_in_service, capacity)
        pause_sec = iso8601utils.parse_isoduration(pause_time)

        batch_cnt = (capacity + efft_bat_sz - 1) // efft_bat_sz
        if pause_sec * (batch_cnt - 1) >= self.stack.timeout_mins * 60:
            raise ValueError('The current UpdatePolicy will result '
                             'in stack update timeout.')

        # effective capacity includes temporary capacity added to accomodate
        # the minimum number of instances in service during update
        efft_capacity = max(capacity - efft_bat_sz, efft_min_sz) + efft_bat_sz

        try:
            remainder = capacity
            while remainder > 0 or efft_capacity > capacity:
                if capacity - remainder >= efft_min_sz:
                    efft_capacity = capacity
                template = self._create_template(efft_capacity, efft_bat_sz)
                self._lb_reload(exclude=changing_instances(template))
                updater = self.update_with_template(template, {})
                updater.run_to_completion()
                self.check_update_complete(updater)
                remainder -= efft_bat_sz
                if remainder > 0 and pause_sec > 0:
                    self._lb_reload()
                    waiter = scheduler.TaskRunner(pause_between_batch)
                    waiter(timeout=pause_sec)
        finally:
            self._lb_reload()

    def resize(self, new_capacity):
        """
        Resize the instance group to the new capacity.

        When shrinking, the oldest instances will be removed.
        """
        new_template = self._create_template(new_capacity)
        try:
            updater = self.update_with_template(new_template, {})
            updater.run_to_completion()
            self.check_update_complete(updater)
        finally:
            # Reload the LB in any case, so it's only pointing at healthy
            # nodes.
            self._lb_reload()

    def _lb_reload(self, exclude=[]):
        '''
        Notify the LoadBalancer to reload its config to include
        the changes in instances we have just made.

        This must be done after activation (instance in ACTIVE state),
        otherwise the instances' IP addresses may not be available.
        '''
        if self.properties['LoadBalancerNames']:
            id_list = [
                inst.FnGetRefId() for inst in self.get_instances()
                if inst.FnGetRefId() not in exclude
            ]
            for lb in self.properties['LoadBalancerNames']:
                lb_resource = self.stack[lb]
                if 'Instances' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['Instances'] = (
                        id_list)
                elif 'members' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['members'] = (
                        id_list)
                else:
                    raise exception.Error(
                        "Unsupported resource '%s' in LoadBalancerNames" %
                        (lb, ))
                resolved_snippet = self.stack.resolve_static_data(
                    lb_resource.json_snippet)
                scheduler.TaskRunner(lb_resource.update, resolved_snippet)()

    def FnGetRefId(self):
        return self.physical_resource_name()

    def _resolve_attribute(self, name):
        '''
        heat extension: "InstanceList" returns comma delimited list of server
        ip addresses.
        '''
        if name == 'InstanceList':
            return u','.join(
                inst.FnGetAtt('PublicIp')
                for inst in self.get_instances()) or None
Esempio n. 11
0
class Resource(object):
    # Status strings
    CREATE_IN_PROGRESS = 'IN_PROGRESS'
    CREATE_FAILED = 'CREATE_FAILED'
    CREATE_COMPLETE = 'CREATE_COMPLETE'
    DELETE_IN_PROGRESS = 'DELETE_IN_PROGRESS'
    DELETE_FAILED = 'DELETE_FAILED'
    DELETE_COMPLETE = 'DELETE_COMPLETE'
    UPDATE_IN_PROGRESS = 'UPDATE_IN_PROGRESS'
    UPDATE_FAILED = 'UPDATE_FAILED'
    UPDATE_COMPLETE = 'UPDATE_COMPLETE'

    # Status values, returned from subclasses to indicate update method
    UPDATE_REPLACE = 'UPDATE_REPLACE'
    UPDATE_INTERRUPTION = 'UPDATE_INTERRUPTION'
    UPDATE_NO_INTERRUPTION = 'UPDATE_NO_INTERRUPTION'
    UPDATE_NOT_IMPLEMENTED = 'UPDATE_NOT_IMPLEMENTED'

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = get_class(json['Type'])
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.cached_t = None
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)

        resource = db_api.resource_get_by_name_and_stack(self.context,
                                                         name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.state = resource.state
            self.state_description = resource.state_description
            self.id = resource.id
        else:
            self.resource_id = None
            self.state = None
            self.state_description = ''
            self.id = None

    def __eq__(self, other):
        '''Allow == comparison of two resources'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (
                self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t['Type']

    def identifier(self):
        '''Return an identifier for this resource'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}, cached=False):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if cached and self.cached_t:
            t = self.cached_t
        else:
            t = self.t
        if section is None:
            template = t
        else:
            template = t.get(section, default)
        return self.stack.resolve_runtime_data(template)

    def cache_template(self):
        '''
        make a cache of the resource's parsed template
        this can then be used via parsed_template(cached=True)
        '''
        self.cached_t = self.stack.resolve_runtime_data(self.t)

    def update_template_diff(self, json_snippet=None):
        '''
        Returns the difference between json_template and self.t
        If something has been removed in json_snippet which exists
        in self.t we set it to None.  If any keys have changed which
        are not in update_allowed_keys, raises NotImplementedError
        '''
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        current_template = self.parsed_template(cached=True)

        template_keys = set(current_template.keys())
        new_template = self.stack.resolve_runtime_data(json_snippet)
        template_keys.update(set(new_template.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set([k for k in template_keys
                               if current_template.get(k) !=
                               new_template.get(k)])

        if not changed_keys_set.issubset(update_allowed_set):
            badkeys = changed_keys_set - update_allowed_set
            raise NotImplementedError("Cannot update keys %s for %s" %
                                      (badkeys, self.name))

        return dict((k, new_template.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, json_snippet=None):
        '''
        Returns the changed Properties between json_template and self.t
        If a property has been removed in json_snippet which exists
        in self.t we set it to None.  If any properties have changed which
        are not in update_allowed_properties, raises NotImplementedError
        '''
        update_allowed_set = set(self.update_allowed_properties)

        # Create a set containing the keys in both current and update template
        tmpl = self.parsed_template(cached=True)
        current_properties = tmpl.get('Properties', {})

        template_properties = set(current_properties.keys())
        updated_properties = json_snippet.get('Properties', {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(k for k in template_properties
                                     if current_properties.get(k) !=
                                     updated_properties.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            badkeys = changed_properties_set - update_allowed_set
            raise NotImplementedError("Cannot update properties %s for %s" %
                                      (badkeys, self.name))

        return dict((k, updated_properties.get(k))
                    for k in changed_properties_set)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref'):
                    target = self.stack.resources[value]
                    if key == 'DependsOn' or target.strict_dependency:
                        deps += (self, target)
                elif key != 'Fn::GetAtt':
                    self._add_dependencies(deps, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, self.t)
        deps += (self, None)

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def quantum(self):
        return self.stack.clients.quantum()

    def cinder(self):
        return self.stack.clients.cinder()

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.CREATE_COMPLETE):
            return 'Resource creation already requested'

        logger.info('creating %s' % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the AWS::StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)
        try:
            self.properties.validate()
            self.state_set(self.CREATE_IN_PROGRESS)
            if callable(getattr(self, 'handle_create', None)):
                self.handle_create()
            while not self.check_active():
                eventlet.sleep(1)
        except greenlet.GreenletExit:
            raise
        except Exception as ex:
            logger.exception('create %s', str(self))
            self.state_set(self.CREATE_FAILED, str(ex))
            return str(ex) or "Error : %s" % type(ex)
        else:
            self.state_set(self.CREATE_COMPLETE)

    def check_active(self):
        '''
        Check if the resource is active (ready to move to the CREATE_COMPLETE
        state). By default this happens as soon as the handle_create() method
        has completed successfully, but subclasses may customise this by
        overriding this function.
        '''
        return True

    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            return 'Resource update already requested'

        if not json_snippet:
            return 'Must specify json snippet for resource update!'

        logger.info('updating %s' % str(self))

        result = self.UPDATE_NOT_IMPLEMENTED
        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data,
                                    self.name)
            properties.validate()
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            self.state_set(self.UPDATE_FAILED, str(ex))
            return str(ex) or "Error : %s" % type(ex)
        else:
            # If resource was updated (with or without interruption),
            # then we set the resource to UPDATE_COMPLETE
            if not result == self.UPDATE_REPLACE:
                self.t = self.stack.resolve_static_data(json_snippet)
                self.state_set(self.UPDATE_COMPLETE)
            return result

    def physical_resource_name(self):
        return '%s.%s' % (self.stack.name, self.name)

    def physical_resource_name_find(self, resource_name):
        if resource_name in self.stack:
            return '%s.%s' % (self.stack.name, resource_name)
        else:
            raise IndexError('no such resource')

    def validate(self):
        logger.info('Validating %s' % str(self))

        return self.properties.validate()

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        if self.state == self.DELETE_COMPLETE:
            return
        if self.state == self.DELETE_IN_PROGRESS:
            return 'Resource deletion already in progress'
        if self.state == self.CREATE_FAILED:
            return
        # Further resources will not be created in a CREATE_FAILED stack.
        # The state of these resources is None.  Do not delete as an
        # undeleteable stack will result
        if self.state is None:
            return

        logger.info('deleting %s (inst:%s db_id:%s)' %
                    (str(self), self.resource_id, str(self.id)))
        self.state_set(self.DELETE_IN_PROGRESS)

        try:
            if callable(getattr(self, 'handle_delete', None)):
                self.handle_delete()
        except Exception as ex:
            logger.exception('Delete %s', str(self))
            self.state_set(self.DELETE_FAILED, str(ex))
            return str(ex) or "Error : %s" % type(ex)

        self.state_set(self.DELETE_COMPLETE)

    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        result = self.delete()
        if result:
            return result

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass
        except Exception as ex:
            logger.exception('Delete %s from DB' % str(self))
            return str(ex) or "Error : %s" % type(ex)

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn('db error %s' % str(ex))

    def _store(self):
        '''Create the resource in the database'''
        try:
            rs = {'state': self.state,
                  'stack_id': self.stack.id,
                  'nova_instance': self.resource_id,
                  'name': self.name,
                  'rsrc_metadata': self.metadata,
                  'stack_name': self.stack.name}

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _add_event(self, new_state, reason):
        '''Add a state change event to the database'''
        ev = event.Event(self.context, self.stack, self,
                         new_state, reason,
                         self.resource_id, self.properties)

        try:
            ev.store()
        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _store_or_update(self, new_state, reason):
        self.state = new_state
        self.state_description = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'state': self.state,
                                    'state_description': reason,
                                    'nova_instance': self.resource_id})

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error('DB error %s' % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif new_state == self.CREATE_IN_PROGRESS:
            self._store()

    def state_set(self, new_state, reason="state changed"):
        old_state = self.state
        self._store_or_update(new_state, reason)

        if new_state != old_state:
            self._add_event(new_state, reason)

    def FnGetRefId(self):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        '''
        return unicode(self.name)

    def FnBase64(self, data):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        '''
        return base64.b64encode(data)

    def handle_update(self, json_snippet=None):
        raise NotImplementedError("Update not implemented for Resource %s"
                                  % type(self))

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            logger.warning("Resource %s does not implement metadata update" %
                           self.name)
Esempio n. 12
0
class InstanceGroup(stack_resource.StackResource):

    PROPERTIES = (
        AVAILABILITY_ZONES, LAUNCH_CONFIGURATION_NAME, SIZE,
        LOAD_BALANCER_NAMES, TAGS,
    ) = (
        'AvailabilityZones', 'LaunchConfigurationName', 'Size',
        'LoadBalancerNames', 'Tags',
    )

    _TAG_KEYS = (
        TAG_KEY, TAG_VALUE,
    ) = (
        'Key', 'Value',
    )

    properties_schema = {
        AVAILABILITY_ZONES: properties.Schema(
            properties.Schema.LIST,
            _('Not Implemented.'),
            required=True
        ),
        LAUNCH_CONFIGURATION_NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of LaunchConfiguration resource.'),
            required=True,
            update_allowed=True
        ),
        SIZE: properties.Schema(
            properties.Schema.NUMBER,
            _('Desired number of instances.'),
            required=True,
            update_allowed=True
        ),
        LOAD_BALANCER_NAMES: properties.Schema(
            properties.Schema.LIST,
            _('List of LoadBalancer resources.')
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            _('Tags to attach to this group.'),
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    TAG_KEY: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                    TAG_VALUE: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                },
            )
        ),
    }

    update_allowed_keys = ('Properties', 'UpdatePolicy',)

    attributes_schema = {
        "InstanceList": _("A comma-delimited list of server ip addresses. "
                          "(Heat extension).")
    }
    rolling_update_schema = {
        'MinInstancesInService': properties.Schema(properties.Schema.NUMBER,
                                                   default=0),
        'MaxBatchSize': properties.Schema(properties.Schema.NUMBER, default=1),
        'PauseTime': properties.Schema(properties.Schema.STRING,
                                       default='PT0S')
    }
    update_policy_schema = {
        'RollingUpdate': properties.Schema(properties.Schema.MAP,
                                           schema=rolling_update_schema)
    }

    def __init__(self, name, json_snippet, stack):
        """
        UpdatePolicy is currently only specific to InstanceGroup and
        AutoScalingGroup. Therefore, init is overridden to parse for the
        UpdatePolicy.
        """
        super(InstanceGroup, self).__init__(name, json_snippet, stack)
        self.update_policy = Properties(self.update_policy_schema,
                                        self.t.get('UpdatePolicy', {}),
                                        parent_name=self.name,
                                        context=self.context)

    def validate(self):
        """
        Add validation for update_policy
        """
        super(InstanceGroup, self).validate()

        if self.update_policy:
            self.update_policy.validate()
            policy_name = self.update_policy_schema.keys()[0]
            if self.update_policy[policy_name]:
                pause_time = self.update_policy[policy_name]['PauseTime']
                if iso8601utils.parse_isoduration(pause_time) > 3600:
                    raise ValueError('Maximum PauseTime is 1 hour.')

    def get_instance_names(self):
        """Get a list of resource names of the instances in this InstanceGroup.

        Failed resources will be ignored.
        """
        return [r.name for r in self.get_instances()]

    def get_instances(self):
        """Get a list of all the instance resources managed by this group.

        Sort the list of instances first by created_time then by name.
        """
        resources = []
        if self.nested():
            resources = [resource for resource in self.nested().itervalues()
                         if resource.status != resource.FAILED]
        return sorted(resources, key=lambda r: (r.created_time, r.name))

    def _environment(self):
        """Return the environment for the nested stack."""
        return {
            environment.PARAMETERS: {},
            environment.RESOURCE_REGISTRY: {
                SCALED_RESOURCE_TYPE: 'AWS::EC2::Instance',
            },
        }

    def handle_create(self):
        """Create a nested stack and add the initial resources to it."""
        num_instances = int(self.properties[self.SIZE])
        initial_template = self._create_template(num_instances)
        return self.create_with_template(initial_template, self._environment())

    def check_create_complete(self, task):
        """
        When stack creation is done, update the load balancer.

        If any instances failed to be created, delete them.
        """
        done = super(InstanceGroup, self).check_create_complete(task)
        if done:
            self._lb_reload()
        return done

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """
        If Properties has changed, update self.properties, so we
        get the new values during any subsequent adjustment.
        """
        if tmpl_diff:
            # parse update policy
            if 'UpdatePolicy' in tmpl_diff:
                self.update_policy = Properties(
                    self.update_policy_schema,
                    json_snippet.get('UpdatePolicy', {}),
                    parent_name=self.name,
                    context=self.context)

        if prop_diff:
            self.properties = Properties(self.properties_schema,
                                         json_snippet.get('Properties', {}),
                                         self.stack.resolve_runtime_data,
                                         self.name,
                                         self.context)

            # Replace instances first if launch configuration has changed
            if (self.update_policy['RollingUpdate'] and
                    self.LAUNCH_CONFIGURATION_NAME in prop_diff):
                policy = self.update_policy['RollingUpdate']
                self._replace(int(policy['MinInstancesInService']),
                              int(policy['MaxBatchSize']),
                              policy['PauseTime'])

            # Get the current capacity, we may need to adjust if
            # Size has changed
            if self.SIZE in prop_diff:
                inst_list = self.get_instances()
                if len(inst_list) != int(self.properties[self.SIZE]):
                    self.resize(int(self.properties[self.SIZE]))

    def _tags(self):
        """
        Make sure that we add a tag that Ceilometer can pick up.
        These need to be prepended with 'metering.'.
        """
        tags = self.properties.get(self.TAGS) or []
        for t in tags:
            if t[self.TAG_KEY].startswith('metering.'):
                # the user has added one, don't add another.
                return tags
        return tags + [{self.TAG_KEY: 'metering.groupname',
                        self.TAG_VALUE: self.FnGetRefId()}]

    def handle_delete(self):
        return self.delete_nested()

    def _get_instance_definition(self):
        conf_name = self.properties[self.LAUNCH_CONFIGURATION_NAME]
        conf = self.stack.resource_by_refid(conf_name)
        instance_definition = copy.deepcopy(conf.t)
        instance_definition['Type'] = SCALED_RESOURCE_TYPE
        instance_definition['Properties']['Tags'] = self._tags()
        if self.properties.get('VPCZoneIdentifier'):
            instance_definition['Properties']['SubnetId'] = \
                self.properties['VPCZoneIdentifier'][0]
        # resolve references within the context of this stack.
        return self.stack.resolve_runtime_data(instance_definition)

    def _create_template(self, num_instances, num_replace=0):
        """
        Create a template to represent autoscaled instances.

        Also see heat.scaling.template.resource_templates.
        """
        instance_definition = self._get_instance_definition()
        old_resources = [(instance.name, instance.t)
                         for instance in self.get_instances()]
        templates = template.resource_templates(
            old_resources, instance_definition, num_instances, num_replace)
        return {"Resources": dict(templates)}

    def _replace(self, min_in_service, batch_size, pause_time):
        """
        Replace the instances in the group using updated launch configuration
        """
        def changing_instances(tmpl):
            instances = self.get_instances()
            serialize_template = functools.partial(json.dumps, sort_keys=True)
            current = set((i.name, serialize_template(i.t)) for i in instances)
            updated = set((k, serialize_template(v))
                          for k, v in tmpl['Resources'].items())
            # includes instances to be updated and deleted
            affected = set(k for k, v in current ^ updated)
            return set(i.FnGetRefId() for i in instances if i.name in affected)

        def pause_between_batch():
            while True:
                try:
                    yield
                except scheduler.Timeout:
                    return

        capacity = len(self.nested()) if self.nested() else 0
        efft_bat_sz = min(batch_size, capacity)
        efft_min_sz = min(min_in_service, capacity)
        pause_sec = iso8601utils.parse_isoduration(pause_time)

        batch_cnt = (capacity + efft_bat_sz - 1) // efft_bat_sz
        if pause_sec * (batch_cnt - 1) >= self.stack.timeout_mins * 60:
            raise ValueError('The current UpdatePolicy will result '
                             'in stack update timeout.')

        # effective capacity includes temporary capacity added to accommodate
        # the minimum number of instances in service during update
        efft_capacity = max(capacity - efft_bat_sz, efft_min_sz) + efft_bat_sz

        try:
            remainder = capacity
            while remainder > 0 or efft_capacity > capacity:
                if capacity - remainder >= efft_min_sz:
                    efft_capacity = capacity
                template = self._create_template(efft_capacity, efft_bat_sz)
                self._lb_reload(exclude=changing_instances(template))
                updater = self.update_with_template(template,
                                                    self._environment())
                updater.run_to_completion()
                self.check_update_complete(updater)
                remainder -= efft_bat_sz
                if remainder > 0 and pause_sec > 0:
                    self._lb_reload()
                    waiter = scheduler.TaskRunner(pause_between_batch)
                    waiter(timeout=pause_sec)
        finally:
            self._lb_reload()

    def resize(self, new_capacity):
        """
        Resize the instance group to the new capacity.

        When shrinking, the oldest instances will be removed.
        """
        new_template = self._create_template(new_capacity)
        try:
            updater = self.update_with_template(new_template,
                                                self._environment())
            updater.run_to_completion()
            self.check_update_complete(updater)
        finally:
            # Reload the LB in any case, so it's only pointing at healthy
            # nodes.
            self._lb_reload()

    def _lb_reload(self, exclude=[]):
        '''
        Notify the LoadBalancer to reload its config to include
        the changes in instances we have just made.

        This must be done after activation (instance in ACTIVE state),
        otherwise the instances' IP addresses may not be available.
        '''
        if self.properties[self.LOAD_BALANCER_NAMES]:
            id_list = [inst.FnGetRefId() for inst in self.get_instances()
                       if inst.FnGetRefId() not in exclude]
            for lb in self.properties[self.LOAD_BALANCER_NAMES]:
                lb_resource = self.stack[lb]
                if 'Instances' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['Instances'] = (
                        id_list)
                elif 'members' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['members'] = (
                        id_list)
                else:
                    raise exception.Error(
                        "Unsupported resource '%s' in LoadBalancerNames" %
                        (lb,))
                resolved_snippet = self.stack.resolve_static_data(
                    lb_resource.json_snippet)
                scheduler.TaskRunner(lb_resource.update, resolved_snippet)()

    def FnGetRefId(self):
        return self.physical_resource_name()

    def _resolve_attribute(self, name):
        '''
        heat extension: "InstanceList" returns comma delimited list of server
        ip addresses.
        '''
        if name == 'InstanceList':
            return u','.join(inst.FnGetAtt('PublicIp')
                             for inst in self.get_instances()) or None
Esempio n. 13
0
class Resource(object):
    # Status strings
    CREATE_IN_PROGRESS = "IN_PROGRESS"
    CREATE_FAILED = "CREATE_FAILED"
    CREATE_COMPLETE = "CREATE_COMPLETE"
    DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"
    DELETE_FAILED = "DELETE_FAILED"
    DELETE_COMPLETE = "DELETE_COMPLETE"
    UPDATE_IN_PROGRESS = "UPDATE_IN_PROGRESS"
    UPDATE_FAILED = "UPDATE_FAILED"
    UPDATE_COMPLETE = "UPDATE_COMPLETE"

    # Status values, returned from subclasses to indicate update method
    UPDATE_REPLACE = "UPDATE_REPLACE"
    UPDATE_INTERRUPTION = "UPDATE_INTERRUPTION"
    UPDATE_NO_INTERRUPTION = "UPDATE_NO_INTERRUPTION"
    UPDATE_NOT_IMPLEMENTED = "UPDATE_NOT_IMPLEMENTED"

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, "created_at")
    updated_time = timestamp.Timestamp(db_api.resource_get, "updated_at")

    metadata = Metadata()

    def __new__(cls, name, json, stack):
        """Create a new Resource of the appropriate class for its type."""

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = get_class(json["Type"]) or GenericResource
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if "/" in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(
            self.properties_schema, self.t.get("Properties", {}), self.stack.resolve_runtime_data, self.name
        )

        resource = db_api.resource_get_by_name_and_stack(self.context, name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.state = resource.state
            self.state_description = resource.state_description
            self.id = resource.id
        else:
            self.resource_id = None
            self.state = None
            self.state_description = ""
            self.id = None

    def __eq__(self, other):
        """Allow == comparison of two resources"""
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        """Allow != comparison of two resources"""
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t["Type"]

    def identifier(self):
        """Return an identifier for this resource"""
        return identifier.ResourceIdentifier(resource_name=self.name, **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        """
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        """
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self.stack.resolve_runtime_data(template)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ("DependsOn", "Ref"):
                    target = self.stack.resources[value]
                    if key == "DependsOn" or target.strict_dependency:
                        deps += (self, target)
                elif key != "Fn::GetAtt":
                    self._add_dependencies(deps, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, self.t)
        deps += (self, None)

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type="compute"):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def quantum(self):
        return self.stack.clients.quantum()

    def create(self):
        """
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        """
        if self.state in (self.CREATE_IN_PROGRESS, self.CREATE_COMPLETE):
            return "Resource creation already requested"

        logger.info("creating %s" % str(self))

        try:
            err = self.properties.validate()
            if err:
                return err
            self.state_set(self.CREATE_IN_PROGRESS)
            if callable(getattr(self, "handle_create", None)):
                self.handle_create()
        except Exception as ex:
            # If we get a GreenletExit exception, the create thread has
            # been killed so we should raise allowing this thread to exit
            if type(ex) is greenlet.GreenletExit:
                logger.warning("GreenletExit during create, exiting")
                raise
            else:
                logger.exception("create %s", str(self))
                self.state_set(self.CREATE_FAILED, str(ex))
                return str(ex)
        else:
            self.state_set(self.CREATE_COMPLETE)

    def update(self, json_snippet=None):
        """
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        """
        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            return "Resource update already requested"

        if not json_snippet:
            return "Must specify json snippet for resource update!"

        logger.info("updating %s" % str(self))

        result = self.UPDATE_NOT_IMPLEMENTED
        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            self.t = self.stack.resolve_static_data(json_snippet)
            err = self.properties.validate()
            if err:
                return err
            if callable(getattr(self, "handle_update", None)):
                result = self.handle_update()
        except Exception as ex:
            logger.exception("update %s : %s" % (str(self), str(ex)))
            self.state_set(self.UPDATE_FAILED, str(ex))
            return str(ex)
        else:
            # If resource was updated (with or without interruption),
            # then we set the resource to UPDATE_COMPLETE
            if not result == self.UPDATE_REPLACE:
                self.state_set(self.UPDATE_COMPLETE)
            return result

    def physical_resource_name(self):
        return "%s.%s" % (self.stack.name, self.name)

    def physical_resource_name_find(self, resource_name):
        if resource_name in self.stack:
            return "%s.%s" % (self.stack.name, resource_name)
        else:
            raise IndexError("no such resource")

    def validate(self):
        logger.info("Validating %s" % str(self))

        return self.properties.validate()

    def delete(self):
        """
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        """
        if self.state == self.DELETE_COMPLETE:
            return
        if self.state == self.DELETE_IN_PROGRESS:
            return "Resource deletion already in progress"

        logger.info("deleting %s (inst:%s db_id:%s)" % (str(self), self.resource_id, str(self.id)))
        self.state_set(self.DELETE_IN_PROGRESS)

        try:
            if callable(getattr(self, "handle_delete", None)):
                self.handle_delete()
        except Exception as ex:
            logger.exception("Delete %s", str(self))
            self.state_set(self.DELETE_FAILED, str(ex))
            return str(ex)

        self.state_set(self.DELETE_COMPLETE)

    def destroy(self):
        """
        Delete the resource and remove it from the database.
        """
        result = self.delete()
        if result:
            return result

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass
        except Exception as ex:
            logger.exception("Delete %s from DB" % str(self))
            return str(ex)

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({"nova_instance": self.resource_id})
            except Exception as ex:
                logger.warn("db error %s" % str(ex))

    def _store(self):
        """Create the resource in the database"""
        try:
            rs = {
                "state": self.state,
                "stack_id": self.stack.id,
                "nova_instance": self.resource_id,
                "name": self.name,
                "rsrc_metadata": self.metadata,
                "stack_name": self.stack.name,
            }

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error("DB error %s" % str(ex))

    def _add_event(self, new_state, reason):
        """Add a state change event to the database"""
        ev = event.Event(self.context, self.stack, self, new_state, reason, self.resource_id, self.properties)

        try:
            ev.store()
        except Exception as ex:
            logger.error("DB error %s" % str(ex))

    def _store_or_update(self, new_state, reason):
        self.state = new_state
        self.state_description = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save(
                    {"state": self.state, "state_description": reason, "nova_instance": self.resource_id}
                )

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error("DB error %s" % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif new_state == self.CREATE_IN_PROGRESS:
            self._store()

    def state_set(self, new_state, reason="state changed"):
        old_state = self.state
        self._store_or_update(new_state, reason)

        if new_state != old_state:
            self._add_event(new_state, reason)

    def FnGetRefId(self):
        """
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        """
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        """
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        """
        return unicode(self.name)

    def FnBase64(self, data):
        """
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        """
        return base64.b64encode(data)

    def handle_update(self):
        raise NotImplementedError("Update not implemented for Resource %s" % type(self))

    def metadata_update(self, metadata):
        """
        No-op for resources which don't explicitly override this method
        """
        logger.warning("Resource %s does not implement metadata update" % self.name)
Esempio n. 14
0
class InstanceGroup(stack_resource.StackResource):

    PROPERTIES = (
        AVAILABILITY_ZONES,
        LAUNCH_CONFIGURATION_NAME,
        SIZE,
        LOAD_BALANCER_NAMES,
        TAGS,
    ) = (
        'AvailabilityZones',
        'LaunchConfigurationName',
        'Size',
        'LoadBalancerNames',
        'Tags',
    )

    _TAG_KEYS = (
        TAG_KEY,
        TAG_VALUE,
    ) = (
        'Key',
        'Value',
    )

    _ROLLING_UPDATE_SCHEMA_KEYS = (MIN_INSTANCES_IN_SERVICE, MAX_BATCH_SIZE,
                                   PAUSE_TIME) = ('MinInstancesInService',
                                                  'MaxBatchSize', 'PauseTime')

    _UPDATE_POLICY_SCHEMA_KEYS = (ROLLING_UPDATE, ) = ('RollingUpdate', )

    properties_schema = {
        AVAILABILITY_ZONES:
        properties.Schema(properties.Schema.LIST,
                          _('Not Implemented.'),
                          required=True),
        LAUNCH_CONFIGURATION_NAME:
        properties.Schema(properties.Schema.STRING,
                          _('Name of LaunchConfiguration resource.'),
                          required=True,
                          update_allowed=True),
        SIZE:
        properties.Schema(properties.Schema.INTEGER,
                          _('Desired number of instances.'),
                          required=True,
                          update_allowed=True),
        LOAD_BALANCER_NAMES:
        properties.Schema(properties.Schema.LIST,
                          _('List of LoadBalancer resources.')),
        TAGS:
        properties.Schema(properties.Schema.LIST,
                          _('Tags to attach to this group.'),
                          schema=properties.Schema(
                              properties.Schema.MAP,
                              schema={
                                  TAG_KEY:
                                  properties.Schema(properties.Schema.STRING,
                                                    required=True),
                                  TAG_VALUE:
                                  properties.Schema(properties.Schema.STRING,
                                                    required=True),
                              },
                          )),
    }

    attributes_schema = {
        "InstanceList":
        _("A comma-delimited list of server ip addresses. "
          "(Heat extension).")
    }
    rolling_update_schema = {
        MIN_INSTANCES_IN_SERVICE:
        properties.Schema(properties.Schema.NUMBER, default=0),
        MAX_BATCH_SIZE:
        properties.Schema(properties.Schema.NUMBER, default=1),
        PAUSE_TIME:
        properties.Schema(properties.Schema.STRING, default='PT0S')
    }
    update_policy_schema = {
        ROLLING_UPDATE:
        properties.Schema(properties.Schema.MAP, schema=rolling_update_schema)
    }

    def __init__(self, name, json_snippet, stack):
        """
        UpdatePolicy is currently only specific to InstanceGroup and
        AutoScalingGroup. Therefore, init is overridden to parse for the
        UpdatePolicy.
        """
        super(InstanceGroup, self).__init__(name, json_snippet, stack)
        self.update_policy = Properties(self.update_policy_schema,
                                        self.t.get('UpdatePolicy', {}),
                                        parent_name=self.name,
                                        context=self.context)

    def validate(self):
        """
        Add validation for update_policy
        """
        super(InstanceGroup, self).validate()

        if self.update_policy:
            self.update_policy.validate()
            policy_name = self.update_policy_schema.keys()[0]
            if self.update_policy[policy_name]:
                pause_time = self.update_policy[policy_name][self.PAUSE_TIME]
                if iso8601utils.parse_isoduration(pause_time) > 3600:
                    raise ValueError('Maximum PauseTime is 1 hour.')

    def get_instance_names(self):
        """Get a list of resource names of the instances in this InstanceGroup.

        Failed resources will be ignored.
        """
        return [r.name for r in self.get_instances()]

    def get_instances(self):
        """Get a list of all the instance resources managed by this group.

        Sort the list of instances first by created_time then by name.
        """
        resources = []
        if self.nested():
            resources = [
                resource for resource in self.nested().itervalues()
                if resource.status != resource.FAILED
            ]
        return sorted(resources, key=lambda r: (r.created_time, r.name))

    def _environment(self):
        """Return the environment for the nested stack."""
        return {
            environment.PARAMETERS: {},
            environment.RESOURCE_REGISTRY: {
                SCALED_RESOURCE_TYPE: 'AWS::EC2::Instance',
            },
        }

    def handle_create(self):
        """Create a nested stack and add the initial resources to it."""
        num_instances = self.properties[self.SIZE]
        initial_template = self._create_template(num_instances)
        return self.create_with_template(initial_template, self._environment())

    def check_create_complete(self, task):
        """
        When stack creation is done, update the load balancer.

        If any instances failed to be created, delete them.
        """
        done = super(InstanceGroup, self).check_create_complete(task)
        if done:
            self._lb_reload()
        return done

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """
        If Properties has changed, update self.properties, so we
        get the new values during any subsequent adjustment.
        """
        if tmpl_diff:
            # parse update policy
            if 'UpdatePolicy' in tmpl_diff:
                self.update_policy = Properties(self.update_policy_schema,
                                                json_snippet.get(
                                                    'UpdatePolicy', {}),
                                                parent_name=self.name,
                                                context=self.context)

        if prop_diff:
            self.properties = Properties(self.properties_schema,
                                         json_snippet.get('Properties', {}),
                                         function.resolve, self.name,
                                         self.context)

            # Replace instances first if launch configuration has changed
            self._try_rolling_update(prop_diff)

            # Get the current capacity, we may need to adjust if
            # Size has changed
            if self.SIZE in prop_diff:
                inst_list = self.get_instances()
                if len(inst_list) != self.properties[self.SIZE]:
                    self.resize(self.properties[self.SIZE])

    def _tags(self):
        """
        Make sure that we add a tag that Ceilometer can pick up.
        These need to be prepended with 'metering.'.
        """
        tags = self.properties.get(self.TAGS) or []
        for t in tags:
            if t[self.TAG_KEY].startswith('metering.'):
                # the user has added one, don't add another.
                return tags
        return tags + [{
            self.TAG_KEY: 'metering.groupname',
            self.TAG_VALUE: self.FnGetRefId()
        }]

    def handle_delete(self):
        return self.delete_nested()

    def _get_instance_definition(self):
        conf_name = self.properties[self.LAUNCH_CONFIGURATION_NAME]
        conf = self.stack.resource_by_refid(conf_name)
        instance_definition = function.resolve(conf.t)
        instance_definition['Type'] = SCALED_RESOURCE_TYPE
        instance_definition['Properties']['Tags'] = self._tags()
        if self.properties.get('VPCZoneIdentifier'):
            instance_definition['Properties']['SubnetId'] = \
                self.properties['VPCZoneIdentifier'][0]
        return instance_definition

    def _get_instance_templates(self):
        """Get templates for resource instances."""
        return [(instance.name, instance.t)
                for instance in self.get_instances()]

    def _create_template(self, num_instances, num_replace=0):
        """
        Create a template to represent autoscaled instances.

        Also see heat.scaling.template.resource_templates.
        """
        instance_definition = self._get_instance_definition()
        old_resources = self._get_instance_templates()
        templates = template.resource_templates(old_resources,
                                                instance_definition,
                                                num_instances, num_replace)
        return {
            "HeatTemplateFormatVersion": "2012-12-12",
            "Resources": dict(templates)
        }

    def _try_rolling_update(self, prop_diff):
        if (self.update_policy[self.ROLLING_UPDATE]
                and self.LAUNCH_CONFIGURATION_NAME in prop_diff):
            policy = self.update_policy[self.ROLLING_UPDATE]
            pause_sec = iso8601utils.parse_isoduration(policy[self.PAUSE_TIME])
            self._replace(policy[self.MIN_INSTANCES_IN_SERVICE],
                          policy[self.MAX_BATCH_SIZE], pause_sec)

    def _replace(self, min_in_service, batch_size, pause_sec):
        """
        Replace the instances in the group using updated launch configuration
        """
        def changing_instances(tmpl):
            def serialize_template(t):
                return json.dumps(function.resolve(t), sort_keys=True)

            instances = self.get_instances()
            # To support both HOT and CFN, need to find out what the name of
            # the resources key is.
            resources_key = self.nested().t.RESOURCES
            current = set((i.name, serialize_template(i.t)) for i in instances)
            updated = set((k, serialize_template(v))
                          for k, v in tmpl[resources_key].items())
            # includes instances to be updated and deleted
            affected = set(k for k, v in current ^ updated)
            return set(i.FnGetRefId() for i in instances if i.name in affected)

        def pause_between_batch():
            while True:
                try:
                    yield
                except scheduler.Timeout:
                    return

        capacity = len(self.nested()) if self.nested() else 0
        efft_bat_sz = min(batch_size, capacity)
        efft_min_sz = min(min_in_service, capacity)

        batch_cnt = (capacity + efft_bat_sz - 1) // efft_bat_sz
        if pause_sec * (batch_cnt - 1) >= self.stack.timeout_secs():
            raise ValueError('The current UpdatePolicy will result '
                             'in stack update timeout.')

        # effective capacity includes temporary capacity added to accommodate
        # the minimum number of instances in service during update
        efft_capacity = max(capacity - efft_bat_sz, efft_min_sz) + efft_bat_sz

        try:
            remainder = capacity
            while remainder > 0 or efft_capacity > capacity:
                if capacity - remainder >= efft_min_sz:
                    efft_capacity = capacity
                template = self._create_template(efft_capacity, efft_bat_sz)
                self._lb_reload(exclude=changing_instances(template))
                updater = self.update_with_template(template,
                                                    self._environment())
                updater.run_to_completion()
                self.check_update_complete(updater)
                remainder -= efft_bat_sz
                if remainder > 0 and pause_sec > 0:
                    self._lb_reload()
                    waiter = scheduler.TaskRunner(pause_between_batch)
                    waiter(timeout=pause_sec)
        finally:
            self._lb_reload()

    def resize(self, new_capacity):
        """
        Resize the instance group to the new capacity.

        When shrinking, the oldest instances will be removed.
        """
        new_template = self._create_template(new_capacity)
        try:
            updater = self.update_with_template(new_template,
                                                self._environment())
            updater.run_to_completion()
            self.check_update_complete(updater)
        finally:
            # Reload the LB in any case, so it's only pointing at healthy
            # nodes.
            self._lb_reload()

    def _lb_reload(self, exclude=[]):
        '''
        Notify the LoadBalancer to reload its config to include
        the changes in instances we have just made.

        This must be done after activation (instance in ACTIVE state),
        otherwise the instances' IP addresses may not be available.
        '''
        if self.properties[self.LOAD_BALANCER_NAMES]:
            id_list = [
                inst.FnGetRefId() for inst in self.get_instances()
                if inst.FnGetRefId() not in exclude
            ]
            for lb in self.properties[self.LOAD_BALANCER_NAMES]:
                lb_resource = self.stack[lb]
                lb_defn = copy.deepcopy(lb_resource.t)
                if 'Instances' in lb_resource.properties_schema:
                    lb_defn['Properties']['Instances'] = id_list
                elif 'members' in lb_resource.properties_schema:
                    lb_defn['Properties']['members'] = id_list
                else:
                    raise exception.Error(
                        _("Unsupported resource '%s' in LoadBalancerNames") %
                        (lb, ))
                resolved_snippet = self.stack.resolve_static_data(lb_defn)
                scheduler.TaskRunner(lb_resource.update, resolved_snippet)()

    def FnGetRefId(self):
        return self.physical_resource_name()

    def _resolve_attribute(self, name):
        '''
        heat extension: "InstanceList" returns comma delimited list of server
        ip addresses.
        '''
        if name == 'InstanceList':
            return u','.join(
                inst.FnGetAtt('PublicIp')
                for inst in self.get_instances()) or None

    def child_template(self):
        num_instances = int(self.properties[self.SIZE])
        return self._create_template(num_instances)

    def child_params(self):
        return self._environment()
Esempio n. 15
0
class Resource(object):
    # Status strings
    CREATE_IN_PROGRESS = 'IN_PROGRESS'
    CREATE_FAILED = 'CREATE_FAILED'
    CREATE_COMPLETE = 'CREATE_COMPLETE'
    DELETE_IN_PROGRESS = 'DELETE_IN_PROGRESS'
    DELETE_FAILED = 'DELETE_FAILED'
    DELETE_COMPLETE = 'DELETE_COMPLETE'
    UPDATE_IN_PROGRESS = 'UPDATE_IN_PROGRESS'
    UPDATE_FAILED = 'UPDATE_FAILED'
    UPDATE_COMPLETE = 'UPDATE_COMPLETE'

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = get_class(json['Type'])
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.cached_t = None
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)

        resource = db_api.resource_get_by_name_and_stack(
            self.context, name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.state = resource.state
            self.state_description = resource.state_description
            self.id = resource.id
        else:
            self.resource_id = None
            self.state = None
            self.state_description = ''
            self.id = None

    def __eq__(self, other):
        '''Allow == comparison of two resources.'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (self.parsed_template()
                                                  == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources.'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t['Type']

    def identifier(self):
        '''Return an identifier for this resource.'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}, cached=False):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if cached and self.cached_t:
            t = self.cached_t
        else:
            t = self.t
        if section is None:
            template = t
        else:
            template = t.get(section, default)
        return self.stack.resolve_runtime_data(template)

    def cache_template(self):
        '''
        make a cache of the resource's parsed template
        this can then be used via parsed_template(cached=True)
        '''
        self.cached_t = self.stack.resolve_runtime_data(self.t)

    def update_template_diff(self, json_snippet=None):
        '''
        Returns the difference between json_template and self.t
        If something has been removed in json_snippet which exists
        in self.t we set it to None.  If any keys have changed which
        are not in update_allowed_keys, raises UpdateReplace if the
        differing keys are not in update_allowed_keys
        '''
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        current_template = self.parsed_template(cached=True)

        template_keys = set(current_template.keys())
        new_template = self.stack.resolve_runtime_data(json_snippet)
        template_keys.update(set(new_template.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set([
            k for k in template_keys
            if current_template.get(k) != new_template.get(k)
        ])

        if not changed_keys_set.issubset(update_allowed_set):
            badkeys = changed_keys_set - update_allowed_set
            raise UpdateReplace(self.name)

        return dict((k, new_template.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, json_snippet=None):
        '''
        Returns the changed Properties between json_template and self.t
        If a property has been removed in json_snippet which exists
        in self.t we set it to None.  If any properties have changed which
        are not in update_allowed_properties, raises UpdateReplace if the
        modified properties are not in the update_allowed_properties
        '''
        update_allowed_set = set(self.update_allowed_properties)

        # Create a set containing the keys in both current and update template
        tmpl = self.parsed_template(cached=True)
        current_properties = tmpl.get('Properties', {})

        template_properties = set(current_properties.keys())
        updated_properties = json_snippet.get('Properties', {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(
            k for k in template_properties
            if current_properties.get(k) != updated_properties.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict(
            (k, updated_properties.get(k)) for k in changed_properties_set)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, head, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref', 'Fn::GetAtt'):
                    if key == 'Fn::GetAtt':
                        value, head = value

                    try:
                        target = self.stack.resources[value]
                    except KeyError:
                        raise exception.InvalidTemplateReference(
                            resource=value, key=head)
                    if key == 'DependsOn' or target.strict_dependency:
                        deps += (self, target)
                else:
                    self._add_dependencies(deps, key, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, head, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, None, self.t)
        deps += (self, None)

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def quantum(self):
        return self.stack.clients.quantum()

    def cinder(self):
        return self.stack.clients.cinder()

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        assert self.state is None, 'Resource create requested in invalid state'

        logger.info('creating %s' % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the AWS::StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)
        try:
            self.properties.validate()
            self.state_set(self.CREATE_IN_PROGRESS)
            create_data = None
            if callable(getattr(self, 'handle_create', None)):
                create_data = self.handle_create()
                yield
            while not self.check_create_complete(create_data):
                yield
        except greenlet.GreenletExit:
            # Older versions of greenlet erroneously had GreenletExit inherit
            # from Exception instead of BaseException
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(self.CREATE_FAILED, 'Creation aborted')
                except Exception:
                    logger.exception('Error marking resource as failed')
        except Exception as ex:
            logger.exception('create %s', str(self))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.CREATE_FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(self.CREATE_FAILED, 'Creation aborted')
                except Exception:
                    logger.exception('Error marking resource as failed')
        else:
            self.state_set(self.CREATE_COMPLETE)

    def check_create_complete(self, create_data):
        '''
        Check if the resource is active (ready to move to the CREATE_COMPLETE
        state). By default this happens as soon as the handle_create() method
        has completed successfully, but subclasses may customise this by
        overriding this function. The return value of handle_create() is
        passed in to this function each time it is called.
        '''
        return True

    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        assert json_snippet is not None, 'Must specify update json snippet'

        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            raise exception.ResourceFailure(
                Exception('Resource update already requested'))

        logger.info('updating %s' % str(self))

        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    json_snippet.get('Properties', {}),
                                    self.stack.resolve_runtime_data, self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(json_snippet)
            prop_diff = self.update_template_diff_properties(json_snippet)
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(json_snippet, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.UPDATE_FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(json_snippet)
            self.state_set(self.UPDATE_COMPLETE)

    def physical_resource_name(self):
        return '%s-%s' % (self.stack.name, self.name)

    def validate(self):
        logger.info('Validating %s' % str(self))

        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get('DeletionPolicy', 'Delete')
        if deletion_policy not in ('Delete', 'Retain', 'Snapshot'):
            msg = 'Invalid DeletionPolicy %s' % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == 'Snapshot':
            if not callable(getattr(cls, 'handle_snapshot_delete', None)):
                msg = 'Snapshot DeletionPolicy not supported'
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        if self.state == self.DELETE_COMPLETE:
            return
        if self.state == self.DELETE_IN_PROGRESS:
            raise exception.Error('Resource deletion already in progress')
        # No need to delete if the resource has never been created
        if self.state is None:
            return

        initial_state = self.state

        logger.info('deleting %s' % str(self))

        try:
            self.state_set(self.DELETE_IN_PROGRESS)

            deletion_policy = self.t.get('DeletionPolicy', 'Delete')
            if deletion_policy == 'Delete':
                if callable(getattr(self, 'handle_delete', None)):
                    self.handle_delete()
            elif deletion_policy == 'Snapshot':
                if callable(getattr(self, 'handle_snapshot_delete', None)):
                    self.handle_snapshot_delete(initial_state)
        except Exception as ex:
            logger.exception('Delete %s', str(self))
            failure = exception.ResourceFailure(ex)
            self.state_set(self.DELETE_FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(self.DELETE_FAILED, 'Deletion aborted')
                except Exception:
                    logger.exception('Error marking resource deletion failed')
        else:
            self.state_set(self.DELETE_COMPLETE)

    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn('db error %s' % str(ex))

    def _store(self):
        '''Create the resource in the database.'''
        try:
            rs = {
                'state': self.state,
                'stack_id': self.stack.id,
                'nova_instance': self.resource_id,
                'name': self.name,
                'rsrc_metadata': self.metadata,
                'stack_name': self.stack.name
            }

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _add_event(self, new_state, reason):
        '''Add a state change event to the database.'''
        ev = event.Event(self.context, self.stack, self, new_state, reason,
                         self.resource_id, self.properties)

        try:
            ev.store()
        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _store_or_update(self, new_state, reason):
        self.state = new_state
        self.state_description = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({
                    'state': self.state,
                    'state_description': reason,
                    'nova_instance': self.resource_id
                })

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error('DB error %s' % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif new_state == self.CREATE_IN_PROGRESS:
            self._store()

    def state_set(self, new_state, reason="state changed"):
        old_state = self.state
        self._store_or_update(new_state, reason)

        if new_state != old_state:
            self._add_event(new_state, reason)

    def FnGetRefId(self):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        '''
        return unicode(self.name)

    def FnBase64(self, data):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        '''
        return base64.b64encode(data)

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            logger.warning("Resource %s does not implement metadata update" %
                           self.name)
Esempio n. 16
0
class Resource(object):
    ACTIONS = (INIT, CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND,
               RESUME) = ('INIT', 'CREATE', 'DELETE', 'UPDATE', 'ROLLBACK',
                          'SUSPEND', 'RESUME')

    STATUSES = (IN_PROGRESS, FAILED, COMPLETE) = ('IN_PROGRESS', 'FAILED',
                                                  'COMPLETE')

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    # Resource implementations set this to the name: description dictionary
    # that describes the appropriate resource attributes
    attributes_schema = {}

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = stack.env.get_class(json['Type'], resource_name=name)
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self._resolve_runtime_data, self.name)
        self.attributes = Attributes(self.name, self.attributes_schema,
                                     self._resolve_attribute)

        resource = db_api.resource_get_by_name_and_stack(
            self.context, name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.action = resource.action
            self.status = resource.status
            self.status_reason = resource.status_reason
            self.id = resource.id
            self.data = resource.data
        else:
            self.resource_id = None
            # if the stack is being deleted, assume we've already been deleted
            if stack.action == stack.DELETE:
                self.action = self.DELETE
            else:
                self.action = self.INIT
            self.status = self.COMPLETE
            self.status_reason = ''
            self.id = None
            self.data = []

    def __eq__(self, other):
        '''Allow == comparison of two resources.'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (self.parsed_template()
                                                  == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources.'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t['Type']

    def _resolve_runtime_data(self, snippet):
        return self.stack.resolve_runtime_data(snippet)

    def has_interface(self, resource_type):
        """Check to see if this resource is either mapped to resource_type
        or is a "resource_type".
        """
        if self.type() == resource_type:
            return True
        ri = self.stack.env.get_resource_info(self.type(), self.name)
        return ri.name == resource_type

    def identifier(self):
        '''Return an identifier for this resource.'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self._resolve_runtime_data(template)

    def update_template_diff(self, after, before):
        '''
        Returns the difference between the before and after json snippets. If
        something has been removed in after which exists in before we set it to
        None. If any keys have changed which are not in update_allowed_keys,
        raises UpdateReplace if the differing keys are not in
        update_allowed_keys
        '''
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        template_keys = set(before.keys())
        template_keys.update(set(after.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set(
            [k for k in template_keys if before.get(k) != after.get(k)])

        if not changed_keys_set.issubset(update_allowed_set):
            badkeys = changed_keys_set - update_allowed_set
            raise UpdateReplace(self.name)

        return dict((k, after.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, after, before):
        '''
        Returns the changed Properties between the before and after json
        snippets. If a property has been removed in after which exists in
        before we set it to None. If any properties have changed which are not
        in update_allowed_properties, raises UpdateReplace if the modified
        properties are not in the update_allowed_properties
        '''
        update_allowed_set = set(self.update_allowed_properties)

        # Create a set containing the keys in both current and update template
        current_properties = before.get('Properties', {})

        template_properties = set(current_properties.keys())
        updated_properties = after.get('Properties', {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(
            k for k in template_properties
            if current_properties.get(k) != updated_properties.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict(
            (k, updated_properties.get(k)) for k in changed_properties_set)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, head, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref', 'Fn::GetAtt'):
                    if key == 'Fn::GetAtt':
                        value, head = value

                    try:
                        target = self.stack.resources[value]
                    except KeyError:
                        raise exception.InvalidTemplateReference(
                            resource=value, key=head)
                    if key == 'DependsOn' or target.strict_dependency:
                        deps += (self, target)
                else:
                    self._add_dependencies(deps, key, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, head, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, None, self.t)
        deps += (self, None)

    def required_by(self):
        '''
        Returns a list of names of resources which directly require this
        resource as a dependency.
        '''
        return list(
            [r.name for r in self.stack.dependencies.required_by(self)])

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def neutron(self):
        return self.stack.clients.neutron()

    def cinder(self):
        return self.stack.clients.cinder()

    def ceilometer(self):
        return self.stack.clients.ceilometer()

    def _do_action(self, action, pre_func=None):
        '''
        Perform a transition to a new state via a specified action
        action should be e.g self.CREATE, self.UPDATE etc, we set
        status based on this, the transistion is handled by calling the
        corresponding handle_* and check_*_complete functions
        Note pre_func is an optional function reference which will
        be called before the handle_<action> function

        If the resource does not declare a check_$action_complete function,
        we declare COMPLETE status as soon as the handle_$action call has
        finished, and if no handle_$action function is declared, then we do
        nothing, useful e.g if the resource requires no action for a given
        state transition
        '''
        assert action in self.ACTIONS, 'Invalid action %s' % action

        try:
            self.state_set(action, self.IN_PROGRESS)

            action_l = action.lower()
            handle = getattr(self, 'handle_%s' % action_l, None)
            check = getattr(self, 'check_%s_complete' % action_l, None)

            if callable(pre_func):
                pre_func()

            handle_data = None
            if callable(handle):
                handle_data = handle()
                yield
                if callable(check):
                    while not check(handle_data):
                        yield
        except Exception as ex:
            logger.exception('%s : %s' % (action, str(self)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, '%s aborted' % action)
                except Exception:
                    logger.exception('Error marking resource as failed')
        else:
            self.state_set(action, self.COMPLETE)

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        action = self.CREATE
        if (self.action, self.status) != (self.INIT, self.COMPLETE):
            exc = exception.Error('State %s invalid for create' %
                                  str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('creating %s' % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the AWS::StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self._resolve_runtime_data, self.name)
        return self._do_action(action, self.properties.validate)

    def update(self, after, before=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        if before is None:
            before = self.parsed_template()

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS)):
            exc = Exception('Resource update already requested')
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data, self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(after, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)

    def suspend(self):
        '''
        Suspend the resource.  Subclasses should provide a handle_suspend()
        method to implement suspend
        '''
        action = self.SUSPEND

        # Don't try to suspend the resource unless it's in a stable state
        if (self.action == self.DELETE or self.status != self.COMPLETE):
            exc = exception.Error('State %s invalid for suspend' %
                                  str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('suspending %s' % str(self))
        return self._do_action(action)

    def resume(self):
        '''
        Resume the resource.  Subclasses should provide a handle_resume()
        method to implement resume
        '''
        action = self.RESUME

        # Can't resume a resource unless it's SUSPEND_COMPLETE
        if self.state != (self.SUSPEND, self.COMPLETE):
            exc = exception.Error('State %s invalid for resume' %
                                  str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('resuming %s' % str(self))
        return self._do_action(action)

    def physical_resource_name(self):
        if self.id is None:
            return None

        return '%s-%s-%s' % (self.stack.name, self.name,
                             short_id.get_id(self.id))

    def validate(self):
        logger.info('Validating %s' % str(self))

        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get('DeletionPolicy', 'Delete')
        if deletion_policy not in ('Delete', 'Retain', 'Snapshot'):
            msg = 'Invalid DeletionPolicy %s' % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == 'Snapshot':
            if not callable(getattr(cls, 'handle_snapshot_delete', None)):
                msg = 'Snapshot DeletionPolicy not supported'
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        action = self.DELETE

        if (self.action, self.status) == (self.DELETE, self.COMPLETE):
            return
        # No need to delete if the resource has never been created
        if self.action == self.INIT:
            return

        initial_state = self.state

        logger.info('deleting %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)

            deletion_policy = self.t.get('DeletionPolicy', 'Delete')
            if deletion_policy == 'Delete':
                if callable(getattr(self, 'handle_delete', None)):
                    self.handle_delete()
            elif deletion_policy == 'Snapshot':
                if callable(getattr(self, 'handle_snapshot_delete', None)):
                    self.handle_snapshot_delete(initial_state)
        except Exception as ex:
            logger.exception('Delete %s', str(self))
            failure = exception.ResourceFailure(ex, self, self.action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, 'Deletion aborted')
                except Exception:
                    logger.exception('Error marking resource deletion failed')
        else:
            self.state_set(action, self.COMPLETE)

    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn('db error %s' % str(ex))

    def _store(self):
        '''Create the resource in the database.'''
        metadata = self.metadata
        try:
            rs = {
                'action': self.action,
                'status': self.status,
                'status_reason': self.status_reason,
                'stack_id': self.stack.id,
                'nova_instance': self.resource_id,
                'name': self.name,
                'rsrc_metadata': metadata,
                'stack_name': self.stack.name
            }

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _add_event(self, action, status, reason):
        '''Add a state change event to the database.'''
        ev = event.Event(self.context, self.stack, action, status, reason,
                         self.resource_id, self.properties, self.name,
                         self.type())

        try:
            ev.store()
        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _store_or_update(self, action, status, reason):
        self.action = action
        self.status = status
        self.status_reason = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({
                    'action': self.action,
                    'status': self.status,
                    'status_reason': reason,
                    'stack_id': self.stack.id,
                    'nova_instance': self.resource_id
                })

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error('DB error %s' % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif (action, status) == (self.CREATE, self.IN_PROGRESS):
            self._store()

    def _resolve_attribute(self, name):
        """
        Default implementation; should be overridden by resources that expose
        attributes

        :param name: The attribute to resolve
        :returns: the resource attribute named key
        """
        # By default, no attributes resolve
        pass

    def state_reset(self):
        """
        Reset state to (INIT, COMPLETE)
        """
        self.action = self.INIT
        self.status = self.COMPLETE

    def state_set(self, action, status, reason="state changed"):
        if action not in self.ACTIONS:
            raise ValueError("Invalid action %s" % action)

        if status not in self.STATUSES:
            raise ValueError("Invalid status %s" % status)

        old_state = (self.action, self.status)
        new_state = (action, status)
        self._store_or_update(action, status, reason)

        if new_state != old_state:
            self._add_event(action, status, reason)

    @property
    def state(self):
        '''Returns state, tuple of action, status.'''
        return (self.action, self.status)

    def FnGetRefId(self):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        '''
        try:
            return self.attributes[key]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name,
                                                     key=key)

    def FnBase64(self, data):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        '''
        return base64.b64encode(data)

    def signal(self, details=None):
        '''
        signal the resource. Subclasses should provide a handle_signal() method
        to implement the signal, the base-class raise an exception if no
        handler is implemented.
        '''
        try:
            if self.action in (self.SUSPEND, self.DELETE):
                msg = 'Cannot signal resource during %s' % self.action
                raise Exception(msg)

            if not callable(getattr(self, 'handle_signal', None)):
                msg = 'Resource %s is not able to receive a signal' % str(self)
                raise Exception(msg)

            self._add_event('signal', self.status, details)
            self.handle_signal(details)
        except Exception as ex:
            logger.exception('signal %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self)
            raise failure

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            logger.warning("Resource %s does not implement metadata update" %
                           self.name)

    @classmethod
    def resource_to_template(cls, resource_type):
        '''
        :param resource_type: The resource type to be displayed in the template
        :param explode_nested: True if a resource's nested properties schema
            should be resolved.
        :returns: A template where the resource's properties_schema is mapped
            as parameters, and the resource's attributes_schema is mapped as
            outputs
        '''
        (parameters,
         properties) = (Properties.schema_to_parameters_and_properties(
             cls.properties_schema))

        resource_name = cls.__name__
        return {
            'Parameters': parameters,
            'Resources': {
                resource_name: {
                    'Type': resource_type,
                    'Properties': properties
                }
            },
            'Outputs': Attributes.as_outputs(resource_name, cls)
        }
Esempio n. 17
0
class Resource(object):
    ACTIONS = (INIT, CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND, RESUME, ADOPT
               ) = ('INIT', 'CREATE', 'DELETE', 'UPDATE', 'ROLLBACK',
                    'SUSPEND', 'RESUME', 'ADOPT')

    STATUSES = (IN_PROGRESS, FAILED, COMPLETE
                ) = ('IN_PROGRESS', 'FAILED', 'COMPLETE')

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    # Resource implementations set this to the name: description dictionary
    # that describes the appropriate resource attributes
    attributes_schema = {}

    # If True, this resource may perform authenticated API requests
    # throughout its lifecycle
    requires_deferred_auth = False

    # Limit to apply to physical_resource_name() size reduction algorithm.
    # If set to None no limit will be applied.
    physical_resource_name_limit = 255

    support_status = support.SupportStatus()

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = stack.env.get_class(json.get('Type'),
                                            resource_name=name)
        return ResourceClass(name, json, stack)

    def __init__(self, name, definition, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        if isinstance(definition, rsrc_defn.ResourceDefinition):
            self.t = definition
        else:
            self.t = self.stack.resolve_static_data(definition)
        self.reparse()
        self.attributes = Attributes(self.name,
                                     self.attributes_schema,
                                     self._resolve_attribute)

        self.abandon_in_progress = False

        resource = stack.db_resource_get(name)

        if resource:
            self.resource_id = resource.nova_instance
            self.action = resource.action
            self.status = resource.status
            self.status_reason = resource.status_reason
            self.id = resource.id
            try:
                self._data = db_api.resource_data_get_all(self, resource.data)
            except exception.NotFound:
                self._data = {}
            self._rsrc_metadata = resource.rsrc_metadata
            self.created_time = resource.created_at
            self.updated_time = resource.updated_at
        else:
            self.resource_id = None
            # if the stack is being deleted, assume we've already been deleted
            if stack.action == stack.DELETE:
                self.action = self.DELETE
            else:
                self.action = self.INIT
            self.status = self.COMPLETE
            self.status_reason = ''
            self.id = None
            self._data = {}
            self._rsrc_metadata = None
            self.created_time = None
            self.updated_time = None

    def reparse(self):
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     function.resolve,
                                     self.name,
                                     self.context)

    def __eq__(self, other):
        '''Allow == comparison of two resources.'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (
                self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources.'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def metadata_get(self, refresh=False):
        if refresh:
            self._rsrc_metadata = None
        if self.id is None:
            return self.parsed_template('Metadata')
        if self._rsrc_metadata is not None:
            return self._rsrc_metadata
        rs = db_api.resource_get(self.stack.context, self.id)
        rs.refresh(attrs=['rsrc_metadata'])
        self._rsrc_metadata = rs.rsrc_metadata
        return rs.rsrc_metadata

    def metadata_set(self, metadata):
        if self.id is None:
            raise exception.ResourceNotAvailable(resource_name=self.name)
        rs = db_api.resource_get(self.stack.context, self.id)
        rs.update_and_save({'rsrc_metadata': metadata})
        self._rsrc_metadata = metadata

    def type(self):
        return self.t['Type']

    def has_interface(self, resource_type):
        """Check to see if this resource is either mapped to resource_type
        or is a "resource_type".
        """
        if self.type() == resource_type:
            return True
        ri = self.stack.env.get_resource_info(self.type(),
                                              self.name)
        return ri.name == resource_type

    def implementation_signature(self):
        '''
        Return a tuple defining the implementation.

        This should be broken down into a definition and an
        implementation version.
        '''

        return (self.__class__.__name__, self.support_status.version)

    def identifier(self):
        '''Return an identifier for this resource.'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return function.resolve(template)

    def update_template_diff(self, after, before):
        '''
        Returns the difference between the before and after json snippets. If
        something has been removed in after which exists in before we set it to
        None.
        '''
        # Create a set containing the keys in both current and update template
        template_keys = set(before.keys())
        template_keys.update(set(after.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set([k for k in template_keys
                                if before.get(k) != after.get(k)])

        return dict((k, after.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, after_props, before_props):
        '''
        Returns the changed Properties between the before and after properties.
        If any properties have changed which are not in
        update_allowed_properties, raises UpdateReplace.
        '''
        update_allowed_set = set(self.update_allowed_properties)
        for (psk, psv) in self.properties.props.iteritems():
            if psv.update_allowed():
                update_allowed_set.add(psk)

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(k for k in after_props
                                     if before_props.get(k) !=
                                     after_props.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict((k, after_props.get(k)) for k in changed_properties_set)

    def __str__(self):
        if self.stack.id:
            if self.resource_id:
                return '%s "%s" [%s] %s' % (self.__class__.__name__, self.name,
                                            self.resource_id, str(self.stack))
            return '%s "%s" %s' % (self.__class__.__name__, self.name,
                                   str(self.stack))
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def add_dependencies(self, deps):
        for dep in self.t.dependencies(self.stack):
            deps += (self, dep)
        deps += (self, None)

    def required_by(self):
        '''
        Returns a list of names of resources which directly require this
        resource as a dependency.
        '''
        return list(
            [r.name for r in self.stack.dependencies.required_by(self)])

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def neutron(self):
        return self.stack.clients.neutron()

    def cinder(self):
        return self.stack.clients.cinder()

    def trove(self):
        return self.stack.clients.trove()

    def ceilometer(self):
        return self.stack.clients.ceilometer()

    def heat(self):
        return self.stack.clients.heat()

    def glance(self):
        return self.stack.clients.glance()

    def _do_action(self, action, pre_func=None, resource_data=None):
        '''
        Perform a transition to a new state via a specified action
        action should be e.g self.CREATE, self.UPDATE etc, we set
        status based on this, the transition is handled by calling the
        corresponding handle_* and check_*_complete functions
        Note pre_func is an optional function reference which will
        be called before the handle_<action> function

        If the resource does not declare a check_$action_complete function,
        we declare COMPLETE status as soon as the handle_$action call has
        finished, and if no handle_$action function is declared, then we do
        nothing, useful e.g if the resource requires no action for a given
        state transition
        '''
        assert action in self.ACTIONS, 'Invalid action %s' % action

        try:
            self.state_set(action, self.IN_PROGRESS)

            action_l = action.lower()
            handle = getattr(self, 'handle_%s' % action_l, None)
            check = getattr(self, 'check_%s_complete' % action_l, None)

            if callable(pre_func):
                pre_func()

            handle_data = None
            if callable(handle):
                handle_data = (handle(resource_data) if resource_data else
                               handle())
                yield
                if callable(check):
                    while not check(handle_data):
                        yield
        except Exception as ex:
            LOG.exception('%s : %s' % (action, str(self)))  # noqa
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, six.text_type(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED,
                                   '%s aborted' % action)
                except Exception:
                    LOG.exception(_('Error marking resource as failed'))
        else:
            self.state_set(action, self.COMPLETE)

    def preview(self):
        '''
        Default implementation of Resource.preview.

        This method should be overridden by child classes for specific
        behavior.
        '''
        return self

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        action = self.CREATE
        if (self.action, self.status) != (self.INIT, self.COMPLETE):
            exc = exception.Error(_('State %s invalid for create')
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        LOG.info(_('creating %s') % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.reparse()
        return self._do_action(action, self.properties.validate)

    def prepare_abandon(self):
        self.abandon_in_progress = True
        return {
            'name': self.name,
            'resource_id': self.resource_id,
            'type': self.type(),
            'action': self.action,
            'status': self.status,
            'metadata': self.metadata_get(refresh=True),
            'resource_data': self.data()
        }

    def adopt(self, resource_data):
        '''
        Adopt the existing resource. Resource subclasses can provide
        a handle_adopt() method to customise adopt.
        '''
        return self._do_action(self.ADOPT, resource_data=resource_data)

    def handle_adopt(self, resource_data=None):
        resource_id, data, metadata = self._get_resource_info(resource_data)

        if not resource_id:
            exc = Exception(_('Resource ID was not provided.'))
            failure = exception.ResourceFailure(exc, self)
            raise failure

        # set resource id
        self.resource_id_set(resource_id)

        # save the resource data
        if data and isinstance(data, dict):
            for key, value in data.iteritems():
                self.data_set(key, value)

        # save the resource metadata
        self.metadata_set(metadata)

    def _get_resource_info(self, resource_data):
        if not resource_data:
            return None, None, None

        return (resource_data.get('resource_id'),
                resource_data.get('resource_data'),
                resource_data.get('metadata'))

    def update(self, after, before=None, prev_resource=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        (cur_class_def, cur_ver) = self.implementation_signature()
        prev_ver = cur_ver
        if prev_resource is not None:
            (prev_class_def,
             prev_ver) = prev_resource.implementation_signature()
            if prev_class_def != cur_class_def:
                raise UpdateReplace(self.name)

        if before is None:
            before = self.parsed_template()
        if prev_ver == cur_ver and before == after:
            return

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS),
                                          (self.ADOPT, self.IN_PROGRESS)):
            exc = Exception(_('Resource update already requested'))
            raise exception.ResourceFailure(exc, self, action)

        LOG.info(_('updating %s') % str(self))

        try:
            self.updated_time = datetime.utcnow()
            self.state_set(action, self.IN_PROGRESS)
            before_properties = Properties(self.properties_schema,
                                           before.get('Properties', {}),
                                           function.resolve,
                                           self.name,
                                           self.context)
            after_properties = Properties(self.properties_schema,
                                          after.get('Properties', {}),
                                          function.resolve,
                                          self.name,
                                          self.context)
            after_properties.validate()
            tmpl_diff = self.update_template_diff(function.resolve(after),
                                                  before)
            prop_diff = self.update_template_diff_properties(after_properties,
                                                             before_properties)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            with excutils.save_and_reraise_exception():
                LOG.debug("Resource %s update requires replacement" %
                          self.name)
        except Exception as ex:
            LOG.exception(_('update %(resource)s : %(err)s') %
                          {'resource': str(self), 'err': ex})
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, six.text_type(failure))
            raise failure
        else:
            self.t = after
            self.reparse()
            self.state_set(action, self.COMPLETE)

    def suspend(self):
        '''
        Suspend the resource.  Subclasses should provide a handle_suspend()
        method to implement suspend
        '''
        action = self.SUSPEND

        # Don't try to suspend the resource unless it's in a stable state
        if (self.action == self.DELETE or self.status != self.COMPLETE):
            exc = exception.Error(_('State %s invalid for suspend')
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        LOG.info(_('suspending %s') % str(self))
        return self._do_action(action)

    def resume(self):
        '''
        Resume the resource.  Subclasses should provide a handle_resume()
        method to implement resume
        '''
        action = self.RESUME

        # Can't resume a resource unless it's SUSPEND_COMPLETE
        if self.state != (self.SUSPEND, self.COMPLETE):
            exc = exception.Error(_('State %s invalid for resume')
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        LOG.info(_('resuming %s') % str(self))
        return self._do_action(action)

    def physical_resource_name(self):
        if self.id is None:
            return None

        name = '%s-%s-%s' % (self.stack.name,
                             self.name,
                             short_id.get_id(self.id))

        if self.physical_resource_name_limit:
            name = self.reduce_physical_resource_name(
                name, self.physical_resource_name_limit)
        return name

    @staticmethod
    def reduce_physical_resource_name(name, limit):
        '''
        Reduce length of physical resource name to a limit.

        The reduced name will consist of the following:

        * the first 2 characters of the name
        * a hyphen
        * the end of the name, truncated on the left to bring
          the name length within the limit

        :param name: The name to reduce the length of
        :param limit: The max length limit
        :returns: A name whose length is less than or equal to the limit
        '''
        if len(name) <= limit:
            return name

        if limit < 4:
            raise ValueError(_('limit cannot be less than 4'))

        postfix_length = limit - 3
        return name[0:2] + '-' + name[-postfix_length:]

    def validate(self):
        LOG.info(_('Validating %s') % str(self))

        function.validate(self.t)
        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get('DeletionPolicy', DELETE)
        if deletion_policy not in DELETION_POLICY:
            msg = _('Invalid DeletionPolicy %s') % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == SNAPSHOT:
            if not callable(getattr(cls, 'handle_snapshot_delete', None)):
                msg = _('Snapshot DeletionPolicy not supported')
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        action = self.DELETE

        if (self.action, self.status) == (self.DELETE, self.COMPLETE):
            return
        # No need to delete if the resource has never been created
        if self.action == self.INIT:
            return

        initial_state = self.state

        LOG.info(_('deleting %s') % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)

            if self.abandon_in_progress:
                deletion_policy = RETAIN
            else:
                deletion_policy = self.t.get('DeletionPolicy', DELETE)
            handle_data = None
            if deletion_policy == DELETE:
                if callable(getattr(self, 'handle_delete', None)):
                    handle_data = self.handle_delete()
                    yield
            elif deletion_policy == SNAPSHOT:
                if callable(getattr(self, 'handle_snapshot_delete', None)):
                    handle_data = self.handle_snapshot_delete(initial_state)
                    yield

            if (deletion_policy != RETAIN and
                    callable(getattr(self, 'check_delete_complete', None))):
                while not self.check_delete_complete(handle_data):
                    yield

        except Exception as ex:
            LOG.exception(_('Delete %s') % str(self))
            failure = exception.ResourceFailure(ex, self, self.action)
            self.state_set(action, self.FAILED, six.text_type(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED,
                                   'Deletion aborted')
                except Exception:
                    LOG.exception(_('Error marking resource deletion failed'))
        else:
            self.state_set(action, self.COMPLETE)

    @scheduler.wrappertask
    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        yield self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                LOG.warn(_('db error %s') % ex)

    def _store(self):
        '''Create the resource in the database.'''
        metadata = self.metadata_get()
        try:
            rs = {'action': self.action,
                  'status': self.status,
                  'status_reason': self.status_reason,
                  'stack_id': self.stack.id,
                  'nova_instance': self.resource_id,
                  'name': self.name,
                  'rsrc_metadata': metadata,
                  'stack_name': self.stack.name}

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id
            self.created_time = new_rs.created_at
            self._rsrc_metadata = metadata
        except Exception as ex:
            LOG.error(_('DB error %s') % ex)

    def _add_event(self, action, status, reason):
        '''Add a state change event to the database.'''
        ev = event.Event(self.context, self.stack, action, status, reason,
                         self.resource_id, self.properties,
                         self.name, self.type())

        ev.store()

    def _store_or_update(self, action, status, reason):
        self.action = action
        self.status = status
        self.status_reason = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'action': self.action,
                                    'status': self.status,
                                    'status_reason': reason,
                                    'stack_id': self.stack.id,
                                    'updated_at': self.updated_time,
                                    'nova_instance': self.resource_id})
            except Exception as ex:
                LOG.error(_('DB error %s') % ex)

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transitions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif (action, status) in [(self.CREATE, self.IN_PROGRESS),
                                  (self.ADOPT, self.IN_PROGRESS)]:
            self._store()

    def _resolve_attribute(self, name):
        """
        Default implementation; should be overridden by resources that expose
        attributes

        :param name: The attribute to resolve
        :returns: the resource attribute named key
        """
        # By default, no attributes resolve
        pass

    def state_reset(self):
        """
        Reset state to (INIT, COMPLETE)
        """
        self.action = self.INIT
        self.status = self.COMPLETE

    def state_set(self, action, status, reason="state changed"):
        if action not in self.ACTIONS:
            raise ValueError(_("Invalid action %s") % action)

        if status not in self.STATUSES:
            raise ValueError(_("Invalid status %s") % status)

        old_state = (self.action, self.status)
        new_state = (action, status)
        self._store_or_update(action, status, reason)

        if new_state != old_state:
            self._add_event(action, status, reason)

    @property
    def state(self):
        '''Returns state, tuple of action, status.'''
        return (self.action, self.status)

    def FnGetRefId(self):
        '''
        For the intrinsic function Ref.

        :results: the id or name of the resource.
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        For the intrinsic function Fn::GetAtt.

        :param key: the attribute key.
        :returns: the attribute value.
        '''
        try:
            return self.attributes[key]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name,
                                                     key=key)

    def FnBase64(self, data):
        '''
        For the instrinsic function Fn::Base64.

        :param data: the input data.
        :returns: the Base64 representation of the input data.
        '''
        return base64.b64encode(data)

    def signal(self, details=None):
        '''
        signal the resource. Subclasses should provide a handle_signal() method
        to implement the signal, the base-class raise an exception if no
        handler is implemented.
        '''
        def get_string_details():
            if details is None:
                return 'No signal details provided'
            if isinstance(details, basestring):
                return details
            if isinstance(details, dict):
                if all(k in details for k in ('previous', 'current',
                                              'reason')):
                    # this is from Ceilometer.
                    auto = '%(previous)s to %(current)s (%(reason)s)' % details
                    return 'alarm state changed from %s' % auto
                elif 'state' in details:
                    # this is from watchrule
                    return 'alarm state changed to %(state)s' % details
                elif 'deploy_status_code' in details:
                    # this is for SoftwareDeployment
                    if details['deploy_status_code'] == 0:
                        return 'deployment succeeded'
                    else:
                        return ('deployment failed '
                                '(%(deploy_status_code)s)' % details)

            return 'Unknown'

        try:
            if not callable(getattr(self, 'handle_signal', None)):
                msg = (_('Resource %s is not able to receive a signal') %
                       str(self))
                raise Exception(msg)

            self._add_event('signal', self.status, get_string_details())
            self.handle_signal(details)
        except Exception as ex:
            LOG.exception(_('signal %(name)s : %(msg)s') % {'name': str(self),
                                                            'msg': ex})
            failure = exception.ResourceFailure(ex, self)
            raise failure

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        if prop_diff:
            raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            LOG.warning(_("Resource %s does not implement metadata update")
                        % self.name)

    @classmethod
    def resource_to_template(cls, resource_type):
        '''
        :param resource_type: The resource type to be displayed in the template
        :returns: A template where the resource's properties_schema is mapped
            as parameters, and the resource's attributes_schema is mapped as
            outputs
        '''
        (parameters, properties) = (Properties.
                                    schema_to_parameters_and_properties(
                                        cls.properties_schema))

        resource_name = cls.__name__
        return {
            'HeatTemplateFormatVersion': '2012-12-12',
            'Parameters': parameters,
            'Resources': {
                resource_name: {
                    'Type': resource_type,
                    'Properties': properties
                }
            },
            'Outputs': Attributes.as_outputs(resource_name, cls)
        }

    def data(self):
        '''
        Resource data for this resource

        Use methods data_set and data_delete to modify the resource data
        for this resource.

        :returns: a dict representing the resource data for this resource.
        '''
        if self._data is None and self.id:
            try:
                self._data = db_api.resource_data_get_all(self)
            except exception.NotFound:
                pass

        return self._data or {}

    def data_set(self, key, value, redact=False):
        '''Save resource's key/value pair to database.'''
        db_api.resource_data_set(self, key, value, redact)
        # force fetch all resource data from the database again
        self._data = None

    def data_delete(self, key):
        '''
        Remove a resource_data element associated to a resource.

        :returns: True if the key existed to delete
        '''
        try:
            db_api.resource_data_delete(self, key)
        except exception.NotFound:
            return False
        else:
            # force fetch all resource data from the database again
            self._data = None
            return True
Esempio n. 18
0
class Resource(object):
    ACTIONS = (INIT, CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND, RESUME
               ) = ('INIT', 'CREATE', 'DELETE', 'UPDATE', 'ROLLBACK',
                    'SUSPEND', 'RESUME')

    STATUSES = (IN_PROGRESS, FAILED, COMPLETE
                ) = ('IN_PROGRESS', 'FAILED', 'COMPLETE')

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    # Resource implementations set this to the name: description dictionary
    # that describes the appropriate resource attributes
    attributes_schema = {}

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = get_class(json['Type'],
                                  resource_name=name,
                                  environment=stack.env)
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)
        self.attributes = Attributes(self.name,
                                     self.attributes_schema,
                                     self._resolve_attribute)

        resource = db_api.resource_get_by_name_and_stack(self.context,
                                                         name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.action = resource.action
            self.status = resource.status
            self.status_reason = resource.status_reason
            self.id = resource.id
            self.data = resource.data
        else:
            self.resource_id = None
            # if the stack is being deleted, assume we've already been deleted
            if stack.action == stack.DELETE:
                self.action = self.DELETE
            else:
                self.action = self.INIT
            self.status = self.COMPLETE
            self.status_reason = ''
            self.id = None
            self.data = []

    def __eq__(self, other):
        '''Allow == comparison of two resources.'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (
                self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources.'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t['Type']

    def identifier(self):
        '''Return an identifier for this resource.'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self.stack.resolve_runtime_data(template)

    def update_template_diff(self, after, before):
        '''
        Returns the difference between the before and after json snippets. If
        something has been removed in after which exists in before we set it to
        None. If any keys have changed which are not in update_allowed_keys,
        raises UpdateReplace if the differing keys are not in
        update_allowed_keys
        '''
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        template_keys = set(before.keys())
        template_keys.update(set(after.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set([k for k in template_keys
                                if before.get(k) != after.get(k)])

        if not changed_keys_set.issubset(update_allowed_set):
            badkeys = changed_keys_set - update_allowed_set
            raise UpdateReplace(self.name)

        return dict((k, after.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, after, before):
        '''
        Returns the changed Properties between the before and after json
        snippets. If a property has been removed in after which exists in
        before we set it to None. If any properties have changed which are not
        in update_allowed_properties, raises UpdateReplace if the modified
        properties are not in the update_allowed_properties
        '''
        update_allowed_set = set(self.update_allowed_properties)

        # Create a set containing the keys in both current and update template
        current_properties = before.get('Properties', {})

        template_properties = set(current_properties.keys())
        updated_properties = after.get('Properties', {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(k for k in template_properties
                                     if current_properties.get(k) !=
                                     updated_properties.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict((k, updated_properties.get(k))
                    for k in changed_properties_set)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, head, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref', 'Fn::GetAtt'):
                    if key == 'Fn::GetAtt':
                        value, head = value

                    try:
                        target = self.stack.resources[value]
                    except KeyError:
                        raise exception.InvalidTemplateReference(
                            resource=value,
                            key=head)
                    if key == 'DependsOn' or target.strict_dependency:
                        deps += (self, target)
                else:
                    self._add_dependencies(deps, key, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, head, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, None, self.t)
        deps += (self, None)

    def required_by(self):
        '''
        Returns a list of names of resources which directly require this
        resource as a dependency.
        '''
        return list(
            [r.name for r in self.stack.dependencies.required_by(self)])

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def neutron(self):
        return self.stack.clients.neutron()

    def cinder(self):
        return self.stack.clients.cinder()

    def ceilometer(self):
        return self.stack.clients.ceilometer()

    def _do_action(self, action, pre_func=None):
        '''
        Perform a transition to a new state via a specified action
        action should be e.g self.CREATE, self.UPDATE etc, we set
        status based on this, the transistion is handled by calling the
        corresponding handle_* and check_*_complete functions
        Note pre_func is an optional function reference which will
        be called before the handle_<action> function

        If the resource does not declare a check_$action_complete function,
        we declare COMPLETE status as soon as the handle_$action call has
        finished, and if no handle_$action function is declared, then we do
        nothing, useful e.g if the resource requires no action for a given
        state transition
        '''
        assert action in self.ACTIONS, 'Invalid action %s' % action

        try:
            self.state_set(action, self.IN_PROGRESS)

            action_l = action.lower()
            handle = getattr(self, 'handle_%s' % action_l, None)
            check = getattr(self, 'check_%s_complete' % action_l, None)

            if callable(pre_func):
                pre_func()

            handle_data = None
            if callable(handle):
                handle_data = handle()
                yield
                if callable(check):
                    while not check(handle_data):
                        yield
        except Exception as ex:
            logger.exception('%s : %s' % (action, str(self)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED,
                                   '%s aborted' % action)
                except Exception:
                    logger.exception('Error marking resource as failed')
        else:
            self.state_set(action, self.COMPLETE)

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        action = self.CREATE
        if (self.action, self.status) != (self.INIT, self.COMPLETE):
            exc = exception.Error('State %s invalid for create'
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('creating %s' % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the AWS::StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)
        return self._do_action(action, self.properties.validate)

    def update(self, after, before=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        if before is None:
            before = self.parsed_template()

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS)):
            exc = Exception('Resource update already requested')
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self.stack.resolve_runtime_data,
                                    self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update(after, tmpl_diff, prop_diff)
        except UpdateReplace:
            logger.debug("Resource %s update requires replacement" % self.name)
            raise
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)

    def suspend(self):
        '''
        Suspend the resource.  Subclasses should provide a handle_suspend()
        method to implement suspend
        '''
        action = self.SUSPEND

        # Don't try to suspend the resource unless it's in a stable state
        if (self.action == self.DELETE or self.status != self.COMPLETE):
            exc = exception.Error('State %s invalid for suspend'
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('suspending %s' % str(self))
        return self._do_action(action)

    def resume(self):
        '''
        Resume the resource.  Subclasses should provide a handle_resume()
        method to implement resume
        '''
        action = self.RESUME

        # Can't resume a resource unless it's SUSPEND_COMPLETE
        if self.state != (self.SUSPEND, self.COMPLETE):
            exc = exception.Error('State %s invalid for resume'
                                  % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('resuming %s' % str(self))
        return self._do_action(action)

    def physical_resource_name(self):
        if self.id is None:
            return None

        return '%s-%s-%s' % (self.stack.name,
                             self.name,
                             short_id.get_id(self.id))

    def validate(self):
        logger.info('Validating %s' % str(self))

        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get('DeletionPolicy', 'Delete')
        if deletion_policy not in ('Delete', 'Retain', 'Snapshot'):
            msg = 'Invalid DeletionPolicy %s' % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == 'Snapshot':
            if not callable(getattr(cls, 'handle_snapshot_delete', None)):
                msg = 'Snapshot DeletionPolicy not supported'
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        action = self.DELETE

        if (self.action, self.status) == (self.DELETE, self.COMPLETE):
            return
        # No need to delete if the resource has never been created
        if self.action == self.INIT:
            return

        initial_state = self.state

        logger.info('deleting %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)

            deletion_policy = self.t.get('DeletionPolicy', 'Delete')
            if deletion_policy == 'Delete':
                if callable(getattr(self, 'handle_delete', None)):
                    self.handle_delete()
            elif deletion_policy == 'Snapshot':
                if callable(getattr(self, 'handle_snapshot_delete', None)):
                    self.handle_snapshot_delete(initial_state)
        except Exception as ex:
            logger.exception('Delete %s', str(self))
            failure = exception.ResourceFailure(ex, self, self.action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED,
                                   'Deletion aborted')
                except Exception:
                    logger.exception('Error marking resource deletion failed')
        else:
            self.state_set(action, self.COMPLETE)

    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn('db error %s' % str(ex))

    def _store(self):
        '''Create the resource in the database.'''
        try:
            rs = {'action': self.action,
                  'status': self.status,
                  'status_reason': self.status_reason,
                  'stack_id': self.stack.id,
                  'nova_instance': self.resource_id,
                  'name': self.name,
                  'rsrc_metadata': self.metadata,
                  'stack_name': self.stack.name}

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _add_event(self, action, status, reason):
        '''Add a state change event to the database.'''
        ev = event.Event(self.context, self.stack, self,
                         action, status, reason,
                         self.resource_id, self.properties)

        try:
            ev.store()
        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _store_or_update(self, action, status, reason):
        self.action = action
        self.status = status
        self.status_reason = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'action': self.action,
                                    'status': self.status,
                                    'status_reason': reason,
                                    'nova_instance': self.resource_id})

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error('DB error %s' % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif (action, status) == (self.CREATE, self.IN_PROGRESS):
            self._store()

    def _resolve_attribute(self, name):
        """
        Default implementation; should be overridden by resources that expose
        attributes

        :param name: The attribute to resolve
        :returns: the resource attribute named key
        """
        # By default, no attributes resolve
        pass

    def state_reset(self):
        """
        Reset state to (INIT, COMPLETE)
        """
        self.action = self.INIT
        self.status = self.COMPLETE

    def state_set(self, action, status, reason="state changed"):
        if action not in self.ACTIONS:
            raise ValueError("Invalid action %s" % action)

        if status not in self.STATUSES:
            raise ValueError("Invalid status %s" % status)

        old_state = (self.action, self.status)
        new_state = (action, status)
        self._store_or_update(action, status, reason)

        if new_state != old_state:
            self._add_event(action, status, reason)

    @property
    def state(self):
        '''Returns state, tuple of action, status.'''
        return (self.action, self.status)

    def FnGetRefId(self):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        '''
        try:
            return self.attributes[key]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name,
                                                     key=key)

    def FnBase64(self, data):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        '''
        return base64.b64encode(data)

    def signal(self, details=None):
        '''
        signal the resource. Subclasses should provide a handle_signal() method
        to implement the signal, the base-class raise an exception if no
        handler is implemented.
        '''
        try:
            if self.action in (self.SUSPEND, self.DELETE):
                msg = 'Cannot signal resource during %s' % self.action
                raise Exception(msg)

            if not callable(getattr(self, 'handle_signal', None)):
                msg = 'Resource %s is not able to receive a signal' % str(self)
                raise Exception(msg)

            self._add_event('signal', self.status, details)
            self.handle_signal(details)
        except Exception as ex:
            logger.exception('signal %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self)
            raise failure

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            logger.warning("Resource %s does not implement metadata update" %
                           self.name)

    @classmethod
    def resource_to_template(cls, resource_type):
        '''
        :param resource_type: The resource type to be displayed in the template
        :param explode_nested: True if a resource's nested properties schema
            should be resolved.
        :returns: A template where the resource's properties_schema is mapped
            as parameters, and the resource's attributes_schema is mapped as
            outputs
        '''
        (parameters, properties) = (Properties.
                                    schema_to_parameters_and_properties(
                                        cls.properties_schema))

        resource_name = cls.__name__
        return {
            'Parameters': parameters,
            'Resources': {
                resource_name: {
                    'Type': resource_type,
                    'Properties': properties
                }
            },
            'Outputs': Attributes.as_outputs(resource_name, cls)
        }
Esempio n. 19
0
class InstanceGroup(stack_resource.StackResource):
    tags_schema = {
        'Key': {
            'Type': 'String',
            'Required': True
        },
        'Value': {
            'Type': 'String',
            'Required': True
        }
    }
    properties_schema = {
        'AvailabilityZones': {
            'Required': True,
            'Type': 'List'
        },
        'LaunchConfigurationName': {
            'Required': True,
            'Type': 'String'
        },
        'Size': {
            'Required': True,
            'Type': 'Number'
        },
        'LoadBalancerNames': {
            'Type': 'List'
        },
        'Tags': {
            'Type': 'List',
            'Schema': {
                'Type': 'Map',
                'Schema': tags_schema
            }
        }
    }
    update_allowed_keys = (
        'Properties',
        'UpdatePolicy',
    )
    update_allowed_properties = (
        'Size',
        'LaunchConfigurationName',
    )
    attributes_schema = {
        "InstanceList": ("A comma-delimited list of server ip addresses. "
                         "(Heat extension)")
    }
    rolling_update_schema = {
        'MinInstancesInService': properties.Schema(properties.NUMBER,
                                                   default=0),
        'MaxBatchSize': properties.Schema(properties.NUMBER, default=1),
        'PauseTime': properties.Schema(properties.STRING, default='PT0S')
    }
    update_policy_schema = {
        'RollingUpdate':
        properties.Schema(properties.MAP, schema=rolling_update_schema)
    }

    def __init__(self, name, json_snippet, stack):
        """
        UpdatePolicy is currently only specific to InstanceGroup and
        AutoScalingGroup. Therefore, init is overridden to parse for the
        UpdatePolicy.
        """
        super(InstanceGroup, self).__init__(name, json_snippet, stack)
        self.update_policy = Properties(self.update_policy_schema,
                                        self.t.get('UpdatePolicy', {}),
                                        parent_name=self.name)

    def validate(self):
        """
        Add validation for update_policy
        """
        super(InstanceGroup, self).validate()
        if self.update_policy:
            self.update_policy.validate()

    def get_instance_names(self):
        """Get a list of resource names of the instances in this InstanceGroup.

        Failed resources will be ignored.
        """
        return sorted(x.name for x in self.get_instances())

    def get_instances(self):
        """Get a set of all the instance resources managed by this group."""
        return [
            resource for resource in self.nested()
            if resource.state[1] != resource.FAILED
        ]

    def handle_create(self):
        """Create a nested stack and add the initial resources to it."""
        num_instances = int(self.properties['Size'])
        initial_template = self._create_template(num_instances)
        return self.create_with_template(initial_template, {})

    def check_create_complete(self, task):
        """
        When stack creation is done, update the load balancer.

        If any instances failed to be created, delete them.
        """
        done = super(InstanceGroup, self).check_create_complete(task)
        if done:
            self._lb_reload()
        return done

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """
        If Properties has changed, update self.properties, so we
        get the new values during any subsequent adjustment.
        """
        if tmpl_diff:
            # parse update policy
            if 'UpdatePolicy' in tmpl_diff:
                self.update_policy = Properties(self.update_policy_schema,
                                                json_snippet.get(
                                                    'UpdatePolicy', {}),
                                                parent_name=self.name)

        if prop_diff:
            self.properties = Properties(self.properties_schema,
                                         json_snippet.get('Properties', {}),
                                         self.stack.resolve_runtime_data,
                                         self.name)

            # Get the current capacity, we may need to adjust if
            # Size has changed
            if 'Size' in prop_diff:
                inst_list = self.get_instances()
                if len(inst_list) != int(self.properties['Size']):
                    self.resize(int(self.properties['Size']))

    def _tags(self):
        """
        Make sure that we add a tag that Ceilometer can pick up.
        These need to be prepended with 'metering.'.
        """
        tags = self.properties.get('Tags') or []
        for t in tags:
            if t['Key'].startswith('metering.'):
                # the user has added one, don't add another.
                return tags
        return tags + [{
            'Key': 'metering.groupname',
            'Value': self.FnGetRefId()
        }]

    def handle_delete(self):
        return self.delete_nested()

    def _create_template(self, num_instances):
        """
        Create a template with a number of instance definitions based on the
        launch configuration.
        """
        conf_name = self.properties['LaunchConfigurationName']
        conf = self.stack.resource_by_refid(conf_name)
        instance_definition = copy.deepcopy(conf.t)
        instance_definition['Type'] = 'AWS::EC2::Instance'
        instance_definition['Properties']['Tags'] = self._tags()
        if self.properties.get('VPCZoneIdentifier'):
            instance_definition['Properties']['SubnetId'] = \
                self.properties['VPCZoneIdentifier'][0]
        # resolve references within the context of this stack.
        fully_parsed = self.stack.resolve_runtime_data(instance_definition)

        resources = {}
        for i in range(num_instances):
            resources["%s-%d" % (self.name, i)] = fully_parsed
        return {"Resources": resources}

    def resize(self, new_capacity):
        """
        Resize the instance group to the new capacity.

        When shrinking, the newest instances will be removed.
        """
        new_template = self._create_template(new_capacity)
        try:
            self.update_with_template(new_template, {})
        finally:
            # Reload the LB in any case, so it's only pointing at healthy
            # nodes.
            self._lb_reload()

    def _lb_reload(self):
        '''
        Notify the LoadBalancer to reload its config to include
        the changes in instances we have just made.

        This must be done after activation (instance in ACTIVE state),
        otherwise the instances' IP addresses may not be available.
        '''
        if self.properties['LoadBalancerNames']:
            id_list = [inst.FnGetRefId() for inst in self.get_instances()]
            for lb in self.properties['LoadBalancerNames']:
                lb_resource = self.stack[lb]
                if 'Instances' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['Instances'] = (
                        id_list)
                elif 'members' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['members'] = (
                        id_list)
                else:
                    raise exception.Error(
                        "Unsupported resource '%s' in LoadBalancerNames" %
                        (lb, ))
                resolved_snippet = self.stack.resolve_static_data(
                    lb_resource.json_snippet)
                scheduler.TaskRunner(lb_resource.update, resolved_snippet)()

    def FnGetRefId(self):
        return unicode(self.name)

    def _resolve_attribute(self, name):
        '''
        heat extension: "InstanceList" returns comma delimited list of server
        ip addresses.
        '''
        if name == 'InstanceList':
            ips = [
                inst.FnGetAtt('PublicIp')
                for inst in self._nested.resources.values()
            ]
            if ips:
                return unicode(','.join(ips))
Esempio n. 20
0
class Resource(object):
    # Status strings
    CREATE_IN_PROGRESS = 'IN_PROGRESS'
    CREATE_FAILED = 'CREATE_FAILED'
    CREATE_COMPLETE = 'CREATE_COMPLETE'
    DELETE_IN_PROGRESS = 'DELETE_IN_PROGRESS'
    DELETE_FAILED = 'DELETE_FAILED'
    DELETE_COMPLETE = 'DELETE_COMPLETE'
    UPDATE_IN_PROGRESS = 'UPDATE_IN_PROGRESS'
    UPDATE_FAILED = 'UPDATE_FAILED'
    UPDATE_COMPLETE = 'UPDATE_COMPLETE'

    # Status values, returned from subclasses to indicate update method
    UPDATE_REPLACE = 'UPDATE_REPLACE'
    UPDATE_INTERRUPTION = 'UPDATE_INTERRUPTION'
    UPDATE_NO_INTERRUPTION = 'UPDATE_NO_INTERRUPTION'
    UPDATE_NOT_IMPLEMENTED = 'UPDATE_NOT_IMPLEMENTED'

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    metadata = Metadata()

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = get_class(json['Type']) or GenericResource
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.references = []
        self.stack = stack
        self.context = stack.context
        self.name = name
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self.stack.resolve_runtime_data,
                                     self.name)

        resource = db_api.resource_get_by_name_and_stack(self.context,
                                                         name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.state = resource.state
            self.state_description = resource.state_description
            self.id = resource.id
        else:
            self.resource_id = None
            self.state = None
            self.state_description = ''
            self.id = None
        self._nova = {}
        self._keystone = None
        self._swift = None
        self._quantum = None

    def __eq__(self, other):
        '''Allow == comparison of two resources'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (
                self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    def type(self):
        return self.t['Type']

    def identifier(self):
        '''Return an identifier for this resource'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self.stack.resolve_runtime_data(template)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref'):
                    target = self.stack.resources[value]
                    if key == 'DependsOn' or target.strict_dependency:
                        deps += (self, target)
                elif key != 'Fn::GetAtt':
                    self._add_dependencies(deps, value)
        elif isinstance(fragment, list):
            for item in fragment:
                self._add_dependencies(deps, item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, self.t)
        deps += (self, None)

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def quantum(self):
        return self.stack.clients.quantum()

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.CREATE_COMPLETE):
            return 'Resource creation already requested'

        logger.info('creating %s' % str(self))

        try:
            err = self.properties.validate()
            if err:
                return err
            self.state_set(self.CREATE_IN_PROGRESS)
            if callable(getattr(self, 'handle_create', None)):
                self.handle_create()
        except Exception as ex:
            logger.exception('create %s', str(self))
            self.state_set(self.CREATE_FAILED, str(ex))
            return str(ex)
        else:
            self.state_set(self.CREATE_COMPLETE)

    def update(self, json_snippet=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        if self.state in (self.CREATE_IN_PROGRESS, self.UPDATE_IN_PROGRESS):
            return 'Resource update already requested'

        if not json_snippet:
            return 'Must specify json snippet for resource update!'

        logger.info('updating %s' % str(self))

        result = self.UPDATE_NOT_IMPLEMENTED
        try:
            self.state_set(self.UPDATE_IN_PROGRESS)
            self.t = self.stack.resolve_static_data(json_snippet)
            err = self.properties.validate()
            if err:
                return err
            if callable(getattr(self, 'handle_update', None)):
                result = self.handle_update()
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            self.state_set(self.UPDATE_FAILED, str(ex))
            return str(ex)
        else:
            # If resource was updated (with or without interruption),
            # then we set the resource to UPDATE_COMPLETE
            if not result == self.UPDATE_REPLACE:
                self.state_set(self.UPDATE_COMPLETE)
            return result

    def physical_resource_name(self):
        return '%s.%s' % (self.stack.name, self.name)

    def physical_resource_name_find(self, resource_name):
        if resource_name in self.stack:
            return '%s.%s' % (self.stack.name, resource_name)
        else:
            raise IndexError('no such resource')

    def validate(self):
        logger.info('Validating %s' % str(self))

        return self.properties.validate()

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        if self.state == self.DELETE_COMPLETE:
            return
        if self.state == self.DELETE_IN_PROGRESS:
            return 'Resource deletion already in progress'

        logger.info('deleting %s (inst:%s db_id:%s)' %
                    (str(self), self.resource_id, str(self.id)))
        self.state_set(self.DELETE_IN_PROGRESS)

        try:
            if callable(getattr(self, 'handle_delete', None)):
                self.handle_delete()
        except Exception as ex:
            logger.exception('Delete %s', str(self))
            self.state_set(self.DELETE_FAILED, str(ex))
            return str(ex)

        self.state_set(self.DELETE_COMPLETE)

    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        result = self.delete()
        if result:
            return result

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass
        except Exception as ex:
            logger.exception('Delete %s from DB' % str(self))
            return str(ex)

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn('db error %s' % str(ex))

    def _store(self):
        '''Create the resource in the database'''
        try:
            rs = {'state': self.state,
                  'stack_id': self.stack.id,
                  'nova_instance': self.resource_id,
                  'name': self.name,
                  'rsrc_metadata': self.metadata,
                  'stack_name': self.stack.name}

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _add_event(self, new_state, reason):
        '''Add a state change event to the database'''
        ev = event.Event(self.context, self.stack, self,
                         new_state, reason,
                         self.resource_id, self.properties)

        try:
            ev.store()
        except Exception as ex:
            logger.error('DB error %s' % str(ex))

    def _store_or_update(self, new_state, reason):
        self.state = new_state
        self.state_description = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'state': self.state,
                                    'state_description': reason,
                                    'nova_instance': self.resource_id})

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error('DB error %s' % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif new_state == self.CREATE_IN_PROGRESS:
            self._store()

    def state_set(self, new_state, reason="state changed"):
        old_state = self.state
        self._store_or_update(new_state, reason)

        if new_state != old_state:
            self._add_event(new_state, reason)

    def FnGetRefId(self):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-ref.html
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
        intrinsic-function-reference-getatt.html
        '''
        return unicode(self.name)

    def FnBase64(self, data):
        '''
        http://docs.amazonwebservices.com/AWSCloudFormation/latest/UserGuide/\
            intrinsic-function-reference-base64.html
        '''
        return base64.b64encode(data)

    def handle_update(self):
        raise NotImplementedError("Update not implemented for Resource %s"
                                  % type(self))
Esempio n. 21
0
class Resource(object):
    ACTIONS = (INIT, CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND, RESUME,
               ADOPT) = ('INIT', 'CREATE', 'DELETE', 'UPDATE', 'ROLLBACK',
                         'SUSPEND', 'RESUME', 'ADOPT')

    STATUSES = (IN_PROGRESS, FAILED, COMPLETE) = ('IN_PROGRESS', 'FAILED',
                                                  'COMPLETE')

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, 'created_at')
    updated_time = timestamp.Timestamp(db_api.resource_get, 'updated_at')

    _metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    # Resource implementations set this to the name: description dictionary
    # that describes the appropriate resource attributes
    attributes_schema = {}

    # If True, this resource may perform authenticated API requests
    # throughout its lifecycle
    requires_deferred_auth = False

    # Limit to apply to physical_resource_name() size reduction algorithm.
    # If set to None no limit will be applied.
    physical_resource_name_limit = 255

    support_status = SupportStatus()

    def __new__(cls, name, json, stack):
        '''Create a new Resource of the appropriate class for its type.'''

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = stack.env.get_class(json.get('Type'),
                                            resource_name=name)
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if '/' in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self._resolve_runtime_data, self.name)
        self.attributes = Attributes(self.name, self.attributes_schema,
                                     self._resolve_attribute)

        if stack.id:
            resource = db_api.resource_get_by_name_and_stack(
                self.context, name, stack.id)
        else:
            resource = None

        if resource:
            self.resource_id = resource.nova_instance
            self.action = resource.action
            self.status = resource.status
            self.status_reason = resource.status_reason
            self.id = resource.id
            self.data = resource.data
        else:
            self.resource_id = None
            # if the stack is being deleted, assume we've already been deleted
            if stack.action == stack.DELETE:
                self.action = self.DELETE
            else:
                self.action = self.INIT
            self.status = self.COMPLETE
            self.status_reason = ''
            self.id = None
            self.data = []

    def __eq__(self, other):
        '''Allow == comparison of two resources.'''
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (self.parsed_template()
                                                  == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        '''Allow != comparison of two resources.'''
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    @property
    def metadata(self):
        return self._metadata

    @metadata.setter
    def metadata(self, metadata):
        self._metadata = metadata

    def type(self):
        return self.t['Type']

    def _resolve_runtime_data(self, snippet):
        return self.stack.resolve_runtime_data(snippet)

    def has_interface(self, resource_type):
        """Check to see if this resource is either mapped to resource_type
        or is a "resource_type".
        """
        if self.type() == resource_type:
            return True
        ri = self.stack.env.get_resource_info(self.type(), self.name)
        return ri.name == resource_type

    def implementation_signature(self):
        '''
        Return a tuple defining the implementation.

        This should be broken down into a definition and an
        implementation version.
        '''

        return (self.__class__.__name__, self.support_status.version)

    def identifier(self):
        '''Return an identifier for this resource.'''
        return identifier.ResourceIdentifier(resource_name=self.name,
                                             **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        '''
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        '''
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self._resolve_runtime_data(template)

    def update_template_diff(self, after, before):
        '''
        Returns the difference between the before and after json snippets. If
        something has been removed in after which exists in before we set it to
        None. If any keys have changed which are not in update_allowed_keys,
        raises UpdateReplace if the differing keys are not in
        update_allowed_keys
        '''
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        template_keys = set(before.keys())
        template_keys.update(set(after.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set(
            [k for k in template_keys if before.get(k) != after.get(k)])

        if not changed_keys_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict((k, after.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, after, before):
        '''
        Returns the changed Properties between the before and after json
        snippets. If a property has been removed in after which exists in
        before we set it to None. If any properties have changed which are not
        in update_allowed_properties, raises UpdateReplace if the modified
        properties are not in the update_allowed_properties
        '''
        update_allowed_set = set(self.update_allowed_properties)
        for (psk, psv) in self.properties.props.iteritems():
            if psv.update_allowed():
                update_allowed_set.add(psk)

        # Create a set containing the keys in both current and update template
        current_properties = before.get('Properties', {})

        template_properties = set(current_properties.keys())
        updated_properties = after.get('Properties', {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(
            k for k in template_properties
            if current_properties.get(k) != updated_properties.get(k))

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict(
            (k, updated_properties.get(k)) for k in changed_properties_set)

    def __str__(self):
        if self.stack.id:
            if self.resource_id:
                return '%s "%s" [%s] %s' % (self.__class__.__name__, self.name,
                                            self.resource_id, str(self.stack))
            return '%s "%s" %s' % (self.__class__.__name__, self.name,
                                   str(self.stack))
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, path, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ('DependsOn', 'Ref', 'Fn::GetAtt', 'get_attr',
                           'get_resource'):
                    if key in ('Fn::GetAtt', 'get_attr'):
                        res_name = value[0]
                        res_list = [res_name]
                    elif key == 'DependsOn' and isinstance(value, list):
                        res_list = value
                    else:
                        res_list = [value]

                    for res in res_list:
                        try:
                            target = self.stack[res]
                        except KeyError:
                            raise exception.InvalidTemplateReference(
                                resource=res, key=path)
                        if key == 'DependsOn' or target.strict_dependency:
                            deps += (self, target)
                else:
                    self._add_dependencies(deps, '%s.%s' % (path, key), value)
        elif isinstance(fragment, list):
            for index, item in enumerate(fragment):
                self._add_dependencies(deps, '%s[%d]' % (path, index), item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, self.name, self.t)
        deps += (self, None)

    def required_by(self):
        '''
        Returns a list of names of resources which directly require this
        resource as a dependency.
        '''
        return list(
            [r.name for r in self.stack.dependencies.required_by(self)])

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type='compute'):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def neutron(self):
        return self.stack.clients.neutron()

    def cinder(self):
        return self.stack.clients.cinder()

    def trove(self):
        return self.stack.clients.trove()

    def ceilometer(self):
        return self.stack.clients.ceilometer()

    def heat(self):
        return self.stack.clients.heat()

    def _do_action(self, action, pre_func=None, resource_data=None):
        '''
        Perform a transition to a new state via a specified action
        action should be e.g self.CREATE, self.UPDATE etc, we set
        status based on this, the transistion is handled by calling the
        corresponding handle_* and check_*_complete functions
        Note pre_func is an optional function reference which will
        be called before the handle_<action> function

        If the resource does not declare a check_$action_complete function,
        we declare COMPLETE status as soon as the handle_$action call has
        finished, and if no handle_$action function is declared, then we do
        nothing, useful e.g if the resource requires no action for a given
        state transition
        '''
        assert action in self.ACTIONS, 'Invalid action %s' % action

        try:
            self.state_set(action, self.IN_PROGRESS)

            action_l = action.lower()
            handle = getattr(self, 'handle_%s' % action_l, None)
            check = getattr(self, 'check_%s_complete' % action_l, None)

            if callable(pre_func):
                pre_func()

            handle_data = None
            if callable(handle):
                handle_data = (handle(resource_data)
                               if resource_data else handle())
                yield
                if callable(check):
                    while not check(handle_data):
                        yield
        except Exception as ex:
            logger.exception('%s : %s' % (action, str(self)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, '%s aborted' % action)
                except Exception:
                    logger.exception(_('Error marking resource as failed'))
        else:
            self.state_set(action, self.COMPLETE)

    def create(self):
        '''
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        '''
        action = self.CREATE
        if (self.action, self.status) != (self.INIT, self.COMPLETE):
            exc = exception.Error(
                _('State %s invalid for create') % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('creating %s' % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(self.properties_schema,
                                     self.t.get('Properties', {}),
                                     self._resolve_runtime_data, self.name)
        return self._do_action(action, self.properties.validate)

    def set_deletion_policy(self, policy):
        self.t['DeletionPolicy'] = policy

    def get_abandon_data(self):
        return {
            'name':
            self.name,
            'resource_id':
            self.resource_id,
            'type':
            self.type(),
            'action':
            self.action,
            'status':
            self.status,
            'metadata':
            self.metadata,
            'resource_data':
            dict((r.key, r.value) for r in db_api.resource_data_get_all(self))
        }

    def adopt(self, resource_data):
        '''
        Adopt the existing resource. Resource subclasses can provide
        a handle_adopt() method to customise adopt.
        '''
        return self._do_action(self.ADOPT, resource_data=resource_data)

    def handle_adopt(self, resource_data=None):
        resource_id, data, metadata = self._get_resource_info(resource_data)

        if not resource_id:
            exc = Exception(_('Resource ID was not provided.'))
            failure = exception.ResourceFailure(exc, self)
            raise failure

        # set resource id
        self.resource_id_set(resource_id)

        # save the resource data
        if data and isinstance(data, dict):
            for key, value in data.iteritems():
                db_api.resource_data_set(self, key, value)

        # save the resource metadata
        self.metadata = metadata

    def _get_resource_info(self, resource_data):
        if not resource_data:
            return None, None, None

        return (resource_data.get('resource_id'),
                resource_data.get('resource_data'),
                resource_data.get('metadata'))

    def update(self, after, before=None, prev_resource=None):
        '''
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        '''
        action = self.UPDATE

        (cur_class_def, cur_ver) = self.implementation_signature()
        prev_ver = cur_ver
        if prev_resource is not None:
            (prev_class_def,
             prev_ver) = prev_resource.implementation_signature()
            if prev_class_def != cur_class_def:
                raise UpdateReplace(self.name)

        if before is None:
            before = self.parsed_template()
        if prev_ver == cur_ver and before == after:
            return

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS),
                                          (self.UPDATE, self.IN_PROGRESS),
                                          (self.ADOPT, self.IN_PROGRESS)):
            exc = Exception(_('Resource update already requested'))
            raise exception.ResourceFailure(exc, self, action)

        logger.info('updating %s' % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(self.properties_schema,
                                    after.get('Properties', {}),
                                    self._resolve_runtime_data, self.name)
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, 'handle_update', None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, 'check_update_complete', None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            with excutils.save_and_reraise_exception():
                logger.debug(
                    _("Resource %s update requires replacement") % self.name)
        except Exception as ex:
            logger.exception('update %s : %s' % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)

    def suspend(self):
        '''
        Suspend the resource.  Subclasses should provide a handle_suspend()
        method to implement suspend
        '''
        action = self.SUSPEND

        # Don't try to suspend the resource unless it's in a stable state
        if (self.action == self.DELETE or self.status != self.COMPLETE):
            exc = exception.Error(
                _('State %s invalid for suspend') % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info(_('suspending %s') % str(self))
        return self._do_action(action)

    def resume(self):
        '''
        Resume the resource.  Subclasses should provide a handle_resume()
        method to implement resume
        '''
        action = self.RESUME

        # Can't resume a resource unless it's SUSPEND_COMPLETE
        if self.state != (self.SUSPEND, self.COMPLETE):
            exc = exception.Error(
                _('State %s invalid for resume') % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info(_('resuming %s') % str(self))
        return self._do_action(action)

    def physical_resource_name(self):
        if self.id is None:
            return None

        name = '%s-%s-%s' % (self.stack.name, self.name,
                             short_id.get_id(self.id))

        if self.physical_resource_name_limit:
            name = self.reduce_physical_resource_name(
                name, self.physical_resource_name_limit)
        return name

    @staticmethod
    def reduce_physical_resource_name(name, limit):
        '''
        Reduce length of physical resource name to a limit.

        The reduced name will consist of the following:

        * the first 2 characters of the name
        * a hyphen
        * the end of the name, truncated on the left to bring
          the name length within the limit

        :param name: The name to reduce the length of
        :param limit: The max length limit
        :returns: A name whose length is less than or equal to the limit
        '''
        if len(name) <= limit:
            return name

        if limit < 4:
            raise ValueError(_('limit cannot be less than 4'))

        postfix_length = limit - 3
        return name[0:2] + '-' + name[-postfix_length:]

    def validate(self):
        logger.info(_('Validating %s') % str(self))

        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get('DeletionPolicy', DELETE)
        if deletion_policy not in DELETION_POLICY:
            msg = _('Invalid DeletionPolicy %s') % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == SNAPSHOT:
            if not callable(getattr(cls, 'handle_snapshot_delete', None)):
                msg = _('Snapshot DeletionPolicy not supported')
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        '''
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        '''
        action = self.DELETE

        if (self.action, self.status) == (self.DELETE, self.COMPLETE):
            return
        # No need to delete if the resource has never been created
        if self.action == self.INIT:
            return

        initial_state = self.state

        logger.info(_('deleting %s') % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)

            deletion_policy = self.t.get('DeletionPolicy', DELETE)
            handle_data = None
            if deletion_policy == DELETE:
                if callable(getattr(self, 'handle_delete', None)):
                    handle_data = self.handle_delete()
                    yield
            elif deletion_policy == SNAPSHOT:
                if callable(getattr(self, 'handle_snapshot_delete', None)):
                    handle_data = self.handle_snapshot_delete(initial_state)
                    yield

            if (deletion_policy != RETAIN and callable(
                    getattr(self, 'check_delete_complete', None))):
                while not self.check_delete_complete(handle_data):
                    yield

        except Exception as ex:
            logger.exception(_('Delete %s'), str(self))
            failure = exception.ResourceFailure(ex, self, self.action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, 'Deletion aborted')
                except Exception:
                    logger.exception(
                        _('Error marking resource deletion '
                          'failed'))
        else:
            self.state_set(action, self.COMPLETE)

    @scheduler.wrappertask
    def destroy(self):
        '''
        Delete the resource and remove it from the database.
        '''
        yield self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({'nova_instance': self.resource_id})
            except Exception as ex:
                logger.warn(_('db error %s') % str(ex))

    def _store(self):
        '''Create the resource in the database.'''
        metadata = self.metadata
        try:
            rs = {
                'action': self.action,
                'status': self.status,
                'status_reason': self.status_reason,
                'stack_id': self.stack.id,
                'nova_instance': self.resource_id,
                'name': self.name,
                'rsrc_metadata': metadata,
                'stack_name': self.stack.name
            }

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error(_('DB error %s') % str(ex))

    def _add_event(self, action, status, reason):
        '''Add a state change event to the database.'''
        ev = event.Event(self.context, self.stack, action, status, reason,
                         self.resource_id, self.properties, self.name,
                         self.type())

        try:
            ev.store()
        except Exception as ex:
            logger.error(_('DB error %s') % str(ex))

    def _store_or_update(self, action, status, reason):
        self.action = action
        self.status = status
        self.status_reason = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({
                    'action': self.action,
                    'status': self.status,
                    'status_reason': reason,
                    'stack_id': self.stack.id,
                    'nova_instance': self.resource_id
                })

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error(_('DB error %s') % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif (action, status) in [(self.CREATE, self.IN_PROGRESS),
                                  (self.ADOPT, self.IN_PROGRESS)]:
            self._store()

    def _resolve_attribute(self, name):
        """
        Default implementation; should be overridden by resources that expose
        attributes

        :param name: The attribute to resolve
        :returns: the resource attribute named key
        """
        # By default, no attributes resolve
        pass

    def state_reset(self):
        """
        Reset state to (INIT, COMPLETE)
        """
        self.action = self.INIT
        self.status = self.COMPLETE

    def state_set(self, action, status, reason="state changed"):
        if action not in self.ACTIONS:
            raise ValueError(_("Invalid action %s") % action)

        if status not in self.STATUSES:
            raise ValueError(_("Invalid status %s") % status)

        old_state = (self.action, self.status)
        new_state = (action, status)
        self._store_or_update(action, status, reason)

        if new_state != old_state:
            self._add_event(action, status, reason)

    @property
    def state(self):
        '''Returns state, tuple of action, status.'''
        return (self.action, self.status)

    def FnGetRefId(self):
        '''
        For the intrinsic function Ref.

        :results: the id or name of the resource.
        '''
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        '''
        For the intrinsic function Fn::GetAtt.

        :param key: the attribute key.
        :returns: the attribute value.
        '''
        try:
            return self.attributes[key]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name,
                                                     key=key)

    def FnBase64(self, data):
        '''
        For the instrinsic function Fn::Base64.

        :param data: the input data.
        :returns: the Base64 representation of the input data.
        '''
        return base64.b64encode(data)

    def signal(self, details=None):
        '''
        signal the resource. Subclasses should provide a handle_signal() method
        to implement the signal, the base-class raise an exception if no
        handler is implemented.
        '''
        def get_string_details():
            if details is None:
                return 'No signal details provided'
            if isinstance(details, basestring):
                return details
            if isinstance(details, dict):
                if all(k in details
                       for k in ('previous', 'current', 'reason')):
                    # this is from Ceilometer.
                    auto = '%(previous)s to %(current)s (%(reason)s)' % details
                    return 'alarm state changed from %s' % auto
                elif 'state' in details:
                    # this is from watchrule
                    return 'alarm state changed to %(state)s' % details

            return 'Unknown'

        try:
            if self.action in (self.SUSPEND, self.DELETE):
                msg = _('Cannot signal resource during %s') % self.action
                raise Exception(msg)

            if not callable(getattr(self, 'handle_signal', None)):
                msg = (_('Resource %s is not able to receive a signal') %
                       str(self))
                raise Exception(msg)

            self._add_event('signal', self.status, get_string_details())
            self.handle_signal(details)
        except Exception as ex:
            logger.exception(
                _('signal %(name)s : %(msg)s') % {
                    'name': str(self),
                    'msg': str(ex)
                })
            failure = exception.ResourceFailure(ex, self)
            raise failure

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        '''
        No-op for resources which don't explicitly override this method
        '''
        if new_metadata:
            logger.warning(
                _("Resource %s does not implement metadata update") %
                self.name)

    @classmethod
    def resource_to_template(cls, resource_type):
        '''
        :param resource_type: The resource type to be displayed in the template
        :returns: A template where the resource's properties_schema is mapped
            as parameters, and the resource's attributes_schema is mapped as
            outputs
        '''
        (parameters,
         properties) = (Properties.schema_to_parameters_and_properties(
             cls.properties_schema))

        resource_name = cls.__name__
        return {
            'HeatTemplateFormatVersion': '2012-12-12',
            'Parameters': parameters,
            'Resources': {
                resource_name: {
                    'Type': resource_type,
                    'Properties': properties
                }
            },
            'Outputs': Attributes.as_outputs(resource_name, cls)
        }
Esempio n. 22
0
class InstanceGroup(stack_resource.StackResource):
    tags_schema = {'Key': {'Type': 'String',
                           'Required': True},
                   'Value': {'Type': 'String',
                             'Required': True}}
    properties_schema = {
        'AvailabilityZones': {
            'Required': True,
            'Type': 'List',
            'Description': _('Not Implemented.')},
        'LaunchConfigurationName': {
            'Required': True,
            'Type': 'String',
            'Description': _('Name of LaunchConfiguration resource.')},
        'Size': {
            'Required': True,
            'Type': 'Number',
            'Description': _('Desired number of instances.')},
        'LoadBalancerNames': {
            'Type': 'List',
            'Description': _('List of LoadBalancer resources.')},
        'Tags': {
            'Type': 'List',
            'Schema': {'Type': 'Map', 'Schema': tags_schema},
            'Description': _('Tags to attach to this group.')}
    }
    update_allowed_keys = ('Properties', 'UpdatePolicy',)
    update_allowed_properties = ('Size', 'LaunchConfigurationName',)
    attributes_schema = {
        "InstanceList": _("A comma-delimited list of server ip addresses. "
                          "(Heat extension).")
    }
    rolling_update_schema = {
        'MinInstancesInService': properties.Schema(properties.NUMBER,
                                                   default=0),
        'MaxBatchSize': properties.Schema(properties.NUMBER,
                                          default=1),
        'PauseTime': properties.Schema(properties.STRING,
                                       default='PT0S')
    }
    update_policy_schema = {
        'RollingUpdate': properties.Schema(properties.MAP,
                                           schema=rolling_update_schema)
    }

    def __init__(self, name, json_snippet, stack):
        """
        UpdatePolicy is currently only specific to InstanceGroup and
        AutoScalingGroup. Therefore, init is overridden to parse for the
        UpdatePolicy.
        """
        super(InstanceGroup, self).__init__(name, json_snippet, stack)
        self.update_policy = Properties(self.update_policy_schema,
                                        self.t.get('UpdatePolicy', {}),
                                        parent_name=self.name)

    def validate(self):
        """
        Add validation for update_policy
        """
        super(InstanceGroup, self).validate()
        if self.update_policy:
            self.update_policy.validate()

    def get_instance_names(self):
        """Get a list of resource names of the instances in this InstanceGroup.

        Failed resources will be ignored.
        """
        return sorted(x.name for x in self.get_instances())

    def get_instances(self):
        """Get a set of all the instance resources managed by this group."""
        return [resource for resource in self.nested().itervalues()
                if resource.state[1] != resource.FAILED]

    def handle_create(self):
        """Create a nested stack and add the initial resources to it."""
        num_instances = int(self.properties['Size'])
        initial_template = self._create_template(num_instances)
        return self.create_with_template(initial_template, {})

    def check_create_complete(self, task):
        """
        When stack creation is done, update the load balancer.

        If any instances failed to be created, delete them.
        """
        done = super(InstanceGroup, self).check_create_complete(task)
        if done:
            self._lb_reload()
        return done

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        """
        If Properties has changed, update self.properties, so we
        get the new values during any subsequent adjustment.
        """
        if tmpl_diff:
            # parse update policy
            if 'UpdatePolicy' in tmpl_diff:
                self.update_policy = Properties(
                    self.update_policy_schema,
                    json_snippet.get('UpdatePolicy', {}),
                    parent_name=self.name)

        if prop_diff:
            self.properties = Properties(self.properties_schema,
                                         json_snippet.get('Properties', {}),
                                         self.stack.resolve_runtime_data,
                                         self.name)

            # Get the current capacity, we may need to adjust if
            # Size has changed
            if 'Size' in prop_diff:
                inst_list = self.get_instances()
                if len(inst_list) != int(self.properties['Size']):
                    self.resize(int(self.properties['Size']))

    def _tags(self):
        """
        Make sure that we add a tag that Ceilometer can pick up.
        These need to be prepended with 'metering.'.
        """
        tags = self.properties.get('Tags') or []
        for t in tags:
            if t['Key'].startswith('metering.'):
                # the user has added one, don't add another.
                return tags
        return tags + [{'Key': 'metering.groupname',
                        'Value': self.FnGetRefId()}]

    def handle_delete(self):
        return self.delete_nested()

    def _create_template(self, num_instances):
        """
        Create a template with a number of instance definitions based on the
        launch configuration.
        """
        conf_name = self.properties['LaunchConfigurationName']
        conf = self.stack.resource_by_refid(conf_name)
        instance_definition = copy.deepcopy(conf.t)
        instance_definition['Type'] = 'AWS::EC2::Instance'
        instance_definition['Properties']['Tags'] = self._tags()
        if self.properties.get('VPCZoneIdentifier'):
            instance_definition['Properties']['SubnetId'] = \
                self.properties['VPCZoneIdentifier'][0]
        # resolve references within the context of this stack.
        fully_parsed = self.stack.resolve_runtime_data(instance_definition)

        resources = {}
        for i in range(num_instances):
            resources["%s-%d" % (self.name, i)] = fully_parsed
        return {"Resources": resources}

    def resize(self, new_capacity):
        """
        Resize the instance group to the new capacity.

        When shrinking, the newest instances will be removed.
        """
        new_template = self._create_template(new_capacity)
        try:
            updater = self.update_with_template(new_template, {})
            updater.run_to_completion()
            self.check_update_complete(updater)
        finally:
            # Reload the LB in any case, so it's only pointing at healthy
            # nodes.
            self._lb_reload()

    def _lb_reload(self):
        '''
        Notify the LoadBalancer to reload its config to include
        the changes in instances we have just made.

        This must be done after activation (instance in ACTIVE state),
        otherwise the instances' IP addresses may not be available.
        '''
        if self.properties['LoadBalancerNames']:
            id_list = [inst.FnGetRefId() for inst in self.get_instances()]
            for lb in self.properties['LoadBalancerNames']:
                lb_resource = self.stack[lb]
                if 'Instances' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['Instances'] = (
                        id_list)
                elif 'members' in lb_resource.properties_schema:
                    lb_resource.json_snippet['Properties']['members'] = (
                        id_list)
                else:
                    raise exception.Error(
                        "Unsupported resource '%s' in LoadBalancerNames" %
                        (lb,))
                resolved_snippet = self.stack.resolve_static_data(
                    lb_resource.json_snippet)
                scheduler.TaskRunner(lb_resource.update, resolved_snippet)()

    def FnGetRefId(self):
        return self.physical_resource_name()

    def _resolve_attribute(self, name):
        '''
        heat extension: "InstanceList" returns comma delimited list of server
        ip addresses.
        '''
        if name == 'InstanceList':
            return u','.join(inst.FnGetAtt('PublicIp')
                             for inst in self.get_instances()) or None
Esempio n. 23
0
class Resource(object):
    ACTIONS = (INIT, CREATE, DELETE, UPDATE, ROLLBACK, SUSPEND, RESUME) = (
        "INIT",
        "CREATE",
        "DELETE",
        "UPDATE",
        "ROLLBACK",
        "SUSPEND",
        "RESUME",
    )

    STATUSES = (IN_PROGRESS, FAILED, COMPLETE) = ("IN_PROGRESS", "FAILED", "COMPLETE")

    # If True, this resource must be created before it can be referenced.
    strict_dependency = True

    created_time = timestamp.Timestamp(db_api.resource_get, "created_at")
    updated_time = timestamp.Timestamp(db_api.resource_get, "updated_at")

    _metadata = Metadata()

    # Resource implementation set this to the subset of template keys
    # which are supported for handle_update, used by update_template_diff
    update_allowed_keys = ()

    # Resource implementation set this to the subset of resource properties
    # supported for handle_update, used by update_template_diff_properties
    update_allowed_properties = ()

    # Resource implementations set this to the name: description dictionary
    # that describes the appropriate resource attributes
    attributes_schema = {}

    # If True, this resource may perform authenticated API requests
    # throughout its lifecycle
    requires_deferred_auth = False

    # Limit to apply to physical_resource_name() size reduction algorithm.
    # If set to None no limit will be applied.
    physical_resource_name_limit = 255

    support_status = SupportStatus()

    def __new__(cls, name, json, stack):
        """Create a new Resource of the appropriate class for its type."""

        if cls != Resource:
            # Call is already for a subclass, so pass it through
            return super(Resource, cls).__new__(cls)

        # Select the correct subclass to instantiate
        ResourceClass = stack.env.get_class(json["Type"], resource_name=name)
        return ResourceClass(name, json, stack)

    def __init__(self, name, json_snippet, stack):
        if "/" in name:
            raise ValueError(_('Resource name may not contain "/"'))

        self.stack = stack
        self.context = stack.context
        self.name = name
        self.json_snippet = json_snippet
        self.t = stack.resolve_static_data(json_snippet)
        self.properties = Properties(
            self.properties_schema, self.t.get("Properties", {}), self._resolve_runtime_data, self.name
        )
        self.attributes = Attributes(self.name, self.attributes_schema, self._resolve_attribute)

        resource = db_api.resource_get_by_name_and_stack(self.context, name, stack.id)
        if resource:
            self.resource_id = resource.nova_instance
            self.action = resource.action
            self.status = resource.status
            self.status_reason = resource.status_reason
            self.id = resource.id
            self.data = resource.data
        else:
            self.resource_id = None
            # if the stack is being deleted, assume we've already been deleted
            if stack.action == stack.DELETE:
                self.action = self.DELETE
            else:
                self.action = self.INIT
            self.status = self.COMPLETE
            self.status_reason = ""
            self.id = None
            self.data = []

    def __eq__(self, other):
        """Allow == comparison of two resources."""
        # For the purposes of comparison, we declare two resource objects
        # equal if their names and parsed_templates are the same
        if isinstance(other, Resource):
            return (self.name == other.name) and (self.parsed_template() == other.parsed_template())
        return NotImplemented

    def __ne__(self, other):
        """Allow != comparison of two resources."""
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    @property
    def metadata(self):
        return self._metadata

    @metadata.setter
    def metadata(self, metadata):
        self._metadata = metadata

    def type(self):
        return self.t["Type"]

    def _resolve_runtime_data(self, snippet):
        return self.stack.resolve_runtime_data(snippet)

    def has_interface(self, resource_type):
        """Check to see if this resource is either mapped to resource_type
        or is a "resource_type".
        """
        if self.type() == resource_type:
            return True
        ri = self.stack.env.get_resource_info(self.type(), self.name)
        return ri.name == resource_type

    def identifier(self):
        """Return an identifier for this resource."""
        return identifier.ResourceIdentifier(resource_name=self.name, **self.stack.identifier())

    def parsed_template(self, section=None, default={}):
        """
        Return the parsed template data for the resource. May be limited to
        only one section of the data, in which case a default value may also
        be supplied.
        """
        if section is None:
            template = self.t
        else:
            template = self.t.get(section, default)
        return self._resolve_runtime_data(template)

    def update_template_diff(self, after, before):
        """
        Returns the difference between the before and after json snippets. If
        something has been removed in after which exists in before we set it to
        None. If any keys have changed which are not in update_allowed_keys,
        raises UpdateReplace if the differing keys are not in
        update_allowed_keys
        """
        update_allowed_set = set(self.update_allowed_keys)

        # Create a set containing the keys in both current and update template
        template_keys = set(before.keys())
        template_keys.update(set(after.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_keys_set = set([k for k in template_keys if before.get(k) != after.get(k)])

        if not changed_keys_set.issubset(update_allowed_set):
            badkeys = changed_keys_set - update_allowed_set
            raise UpdateReplace(self.name)

        return dict((k, after.get(k)) for k in changed_keys_set)

    def update_template_diff_properties(self, after, before):
        """
        Returns the changed Properties between the before and after json
        snippets. If a property has been removed in after which exists in
        before we set it to None. If any properties have changed which are not
        in update_allowed_properties, raises UpdateReplace if the modified
        properties are not in the update_allowed_properties
        """
        update_allowed_set = set(self.update_allowed_properties)
        for (psk, psv) in self.properties.props.iteritems():
            if psv.update_allowed():
                update_allowed_set.add(psk)

        # Create a set containing the keys in both current and update template
        current_properties = before.get("Properties", {})

        template_properties = set(current_properties.keys())
        updated_properties = after.get("Properties", {})
        template_properties.update(set(updated_properties.keys()))

        # Create a set of keys which differ (or are missing/added)
        changed_properties_set = set(
            k for k in template_properties if current_properties.get(k) != updated_properties.get(k)
        )

        if not changed_properties_set.issubset(update_allowed_set):
            raise UpdateReplace(self.name)

        return dict((k, updated_properties.get(k)) for k in changed_properties_set)

    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name)

    def _add_dependencies(self, deps, path, fragment):
        if isinstance(fragment, dict):
            for key, value in fragment.items():
                if key in ("DependsOn", "Ref", "Fn::GetAtt", "get_attr", "get_resource"):
                    if key in ("Fn::GetAtt", "get_attr"):
                        res_name, att = value
                        res_list = [res_name]
                    elif key == "DependsOn" and isinstance(value, list):
                        res_list = value
                    else:
                        res_list = [value]

                    for res in res_list:
                        try:
                            target = self.stack[res]
                        except KeyError:
                            raise exception.InvalidTemplateReference(resource=res, key=path)
                        if key == "DependsOn" or target.strict_dependency:
                            deps += (self, target)
                else:
                    self._add_dependencies(deps, "%s.%s" % (path, key), value)
        elif isinstance(fragment, list):
            for index, item in enumerate(fragment):
                self._add_dependencies(deps, "%s[%d]" % (path, index), item)

    def add_dependencies(self, deps):
        self._add_dependencies(deps, self.name, self.t)
        deps += (self, None)

    def required_by(self):
        """
        Returns a list of names of resources which directly require this
        resource as a dependency.
        """
        return list([r.name for r in self.stack.dependencies.required_by(self)])

    def keystone(self):
        return self.stack.clients.keystone()

    def nova(self, service_type="compute"):
        return self.stack.clients.nova(service_type)

    def swift(self):
        return self.stack.clients.swift()

    def neutron(self):
        return self.stack.clients.neutron()

    def cinder(self):
        return self.stack.clients.cinder()

    def trove(self):
        return self.stack.clients.trove()

    def ceilometer(self):
        return self.stack.clients.ceilometer()

    def heat(self):
        return self.stack.clients.heat()

    def _do_action(self, action, pre_func=None):
        """
        Perform a transition to a new state via a specified action
        action should be e.g self.CREATE, self.UPDATE etc, we set
        status based on this, the transistion is handled by calling the
        corresponding handle_* and check_*_complete functions
        Note pre_func is an optional function reference which will
        be called before the handle_<action> function

        If the resource does not declare a check_$action_complete function,
        we declare COMPLETE status as soon as the handle_$action call has
        finished, and if no handle_$action function is declared, then we do
        nothing, useful e.g if the resource requires no action for a given
        state transition
        """
        assert action in self.ACTIONS, "Invalid action %s" % action

        try:
            self.state_set(action, self.IN_PROGRESS)

            action_l = action.lower()
            handle = getattr(self, "handle_%s" % action_l, None)
            check = getattr(self, "check_%s_complete" % action_l, None)

            if callable(pre_func):
                pre_func()

            handle_data = None
            if callable(handle):
                handle_data = handle()
                yield
                if callable(check):
                    while not check(handle_data):
                        yield
        except Exception as ex:
            logger.exception("%s : %s" % (action, str(self)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, "%s aborted" % action)
                except Exception:
                    logger.exception(_("Error marking resource as failed"))
        else:
            self.state_set(action, self.COMPLETE)

    def create(self):
        """
        Create the resource. Subclasses should provide a handle_create() method
        to customise creation.
        """
        action = self.CREATE
        if (self.action, self.status) != (self.INIT, self.COMPLETE):
            exc = exception.Error(_("State %s invalid for create") % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info("creating %s" % str(self))

        # Re-resolve the template, since if the resource Ref's
        # the AWS::StackId pseudo parameter, it will change after
        # the parser.Stack is stored (which is after the resources
        # are __init__'d, but before they are create()'d)
        self.t = self.stack.resolve_static_data(self.json_snippet)
        self.properties = Properties(
            self.properties_schema, self.t.get("Properties", {}), self._resolve_runtime_data, self.name
        )
        return self._do_action(action, self.properties.validate)

    def set_deletion_policy(self, policy):
        self.t["DeletionPolicy"] = policy

    def get_abandon_data(self):
        return {
            "name": self.name,
            "resource_id": self.resource_id,
            "type": self.type(),
            "action": self.action,
            "status": self.status,
            "metadata": self.metadata,
            "resource_data": dict((r.key, r.value) for r in db_api.resource_data_get_all(self)),
        }

    def update(self, after, before=None):
        """
        update the resource. Subclasses should provide a handle_update() method
        to customise update, the base-class handle_update will fail by default.
        """
        action = self.UPDATE

        if before is None:
            before = self.parsed_template()
        elif before == after:
            return

        if (self.action, self.status) in ((self.CREATE, self.IN_PROGRESS), (self.UPDATE, self.IN_PROGRESS)):
            exc = Exception(_("Resource update already requested"))
            raise exception.ResourceFailure(exc, self, action)

        logger.info("updating %s" % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)
            properties = Properties(
                self.properties_schema, after.get("Properties", {}), self._resolve_runtime_data, self.name
            )
            properties.validate()
            tmpl_diff = self.update_template_diff(after, before)
            prop_diff = self.update_template_diff_properties(after, before)
            if callable(getattr(self, "handle_update", None)):
                handle_data = self.handle_update(after, tmpl_diff, prop_diff)
                yield
                if callable(getattr(self, "check_update_complete", None)):
                    while not self.check_update_complete(handle_data):
                        yield
        except UpdateReplace:
            with excutils.save_and_reraise_exception():
                logger.debug(_("Resource %s update requires replacement") % self.name)
        except Exception as ex:
            logger.exception("update %s : %s" % (str(self), str(ex)))
            failure = exception.ResourceFailure(ex, self, action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        else:
            self.t = self.stack.resolve_static_data(after)
            self.state_set(action, self.COMPLETE)

    def suspend(self):
        """
        Suspend the resource.  Subclasses should provide a handle_suspend()
        method to implement suspend
        """
        action = self.SUSPEND

        # Don't try to suspend the resource unless it's in a stable state
        if self.action == self.DELETE or self.status != self.COMPLETE:
            exc = exception.Error(_("State %s invalid for suspend") % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info(_("suspending %s") % str(self))
        return self._do_action(action)

    def resume(self):
        """
        Resume the resource.  Subclasses should provide a handle_resume()
        method to implement resume
        """
        action = self.RESUME

        # Can't resume a resource unless it's SUSPEND_COMPLETE
        if self.state != (self.SUSPEND, self.COMPLETE):
            exc = exception.Error(_("State %s invalid for resume") % str(self.state))
            raise exception.ResourceFailure(exc, self, action)

        logger.info(_("resuming %s") % str(self))
        return self._do_action(action)

    def physical_resource_name(self):
        if self.id is None:
            return None

        name = "%s-%s-%s" % (self.stack.name, self.name, short_id.get_id(self.id))

        if self.physical_resource_name_limit:
            name = self.reduce_physical_resource_name(name, self.physical_resource_name_limit)
        return name

    @staticmethod
    def reduce_physical_resource_name(name, limit):
        """
        Reduce length of physical resource name to a limit.

        The reduced name will consist of the following:

        * the first 2 characters of the name
        * a hyphen
        * the end of the name, truncated on the left to bring
          the name length within the limit

        :param name: The name to reduce the length of
        :param limit: The max length limit
        :returns: A name whose length is less than or equal to the limit
        """
        if len(name) <= limit:
            return name

        if limit < 4:
            raise ValueError(_("limit cannot be less than 4"))

        postfix_length = limit - 3
        return name[0:2] + "-" + name[-postfix_length:]

    def validate(self):
        logger.info(_("Validating %s") % str(self))

        self.validate_deletion_policy(self.t)
        return self.properties.validate()

    @classmethod
    def validate_deletion_policy(cls, template):
        deletion_policy = template.get("DeletionPolicy", DELETE)
        if deletion_policy not in DELETION_POLICY:
            msg = _("Invalid DeletionPolicy %s") % deletion_policy
            raise exception.StackValidationFailed(message=msg)
        elif deletion_policy == SNAPSHOT:
            if not callable(getattr(cls, "handle_snapshot_delete", None)):
                msg = _("Snapshot DeletionPolicy not supported")
                raise exception.StackValidationFailed(message=msg)

    def delete(self):
        """
        Delete the resource. Subclasses should provide a handle_delete() method
        to customise deletion.
        """
        action = self.DELETE

        if (self.action, self.status) == (self.DELETE, self.COMPLETE):
            return
        # No need to delete if the resource has never been created
        if self.action == self.INIT:
            return

        initial_state = self.state

        logger.info(_("deleting %s") % str(self))

        try:
            self.state_set(action, self.IN_PROGRESS)

            deletion_policy = self.t.get("DeletionPolicy", DELETE)
            handle_data = None
            if deletion_policy == DELETE:
                if callable(getattr(self, "handle_delete", None)):
                    handle_data = self.handle_delete()
                    yield
            elif deletion_policy == SNAPSHOT:
                if callable(getattr(self, "handle_snapshot_delete", None)):
                    handle_data = self.handle_snapshot_delete(initial_state)
                    yield

            if deletion_policy != RETAIN and callable(getattr(self, "check_delete_complete", None)):
                while not self.check_delete_complete(handle_data):
                    yield

        except Exception as ex:
            logger.exception(_("Delete %s"), str(self))
            failure = exception.ResourceFailure(ex, self, self.action)
            self.state_set(action, self.FAILED, str(failure))
            raise failure
        except:
            with excutils.save_and_reraise_exception():
                try:
                    self.state_set(action, self.FAILED, "Deletion aborted")
                except Exception:
                    logger.exception(_("Error marking resource deletion " "failed"))
        else:
            self.state_set(action, self.COMPLETE)

    @scheduler.wrappertask
    def destroy(self):
        """
        Delete the resource and remove it from the database.
        """
        yield self.delete()

        if self.id is None:
            return

        try:
            db_api.resource_get(self.context, self.id).delete()
        except exception.NotFound:
            # Don't fail on delete if the db entry has
            # not been created yet.
            pass

        self.id = None

    def resource_id_set(self, inst):
        self.resource_id = inst
        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save({"nova_instance": self.resource_id})
            except Exception as ex:
                logger.warn(_("db error %s") % str(ex))

    def _store(self):
        """Create the resource in the database."""
        metadata = self.metadata
        try:
            rs = {
                "action": self.action,
                "status": self.status,
                "status_reason": self.status_reason,
                "stack_id": self.stack.id,
                "nova_instance": self.resource_id,
                "name": self.name,
                "rsrc_metadata": metadata,
                "stack_name": self.stack.name,
            }

            new_rs = db_api.resource_create(self.context, rs)
            self.id = new_rs.id

            self.stack.updated_time = datetime.utcnow()

        except Exception as ex:
            logger.error(_("DB error %s") % str(ex))

    def _add_event(self, action, status, reason):
        """Add a state change event to the database."""
        ev = event.Event(
            self.context, self.stack, action, status, reason, self.resource_id, self.properties, self.name, self.type()
        )

        try:
            ev.store()
        except Exception as ex:
            logger.error(_("DB error %s") % str(ex))

    def _store_or_update(self, action, status, reason):
        self.action = action
        self.status = status
        self.status_reason = reason

        if self.id is not None:
            try:
                rs = db_api.resource_get(self.context, self.id)
                rs.update_and_save(
                    {
                        "action": self.action,
                        "status": self.status,
                        "status_reason": reason,
                        "stack_id": self.stack.id,
                        "nova_instance": self.resource_id,
                    }
                )

                self.stack.updated_time = datetime.utcnow()
            except Exception as ex:
                logger.error(_("DB error %s") % str(ex))

        # store resource in DB on transition to CREATE_IN_PROGRESS
        # all other transistions (other than to DELETE_COMPLETE)
        # should be handled by the update_and_save above..
        elif (action, status) == (self.CREATE, self.IN_PROGRESS):
            self._store()

    def _resolve_attribute(self, name):
        """
        Default implementation; should be overridden by resources that expose
        attributes

        :param name: The attribute to resolve
        :returns: the resource attribute named key
        """
        # By default, no attributes resolve
        pass

    def state_reset(self):
        """
        Reset state to (INIT, COMPLETE)
        """
        self.action = self.INIT
        self.status = self.COMPLETE

    def state_set(self, action, status, reason="state changed"):
        if action not in self.ACTIONS:
            raise ValueError(_("Invalid action %s") % action)

        if status not in self.STATUSES:
            raise ValueError(_("Invalid status %s") % status)

        old_state = (self.action, self.status)
        new_state = (action, status)
        self._store_or_update(action, status, reason)

        if new_state != old_state:
            self._add_event(action, status, reason)

    @property
    def state(self):
        """Returns state, tuple of action, status."""
        return (self.action, self.status)

    def FnGetRefId(self):
        """
        For the intrinsic function Ref.

        :results: the id or name of the resource.
        """
        if self.resource_id is not None:
            return unicode(self.resource_id)
        else:
            return unicode(self.name)

    def FnGetAtt(self, key):
        """
        For the intrinsic function Fn::GetAtt.

        :param key: the attribute key.
        :returns: the attribute value.
        """
        try:
            return self.attributes[key]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name, key=key)

    def FnBase64(self, data):
        """
        For the instrinsic function Fn::Base64.

        :param data: the input data.
        :returns: the Base64 representation of the input data.
        """
        return base64.b64encode(data)

    def signal(self, details=None):
        """
        signal the resource. Subclasses should provide a handle_signal() method
        to implement the signal, the base-class raise an exception if no
        handler is implemented.
        """

        def get_string_details():
            if details is None:
                return "No signal details provided"
            if isinstance(details, basestring):
                return details
            if isinstance(details, dict):
                if all(k in details for k in ("previous", "current", "reason")):
                    # this is from Ceilometer.
                    auto = "%(previous)s to %(current)s (%(reason)s)" % details
                    return "alarm state changed from %s" % auto
                elif "state" in details:
                    # this is from watchrule
                    return "alarm state changed to %(state)s" % details

            return "Unknown"

        try:
            if self.action in (self.SUSPEND, self.DELETE):
                msg = _("Cannot signal resource during %s") % self.action
                raise Exception(msg)

            if not callable(getattr(self, "handle_signal", None)):
                msg = _("Resource %s is not able to receive a signal") % str(self)
                raise Exception(msg)

            self._add_event("signal", self.status, get_string_details())
            self.handle_signal(details)
        except Exception as ex:
            logger.exception(_("signal %(name)s : %(msg)s") % {"name": str(self), "msg": str(ex)})
            failure = exception.ResourceFailure(ex, self)
            raise failure

    def handle_update(self, json_snippet=None, tmpl_diff=None, prop_diff=None):
        raise UpdateReplace(self.name)

    def metadata_update(self, new_metadata=None):
        """
        No-op for resources which don't explicitly override this method
        """
        if new_metadata:
            logger.warning(_("Resource %s does not implement metadata update") % self.name)

    @classmethod
    def resource_to_template(cls, resource_type):
        """
        :param resource_type: The resource type to be displayed in the template
        :returns: A template where the resource's properties_schema is mapped
            as parameters, and the resource's attributes_schema is mapped as
            outputs
        """
        (parameters, properties) = Properties.schema_to_parameters_and_properties(cls.properties_schema)

        resource_name = cls.__name__
        return {
            "Parameters": parameters,
            "Resources": {resource_name: {"Type": resource_type, "Properties": properties}},
            "Outputs": Attributes.as_outputs(resource_name, cls),
        }