当前位置: 首页>>代码示例>>Python>>正文


Python VimClient.disconnect方法代码示例

本文整理汇总了Python中host.hypervisor.esx.vim_client.VimClient.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python VimClient.disconnect方法的具体用法?Python VimClient.disconnect怎么用?Python VimClient.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在host.hypervisor.esx.vim_client.VimClient的用法示例。


在下文中一共展示了VimClient.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_update_fail_without_looping

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
 def test_update_fail_without_looping(self, connect_mock, update_mock):
     client = VimClient("esx.local", "root", "password", auto_sync=True,
                        min_interval=1)
     update_mock.side_effect = vim.fault.HostConnectFault
     time.sleep(0.5)
     client.disconnect(wait=True)
     assert_that(update_mock.call_count, less_than(4))  # no crazy loop
开发者ID:tomzhang,项目名称:photon-controller,代码行数:9,代码来源:test_vim_client.py

示例2: test_update_host_cache_in_thread

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
    def test_update_host_cache_in_thread(self, disconnect_mock, connect_mock, spec_mock,
                                         update_mock, prop_collector_mock):
        vm = vim.VirtualMachine("moid", None)
        vm.kind = "enter"
        vm.changeSet = {}
        update = MagicMock()
        update.filterSet = [MagicMock()]
        update.filterSet[0].objectSet = [MagicMock()]
        update.filterSet[0].objectSet[0] = vm

        # Mock the Vim APIs.
        prop_collector_mock.WaitForUpdatesEx = MagicMock()
        prop_collector_mock.WaitForUpdatesEx.return_value = update

        # Create VimClient.
        vim_client = VimClient(min_interval=0.1, auto_sync=True)
        vim_client.connect_userpwd("esx.local", "root", "password")

        # Verify that the update mock is called a few times.
        retry = 0
        while update_mock.call_count < 5 and retry < 10:
            time.sleep(0.2)
            retry += 1
        assert_that(retry, is_not(10), "VimClient.update_mock is not called repeatedly")

        # Disconnect the client and stop the thread.
        vim_client.disconnect()
        assert_that(disconnect_mock.called, is_(True))

        assert_that(update_mock.call_count, is_not(0), "VimClient.update_mock is not called")
开发者ID:cartlhd,项目名称:photon-controller,代码行数:32,代码来源:test_vim_client.py

示例3: test_update_host_cache_in_thread

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
    def test_update_host_cache_in_thread(self, disconnect_mock, connect_mock,
                                         spec_mock, update_mock,
                                         update_host_mock, query_spec_mock,
                                         perf_manager_mock,
                                         prop_collector_mock):

        # Test Values.
        counter = MagicMock()
        counter.groupInfo.key = "mem"
        counter.nameInfo.key = "consumed"
        counter.key = 65613

        n = 5
        statValues = ','.join([str(x) for x in range(1, n+1)])
        statAverage = sum(range(1, n+1)) / len(range(1, n+1))
        stat = MagicMock()
        stat.value = [MagicMock()]
        stat.value[0].id.counterId = 65613
        stat.value[0].value = statValues

        # Mock the Vim APIs.
        pc_return_mock = MagicMock({'WaitForUpdatesEx.return_value': {}})
        summarize_stats = {'QueryPerf.return_value': [stat]}
        pm_return_mock = MagicMock(perfCounter=[counter], **summarize_stats)

        # Tie the mocked APIs with VimClient.
        prop_collector_mock.return_value = pc_return_mock
        perf_manager_mock.return_value = pm_return_mock

        # Create VimClient.
        vim_client = VimClient("esx.local", "root", "password",
                               min_interval=0.1, auto_sync=True,
                               stats_interval=0.2)

        # Verify that the update mock is called a few times.
        retry = 0
        while update_mock.call_count < 5 and retry < 10:
            time.sleep(0.2)
            retry += 1
        assert_that(retry, is_not(10), "VimClient.update_mock is not "
                                       "called repeatedly")

        # Disconnect the client and stop the thread.
        vim_client.disconnect(wait=True)
        assert_that(disconnect_mock.called, is_(True))

        # Verify that update_host_mock is called atleast once and is called
        # less number of times than update_mock.
        assert_that(update_host_mock.call_count, is_not(0),
                    "VimClient.update_host_mock is not called repeatedly")
        assert_that(update_host_mock.call_count,
                    less_than(update_mock.call_count))

        host_stats = update_host_mock.call_args_list
        for host in host_stats:
            assert_that(host[0][0]['mem.consumed'], equal_to(statAverage))
开发者ID:tomzhang,项目名称:photon-controller,代码行数:58,代码来源:test_vim_client.py

