class TestSharedTarget(JobTestCaseWithHost):
    mock_servers = {
        "pair1": {
            "fqdn": "pair1.mycompany.com",
            "nodename": "test01.pair1.mycompany.com",
            "nids": [Nid.Nid("192.168.0.1", "tcp", 0)],
        },
        "pair2": {
            "fqdn": "pair2.mycompany.com",
            "nodename": "test02.pair2.mycompany.com",
            "nids": [Nid.Nid("192.168.0.2", "tcp", 0)],
        },
    }

    def setUp(self):
        super(TestSharedTarget, self).setUp()

        (mgt, fs, mdt, ost) = create_simple_fs()
        self.mgt = mgt

        self.assertEqual(
            ManagedMgs.objects.get(pk=self.mgt.pk).state, "unmounted")

    def test_clean_setup(self):
        # Start it normally the way the API would on creation
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, "mounted")
        self.assertEqual(
            ManagedTarget.objects.get(pk=self.mgt.pk).state, "mounted")
Ejemplo n.º 2
0
    def setUp(self):
        super(TestHostResource, self).setUp()

        MockAgentRpc.mock_servers = {
            "foo": {
                "fqdn": "foo.mycompany.com",
                "nodename": "test01.foo.mycompany.com",
                "nids": [Nid.Nid("192.168.0.19", "tcp", 0)],
            },
            "bar": {
                "fqdn": "bar.mycompany.com",
                "nodename": "test01.bar.mycompany.com",
                "nids": [Nid.Nid("192.168.0.91", "tcp", 0)],
            },
        }
Ejemplo n.º 3
0
    def setUp(self):
        super(TestHostResource, self).setUp()

        MockAgentRpc.mock_servers = {
            'foo': {
                'fqdn': 'foo.mycompany.com',
                'nodename': 'test01.foo.mycompany.com',
                'nids': [Nid.Nid("192.168.0.19", "tcp", 0)]
            },
            'bar': {
                'fqdn': 'bar.mycompany.com',
                'nodename': 'test01.bar.mycompany.com',
                'nids': [Nid.Nid("192.168.0.91", "tcp", 0)]
            }
        }
Ejemplo n.º 4
0
    def setUp(self):
        super(TestHostResource, self).setUp()

        self.host = {
            'fqdn': 'foo.mycompany.com',
            'nodename': 'foo.mycompany.com',
            'nids': [Nid.Nid("192.168.0.19", "tcp", 0)]
        }

        MockAgentRpc.mock_servers = {'foo': self.host}

        self.api_post('/api/host/',
                      data={
                          'address': 'foo',
                          'server_profile': '/api/server_profile/test_profile/'
                      })
        self._lnetinfo = self._get_lnet_info(self.host)

        # Sanity check.
        self.assertEqual(self._lnetinfo.nids,
                         self._lnetinfo.lnet_configuration['nids'])

        mock.patch(
            'chroma_core.services.job_scheduler.job_scheduler_client.JobSchedulerClient.update_nids',
            new=mock.Mock(side_effect=mock_update_nids)).start()

        self.addCleanup(mock.patch.stopall)
class JobTestCaseWithHost(JobTestCase):
    mock_servers = {
        "myaddress": {
            "fqdn": "myaddress.mycompany.com",
            "nodename": "test01.myaddress.mycompany.com",
            "nids": [Nid.Nid("192.168.0.1", "tcp", 0)],
        }
    }

    @classmethod
    def setUpTestData(cls):
        super(JobTestCaseWithHost, cls).setUpTestData()

        cls.hosts = []
        for address, info in cls.mock_servers.items():
            host = synthetic_host(address=address,
                                  fqdn=info["fqdn"],
                                  nids=info["nids"],
                                  nodename=info["nodename"])
            cls.hosts.append(host)

    def setUp(self):
        super(JobTestCaseWithHost, self).setUp()

        for host in self.hosts:
            host.refresh_from_db()

        # Handy if you're only using one
        self.host = self.hosts[0]
