Ejemplo n.º 1
0
    def test_attach_wait_for_sync(self, mrapi):
        """Test wait_for_sync when attaching volume to instance.

        """
        volume = mfactory.VolumeFactory()
        vm = volume.machine
        # Test Started VM
        vm.operstate = "STARTED"
        vm.save()
        mrapi().ModifyInstance.return_value = 1
        for sync in [True, False]:
            with override_settings(settings, GANETI_DISKS_WAIT_FOR_SYNC=sync):
                jobid = backend.attach_volume(vm, volume)
                self.assertEqual(jobid, 1)
                name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]
                self.assertEqual(kwargs['wait_for_sync'], sync)

        # Test Stopped VM. We do not pass wait_for_sync.
        vm.operstate = "STOPPED"
        vm.save()
        mrapi().ModifyInstance.return_value = 1
        for sync in [True, False]:
            with override_settings(settings, GANETI_DISKS_WAIT_FOR_SYNC=sync):
                jobid = backend.attach_volume(vm, volume)
                self.assertEqual(jobid, 1)
                name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]
                self.assertFalse('wait_for_sync' in kwargs)
Ejemplo n.º 2
0
 def test_server_fqdn(self):
     vm = mfactory.VirtualMachineFactory()
     # Setting set to None
     with override_settings(settings, CYCLADES_SERVERS_FQDN=None):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"], None)
     # Unformated setting
     with override_settings(settings,
                            CYCLADES_SERVERS_FQDN="vm.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"], "vm.example.org")
     # Formatted settings
     with override_settings(
             settings, CYCLADES_SERVERS_FQDN="snf-%(id)s.vm.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"],
                          "snf-%d.vm.example.org" % vm.id)
     with override_settings(
             settings,
             CYCLADES_SERVERS_FQDN="snf-%(id)s.vm-%(id)s.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"],
                          "snf-%d.vm-%d.example.org" % (vm.id, vm.id))
Ejemplo n.º 3
0
 def test_hypervisor(self):
     from synnefo.db.models import snf_settings
     kvm_backend = mfact.BackendFactory(hypervisor="kvm")
     xen_pvm_backend = mfact.BackendFactory(hypervisor="xen-pvm")
     xen_hvm_backend = mfact.BackendFactory(hypervisor="xen-hvm")
     with override_settings(snf_settings, GANETI_USE_HOTPLUG=True):
         self.assertTrue(kvm_backend.use_hotplug())
         self.assertFalse(xen_pvm_backend.use_hotplug())
         self.assertFalse(xen_hvm_backend.use_hotplug())
     with override_settings(snf_settings, GANETI_USE_HOTPLUG=False):
         self.assertFalse(kvm_backend.use_hotplug())
         self.assertFalse(xen_pvm_backend.use_hotplug())
         self.assertFalse(xen_hvm_backend.use_hotplug())
     kwargs = {"os": "snf-image+default",
               "hvparams": {"kvm": {"foo1": "mpaz1"},
                            "xen-pvm": {"foo2": "mpaz2"},
                            "xen-hvm": {"foo3": "mpaz3"}}}
     with override_settings(snf_settings,
                            GANETI_CREATEINSTANCE_KWARGS=kwargs):
         self.assertEqual(kvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo1": "mpaz1"}})
         self.assertEqual(xen_pvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo2": "mpaz2"}})
         self.assertEqual(xen_hvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo3": "mpaz3"}})
     with override_settings(snf_settings, GANETI_CREATEINSTANCE_KWARGS={}):
         self.assertEqual(kvm_backend.get_create_params(), {"hvparams": {}})
Ejemplo n.º 4
0
 def test_server_fqdn(self):
     vm = mfactory.VirtualMachineFactory()
     # Setting set to None
     with override_settings(settings,
                            CYCLADES_SERVERS_FQDN=None):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"], None)
     # Unformated setting
     with override_settings(settings,
                            CYCLADES_SERVERS_FQDN="vm.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"], "vm.example.org")
     # Formatted settings
     with override_settings(settings, CYCLADES_SERVERS_FQDN=
                            "snf-%(id)s.vm.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"],
                          "snf-%d.vm.example.org" % vm.id)
     with override_settings(settings,
                            CYCLADES_SERVERS_FQDN=
                            "snf-%(id)s.vm-%(id)s.example.org"):
         response = self.myget("servers/%d" % vm.id, vm.userid)
         server = json.loads(response.content)['server']
         self.assertEqual(server["SNF:fqdn"], "snf-%d.vm-%d.example.org" %
                          (vm.id, vm.id))
Ejemplo n.º 5
0
 def test_hypervisor(self):
     from synnefo.db.models import snf_settings
     kvm_backend = mfact.BackendFactory(hypervisor="kvm")
     xen_pvm_backend = mfact.BackendFactory(hypervisor="xen-pvm")
     xen_hvm_backend = mfact.BackendFactory(hypervisor="xen-hvm")
     with override_settings(snf_settings, GANETI_USE_HOTPLUG=True):
         self.assertTrue(kvm_backend.use_hotplug())
         self.assertFalse(xen_pvm_backend.use_hotplug())
         self.assertFalse(xen_hvm_backend.use_hotplug())
     with override_settings(snf_settings, GANETI_USE_HOTPLUG=False):
         self.assertFalse(kvm_backend.use_hotplug())
         self.assertFalse(xen_pvm_backend.use_hotplug())
         self.assertFalse(xen_hvm_backend.use_hotplug())
     kwargs = {"os": "snf-image+default",
               "hvparams": {"kvm": {"foo1": "mpaz1"},
                            "xen-pvm": {"foo2": "mpaz2"},
                            "xen-hvm": {"foo3": "mpaz3"}}}
     with override_settings(snf_settings,
                            GANETI_CREATEINSTANCE_KWARGS=kwargs):
         self.assertEqual(kvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo1": "mpaz1"}})
         self.assertEqual(xen_pvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo2": "mpaz2"}})
         self.assertEqual(xen_hvm_backend.get_create_params(),
                          {"os": "snf-image+default",
                           "hvparams": {"foo3": "mpaz3"}})
     with override_settings(snf_settings, GANETI_CREATEINSTANCE_KWARGS={}):
         self.assertEqual(kvm_backend.get_create_params(), {"hvparams": {}})
Ejemplo n.º 6
0
 def test_create_port_private_net(self, mrapi):
     net = dbmf.NetworkFactory(public=False)
     dbmf.IPv4SubnetFactory(network=net)
     dbmf.IPv6SubnetFactory(network=net)
     sg1 = dbmf.SecurityGroupFactory()
     sg2 = dbmf.SecurityGroupFactory()
     vm = dbmf.VirtualMachineFactory(userid=net.userid)
     request = {
         "port": {
             "name": "port1",
             "network_id": str(net.id),
             "device_id": str(vm.id),
             "security_groups": [str(sg1.id), str(sg2.id)]
         }
     }
     mrapi().ModifyInstance.return_value = 42
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         response = self.post(PORTS_URL,
                              params=json.dumps(request),
                              user=net.userid)
     self.assertEqual(response.status_code, 400)
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.post(PORTS_URL,
                              params=json.dumps(request),
                              user=net.userid)
     self.assertEqual(response.status_code, 201)
Ejemplo n.º 7
0
    def test_server_port_forwarding(self):
        vm = mfactory.VirtualMachineFactory()
        # test None if the server has no public IP
        ports = {22: ("foo", 61000), 80: lambda ip, id, fqdn, user: ("bar", 61001)}
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
        server = json.loads(response.content)["server"]
        self.assertEqual(server["SNF:port_forwarding"], {})

        # Add with public IP
        mfactory.IPv4AddressFactory(nic__machine=vm, network__public=True)
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
        server = json.loads(response.content)["server"]
        self.assertEqual(
            server["SNF:port_forwarding"],
            {"22": {"host": "foo", "port": "61000"}, "80": {"host": "bar", "port": "61001"}},
        )

        def _port_from_ip(ip, base):
            fields = ip.split(".", 4)
            return base + 256 * int(fields[2]) + int(fields[3])

        ports = {22: lambda ip, id, fqdn, user: ip and ("gate", _port_from_ip(ip, 10000)) or None}
        vm = mfactory.VirtualMachineFactory()
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
            server = json.loads(response.content)["server"]
            self.assertEqual(server["SNF:port_forwarding"], {})

        mfactory.IPv4AddressFactory(nic__machine=vm, network__public=True, address="192.168.2.2")
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
            server = json.loads(response.content)["server"]
            self.assertEqual(server["SNF:port_forwarding"], {"22": {"host": "gate", "port": "10514"}})
Ejemplo n.º 8
0
    def test_attach_wait_for_sync(self, mrapi):
        """Test wait_for_sync when attaching volume to instance.

        """
        volume = mfactory.VolumeFactory()
        vm = volume.machine
        # Test Started VM
        vm.operstate = "STARTED"
        vm.save()
        mrapi().ModifyInstance.return_value = 1
        for sync in [True, False]:
            with override_settings(settings, GANETI_DISKS_WAIT_FOR_SYNC=sync):
                jobid = backend.attach_volume(vm, volume)
                self.assertEqual(jobid, 1)
                name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]
                self.assertEqual(kwargs['wait_for_sync'], sync)

        # Test Stopped VM. We do not pass wait_for_sync.
        vm.operstate = "STOPPED"
        vm.save()
        mrapi().ModifyInstance.return_value = 1
        for sync in [True, False]:
            with override_settings(settings, GANETI_DISKS_WAIT_FOR_SYNC=sync):
                jobid = backend.attach_volume(vm, volume)
                self.assertEqual(jobid, 1)
                name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]
                self.assertFalse('wait_for_sync' in kwargs)
Ejemplo n.º 9
0
 def test_delete_port(self, mrapi):
     nic = dbmf.NetworkInterfaceFactory(device_owner='vm')
     url = join_urls(PORTS_URL, str(nic.id))
     mrapi().ModifyInstance.return_value = 42
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.delete(url, user=nic.userid)
     self.assertEqual(response.status_code, 204)
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         response = self.delete(url, user=nic.userid)
     self.assertEqual(response.status_code, 400)
Ejemplo n.º 10
0
 def test_delete_port(self, mrapi):
     nic = dbmf.NetworkInterfaceFactory(device_owner='vm')
     url = join_urls(PORTS_URL, str(nic.id))
     mrapi().ModifyInstance.return_value = 42
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.delete(url, user=nic.userid)
     self.assertEqual(response.status_code, 204)
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         response = self.delete(url, user=nic.userid)
     self.assertEqual(response.status_code, 400)
Ejemplo n.º 11
0
    def test_server_port_forwarding(self):
        vm = mfactory.VirtualMachineFactory()
        # test None if the server has no public IP
        ports = {
            22: ("foo", 61000),
            80: lambda ip, id, fqdn, user: ("bar", 61001)
        }
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
        server = json.loads(response.content)['server']
        self.assertEqual(server["SNF:port_forwarding"], {})

        # Add with public IP
        mfactory.IPv4AddressFactory(nic__machine=vm, network__public=True)
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
        server = json.loads(response.content)['server']
        self.assertEqual(
            server["SNF:port_forwarding"], {
                "22": {
                    "host": "foo",
                    "port": "61000"
                },
                "80": {
                    "host": "bar",
                    "port": "61001"
                }
            })

        def _port_from_ip(ip, base):
            fields = ip.split('.', 4)
            return (base + 256 * int(fields[2]) + int(fields[3]))

        ports = {
            22:
            lambda ip, id, fqdn, user: ip and
            ("gate", _port_from_ip(ip, 10000)) or None
        }
        vm = mfactory.VirtualMachineFactory()
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
            server = json.loads(response.content)['server']
            self.assertEqual(server["SNF:port_forwarding"], {})

        mfactory.IPv4AddressFactory(nic__machine=vm,
                                    network__public=True,
                                    address="192.168.2.2")
        with override_settings(settings, CYCLADES_PORT_FORWARDING=ports):
            response = self.myget("servers/%d" % vm.id, vm.userid)
            server = json.loads(response.content)['server']
            self.assertEqual(server["SNF:port_forwarding"],
                             {"22": {
                                 "host": "gate",
                                 "port": "10514"
                             }})
Ejemplo n.º 12
0
    def test_create_network_settings(self, mrapi):
        mrapi().CreateInstance.return_value = 12
        # User requested private networks
        # no public IPv4
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS": ["SNF:ANY_PUBLIC_IPV4"]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 503)
        # no public IPv4, IPv6 exists
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS": ["SNF:ANY_PUBLIC"]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(vm.nics.get().ipv4_address, None)

        # IPv4 exists
        mfactory.IPv4SubnetFactory(network__public=True,
                                   cidr="192.168.2.0/24",
                                   pool__offset=2,
                                   pool__size=1)
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(vm.nics.get().ipv4_address, "192.168.2.2")

        # Fixed networks
        net1 = mfactory.NetworkFactory(userid="test")
        net2 = mfactory.NetworkFactory(userid="test")
        net3 = mfactory.NetworkFactory(userid="test")
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS": [net1.id, [net2.id, net3.id],
                                                (net3.id, net2.id)]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(len(vm.nics.all()), 3)