示例4: test_poll_update_in_thread

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
    def test_poll_update_in_thread(self, disconnect_mock, connect_mock, spec_mock, update_mock):
        vim_client = VimClient(min_interval=0, auto_sync=True)
        vim_client.connect_userpwd("esx.local", "root", "password")
        vim_client._property_collector.WaitForUpdatesEx.return_value = {}

        assert_that(update_mock.called, is_(True))
        retry = 0
        while update_mock.call_count < 5 and retry < 10:
            time.sleep(0.2)
            retry += 1
        assert_that(retry, is_not(10), "VimClient._poll_updates is not called repeatedly")
        vim_client.disconnect()
        assert_that(disconnect_mock.called, is_(True))
开发者ID:cartlhd,项目名称:photon-controller,代码行数:15,代码来源:test_vim_client.py

示例5: TestVmManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestVmManager(unittest.TestCase):

    def setUp(self):
        if "host_remote_test" not in config:
            raise SkipTest()

        self.host = config["host_remote_test"]["server"]
        self.pwd = config["host_remote_test"]["esx_pwd"]

        if self.host is None or self.pwd is None:
            raise SkipTest()

        self._logger = logging.getLogger(__name__)
        self.vim_client = VimClient()
        self.vim_client.connect_userpwd(self.host, "root", self.pwd)
        self.vm_manager = VmManager(self.vim_client, None)
        for vm in self.vim_client._get_vms():
            vm.Destroy()

    def tearDown(self):
        self.vim_client.disconnect()

    @patch('os.path.exists', return_value=True)
    def test_mks_ticket(self, _exists):
        vm_id = self._vm_id()
        flavor = Flavor("vm", [QuotaLineItem("vm.cpu", 1, Unit.COUNT),
                               QuotaLineItem("vm.memory", 8, Unit.MB)])
        datastore = self.vim_client.get_all_datastores()[0].name
        spec = self.vm_manager.create_vm_spec(vm_id, datastore, flavor)
        try:
            self.vm_manager.create_vm(vm_id, spec)
            self.vm_manager.power_on_vm(vm_id)
            ticket = self.vm_manager.get_mks_ticket(vm_id)
            assert_that(ticket.cfg_file, not_none())
            assert_that(ticket.ticket, not_none())
        finally:
            self.vm_manager.power_off_vm(vm_id)
            self.vm_manager.delete_vm(vm_id)

    def _vm_id(self):
        vm_id = strftime("%Y-%m-%d-%H%M%S-", localtime())
        vm_id += str(random.randint(1, 10000))

        return vm_id

    def _test_port(self):
        return 5907
开发者ID:cartlhd,项目名称:photon-controller,代码行数:49,代码来源:test_vm_manager.py

示例6: TestEsxDiskManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestEsxDiskManager(unittest.TestCase):

    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.vim_client.wait_for_task = MagicMock()
        self.disk_manager = EsxDiskManager(self.vim_client, [])
        self.disk_manager._vmdk_mkdir = MagicMock()
        self.disk_manager._vmdk_rmdir = MagicMock()

    def tearDown(self):
        self.vim_client.disconnect(wait=True)

    def test_create_spec(self):
        """Test that we create a valid disk spec."""

        capacity = 2
        spec = self.disk_manager._create_spec(capacity)
        assert_that(spec.capacityKb, equal_to(capacity * (1024 ** 2)))
        assert_that(spec.adapterType, equal_to(DEFAULT_DISK_ADAPTER_TYPE))

    def test_invalid_datastore_path(self):
        """Test that we propagate InvalidDatastorePath."""

        self.vim_client.wait_for_task.side_effect = \
            vim.fault.InvalidDatastorePath
        self.assertRaises(DiskPathException,
                          self.disk_manager.create_disk, "ds1", "foo", 101)

    def test_disk_not_found(self):
        """Test that we propagate FileNotFound."""

        self.vim_client.wait_for_task.side_effect = vim.fault.FileNotFound
        self.assertRaises(DiskFileException,
                          self.disk_manager.delete_disk, "ds1", "bar")

    def test_general_fault(self):
        """Test general Exception propagation."""

        self.vim_client.wait_for_task.side_effect = vim.fault.TaskInProgress

        self.assertRaises(vim.fault.TaskInProgress,
                          self.disk_manager.move_disk,
                          "ds1", "biz", "ds1", "baz")
开发者ID:aasthabh,项目名称:photon-controller,代码行数:49,代码来源:test_esx_disk_manager.py

示例7: vim_delete_vm

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
 def vim_delete_vm(self, vm_id):
     """ Delete a VM using the vim client """
     try:
         vim_client = VimClient()
         vim_client.connect_ticket(self.server, self._get_vim_ticket())
         vim_vm = vim_client.get_vm(vm_id)
         if vim_vm.runtime.powerState != 'poweredOff':
             try:
                 vim_task = vim_vm.PowerOff()
                 vim_client.wait_for_task(vim_task)
             except:
                 logger.info("Cannot power off vm", exc_info=True)
         vim_task = vim_vm.Destroy()
         vim_client.wait_for_task(vim_task)
     finally:
         if vim_client:
             vim_client.disconnect()