class TestOneHost(JobTestCase):
    mock_servers = {
        "myaddress": {
            "fqdn": "myaddress.mycompany.com",
            "nodename": "test01.myaddress.mycompany.com",
            "nids": [Nid.Nid("192.168.0.1", "tcp", 0)],
        }
    }

    def setUp(self):
        super(TestOneHost, self).setUp()
        connection.use_debug_cursor = True

    def tearDown(self):
        super(TestOneHost, self).tearDown()
        connection.use_debug_cursor = False

    def test_one_host(self):
        try:
            dbperf.enabled = True

            with dbperf("create_from_string"):
                host = synthetic_host("myaddress")
            with dbperf("set_state"):
                self.set_state_delayed([(host, "managed")])
            with dbperf("run_next"):
                self.set_state_complete()
            self.assertState(host, "managed")
        finally:
            dbperf.enabled = False
Ejemplo n.º 7
0
 def _host_with_nids(self, address):
     host_nids = {
         "primary-mgs": [Nid.Nid("1.2.3.4", "tcp", 0)],
         "failover-mgs": [Nid.Nid("1.2.3.5", "tcp", 5)],
         "primary-mgs-twonid": [Nid.Nid("1.2.3.4", "tcp", 0), Nid.Nid("4.3.2.1", "tcp", 1)],
         "failover-mgs-twonid": [Nid.Nid("1.2.3.5", "tcp", 5), Nid.Nid("4.3.2.2", "tcp", 1)],
         "othernode": [Nid.Nid("1.2.3.6", "tcp", 0), Nid.Nid("4.3.2.3", "tcp", 1)],
     }
     return synthetic_host(address, host_nids[address])
Ejemplo n.º 8
0
 def _host_with_nids(self, address):
     host_nids = {
         'primary-mgs': [Nid.Nid('1.2.3.4', 'tcp', 0)],
         'failover-mgs': [Nid.Nid('1.2.3.5', 'tcp', 5)],
         'primary-mgs-twonid': [Nid.Nid('1.2.3.4', 'tcp', 0), Nid.Nid('4.3.2.1', 'tcp', 1)],
         'failover-mgs-twonid': [Nid.Nid('1.2.3.5', 'tcp', 5), Nid.Nid('4.3.2.2', 'tcp', 1)],
         'othernode': [Nid.Nid('1.2.3.6', 'tcp', 0), Nid.Nid('4.3.2.3', 'tcp', 1)]
     }
     return synthetic_host(address, host_nids[address])
    def run(self, kwargs):
        host_id = kwargs["host_id"]
        fqdn = kwargs["fqdn"]
        nid_updates = kwargs["config_changes"]["nid_updates"]
        nid_deletes = kwargs["config_changes"]["nid_deletes"]

        modprobe_entries = []
        nid_tuples = []

        network_interfaces = NetworkInterface.objects.filter(host__id=host_id)
        lnet_configuration = LNetConfiguration.objects.get(host__id=host_id)

        for network_interface in network_interfaces:
            # See if we have deleted the nid for this network interface or
            # see if we have a new configuration for this if we do then it
            # will replace the current configuration.
            #
            # The int will have become a string - we should use a PickledObjectField really.
            if str(network_interface.id) in nid_deletes:
                nid = None
            elif str(network_interface.id) in nid_updates:
                nid = Nid(
                    network_interface=network_interface,
                    lnet_configuration=lnet_configuration,
                    lnd_network=nid_updates[str(
                        network_interface.id)]["lnd_network"],
                    lnd_type=nid_updates[str(
                        network_interface.id)]["lnd_type"],
                )
            else:
                try:
                    nid = Nid.objects.get(network_interface=network_interface)
                except ObjectDoesNotExist:
                    nid = None
                    pass

            if nid is not None:
                modprobe_entries.append(nid.modprobe_entry)
                nid_tuples.append(nid.to_tuple)

        self.invoke_agent_expect_result(
            fqdn,
            "configure_lnet",
            {
                "lnet_configuration": {
                    "state": lnet_configuration.state,
                    "modprobe_entries": modprobe_entries,
                    "network_interfaces": nid_tuples,
                }
            },
        )
