示例#1
0
文件: utils.py 项目: NicolasT/cinder
def _usage_from_volume(context, volume_ref, **kw):
    usage_info = dict(tenant_id=volume_ref['project_id'],
                      host=volume_ref['host'],
                      user_id=volume_ref['user_id'],
                      instance_uuid=volume_ref['instance_uuid'],
                      availability_zone=volume_ref['availability_zone'],
                      volume_id=volume_ref['id'],
                      volume_type=volume_ref['volume_type_id'],
                      display_name=volume_ref['display_name'],
                      launched_at=timeutils.isotime(at=
                                                    volume_ref['launched_at']),
                      created_at=timeutils.isotime(at=
                                                   volume_ref['created_at']),
                      status=volume_ref['status'],
                      snapshot_id=volume_ref['snapshot_id'],
                      size=volume_ref['size'],
                      replication_status=volume_ref['replication_status'],
                      replication_extended_status=
                      volume_ref['replication_extended_status'],
                      replication_driver_data=
                      volume_ref['replication_driver_data'],
                      )

    usage_info.update(kw)
    return usage_info
示例#2
0
文件: instance.py 项目: badock/nova
    def get_active_by_window_joined(cls, context, begin, end=None,
                                    project_id=None, host=None,
                                    expected_attrs=None,
                                    use_slave=False):
        """Get instances and joins active during a certain time window.

        :param:context: nova request context
        :param:begin: datetime for the start of the time window
        :param:end: datetime for the end of the time window
        :param:project_id: used to filter instances by project
        :param:host: used to filter instances on a given compute host
        :param:expected_attrs: list of related fields that can be joined
        in the database layer when querying for instances
        :param use_slave if True, ship this query off to a DB slave
        :returns: InstanceList

        """
        # NOTE(mriedem): We have to convert the datetime objects to string
        # primitives for the remote call.
        begin = timeutils.isotime(begin)
        end = timeutils.isotime(end) if end else None
        return cls._get_active_by_window_joined(context, begin, end,
                                                project_id, host,
                                                expected_attrs,
                                                use_slave=use_slave)
示例#3
0
    def show(self, request, instance):
        """Detailed view of a single instance."""
        server = {
            "server": {
                "id": instance["uuid"],
                "name": instance["display_name"],
                "status": self._get_vm_status(instance),
                "tenant_id": instance.get("project_id") or "",
                "user_id": instance.get("user_id") or "",
                "metadata": self._get_metadata(instance),
                "hostId": self._get_host_id(instance) or "",
                # TODO(alex_xu): '_get_image' return {} when there image_ref
                # isn't existed in V3 API, we revert it back to return "" in
                # V2.1.
                "image": self._get_image(request, instance),
                "flavor": self._get_flavor(request, instance),
                "created": timeutils.isotime(instance["created_at"]),
                "updated": timeutils.isotime(instance["updated_at"]),
                "addresses": self._get_addresses(request, instance),
                "links": self._get_links(request,
                                         instance["uuid"],
                                         self._collection_name),
            },
        }
        if server["server"]["status"] in self._fault_statuses:
            _inst_fault = self._get_fault(request, instance)
            if _inst_fault:
                server['server']['fault'] = _inst_fault

        if server["server"]["status"] in self._progress_statuses:
            server["server"]["progress"] = instance.get("progress", 0)

        return server
示例#4
0
def format_watch(watch):

    result = {
        api.WATCH_ACTIONS_ENABLED: watch.rule.get(api.RULE_ACTIONS_ENABLED),
        api.WATCH_ALARM_ACTIONS: watch.rule.get(api.RULE_ALARM_ACTIONS),
        api.WATCH_TOPIC: watch.rule.get(api.RULE_TOPIC),
        api.WATCH_UPDATED_TIME: timeutils.isotime(watch.updated_at),
        api.WATCH_DESCRIPTION: watch.rule.get(api.RULE_DESCRIPTION),
        api.WATCH_NAME: watch.name,
        api.WATCH_COMPARISON: watch.rule.get(api.RULE_COMPARISON),
        api.WATCH_DIMENSIONS: watch.rule.get(api.RULE_DIMENSIONS) or [],
        api.WATCH_PERIODS: watch.rule.get(api.RULE_PERIODS),
        api.WATCH_INSUFFICIENT_ACTIONS:
        watch.rule.get(api.RULE_INSUFFICIENT_ACTIONS),
        api.WATCH_METRIC_NAME: watch.rule.get(api.RULE_METRIC_NAME),
        api.WATCH_NAMESPACE: watch.rule.get(api.RULE_NAMESPACE),
        api.WATCH_OK_ACTIONS: watch.rule.get(api.RULE_OK_ACTIONS),
        api.WATCH_PERIOD: watch.rule.get(api.RULE_PERIOD),
        api.WATCH_STATE_REASON: watch.rule.get(api.RULE_STATE_REASON),
        api.WATCH_STATE_REASON_DATA:
        watch.rule.get(api.RULE_STATE_REASON_DATA),
        api.WATCH_STATE_UPDATED_TIME: timeutils.isotime(
            watch.rule.get(api.RULE_STATE_UPDATED_TIME)),
        api.WATCH_STATE_VALUE: watch.state,
        api.WATCH_STATISTIC: watch.rule.get(api.RULE_STATISTIC),
        api.WATCH_THRESHOLD: watch.rule.get(api.RULE_THRESHOLD),
        api.WATCH_UNIT: watch.rule.get(api.RULE_UNIT),
        api.WATCH_STACK_ID: watch.stack_id
    }

    return result
示例#5
0
def format_stack(stack, preview=False):
    '''
    Return a representation of the given stack that matches the API output
    expectations.
    '''
    updated_time = stack.updated_time and timeutils.isotime(stack.updated_time)
    info = {
        api.STACK_NAME: stack.name,
        api.STACK_ID: dict(stack.identifier()),
        api.STACK_CREATION_TIME: timeutils.isotime(stack.created_time),
        api.STACK_UPDATED_TIME: updated_time,
        api.STACK_NOTIFICATION_TOPICS: [],  # TODO Not implemented yet
        api.STACK_PARAMETERS: stack.parameters.map(str),
        api.STACK_DESCRIPTION: stack.t[stack.t.DESCRIPTION],
        api.STACK_TMPL_DESCRIPTION: stack.t[stack.t.DESCRIPTION],
        api.STACK_CAPABILITIES: [],   # TODO Not implemented yet
        api.STACK_DISABLE_ROLLBACK: stack.disable_rollback,
        api.STACK_TIMEOUT: stack.timeout_mins,
        api.STACK_OWNER: stack.username,
        api.STACK_PARENT: stack.owner_id,
    }

    if not preview:
        update_info = {
            api.STACK_ACTION: stack.action or '',
            api.STACK_STATUS: stack.status or '',
            api.STACK_STATUS_DATA: stack.status_reason,
        }
        info.update(update_info)

    # allow users to view the outputs of stacks
    if (stack.action != stack.DELETE and stack.status != stack.IN_PROGRESS):
        info[api.STACK_OUTPUTS] = format_stack_outputs(stack, stack.outputs)

    return info
 def get(key):
     if key == "tokens/%s" % VALID_TOKEN:
         dt = timeutils.utcnow() + datetime.timedelta(minutes=5)
         return json.dumps(({'access': {
             'token': {'id': VALID_TOKEN,
                       'expires': timeutils.isotime(dt)},
             'user': {
                 'id': 'user_id1',
                 'name': 'user_name1',
                 'tenantId': '123i2910',
                 'tenantName': 'mytenant',
                 'roles': [
                     {'name': 'admin'},
                 ]},
         }}, timeutils.isotime(dt)))
     if key == "tokens/%s" % VALID_TOKEN2:
         dt = timeutils.utcnow() + datetime.timedelta(minutes=5)
         return json.dumps(({'access': {
             'token': {'id': VALID_TOKEN2,
                       'expires': timeutils.isotime(dt)},
             'user': {
                 'id': 'user_id2',
                 'name': 'user-good',
                 'tenantId': 'project-good',
                 'tenantName': 'goodies',
                 'roles': [
                     {'name': 'Member'},
                 ]},
         }}, timeutils.isotime(dt)))