Ejemplo n.º 13
0
    def test_create_network_settings(self, mrapi):
        mrapi().CreateInstance.return_value = 12
        # User requested private networks
        # no public IPv4
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS": ["SNF:ANY_PUBLIC_IPV4"]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 503)
        # no public IPv4, IPv6 exists
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS": ["SNF:ANY_PUBLIC"]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(vm.nics.get().ipv4_address, None)

        # IPv4 exists
        mfactory.IPv4SubnetFactory(network__public=True,
                                   cidr="192.168.2.0/24",
                                   pool__offset=2,
                                   pool__size=1)
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(vm.nics.get().ipv4_address, "192.168.2.2")

        # Fixed networks
        net1 = mfactory.NetworkFactory(userid="test")
        net2 = mfactory.NetworkFactory(userid="test")
        net3 = mfactory.NetworkFactory(userid="test")
        network_settings = {
            "CYCLADES_DEFAULT_SERVER_NETWORKS": [],
            "CYCLADES_FORCED_SERVER_NETWORKS":
            [net1.id, [net2.id, net3.id], (net3.id, net2.id)]
        }
        with override_settings(settings, **network_settings):
            response = self.mypost('servers', "test", json.dumps(self.request),
                                   'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        vm = VirtualMachine.objects.get(id=server_id)
        self.assertEqual(len(vm.nics.all()), 3)
Ejemplo n.º 14
0
    def test_default_view(self):
        """Test if the default_view() function works as expected."""
        self.assertEqual(utils.default_view(), 'user')
        with override_settings(settings, ADMIN_VIEWS_ORDER=[]):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=['1', '2']):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=['1', 'user', '3']):
            reload_settings()
            self.assertEqual(utils.default_view(), 'user')

        reload_settings()
Ejemplo n.º 15
0
    def test_default_view(self):
        """Test if the default_view() function works as expected."""
        self.assertEqual(utils.default_view(), "user")
        with override_settings(settings, ADMIN_VIEWS_ORDER=[]):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=["1", "2"]):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=["1", "user", "3"]):
            reload_settings()
            self.assertEqual(utils.default_view(), "user")

        reload_settings()
Ejemplo n.º 16
0
 def test_create_port_without_device(self):
     net = dbmf.NetworkWithSubnetFactory(userid="test_user",
                                         public=False,
                                         subnet__cidr="192.168.2.0/24",
                                         subnet__gateway=None,
                                         subnet__pool__size=3,
                                         subnet__pool__offset=1)
     request = {
         "port": {
             "name": "port_with_address",
             "network_id": str(net.id),
         }
     }
     response = self.post(PORTS_URL,
                          params=json.dumps(request),
                          user="******")
     self.assertEqual(response.status_code, 201)
     new_port = json.loads(response.content)["port"]
     self.assertEqual(new_port["device_id"], None)
     # And with address
     request["port"]["fixed_ips"] = [{"ip_address": "192.168.2.2"}]
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.post(PORTS_URL,
                              params=json.dumps(request),
                              user="******")
     self.assertEqual(response.status_code, 201)
     new_port = json.loads(response.content)["port"]
     self.assertEqual(new_port["device_id"], None)
     self.assertEqual(new_port["fixed_ips"][0]["ip_address"], "192.168.2.2")
Ejemplo n.º 17
0
    def test_create_server_wrong_flavor(self, mrapi):
        # Test with a flavor that does not exist
        request = deepcopy(self.request)
        request["server"]["flavorRef"] = 42
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost("servers", "test_user", json.dumps(request), "json")
        self.assertItemNotFound(response)

        # Test with an flavor that is not allowed
        flavor = mfactory.FlavorFactory(allow_create=False)
        request["server"]["flavorRef"] = flavor.id
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost("servers", "test_user", json.dumps(request), "json")
        self.assertEqual(response.status_code, 403)