Ejemplo n.º 10
0
 def test_log_links(self):
     """Test that log viewer only displays valid links."""
     self.host = synthetic_host("myserver-with-nids",
                                [Nid.Nid("192.168.0.1", "tcp", 0)])
     self.create_simple_filesystem(self.host)
     fake_log_message("192.168.0.1@tcp testfs-MDT0000")
     response = self.api_client.get("/api/log/")
     event, = self.deserialize(response)["objects"]
     self.assertEqual(len(event["substitutions"]), 2)
     self.host.state = "removed"
     self.host.save()
     self.mdt.not_deleted = False
     self.mdt.save()
     response = self.api_client.get("/api/log/")
     event, = self.deserialize(response)["objects"]
     self.assertEqual(len(event["substitutions"]), 0)
def parse_synthentic_device_info(host_id, data):
    """ Parses the data returned from plugins for integration test purposes. On does lnet data because
        at present that is all we need. """

    # This creates nid tuples so it can use synthetic_host_create_lnet_configuration to do the
    # actual writes to the database
    for plugin, device_data in data.items():
        if plugin == "linux_network":
            if len(device_data["lnet"]["nids"]) > 0:
                nid_tuples = []

                for name, nid in device_data["lnet"]["nids"].items():
                    nid_tuples.append(Nid.Nid(nid["nid_address"], nid["lnd_type"], nid["lnd_network"]))
            else:
                nid_tuples = None

            synthetic_lnet_configuration(ManagedHost.objects.get(id=host_id), nid_tuples)
    def run(self, kwargs):
        host = kwargs['host']
        nid_updates = kwargs['config_changes']['nid_updates']
        nid_deletes = kwargs['config_changes']['nid_deletes']

        modprobe_entries = []
        nid_tuples = []

        network_interfaces = NetworkInterface.objects.filter(host=host)
        lnet_configuration = LNetConfiguration.objects.get(host=host)

        for network_interface in network_interfaces:
            # See if we have deleted the nid for this network interface or
            # see if we have a new configuration for this if we do then it
            # will replace the current configuration.
            #
            # The int will have become a string - we should use a PickledObjectField really.
            if str(network_interface.id) in nid_deletes:
                nid = None
            elif str(network_interface.id) in nid_updates:
                nid = Nid(network_interface=network_interface,
                          lnet_configuration=lnet_configuration,
                          lnd_network=nid_updates[str(
                              network_interface.id)]['lnd_network'],
                          lnd_type=nid_updates[str(
                              network_interface.id)]['lnd_type'])
            else:
                try:
                    nid = Nid.objects.get(network_interface=network_interface)
                except ObjectDoesNotExist:
                    nid = None
                    pass

            if nid is not None:
                modprobe_entries.append(nid.modprobe_entry)
                nid_tuples.append(nid.to_tuple)

        self.invoke_agent_expect_result(
            host, "configure_lnet", {
                'lnet_configuration': {
                    'state': lnet_configuration.state,
                    'modprobe_entries': modprobe_entries,
                    'network_interfaces': nid_tuples
                }
            })
Ejemplo n.º 13
0
def step(context, name):
    import os
    import json
    from chroma_core.models import Nid
    from tests.unit.chroma_core.helpers import MockAgentRpc

    # Skip setup if it was already done in a previous scenario.
    if len(MockAgentRpc.mock_servers) > 0:
        return

    path = os.path.join(os.path.dirname(__file__),
                        "../../../../sample_data/%s.json" % name)
    with open(path) as fh:
        data = json.load(fh)

    for host in data["hosts"]:
        host["nids"] = [Nid.split_nid_string(n) for n in host["nids"]]
        MockAgentRpc.mock_servers[host["address"]] = host
