Example #1
0
    def strato_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 "",
                "image": self._get_image(request, instance),
                "flavor": self._strato_get_flavor(request, instance),
                "created": timeutils.isotime(instance["created_at"]),
                "updated": timeutils.isotime(instance["updated_at"]),
                "OS-EXT-SRV-ATTR:host": instance["host"],
                "OS-EXT-SRV-ATTR:instance_name": instance["name"],
                "OS-EXT-SRV-ATTR:hypervisor_hostname": instance["node"],
                "links": self._get_links(request,
                                         instance["uuid"],
                                         self._collection_name),
            },
        }
        if server["server"]["status"] in self._progress_statuses:
            server["server"]["progress"] = instance.get("progress", 0)

        return server
Example #2
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),
                "host_id": 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),
                "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)

        # We should modify the "image" to empty dictionary
        if not server["server"]["image"]:
            server["server"]["image"] = {}
        return server
Example #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
Example #4
0
    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)
Example #5
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_state(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),
            },
        }
        _inst_fault = self._get_fault(request, instance)
        if server["server"]["status"] in self._fault_statuses and _inst_fault:
            server['server']['fault'] = _inst_fault

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

        return server
Example #6
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)]
Example #7
0
 def test_index_serializer(self):
     serializer = cloudpipe.CloudpipesTemplate()
     exemplar = dict(cloudpipes=[
             dict(cloudpipe=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(cloudpipe=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):
         self.assertEqual('cloudpipe', cl_pipe.tag)
         kp_data = exemplar['cloudpipes'][idx]['cloudpipe']
         for child in cl_pipe:
             self.assertTrue(child.tag in kp_data)
             self.assertEqual(child.text, kp_data[child.tag])
Example #8
0
 def test_datetime_or_none(self):
     naive_dt = datetime.datetime.now()
     dt = timeutils.parse_isotime(timeutils.isotime(naive_dt))
     self.assertEqual(utils.datetime_or_none(dt), dt)
     self.assertEqual(utils.datetime_or_none(dt), naive_dt.replace(tzinfo=iso8601.iso8601.Utc(), microsecond=0))
     self.assertEqual(utils.datetime_or_none(None), None)
     self.assertRaises(ValueError, utils.datetime_or_none, "foo")
Example #9
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)
Example #10
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.assertEqual(utils.datetime_or_str_or_none(None), None)
     self.assertEqual(utils.datetime_or_str_or_none(dts), dt)
     self.assertRaises(ValueError, utils.datetime_or_str_or_none, 'foo')
Example #11
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()
Example #12
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)
    def test_validate_ec2_req_timestamp_Expires(self):

        #EC2 request with both Timestamp and Expires
        params = {'Timestamp': '2011-04-22T11:29:49Z',
                  'Expires': timeutils.isotime()}
        self.assertRaises(exception.InvalidRequest,
                          ec2utils.is_ec2_timestamp_expired,
                          params)
Example #14
0
 def _build_rate_limit(self, rate_limit):
     _get_utc = datetime.datetime.utcfromtimestamp
     next_avail = _get_utc(rate_limit["resetTime"])
     return {
         "verb": rate_limit["verb"],
         "value": rate_limit["value"],
         "remaining": int(rate_limit["remaining"]),
         "unit": rate_limit["unit"],
         "next-available": timeutils.isotime(at=next_avail),
     }
Example #15
0
 def test_get_hung_in_rebooting(self):
     fakes = [self.fake_instance(1), self.fake_instance(2)]
     dt = timeutils.isotime()
     self.mox.StubOutWithMock(db, "instance_get_all_hung_in_rebooting")
     db.instance_get_all_hung_in_rebooting(self.context, dt).AndReturn(fakes)
     self.mox.ReplayAll()
     inst_list = instance.InstanceList.get_hung_in_rebooting(self.context, dt)
     for i in range(0, len(fakes)):
         self.assertIsInstance(inst_list.objects[i], instance.Instance)
         self.assertEqual(inst_list.objects[i].uuid, fakes[i]["uuid"])
     self.assertRemotes()
Example #16
0
 def test_trusted_filter_untrusted_and_untrusted_passes(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.assertTrue(self.filt_cls.host_passes(host, filter_properties))
Example #17
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_state(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": instance.get("access_ip_v4") or "",
                "accessIPv6": instance.get("access_ip_v6") or "",
                "links": self._get_links(request,
                                         instance["uuid"],
                                         self._collection_name),
            },
        }

        if FLAGS.use_network_qos:
            (network_qos_pub, network_qos_pvt) = get_network_qos(
                                                                request,
                                                                instance)
            server['server']['network_qos_public'] = network_qos_pub
            server['server']['network_qos_private'] = network_qos_pvt

        _inst_fault = self._get_fault(request, instance)
        if server["server"]["status"] in self._fault_statuses and _inst_fault:
            server['server']['fault'] = _inst_fault

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

        return server
Example #18
0
 def wrapper(obj, *args, **kwargs):
     for kw in kwargs:
         value_arg = kwargs.get(kw)
         if kw == 'exc_val' and value_arg:
             kwargs[kw] = str(value_arg)
         elif kw == 'exc_tb' and (
                 not isinstance(value_arg, six.string_types) and value_arg):
             kwargs[kw] = ''.join(traceback.format_tb(value_arg))
         elif isinstance(value_arg, datetime.datetime):
             kwargs[kw] = timeutils.isotime(value_arg)
     if hasattr(fn, '__call__'):
         return fn(obj, *args, **kwargs)
     # NOTE(danms): We wrap a descriptor, so use that protocol
     return fn.__get__(None, obj)(*args, **kwargs)
Example #19
0
 def test_disassociate_all_by_timeout(self, disassociate):
     now = timeutils.utcnow()
     now_tz = timeutils.parse_isotime(
         timeutils.isotime(now)).replace(
             tzinfo=iso8601.iso8601.Utc())
     disassociate.return_value = 123
     result = fixed_ip.FixedIP.disassociate_all_by_timeout(self.context,
                                                           'host', now)
     self.assertEqual(123, result)
     # NOTE(danms): be pedantic about timezone stuff
     args, kwargs = disassociate.call_args_list[0]
     self.assertEqual(now_tz, args[2])
     self.assertEqual((self.context, 'host'), args[:2])
     self.assertEqual({}, kwargs)
Example #20
0
 def test_get_hung_in_rebooting(self):
     fakes = [self.fake_instance(1),
              self.fake_instance(2)]
     dt = timeutils.isotime()
     self.mox.StubOutWithMock(db, 'instance_get_all_hung_in_rebooting')
     db.instance_get_all_hung_in_rebooting(self.context, dt).AndReturn(
         fakes)
     self.mox.ReplayAll()
     inst_list = instance.InstanceList.get_hung_in_rebooting(self.context,
                                                             dt)
     for i in range(0, len(fakes)):
         self.assertIsInstance(inst_list.objects[i], instance.Instance)
         self.assertEqual(inst_list.objects[i].uuid, fakes[i]['uuid'])
     self.assertRemotes()
Example #21
0
File: base.py Project: gilmeir/nova
 def wrapper(obj, *args, **kwargs):
     for kw in kwargs:
         value_arg = kwargs.get(kw)
         if kw == 'exc_val' and value_arg:
             kwargs[kw] = str(value_arg)
         elif kw == 'exc_tb' and (
                 not isinstance(value_arg, six.string_types) and value_arg):
             kwargs[kw] = ''.join(traceback.format_tb(value_arg))
         elif isinstance(value_arg, datetime.datetime):
             kwargs[kw] = timeutils.isotime(value_arg)
     if hasattr(fn, '__call__'):
         return fn(obj, *args, **kwargs)
     # NOTE(danms): We wrap a descriptor, so use that protocol
     return fn.__get__(None, obj)(*args, **kwargs)
 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)
