Exemplo n.º 1
0
 def assertServerUsage(self, server, launched_at, terminated_at):
     resp_launched_at = timeutils.parse_isotime(
         server.get('%slaunched_at' % self.prefix))
     self.assertEqual(timeutils.normalize_time(resp_launched_at),
                      launched_at)
     resp_terminated_at = timeutils.parse_isotime(
         server.get('%sterminated_at' % self.prefix))
     self.assertEqual(timeutils.normalize_time(resp_terminated_at),
                      terminated_at)
Exemplo n.º 2
0
 def assertServerUsage(self, server, launched_at, terminated_at):
     resp_launched_at = timeutils.parse_isotime(
         server.get('%slaunched_at' % self.prefix))
     self.assertEqual(timeutils.normalize_time(resp_launched_at),
                      launched_at)
     resp_terminated_at = timeutils.parse_isotime(
         server.get('%sterminated_at' % self.prefix))
     self.assertEqual(timeutils.normalize_time(resp_terminated_at),
                      terminated_at)
Exemplo n.º 3
0
 def test_destroy_stubbed(self):
     self.mox.StubOutWithMock(db, 'instance_destroy')
     deleted_at = datetime.datetime(1955, 11, 6)
     fake_inst = fake_instance.fake_db_instance(deleted_at=deleted_at,
                                                deleted=True)
     db.instance_destroy(self.context, 'fake-uuid',
                         constraint=None).AndReturn(fake_inst)
     self.mox.ReplayAll()
     inst = instance.Instance(id=1, uuid='fake-uuid', host='foo')
     inst.destroy(self.context)
     self.assertEqual(timeutils.normalize_time(inst.deleted_at),
                      timeutils.normalize_time(deleted_at))
     self.assertTrue(inst.deleted)
Exemplo n.º 4
0
 def test_destroy_stubbed(self):
     self.mox.StubOutWithMock(db, 'instance_destroy')
     deleted_at = datetime.datetime(1955, 11, 6)
     fake_inst = fake_instance.fake_db_instance(deleted_at=deleted_at,
                                                deleted=True)
     db.instance_destroy(self.context, 'fake-uuid',
                         constraint=None).AndReturn(fake_inst)
     self.mox.ReplayAll()
     inst = instance.Instance(id=1, uuid='fake-uuid', host='foo')
     inst.destroy(self.context)
     self.assertEqual(timeutils.normalize_time(inst.deleted_at),
                      timeutils.normalize_time(deleted_at))
     self.assertTrue(inst.deleted)
Exemplo n.º 5
0
 def _init_cache_entry(self, host):
     self.compute_nodes[host] = {
         'trust_lvl': 'unknown',
         'vtime': timeutils.normalize_time(
             timeutils.parse_isotime("1970-01-01T00:00:00Z")
         )
     }
Exemplo n.º 6
0
    def test_trusted_filter_update_cache_timezone(self, req_mock):
        oat_data = {"hosts": [{"host_name": "node1",
                                    "trust_lvl": "untrusted",
                                    "vtime": "2012-09-09T05:10:40-04:00"}]}
        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', {})

        timeutils.set_time_override(
            timeutils.normalize_time(
                timeutils.parse_isotime("2012-09-09T09:10:40Z")))

        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.advance_time_seconds(
            CONF.trusted_computing.attestation_auth_timeout - 10)
        self.filt_cls.host_passes(host, filter_properties)
        self.assertFalse(req_mock.called)

        timeutils.clear_time_override()
Exemplo n.º 7
0
 def _init_cache_entry(self, host):
     self.compute_nodes[host] = {
         'trust_lvl': 'unknown',
         'vtime': timeutils.normalize_time(
             timeutils.parse_isotime("1970-01-01T00:00:00Z")
         )
     }
Exemplo n.º 8
0
    def _update_cache_entry(self, state):
        entry = {}

        host = state['host_name']
        entry['trust_lvl'] = state['trust_lvl']

        try:
            # Normalize as naive object to interoperate with utcnow().
            entry['vtime'] = timeutils.normalize_time(
                            timeutils.parse_isotime(state['vtime']))
        except ValueError:
            try:
                # Mt. Wilson does not necessarily return an ISO8601 formatted
                # `vtime`, so we should try to parse it as a string formatted
                # datetime.
                vtime = timeutils.parse_strtime(state['vtime'], fmt="%c")
                entry['vtime'] = timeutils.normalize_time(vtime)
            except ValueError:
                # Mark the system as un-trusted if get invalid vtime.
                entry['trust_lvl'] = 'unknown'
                entry['vtime'] = timeutils.utcnow()

        self.compute_nodes[host] = entry
Exemplo n.º 9
0
    def _update_cache_entry(self, state):
        entry = {}

        host = state['host_name']
        entry['trust_lvl'] = state['trust_lvl']

        try:
            # Normalize as naive object to interoperate with utcnow().
            entry['vtime'] = timeutils.normalize_time(
                            timeutils.parse_isotime(state['vtime']))
        except ValueError:
            # Mark the system as un-trusted if get invalid vtime.
            entry['trust_lvl'] = 'unknown'
            entry['vtime'] = timeutils.utcnow()

        self.compute_nodes[host] = entry