示例#7
0
def format_image_notification(image):
    """
    Given a glance.domain.Image object, return a dictionary of relevant
    notification information. We purposely do not include 'location'
    as it may contain credentials.
    """
    return {
        'id': image.image_id,
        'name': image.name,
        'status': image.status,
        'created_at': timeutils.isotime(image.created_at),
        'updated_at': timeutils.isotime(image.updated_at),
        'min_disk': image.min_disk,
        'min_ram': image.min_ram,
        'protected': image.protected,
        'checksum': image.checksum,
        'owner': image.owner,
        'disk_format': image.disk_format,
        'container_format': image.container_format,
        'size': image.size,
        'is_public': image.visibility == 'public',
        'properties': dict(image.extra_properties),
        'tags': list(image.tags),
        'deleted': False,
        'deleted_at': None,
    }
示例#8
0
    def show(self, request, instance):
        """Detailed view of a single instance."""
        ip_v4 = instance.get('access_ip_v4')
        ip_v6 = instance.get('access_ip_v6')
        server = {
            "server": {
                "id": instance["uuid"],
                "name": instance["display_name"],
                "status": self._get_vm_status(instance),
                "tenant_id": instance.get("project_id") or "",
                "user_id": instance.get("user_id") or "",
                "metadata": self._get_metadata(instance),
                "hostId": self._get_host_id(instance) or "",
                "image": self._get_image(request, instance),
                "flavor": self._get_flavor(request, instance),
                "created": timeutils.isotime(instance["created_at"]),
                "updated": timeutils.isotime(instance["updated_at"]),
                "addresses": self._get_addresses(request, instance),
                "accessIPv4": str(ip_v4) if ip_v4 is not None else '',
                "accessIPv6": str(ip_v6) if ip_v6 is not None else '',
                "links": self._get_links(request,
                                         instance["uuid"],
                                         self._collection_name),
            },
        }
        if server["server"]["status"] in self._fault_statuses:
            _inst_fault = self._get_fault(request, instance)
            if _inst_fault:
                server['server']['fault'] = _inst_fault

        if server["server"]["status"] in self._progress_statuses:
            server["server"]["progress"] = instance.get("progress", 0)

        return server
示例#9
0
 def _populate_token_dates(self, token_data, expires=None, trust=None,
                           issued_at=None):
     if not expires:
         expires = provider.default_expire_time()
     if not isinstance(expires, six.string_types):
         expires = timeutils.isotime(expires, subsecond=True)
     token_data['expires_at'] = expires
     token_data['issued_at'] = (issued_at or
                                timeutils.isotime(subsecond=True))
示例#10
0
 def setUp(self):
     super(TestDateTime, self).setUp()
     self.dt = datetime.datetime(1955, 11, 5, tzinfo=iso8601.iso8601.Utc())
     self.field = fields.DateTimeField()
     self.coerce_good_values = [(self.dt, self.dt),
                                (timeutils.isotime(self.dt), self.dt)]
     self.coerce_bad_values = [1, 'foo']
     self.to_primitive_values = [(self.dt, timeutils.isotime(self.dt))]
     self.from_primitive_values = [(timeutils.isotime(self.dt), self.dt)]
示例#11
0
    def test_update_environment(self):
        """Check that environment rename works."""
        self._set_policy_rules(
            {'show_environment': '@',
             'update_environment': '@'}
        )
        self.expect_policy_check('update_environment',
                                 {'environment_id': '12345'})

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        expected = dict(
            id='12345',
            name='my-env',
            version=0,
            networking={},
            created=fake_now,
            updated=fake_now,
            tenant_id=self.tenant,
            description={
                'Objects': {
                    '?': {'id': '12345'}
                },
                'Attributes': []
            }
        )
        e = models.Environment(**expected)
        test_utils.save_models(e)

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        del expected['description']
        expected['services'] = []
        expected['status'] = 'ready'
        expected['name'] = 'renamed_env'
        expected['updated'] = fake_now

        body = {
            'name': 'renamed_env'
        }
        req = self._put('/environments/12345', json.dumps(body))
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)

        self.expect_policy_check('show_environment',
                                 {'environment_id': '12345'})
        req = self._get('/environments/12345')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)

        expected['created'] = timeutils.isotime(expected['created'])[:-1]
        expected['updated'] = timeutils.isotime(expected['updated'])[:-1]

        self.assertEqual(expected, json.loads(result.body))
示例#12
0
 def _format_image_member(self, member):
     member_view = {}
     attributes = ['member_id', 'image_id', 'status']
     for key in attributes:
         member_view[key] = getattr(member, key)
     member_view['created_at'] = timeutils.isotime(member.created_at)
     member_view['updated_at'] = timeutils.isotime(member.updated_at)
     member_view['schema'] = '/v2/schemas/member'
     member_view = self.schema.filter(member_view)
     return member_view
示例#13
0
 def _format_task_stub(self, schema, task):
     task_view = {}
     task_view['id'] = task.task_id
     task_view['type'] = task.type
     task_view['status'] = task.status
     task_view['owner'] = task.owner
     if task.expires_at:
         task_view['expires_at'] = timeutils.isotime(task.expires_at)
     task_view['created_at'] = timeutils.isotime(task.created_at)
     task_view['updated_at'] = timeutils.isotime(task.updated_at)
     task_view['self'] = self._get_task_location(task)
     task_view['schema'] = '/v2/schemas/task'
     task_view = schema.filter(task_view)  # domain
     return task_view
示例#14
0
    def test_create_environment(self):
        """Create an environment, test environment.show()."""
        self._set_policy_rules(
            {'list_environments': '@',
             'create_environment': '@',
             'show_environment': '@'}
        )
        self.expect_policy_check('create_environment')

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        uuids = ('env_object_id', 'network_id', 'environment_id')
        mock_uuid = self._stub_uuid(uuids)

        expected = {'tenant_id': self.tenant,
                    'id': 'environment_id',
                    'name': 'my_env',
                    'networking': {},
                    'version': 0,
                    # TODO(sjmc7) - bug 1347298
                    'created': timeutils.isotime(fake_now)[:-1],
                    'updated': timeutils.isotime(fake_now)[:-1]}

        body = {'name': 'my_env'}
        req = self._post('/environments', json.dumps(body))
        result = req.get_response(self.api)
        self.assertEqual(expected, json.loads(result.body))

        expected['status'] = 'ready'

        # Reset the policy expectation
        self.expect_policy_check('list_environments')

        req = self._get('/environments')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)
        self.assertEqual({'environments': [expected]}, json.loads(result.body))

        expected['services'] = []

        # Reset the policy expectation
        self.expect_policy_check('show_environment',
                                 {'environment_id': uuids[-1]})

        req = self._get('/environments/%s' % uuids[-1])
        result = req.get_response(self.api)

        self.assertEqual(expected, json.loads(result.body))
        self.assertEqual(3, mock_uuid.call_count)
