Пример #1
0
    def __new__(cls, name, bases, dct):
        def get_tenant_id(self):
            tenant_id = getattr(self, '_tenant_id', wtypes.Unset)
            # If tenant_id was explicitly set to Unset, return that
            if tenant_id is wtypes.Unset and self._unset_tenant:
                return tenant_id
            # Otherwise, assume we can return project_id
            return self.project_id

        def set_tenant_id(self, tenant_id):
            self._tenant_id = tenant_id

            if tenant_id is wtypes.Unset:
                # Record that tenant_id was explicitly Unset
                self._unset_tenant = True
            else:
                # Reset 'unset' state, and update project_id as well
                self._unset_tenant = False
                self.project_id = tenant_id

        if 'project_id' in dct and 'tenant_id' not in dct:
            dct['tenant_id'] = wtypes.wsproperty(
                wtypes.StringType(max_length=36), get_tenant_id, set_tenant_id)
            # This will let us know if tenant_id was explicitly set to Unset
            dct['_unset_tenant'] = False
        return super(BaseMeta, cls).__new__(cls, name, bases, dct)
Пример #2
0
    def __new__(cls, name, bases, dct):
        def get_tenant_id(self):
            tenant_id = getattr(self, '_tenant_id', wtypes.Unset)
            # If tenant_id was explicitly set to Unset, return that
            if tenant_id is wtypes.Unset and self._unset_tenant:
                return tenant_id
            # Otherwise, assume we can return project_id
            return self.project_id

        def set_tenant_id(self, tenant_id):
            self._tenant_id = tenant_id

            if tenant_id is wtypes.Unset:
                # Record that tenant_id was explicitly Unset
                self._unset_tenant = True
            else:
                # Reset 'unset' state, and update project_id as well
                self._unset_tenant = False
                self.project_id = tenant_id

        if 'project_id' in dct and 'tenant_id' not in dct:
            dct['tenant_id'] = wtypes.wsproperty(
                wtypes.StringType(max_length=36),
                get_tenant_id, set_tenant_id)
            # This will let us know if tenant_id was explicitly set to Unset
            dct['_unset_tenant'] = False
        return super(BaseMeta, cls).__new__(cls, name, bases, dct)
Пример #3
0
class Base(wtypes.Base):
    """Base class for all API types."""

    uri = common_types.Uri
    "URI to the resource."

    uuid = wtypes.text
    "Unique Identifier of the resource"

    def get_name(self):
        return self.__name

    def set_name(self, value):
        allowed_chars = string.letters + string.digits + '-_'
        for ch in value:
            if ch not in allowed_chars:
                raise ValueError(_('Names must only contain a-z,A-Z,0-9,-,_'))
        self.__name = value

    name = wtypes.wsproperty(str, get_name, set_name, mandatory=True)
    "Name of the resource."

    type = wtypes.text
    "The resource type."

    description = wtypes.text
    "Textual description of the resource."

    tags = [wtypes.text]
    "Tags for the resource."

    project_id = wtypes.text
    "The project that this resource belongs in."

    user_id = wtypes.text
    "The user that owns this resource."

    def __init__(self, **kwds):
        self.__name = wsme.Unset
        super(Base, self).__init__(**kwds)

    @classmethod
    def from_db_model(cls, m, host_url):
        json = m.as_dict()
        json['type'] = m.__tablename__
        json['uri'] = '%s/v1/%s/%s' % (host_url, m.__resource__, m.uuid)
        del json['id']
        return cls(**(json))

    def as_dict(self, db_model):
        valid_keys = (attr for attr in db_model.__dict__.keys()
                      if attr[:2] != '__' and attr != 'as_dict')
        return self.as_dict_from_keys(valid_keys)

    def as_dict_from_keys(self, keys):
        return dict((k, getattr(self, k)) for k in keys
                    if hasattr(self, k) and getattr(self, k) != wsme.Unset)
Пример #4
0
        class WithWSProp(object):
            def __init__(self):
                self._aint = 0

            def get_aint(self):
                return self._aint

            def set_aint(self, value):
                self._aint = value

            aint = types.wsproperty(int, get_aint, set_aint, mandatory=True)
class SubscriptionInfo(wtypes.Base):
    SubscriptionId = wtypes.text
    UriLocation = wtypes.text
    ResourceType = EnumResourceType
    EndpointUri = wtypes.text

    # dynamic type depending on ResourceType
    def set_resource_qualifier(self, value):
        if isinstance(value, wtypes.Base):
            self._ResourceQualifer = value
        else:
            self._ResourceQualifierJson = value
            self._ResourceQualifer = None

    def get_resource_qualifier(self):
        if not self._ResourceQualifer:
            if self.ResourceType == ResourceType.TypePTP:
                self._ResourceQualifer = ResourceQualifierPtp(**self._ResourceQualifierJson)

        return self._ResourceQualifer

    ResourceQualifier = wtypes.wsproperty(wtypes.Base,
    get_resource_qualifier, set_resource_qualifier, mandatory=True)


    def __init__(self, orm_entry=None):
        if orm_entry:
            self.SubscriptionId = orm_entry.SubscriptionId
            self.ResourceType = orm_entry.ResourceType
            self.UriLocation = orm_entry.UriLocation
            self.ResourceQualifier = json.loads(orm_entry.ResourceQualifierJson)
            self.EndpointUri = orm_entry.EndpointUri

    def to_dict(self):
        d = {
                'SubscriptionId': self.SubscriptionId,
                'ResourceType': self.ResourceType,
                'UriLocation': self.UriLocation,
                'EndpointUri': self.EndpointUri,
                'ResourceQualifier': self.ResourceQualifier.to_dict()
            }
        return d

    def to_orm(self):
        d = {
                'SubscriptionId': self.SubscriptionId,
                'ResourceType': self.ResourceType or '',
                'UriLocation': self.UriLocation,
                'EndpointUri': self.EndpointUri or '',
                'ResourceQualifierJson': json.dumps(self.ResourceQualifier.to_dict())  or ''
            }
        return d