Exemplo n.º 10
0
    def _update_cache_entry(self, state):
        entry = {}

        host = state['host_name']
        entry['trust_lvl'] = state['trust_lvl']

        try:
            # Normalize as naive object to interoperate with utcnow().
            entry['vtime'] = timeutils.normalize_time(
                timeutils.parse_isotime(state['vtime']))
        except ValueError:
            # Mark the system as un-trusted if get invalid vtime.
            entry['trust_lvl'] = 'unknown'
            entry['vtime'] = timeutils.utcnow()

        self.compute_nodes[host] = entry
Exemplo n.º 11
0
 def _request_admin_token(self):
         """Retrieve new token as admin user from keystone.
 
         :return token id upon success
         :raises ServerError when unable to communicate with keystone
 
         Irrespective of the auth version we are going to use for the
         user token, for simplicity we always use a v2 admin token to
         validate the user token.
 
         """
         params = {
         'auth': {
             'passwordCredentials': {
                 'username': self.admin_user,
                 'password': self.admin_password,
                 },
             'tenantName': self.admin_tenant_name,
             }
         }
 
         response, data = self._json_request(self.keystone_auth_host,
                         self.keystone_auth_port,
                         'POST',
                                             '/v2.0/tokens',
                                             body=params)
         try:
             token = data['access']['token']['id']
             expiry = data['access']['token']['expires']
             assert token
             assert expiry
             datetime_expiry = timeutils.parse_isotime(expiry)
             return (token, timeutils.normalize_time(datetime_expiry))
         except (AssertionError, KeyError):
             self.LOG.warn(
                 "Unexpected response from keystone service: %s", data)
             raise ServiceError('invalid json response')
         except (ValueError):
             self.LOG.warn(
                 "Unable to parse expiration time from token: %s", data)
             raise ServiceError('invalid json response')
Exemplo n.º 12
0
    def test_trusted_filter_update_cache_timezone(self, req_mock):
        oat_data = {
            "hosts": [{
                "host_name": "node1",
                "trust_lvl": "untrusted",
                "vtime": "2012-09-09T05:10:40-04:00"
            }]
        }
        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', {})

        timeutils.set_time_override(
            timeutils.normalize_time(
                timeutils.parse_isotime("2012-09-09T09:10:40Z")))

        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.advance_time_seconds(
            CONF.trusted_computing.attestation_auth_timeout - 10)
        self.filt_cls.host_passes(host, filter_properties)
        self.assertFalse(req_mock.called)

        timeutils.clear_time_override()
Exemplo n.º 13
0
    def _tenant_usages_for_period(self, context, period_start,
                                  period_stop, tenant_id=None, detailed=True):

        instances = objects.InstanceList.get_active_by_window_joined(
                        context, period_start, period_stop, tenant_id,
                        expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS)
        rval = {}
        flavors = {}

        for instance in instances:
            info = {}
            info['hours'] = self._hours_for(instance,
                                            period_start,
                                            period_stop)
            flavor = self._get_flavor(context, instance, flavors)
            if not flavor:
                info['flavor'] = ''
            else:
                info['flavor'] = flavor.name

            info['instance_id'] = instance.uuid
            info['name'] = instance.display_name

            info['memory_mb'] = instance.memory_mb
            info['local_gb'] = instance.root_gb + instance.ephemeral_gb
            info['vcpus'] = instance.vcpus

            info['tenant_id'] = instance.project_id

            # NOTE(mriedem): We need to normalize the start/end times back
            # to timezone-naive so the response doesn't change after the
            # conversion to objects.
            info['started_at'] = timeutils.normalize_time(instance.launched_at)

            info['ended_at'] = (
                timeutils.normalize_time(instance.terminated_at) if
                    instance.terminated_at else None)

            if info['ended_at']:
                info['state'] = 'terminated'
            else:
                info['state'] = instance.vm_state

            now = timeutils.utcnow()

            if info['state'] == 'terminated':
                delta = info['ended_at'] - info['started_at']
            else:
                delta = now - info['started_at']

            info['uptime'] = delta.days * 24 * 3600 + delta.seconds

            if info['tenant_id'] not in rval:
                summary = {}
                summary['tenant_id'] = info['tenant_id']
                if detailed:
                    summary['server_usages'] = []
                summary['total_local_gb_usage'] = 0
                summary['total_vcpus_usage'] = 0
                summary['total_memory_mb_usage'] = 0
                summary['total_hours'] = 0
                summary['start'] = timeutils.normalize_time(period_start)
                summary['stop'] = timeutils.normalize_time(period_stop)
                rval[info['tenant_id']] = summary

            summary = rval[info['tenant_id']]
            summary['total_local_gb_usage'] += info['local_gb'] * info['hours']
            summary['total_vcpus_usage'] += info['vcpus'] * info['hours']
            summary['total_memory_mb_usage'] += (info['memory_mb'] *
                                                 info['hours'])

            summary['total_hours'] += info['hours']
            if detailed:
                summary['server_usages'].append(info)

        return rval.values()