示例#15
0
def format_task_notification(task):
    # NOTE(nikhil): input is not passed to the notifier payload as it may
    # contain sensitive info.
    return {'id': task.task_id,
            'type': task.type,
            'status': task.status,
            'result': None,
            'owner': task.owner,
            'message': None,
            'expires_at': timeutils.isotime(task.expires_at),
            'created_at': timeutils.isotime(task.created_at),
            'updated_at': timeutils.isotime(task.updated_at),
            'deleted': False,
            'deleted_at': None,
            }
示例#16
0
    def _format_image(self, image):
        image_view = dict()
        try:
            image_view = dict(image.extra_properties)
            attributes = ['name', 'disk_format', 'container_format',
                          'visibility', 'size', 'virtual_size', 'status',
                          'checksum', 'protected', 'min_ram', 'min_disk',
                          'owner']
            for key in attributes:
                image_view[key] = getattr(image, key)
            image_view['id'] = image.image_id
            image_view['created_at'] = timeutils.isotime(image.created_at)
            image_view['updated_at'] = timeutils.isotime(image.updated_at)

            if CONF.show_multiple_locations:
                locations = list(image.locations)
                if locations:
                    image_view['locations'] = []
                    for loc in locations:
                        tmp = dict(loc)
                        tmp.pop('id', None)
                        tmp.pop('status', None)
                        image_view['locations'].append(tmp)
                else:
                    # NOTE (flwang): We will still show "locations": [] if
                    # image.locations is None to indicate it's allowed to show
                    # locations but it's just non-existent.
                    image_view['locations'] = []
                    LOG.debug("There is not available location "
                              "for image %s" % image.image_id)

            if CONF.show_image_direct_url:
                if image.locations:
                    # Choose best location configured strategy
                    l = location_strategy.choose_best_location(image.locations)
                    image_view['direct_url'] = l['url']
                else:
                    LOG.debug("There is not available location "
                              "for image %s" % image.image_id)

            image_view['tags'] = list(image.tags)
            image_view['self'] = self._get_image_href(image)
            image_view['file'] = self._get_image_href(image, 'file')
            image_view['schema'] = '/v2/schemas/image'
            image_view = self.schema.filter(image_view)  # domain
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        return image_view
示例#17
0
 def assertReportedEventMatchesRecorded(self, event, sample, before_time):
     after_time = timeutils.utcnow()
     event_issued_before = timeutils.normalize_time(
         timeutils.parse_isotime(event['issued_before']))
     self.assertTrue(
         before_time <= event_issued_before,
         'invalid event issued_before time; %s is not later than %s.' % (
             timeutils.isotime(event_issued_before, subsecond=True),
             timeutils.isotime(before_time, subsecond=True)))
     self.assertTrue(
         event_issued_before <= after_time,
         'invalid event issued_before time; %s is not earlier than %s.' % (
             timeutils.isotime(event_issued_before, subsecond=True),
             timeutils.isotime(after_time, subsecond=True)))
     del (event['issued_before'])
     self.assertEqual(sample, event)
示例#18
0
    def test_view_builder_list(self):
        view_builder = views_types.ViewBuilder()

        now = timeutils.isotime()
        raw_volume_types = []
        for i in range(0, 10):
            raw_volume_types.append(
                dict(
                    name='new_type',
                    deleted=False,
                    created_at=now,
                    updated_at=now,
                    extra_specs={},
                    deleted_at=None,
                    id=42 + i
                )
            )

        request = fakes.HTTPRequest.blank("/v2")
        output = view_builder.index(request, raw_volume_types)

        self.assertIn('volume_types', output)
        for i in range(0, 10):
            expected_volume_type = dict(
                name='new_type',
                extra_specs={},
                id=42 + i
            )
            self.assertDictMatch(output['volume_types'][i],
                                 expected_volume_type)
示例#19
0
    def test_set_and_get_keyring_expired(self):
        cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
                                   tenant_id=TENANT_ID, auth_url=AUTH_URL,
                                   use_keyring=True)

        # set an expired token into the keyring
        auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
        auth_ref['token']['expires'] = timeutils.isotime(expired)
        self.memory_keyring.password = pickle.dumps(auth_ref)

        # stub and check that a new token is received, so not using expired
        method = 'get_raw_token_from_identity_service'
        with mock.patch.object(cl, method) as meth:
            meth.return_value = (True, PROJECT_SCOPED_TOKEN)

            self.assertTrue(cl.authenticate())

            self.assertEqual(1, meth.call_count)

        # check that a value was returned from the keyring
        self.assertTrue(self.memory_keyring.fetched)

        # check that the new token has been loaded into the keyring
        new_auth_ref = pickle.loads(self.memory_keyring.password)
        self.assertEqual(new_auth_ref['token']['expires'],
                         PROJECT_SCOPED_TOKEN['access']['token']['expires'])
示例#20
0
 def test_datetime_or_str_or_none(self):
     dts = timeutils.isotime()
     dt = timeutils.parse_isotime(dts)
     self.assertEqual(utils.datetime_or_str_or_none(dt), dt)
     self.assertIsNone(utils.datetime_or_str_or_none(None))
     self.assertEqual(utils.datetime_or_str_or_none(dts), dt)
     self.assertRaises(ValueError, utils.datetime_or_str_or_none, 'foo')
示例#21
0
    def create_test_stack(self):
        test_template = {'HeatTemplateFormatVersion': '2012-12-12',
                         'Parameters': {'Foo': {'Type': 'String'},
                                        'Pass': {'Type': 'String',
                                                 'NoEcho': True}},
                         'Resources':
                         {'TestResource': {'Type': 'GenericResource',
                                           'Properties': {'Foo': 'abc'}}},
                         'Outputs': {'food':
                                     {'Value':
                                      {'Fn::GetAtt': ['TestResource',
                                                      'foo']}}}}
        template = parser.Template(test_template)
        self.ctx = utils.dummy_context()
        self.ctx.tenant_id = 'test_tenant'

        env = environment.Environment()
        env.load({u'parameters':
                  {u'Foo': 'user_data', u'Pass': '******'}})
        self.stack_name = utils.random_name()
        stack = parser.Stack(self.ctx, self.stack_name, template,
                             env=env, disable_rollback=True)
        self.stack = stack
        stack.store()
        self.created_time = stack.created_time
        self.create_at = timeutils.isotime(self.created_time)
        stack.create()

        self.expected = {}
        for action in ('create', 'suspend', 'delete'):
            self.make_mocks(action)
示例#22
0
    def make_vnic_sample(instance, name, type, unit, volume, vnic_data):
        metadata = copy.copy(vnic_data)
        resource_metadata = dict(zip(metadata._fields, metadata))
        resource_metadata['instance_id'] = instance.id
        resource_metadata['instance_type'] = (instance.flavor['id'] if
                                              instance.flavor else None)

        compute_util.add_reserved_user_metadata(instance.metadata,
                                                resource_metadata)

        if vnic_data.fref is not None:
            rid = vnic_data.fref
        else:
            instance_name = util.instance_name(instance)
            rid = "%s-%s-%s" % (instance_name, instance.id, vnic_data.name)

        return sample.Sample(
            name=name,
            type=type,
            unit=unit,
            volume=volume,
            user_id=instance.user_id,
            project_id=instance.tenant_id,
            resource_id=rid,
            timestamp=timeutils.isotime(),
            resource_metadata=resource_metadata
        )