class JobTestCaseWithHost(JobTestCase):
    mock_servers = {
        "myaddress": {
            "fqdn": "myaddress.mycompany.com",
            "nodename": "test01.myaddress.mycompany.com",
            "nids": [Nid.Nid("192.168.0.1", "tcp", 0)],
        }
    }

    def setUp(self):
        super(JobTestCaseWithHost, self).setUp()

        self.hosts = []
        for address, info in self.mock_servers.items():
            host = synthetic_host(address=address,
                                  fqdn=info["fqdn"],
                                  nids=info["nids"],
                                  nodename=info["nodename"])
            self.hosts.append(host)

        # Handy if you're only using one
        self.host = self.hosts[0]
Ejemplo n.º 15
0
class JobTestCaseWithHost(JobTestCase):
    mock_servers = {
        'myaddress': {
            'fqdn': 'myaddress.mycompany.com',
            'nodename': 'test01.myaddress.mycompany.com',
            'nids': [Nid.Nid("192.168.0.1", "tcp", 0)]
        }
    }

    def setUp(self):
        super(JobTestCaseWithHost, self).setUp()

        self.hosts = []
        for address, info in self.mock_servers.items():
            host = synthetic_host(address=address,
                                  fqdn=info['fqdn'],
                                  nids=info['nids'],
                                  nodename=info['nodename'])
            self.hosts.append(host)

        # Handy if you're only using one
        self.host = self.hosts[0]
    def setUp(self):
        super(TestHostResource, self).setUp()

        self.host = {
            "fqdn": "foo.mycompany.com",
            "nodename": "foo.mycompany.com",
            "nids": [Nid.Nid("192.168.0.19", "tcp", 0)],
        }

        MockAgentRpc.mock_servers = {"foo": self.host}

        self.api_post("/api/host/", data={"address": "foo", "server_profile": "/api/server_profile/test_profile/"})
        self._lnetinfo = self._get_lnet_info(self.host)

        # Sanity check.
        self.assertEqual(self._lnetinfo.nids, self._lnetinfo.lnet_configuration["nids"])

        mock.patch(
            "chroma_core.services.job_scheduler.job_scheduler_client.JobSchedulerClient.update_nids",
            new=mock.Mock(side_effect=mock_update_nids),
        ).start()

        self.addCleanup(mock.patch.stopall)
 def lnd_types(self):
     return Nid.lnd_types_for_network_type(self.type)