Ejemplo n.º 18
0
 def test_invalid_operstate_for_action(self, mrapi):
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     self.assertRaises(faults.BadRequest, servers.start, vm)
     vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
     self.assertRaises(faults.BadRequest, servers.stop, vm)
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     flavor = mfactory.FlavorFactory()
     self.assertRaises(faults.BadRequest, servers.resize, vm, flavor)
     # Check that connect/disconnect is allowed only in STOPPED vms
     # if hotplug is disabled.
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     network = mfactory.NetworkFactory(state="ACTIVE")
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         self.assertRaises(faults.BadRequest, servers.connect, vm, network)
         self.assertRaises(faults.BadRequest, servers.disconnect, vm,
                           network)
     #test valid
     vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
     mrapi().StartupInstance.return_value = 1
     with mocked_quotaholder():
         servers.start(vm)
     vm.task = None
     vm.task_job_id = None
     vm.save()
     with mocked_quotaholder():
         quotas.accept_resource_serial(vm)
     mrapi().RebootInstance.return_value = 1
     with mocked_quotaholder():
         servers.reboot(vm, "HARD")
Ejemplo n.º 19
0
    def test_default_view(self):
        """Test if the default_view() function works as expected."""
        self.assertEqual(utils.default_view(), 'user')
        with override_settings(settings, ADMIN_VIEWS_ORDER=[]):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=['1', '2']):
            reload_settings()
            self.assertEqual(utils.default_view(), None)

        with override_settings(settings, ADMIN_VIEWS_ORDER=['1', 'user', '3']):
            reload_settings()
            self.assertEqual(utils.default_view(), 'user')

        reload_settings()
Ejemplo n.º 20
0
 def test_create_port_without_device(self):
     net = dbmf.NetworkWithSubnetFactory(userid="test_user",
                                         public=False,
                                         subnet__cidr="192.168.2.0/24",
                                         subnet__gateway=None,
                                         subnet__pool__size=3,
                                         subnet__pool__offset=1)
     request = {
         "port": {
             "name": "port_with_address",
             "network_id": str(net.id),
         }
     }
     response = self.post(PORTS_URL, params=json.dumps(request),
                          user="******")
     self.assertEqual(response.status_code, 201)
     new_port = json.loads(response.content)["port"]
     self.assertEqual(new_port["device_id"], None)
     # And with address
     request["port"]["fixed_ips"] = [{"ip_address": "192.168.2.2"}]
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.post(PORTS_URL, params=json.dumps(request),
                              user="******")
     self.assertEqual(response.status_code, 201)
     new_port = json.loads(response.content)["port"]
     self.assertEqual(new_port["device_id"], None)
     self.assertEqual(new_port["fixed_ips"][0]["ip_address"], "192.168.2.2")
Ejemplo n.º 21
0
 def test_invalid_operstate_for_action(self, mrapi):
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     self.assertRaises(faults.BadRequest, servers.start, vm)
     vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
     self.assertRaises(faults.BadRequest, servers.stop, vm)
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     flavor = mfactory.FlavorFactory()
     self.assertRaises(faults.BadRequest, servers.resize, vm, flavor)
     # Check that connect/disconnect is allowed only in STOPPED vms
     # if hotplug is disabled.
     vm = mfactory.VirtualMachineFactory(operstate="STARTED")
     network = mfactory.NetworkFactory(state="ACTIVE")
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         self.assertRaises(faults.BadRequest, servers.connect, vm, network)
         self.assertRaises(faults.BadRequest, servers.disconnect, vm, network)
     # test valid
     vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
     mrapi().StartupInstance.return_value = 1
     with mocked_quotaholder():
         servers.start(vm)
     vm.task = None
     vm.task_job_id = None
     vm.save()
     with mocked_quotaholder():
         quotas.accept_resource_serial(vm)
     mrapi().RebootInstance.return_value = 1
     with mocked_quotaholder():
         servers.reboot(vm, "HARD")
Ejemplo n.º 22
0
    def test_create(self, mrapi):
        flavor = mfactory.FlavorFactory()
        kwargs = {
            "userid": "test",
            "name": "test_vm",
            "password": "******",
            "flavor": flavor,
            "image": {
                "id": "foo",
                "backend_id": "foo",
                "format": "diskdump",
                "checksum": "test_checksum",
                "metadata": "{}",
            },
            "networks": [],
            "metadata": {"foo": "bar"},
            "personality": [],
        }
        # no backend!
        mfactory.BackendFactory(offline=True)
        self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        mfactory.IPv4SubnetFactory(network__public=True)
        mfactory.IPv6SubnetFactory(network__public=True)
        backend = mfactory.BackendFactory()

        # error in nics
        req = deepcopy(kwargs)
        req["networks"] = [{"uuid": 42}]
        self.assertRaises(faults.ItemNotFound, servers.create, **req)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        # error in enqueue. check the vm is deleted and resources released
        mrapi().CreateInstance.side_effect = Exception("ganeti is down")
        with mocked_quotaholder():
            servers.create(**kwargs)
        vm = models.VirtualMachine.objects.get()
        self.assertFalse(vm.deleted)
        self.assertEqual(vm.operstate, "ERROR")
        for nic in vm.nics.all():
            self.assertEqual(nic.state, "ERROR")

        # test ext settings:
        req = deepcopy(kwargs)
        ext_flavor = mfactory.FlavorFactory(disk_template="ext_archipelago", disk=1)
        req["flavor"] = ext_flavor
        mrapi().CreateInstance.return_value = 42
        backend.disk_templates = ["ext"]
        backend.save()
        osettings = {"GANETI_DISK_PROVIDER_KWARGS": {"archipelago": {"foo": "mpaz", "lala": "lolo"}}}
        with mocked_quotaholder():
            with override_settings(settings, **osettings):
                vm = servers.create(**req)
        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        self.assertEqual(
            kwargs["disks"][0],
            {"provider": "archipelago", "origin": "test_checksum", "foo": "mpaz", "lala": "lolo", "size": 1024},
        )
Ejemplo n.º 23
0
    def test_attach_volume_type_specs(self, mrapi):
        """Test volume type spces propagation when attaching a
           volume to an instance
        """
        vlmt = mfactory.VolumeTypeFactory(disk_template='ext_archipelago')
        # Generate 4 specs. 2 prefixed with GNT_EXTP_VOLTYPESPEC_PREFIX
        # and 2 with an other prefix that should be omitted
        volume_type_specs = [
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='%sbar' %
                                            GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='%sfoo' %
                                            GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='other-prefx-baz'),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='another-prefix-biz'),
        ]

        gnt_prefixed_specs = filter(
            lambda s: s.key.startswith(GNT_EXTP_VOLTYPESPEC_PREFIX),
            volume_type_specs)
        volume = mfactory.VolumeFactory(volume_type=vlmt, size=1)
        vm = volume.machine
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }

        with override_settings(settings, **osettings):
            mrapi().ModifyInstance.return_value = 1
            jobid = backend.attach_volume(vm, volume)
            self.assertEqual(jobid, 1)
            name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]

            disk_kwargs = {
                "provider": "archipelago",
                "name": vm.volumes.all()[0].backend_volume_uuid,
                "reuse_data": 'False',
                "foo": "mpaz",
                "lala": "lolo",
                "size": 1024
            }
            disk_kwargs.update({
                spec.key[len(GNT_EXTP_VOLTYPESPEC_PREFIX):]: spec.value
                for spec in gnt_prefixed_specs
            })

        # Should be "disks": [('add', '-1', {disk_kwargs}), ]
        disk = kwargs["disks"][0]
        self.assertEqual(disk[0], 'add')
        self.assertEqual(disk[1], '-1')
        self.assertEqual(disk[2], disk_kwargs)
Ejemplo n.º 24
0
    def test_create_server_wrong_flavor(self, mrapi):
        # Test with a flavor that does not exist
        request = deepcopy(self.request)
        request["server"]["flavorRef"] = 42
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', 'test_user',
                                       json.dumps(request), 'json')
        self.assertItemNotFound(response)

        # Test with an flavor that is not allowed
        flavor = mfactory.FlavorFactory(allow_create=False)
        request["server"]["flavorRef"] = flavor.id
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', 'test_user',
                                       json.dumps(request), 'json')
        self.assertEqual(response.status_code, 403)