开发者ID:hartsock,项目名称:photon-controller,代码行数:19,代码来源:test_remote_agent.py

示例8: test_update_fail_will_suicide

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
    def test_update_fail_will_suicide(self, sleep_mock, connect_mock, update_mock):
        killed = threading.Event()

        def suicide():
            killed.set()
            threading.current_thread().stop()

        poll_updates = MagicMock()
        poll_updates.side_effect = vim.fault.HostConnectFault

        client = VimClient(auto_sync=True, min_interval=1, errback=lambda: suicide())
        client.connect_userpwd("esx.local", "root", "password")
        client._vim_cache.poll_updates = poll_updates

        killed.wait(1)
        client.disconnect()

        # poll_updates will be called 5 times before it kill itself
        assert_that(poll_updates.call_count, is_(5))
        assert_that(killed.is_set(), is_(True))
开发者ID:cartlhd,项目名称:photon-controller,代码行数:22,代码来源:test_vim_client.py

示例9: TestEsxImageManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestEsxImageManager(unittest.TestCase):
    """Image Manager tests."""

    # We can use even more unit test coverage of the image manager here

    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.ds_manager = MagicMock()
        services.register(ServiceName.AGENT_CONFIG, MagicMock())
        self.image_manager = EsxImageManager(self.vim_client, self.ds_manager)

    def tearDown(self):
        self.vim_client.disconnect(wait=True)

    @patch("os.path.isdir", return_value=False)
    @patch("os.makedirs", side_effect=OSError)
    def test_make_image_dir(self, _makedirs, _isdir):
        self.assertRaises(
            OSError, self.image_manager._make_image_dir, "ds", "fake_iid")
        _isdir.assert_called_once_with("/vmfs/volumes/ds/images/fa/fake_iid")
        self.assertEqual(
            _makedirs.call_count, EsxImageManager.NUM_MAKEDIRS_ATTEMPTS)
        for i in range(0, EsxImageManager.NUM_MAKEDIRS_ATTEMPTS):
            self.assertEqual(_makedirs.call_args_list[i][0],
                             ("/vmfs/volumes/ds/images/fa/fake_iid",))

    @patch(
        "host.hypervisor.esx.image_manager.EsxImageManager.reap_tmp_images")
    def test_periodic_reaper(self, mock_reap):
        """ Test that the we invoke the image reaper periodically """
        image_manager = EsxImageManager(self.vim_client, self.ds_manager)
        image_manager.monitor_for_cleanup(reap_interval=0.1)

        self.assertFalse(image_manager._image_reaper is None)

        retry = 0
        while mock_reap.call_count < 2 and retry < 10:
            time.sleep(0.1)
            retry += 1
        image_manager.cleanup()
        assert_that(mock_reap.call_count, greater_than(1))
        assert_that(retry, is_not(10), "reaper cleanup not called repeatedly")

    @patch("uuid.uuid4", return_value="fake_id")
    @patch("host.hypervisor.esx.vm_config.os_datastore_path")
    def test_reap_tmp_images(self, _os_datastore_path, _uuid):
        """ Test that stray images are found and deleted by the reaper """

        def _fake_ds_folder(datastore, folder):
            return "%s__%s" % (datastore, folder)

        ds = MagicMock()
        ds.id = "dsid"
        ds.type = DatastoreType.EXT3

        # In a random transient directory, set up a directory to act as the
        # tmp images folder and to contain a stray image folder with a file.
        tmpdir = file_util.mkdtemp(delete=True)
        tmp_images_folder = _fake_ds_folder(ds.id, TMP_IMAGE_FOLDER_NAME)
        tmp_images_dir = os.path.join(tmpdir, tmp_images_folder)
        tmp_image_dir = os.path.join(tmp_images_dir, "stray_image")
        os.mkdir(tmp_images_dir)
        os.mkdir(tmp_image_dir)
        (fd, path) = tempfile.mkstemp(prefix='strayimage_', dir=tmp_image_dir)

        self.assertTrue(os.path.exists(path))

        def _fake_os_datastore_path(datastore, folder):
            return os.path.join(tmpdir, _fake_ds_folder(datastore, folder))

        _os_datastore_path.side_effect = _fake_os_datastore_path

        ds_manager = MagicMock()
        ds_manager.get_datastores.return_value = [ds]
        image_manager = EsxImageManager(self.vim_client, ds_manager)
        image_manager.reap_tmp_images()

        # verify stray image is deleted
        self.assertFalse(os.path.exists(path))

    @patch("os.path.isdir")
    @patch("os.makedirs")
    def test_vmdk_mkdir_eexist(self, _makedirs, _isdir):
        eexist = OSError()
        eexist.errno = errno.EEXIST
        _makedirs.side_effect = eexist
        _isdir.side_effect = (False,  # dest image dir missing
                              True)   # dest image dir is created

        self.image_manager._make_image_dir("ds", "fake_iid")
        _isdir.assert_called("/vmfs/volumes/ds/images/fa/fake_iid")

    @patch("pysdk.task.WaitForTask")
    @patch("uuid.uuid4", return_value="fake_id")
    @patch("os.path.exists")
    @patch("os.makedirs")