Пример #6
0
class Query(Base):
    """
    Query filter.
    """

    _op = None  # provide a default

    def get_op(self):
        return self._op or 'eq'

    def set_op(self, value):
        self._op = value

    field = text
    "The name of the field to test"

    #op = wsme.wsattr(operation_kind, default='eq')
    # this ^ doesn't seem to work.
    op = wsproperty(operation_kind, get_op, set_op)
    "The comparison operator. Defaults to 'eq'."

    value = text
    "The value to compare against the stored data"

    def __repr__(self):
        # for LOG calls
        return '<Query %r %s %r>' % (self.field, self.op, self.value)

    @classmethod
    def sample(cls):
        return cls(
            field='resource_id',
            op='eq',
            value='bd9431c1-8d69-4ad3-803a-8d4a6b89fd36',
        )

    def as_dict(self):
        return {'op': self.op, 'field': self.field, 'value': self.value}
Пример #7
0
class Sensor(api_types.Base):
    """A Sensor resource represents exactly one supported sensor.

    Sensor resources represent dynamic data about resources,
    such as metrics or state. Sensor resources are useful for exposing data
    that changes rapidly, or that may need to be fetched from a secondary
    system.
    """

    documentation = common_types.Uri
    "Documentation URI for the sensor."

    target_resource = common_types.Uri
    "Target resource URI to the sensor."

    sensor_type = SENSOR_TYPE
    "Sensor data type."

    timestamp = datetime.datetime
    "Timestamp for Sensor."

    operations = [operation.Operation]
    "Operations that belong to the sensor."

    def get_value(self):
        if self.sensor_type == 'int':
            if int(self._value) != float(self._value):
                raise ValueError(
                    _('Value "%s" is not an integer.') % str(self._value))
            return int(self._value)
        elif self.sensor_type == 'float':
            return float(self._value)
        else:
            return str(self._value)

    def set_value(self, value):
        # Store the value as-is, because we don't know the order that the
        # value and sensor_type are written, so convert to the desired type
        # in get_value().
        self._value = value

    value = wtypes.wsproperty(str, get_value, set_value, mandatory=False)
    "Value of the sensor."

    def __init__(self, **kwds):
        self._value = '0'
        super(Sensor, self).__init__(**kwds)

    @classmethod
    def sample(cls):
        return cls(uri='http://example.com/v1/sensors/hb',
                   name='hb',
                   type='sensor',
                   project_id='1dae5a09ef2b4d8cbf3594b0eb4f6b94',
                   user_id='55f41cf46df74320b9486a35f5d28a11',
                   description='A heartbeat sensor',
                   documentation='http://example.com/docs/heartbeat/',
                   target_resource='http://example.com/instances/uuid',
                   sensor_type='str',
                   value='30',
                   timestamp=datetime.datetime.utcnow(),
                   operations=[])