Ejemplo n.º 25
0
    def test_connect_network(self, mrapi):
        # Common connect
        for dhcp in [True, False]:
            subnet = mfactory.IPv4SubnetFactory(network__flavor="CUSTOM",
                                                cidr="192.168.2.0/24",
                                                gateway="192.168.2.1",
                                                dhcp=dhcp)
            net = subnet.network
            vm = mfactory.VirtualMachineFactory(operstate="STARTED")
            mfactory.BackendNetworkFactory(network=net, backend=vm.backend)
            mrapi().ModifyInstance.return_value = 42
            with override_settings(settings, GANETI_USE_HOTPLUG=True):
                with transaction.atomic():
                    port = servers._create_port(vm.userid, net)
                    servers.connect_port(vm, net, port)
            pool = net.get_ip_pools(locked=False)[0]
            self.assertFalse(pool.is_available("192.168.2.2"))
            args, kwargs = mrapi().ModifyInstance.call_args
            nics = kwargs["nics"][0]
            self.assertEqual(kwargs["instance"], vm.backend_vm_id)
            self.assertEqual(nics[0], "add")
            self.assertEqual(nics[1], "-1")
            self.assertEqual(nics[2]["ip"], "192.168.2.2")
            self.assertEqual(nics[2]["network"], net.backend_id)

        # Test connect to IPv6 only network
        vm = mfactory.VirtualMachineFactory(operstate="STARTED")
        subnet = mfactory.IPv6SubnetFactory(cidr="2000::/64",
                                            gateway="2000::1")
        net = subnet.network
        mfactory.BackendNetworkFactory(network=net, backend=vm.backend)
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            with transaction.atomic():
                port = servers._create_port(vm.userid, net)
                servers.connect_port(vm, net, port)
        args, kwargs = mrapi().ModifyInstance.call_args
        nics = kwargs["nics"][0]
        self.assertEqual(kwargs["instance"], vm.backend_vm_id)
        self.assertEqual(nics[0], "add")
        self.assertEqual(nics[1], "-1")
        self.assertEqual(nics[2]["ip"], None)
        self.assertEqual(nics[2]["network"], net.backend_id)
Ejemplo n.º 26
0
    def test_connect_network(self, mrapi):
        # Common connect
        for dhcp in [True, False]:
            subnet = mfactory.IPv4SubnetFactory(network__flavor="CUSTOM",
                                                cidr="192.168.2.0/24",
                                                gateway="192.168.2.1",
                                                dhcp=dhcp)
            net = subnet.network
            vm = mfactory.VirtualMachineFactory(operstate="STARTED")
            mfactory.BackendNetworkFactory(network=net, backend=vm.backend)
            mrapi().ModifyInstance.return_value = 42
            with override_settings(settings, GANETI_USE_HOTPLUG=True):
                with transaction.atomic():
                    port = servers._create_port(vm.userid, net)
                    servers.connect_port(vm, net, port)
            pool = net.get_ip_pools(locked=False)[0]
            self.assertFalse(pool.is_available("192.168.2.2"))
            args, kwargs = mrapi().ModifyInstance.call_args
            nics = kwargs["nics"][0]
            self.assertEqual(kwargs["instance"], vm.backend_vm_id)
            self.assertEqual(nics[0], "add")
            self.assertEqual(nics[1], "-1")
            self.assertEqual(nics[2]["ip"], "192.168.2.2")
            self.assertEqual(nics[2]["network"], net.backend_id)

        # Test connect to IPv6 only network
        vm = mfactory.VirtualMachineFactory(operstate="STARTED")
        subnet = mfactory.IPv6SubnetFactory(cidr="2000::/64",
                                            gateway="2000::1")
        net = subnet.network
        mfactory.BackendNetworkFactory(network=net, backend=vm.backend)
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            with transaction.atomic():
                port = servers._create_port(vm.userid, net)
                servers.connect_port(vm, net, port)
        args, kwargs = mrapi().ModifyInstance.call_args
        nics = kwargs["nics"][0]
        self.assertEqual(kwargs["instance"], vm.backend_vm_id)
        self.assertEqual(nics[0], "add")
        self.assertEqual(nics[1], "-1")
        self.assertEqual(nics[2]["ip"], None)
        self.assertEqual(nics[2]["network"], net.backend_id)
Ejemplo n.º 27
0
    def test_create_port_with_address(self, mrapi):
        """Test creation if IP address is specified."""
        mrapi().ModifyInstance.return_value = 42
        vm = dbmf.VirtualMachineFactory()
        net = dbmf.NetworkWithSubnetFactory(userid=vm.userid,
                                            public=False,
                                            subnet__cidr="192.168.2.0/24",
                                            subnet__gateway=None,
                                            subnet__pool__size=1,
                                            subnet__pool__offset=1)
        request = {
            "port": {
                "name": "port_with_address",
                "network_id": str(net.id),
                "device_id": str(vm.id),
                "fixed_ips": [{
                    "ip_address": "192.168.2.1"
                }]
            }
        }
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL,
                                 params=json.dumps(request),
                                 user=vm.userid)
        self.assertEqual(response.status_code, 201)
        new_port_ip = json.loads(response.content)["port"]["fixed_ips"][0]
        self.assertEqual(new_port_ip["ip_address"], "192.168.2.1")

        # But 409 if address is already used
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL,
                                 params=json.dumps(request),
                                 user=vm.userid)
        self.assertConflict(response)

        # And bad request if IPv6 address is specified
        request["port"]["fixed_ips"][0]["ip_address"] = "babe::"
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL,
                                 params=json.dumps(request),
                                 user=vm.userid)
        self.assertBadRequest(response)
Ejemplo n.º 28
0
 def test_create_server_with_port(self, mrapi):
     # Test invalid networks
     request = deepcopy(self.request)
     request["server"]["networks"] = {"foo": "lala"}
     with override_settings(settings, **self.network_settings):
         response = self.mypost("servers", "dummy_user",
                                json.dumps(request), 'json')
     self.assertBadRequest(response)
     request["server"]["networks"] = ['1', '2']
     with override_settings(settings, **self.network_settings):
         response = self.mypost("servers", "dummy_user",
                                json.dumps(request), 'json')
     self.assertBadRequest(response)
     mrapi().CreateInstance.return_value = 42
     ip = mfactory.IPv4AddressFactory(nic__machine=None)
     port1 = ip.nic
     request = deepcopy(self.request)
     request["server"]["networks"] = [{"port": port1.id}]
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", port1.userid,
                                    json.dumps(request), 'json')
     self.assertEqual(response.status_code, 202)
     vm_id = json.loads(response.content)["server"]["id"]
     port1 = NetworkInterface.objects.get(id=port1.id)
     self.assertEqual(port1.machine_id, vm_id)
     # 409 if already used
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", port1.userid,
                                    json.dumps(request), 'json')
     self.assertConflict(response)
     # Test permissions
     ip = mfactory.IPv4AddressFactory(userid="user1", nic__userid="user1")
     port2 = ip.nic
     request["server"]["networks"] = [{"port": port2.id}]
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", "user2", json.dumps(request),
                                    'json')
     self.assertEqual(response.status_code, 404)
Ejemplo n.º 29
0
 def test_create_server_with_port(self, mrapi):
     # Test invalid networks
     request = deepcopy(self.request)
     request["server"]["networks"] = {"foo": "lala"}
     with override_settings(settings, **self.network_settings):
         response = self.mypost("servers", "dummy_user",
                                json.dumps(request), 'json')
     self.assertBadRequest(response)
     request["server"]["networks"] = ['1', '2']
     with override_settings(settings, **self.network_settings):
         response = self.mypost("servers", "dummy_user",
                                json.dumps(request), 'json')
     self.assertBadRequest(response)
     mrapi().CreateInstance.return_value = 42
     ip = mfactory.IPv4AddressFactory(nic__machine=None)
     port1 = ip.nic
     request = deepcopy(self.request)
     request["server"]["networks"] = [{"port": port1.id}]
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", port1.userid,
                                    json.dumps(request), 'json')
     self.assertEqual(response.status_code, 202)
     vm_id = json.loads(response.content)["server"]["id"]
     port1 = NetworkInterface.objects.get(id=port1.id)
     self.assertEqual(port1.machine_id, vm_id)
     # 409 if already used
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", port1.userid,
                                    json.dumps(request), 'json')
     self.assertConflict(response)
     # Test permissions
     ip = mfactory.IPv4AddressFactory(userid="user1", nic__userid="user1")
     port2 = ip.nic
     request["server"]["networks"] = [{"port": port2.id}]
     with override_settings(settings, **self.network_settings):
         with mocked_quotaholder():
             response = self.mypost("servers", "user2",
                                    json.dumps(request), 'json')
     self.assertEqual(response.status_code, 404)