#.........这里部分代码省略.........
开发者ID:tomzhang,项目名称:photon-controller,代码行数:103,代码来源:test_esx_image_manager.py

示例10: TestEsxVmConfig

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestEsxVmConfig(unittest.TestCase):
    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        with patch("host.hypervisor.esx.vm_config.GetEnv"):
            self.vm_config = EsxVmConfig(self.vim_client)

    def tearDown(self):
        self.vim_client.disconnect(wait=True)

    def dummy_devices(self):
        return [
            vim.vm.device.VirtualFloppy(key=10),
            vim.vm.device.VirtualPCIController(key=100),
            DEFAULT_DISK_CONTROLLER_CLASS(key=1000),
            vim.vm.device.VirtualSoundCard(key=10000),
        ]

    def test_vm_create_spec(self):
        datastore = "ds1"
        vm_id = str(uuid.uuid4())
        metadata = {
            "configuration": {"guestOS": "otherLinuxGuest"},
            "parameters": [{"name": "key1"}, {"name": "key2"}]
        }
        env = {
            "key1": "value1",
            "keyUnexpected": "valueNotSet",
        }
        spec = self.vm_config.create_spec(vm_id, datastore, 512, 1, metadata,
                                          env)
        assert_that(spec.memoryMB, equal_to(512))
        assert_that(spec.numCPUs, equal_to(1))
        assert_that(spec.name, equal_to(vm_id))
        assert_that(spec.guestId, equal_to("otherLinuxGuest"))
        expected_metadata = {'guestOS': 'otherLinuxGuest', 'key1': 'value1'}
        assert_that(spec._metadata, equal_to(expected_metadata))

    def test_create_nic_spec(self):
        net_name = "VM_network"
        cspec = self.vm_config.update_spec()
        spec = self.vm_config.add_nic(cspec, net_name)
        backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo
        assert_that(spec.deviceChange[0].device.backing.__class__,
                    equal_to(backing))
        assert_that(spec.deviceChange[0].device.backing.deviceName,
                    equal_to(net_name))

    def test_find_disk_controller(self):
        devices = self.dummy_devices()
        device_type = DEFAULT_DISK_CONTROLLER_CLASS
        disk_controller = self.vm_config.find_device(devices, device_type)
        assert_that(disk_controller.key, equal_to(1000))

    def test_find_nic_controller(self):
        devices = self.dummy_devices()
        device_type = vim.vm.device.VirtualPCIController
        disk_controller = self.vm_config.find_device(devices, device_type)
        assert_that(disk_controller.key, equal_to(100))

    def test_find_virtual_disk(self):
        spec = vim.vm.ConfigSpec()
        vm_config = self.vm_config
        devices = self.dummy_devices()
        for device in devices:
            vm_config.add_device(spec, device)
        cfg_info = FakeConfigInfo()
        device_type = vim.vm.device.VirtualDisk
        datastore = "ds1"
        filename = "folder/foo"
        path = vmdk_path(datastore, filename)

        find_disk = vm_config.disk_matcher(datastore, filename)
        disk = vm_config.find_device(devices, device_type, matcher=find_disk)
        assert_that(disk, equal_to(None))

        vm_config.add_scsi_disk(cfg_info, spec, datastore, "nope")

        self.assertRaises(DeviceNotFoundException, vm_config.get_device,
                          devices, device_type, matcher=find_disk)

        vm_config.add_scsi_disk(cfg_info, spec, datastore,
                                filename)
        device_changes = spec.deviceChange
        device_list = []
        for device_change in device_changes:
            device_list.append(device_change.device)

        disk = vm_config.find_device(device_list, device_type,
                                     matcher=find_disk)
        assert_that(disk.backing.fileName, equal_to(path))

    def _create_spec_for_disk_test(self, datastore, vm_id):
        spec = vim.vm.ConfigSpec()
        devices = self.dummy_devices()
        for device in devices:
            self.vm_config.add_device(spec, device)
#.........这里部分代码省略.........
开发者ID:aju0987,项目名称:photon-controller,代码行数:103,代码来源:test_esx_vm_config.py