示例#23
0
文件: sql.py 项目: ging/keystone
    def create_access_token(self, request_token_id, token_duration, access_token_id=None, access_token_secret=None):
        if access_token_id is None:
            access_token_id = uuid.uuid4().hex
        if access_token_secret is None:
            access_token_secret = uuid.uuid4().hex
        session = sql.get_session()
        with session.begin():
            req_token_ref = self._get_request_token(session, request_token_id)
            token_dict = req_token_ref.to_dict()

            expiry_date = None
            if token_duration:
                now = timeutils.utcnow()
                future = now + datetime.timedelta(seconds=token_duration)
                expiry_date = timeutils.isotime(future, subsecond=True)

            # add Access Token
            ref = {}
            ref["id"] = access_token_id
            ref["access_secret"] = access_token_secret
            ref["authorizing_user_id"] = token_dict["authorizing_user_id"]
            ref["project_id"] = token_dict["requested_project_id"]
            ref["role_ids"] = token_dict["role_ids"]
            ref["consumer_id"] = token_dict["consumer_id"]
            ref["expires_at"] = expiry_date
            token_ref = AccessToken.from_dict(ref)
            session.add(token_ref)

            # remove request token, it's been used
            session.delete(req_token_ref)

        return token_ref.to_dict()
示例#24
0
    def test_trusted_filter_update_cache(self, req_mock):
        oat_data = {"hosts": [{"host_name": "node1",
                                    "trust_lvl": "untrusted",
                                    "vtime": timeutils.isotime()}]}

        req_mock.return_value = requests.codes.OK, oat_data
        extra_specs = {'trust:trusted_host': 'untrusted'}
        filter_properties = {'context': mock.sentinel.ctx,
                             'instance_type': {'memory_mb': 1024,
                                               'extra_specs': extra_specs}}
        host = fakes.FakeHostState('host1', 'node1', {})

        self.filt_cls.host_passes(host, filter_properties)  # Fill the caches

        req_mock.reset_mock()
        self.filt_cls.host_passes(host, filter_properties)
        self.assertFalse(req_mock.called)

        req_mock.reset_mock()

        timeutils.set_time_override(timeutils.utcnow())
        timeutils.advance_time_seconds(
            CONF.trusted_computing.attestation_auth_timeout + 80)
        self.filt_cls.host_passes(host, filter_properties)
        self.assertTrue(req_mock.called)

        timeutils.clear_time_override()
示例#25
0
文件: idp.py 项目: k4veri/keystone
    def _create_assertion(self, issuer, signature, subject, authn_statement,
                          attribute_statement):
        """Create an object that represents a SAML Assertion.

        <ns0:Assertion
          ID="35daed258ba647ba8962e9baff4d6a46"
          IssueInstant="2014-06-11T15:45:58Z"
          Version="2.0">
            <ns0:Issuer> ... </ns0:Issuer>
            <ns1:Signature> ... </ns1:Signature>
            <ns0:Subject> ... </ns0:Subject>
            <ns0:AuthnStatement> ... </ns0:AuthnStatement>
            <ns0:AttributeStatement> ... </ns0:AttributeStatement>
        </ns0:Assertion>

        :return: XML <Assertion> object

        """
        assertion = saml.Assertion()
        assertion.id = self.assertion_id
        assertion.issue_instant = timeutils.isotime()
        assertion.version = '2.0'
        assertion.issuer = issuer
        assertion.signature = signature
        assertion.subject = subject
        assertion.authn_statement = authn_statement
        assertion.attribute_statement = attribute_statement
        return assertion
示例#26
0
文件: idp.py 项目: k4veri/keystone
    def _create_response(self, issuer, status, assertion, recipient):
        """Create an object that represents a SAML Response.

        <ns0:Response
          Destination="http://beta.com/Shibboleth.sso/SAML2/POST"
          ID="c5954543230e4e778bc5b92923a0512d"
          IssueInstant="2014-07-30T03:19:45Z"
          Version="2.0" />
            <ns0:Issuer> ... </ns0:Issuer>
            <ns0:Assertion> ... </ns0:Assertion>
            <ns0:Status> ... </ns0:Status>
        </ns0:Response>

        :return: XML <Response> object

        """
        response = samlp.Response()
        response.id = uuid.uuid4().hex
        response.destination = recipient
        response.issue_instant = timeutils.isotime()
        response.version = '2.0'
        response.issuer = issuer
        response.status = status
        response.assertion = assertion
        return response
示例#27
0
    def test_view_builder_show(self):
        view_builder = views_types.ViewBuilder()

        now = timeutils.isotime()
        raw_volume_type = dict(
            name='new_type',
            description='new_type_desc',
            deleted=False,
            created_at=now,
            updated_at=now,
            extra_specs={},
            deleted_at=None,
            id=42,
        )

        request = fakes.HTTPRequest.blank("/v2")
        output = view_builder.show(request, raw_volume_type)

        self.assertIn('volume_type', output)
        expected_volume_type = dict(
            name='new_type',
            description='new_type_desc',
            extra_specs={},
            id=42,
        )
        self.assertDictMatch(output['volume_type'], expected_volume_type)
示例#28
0
def format_stack_resource(resource, detail=True, with_props=False):
    '''
    Return a representation of the given resource that matches the API output
    expectations.
    '''
    last_updated_time = resource.updated_time or resource.created_time
    res = {
        api.RES_UPDATED_TIME: timeutils.isotime(last_updated_time),
        api.RES_NAME: resource.name,
        api.RES_PHYSICAL_ID: resource.resource_id or '',
        api.RES_ACTION: resource.action,
        api.RES_STATUS: resource.status,
        api.RES_STATUS_DATA: resource.status_reason,
        api.RES_TYPE: resource.type(),
        api.RES_ID: dict(resource.identifier()),
        api.RES_STACK_ID: dict(resource.stack.identifier()),
        api.RES_STACK_NAME: resource.stack.name,
        api.RES_REQUIRED_BY: resource.required_by(),
    }

    if (hasattr(resource, 'nested') and callable(resource.nested) and
            resource.nested()):
        res[api.RES_NESTED_STACK_ID] = dict(resource.nested().identifier())

    if resource.stack.parent_resource:
        res[api.RES_PARENT_RESOURCE] = resource.stack.parent_resource.name

    if detail:
        res[api.RES_DESCRIPTION] = resource.t.description
        res[api.RES_METADATA] = resource.metadata_get()

    if with_props:
        res[api.RES_SCHEMA_PROPERTIES] = format_resource_properties(resource)

    return res
示例#29
0
 def test_base_attributes(self):
     dt = datetime.datetime(1955, 11, 5)
     obj = MyObj(created_at=dt, updated_at=dt, deleted_at=None, deleted=False)
     expected = {
         "nova_object.name": "MyObj",
         "nova_object.namespace": "nova",
         "nova_object.version": "1.6",
         "nova_object.changes": ["deleted", "created_at", "deleted_at", "updated_at"],
         "nova_object.data": {
             "created_at": timeutils.isotime(dt),
             "updated_at": timeutils.isotime(dt),
             "deleted_at": None,
             "deleted": False,
         },
     }
     self.assertEqual(obj.obj_to_primitive(), expected)