Ejemplo n.º 18
0
class TestRegistration(IMLUnitTestCase):
    """API unit tests for functionality used only by the agent"""

    mock_servers = {
        "mynewhost": {
            "fqdn": "mynewhost.mycompany.com",
            "nodename": "test01.mynewhost.mycompany.com",
            "nids": [Nid.Nid("192.168.0.1", "tcp", 0)],
        }
    }

    def setUp(self):
        super(TestRegistration, self).setUp()

        load_default_profile()

        self.old_create_host = JobSchedulerClient.create_host
        JobSchedulerClient.create_host = mock.Mock(
            side_effect=lambda *args, **kwargs: (
                synthetic_host("mynewhost", **self.mock_servers["mynewhost"]),
                mock.Mock(id="bar"),
            ))
        ValidatedClientView.valid_certs = {}

    def tearDown(self):
        JobSchedulerClient.create_host = self.old_create_host

    def test_version(self):
        host_info = self.mock_servers["mynewhost"]
        with timed("csr", 10):
            data = {
                "fqdn": host_info["fqdn"],
                "nodename": host_info["nodename"],
                "version": "1.0",
                "capabilities": ["manage_targets"],
                "address": "mynewhost",
                "csr": generate_csr(host_info["fqdn"]),
            }

        with patch(settings, VERSION="2.0"):
            # Try with a mis-matched version
            token = RegistrationToken.objects.create(
                profile=ServerProfile.objects.get())
            with timed("register fail", 10):
                response = Client().post("/agent/register/%s/" % token.secret,
                                         data=json.dumps(data),
                                         content_type="application/json")
            self.assertEqual(response.status_code, 400)

            # Try with a matching version
            token = RegistrationToken.objects.create(
                profile=ServerProfile.objects.get())
            settings.VERSION = "1.1"
            with timed("register pass", 10):
                response = Client().post("/agent/register/%s/" % token.secret,
                                         data=json.dumps(data),
                                         content_type="application/json")
            self.assertEqual(response.status_code, 201)
            content = json.loads(response.content)

            # reregistration should fail with unknown serial
            data = {"address": "mynewhost", "fqdn": "mynewhost.newcompany.com"}
            headers = {
                "HTTP_X_SSL_CLIENT_NAME": host_info["fqdn"],
                "HTTP_X_SSL_CLIENT_SERIAL": ""
            }
            response = Client().post("/agent/reregister/",
                                     data=json.dumps(data),
                                     content_type="application/json",
                                     **headers)
            self.assertEqual(response.status_code, 403)

            # reregistration should update host's domain name
            headers["HTTP_X_SSL_CLIENT_SERIAL"] = Crypto().get_serial(
                content["certificate"])
            response = Client().post("/agent/reregister/",
                                     data=json.dumps(data),
                                     content_type="application/json",
                                     **headers)
            self.assertEqual(response.status_code, 200)
            host = ManagedHost.objects.get(id=content["host_id"])
            self.assertEqual(host.fqdn, data["fqdn"])
Ejemplo n.º 19
0
def load_filesystem_from_json(data):
    # Since this is only ever used for the behave tests, and the behave tests
    # are slated to be decommissioned at some point, we're just going to
    # abandon all pretense that we might be loading a non-synthetic cluster.
    from chroma_core.services.job_scheduler.job_scheduler_client import JobSchedulerClient
    from tests.unit.chroma_core.helpers import synthetic_volume
    from chroma_core.models import ManagedMgs, VolumeNode

    from chroma_core.lib.cache import ObjectCache
    from chroma_core.models import ManagedHost, ManagedTarget, ManagedTargetMount
    from chroma_core.models import Nid
    from tests.unit.chroma_core.helpers import synthetic_host

    lookup = defaultdict(dict)

    for host_info in data["hosts"]:
        from tests.unit.chroma_core.helpers import MockAgentRpc

        mock_host_info = MockAgentRpc.mock_servers[host_info["address"]]
        # host, command = JobSchedulerClient.create_host(mock_host_info['fqdn'], mock_host_info['nodename'], ['manage_targets'], address = host_info['address'])
        nids = [Nid.split_nid_string(n) for n in mock_host_info["nids"]]

        # update mock_servers with list of Nid objects
        MockAgentRpc.mock_servers[host_info["address"]]["nids"] = nids

        host = synthetic_host(mock_host_info["address"],
                              nids=nids,
                              fqdn=mock_host_info["fqdn"],
                              nodename=mock_host_info["nodename"])
        ObjectCache.add(ManagedHost, host)
        host.state = "managed"
        host.save()
        lookup["hosts"][host_info["address"]] = host

    def _create_volume_for_mounts(mounts):
        # The test data doesn't give us a serial, so mung one out of the device paths
        # on the basis that they're iSCSI-style
        serial = mounts[0]["device_node"].split("/")[-1]
        volume = synthetic_volume(serial=serial)
        for mount in mounts:
            VolumeNode.objects.create(host=lookup["hosts"][mount["host"]],
                                      path=mount["device_node"],
                                      primary=mount["primary"],
                                      volume=volume)
        return volume

    for mgs_info in data["mgss"]:
        volume = _create_volume_for_mounts(mgs_info["mounts"])
        target, target_mounts = ManagedMgs.create_for_volume(volume.id)
        target.uuid = uuid.uuid4().__str__()
        target.ha_label = "%s_%s" % (target.name, uuid.uuid4().__str__()[0:6])
        ObjectCache.add(ManagedTarget, target.managedtarget_ptr)
        for tm in target_mounts:
            ObjectCache.add(ManagedTargetMount, tm)
        lookup["mgt"][mgs_info["mounts"][0]["host"]] = target

    for fs_info in data["filesystems"]:
        fs_bundle = {
            "name": fs_info["name"],
            "mgt": {
                "id": lookup["mgt"][fs_info["mgs"]].id
            },
            "mdts": [],
            "osts": [],
            "conf_params": {},
        }

        for mdt_info in fs_info["mdts"]:
            volume = _create_volume_for_mounts(mdt_info["mounts"])

            # Although we create multiple volumes for the mdt, initially only add a single volume, once delete of MDT
            # is possible we can add them all and then delete before adding. This code is structured for that fixed case.
            if not fs_bundle["mdts"]:
                fs_bundle["mdts"].append({
                    "volume_id": volume.id,
                    "conf_params": {}
                })

        for ost_info in fs_info["osts"]:
            volume = _create_volume_for_mounts(ost_info["mounts"])
            fs_bundle["osts"].append({
                "volume_id": volume.id,
                "conf_params": {}
            })

        fs, command = JobSchedulerClient.create_filesystem(fs_bundle)