Example #23
0
    def strato_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 "",
                "image":
                self._get_image(request, instance),
                "flavor":
                self._strato_get_flavor(request, instance),
                "created":
                timeutils.isotime(instance["created_at"]),
                "updated":
                timeutils.isotime(instance["updated_at"]),
                "OS-EXT-SRV-ATTR:host":
                instance["host"],
                "OS-EXT-SRV-ATTR:instance_name":
                instance["name"],
                "OS-EXT-SRV-ATTR:hypervisor_hostname":
                instance["node"],
                "links":
                self._get_links(request, instance["uuid"],
                                self._collection_name),
            },
        }
        if server["server"]["status"] in self._progress_statuses:
            server["server"]["progress"] = instance.get("progress", 0)

        return server
Example #24
0
 def test_datetime_deserialization(self):
     red_letter_date = timeutils.parse_isotime(timeutils.isotime(datetime.datetime(1955, 11, 5)))
     inst = instance.Instance(uuid="fake-uuid", launched_at=red_letter_date)
     primitive = inst.obj_to_primitive()
     expected = {
         "nova_object.name": "Instance",
         "nova_object.namespace": "nova",
         "nova_object.version": "1.10",
         "nova_object.data": {"uuid": "fake-uuid", "launched_at": "1955-11-05T00:00:00Z"},
         "nova_object.changes": ["launched_at", "uuid"],
     }
     self.assertEqual(primitive, expected)
     inst2 = instance.Instance.obj_from_primitive(primitive)
     self.assertIsInstance(inst2.launched_at, datetime.datetime)
     self.assertEqual(inst2.launched_at, red_letter_date)