示例#30
0
 def list_trusts(self, context):
     query = context['query_string']
     trusts = []
     if not query:
         self.assert_admin(context)
         trusts += self.trust_api.list_trusts()
     if 'trustor_user_id' in query:
         user_id = query['trustor_user_id']
         calling_user_id = self._get_user_id(context)
         if user_id != calling_user_id:
             raise exception.Forbidden()
         trusts += (self.trust_api.
                    list_trusts_for_trustor(user_id))
     if 'trustee_user_id' in query:
         user_id = query['trustee_user_id']
         calling_user_id = self._get_user_id(context)
         if user_id != calling_user_id:
             raise exception.Forbidden()
         trusts += self.trust_api.list_trusts_for_trustee(user_id)
     for trust in trusts:
         # get_trust returns roles, list_trusts does not
         # It seems in some circumstances, roles does not
         # exist in the query response, so check first
         if 'roles' in trust:
             del trust['roles']
         if trust.get('expires_at') is not None:
             trust['expires_at'] = (timeutils.isotime
                                    (trust['expires_at'],
                                     subsecond=True))
     return TrustV3.wrap_collection(context, trusts)
示例#31
0
 def get_samples(self, manager, cache, resources):
     tenants = resources
     for tenant, account in self._iter_accounts(manager.keystone,
                                                cache, tenants):
         yield sample.Sample(
             name='storage.objects.containers',
             type=sample.TYPE_GAUGE,
             volume=int(account['x-account-container-count']),
             unit='container',
             user_id=None,
             project_id=tenant,
             resource_id=tenant,
             timestamp=timeutils.isotime(),
             resource_metadata=None,
         )
示例#32
0
    def test_cleanup_user_index_on_create(self):
        user_id = six.text_type(uuid.uuid4().hex)
        valid_token_id, data = self.create_token_sample_data(user_id=user_id)
        expired_token_id, expired_data = self.create_token_sample_data(
            user_id=user_id)

        expire_delta = datetime.timedelta(seconds=86400)

        # NOTE(morganfainberg): Directly access the data cache since we need to
        # get expired tokens as well as valid tokens.
        user_key = self.token_api.driver._prefix_user_id(user_id)
        user_token_list = self.token_api.driver._store.get(user_key)
        valid_token_ref = self.token_api.get_token(valid_token_id)
        expired_token_ref = self.token_api.get_token(expired_token_id)
        expected_user_token_list = [
            (valid_token_id,
             timeutils.isotime(valid_token_ref['expires'], subsecond=True)),
            (expired_token_id,
             timeutils.isotime(expired_token_ref['expires'], subsecond=True))
        ]
        self.assertEqual(expected_user_token_list, user_token_list)
        new_expired_data = (expired_token_id,
                            timeutils.isotime(
                                (timeutils.utcnow() - expire_delta),
                                subsecond=True))
        self._update_user_token_index_direct(user_key, expired_token_id,
                                             new_expired_data)
        valid_token_id_2, valid_data_2 = self.create_token_sample_data(
            user_id=user_id)
        valid_token_ref_2 = self.token_api.get_token(valid_token_id_2)
        expected_user_token_list = [
            (valid_token_id,
             timeutils.isotime(valid_token_ref['expires'], subsecond=True)),
            (valid_token_id_2,
             timeutils.isotime(valid_token_ref_2['expires'], subsecond=True))
        ]
        user_token_list = self.token_api.driver._store.get(user_key)
        self.assertEqual(expected_user_token_list, user_token_list)

        # Test that revoked tokens are removed from the list on create.
        self.token_api.delete_token(valid_token_id_2)
        new_token_id, data = self.create_token_sample_data(user_id=user_id)
        new_token_ref = self.token_api.get_token(new_token_id)
        expected_user_token_list = [
            (valid_token_id,
             timeutils.isotime(valid_token_ref['expires'], subsecond=True)),
            (new_token_id,
             timeutils.isotime(new_token_ref['expires'], subsecond=True))
        ]
        user_token_list = self.token_api.driver._store.get(user_key)
        self.assertEqual(expected_user_token_list, user_token_list)
示例#33
0
    def revocation_list(self, context, auth=None):
        if not CONF.token.revoke_by_id:
            raise exception.Gone()
        tokens = self.token_provider_api.list_revoked_tokens()

        for t in tokens:
            expires = t['expires']
            if expires and isinstance(expires, datetime.datetime):
                t['expires'] = timeutils.isotime(expires)
        data = {'revoked': tokens}
        json_data = jsonutils.dumps(data)
        signed_text = cms.cms_sign_text(json_data, CONF.signing.certfile,
                                        CONF.signing.keyfile)

        return {'signed': signed_text}
示例#34
0
 def format_token(cls, token_ref, roles_ref=None, catalog_ref=None):
     user_ref = token_ref['user']
     metadata_ref = token_ref['metadata']
     if roles_ref is None:
         roles_ref = []
     expires = token_ref.get('expires', provider.default_expire_time())
     if expires is not None:
         if not isinstance(expires, six.text_type):
             expires = timeutils.isotime(expires)
     o = {
         'access': {
             'token': {
                 'id': token_ref['id'],
                 'expires': expires,
                 'issued_at': timeutils.strtime()
             },
             'user': {
                 'id': user_ref['id'],
                 'name': user_ref['name'],
                 'username': user_ref['name'],
                 'roles': roles_ref,
                 'roles_links': metadata_ref.get('roles_links', [])
             }
         }
     }
     if 'bind' in token_ref:
         o['access']['token']['bind'] = token_ref['bind']
     if 'tenant' in token_ref and token_ref['tenant']:
         token_ref['tenant']['enabled'] = True
         o['access']['token']['tenant'] = token_ref['tenant']
     if catalog_ref is not None:
         o['access']['serviceCatalog'] = V2TokenDataHelper.format_catalog(
             catalog_ref)
     if metadata_ref:
         if 'is_admin' in metadata_ref:
             o['access']['metadata'] = {
                 'is_admin': metadata_ref['is_admin']
             }
         else:
             o['access']['metadata'] = {'is_admin': 0}
     if 'roles' in metadata_ref:
         o['access']['metadata']['roles'] = metadata_ref['roles']
     if CONF.trust.enabled and 'trust_id' in metadata_ref:
         o['access']['trust'] = {
             'trustee_user_id': metadata_ref['trustee_user_id'],
             'id': metadata_ref['trust_id']
         }
     return o
示例#35
0
def make_sample_from_host(host_url, name, type, unit, volume,
                          project_id=None, user_id=None, res_metadata=None):

    resource_metadata = make_resource_metadata(res_metadata, host_url)

    return sample.Sample(
        name='hardware.' + name,
        type=type,
        unit=unit,
        volume=volume,
        user_id=project_id,
        project_id=user_id,
        resource_id=host_url.hostname,
        timestamp=timeutils.isotime(),
        resource_metadata=resource_metadata,
        source='hardware',
    )
示例#36
0
 def get_samples(self, manager, cache, resources):
     for endpoint in resources:
         for project, account in self._iter_accounts(
                 manager.keystone, cache, endpoint):
             containers_info = account[1]
             for container in containers_info:
                 yield sample.Sample(
                     name='storage.containers.objects',
                     type=sample.TYPE_GAUGE,
                     volume=int(container['count']),
                     unit='object',
                     user_id=None,
                     project_id=project,
                     resource_id=project + '/' + container['name'],
                     timestamp=timeutils.isotime(),
                     resource_metadata=None,
                 )
示例#37
0
 def get_samples(self, manager, cache, resources):
     tenants = resources
     for tenant, account in self._iter_accounts(manager.keystone, cache,
                                                tenants):
         containers_info = account[1]
         for container in containers_info:
             yield sample.Sample(
                 name='storage.containers.objects.size',
                 type=sample.TYPE_GAUGE,
                 volume=int(container['bytes']),
                 unit='B',
                 user_id=None,
                 project_id=tenant,
                 resource_id=tenant + '/' + container['name'],
                 timestamp=timeutils.isotime(),
                 resource_metadata=None,
             )