Ejemplo n.º 20
0
    def test_combined_mgs_mdt(self, invoke):
        invoke.return_value = '{"Ok": []}'

        def fixture_glob(g):
            return glob.glob(
                os.path.join(os.path.dirname(__file__),
                             "fixtures/test_combined_mgs_mdt", g))

        for path in fixture_glob("*_nid.txt"):
            address = os.path.basename(path).split("_")[0]
            nids = [
                Nid.split_nid_string(l.strip())
                for l in open(path).readlines()
            ]
            synthetic_host(address, nids)

        host_data = {}
        for path in fixture_glob("*detect_scan_output.txt"):
            address = os.path.basename(path).split("_")[0]
            data = json.load(open(path))["result"]
            host_data[ManagedHost.objects.get(address=address)] = data

        # Simplified volume construction:
        #  * Assume all device paths referenced in detection exist
        #  * Assume all devices visible on all hosts
        #  * Assume device node paths are identical on all hosts
        devpaths = set()
        for host, data in host_data.items():
            for lt in data["local_targets"]:
                for d in lt["device_paths"]:
                    if not d in devpaths:
                        devpaths.add(d)
                        volume = Volume.objects.create()
                        for host in host_data.keys():
                            VolumeNode.objects.create(volume=volume,
                                                      path=d,
                                                      host=host)

        def _detect_scan_device_plugin(host, command, args=None):
            self.assertIn(command, ["detect_scan", "device_plugin"])

            if command == "detect_scan":
                return host_data[host]

            raise AgentException(
                host, command, args,
                "No device plugin data available in unit tests")

        job = DetectTargetsJob.objects.create()

        with mock.patch("chroma_core.lib.job.Step.invoke_agent",
                        new=mock.Mock(side_effect=_detect_scan_device_plugin)):
            with mock.patch("chroma_core.models.Volume.storage_resource"):
                synchronous_run_job(job)

        self.assertEqual(ManagedFilesystem.objects.count(), 1)
        self.assertEqual(ManagedFilesystem.objects.get().name, "test18fs")

        self.assertEqual(ManagedOst.objects.count(), 8)

        for t in ManagedTarget.objects.all():
            self.assertEqual(t.immutable_state, True)

        def assertMount(target_name, primary_host, failover_hosts=list()):
            target = ManagedTarget.objects.get(name=target_name)
            self.assertEquals(
                ManagedTargetMount.objects.filter(target=target).count(),
                1 + len(failover_hosts))
            self.assertEquals(
                ManagedTargetMount.objects.filter(
                    target=target,
                    primary=True,
                    host=ManagedHost.objects.get(
                        address=primary_host)).count(),
                1,
            )
            for h in failover_hosts:
                self.assertEquals(
                    ManagedTargetMount.objects.filter(
                        target=target,
                        primary=False,
                        host=ManagedHost.objects.get(address=h)).count(),
                    1,
                )

        assertMount("MGS", "kp-lustre-1-8-mgs-1")
        assertMount("test18fs-MDT0000", "kp-lustre-1-8-mgs-1")
        assertMount("test18fs-OST0000", "kp-lustre-1-8-oss-1")
        assertMount("test18fs-OST0001", "kp-lustre-1-8-oss-1")
        assertMount("test18fs-OST0002", "kp-lustre-1-8-oss-2")
        assertMount("test18fs-OST0003", "kp-lustre-1-8-oss-2")
        assertMount("test18fs-OST0004", "kp-lustre-1-8-oss-3")
        assertMount("test18fs-OST0005", "kp-lustre-1-8-oss-3")
        assertMount("test18fs-OST0006", "kp-lustre-1-8-oss-4")
        assertMount("test18fs-OST0007", "kp-lustre-1-8-oss-4")

        self.assertEqual(ManagedFilesystem.objects.get().state, "available")