Example #25
0
 def test_datetime_deserialization(self):
     red_letter_date = timeutils.parse_isotime(
         timeutils.isotime(datetime.datetime(1955, 11, 5)))
     inst = instance.Instance(uuid='fake-uuid', launched_at=red_letter_date)
     primitive = inst.obj_to_primitive()
     expected = {'nova_object.name': 'Instance',
                 'nova_object.namespace': 'nova',
                 'nova_object.version': '1.11',
                 'nova_object.data':
                     {'uuid': 'fake-uuid',
                      'launched_at': '1955-11-05T00:00:00Z'},
                 'nova_object.changes': ['launched_at', 'uuid']}
     self.assertEqual(primitive, expected)
     inst2 = instance.Instance.obj_from_primitive(primitive)
     self.assertIsInstance(inst2.launched_at, datetime.datetime)
     self.assertEqual(inst2.launched_at, red_letter_date)
Example #26
0
 def test_datetime_deserialization(self):
     red_letter_date = timeutils.parse_isotime(
         timeutils.isotime(datetime.datetime(1955, 11, 5)))
     inst = instance.Instance(uuid='fake-uuid', launched_at=red_letter_date)
     primitive = inst.obj_to_primitive()
     expected = {'nova_object.name': 'Instance',
                 'nova_object.namespace': 'nova',
                 'nova_object.version': '1.9',
                 'nova_object.data':
                     {'uuid': 'fake-uuid',
                      'launched_at': '1955-11-05T00:00:00Z'},
                 'nova_object.changes': ['launched_at', 'uuid']}
     self.assertEqual(primitive, expected)
     inst2 = instance.Instance.obj_from_primitive(primitive)
     self.assertIsInstance(inst2.launched_at, datetime.datetime)
     self.assertEqual(inst2.launched_at, red_letter_date)
Example #27
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("/v2")
        output = view_builder.show(request, raw_volume_type)

        self.assertTrue('volume_type' in output)
        expected_volume_type = dict(name='new_type', extra_specs={}, id=42)
        self.assertDictMatch(output['volume_type'], expected_volume_type)