示例#38
0
    def create_token(self, token_id, data):
        """Create a token by id and data.

        It is assumed the caller has performed data validation on the "data"
        parameter.
        """
        data_copy = copy.deepcopy(data)
        ptk = self._prefix_token_id(token_id)
        if not data_copy.get('expires'):
            data_copy['expires'] = provider.default_expire_time()
        if not data_copy.get('user_id'):
            data_copy['user_id'] = data_copy['user']['id']

        # NOTE(morganfainberg): for ease of manipulating the data without
        # concern about the backend, always store the value(s) in the
        # index as the isotime (string) version so this is where the string is
        # built.
        expires_str = timeutils.isotime(data_copy['expires'], subsecond=True)

        self._set_key(ptk, data_copy)
        user_id = data['user']['id']
        user_key = self._prefix_user_id(user_id)
        self._update_user_token_list(user_key, token_id, expires_str)
        if CONF.trust.enabled and data.get('trust_id'):
            # NOTE(morganfainberg): If trusts are enabled and this is a trust
            # scoped token, we add the token to the trustee list as well.  This
            # allows password changes of the trustee to also expire the token.
            # There is no harm in placing the token in multiple lists, as
            # _list_tokens is smart enough to handle almost any case of
            # valid/invalid/expired for a given token.
            token_data = data_copy['token_data']
            if data_copy['token_version'] == token.provider.V2:
                trustee_user_id = token_data['access']['trust'][
                    'trustee_user_id']
            elif data_copy['token_version'] == token.provider.V3:
                trustee_user_id = token_data['OS-TRUST:trust'][
                    'trustee_user_id']
            else:
                raise exception.UnsupportedTokenVersionException(
                    _('Unknown token version %s') %
                    data_copy.get('token_version'))

            trustee_key = self._prefix_user_id(trustee_user_id)
            self._update_user_token_list(trustee_key, token_id, expires_str)

        return data_copy
示例#39
0
文件: api.py 项目: gerryw/heat
def format_event(event):
    stack_identifier = event.stack.identifier()

    result = {
        rpc_api.EVENT_ID: dict(event.identifier()),
        rpc_api.EVENT_STACK_ID: dict(stack_identifier),
        rpc_api.EVENT_STACK_NAME: stack_identifier.stack_name,
        rpc_api.EVENT_TIMESTAMP: timeutils.isotime(event.timestamp),
        rpc_api.EVENT_RES_NAME: event.resource_name,
        rpc_api.EVENT_RES_PHYSICAL_ID: event.physical_resource_id,
        rpc_api.EVENT_RES_ACTION: event.action,
        rpc_api.EVENT_RES_STATUS: event.status,
        rpc_api.EVENT_RES_STATUS_DATA: event.reason,
        rpc_api.EVENT_RES_TYPE: event.resource_type,
        rpc_api.EVENT_RES_PROPERTIES: event.resource_properties,
    }

    return result
示例#40
0
 def save_authorization_code(self, client_id, code, request, *args, **kwargs):
     # Remember to associate it with request.scopes, request.redirect_uri
     # request.client, request.state and request.user (the last is passed in
     # post_authorization credentials, i.e. { 'user': request.user}.
     authorization_code = {
         'code': code['code'], # code is a dict with state and the code
         'consumer_id': client_id,
         'scopes': request.scopes,
         'authorizing_user_id': request.user_id, # populated through the credentials
         'state': request.state,
         'redirect_uri': request.redirect_uri
     }
     token_duration = 28800 # TODO(garcianavalon) extract as configuration option
     # TODO(garcianavalon) find a better place to do this
     now = timeutils.utcnow()
     future = now + datetime.timedelta(seconds=token_duration)
     expiry_date = timeutils.isotime(future, subsecond=True)
     authorization_code['expires_at'] = expiry_date
     self.oauth2_api.store_authorization_code(authorization_code)
 def test_trusted_filter_untrusted_and_trusted_fails(self, req_mock):
     oat_data = {
         "hosts": [{
             "host_name": "node",
             "trust_lvl": "trusted",
             "vtime": timeutils.isotime()
         }]
     }
     req_mock.return_value = requests.codes.OK, oat_data
     extra_specs = {'trust:trusted_host': 'untrusted'}
     filter_properties = {
         'context': mock.sentinel.ctx,
         'instance_type': {
             'memory_mb': 1024,
             'extra_specs': extra_specs
         }
     }
     host = fakes.FakeHostState('host1', 'node1', {})
     self.assertFalse(self.filt_cls.host_passes(host, filter_properties))
示例#42
0
def make_sample_from_pool(pool,
                          name,
                          type,
                          unit,
                          volume,
                          resource_metadata=None):
    resource_metadata = resource_metadata or {}

    return sample.Sample(
        name=name,
        type=type,
        unit=unit,
        volume=volume,
        user_id=None,
        project_id=pool['tenant_id'],
        resource_id=pool['id'],
        timestamp=timeutils.isotime(),
        resource_metadata=resource_metadata,
    )
示例#43
0
文件: api.py 项目: gerryw/heat
def format_notification_body(stack):
    # some other possibilities here are:
    # - template name
    # - template size
    # - resource count
    if stack.status is not None and stack.action is not None:
        state = '_'.join(stack.state)
    else:
        state = 'Unknown'
    result = {
        rpc_api.NOTIFY_TENANT_ID: stack.context.tenant_id,
        rpc_api.NOTIFY_USER_ID: stack.context.user,
        rpc_api.NOTIFY_STACK_ID: stack.identifier().arn(),
        rpc_api.NOTIFY_STACK_NAME: stack.name,
        rpc_api.NOTIFY_STATE: state,
        rpc_api.NOTIFY_STATE_REASON: stack.status_reason,
        rpc_api.NOTIFY_CREATE_AT: timeutils.isotime(stack.created_time),
    }
    return result
示例#44
0
    def create(self,
               trustee_user,
               trustor_user,
               role_names=None,
               project=None,
               impersonation=False,
               expires_at=None,
               remaining_uses=None,
               **kwargs):
        """Create a Trust.

        :param string trustee_user: user who is capable of consuming the trust
        :param string trustor_user: user who's authorization is being delegated
        :param string role_names: subset of trustor's roles to be granted
        :param string project: project which the trustor is delegating
        :param boolean impersonation: enable explicit impersonation
        :param datetime.datetime expires_at: expiry time
        :param integer remaining_uses: how many times this trust can be used
                                       to generate a token. None means
                                       unlimited tokens.

        """
        # Convert role_names list into list-of-dict API format
        if role_names:
            roles = [{'name': n} for n in role_names]
        else:
            roles = None

        # Convert datetime.datetime expires_at to iso format string
        if expires_at:
            expires_str = timeutils.isotime(at=expires_at, subsecond=True)
        else:
            expires_str = None

        return super(TrustManager,
                     self).create(expires_at=expires_str,
                                  impersonation=impersonation,
                                  project_id=base.getid(project),
                                  remaining_uses=remaining_uses,
                                  roles=roles,
                                  trustee_user_id=base.getid(trustee_user),
                                  trustor_user_id=base.getid(trustor_user),
                                  **kwargs)