Ejemplo n.º 30
0
    def test_attach_volume_type_specs(self, mrapi):
        """Test volume type spces propagation when attaching a
           volume to an instance
        """
        vlmt = mfactory.VolumeTypeFactory(disk_template='ext_archipelago')
        # Generate 4 specs. 2 prefixed with GNT_EXTP_VOLTYPESPEC_PREFIX
        # and 2 with an other prefix that should be omitted
        volume_type_specs = [
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='%sbar' % GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='%sfoo' % GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='other-prefx-baz'),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='another-prefix-biz'),
        ]

        gnt_prefixed_specs = filter(lambda s: s.key.startswith(
            GNT_EXTP_VOLTYPESPEC_PREFIX), volume_type_specs)
        volume = mfactory.VolumeFactory(volume_type=vlmt, size=1)
        vm = volume.machine
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }

        with override_settings(settings, **osettings):
            mrapi().ModifyInstance.return_value = 1
            jobid = backend.attach_volume(vm, volume)
            self.assertEqual(jobid, 1)
            name, args, kwargs = mrapi().ModifyInstance.mock_calls[-1]

            disk_kwargs = {"provider": "archipelago",
                           "name": vm.volumes.all()[0].backend_volume_uuid,
                           "reuse_data": 'False',
                           "foo": "mpaz",
                           "lala": "lolo",
                           "size": 1024}
            disk_kwargs.update({spec.key[len(GNT_EXTP_VOLTYPESPEC_PREFIX):]:
                                spec.value
                                for spec in gnt_prefixed_specs})

        # Should be "disks": [('add', '-1', {disk_kwargs}), ]
        disk = kwargs["disks"][0]
        self.assertEqual(disk[0], 'add')
        self.assertEqual(disk[1], '-1')
        self.assertEqual(disk[2], disk_kwargs)
Ejemplo n.º 31
0
 def test_invalid_create(self):
     """Test invalid flavor"""
     request = {"network": {}}
     response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
     self.assertBadRequest(response)
     request = {"network": {"type": "foo"}}
     response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
     self.assertBadRequest(response)
     request = {"network": {"type": "MAC_FILTERED"}}
     with override_settings(settings, API_ENABLED_NETWORK_FLAVORS=["CUSTOM"]):
         response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(Network.objects.filter(userid="user1")), 0)
Ejemplo n.º 32
0
    def test_create_port_with_address(self, mrapi):
        """Test creation if IP address is specified."""
        mrapi().ModifyInstance.return_value = 42
        vm = dbmf.VirtualMachineFactory()
        net = dbmf.NetworkWithSubnetFactory(userid=vm.userid,
                                            public=False,
                                            subnet__cidr="192.168.2.0/24",
                                            subnet__gateway=None,
                                            subnet__pool__size=1,
                                            subnet__pool__offset=1)
        request = {
            "port": {
                "name": "port_with_address",
                "network_id": str(net.id),
                "device_id": str(vm.id),
                "fixed_ips": [{"ip_address": "192.168.2.1"}]
            }
        }
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL, params=json.dumps(request),
                                 user=vm.userid)
        self.assertEqual(response.status_code, 201)
        new_port_ip = json.loads(response.content)["port"]["fixed_ips"][0]
        self.assertEqual(new_port_ip["ip_address"], "192.168.2.1")

        # But 409 if address is already used
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL, params=json.dumps(request),
                                 user=vm.userid)
        self.assertConflict(response)

        # And bad request if IPv6 address is specified
        request["port"]["fixed_ips"][0]["ip_address"] = "babe::"
        with override_settings(settings, GANETI_USE_HOTPLUG=True):
            response = self.post(PORTS_URL, params=json.dumps(request),
                                 user=vm.userid)
        self.assertBadRequest(response)
Ejemplo n.º 33
0
 def test_invalid_create(self):
     """Test invalid flavor"""
     request = {'network': {}}
     response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
     self.assertBadRequest(response)
     request = {'network': {"type": "foo"}}
     response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
     self.assertBadRequest(response)
     request = {'network': {"type": "MAC_FILTERED"}}
     with override_settings(settings,
                            API_ENABLED_NETWORK_FLAVORS=["CUSTOM"]):
         response = self.post(NETWORKS_URL, "user1",
                              params=json.dumps(request))
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(Network.objects.filter(userid='user1')), 0)
Ejemplo n.º 34
0
    def test_active_server(self):
        """Test console req for ACTIVE server"""
        vm = mfactory.VirtualMachineFactory()
        vm.operstate = "STARTED"
        vm.save()

        data = json.dumps({"console": {"type": "vnc"}})
        with override_settings(settings, TEST=True):
            response = self.mypost("servers/%d/action" % vm.id, vm.userid, data, "json")
        self.assertEqual(response.status_code, 200)
        reply = json.loads(response.content)
        self.assertEqual(reply.keys(), ["console"])
        console = reply["console"]
        self.assertEqual(console["type"], "vnc")
        self.assertEqual(set(console.keys()), set(["type", "host", "port", "password"]))
Ejemplo n.º 35
0
 def test_create_port_private_net(self, mrapi):
     net = dbmf.NetworkFactory(public=False)
     dbmf.IPv4SubnetFactory(network=net)
     dbmf.IPv6SubnetFactory(network=net)
     sg1 = dbmf.SecurityGroupFactory()
     sg2 = dbmf.SecurityGroupFactory()
     vm = dbmf.VirtualMachineFactory(userid=net.userid)
     request = {
         "port": {
             "name": "port1",
             "network_id": str(net.id),
             "device_id": str(vm.id),
             "security_groups": [str(sg1.id), str(sg2.id)]
         }
     }
     mrapi().ModifyInstance.return_value = 42
     with override_settings(settings, GANETI_USE_HOTPLUG=False):
         response = self.post(PORTS_URL, params=json.dumps(request),
                              user=net.userid)
     self.assertEqual(response.status_code, 400)
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.post(PORTS_URL, params=json.dumps(request),
                              user=net.userid)
     self.assertEqual(response.status_code, 201)
Ejemplo n.º 36
0
    def test_create_server_error(self, mrapi):
        """Test if the create server call returns the expected response
           if a valid request has been speficied."""
        mrapi().CreateInstance.side_effect = GanetiApiError("..ganeti is down")

        request = self.request
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost("servers", "test_user", json.dumps(request), "json")
        self.assertEqual(response.status_code, 202)
        mrapi().CreateInstance.assert_called_once()
        vm = VirtualMachine.objects.get()
        # The VM has not been deleted
        self.assertFalse(vm.deleted)
        # but is in "ERROR" operstate
        self.assertEqual(vm.operstate, "ERROR")
Ejemplo n.º 37
0
    def test_create_server_error(self, mrapi):
        """Test if the create server call returns the expected response
           if a valid request has been speficied."""
        mrapi().CreateInstance.side_effect = GanetiApiError("..ganeti is down")

        request = self.request
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', 'test_user',
                                       json.dumps(request), 'json')
        self.assertEqual(response.status_code, 202)
        mrapi().CreateInstance.assert_called_once()
        vm = VirtualMachine.objects.get()
        # The VM has not been deleted
        self.assertFalse(vm.deleted)
        # but is in "ERROR" operstate
        self.assertEqual(vm.operstate, "ERROR")
Ejemplo n.º 38
0
    def test_active_server(self):
        """Test console req for ACTIVE server"""
        vm = mfactory.VirtualMachineFactory()
        vm.operstate = 'STARTED'
        vm.save()

        data = json.dumps({'console': {'type': 'vnc'}})
        with override_settings(settings, TEST=True):
            response = self.mypost('servers/%d/action' % vm.id, vm.userid,
                                   data, 'json')
        self.assertEqual(response.status_code, 200)
        reply = json.loads(response.content)
        self.assertEqual(reply.keys(), ['console'])
        console = reply['console']
        self.assertEqual(console['type'], 'vnc')
        self.assertEqual(set(console.keys()),
                         set(['type', 'host', 'port', 'password']))