示例11: TestHttpTransfer

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestHttpTransfer(unittest.TestCase):
    """Http Transferer tests."""

    @patch.object(VimClient, "acquire_credentials")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, creds):
        self.shadow_vm_id = SHADOW_VM_NAME_PREFIX + str(uuid.uuid1())
        self.image_datastores = ["image_ds", "alt_image_ds"]
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.patcher = patch("host.hypervisor.esx.vm_config.GetEnv")
        self.patcher.start()
        services.register(ServiceName.AGENT_CONFIG, MagicMock())
        self.http_transferer = HttpNfcTransferer(self.vim_client,
                                                 self.image_datastores)

    def tearDown(self):
        self.vim_client.disconnect(wait=True)
        self.patcher.stop()

    @parameterized.expand([
        (True,), (False,)
    ])
    @patch("host.hypervisor.esx.http_disk_transfer.VimClient")
    @patch("host.hypervisor.esx.http_disk_transfer.DirectClient")
    def test_get_remote_connections(self, get_svc_ticket_success, _client_cls,
                                    _vim_client_cls):
        host = "mock_host"
        port = 8835
        get_service_ticket_mock = MagicMock()
        if get_svc_ticket_success:
            get_service_ticket_mock.result = ServiceTicketResultCode.OK
        else:
            get_service_ticket_mock.result = ServiceTicketResultCode.NOT_FOUND
        instance = _client_cls.return_value
        instance.get_service_ticket.return_value = get_service_ticket_mock

        if get_svc_ticket_success:
            (agent_conn,
             vim_conn) = self.http_transferer._get_remote_connections(
                 host, port)
            _client_cls.assert_called_once_with(
                "Host", Host.Client, host, port)
            instance.connect.assert_called_once_with()
            request = ServiceTicketRequest(service_type=ServiceType.VIM)
            instance.get_service_ticket.assert_called_once_with(request)

            _vim_client_cls.assert_called_once_with(
                host=host, ticket=get_service_ticket_mock.vim_ticket,
                auto_sync=False)

            self.assertEqual(agent_conn, instance)
            self.assertEqual(vim_conn, _vim_client_cls.return_value)
        else:
            self.assertRaises(
                ValueError, self.http_transferer._get_remote_connections,
                host, port)

    @parameterized.expand([
        (None, "http://*/ha-nfc/x.vmdk", "http://actual_host/ha-nfc/x.vmdk"),
        (None, "https://*/foo", "https://actual_host/foo"),
        (None, "http://*:1234/foo", "http://actual_host:1234/foo"),
        (None, "https://host/foo", "https://host/foo")
    ])
    def test_ensure_host_in_url(self, _, url, replaced_url):
        host = "actual_host"
        result = self.http_transferer._ensure_host_in_url(url, host)
        self.assertEqual(result, replaced_url)

    def test_export_shadow_vm(self):
        self.http_transferer._get_disk_url_from_lease = MagicMock()
        self.http_transferer._wait_for_lease = MagicMock()
        mock_get_vm = MagicMock()
        mock_lease = MagicMock()
        self.vim_client.get_vm_obj_in_cache = mock_get_vm
        mock_get_vm.return_value.ExportVm.return_value = mock_lease

        lease, url = self.http_transferer._export_shadow_vm(self.shadow_vm_id)

        mock_get_vm.assert_called_once_with(self.shadow_vm_id)
        mock_get_vm.return_value.ExportVm.assert_called_once_with()
        self.http_transferer._wait_for_lease.assert_called_once_with(
            mock_lease)
        self.http_transferer._get_disk_url_from_lease.assert_called_once_with(
            mock_lease)

    def test_create_shadow_vm(self):
        self.http_transferer._vm_manager.create_vm = MagicMock()

        shadow_vm_id = self.http_transferer._create_shadow_vm()

        create_vm = self.http_transferer._vm_manager.create_vm
        self.assertTrue(create_vm.called)
        vm_id_arg, vm_spec_arg = create_vm.call_args_list[0][0]
        self.assertEqual(vm_id_arg, shadow_vm_id)
        self.assertEqual(
            vm_spec_arg.files.vmPathName,
            '[] /vmfs/volumes/%s/vm_%s' % (self.image_datastores[0], shadow_vm_id))

    def test_configure_shadow_vm_with_disk(self):
#.........这里部分代码省略.........
开发者ID:thulasi39,项目名称:photon-controller,代码行数:103,代码来源:test_http_transfer.py