示例#45
0
    def test_view_builder_show(self):
        view_builder = views_types.ViewBuilder()

        now = timeutils.isotime()
        raw_volume_type = dict(name='new_type',
                               deleted=False,
                               created_at=now,
                               updated_at=now,
                               extra_specs={},
                               deleted_at=None,
                               id=42)

        request = fakes.HTTPRequest.blank("/v1")
        output = view_builder.show(request, raw_volume_type)

        self.assertIn('volume_type', output)
        expected_volume_type = dict(name='new_type',
                                    extra_specs={},
                                    id=42)
        self.assertDictMatch(output['volume_type'], expected_volume_type)
示例#46
0
    def create_autoscaling_stack_and_get_group(self):

        env = environment.Environment()
        env.load({u'parameters': {u'KeyName': 'foo', 'ImageId': 'cloudimage'}})
        t = template_format.parse(as_template)
        template = parser.Template(t)
        self.stack_name = utils.random_name()
        stack = parser.Stack(self.ctx,
                             self.stack_name,
                             template,
                             env=env,
                             disable_rollback=True)
        stack.store()
        self.created_time = stack.created_time
        self.create_at = timeutils.isotime(self.created_time)
        stack.create()
        self.stack = stack
        group = stack['WebServerGroup']
        self.assertEqual((group.CREATE, group.COMPLETE), group.state)
        return group
示例#47
0
文件: api.py 项目: gerryw/heat
def format_stack_resource(resource,
                          detail=True,
                          with_props=False,
                          with_attr=None):
    '''
    Return a representation of the given resource that matches the API output
    expectations.
    '''
    last_updated_time = resource.updated_time or resource.created_time
    res = {
        rpc_api.RES_UPDATED_TIME: timeutils.isotime(last_updated_time),
        rpc_api.RES_NAME: resource.name,
        rpc_api.RES_PHYSICAL_ID: resource.resource_id or '',
        rpc_api.RES_ACTION: resource.action,
        rpc_api.RES_STATUS: resource.status,
        rpc_api.RES_STATUS_DATA: resource.status_reason,
        rpc_api.RES_TYPE: resource.type(),
        rpc_api.RES_ID: dict(resource.identifier()),
        rpc_api.RES_STACK_ID: dict(resource.stack.identifier()),
        rpc_api.RES_STACK_NAME: resource.stack.name,
        rpc_api.RES_REQUIRED_BY: resource.required_by(),
    }

    if (hasattr(resource, 'nested') and callable(resource.nested)
            and resource.nested()):
        res[rpc_api.RES_NESTED_STACK_ID] = dict(resource.nested().identifier())

    if resource.stack.parent_resource:
        res[rpc_api.RES_PARENT_RESOURCE] = resource.stack.parent_resource.name

    if detail:
        res[rpc_api.RES_DESCRIPTION] = resource.t.description
        res[rpc_api.RES_METADATA] = resource.metadata_get()
        res[rpc_api.RES_SCHEMA_ATTRIBUTES] = format_resource_attributes(
            resource, with_attr)

    if with_props:
        res[rpc_api.RES_SCHEMA_PROPERTIES] = format_resource_properties(
            resource)

    return res
示例#48
0
def make_sample_from_host(host,
                          name,
                          type,
                          unit,
                          volume,
                          resource_id=None,
                          additional_metadata=None):
    additional_metadata = additional_metadata or {}
    resource_metadata = {}
    resource_metadata.update(additional_metadata)
    return sample.Sample(
        name=name,
        type=type,
        unit=unit,
        volume=volume,
        user_id=None,
        project_id=None,
        resource_id=host,
        timestamp=timeutils.isotime(),
        resource_metadata=resource_metadata,
    )
示例#49
0
def make_sample_from_instance(instance,
                              name,
                              type,
                              unit,
                              volume,
                              resource_id=None,
                              additional_metadata=None):
    additional_metadata = additional_metadata or {}
    resource_metadata = _get_metadata_from_object(instance)
    resource_metadata.update(additional_metadata)
    return sample.Sample(
        name=name,
        type=type,
        unit=unit,
        volume=volume,
        user_id=instance.user_id,
        project_id=instance.tenant_id,
        resource_id=resource_id or instance.id,
        timestamp=timeutils.isotime(),
        resource_metadata=resource_metadata,
    )
示例#50
0
def make_sample_from_host(host_url, name, sample_type, unit, volume,
                          project_id=None, user_id=None, resource_id=None,
                          res_metadata=None, extra=None):

    extra = extra or {}
    resource_metadata = make_resource_metadata(res_metadata, host_url)
    resource_metadata.update(extra)

    res_id = resource_id or extra.get('resource_id') or host_url.hostname
    return sample.Sample(
        name='hardware.' + name,
        type=sample_type,
        unit=unit,
        volume=volume,
        user_id=user_id or extra.get('user_id'),
        project_id=project_id or extra.get('project_id'),
        resource_id=res_id,
        timestamp=timeutils.isotime(),
        resource_metadata=resource_metadata,
        source='hardware',
    )
示例#51
0
文件: net.py 项目: nsaje/ceilometer
    def make_vnic_sample(instance, name, type, unit, volume, vnic_data):
        metadata = copy.copy(vnic_data)
        resource_metadata = dict(zip(metadata._fields, metadata))
        resource_metadata['instance_id'] = instance.id
        resource_metadata['instance_type'] = (instance.flavor['id']
                                              if instance.flavor else None)

        if vnic_data.fref is not None:
            rid = vnic_data.fref
        else:
            instance_name = util.instance_name(instance)
            rid = "%s-%s-%s" % (instance_name, instance.id, vnic_data.name)

        return sample.Sample(name=name,
                             type=type,
                             unit=unit,
                             volume=volume,
                             user_id=instance.user_id,
                             project_id=instance.tenant_id,
                             resource_id=rid,
                             timestamp=timeutils.isotime(),
                             resource_metadata=resource_metadata)
示例#52
0
文件: api.py 项目: gerryw/heat
def format_watch_data(wd):

    # Demangle DB format data into something more easily used in the API
    # We are expecting a dict with exactly two items, Namespace and
    # a metric key
    namespace = wd.data['Namespace']
    metric = [(k, v) for k, v in wd.data.items() if k != 'Namespace']
    if len(metric) == 1:
        metric_name, metric_data = metric[0]
    else:
        LOG.error(_LE("Unexpected number of keys in watch_data.data!"))
        return

    result = {
        rpc_api.WATCH_DATA_ALARM: wd.watch_rule.name,
        rpc_api.WATCH_DATA_METRIC: metric_name,
        rpc_api.WATCH_DATA_TIME: timeutils.isotime(wd.created_at),
        rpc_api.WATCH_DATA_NAMESPACE: namespace,
        rpc_api.WATCH_DATA: metric_data
    }

    return result
示例#53
0
    def _get_fault(self, request, instance):
        # This can result in a lazy load of the fault information
        fault = instance.fault

        if not fault:
            return None

        fault_dict = {
            "code": fault["code"],
            "created": timeutils.isotime(fault["created_at"]),
            "message": fault["message"],
        }

        if fault.get('details', None):
            is_admin = False
            context = request.environ["nova.context"]
            if context:
                is_admin = getattr(context, 'is_admin', False)

            if is_admin or fault['code'] != 500:
                fault_dict['details'] = fault["details"]

        return fault_dict