Ejemplo n.º 39
0
 def test_create_port_with_floating_ip(self, mrapi):
     vm = dbmf.VirtualMachineFactory()
     fip = dbmf.FloatingIPFactory(network__public=True, nic=None,
                                  userid=vm.userid)
     request = {
         "port": {
             "name": "Port in the \u2601",
             "network_id": str(fip.network_id),
             "device_id": str(vm.id),
             "fixed_ips": [{"ip_address": fip.address}]
         }
     }
     mrapi().ModifyInstance.return_value = 42
     with override_settings(settings, GANETI_USE_HOTPLUG=True):
         response = self.post(PORTS_URL, params=json.dumps(request),
                              user=vm.userid)
     self.assertEqual(response.status_code, 201)
Ejemplo n.º 40
0
    def test_create_server(self, mrapi):
        """Test if the create server call returns the expected response
           if a valid request has been speficied."""

        mrapi().CreateInstance.return_value = 12
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost("servers", "test_user", json.dumps(self.request), "json")
        self.assertEqual(response.status_code, 202)
        mrapi().CreateInstance.assert_called_once()

        api_server = json.loads(response.content)["server"]
        self.assertEqual(api_server["status"], "BUILD")
        self.assertEqual(api_server["progress"], 0)
        self.assertEqual(api_server["metadata"][u"Meta \u2601"], u"Meta in the \u2601")
        self.assertTrue("adminPass" in api_server)

        db_vm = VirtualMachine.objects.get(userid="test_user")
        self.assertEqual(api_server["name"], u"Server in the \u2601")
        self.assertEqual(api_server["status"], db_vm.operstate)
Ejemplo n.º 41
0
    def test_create_server(self, mrapi):
        """Test if the create server call returns the expected response
           if a valid request has been speficied."""

        mrapi().CreateInstance.return_value = 12
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', 'test_user',
                                       json.dumps(self.request), 'json')
        self.assertEqual(response.status_code, 202)
        mrapi().CreateInstance.assert_called_once()

        api_server = json.loads(response.content)['server']
        self.assertEqual(api_server['status'], "BUILD")
        self.assertEqual(api_server['progress'], 0)
        self.assertEqual(api_server['metadata'][u"Meta \u2601"],
                         u"Meta in the \u2601")
        self.assertTrue('adminPass' in api_server)

        db_vm = VirtualMachine.objects.get(userid='test_user')
        self.assertEqual(api_server['name'], u"Server in the \u2601")
        self.assertEqual(api_server['status'], db_vm.operstate)
Ejemplo n.º 42
0
    def test_create_server(self, mrapi):
        """Test if the create server call returns the expected response
           if a valid request has been speficied."""

        mrapi().CreateInstance.return_value = 12
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', 'test_user',
                                       json.dumps(self.request), 'json')
        self.assertEqual(response.status_code, 202)
        self.assertEqual(1, mrapi().CreateInstance.call_count)

        api_server = json.loads(response.content)['server']
        self.assertEqual(api_server['status'], "BUILD")
        self.assertEqual(api_server['progress'], 0)
        self.assertEqual(api_server['metadata'][u"Meta \u2601"],
                         u"Meta in the \u2601")
        self.assertTrue('adminPass' in api_server)

        db_vm = VirtualMachine.objects.get(userid='test_user')
        self.assertEqual(api_server['name'], u"Server in the \u2601")
        self.assertEqual(api_server['status'], db_vm.operstate)
Ejemplo n.º 43
0
    def test_create(self, mrapi):
        flavor = mfactory.FlavorFactory()
        kwargs = {
            "userid": "test",
            "name": "test_vm",
            "password": "******",
            "flavor": flavor,
            "image_id": "safs",
            "networks": [],
            "metadata": {
                "foo": "bar"
            },
            "personality": [],
        }
        # no backend!
        mfactory.BackendFactory(offline=True)
        self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        mfactory.IPv4SubnetFactory(network__public=True)
        mfactory.IPv6SubnetFactory(network__public=True)
        backend = mfactory.BackendFactory()

        # error in nics
        req = deepcopy(kwargs)
        req["networks"] = [{"uuid": 42}]
        self.assertRaises(faults.ItemNotFound, servers.create, **req)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        # error in enqueue. check the vm is deleted and resources released
        mrapi().CreateInstance.side_effect = Exception("ganeti is down")
        with mocked_quotaholder():
            servers.create(**kwargs)
        vm = models.VirtualMachine.objects.get()
        self.assertFalse(vm.deleted)
        self.assertEqual(vm.operstate, "ERROR")
        for nic in vm.nics.all():
            self.assertEqual(nic.state, "ERROR")

        # test ext settings:
        req = deepcopy(kwargs)
        ext_flavor = mfactory.FlavorFactory(
            volume_type__disk_template="ext_archipelago", disk=1)
        req["flavor"] = ext_flavor
        mrapi().CreateInstance.return_value = 42
        backend.disk_templates = ["ext"]
        backend.save()
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }
        with mocked_quotaholder():
            with override_settings(settings, **osettings):
                vm = servers.create(**req)
        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        self.assertEqual(
            kwargs["disks"][0], {
                "provider": "archipelago",
                "origin": "test_mapfile",
                "origin_size": 1000,
                "name": vm.volumes.all()[0].backend_volume_uuid,
                "foo": "mpaz",
                "lala": "lolo",
                "size": 1024
            })
Ejemplo n.º 44
0
    def test_create(self, mrapi):
        flavor = mfactory.FlavorFactory()
        kwargs = {
            "credentials": self.credentials,
            "name": "test_vm",
            "password": "******",
            "flavor": flavor,
            "image_id": "safs",
            "networks": [],
            "metadata": {"foo": "bar"},
            "personality": [],
        }
        # no backend!
        mfactory.BackendFactory(offline=True)
        self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        mfactory.IPv4SubnetFactory(network__public=True)
        mfactory.IPv6SubnetFactory(network__public=True)
        backend = mfactory.BackendFactory()

        # error in nics
        req = deepcopy(kwargs)
        req["networks"] = [{"uuid": 42}]
        self.assertRaises(faults.ItemNotFound, servers.create, **req)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        # error in enqueue. check the vm is deleted and resources released
        mrapi().CreateInstance.side_effect = Exception("ganeti is down")
        with mocked_quotaholder():
            servers.create(**kwargs)
        vm = models.VirtualMachine.objects.get()
        self.assertFalse(vm.deleted)
        self.assertEqual(vm.operstate, "ERROR")
        for nic in vm.nics.all():
            self.assertEqual(nic.state, "ERROR")

        # test ext settings:
        req = deepcopy(kwargs)
        vlmt = mfactory.VolumeTypeFactory(disk_template='ext_archipelago')
        # Generate 4 specs. 2 prefixed with GNT_EXTP_VOLTYPESPEC_PREFIX
        # and 2 with an other prefix that should be omitted
        volume_type_specs = [
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='%sbar' % GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='%sfoo' % GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='other-prefx-baz'),
            mfactory.VolumeTypeSpecsFactory(
                volume_type=vlmt, key='another-prefix-biz'),
        ]

        gnt_prefixed_specs = filter(lambda s: s.key.startswith(
            GNT_EXTP_VOLTYPESPEC_PREFIX), volume_type_specs)
        ext_flavor = mfactory.FlavorFactory(
            volume_type=vlmt,
            disk=1)
        req["flavor"] = ext_flavor
        mrapi().CreateInstance.return_value = 42
        backend.disk_templates = ["ext"]
        backend.save()
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }
        with mocked_quotaholder():
            with override_settings(settings, **osettings):
                with patch(
                    'synnefo.logic.backend_allocator.update_backends_disk_templates'  # noqa E265
                ) as update_disk_templates_mock:
                    # Check that between the `get_available_backends` call
                    # and the `update_backend_disk_templates` call
                    # the backend doesn't change.
                    update_disk_templates_mock.return_value = [backend]
                    vm = servers.create(**req)

        update_disk_templates_mock.assert_called_once_with([backend])
        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        disk_kwargs = {"provider": "archipelago",
                       "origin": "test_mapfile",
                       "origin_size": 1000,
                       "name": vm.volumes.all()[0].backend_volume_uuid,
                       "foo": "mpaz",
                       "lala": "lolo",
                       "size": 1024}
        disk_kwargs.update({spec.key[len(GNT_EXTP_VOLTYPESPEC_PREFIX):]:
                            spec.value
                            for spec in gnt_prefixed_specs})
        self.assertEqual(kwargs["disks"][0], disk_kwargs)