Пример #8
0
class ActionPlan(base.APIBase):
    """API representation of a action plan.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of an
    action plan.
    """

    _audit_uuid = None
    _strategy_uuid = None
    _strategy_name = None
    _efficacy_indicators = None

    def _get_audit_uuid(self):
        return self._audit_uuid

    def _set_audit_uuid(self, value):
        if value == wtypes.Unset:
            self._audit_uuid = wtypes.Unset
        elif value and self._audit_uuid != value:
            try:
                audit = objects.Audit.get(pecan.request.context, value)
                self._audit_uuid = audit.uuid
                self.audit_id = audit.id
            except exception.AuditNotFound:
                self._audit_uuid = None

    def _get_efficacy_indicators(self):
        if self._efficacy_indicators is None:
            self._set_efficacy_indicators(wtypes.Unset)
        return self._efficacy_indicators

    def _set_efficacy_indicators(self, value):
        efficacy_indicators = []
        if value == wtypes.Unset and not self._efficacy_indicators:
            try:
                _efficacy_indicators = objects.EfficacyIndicator.list(
                    pecan.request.context,
                    filters={"action_plan_uuid": self.uuid})

                for indicator in _efficacy_indicators:
                    efficacy_indicator = efficacyindicator.EfficacyIndicator(
                        context=pecan.request.context,
                        name=indicator.name,
                        description=indicator.description,
                        unit=indicator.unit,
                        value=indicator.value,
                    )
                    efficacy_indicators.append(efficacy_indicator.as_dict())
                self._efficacy_indicators = efficacy_indicators
            except exception.EfficacyIndicatorNotFound as exc:
                LOG.exception(exc)
        elif value and self._efficacy_indicators != value:
            self._efficacy_indicators = value

    def _get_strategy(self, value):
        if value == wtypes.Unset:
            return None
        strategy = None
        try:
            if utils.is_uuid_like(value) or utils.is_int_like(value):
                strategy = objects.Strategy.get(pecan.request.context, value)
            else:
                strategy = objects.Strategy.get_by_name(
                    pecan.request.context, value)
        except exception.StrategyNotFound:
            pass
        if strategy:
            self.strategy_id = strategy.id
        return strategy

    def _get_strategy_uuid(self):
        return self._strategy_uuid

    def _set_strategy_uuid(self, value):
        if value and self._strategy_uuid != value:
            self._strategy_uuid = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_uuid = strategy.uuid

    def _get_strategy_name(self):
        return self._strategy_name

    def _set_strategy_name(self, value):
        if value and self._strategy_name != value:
            self._strategy_name = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_name = strategy.name

    uuid = wtypes.wsattr(types.uuid, readonly=True)
    """Unique UUID for this action plan"""

    audit_uuid = wtypes.wsproperty(types.uuid,
                                   _get_audit_uuid,
                                   _set_audit_uuid,
                                   mandatory=True)
    """The UUID of the audit this port belongs to"""

    strategy_uuid = wtypes.wsproperty(wtypes.text,
                                      _get_strategy_uuid,
                                      _set_strategy_uuid,
                                      mandatory=False)
    """Strategy UUID the action plan refers to"""

    strategy_name = wtypes.wsproperty(wtypes.text,
                                      _get_strategy_name,
                                      _set_strategy_name,
                                      mandatory=False)
    """The name of the strategy this action plan refers to"""

    efficacy_indicators = wtypes.wsproperty(types.jsontype,
                                            _get_efficacy_indicators,
                                            _set_efficacy_indicators,
                                            mandatory=True)
    """The list of efficacy indicators associated to this action plan"""

    global_efficacy = wtypes.wsattr(types.jsontype, readonly=True)
    """The global efficacy of this action plan"""

    state = wtypes.text
    """This action plan state"""

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link and associated action links"""

    hostname = wtypes.wsattr(wtypes.text, mandatory=False)
    """Hostname the actionplan is running on"""

    def __init__(self, **kwargs):
        super(ActionPlan, self).__init__()
        self.fields = []
        fields = list(objects.ActionPlan.fields)
        for field in fields:
            # Skip fields we do not expose.
            if not hasattr(self, field):
                continue
            self.fields.append(field)
            setattr(self, field, kwargs.get(field, wtypes.Unset))

        self.fields.append('audit_uuid')
        self.fields.append('efficacy_indicators')

        setattr(self, 'audit_uuid', kwargs.get('audit_id', wtypes.Unset))
        fields.append('strategy_uuid')
        setattr(self, 'strategy_uuid', kwargs.get('strategy_id', wtypes.Unset))
        fields.append('strategy_name')
        setattr(self, 'strategy_name', kwargs.get('strategy_id', wtypes.Unset))

    @staticmethod
    def _convert_with_links(action_plan, url, expand=True):
        if not expand:
            action_plan.unset_fields_except([
                'uuid', 'state', 'efficacy_indicators', 'global_efficacy',
                'updated_at', 'audit_uuid', 'strategy_uuid', 'strategy_name'
            ])

        action_plan.links = [
            link.Link.make_link('self', url, 'action_plans', action_plan.uuid),
            link.Link.make_link('bookmark',
                                url,
                                'action_plans',
                                action_plan.uuid,
                                bookmark=True)
        ]
        return action_plan

    @classmethod
    def convert_with_links(cls, rpc_action_plan, expand=True):
        action_plan = ActionPlan(**rpc_action_plan.as_dict())
        hide_fields_in_newer_versions(action_plan)
        return cls._convert_with_links(action_plan, pecan.request.host_url,
                                       expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(uuid='9ef4d84c-41e8-4418-9220-ce55be0436af',
                     state='ONGOING',
                     created_at=datetime.datetime.utcnow(),
                     deleted_at=None,
                     updated_at=datetime.datetime.utcnow())
        sample._audit_uuid = 'abcee106-14d3-4515-b744-5a26885cf6f6'
        sample._efficacy_indicators = [{
            'description': 'Test indicator',
            'name': 'test_indicator',
            'unit': '%'
        }]
        sample._global_efficacy = {
            'description': 'Global efficacy',
            'name': 'test_global_efficacy',
            'unit': '%'
        }
        return cls._convert_with_links(sample, 'http://localhost:9322', expand)
Пример #9
0
class LanguagePack(api_types.Base):
    """Representation of a language pack.

    When a user creates an application, he specifies the language pack
    to be used. The language pack is responsible for building the application
    and producing an artifact for deployment.

    For a complete list of language pack attributes please
    refer: https://etherpad.openstack.org/p/Solum-Language-pack-json-format
    """
    def __init__(self, **kwds):
        self.__name = wsme.Unset
        super(LanguagePack, self).__init__(**kwds)

    def get_name(self):
        return self.__name

    def set_name(self, value):
        if len(value) > 100:
            raise ValueError(
                _('Names must not be longer than 100 '
                  'characters'))
        allowed_chars = string.ascii_lowercase + string.digits + '-_'
        for ch in value:
            if ch not in allowed_chars:
                raise ValueError(_('Names must only contain a-z,0-9,-,_'))
        self.__name = value

    name = wtypes.wsproperty(str, get_name, set_name, mandatory=True)

    language_pack_type = wtypes.text
    """Type of the language pack. Identifies the language supported by the
    language pack. This attribute value will use the
    org.openstack.solum namespace.
    """

    compiler_versions = [wtypes.text]
    """List of all the compiler versions supported by the language pack.
    Example: For a java language pack supporting Java versions 1.4 to 1.7,
    version = ['1.4', '1.6', '1.7']
    """

    runtime_versions = [wtypes.text]
    """List of all runtime versions supported by the language pack.
    Runtime version can be different than compiler version.
    Example: An application can be compiled with java 1.7 but it should
    run in java 1.6 as it is backward compatible.
    """

    language_implementation = wtypes.text
    """Actual language implementation supported by the language pack.
    Example: In case of java it might be 'Sun' or 'openJava'
    In case of C++ it can be 'gcc' or 'icc' or 'microsoft'.
    """

    build_tool_chain = [BuildTool]
    """Toolchain available in the language pack.
    Example: For a java language pack which supports Ant and Maven,
    build_tool_chain = ["{type:ant,version:1.7}","{type:maven,version:1.2}"]
    """

    os_platform = {str: wtypes.text}
    """OS and its version used by the language pack.
    This attribute identifies the base image of the language pack.
    """

    attributes = {str: wtypes.text}
    """Additional section attributes will be used to expose custom
    attributes designed by language pack creator.
    """

    source_uri = wtypes.text
    """The URI of the app/element."""

    source_format = SOURCE_KIND
    """The source repository format."""

    status = STATE_KIND
    """The state of the image. """

    base_image_id = wtypes.text
    """The id (in glance) of the image to customize."""

    image_format = IMAGE_KIND
    """The image format."""

    created_image_id = wtypes.text
    """The id of the created image in glance."""

    lp_metadata = wtypes.text
    """The languagepack meta data."""
    """Parameters that can be used as part of lp building process."""
    lp_params = wtypes.DictType(
        wtypes.text,
        wtypes.DictType(
            wtypes.text,
            api_types.MultiType(wtypes.text, six.integer_types, bool, float)))

    @classmethod
    def from_image(cls, image, host_url):
        as_dict = {}
        image_id = image['id']
        as_dict['uuid'] = image_id
        as_dict['name'] = image['name']
        as_dict['type'] = 'language_pack'
        as_dict['uri'] = '%s/v1/%s/%s' % (host_url, 'language_packs', image_id)
        image_tags = image['tags']
        comp_versions = []
        run_versions = []
        build_tools = []
        attrs = {}
        for tag in image_tags:
            if tag.startswith(DESCRIPTION):
                as_dict['description'] = tag[len(DESCRIPTION):]
            if tag.startswith(TYPE):
                as_dict['language_pack_type'] = tag[len(TYPE):]
            if tag.startswith(COMPILER_VERSION):
                comp_versions.append(tag[len(COMPILER_VERSION):])
            if tag.startswith(RUNTIME_VERSION):
                run_versions.append(tag[len(RUNTIME_VERSION):])
            if tag.startswith(IMPLEMENTATION):
                as_dict['language_implementation'] = tag[len(IMPLEMENTATION):]
            if tag.startswith(BUILD_TOOL):
                bt_type, bt_version = tag[len(BUILD_TOOL):].split('::')
                build_tool = BuildTool(type=bt_type, version=bt_version)
                build_tools.append(build_tool)
            if tag.startswith(OS_PLATFORM):
                osp_type, osp_version = tag[len(OS_PLATFORM):].split('::')
                os_platform = {'OS': osp_type, 'version': osp_version}
                as_dict['os_platform'] = os_platform
            if tag.startswith(ATTRIBUTE):
                key, value = tag[len(ATTRIBUTE):].split('::')
                attrs[key] = value
        as_dict['attributes'] = attrs
        as_dict['compiler_versions'] = comp_versions
        as_dict['runtime_versions'] = run_versions
        as_dict['build_tool_chain'] = build_tools
        return cls(**(as_dict))

    def as_image_dict(self):
        tags = ['solum::lp']
        if self.description is not wsme.Unset:
            tags.append(DESCRIPTION + self.description)
        if self.language_pack_type is not wsme.Unset:
            tags.append(TYPE + self.language_pack_type)
        if self.compiler_versions is not wsme.Unset:
            for cv in self.compiler_versions:
                tags.append(COMPILER_VERSION + cv)
        if self.runtime_versions is not wsme.Unset:
            for rv in self.runtime_versions:
                tags.append(RUNTIME_VERSION + rv)
        if self.language_implementation is not wsme.Unset:
            tags.append(IMPLEMENTATION + self.language_implementation)
        if self.build_tool_chain is not wsme.Unset:
            for bt in self.build_tool_chain:
                tags.append(BUILD_TOOL + bt.type + '::' + bt.version)
        ptfm = self.os_platform
        if ptfm is not wsme.Unset and 'OS' in ptfm and 'version' in ptfm:
            tags.append(OS_PLATFORM + ptfm['OS'] + '::' + ptfm['version'])
        if self.build_tool_chain is not wsme.Unset:
            for key, value in self.attributes.items():
                tags.append(ATTRIBUTE + key + '::' + value)
        # TODO(julienvey) parse specific attributes for image creation from
        # self.attributes, such as image_format...
        return {'name': self.name, 'tags': tags}

    @classmethod
    def sample(cls):
        return cls(
            uri='http://example.com/v1/images/b3e0d79',
            source_uri='git://example.com/project/app.git',
            source_format='heroku',
            name='php-web-app',
            type='languagepack',
            description='A php web application',
            tags=['group_xyz'],
            project_id='1dae5a09ef2b4d8cbf3594b0eb4f6b94',
            user_id='55f41cf46df74320b9486a35f5d28a11',
            base_image_id='4dae5a09ef2b4d8cbf3594b0eb4f6b94',
            created_image_id='4afasa09ef2b4d8cbf3594b0ec4f6b94',
            image_format='docker',
            language_pack_name='java-1.4-1.7',
            language_pack_type='org.openstack.solum.Java',
            language_pack_id='123456789abcdef',
            compiler_versions=['1.4', '1.6', '1.7'],
            runtime_versions=['1.4', '1.6', '1.7'],
            language_implementation='Sun',
            build_tool_chain=[
                BuildTool(type='ant', version='1.7'),
                BuildTool(type='maven', version='1.2')
            ],
            os_platform={
                'OS': 'Ubuntu',
                'version': '12.04'
            },
            attributes={
                'optional_attr1': 'value',
                'admin_email': '*****@*****.**'
            },
        )
Пример #10
0
class Action(base.APIBase):
    """API representation of a action.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of a action.
    """
    _action_plan_uuid = None

    def _get_action_plan_uuid(self):
        return self._action_plan_uuid

    def _set_action_plan_uuid(self, value):
        if value == wtypes.Unset:
            self._action_plan_uuid = wtypes.Unset
        elif value and self._action_plan_uuid != value:
            try:
                action_plan = objects.ActionPlan.get(pecan.request.context,
                                                     value)
                self._action_plan_uuid = action_plan.uuid
                self.action_plan_id = action_plan.id
            except exception.ActionPlanNotFound:
                self._action_plan_uuid = None

    uuid = wtypes.wsattr(types.uuid, readonly=True)
    """Unique UUID for this action"""

    action_plan_uuid = wtypes.wsproperty(types.uuid,
                                         _get_action_plan_uuid,
                                         _set_action_plan_uuid,
                                         mandatory=True)
    """The action plan this action belongs to """

    state = wtypes.text
    """This audit state"""

    action_type = wtypes.text
    """Action type"""

    description = wtypes.text
    """Action description"""

    input_parameters = types.jsontype
    """One or more key/value pairs """

    parents = wtypes.wsattr(types.jsontype, readonly=True)
    """UUIDs of parent actions"""

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link and associated action links"""

    def __init__(self, **kwargs):
        super(Action, self).__init__()

        self.fields = []
        fields = list(objects.Action.fields)
        fields.append('action_plan_uuid')
        for field in fields:
            # Skip fields we do not expose.
            if not hasattr(self, field):
                continue
            self.fields.append(field)
            setattr(self, field, kwargs.get(field, wtypes.Unset))

        self.fields.append('action_plan_id')
        self.fields.append('description')
        setattr(self, 'action_plan_uuid',
                kwargs.get('action_plan_id', wtypes.Unset))

    @staticmethod
    def _convert_with_links(action, url, expand=True):
        if not expand:
            action.unset_fields_except([
                'uuid', 'state', 'action_plan_uuid', 'action_plan_id',
                'action_type', 'parents'
            ])

        action.links = [
            link.Link.make_link('self', url, 'actions', action.uuid),
            link.Link.make_link('bookmark',
                                url,
                                'actions',
                                action.uuid,
                                bookmark=True)
        ]
        return action

    @classmethod
    def convert_with_links(cls, action, expand=True):
        action = Action(**action.as_dict())
        try:
            obj_action_desc = objects.ActionDescription.get_by_type(
                pecan.request.context, action.action_type)
            description = obj_action_desc.description
        except exception.ActionDescriptionNotFound:
            description = ""
        setattr(action, 'description', description)

        hide_fields_in_newer_versions(action)

        return cls._convert_with_links(action, pecan.request.host_url, expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c',
                     description='action description',
                     state='PENDING',
                     created_at=datetime.datetime.utcnow(),
                     deleted_at=None,
                     updated_at=datetime.datetime.utcnow(),
                     parents=[])
        sample._action_plan_uuid = '7ae81bb3-dec3-4289-8d6c-da80bd8001ae'
        return cls._convert_with_links(sample, 'http://localhost:9322', expand)