示例#54
0
 def test_index_serializer(self):
     serializer = cloudpipe_v2.CloudpipesTemplate()
     exemplar = dict(cloudpipes=[
         dict(project_id='1234',
              public_ip='1.2.3.4',
              public_port='321',
              instance_id='1234-1234-1234-1234',
              created_at=timeutils.isotime(),
              state='running'),
         dict(project_id='4321',
              public_ip='4.3.2.1',
              public_port='123',
              state='pending')
     ])
     text = serializer.serialize(exemplar)
     tree = etree.fromstring(text)
     self.assertEqual('cloudpipes', tree.tag)
     self.assertEqual(len(exemplar['cloudpipes']), len(tree))
     for idx, cl_pipe in enumerate(tree):
         kp_data = exemplar['cloudpipes'][idx]
         for child in cl_pipe:
             self.assertIn(child.tag, kp_data)
             self.assertEqual(child.text, kp_data[child.tag])
示例#55
0
    def first(self, queue, project=None, sort=1):
        if project is None:
            project = ''

        qid = utils.get_qid(self.driver, queue, project)

        sel = sa.sql.select([
            tables.Messages.c.id, tables.Messages.c.body,
            tables.Messages.c.ttl, tables.Messages.c.created
        ],
                            sa.and_(
                                tables.Messages.c.ttl >
                                sfunc.now() - tables.Messages.c.created,
                                tables.Messages.c.qid == qid))
        if sort not in (1, -1):
            raise ValueError(u'sort must be either 1 (ascending) '
                             u'or -1 (descending)')

        order = sa.asc
        if sort == -1:
            order = sa.desc

        sel = sel.order_by(order(tables.Messages.c.id))

        try:
            id, body, ttl, created = self.driver.get(sel)
        except utils.NoResult:
            raise errors.QueueIsEmpty(queue, project)

        created_iso = timeutils.isotime(created)
        return {
            'id': utils.msgid_encode(int(id)),
            'ttl': ttl,
            'created': created_iso,
            'age': int((timeutils.utcnow() - created).seconds),
            'body': body,
        }
示例#56
0
    def create_access_token(self,
                            request_token_id,
                            token_duration,
                            access_token_id=None,
                            access_token_secret=None):
        if access_token_id is None:
            access_token_id = uuid.uuid4().hex
        if access_token_secret is None:
            access_token_secret = uuid.uuid4().hex
        session = sql.get_session()
        with session.begin():
            req_token_ref = self._get_request_token(session, request_token_id)
            token_dict = req_token_ref.to_dict()

            expiry_date = None
            if token_duration:
                now = timeutils.utcnow()
                future = now + datetime.timedelta(seconds=token_duration)
                expiry_date = timeutils.isotime(future, subsecond=True)

            # add Access Token
            ref = {}
            ref['id'] = access_token_id
            ref['access_secret'] = access_token_secret
            ref['authorizing_user_id'] = token_dict['authorizing_user_id']
            ref['project_id'] = token_dict['requested_project_id']
            ref['role_ids'] = token_dict['role_ids']
            ref['consumer_id'] = token_dict['consumer_id']
            ref['expires_at'] = expiry_date
            token_ref = AccessToken.from_dict(ref)
            session.add(token_ref)

            # remove request token, it's been used
            session.delete(req_token_ref)

        return token_ref.to_dict()
示例#57
0
    def test_view_builder_list(self):
        view_builder = views_types.ViewBuilder()

        now = timeutils.isotime()
        raw_volume_types = []
        for i in range(0, 10):
            raw_volume_types.append(dict(name='new_type',
                                         deleted=False,
                                         created_at=now,
                                         updated_at=now,
                                         extra_specs={},
                                         deleted_at=None,
                                         id=42 + i))

        request = fakes.HTTPRequest.blank("/v1")
        output = view_builder.index(request, raw_volume_types)

        self.assertIn('volume_types', output)
        for i in range(0, 10):
            expected_volume_type = dict(name='new_type',
                                        extra_specs={},
                                        id=42 + i)
            self.assertDictMatch(output['volume_types'][i],
                                 expected_volume_type)
示例#58
0
    def _create_authn_statement(self, issuer, expiration_time):
        """Create an object that represents a SAML AuthnStatement.

        <ns0:AuthnStatement xmlns:ns0="urn:oasis:names:tc:SAML:2.0:assertion"
          AuthnInstant="2014-07-30T03:04:25Z" SessionIndex="47335964efb"
          SessionNotOnOrAfter="2014-07-30T03:04:26Z">
            <ns0:AuthnContext>
                <ns0:AuthnContextClassRef>
                  urn:oasis:names:tc:SAML:2.0:ac:classes:Password
                </ns0:AuthnContextClassRef>
                <ns0:AuthenticatingAuthority>
                  https://acme.com/FIM/sps/openstack/saml20
                </ns0:AuthenticatingAuthority>
            </ns0:AuthnContext>
        </ns0:AuthnStatement>

        :return: XML <AuthnStatement> object

        """
        authn_statement = saml.AuthnStatement()
        authn_statement.authn_instant = timeutils.isotime()
        authn_statement.session_index = uuid.uuid4().hex
        authn_statement.session_not_on_or_after = expiration_time

        authn_context = saml.AuthnContext()
        authn_context_class = saml.AuthnContextClassRef()
        authn_context_class.set_text(saml.AUTHN_PASSWORD)

        authn_authority = saml.AuthenticatingAuthority()
        authn_authority.set_text(issuer)
        authn_context.authn_context_class_ref = authn_context_class
        authn_context.authenticating_authority = authn_authority

        authn_statement.authn_context = authn_context

        return authn_statement
示例#59
0
    def _fill_in_roles(self, context, trust, all_roles):
        if trust.get('expires_at') is not None:
            trust['expires_at'] = (timeutils.isotime(trust['expires_at'],
                                                     subsecond=True))

        if 'roles' not in trust:
            trust['roles'] = []
        trust_full_roles = []
        for trust_role in trust['roles']:
            if isinstance(trust_role, six.string_types):
                trust_role = {'id': trust_role}
            matching_roles = [
                x for x in all_roles if x['id'] == trust_role['id']
            ]
            if matching_roles:
                full_role = assignment.controllers.RoleV3.wrap_member(
                    context, matching_roles[0])['role']
                trust_full_roles.append(full_role)
        trust['roles'] = trust_full_roles
        trust['roles_links'] = {
            'self': (self.base_url(context) + "/%s/roles" % trust['id']),
            'next': None,
            'previous': None
        }
示例#60
0
 def _vpn_dict(self, context, project_id, instance):
     elevated = context.elevated()
     rv = {'project_id': project_id}
     if not instance:
         rv['state'] = 'pending'
         return rv
     rv['instance_id'] = instance['uuid']
     rv['created_at'] = timeutils.isotime(instance['created_at'])
     nw_info = compute_utils.get_nw_info_for_instance(instance)
     if not nw_info:
         return rv
     vif = nw_info[0]
     ips = [ip for ip in vif.fixed_ips() if ip['version'] == 4]
     if ips:
         rv['internal_ip'] = ips[0]['address']
     # NOTE(vish): Currently network_api.get does an owner check on
     #             project_id. This is probably no longer necessary
     #             but rather than risk changes in the db layer,
     #             we are working around it here by changing the
     #             project_id in the context. This can be removed
     #             if we remove the project_id check in the db.
     elevated.project_id = project_id
     network = self.network_api.get(elevated, vif['network']['id'])
     if network:
         vpn_ip = network['vpn_public_address']
         vpn_port = network['vpn_public_port']
         rv['public_ip'] = vpn_ip
         rv['public_port'] = vpn_port
         if vpn_ip and vpn_port:
             if utils.vpn_ping(vpn_ip, vpn_port):
                 rv['state'] = 'running'
             else:
                 rv['state'] = 'down'
         else:
             rv['state'] = 'invalid'
     return rv