Ejemplo n.º 45
0
    def test_url_resolving(self):
        """Test if URL resolving works properly.

        Check if the ADMIN_BASE_URL setting is used by Admin and if we have any
        issues with slashes and redirections.
        """
        ##
        # Test 1 - Default Admin URL.
        #
        # By default, the BASE_PATH for Admin is '/admin/'.
        r = resolve('/admin/')
        self.assertEqual(r.url_name, 'admin-default')

        # If we try to resolve the BASE_PATH without the slash, then we should
        # get redirected to the correct ('/admin/') URL.
        r = resolve('/admin')
        self.assertEqual(r.url_name, 'django.views.generic.simple.redirect_to')
        self.assertEqual(r.args, ())
        self.assertEqual(r.kwargs, {'url': 'admin/'})

        # Any URL that starts with the '/admin' string but has extra characters
        # should return 404.
        with self.assertRaises(Resolver404):
            r = resolve('/adminandoopstoomanychars')

        ##
        # Test 2 - Custom Admin URL with suffix. This tests if URL resolving
        # works properly when using a custom ADMIN_BASE_URL with a unique
        # suffix.

        # Change the ADMIN_BASE_URL and update the URLpatterns of Synnefo.
        with override_settings(settings, ADMIN_BASE_URL=URL1):
            reload_urlconf()

            # Check that the '/admin/' URL no longer works.
            with self.assertRaises(Resolver404):
                r = resolve('/admin/')

            # The new BASE_PATH should be 'rand0m'. Check if the resolved view
            # is the expected.
            r = resolve('/rand0m/')
            self.assertEqual(r.url_name, 'admin-default')

            # Check if resolving the BASE_PATH without a slash redirects us
            # properly.
            r = resolve('/rand0m')
            self.assertEqual(r.url_name,
                             'django.views.generic.simple.redirect_to')
            self.assertEqual(r.args, ())
            self.assertEqual(r.kwargs, {'url': 'rand0m/'})

            # Check if extra characters return 404.
            with self.assertRaises(Resolver404):
                r = resolve('/rand0mandoopstoomanychars')

        ##
        # Test 3 - Custom Admin URL without suffix. This tests if URL resolving
        # works properly when using a custom ADMIN_BASE_URL that points to a
        # node only, with no extra suffix.

        # Although Admin can be installed in a separate node from the
        # Cyclades/Astakos nodes, their packages - and by extension their
        # URLPatterns - will be installed in the Admin node. In order to "hide"
        # their urls, we will use the Admin urls as our ROOT_URLCONF for this
        # part of the test.
        with override_settings(settings, ADMIN_BASE_URL=URL2):
            reload_urlconf('synnefo_admin.urls')

            # Check that hitting the node URL sends us to Admin.
            r = resolve('/')
            self.assertEqual(r.url_name, 'admin-default')
Ejemplo n.º 46
0
    def test_url_resolving(self):
        """Test if URL resolving works properly.

        Check if the ADMIN_BASE_URL setting is used by Admin and if we have any
        issues with slashes and redirections.
        """
        ##
        # Test 1 - Default Admin URL.
        #
        # By default, the BASE_PATH for Admin is '/admin/'.
        r = resolve('/admin/')
        self.assertEqual(r.url_name, 'admin-default')

        # If we try to resolve the BASE_PATH without the slash, then we should
        # get redirected to the correct ('/admin/') URL.
        r = resolve('/admin')
        self.assertEqual(r.url_name, 'django.views.generic.simple.redirect_to')
        self.assertEqual(r.args, ())
        self.assertEqual(r.kwargs, {'url': 'admin/'})

        # Any URL that starts with the '/admin' string but has extra characters
        # should return 404.
        with self.assertRaises(Resolver404):
            r = resolve('/adminandoopstoomanychars')

        ##
        # Test 2 - Custom Admin URL with suffix. This tests if URL resolving
        # works properly when using a custom ADMIN_BASE_URL with a unique
        # suffix.

        # Change the ADMIN_BASE_URL and update the URLpatterns of Synnefo.
        with override_settings(settings, ADMIN_BASE_URL=URL1):
            reload_urlconf()

            # Check that the '/admin/' URL no longer works.
            with self.assertRaises(Resolver404):
                r = resolve('/admin/')

            # The new BASE_PATH should be 'rand0m'. Check if the resolved view
            # is the expected.
            r = resolve('/rand0m/')
            self.assertEqual(r.url_name, 'admin-default')

            # Check if resolving the BASE_PATH without a slash redirects us
            # properly.
            r = resolve('/rand0m')
            self.assertEqual(r.url_name,
                             'django.views.generic.simple.redirect_to')
            self.assertEqual(r.args, ())
            self.assertEqual(r.kwargs, {'url': 'rand0m/'})

            # Check if extra characters return 404.
            with self.assertRaises(Resolver404):
                r = resolve('/rand0mandoopstoomanychars')

        ##
        # Test 3 - Custom Admin URL without suffix. This tests if URL resolving
        # works properly when using a custom ADMIN_BASE_URL that points to a
        # node only, with no extra suffix.

        # Although Admin can be installed in a separate node from the
        # Cyclades/Astakos nodes, their packages - and by extension their
        # URLPatterns - will be installed in the Admin node. In order to "hide"
        # their urls, we will use the Admin urls as our ROOT_URLCONF for this
        # part of the test.
        with override_settings(settings, ADMIN_BASE_URL=URL2):
            reload_urlconf('synnefo_admin.urls')

            # Check that hitting the node URL sends us to Admin.
            r = resolve('/')
            self.assertEqual(r.url_name, 'admin-default')
Ejemplo n.º 47
0
    def test_create(self, mrapi):
        flavor = mfactory.FlavorFactory()
        kwargs = {
            "userid": "test",
            "name": "test_vm",
            "password": "******",
            "flavor": flavor,
            "image_id": "safs",
            "networks": [],
            "metadata": {"foo": "bar"},
            "personality": [],
        }
        # no backend!
        mfactory.BackendFactory(offline=True)
        self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        mfactory.IPv4SubnetFactory(network__public=True)
        mfactory.IPv6SubnetFactory(network__public=True)
        backend = mfactory.BackendFactory()

        # error in nics
        req = deepcopy(kwargs)
        req["networks"] = [{"uuid": 42}]
        self.assertRaises(faults.ItemNotFound, servers.create, **req)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        # error in enqueue. check the vm is deleted and resources released
        mrapi().CreateInstance.side_effect = Exception("ganeti is down")
        with mocked_quotaholder():
            servers.create(**kwargs)
        vm = models.VirtualMachine.objects.get()
        self.assertFalse(vm.deleted)
        self.assertEqual(vm.operstate, "ERROR")
        for nic in vm.nics.all():
            self.assertEqual(nic.state, "ERROR")

        # test ext settings:
        req = deepcopy(kwargs)
        ext_flavor = mfactory.FlavorFactory(
            volume_type__disk_template="ext_archipelago",
            disk=1)
        req["flavor"] = ext_flavor
        mrapi().CreateInstance.return_value = 42
        backend.disk_templates = ["ext"]
        backend.save()
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }
        with mocked_quotaholder():
            with override_settings(settings, **osettings):
                with patch(
                    'synnefo.logic.backend_allocator.update_backends_disk_templates'
                ) as update_disk_templates_mock:
                    # Check that between the `get_available_backends` call
                    # and the `update_backend_disk_templates` call
                    # the backend doesn't change.
                    update_disk_templates_mock.return_value = [backend]
                    vm = servers.create(**req)

        update_disk_templates_mock.assert_called_once_with([backend], ext_flavor)
        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        self.assertEqual(kwargs["disks"][0],
                         {"provider": "archipelago",
                          "origin": "test_mapfile",
                          "origin_size": 1000,
                          "name": vm.volumes.all()[0].backend_volume_uuid,
                          "foo": "mpaz",
                          "lala": "lolo",
                          "size": 1024})