class TestRegistration(IMLUnitTestCase):
    """API unit tests for functionality used only by the agent"""
    mock_servers = {
        'mynewhost': {
            'fqdn': 'mynewhost.mycompany.com',
            'nodename': 'test01.mynewhost.mycompany.com',
            'nids': [Nid.Nid("192.168.0.1", "tcp", 0)],
        }
    }

    def setUp(self):
        super(TestRegistration, self).setUp()

        load_default_profile()

        self.old_create_host = JobSchedulerClient.create_host
        JobSchedulerClient.create_host = mock.Mock(
            side_effect=lambda *args, **kwargs:
            (synthetic_host('mynewhost', **self.mock_servers['mynewhost']),
             mock.Mock(id='bar')))
        ValidatedClientView.valid_certs = {}

    def tearDown(self):
        JobSchedulerClient.create_host = self.old_create_host

    def test_version(self):
        host_info = self.mock_servers['mynewhost']
        with timed('csr', 10):
            data = {
                'fqdn': host_info['fqdn'],
                'nodename': host_info['nodename'],
                'version': '1.0',
                'capabilities': ['manage_targets'],
                'address': 'mynewhost',
                'csr': generate_csr(host_info['fqdn']),
            }

        with patch(settings, VERSION='2.0'):
            # Try with a mis-matched version
            token = RegistrationToken.objects.create(
                profile=ServerProfile.objects.get())
            with timed('register fail', 10):
                response = Client().post("/agent/register/%s/" % token.secret,
                                         data=json.dumps(data),
                                         content_type="application/json")
            self.assertEqual(response.status_code, 400)

            # Try with a matching version
            token = RegistrationToken.objects.create(
                profile=ServerProfile.objects.get())
            settings.VERSION = '1.1'
            with timed('register pass', 10):
                response = Client().post("/agent/register/%s/" % token.secret,
                                         data=json.dumps(data),
                                         content_type="application/json")
            self.assertEqual(response.status_code, 201)
            content = json.loads(response.content)

            # reregistration should fail with unknown serial
            data = {'address': 'mynewhost', 'fqdn': 'mynewhost.newcompany.com'}
            headers = {
                'HTTP_X_SSL_CLIENT_NAME': host_info['fqdn'],
                'HTTP_X_SSL_CLIENT_SERIAL': ''
            }
            response = Client().post('/agent/reregister/',
                                     data=json.dumps(data),
                                     content_type='application/json',
                                     **headers)
            self.assertEqual(response.status_code, 403)

            # reregistration should update host's domain name
            headers['HTTP_X_SSL_CLIENT_SERIAL'] = Crypto().get_serial(
                content['certificate'])
            response = Client().post('/agent/reregister/',
                                     data=json.dumps(data),
                                     content_type='application/json',
                                     **headers)
            self.assertEqual(response.status_code, 200)
            host = ManagedHost.objects.get(id=content['host_id'])
            self.assertEqual(host.fqdn, data['fqdn'])