示例12: TestEsxVmManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestEsxVmManager(unittest.TestCase):
    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.vim_client.wait_for_task = MagicMock()
        self.patcher = patch("host.hypervisor.esx.vm_config.GetEnv")
        self.patcher.start()
        self.vm_manager = EsxVmManager(self.vim_client, MagicMock())

    def tearDown(self):
        self.patcher.stop()
        self.vim_client.disconnect(wait=True)

    def test_power_vm_not_found(self):
        """Test that we propagate VmNotFound."""

        self.vim_client.find_by_inventory_path = MagicMock(return_value=None)
        self.assertRaises(VmNotFoundException,
                          self.vm_manager.power_on_vm, "ENOENT")

    def test_power_vm_illegal_state(self):
        """Test InvalidPowerState propagation."""

        vm_mock = MagicMock(name="vm_mock")
        self.vm_manager.vim_client.get_vm = vm_mock
        self.vim_client.wait_for_task.side_effect = \
            vim.fault.InvalidPowerState()

        self.assertRaises(VmPowerStateException,
                          self.vm_manager.power_on_vm, "foo")

    def test_power_vm_error(self):
        """Test general Exception propagation."""

        vm_mock = MagicMock(name="vm_mock")
        self.vm_manager.vim_client.get_vm = vm_mock
        self.vim_client.wait_for_task.side_effect = vim.fault.TaskInProgress

        self.assertRaises(vim.fault.TaskInProgress,
                          self.vm_manager.power_on_vm, "foo")

    def test_add_nic(self):
        """Test add nic"""

        # 3 cases for add_nic:
        # * caller passes in network_id = None
        # * caller passes in the correct network_id and hostd
        #   returns the right thing from get_network.

        def _get_device(devices, controller_type):
            f = MagicMock("get_device_foo")
            f.key = 1
            return f
        self.vm_manager.vm_config.get_device = _get_device

        spec = self.vm_manager.vm_config.update_spec()
        # Caller passes none
        self.vm_manager.add_nic(spec, None)

        # Caller passes some network_id
        self.vm_manager.add_nic(spec, "Private Vlan")

    def test_create_vm_already_exist(self):
        """Test VM creation fails if VM is found"""

        vim_mock = MagicMock()
        self.vm_manager.vim_client = vim_mock
        vim_mock.find_vm = MagicMock(return_value="existing_vm")
        mock_spec = MagicMock()
        self.assertRaises(VmAlreadyExistException,
                          self.vm_manager.create_vm,
                          "existing_vm_name",
                          mock_spec)

    def test_create_vm(self):
        """Test VM creation"""

        vim_mock = MagicMock()
        self.vm_manager.vim_client = vim_mock

        vm_folder_mock = MagicMock()
        vim_mock.vm_folder = vm_folder_mock

        root_res_pool_mock = PropertyMock(return_value="fake_rp")
        type(vim_mock).root_resource_pool = root_res_pool_mock

        vim_mock.get_vm_in_cache = MagicMock(return_value=None)
        vm_folder_mock.CreateVm.return_value = "fake-task"

        mock_spec = MagicMock()
        mock_spec.files.vmPathName = "[] /vmfs/volumes/ds/vms"
        self.vm_manager.create_vm("fake_vm_id", mock_spec)

        vim_mock.get_vm_in_cache.assert_called_once_with("fake_vm_id")
        vm_folder_mock.CreateVm.assert_called_once_with(
            mock_spec, 'fake_rp', None)
        vim_mock.wait_for_task.assert_called_once_with("fake-task")
#.........这里部分代码省略.........
开发者ID:aju0987,项目名称:photon-controller,代码行数:103,代码来源:test_esx_vm_manager.py

示例13: TestEsxImageManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestEsxImageManager(unittest.TestCase):
    """Image Manager tests."""

    # We can use even more unit test coverage of the image manager here

    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.ds_manager = MagicMock()
        services.register(ServiceName.AGENT_CONFIG, MagicMock())
        self.image_manager = EsxImageManager(self.vim_client, self.ds_manager)

    def tearDown(self):
        self.vim_client.disconnect(wait=True)

    @patch("os.path.isdir", return_value=False)
    @patch("os.makedirs", side_effect=OSError)
    def test_make_image_dir(self, _makedirs, _isdir):
        path = "/vmfs/volumes/ds/image_fake_iid"
        self.assertRaises(
            OSError, self.image_manager._make_image_dir, "ds", "fake_iid")
        _isdir.assert_called_once_with(path)
        self.assertEqual(
            _makedirs.call_count, EsxImageManager.NUM_MAKEDIRS_ATTEMPTS)
        for i in range(0, EsxImageManager.NUM_MAKEDIRS_ATTEMPTS):
            self.assertEqual(_makedirs.call_args_list[i][0], (path,))

    @patch(
        "host.hypervisor.esx.image_manager.EsxImageManager.reap_tmp_images")
    def test_periodic_reaper(self, mock_reap):
        """ Test that the we invoke the image reaper periodically """
        image_manager = EsxImageManager(self.vim_client, self.ds_manager)
        image_manager.monitor_for_cleanup(reap_interval=0.1)

        self.assertFalse(image_manager._image_reaper is None)

        retry = 0
        while mock_reap.call_count < 2 and retry < 10:
            time.sleep(0.1)
            retry += 1
        image_manager.cleanup()
        assert_that(mock_reap.call_count, greater_than(1))
        assert_that(retry, is_not(10), "reaper cleanup not called repeatedly")

    @parameterized.expand([
        (True, ),
        (False, )
    ])
    @patch("uuid.uuid4", return_value="fake_id")
    @patch("host.hypervisor.esx.vm_config.os_datastore_root")
    def test_reap_tmp_images(self, _allow_grace_period, _os_datastore_root,
                             _uuid):
        """ Test that stray images are found and deleted by the reaper """
        ds = MagicMock()
        ds.id = "dsid"
        ds.type = DatastoreType.EXT3

        # In a random transient directory, set up a directory to act as the
        # tmp images folder and to contain a stray image folder with a file.
        tmpdir = file_util.mkdtemp(delete=True)
        tmp_ds_dir = os.path.join(tmpdir, ds.id)
        os.mkdir(tmp_ds_dir)
        tmp_image_dir = os.path.join(tmp_ds_dir, compond_path_join(TMP_IMAGE_FOLDER_NAME_PREFIX, "stray_image"))
        os.mkdir(tmp_image_dir)
        (fd, path) = tempfile.mkstemp(prefix='strayimage_', dir=tmp_image_dir)

        self.assertTrue(os.path.exists(path))

        def _fake_os_datastore_root(datastore):
            return os.path.join(tmpdir, datastore)

        _os_datastore_root.side_effect = _fake_os_datastore_root

        ds_manager = MagicMock()
        ds_manager.get_datastores.return_value = [ds]
        image_manager = EsxImageManager(self.vim_client, ds_manager)
        if not _allow_grace_period:
            image_manager.REAP_TMP_IMAGES_GRACE_PERIOD = 0.0
            time.sleep(0.1)
        image_manager.reap_tmp_images()

        if _allow_grace_period:
            # verify stray image is not deleted due to grace period
            self.assertTrue(os.path.exists(path))
        else:
            # verify stray image is deleted
            self.assertFalse(os.path.exists(path))

    @patch("os.path.isdir")
    @patch("os.makedirs")
    def test_vmdk_mkdir_eexist(self, _makedirs, _isdir):
        eexist = OSError()
        eexist.errno = errno.EEXIST
        _makedirs.side_effect = eexist
        _isdir.side_effect = (False,  # dest image dir missing
                              True)   # dest image dir is created