Ejemplo n.º 48
0
    def test_create(self, mrapi):
        flavor = mfactory.FlavorFactory()
        kwargs = {
            "credentials": self.credentials,
            "name": "test_vm",
            "password": "******",
            "flavor": flavor,
            "image_id": "safs",
            "networks": [],
            "metadata": {
                "foo": "bar"
            },
            "personality": [],
        }
        # no backend!
        mfactory.BackendFactory(offline=True)
        self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        mfactory.IPv4SubnetFactory(network__public=True)
        mfactory.IPv6SubnetFactory(network__public=True)
        backend = mfactory.BackendFactory()

        # error in nics
        req = deepcopy(kwargs)
        req["networks"] = [{"uuid": 42}]
        self.assertRaises(faults.ItemNotFound, servers.create, **req)
        self.assertEqual(models.VirtualMachine.objects.count(), 0)

        # error in enqueue. check the vm is deleted and resources released
        mrapi().CreateInstance.side_effect = Exception("ganeti is down")
        with mocked_quotaholder():
            servers.create(**kwargs)
        vm = models.VirtualMachine.objects.get()
        self.assertFalse(vm.deleted)
        self.assertEqual(vm.operstate, "ERROR")
        for nic in vm.nics.all():
            self.assertEqual(nic.state, "ERROR")

        # test ext settings:
        req = deepcopy(kwargs)
        vlmt = mfactory.VolumeTypeFactory(disk_template='ext_archipelago')
        # Generate 4 specs. 2 prefixed with GNT_EXTP_VOLTYPESPEC_PREFIX
        # and 2 with an other prefix that should be omitted
        volume_type_specs = [
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='%sbar' %
                                            GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='%sfoo' %
                                            GNT_EXTP_VOLTYPESPEC_PREFIX),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='other-prefx-baz'),
            mfactory.VolumeTypeSpecsFactory(volume_type=vlmt,
                                            key='another-prefix-biz'),
        ]

        gnt_prefixed_specs = filter(
            lambda s: s.key.startswith(GNT_EXTP_VOLTYPESPEC_PREFIX),
            volume_type_specs)
        ext_flavor = mfactory.FlavorFactory(volume_type=vlmt, disk=1)
        req["flavor"] = ext_flavor
        mrapi().CreateInstance.return_value = 42
        backend.disk_templates = ["ext"]
        backend.save()
        osettings = {
            "GANETI_DISK_PROVIDER_KWARGS": {
                "archipelago": {
                    "foo": "mpaz",
                    "lala": "lolo"
                }
            }
        }
        with mocked_quotaholder():
            with override_settings(settings, **osettings):
                with patch(
                        'synnefo.logic.backend_allocator.update_backends_disk_templates'  # noqa E265
                ) as update_disk_templates_mock:
                    # Check that between the `get_available_backends` call
                    # and the `update_backend_disk_templates` call
                    # the backend doesn't change.
                    update_disk_templates_mock.return_value = [backend]
                    vm = servers.create(**req)

        update_disk_templates_mock.assert_called_once_with([backend])
        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        disk_kwargs = {
            "provider": "archipelago",
            "origin": "test_mapfile",
            "origin_size": 1000,
            "name": vm.volumes.all()[0].backend_volume_uuid,
            "foo": "mpaz",
            "lala": "lolo",
            "size": 1024
        }
        disk_kwargs.update({
            spec.key[len(GNT_EXTP_VOLTYPESPEC_PREFIX):]: spec.value
            for spec in gnt_prefixed_specs
        })
        self.assertEqual(kwargs["disks"][0], disk_kwargs)
Ejemplo n.º 49
0
    def test_create_network_info(self, mrapi):
        mrapi().CreateInstance.return_value = 12

        # User requested private networks
        s1 = mfactory.IPv4SubnetFactory(network__userid="test")
        s2 = mfactory.IPv6SubnetFactory(network__userid="test")
        # and a public IPv6
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id},
                                         {"uuid": s2.network_id}]
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', "test",
                                       json.dumps(request), 'json')
        self.assertEqual(response.status_code, 202)
        name, args, kwargs = mrapi().CreateInstance.mock_calls[0]
        self.assertEqual(len(kwargs["nics"]), 3)
        self.assertEqual(kwargs["nics"][0]["network"], self.net6.backend_id)
        self.assertEqual(kwargs["nics"][1]["network"], s1.network.backend_id)
        self.assertEqual(kwargs["nics"][2]["network"], s2.network.backend_id)

        # but fail if others user network
        s3 = mfactory.IPv6SubnetFactory(network__userid="test_other")
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s3.network_id}]
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 404)

        # User requested public networks
        # but no floating IP..
        s1 = mfactory.IPv4SubnetFactory(network__public=True)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id}]
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 409)

        # Add one floating IP
        fp1 = mfactory.IPv4AddressFactory(userid="test", subnet=s1,
                                          network=s1.network,
                                          floating_ip=True, nic=None)
        self.assertEqual(fp1.nic, None)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id,
                                          "fixed_ip": fp1.address}]
        with mocked_quotaholder():
            with override_settings(settings, **self.network_settings):
                response = self.mypost('servers', "test",
                                       json.dumps(request), 'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        fp1 = IPAddress.objects.get(id=fp1.id)
        self.assertEqual(fp1.nic.machine_id, server_id)

        # check used floating IP
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 409)

        # Add more floating IP. but check auto-reserve
        fp2 = mfactory.IPv4AddressFactory(userid="test", subnet=s1,
                                          network=s1.network,
                                          floating_ip=True, nic=None)
        self.assertEqual(fp2.nic, None)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id}]
        with mocked_quotaholder():
            with override_settings(settings, **self.network_settings):
                response = self.mypost('servers', "test",
                                       json.dumps(request), 'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        fp2 = IPAddress.objects.get(id=fp2.id)
        self.assertEqual(fp2.nic.machine_id, server_id)

        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        self.assertEqual(len(kwargs["nics"]), 2)
        self.assertEqual(kwargs["nics"][0]["network"], self.net6.backend_id)
        self.assertEqual(kwargs["nics"][1]["network"], fp2.network.backend_id)
Ejemplo n.º 50
0
    def test_create_network_info(self, mrapi):
        mrapi().CreateInstance.return_value = 12

        # User requested private networks
        s1 = mfactory.IPv4SubnetFactory(network__userid="test")
        s2 = mfactory.IPv6SubnetFactory(network__userid="test")
        # and a public IPv6
        request = deepcopy(self.request)
        request["server"]["networks"] = [{
            "uuid": s1.network_id
        }, {
            "uuid": s2.network_id
        }]
        with override_settings(settings, **self.network_settings):
            with mocked_quotaholder():
                response = self.mypost('servers', "test", json.dumps(request),
                                       'json')
        self.assertEqual(response.status_code, 202)
        name, args, kwargs = mrapi().CreateInstance.mock_calls[0]
        self.assertEqual(len(kwargs["nics"]), 3)
        self.assertEqual(kwargs["nics"][0]["network"], self.net6.backend_id)
        self.assertEqual(kwargs["nics"][1]["network"], s1.network.backend_id)
        self.assertEqual(kwargs["nics"][2]["network"], s2.network.backend_id)

        # but fail if others user network
        s3 = mfactory.IPv6SubnetFactory(network__userid="test_other")
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s3.network_id}]
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 404)

        # User requested public networks
        # but no floating IP..
        s1 = mfactory.IPv4SubnetFactory(network__public=True)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id}]
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 409)

        # Add one floating IP
        fp1 = mfactory.IPv4AddressFactory(userid="test",
                                          subnet=s1,
                                          network=s1.network,
                                          floating_ip=True,
                                          nic=None)
        self.assertEqual(fp1.nic, None)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{
            "uuid": s1.network_id,
            "fixed_ip": fp1.address
        }]
        with mocked_quotaholder():
            with override_settings(settings, **self.network_settings):
                response = self.mypost('servers', "test", json.dumps(request),
                                       'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        fp1 = IPAddress.objects.get(id=fp1.id)
        self.assertEqual(fp1.nic.machine_id, server_id)

        # check used floating IP
        response = self.mypost('servers', "test", json.dumps(request), 'json')
        self.assertEqual(response.status_code, 409)

        # Add more floating IP. but check auto-reserve
        fp2 = mfactory.IPv4AddressFactory(userid="test",
                                          subnet=s1,
                                          network=s1.network,
                                          floating_ip=True,
                                          nic=None)
        self.assertEqual(fp2.nic, None)
        request = deepcopy(self.request)
        request["server"]["networks"] = [{"uuid": s1.network_id}]
        with mocked_quotaholder():
            with override_settings(settings, **self.network_settings):
                response = self.mypost('servers', "test", json.dumps(request),
                                       'json')
        self.assertEqual(response.status_code, 202)
        server_id = json.loads(response.content)["server"]["id"]
        fp2 = IPAddress.objects.get(id=fp2.id)
        self.assertEqual(fp2.nic.machine_id, server_id)

        name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
        self.assertEqual(len(kwargs["nics"]), 2)
        self.assertEqual(kwargs["nics"][0]["network"], self.net6.backend_id)
        self.assertEqual(kwargs["nics"][1]["network"], fp2.network.backend_id)