Пример #11
0
class Strategy(base.APIBase):
    """API representation of a strategy.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of a strategy.
    """
    _goal_uuid = None
    _goal_name = None

    def _get_goal(self, value):
        if value == wtypes.Unset:
            return None
        goal = None
        try:
            if (common_utils.is_uuid_like(value)
                    or common_utils.is_int_like(value)):
                goal = objects.Goal.get(pecan.request.context, value)
            else:
                goal = objects.Goal.get_by_name(pecan.request.context, value)
        except exception.GoalNotFound:
            pass
        if goal:
            self.goal_id = goal.id
        return goal

    def _get_goal_uuid(self):
        return self._goal_uuid

    def _set_goal_uuid(self, value):
        if value and self._goal_uuid != value:
            self._goal_uuid = None
            goal = self._get_goal(value)
            if goal:
                self._goal_uuid = goal.uuid

    def _get_goal_name(self):
        return self._goal_name

    def _set_goal_name(self, value):
        if value and self._goal_name != value:
            self._goal_name = None
            goal = self._get_goal(value)
            if goal:
                self._goal_name = goal.name

    uuid = types.uuid
    """Unique UUID for this strategy"""

    name = wtypes.text
    """Name of the strategy"""

    display_name = wtypes.text
    """Localized name of the strategy"""

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link and associated goal links"""

    goal_uuid = wtypes.wsproperty(wtypes.text,
                                  _get_goal_uuid,
                                  _set_goal_uuid,
                                  mandatory=True)
    """The UUID of the goal this audit refers to"""

    goal_name = wtypes.wsproperty(wtypes.text,
                                  _get_goal_name,
                                  _set_goal_name,
                                  mandatory=False)
    """The name of the goal this audit refers to"""

    parameters_spec = {wtypes.text: types.jsontype}
    """Parameters spec dict"""

    def __init__(self, **kwargs):
        super(Strategy, self).__init__()

        self.fields = []
        self.fields.append('uuid')
        self.fields.append('name')
        self.fields.append('display_name')
        self.fields.append('goal_uuid')
        self.fields.append('goal_name')
        self.fields.append('parameters_spec')
        setattr(self, 'uuid', kwargs.get('uuid', wtypes.Unset))
        setattr(self, 'name', kwargs.get('name', wtypes.Unset))
        setattr(self, 'display_name', kwargs.get('display_name', wtypes.Unset))
        setattr(self, 'goal_uuid', kwargs.get('goal_id', wtypes.Unset))
        setattr(self, 'goal_name', kwargs.get('goal_id', wtypes.Unset))
        setattr(self, 'parameters_spec',
                kwargs.get('parameters_spec', wtypes.Unset))

    @staticmethod
    def _convert_with_links(strategy, url, expand=True):
        if not expand:
            strategy.unset_fields_except(
                ['uuid', 'name', 'display_name', 'goal_uuid', 'goal_name'])

        strategy.links = [
            link.Link.make_link('self', url, 'strategies', strategy.uuid),
            link.Link.make_link('bookmark',
                                url,
                                'strategies',
                                strategy.uuid,
                                bookmark=True)
        ]
        return strategy

    @classmethod
    def convert_with_links(cls, strategy, expand=True):
        strategy = Strategy(**strategy.as_dict())
        hide_fields_in_newer_versions(strategy)
        return cls._convert_with_links(strategy, pecan.request.host_url,
                                       expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c',
                     name='DUMMY',
                     display_name='Dummy strategy')
        return cls._convert_with_links(sample, 'http://localhost:9322', expand)
Пример #12
0
class Audit(base.APIBase):
    """API representation of an audit.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of an audit.
    """
    _goal_uuid = None
    _goal_name = None
    _strategy_uuid = None
    _strategy_name = None

    def _get_goal(self, value):
        if value == wtypes.Unset:
            return None
        goal = None
        try:
            if utils.is_uuid_like(value) or utils.is_int_like(value):
                goal = objects.Goal.get(
                    pecan.request.context, value)
            else:
                goal = objects.Goal.get_by_name(
                    pecan.request.context, value)
        except exception.GoalNotFound:
            pass
        if goal:
            self.goal_id = goal.id
        return goal

    def _get_goal_uuid(self):
        return self._goal_uuid

    def _set_goal_uuid(self, value):
        if value and self._goal_uuid != value:
            self._goal_uuid = None
            goal = self._get_goal(value)
            if goal:
                self._goal_uuid = goal.uuid

    def _get_goal_name(self):
        return self._goal_name

    def _set_goal_name(self, value):
        if value and self._goal_name != value:
            self._goal_name = None
            goal = self._get_goal(value)
            if goal:
                self._goal_name = goal.name

    def _get_strategy(self, value):
        if value == wtypes.Unset:
            return None
        strategy = None
        try:
            if utils.is_uuid_like(value) or utils.is_int_like(value):
                strategy = objects.Strategy.get(
                    pecan.request.context, value)
            else:
                strategy = objects.Strategy.get_by_name(
                    pecan.request.context, value)
        except exception.StrategyNotFound:
            pass
        if strategy:
            self.strategy_id = strategy.id
        return strategy

    def _get_strategy_uuid(self):
        return self._strategy_uuid

    def _set_strategy_uuid(self, value):
        if value and self._strategy_uuid != value:
            self._strategy_uuid = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_uuid = strategy.uuid

    def _get_strategy_name(self):
        return self._strategy_name

    def _set_strategy_name(self, value):
        if value and self._strategy_name != value:
            self._strategy_name = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_name = strategy.name

    uuid = types.uuid
    """Unique UUID for this audit"""

    name = wtypes.text
    """Name of this audit"""

    audit_type = wtypes.text
    """Type of this audit"""

    state = wtypes.text
    """This audit state"""

    goal_uuid = wtypes.wsproperty(
        wtypes.text, _get_goal_uuid, _set_goal_uuid, mandatory=True)
    """Goal UUID the audit refers to"""

    goal_name = wtypes.wsproperty(
        wtypes.text, _get_goal_name, _set_goal_name, mandatory=False)
    """The name of the goal this audit refers to"""

    strategy_uuid = wtypes.wsproperty(
        wtypes.text, _get_strategy_uuid, _set_strategy_uuid, mandatory=False)
    """Strategy UUID the audit refers to"""

    strategy_name = wtypes.wsproperty(
        wtypes.text, _get_strategy_name, _set_strategy_name, mandatory=False)
    """The name of the strategy this audit refers to"""

    parameters = {wtypes.text: types.jsontype}
    """The strategy parameters for this audit"""

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link and associated audit links"""

    interval = wtypes.wsattr(wtypes.text, mandatory=False)
    """Launch audit periodically (in seconds)"""

    scope = wtypes.wsattr(types.jsontype, mandatory=False)
    """Audit Scope"""

    auto_trigger = wtypes.wsattr(bool, mandatory=False, default=False)
    """Autoexecute action plan once audit is succeeded"""

    next_run_time = wtypes.wsattr(datetime.datetime, mandatory=False)
    """The next time audit launch"""

    hostname = wtypes.wsattr(wtypes.text, mandatory=False)
    """Hostname the audit is running on"""

    start_time = wtypes.wsattr(datetime.datetime, mandatory=False)
    """The start time for continuous audit launch"""

    end_time = wtypes.wsattr(datetime.datetime, mandatory=False)
    """The end time that stopping continuous audit"""

    force = wsme.wsattr(bool, mandatory=False, default=False)
    """Allow Action Plan of this Audit be executed in parallel
       with other Action Plan"""

    def __init__(self, **kwargs):
        self.fields = []
        fields = list(objects.Audit.fields)
        for k in fields:
            # Skip fields we do not expose.
            if not hasattr(self, k):
                continue
            self.fields.append(k)
            setattr(self, k, kwargs.get(k, wtypes.Unset))

        self.fields.append('goal_id')
        self.fields.append('strategy_id')
        fields.append('goal_uuid')
        setattr(self, 'goal_uuid', kwargs.get('goal_id',
                wtypes.Unset))
        fields.append('goal_name')
        setattr(self, 'goal_name', kwargs.get('goal_id',
                wtypes.Unset))
        fields.append('strategy_uuid')
        setattr(self, 'strategy_uuid', kwargs.get('strategy_id',
                wtypes.Unset))
        fields.append('strategy_name')
        setattr(self, 'strategy_name', kwargs.get('strategy_id',
                wtypes.Unset))

    @staticmethod
    def _convert_with_links(audit, url, expand=True):
        if not expand:
            audit.unset_fields_except(['uuid', 'name', 'audit_type', 'state',
                                       'goal_uuid', 'interval', 'scope',
                                       'strategy_uuid', 'goal_name',
                                       'strategy_name', 'auto_trigger',
                                       'next_run_time'])

        audit.links = [link.Link.make_link('self', url,
                                           'audits', audit.uuid),
                       link.Link.make_link('bookmark', url,
                                           'audits', audit.uuid,
                                           bookmark=True)
                       ]

        return audit

    @classmethod
    def convert_with_links(cls, rpc_audit, expand=True):
        audit = Audit(**rpc_audit.as_dict())
        hide_fields_in_newer_versions(audit)
        return cls._convert_with_links(audit, pecan.request.host_url, expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c',
                     name='My Audit',
                     audit_type='ONESHOT',
                     state='PENDING',
                     created_at=datetime.datetime.utcnow(),
                     deleted_at=None,
                     updated_at=datetime.datetime.utcnow(),
                     interval='7200',
                     scope=[],
                     auto_trigger=False,
                     next_run_time=datetime.datetime.utcnow(),
                     start_time=datetime.datetime.utcnow(),
                     end_time=datetime.datetime.utcnow())

        sample.goal_id = '7ae81bb3-dec3-4289-8d6c-da80bd8001ae'
        sample.strategy_id = '7ae81bb3-dec3-4289-8d6c-da80bd8001ff'

        return cls._convert_with_links(sample, 'http://localhost:9322', expand)