Ejemplo n.º 22
0
class TestSharedTarget(JobTestCaseWithHost):
    mock_servers = {
        'pair1': {
            'fqdn': 'pair1.mycompany.com',
            'nodename': 'test01.pair1.mycompany.com',
            'nids': [Nid.Nid("192.168.0.1", "tcp", 0)]
        },
        'pair2': {
            'fqdn': 'pair2.mycompany.com',
            'nodename': 'test02.pair2.mycompany.com',
            'nids': [Nid.Nid("192.168.0.2", "tcp", 0)]
        }
    }

    def setUp(self):
        super(TestSharedTarget, self).setUp()

        self.mgt, tms = ManagedMgs.create_for_volume(self._test_lun(
            ManagedHost.objects.get(address='pair1'),
            secondary_hosts=[ManagedHost.objects.get(address='pair2')]).id,
                                                     name="MGS")

        ObjectCache.add(ManagedTarget, self.mgt.managedtarget_ptr)
        for tm in tms:
            ObjectCache.add(ManagedTargetMount, tm)
        self.assertEqual(
            ManagedMgs.objects.get(pk=self.mgt.pk).state, 'unformatted')

    def test_clean_setup(self):
        # Start it normally the way the API would on creation
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'mounted')
        self.assertEqual(
            ManagedTarget.objects.get(pk=self.mgt.pk).state, 'mounted')
        self.assertEqual(
            ManagedTarget.objects.get(pk=self.mgt.pk).active_mount,
            ManagedTargetMount.objects.get(host=self.hosts[0],
                                           target=self.mgt))

    def test_teardown_unformatted(self):
        self.assertEqual(
            ManagedTarget.objects.get(pk=self.mgt.pk).state, 'unformatted')
        try:
            # We should need no agent ops to remove something we never formatted
            MockAgentRpc.succeed = False
            self.mgt.managedtarget_ptr = self.set_and_assert_state(
                self.mgt.managedtarget_ptr, 'removed')
        finally:
            MockAgentRpc.succeed = True

        with self.assertRaises(ManagedTarget.DoesNotExist):
            ManagedTarget.objects.get(pk=self.mgt.pk)

    def test_teardown_remove_primary_host(self):
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'mounted')
        self.set_and_assert_state(self.mgt.primary_host, 'removed')

        # Removing the primary server removes the target
        with self.assertRaises(ManagedTarget.DoesNotExist):
            ManagedTarget.objects.get(pk=self.mgt.pk)

    def test_teardown_remove_secondary_host(self):
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'mounted')
        self.set_and_assert_state(self.mgt.failover_hosts[0], 'removed')

        # Removing the secondary server removes the target
        with self.assertRaises(ManagedTarget.DoesNotExist):
            ManagedTarget.objects.get(pk=self.mgt.pk)

    def test_teardown_friendly_user(self):
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'mounted')

        # Friendly user stops the target
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'unmounted')

        # Friendly user removes the target
        self.mgt.managedtarget_ptr = self.set_and_assert_state(
            self.mgt.managedtarget_ptr, 'removed')
        with self.assertRaises(ManagedTarget.DoesNotExist):
            ManagedTarget.objects.get(pk=self.mgt.pk)

        # Friendly user removes the secondary host
        self.hosts[1] = self.set_and_assert_state(self.hosts[1], 'removed')

        # Friendly user removes the primary host
        self.hosts[0] = self.set_and_assert_state(self.hosts[0], 'removed')