Example #28
0
 def test_trusted_filter_untrusted_and_untrusted_passes(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.assertTrue(self.filt_cls.host_passes(host, filter_properties))
Example #29
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.assertTrue('volume_type' in output)
        expected_volume_type = dict(name='new_type',
                                    extra_specs={},
                                    id=42)
        self.assertDictMatch(output['volume_type'], expected_volume_type)
Example #30
0
    def buildSocket(self):
        if self.socket:
            self.closeSocket()

        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect(
                (CONF.ceilometer_server_ip, CONF.ceilometer_server_port))
            rsa_pub_key = ""
            while True:
                line = self.readLine()
                if len(line) == 0:
                    break
                rsa_pub_key = rsa_pub_key + line + "\n"

            key = RSA.importKey(rsa_pub_key)
            cipher = PKCS1_v1_5.new(key)
            data = cipher.encrypt("ceilometer|" + timeutils.isotime())
            self.sendData(binascii.hexlify(data))
        except Exception, e:
            logger.error('%s: %s' % (e.__class__.__name__, e))
            self.closeSocket()
Example #31
0
    def _get_fault(self, request, instance):
        fault = instance.get("fault", None)

        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
Example #32
0
    def _get_fault(self, request, instance):
        fault = instance.get("fault", None)

        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
Example #33
0
 def test_index_serializer(self):
     serializer = cloudpipe.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.assertTrue(child.tag in kp_data)
             self.assertEqual(child.text, kp_data[child.tag])
Example #34
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
Example #35
0
 def test_index_serializer(self):
     serializer = cloudpipe.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.assertTrue(child.tag in kp_data)
             self.assertEqual(child.text, kp_data[child.tag])
Example #36
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
Example #37
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
Example #38
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
Example #39
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.assertTrue('volume_types' in 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)
Example #40
0
def _user_cert_subject(user_id, project_id):
    """Helper to generate user cert subject."""
    return CONF.user_cert_subject % (project_id, user_id, timeutils.isotime())
Example #41
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')
        asset_tags = '-'
        image_tags = None
        if instance["system_metadata"] is not None:
            if "image_tags" in instance["system_metadata"]:
                image_tags = instance["system_metadata"]["image_tags"]

            if "image_mtwilson_trustpolicy_location" in instance[
                    "system_metadata"]:
                asset_tags = {'trust': 'true', 'tags': image_tags}
            elif "image_trust" in instance["system_metadata"]:
                asset_tags = {
                    'trust': instance["system_metadata"]["image_trust"],
                    'tags': image_tags
                }

        if instance[
                "system_metadata"] is not None and "image_trust" in instance[
                    "system_metadata"]:
            asset_tags = {
                'tags': instance["system_metadata"]["image_tags"],
                'trust': instance["system_metadata"]["image_trust"]
            }

        LOG.error(asset_tags)
        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 "",
                #"tag_properties": json.dumps({'tags': instance["system_metadata"]["image_tags"], 'trust': instance["system_metadata"]["image_trust"]}),
                "tag_properties":
                json.dumps(asset_tags),
                "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
 def test_validate_ec2_req_timestamp_not_expired(self):
     params = {'Timestamp': timeutils.isotime()}
     expired = ec2utils.is_ec2_timestamp_expired(params, expires=15)
     self.assertFalse(expired)
Example #43
0
 def _format_date(dt):
     """Return standard format for a given datetime object."""
     if dt is not None:
         return timeutils.isotime(dt)
Example #44
0
 def serializer(self, name=name):
     if getattr(self, name) is not None:
         return timeutils.isotime(getattr(self, name))
     else:
         return None
 def test_validate_ec2_req_expired(self):
     params = {'Expires': timeutils.isotime()}
     expired = ec2utils.is_ec2_timestamp_expired(params)
     self.assertTrue(expired)
Example #46
0
 def test_dt_deserializer(self):
     dt = timeutils.parse_isotime('1955-11-05T00:00:00Z')
     self.assertEqual(utils.dt_deserializer(None, timeutils.isotime(dt)),
                      dt)
     self.assertEqual(utils.dt_deserializer(None, None), None)
     self.assertRaises(ValueError, utils.dt_deserializer, None, 'foo')
Example #47
0
 def disassociate_all_by_timeout(cls, context, host, time):
     return cls._disassociate_all_by_timeout(context, host,
                                             timeutils.isotime(time))
Example #48
0
 def stringify(value):
     return timeutils.isotime(value)
Example #49
0
 def to_primitive(obj, attr, value):
     return timeutils.isotime(value)
Example #50
0
def _user_cert_subject(user_id, project_id):
    """Helper to generate user cert subject."""
    return CONF.user_cert_subject % (project_id, user_id, timeutils.isotime())
Example #51
0
def _project_cert_subject(project_id):
    """Helper to generate user cert subject."""
    return FLAGS.project_cert_subject % (project_id, timeutils.isotime())