#.........这里部分代码省略.........
开发者ID:aju0987,项目名称:photon-controller,代码行数:103,代码来源:test_esx_image_manager.py

示例14: ImageScannerTestCase

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class ImageScannerTestCase(unittest.TestCase):
    DATASTORE_ID = "DS01"
    BASE_TEMP_DIR = "image_scanner"

    @patch.object(VimClient, "acquire_credentials")
    @patch.object(VimClient, "update_cache")
    @patch("pysdk.connect.Connect")
    def setUp(self, connect, update, creds):
        # Create VM manager
        creds.return_value = ["username", "password"]
        self.vim_client = VimClient(auto_sync=False)
        self.vim_client.wait_for_task = MagicMock()
        self.patcher = patch("host.hypervisor.esx.vm_config.GetEnv")
        self.patcher.start()
        self.vm_manager = EsxVmManager(self.vim_client, MagicMock())

        # Set up test files
        self.base_dir = os.path.dirname(__file__)
        self.test_dir = os.path.join(self.base_dir, "../../test_files")
        self.image_manager = EsxImageManager(MagicMock(), MagicMock())
        self.image_scanner = DatastoreImageScanner(self.image_manager,
                                                   self.vm_manager,
                                                   self.DATASTORE_ID)
        self.image_scanner._task_runner = MagicMock()
        self.image_scanner._task_runner.is_stopped.return_value = False
        self.write_count = 0

    def tearDown(self):
        self.patcher.stop()
        self.vim_client.disconnect(wait=True)

    def test_vm_scan(self):
        self.image_scanner.vm_scan_rate = 60000
        dictionary = self.vm_manager.\
            _collect_active_images(self.image_scanner, self.test_dir)
        assert_that(len(dictionary) is 1)
        assert_that(dictionary["92e62599-6689-4a8f-ba2a-633914b5048e"] ==
                    "/vmfs/volumes/555ca9f8-9f24fa2c-41c1-0025b5414043/"
                    "images/92/92e62599-6689-4a8f-ba2a-633914b5048e/92e"
                    "62599-6689-4a8f-ba2a-633914b5048e.vmdk")

    def test_vm_scan_bad_root(self):
        self.image_scanner.vm_scan_rate = 60000
        bad_dir = os.path.join(self.base_dir,
                               "test_files",
                               "vms",
                               "test",
                               "bad",
                               "bad.vmdk")
        dictionary = self.vm_manager.\
            _collect_active_images(self.image_scanner, bad_dir)
        assert_that(len(dictionary) is 0)

    def test_vm_scan_bad_vmdk(self):
        self.image_scanner.vm_scan_rate = 60000
        bad_dir = os.path.join(self.base_dir,
                               "test_files",
                               "vms",
                               "test",
                               "bad")
        dictionary = self.vm_manager.\
            _collect_active_images(self.image_scanner, bad_dir)
        assert_that(len(dictionary) is 0)

    @patch("host.hypervisor.image_scanner.waste_time")
    def test_vm_scan_rate(self, waste_time):
        waste_time.side_effect = self.fake_waste_time
        # fake activation
        self.image_scanner.vm_scan_rate = 30
        dictionary = self.vm_manager.\
            _collect_active_images(self.image_scanner, self.test_dir)
        assert_that(len(dictionary) is 1)
        assert_that(dictionary["92e62599-6689-4a8f-ba2a-633914b5048e"] ==
                    "/vmfs/volumes/555ca9f8-9f24fa2c-41c1-0025b5414043/"
                    "images/92/92e62599-6689-4a8f-ba2a-633914b5048e/92e"
                    "62599-6689-4a8f-ba2a-633914b5048e.vmdk")

    def fake_waste_time(self, seconds):
        assert_that((seconds > 1.0) is True)