Пример #13
0
class Service(base.APIBase):
    """API representation of a service.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of a service.
    """

    _status = None
    _context = context.RequestContext(is_admin=True)

    def _get_status(self):
        return self._status

    def _set_status(self, id):
        service = objects.Service.get(pecan.request.context, id)
        last_heartbeat = (service.last_seen_up or service.updated_at
                          or service.created_at)
        if isinstance(last_heartbeat, six.string_types):
            # NOTE(russellb) If this service came in over rpc via
            # conductor, then the timestamp will be a string and needs to be
            # converted back to a datetime.
            last_heartbeat = timeutils.parse_strtime(last_heartbeat)
        else:
            # Objects have proper UTC timezones, but the timeutils comparison
            # below does not (and will fail)
            last_heartbeat = last_heartbeat.replace(tzinfo=None)
        elapsed = timeutils.delta_seconds(last_heartbeat, timeutils.utcnow())
        is_up = abs(elapsed) <= CONF.service_down_time
        if not is_up:
            LOG.warning(
                'Seems service %(name)s on host %(host)s is down. '
                'Last heartbeat was %(lhb)s.'
                'Elapsed time is %(el)s', {
                    'name': service.name,
                    'host': service.host,
                    'lhb': str(last_heartbeat),
                    'el': str(elapsed)
                })
            self._status = objects.service.ServiceStatus.FAILED
        else:
            self._status = objects.service.ServiceStatus.ACTIVE

    id = wtypes.wsattr(int, readonly=True)
    """ID for this service."""

    name = wtypes.text
    """Name of the service."""

    host = wtypes.text
    """Host where service is placed on."""

    last_seen_up = wtypes.wsattr(datetime.datetime, readonly=True)
    """Time when Watcher service sent latest heartbeat."""

    status = wtypes.wsproperty(wtypes.text,
                               _get_status,
                               _set_status,
                               mandatory=True)

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link."""

    def __init__(self, **kwargs):
        super(Service, self).__init__()

        fields = list(objects.Service.fields) + ['status']
        self.fields = []
        for field in fields:
            self.fields.append(field)
            setattr(
                self, field,
                kwargs.get(field if field != 'status' else 'id', wtypes.Unset))

    @staticmethod
    def _convert_with_links(service, url, expand=True):
        if not expand:
            service.unset_fields_except(['id', 'name', 'host', 'status'])

        service.links = [
            link.Link.make_link('self', url, 'services', str(service.id)),
            link.Link.make_link('bookmark',
                                url,
                                'services',
                                str(service.id),
                                bookmark=True)
        ]
        return service

    @classmethod
    def convert_with_links(cls, service, expand=True):
        service = Service(**service.as_dict())
        hide_fields_in_newer_versions(service)
        return cls._convert_with_links(service, pecan.request.host_url, expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(id=1,
                     name='watcher-applier',
                     host='Controller',
                     last_seen_up=datetime.datetime(2016, 1, 1))
        return cls._convert_with_links(sample, 'http://localhost:9322', expand)
Пример #14
0
class AuditTemplate(base.APIBase):
    """API representation of a audit template.

    This class enforces type checking and value constraints, and converts
    between the internal object model and the API representation of an
    audit template.
    """

    _goal_uuid = None
    _goal_name = None

    _strategy_uuid = None
    _strategy_name = None

    def _get_goal(self, value):
        if value == wtypes.Unset:
            return None
        goal = None
        try:
            if (common_utils.is_uuid_like(value)
                    or common_utils.is_int_like(value)):
                goal = objects.Goal.get(pecan.request.context, value)
            else:
                goal = objects.Goal.get_by_name(pecan.request.context, value)
        except exception.GoalNotFound:
            pass
        if goal:
            self.goal_id = goal.id
        return goal

    def _get_strategy(self, value):
        if value == wtypes.Unset:
            return None
        strategy = None
        try:
            if (common_utils.is_uuid_like(value)
                    or common_utils.is_int_like(value)):
                strategy = objects.Strategy.get(pecan.request.context, value)
            else:
                strategy = objects.Strategy.get_by_name(
                    pecan.request.context, value)
        except exception.StrategyNotFound:
            pass
        if strategy:
            self.strategy_id = strategy.id
        return strategy

    def _get_goal_uuid(self):
        return self._goal_uuid

    def _set_goal_uuid(self, value):
        if value and self._goal_uuid != value:
            self._goal_uuid = None
            goal = self._get_goal(value)
            if goal:
                self._goal_uuid = goal.uuid

    def _get_strategy_uuid(self):
        return self._strategy_uuid

    def _set_strategy_uuid(self, value):
        if value and self._strategy_uuid != value:
            self._strategy_uuid = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_uuid = strategy.uuid

    def _get_goal_name(self):
        return self._goal_name

    def _set_goal_name(self, value):
        if value and self._goal_name != value:
            self._goal_name = None
            goal = self._get_goal(value)
            if goal:
                self._goal_name = goal.name

    def _get_strategy_name(self):
        return self._strategy_name

    def _set_strategy_name(self, value):
        if value and self._strategy_name != value:
            self._strategy_name = None
            strategy = self._get_strategy(value)
            if strategy:
                self._strategy_name = strategy.name

    uuid = wtypes.wsattr(types.uuid, readonly=True)
    """Unique UUID for this audit template"""

    name = wtypes.text
    """Name of this audit template"""

    description = wtypes.wsattr(wtypes.text, mandatory=False)
    """Short description of this audit template"""

    goal_uuid = wtypes.wsproperty(wtypes.text,
                                  _get_goal_uuid,
                                  _set_goal_uuid,
                                  mandatory=True)
    """Goal UUID the audit template refers to"""

    goal_name = wtypes.wsproperty(wtypes.text,
                                  _get_goal_name,
                                  _set_goal_name,
                                  mandatory=False)
    """The name of the goal this audit template refers to"""

    strategy_uuid = wtypes.wsproperty(wtypes.text,
                                      _get_strategy_uuid,
                                      _set_strategy_uuid,
                                      mandatory=False)
    """Strategy UUID the audit template refers to"""

    strategy_name = wtypes.wsproperty(wtypes.text,
                                      _get_strategy_name,
                                      _set_strategy_name,
                                      mandatory=False)
    """The name of the strategy this audit template refers to"""

    audits = wtypes.wsattr([link.Link], readonly=True)
    """Links to the collection of audits contained in this audit template"""

    links = wtypes.wsattr([link.Link], readonly=True)
    """A list containing a self link and associated audit template links"""

    scope = wtypes.wsattr(types.jsontype, mandatory=False)
    """Audit Scope"""

    def __init__(self, **kwargs):
        super(AuditTemplate, self).__init__()
        self.fields = []
        fields = list(objects.AuditTemplate.fields)

        for k in fields:
            # Skip fields we do not expose.
            if not hasattr(self, k):
                continue
            self.fields.append(k)
            setattr(self, k, kwargs.get(k, wtypes.Unset))

        self.fields.append('goal_id')
        self.fields.append('strategy_id')
        setattr(self, 'strategy_id', kwargs.get('strategy_id', wtypes.Unset))

        # goal_uuid & strategy_uuid are not part of
        # objects.AuditTemplate.fields because they're API-only attributes.
        self.fields.append('goal_uuid')
        self.fields.append('goal_name')
        self.fields.append('strategy_uuid')
        self.fields.append('strategy_name')
        setattr(self, 'goal_uuid', kwargs.get('goal_id', wtypes.Unset))
        setattr(self, 'goal_name', kwargs.get('goal_id', wtypes.Unset))
        setattr(self, 'strategy_uuid', kwargs.get('strategy_id', wtypes.Unset))
        setattr(self, 'strategy_name', kwargs.get('strategy_id', wtypes.Unset))

    @staticmethod
    def _convert_with_links(audit_template, url, expand=True):
        if not expand:
            audit_template.unset_fields_except([
                'uuid', 'name', 'goal_uuid', 'goal_name', 'scope',
                'strategy_uuid', 'strategy_name'
            ])

        # The numeric ID should not be exposed to
        # the user, it's internal only.
        audit_template.goal_id = wtypes.Unset
        audit_template.strategy_id = wtypes.Unset

        audit_template.links = [
            link.Link.make_link('self', url, 'audit_templates',
                                audit_template.uuid),
            link.Link.make_link('bookmark',
                                url,
                                'audit_templates',
                                audit_template.uuid,
                                bookmark=True)
        ]
        return audit_template

    @classmethod
    def convert_with_links(cls, rpc_audit_template, expand=True):
        audit_template = AuditTemplate(**rpc_audit_template.as_dict())
        hide_fields_in_newer_versions(audit_template)
        return cls._convert_with_links(audit_template, pecan.request.host_url,
                                       expand)

    @classmethod
    def sample(cls, expand=True):
        sample = cls(
            uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c',
            name='My Audit Template',
            description='Description of my audit template',
            goal_uuid='83e44733-b640-40e2-8d8a-7dd3be7134e6',
            strategy_uuid='367d826e-b6a4-4b70-bc44-c3f6fe1c9986',
            created_at=datetime.datetime.utcnow(),
            deleted_at=None,
            updated_at=datetime.datetime.utcnow(),
            scope=[],
        )
        return cls._convert_with_links(sample, 'http://localhost:9322', expand)