开发者ID:tomzhang,项目名称:photon-controller,代码行数:81,代码来源:test_esx_vm_manager.py

示例15: TestVmManager

# 需要导入模块: from host.hypervisor.esx.vim_client import VimClient [as 别名]
# 或者: from host.hypervisor.esx.vim_client.VimClient import disconnect [as 别名]
class TestVmManager(unittest.TestCase):
    def setUp(self):
        if "host_remote_test" not in config:
            raise SkipTest()

        self.host = config["host_remote_test"]["server"]
        self.pwd = config["host_remote_test"]["esx_pwd"]

        if self.host is None or self.pwd is None:
            raise SkipTest()

        self._logger = logging.getLogger(__name__)
        self.vim_client = VimClient(self.host, "root", self.pwd)
        self.vm_manager = EsxVmManager(self.vim_client, [])
        for vm in self.vim_client.get_vms():
            vm.Destroy()

    def tearDown(self):
        self.vim_client.disconnect(wait=True)

    @patch("os.path.exists", return_value=True)
    def test_vnc_ports(self, _exists):
        vm_id = self._vm_id()
        port = self._test_port()
        flavor = Flavor("vm", [QuotaLineItem("vm.cpu", 1, Unit.COUNT), QuotaLineItem("vm.memory", 8, Unit.MB)])
        datastore = self.vim_client.get_datastore().name
        spec = self.vm_manager.create_vm_spec(vm_id, datastore, flavor)
        self.vm_manager.set_vnc_port(spec, port)
        try:
            self.vm_manager.create_vm(vm_id, spec)
            expected = self.vm_manager.get_vnc_port(vm_id)
            assert_that(expected, equal_to(port))

            ports = self.vm_manager.get_occupied_vnc_ports()
            assert_that(ports, contains(port))
        finally:
            self.vm_manager.delete_vm(vm_id)

    @patch("os.path.exists", return_value=True)
    def test_mks_ticket(self, _exists):
        vm_id = self._vm_id()
        flavor = Flavor("vm", [QuotaLineItem("vm.cpu", 1, Unit.COUNT), QuotaLineItem("vm.memory", 8, Unit.MB)])
        datastore = self.vim_client.get_datastore().name
        spec = self.vm_manager.create_vm_spec(vm_id, datastore, flavor)
        try:
            self.vm_manager.create_vm(vm_id, spec)
            self.vm_manager.power_on_vm(vm_id)
            ticket = self.vm_manager.get_mks_ticket(vm_id)
            assert_that(ticket.cfg_file, not_none())
            assert_that(ticket.ticket, not_none())
        finally:
            self.vm_manager.power_off_vm(vm_id)
            self.vm_manager.delete_vm(vm_id)

    @patch("os.path.exists", return_value=True)
    def test_vminfo(self, _exists):
        self._test_vminfo({})
        self._test_vminfo({"project": "p1"})
        self._test_vminfo({"tenant": "t1"})
        self._test_vminfo({"project": "p1", "tenant": "t1"})

    def _test_vminfo(self, vminfo):
        vm_id = self._vm_id()
        flavor = Flavor("vm", [QuotaLineItem("vm.cpu", 1, Unit.COUNT), QuotaLineItem("vm.memory", 8, Unit.MB)])
        datastore = self.vim_client.get_datastore().name
        spec = self.vm_manager.create_vm_spec(vm_id, datastore, flavor)
        self.vm_manager.set_vminfo(spec, vminfo)
        try:
            self.vm_manager.create_vm(vm_id, spec)
            got_metadata = self.vm_manager.get_vminfo(vm_id)
            assert_that(got_metadata, equal_to(vminfo))
        finally:
            self.vm_manager.delete_vm(vm_id)

    def _vm_id(self):
        vm_id = strftime("%Y-%m-%d-%H%M%S-", localtime())
        vm_id += str(random.randint(1, 10000))

        return vm_id

    def _test_port(self):
        return 5907
开发者ID:fakber,项目名称:photon-controller,代码行数:84,代码来源:test_vm_manager.py


注:本文中的host.hypervisor.esx.vim_client.VimClient.disconnect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。