class VM_Server_225_145: def __init__(self): self.sdk = Sdk() self.server_details = Config().vsphere_server_details() self.vm_name__minio_test = 'dinis-test-via-ovf' def minio_test_setup_network(self): vm = self.sdk.find_by_name(self.vm_name__minio_test) vm_process = VM_Process(vm) #print(vm_process.exec('/bin/ip', 'a')) #print(vm_process.exec('/bin/ip', 'addr add 10.102.66.200/24 dev enp0s25')) #print(vm_process.exec('/bin/cat', '/etc/shadow')) #print(vm_process.exec('/bin/bash', '-c "sudo /bin/cat /etc/shadow"')) print( vm_process.exec('/bin/bash', '-c "sudo ip addr add 91.109.26.22/27 dev eth0"') ) # commands from https://ubuntu.com/server/docs/network-configuration print( vm_process.exec('/bin/bash', '-c "sudo ip route add default via 91.109.26.30"')) print(vm_process.exec('/bin/ip', 'a')) print(vm_process.exec('/bin/ip', 'route show')) def minio_test_get_request(self): resp = requests.get('http://91.109.26.22') return resp.text def minio_test_vm_power_off(self): vm = self.sdk.find_by_name(self.vm_name__minio_test) vm.task().power_off() return vm.info()
def __init__(self, ds_folder=None, ds_file=None): self.sdk = Sdk() self.datastore = Datastore() self.config = Config() self.ds_folder = ds_folder or "" self.ds_file = ds_file or "" self.verify_cert = False
def setUp(self) -> None: sdk = Sdk() self.vm = sdk.vm( 'photon' ) # todo: refactor to use a VM we know will exist in the target Server self.vm_keystroke = VM_Keystroke(self.vm) if self.vm is None: pytest.skip(f"target server did not have vm {self.vm_name}")
def __init__(self, vm): self.sdk = Sdk() self.vm = vm self.vm_account = Config().vm_account() self.server_details = Config().vsphere_server_details() self.vm_user_name = self.vm_account['username'] self.vm_password = self.vm_account['password'] self.ip_server = self.server_details['host']
def __init__(self): self.sdk = Sdk() self.network = Network() self.server_details = Config().vsphere_server_details() # settings self.vswitch_name = 'vSwitch0' self.port_group_name = 'VM'
def test____enter____exit__(self): sdk = Sdk() vm_name = f"test____enter____exit__{random_string()}" with Temp_VM(vm_name) as vm: assert vm.name() == vm_name assert sdk.find_by_name(vm_name).name() == vm_name # search VM and confirm it is there assert sdk.find_by_name(vm_name) == None # search outsite the `with` statement and confirm that is NOT there
def __init__(self): load_dotenv() self.mode_tag = environ.get("mode_tag", None) self.start_shut_tag = environ.get("start_shut_tag", None) self.not_shutdown_tag = environ.get("not_shutdown_tag", None) self.auto = int(environ.get("auto", 0)) self.sdk = Sdk() self.dt_format = "%Y-%m-%d %I:%M%p" self.action_maps = {"start": "power_on", "shutdown": "power_off"}
class Network: def __init__(self): self.sdk = Sdk() def get_host(self): # assume there is only one host hosts = self.sdk.get_objects_Hosts() assert len(hosts) == 1 # throw exception if there is more than one host return hosts.pop() def network(self, name): for network in self.networks(): if network.name == name: return network def networks(self): return self.sdk.get_objects_Networks() def networks_names(self): names = [] for network in self.sdk.get_objects_Networks(): names.append(network.name) return names def virtual_switches(self): switches = [] for host in self.sdk.get_objects_Hosts(): for switch in host.config.network.vswitch: switches.append(switch) return switches def port_group_create(self, name, vswitch_name, vlan=0, promiscuous=False): host = self.get_host() policy = pyVmomi.vim.host.NetworkPolicy() policy.security = pyVmomi.vim.host.NetworkPolicy.SecurityPolicy() policy.security.allowPromiscuous = bool(promiscuous) policy.security.macChanges = False policy.security.forgedTransmits = False spec = pyVmomi.vim.host.PortGroup.Specification(name=name, vlanId=int(vlan), vswitchName=vswitch_name, policy=policy) host.configManager.networkSystem.AddPortGroup(spec) return self.sdk.get_object_network(name) def port_group_exists(self, name): return name in self.networks_names() def port_group_not_exists(self, name): return self.port_group_exists(name) == False def port_group_delete(self, name): host = self.get_host() host.configManager.networkSystem.RemovePortGroup(name)
def setUp(self) -> None: self.sdk = Sdk() self.vm_name = 'dinis-test-via-ovf' self.vm = self.sdk.find_by_name(self.vm_name) if self.vm is None: pytest.skip(f"target server did not have vm {self.vm_name}") else: if self.vm.powered_off(): pytest.skip( f"target server exists but it not Powered On {self.vm_name}" ) self.vm_process = VM_Process(vm=self.vm)
class Task: def __init__(self): self.sdk = Sdk() def wait_for_task(self, task): self.wait_for_tasks([task]) return task def wait_for_tasks( self, tasks ): # todo: refactor this out (the management of multiple tasks should be done by the caller not by this method) service_instance = self.sdk.service_instance() """Given the service instance si and tasks, it returns after all the tasks are complete """ property_collector = service_instance.content.propertyCollector task_list = [str(task) for task in tasks] # Create filter obj_specs = [ pyVmomi.vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks ] property_spec = pyVmomi.vmodl.query.PropertyCollector.PropertySpec( type=pyVmomi.vim.Task, pathSet=[], all=True) filter_spec = pyVmomi.vmodl.query.PropertyCollector.FilterSpec() filter_spec.objectSet = obj_specs filter_spec.propSet = [property_spec] pcfilter = property_collector.CreateFilter(filter_spec, True) try: version, state = None, None # Loop looking for updates till the state moves to a completed state. while len(task_list): update = property_collector.WaitForUpdates(version) for filter_set in update.filterSet: for obj_set in filter_set.objectSet: task = obj_set.obj for change in obj_set.changeSet: if change.name == 'info': state = change.val.state elif change.name == 'info.state': state = change.val else: continue if not str(task) in task_list: continue if state == pyVmomi.vim.TaskInfo.State.success: # Remove task from taskList task_list.remove(str(task)) elif state == pyVmomi.vim.TaskInfo.State.error: raise task.info.error # Move to next version version = update.version finally: if pcfilter: pcfilter.Destroy() return tasks
def __init__(self, vm_name=None, memory=1024, data_store=None, guest_id=None): self.vm_name : str = vm_name or f"random_name_{random_string()}" self.memory : int = memory self.data_store : str = data_store or 'datastore1' self.guest_id : str = guest_id or 'ubuntu64Guest' self.sdk : Sdk = Sdk() self.vm : VM = None # will have the VM object after creation self.devices : list = []
class Ubuntu: def __init__(self, vm_name): self.sdk = Sdk() self.vm_name = vm_name @cache_on_self def vm(self) -> VM: return self.sdk.vm(self.vm_name) def exists(self) -> bool: return self.vm() is not None
class test_Sdk_User(TestCase): def setUp(self) -> None: self.config = Config() self.sdk = Sdk() def test__enter__(self): server_details = self.config.vsphere_server_details( ) # get server details (from env variables) with Sdk_User(user_id=server_details['username'], password=server_details['password']) as sdk_user: assert self.sdk.login() is True assert sdk_user.login_result is True assert self.sdk.login() is True assert sdk_user.login_result is True def test__enter__bad_details(self): with Sdk_User(user_id='aaa', password='******') as sdk_user: assert sdk_user.login_result is False assert sdk_user.login_result is True
class Delete_Old_VMs: def __init__(self): load_dotenv() self.delete_note = environ.get('DELETE_NOTE') self.dont_delete_note = environ.get('DONT_DELETE_NOTE') self.esxi_expire_days = environ.get('ESXI_EXPIRE_DAYS') self.sdk = Sdk() def __validate_days_type(self): if not self.esxi_expire_days or not self.esxi_expire_days.isdigit(): print(" Expire days number must be postive integer") sys.exit(1) def vms_to_delete(self): removed_VMs = [] self.esxi_expire_days = int(self.esxi_expire_days) vms = self.sdk.get_objects_Virtual_Machines() now = datetime.now(pytz.utc) for vm in vms: vm_info = VM(vm) summary = vm_info.summary() notes = summary.config.annotation create_date = vm.config.createDate if create_date < datetime(2000, 1, 1, tzinfo=pytz.utc): continue if (self.delete_note and self.delete_note.lower() == notes.lower()) or \ (create_date < (now - timedelta(days=self.esxi_expire_days)) and ( not self.dont_delete_note or self.dont_delete_note.lower() not in notes.lower())): removed_VMs.append(vm_info) return removed_VMs def remove_vms(self, removed_VMs): removed_VMs_names = [] for vm in removed_VMs: vm.task().delete() removed_VMs_names.append(vm.info()["Name"]) return removed_VMs_names def run(self): self.__validate_days_type() removed_VMs = self.vms_to_delete() removed_VMs_names = self.remove_vms(removed_VMs) if removed_VMs_names: print("Removed VMs: ") print("=============") print("\n".join(removed_VMs_names)) else: print("No VM was removed!")
class Tiny_Core_Linux: def __init__(self): self.url_core_iso = 'https://distro.ibiblio.org/tinycorelinux/11.x/x86/release/Core-current.iso' self.path_core_iso = '/tmp/core-currenet.iso' self.vm_name = 'tiny-core-linux' self.sdk = Sdk() def create_vm(self): self.sdk.content() print('-----') vm = self.sdk.vm(self.vm_name) print('-----') #if vm is None: # print('need to create vm') #print(f"VM: {vm}") pass def download_iso(self): if file_not_exists(self.path_core_iso): Http.GET_bytes_to_file(self.url_core_iso, self.path_core_iso) return self.path_core_iso
def test_system_account_create( self ): # note: setUpClass will create and user with the id self.user_id assert self.user_id in set( self.esx_cli.system_account_list( index_by='UserID')) # confirm user exists with Sdk_User(user_id=self.user_id, password=self.password ) as sdk_user: # login to server with the temp user assert sdk_user.login_result is True # confirm login was ok assert Sdk().about_name( ) == 'VMware ESXi' # confirms we are able to login and make calls to the SOAP API assert self.esx_cli.system_account_create( self.user_id, self.password, self.description ) == f"The specified key, name, or identifier '{self.user_id}' already exists."
class VM_Process: def __init__(self, vm): self.sdk = Sdk() self.vm = vm self.vm_account = Config().vm_account() self.server_details = Config().vsphere_server_details() self.vm_user_name = self.vm_account['username'] self.vm_password = self.vm_account['password'] self.ip_server = self.server_details['host'] def exec(self, program_path, arguments=""): return self.start_process_return_stdout(program_path, arguments) def set_vm_account(self, username, password): self.vm_user_name = username self.vm_password = password def set_vm_account_from_env(self, env_prefix): self.vm_account['username'] = environ.get(f'{env_prefix}_USERNAME') self.vm_account['password'] = environ.get(f'{env_prefix}_PASSWORD') return self def start_process_return_stdout(self, program_path, arguments=""): content = self.sdk.content() # assert self.vm.guest().toolsStatus == 'toolsOk' file_stdout = f"/tmp/_vm_exec_{random_string()}" arguments += f" > {file_stdout}" # capture stdout in a file creds = pyVmomi.vim.vm.guest.NamePasswordAuthentication( username=self.vm_user_name, password=self.vm_password) pm = content.guestOperationsManager.processManager ps = pyVmomi.vim.vm.guest.ProcessManager.ProgramSpec( programPath=program_path, arguments=arguments) res = pm.StartProgramInGuest(self.vm.vm, creds, ps) file_transfer = content.guestOperationsManager.fileManager.InitiateFileTransferFromGuest( self.vm.vm, creds, file_stdout) file_url = file_transfer.url.replace("*:443", self.ip_server) resp = requests.get(file_url, verify=False) return resp.text # helper commands def curl(self, target='-h'): return self.exec('/usr/bin/curl', target) def ls(self, path=""): return self.exec('/bin/ls', path)
class Firewall: def __init__(self): self.sdk = Sdk() def hosts(self): return self.sdk.get_objects_Hosts() @group_by @index_by def rules(self): rules = [] for host in self.hosts(): for ruleset in host.configManager.firewallSystem.firewallInfo.ruleset: for ruleset_rule in ruleset.rule: pprint(ruleset) pprint(ruleset_rule) rule = { "allow_all_ips": ruleset.allowedHosts.allIp, "allow_ip_addresses": json_round_trip(ruleset.allowedHosts.ipNetwork), "allow_ip_networks": json_round_trip(ruleset.allowedHosts.ipAddress), "enabled": ruleset.enabled, "direction": ruleset_rule.direction, "key": ruleset.key, "label": ruleset.label, "port": ruleset_rule.port, "port_end": ruleset_rule.endPort, "port_type": ruleset_rule.portType, "protocol": ruleset_rule.protocol, "required": ruleset.required, "service": ruleset.service } rules.append(rule) #return rules return rules
class test_VM_Process(TestCase): def setUp(self) -> None: self.sdk = Sdk() self.vm_name = 'dinis-test-via-ovf' self.vm = self.sdk.find_by_name(self.vm_name) if self.vm is None: pytest.skip(f"target server did not have vm {self.vm_name}") else: if self.vm.powered_off(): pytest.skip( f"target server exists but it not Powered On {self.vm_name}" ) self.vm_process = VM_Process(vm=self.vm) def test_start_process_return_stdout(self): program_path = "/bin/ip" arguments = "a" result = self.vm_process.start_process_return_stdout( program_path, arguments) assert 'eth0: <BROADCAST,MULTICAST,UP,LOWER_UP>' in result
import sys from datetime import timedelta, datetime from dotenv import load_dotenv from k8_vmware.vsphere.Sdk import Sdk from k8_vmware.vsphere.VM import VM env_path = PurePath(__file__).parent / 'script.env' load_dotenv(dotenv_path=env_path) load_dotenv() rm_note = environ.get('rm_note') dont_rm_note = environ.get('dont_rm_note') expire_days_no = environ.get('expire_days_no', '') if not expire_days_no.isdigit(): print(" Expire days number must be integer") sys.exit(1) expire_days_no = int(expire_days_no) sdk = Sdk() vms_o = sdk.get_objects_Virtual_Machines() removed_VMs = [] now = datetime.now(pytz.utc) for vm_o in vms_o: vm = VM(vm_o) summary = vm.summary() info = vm.info() state = summary.runtime.powerState notes = summary.config.annotation create_date = vm_o.config.createDate if create_date < datetime(2000, 1, 1): continue if rm_note.lower() in notes.lower() or ( create_date < (now - timedelta(days=expire_days_no)) and dont_rm_note.lower() not in notes.lower()):
def test_vms_ips( self ): # todo: move to Sdk to method called vms_ips() (returns object with data) sdk = Sdk() for vm in sdk.vms(): print(f"{vm.name():30} {vm.powered_state():20} {vm.ip()}")
class Datastore: def __init__(self, name="datastore1", datacenter='ha-datacenter'): self.name = name self.datacenter = datacenter self.sdk = Sdk() def datastore(self): return self.sdk.get_object(pyVmomi.vim.Datastore, self.name) def delete(self, target): item_path = f'[{self.name}]/{target}'.replace('//','/') return self.delete_path(item_path) def delete_path(self, item_path): content = self.sdk.content() datacenter = self.sdk.datacenter() try: task = content.fileManager.DeleteDatastoreFile_Task(item_path, datacenter) Task().wait_for_task(task) if task.info.state == "success": return True except Exception as error: print(f"[Error][delete] {error.msg}") # todo: add global error handler and use it here return False def info(self): info = self.datastore().info vmfs = info.vmfs data = { "Capacity": self.sizeof_fmt(vmfs.capacity) , "Name" : info.name , "Type" : vmfs.type , "SSD" : vmfs.ssd , "UUID" : vmfs.uuid , } return data def add_query_details_to_search_spec(self,search_spec): query_details = pyVmomi.vim.host.DatastoreBrowser.FileInfo.Details(fileOwner = True, fileSize = True, fileType = True, modification = True) search_spec.details = query_details return self def execute_search_task(self, search_function, search_spec): self.add_query_details_to_search_spec(search_spec) task = search_function("[%s]" % self.name, search_spec) Task().wait_for_task(task) return task.info.result def get_search_data__for_files(self, search_results): data = [] for item in search_results: #print(item) for file in item.file: data.append({ "Folder_path": item.folderPath , "Modified" : str(file.modification) , "Owner" : file.owner , "FileName" : file.path , "Size" : self.sizeof_fmt(file.fileSize), "Type" : type(file).__name__.replace('vim.host.DatastoreBrowser.','') }) return data def get_search_data__for_folders(self, search_results): data = [] for item in search_results: data.append({ "Modified" : str(item.modification) , "Owner" : item.owner , "FolderName": item.path , "Size" : self.sizeof_fmt(item.fileSize) }) return data def file_delete(self, folder_name, file_name): file_path = f"{folder_name}/{file_name}" return self.delete(file_path) @index_by @group_by def files(self, match_pattern="*"): search_function = self.datastore().browser.SearchDatastoreSubFolders_Task search_spec = pyVmomi.vim.HostDatastoreBrowserSearchSpec() search_spec.matchPattern = match_pattern search_results = self.execute_search_task(search_function, search_spec) return self.get_search_data__for_files(search_results) def files_names(self, match_pattern="*"): return sorted(list(set(self.files(match_pattern, index_by='FileName')))) def files_paths(self, match_pattern="*"): files = self.files(match_pattern) paths = [] for file in files: path = f"{file['Folder_path']}/{file['FileName']}" #path = path.replace(f'[{self.name}] ', "") # remove datastore from path paths.append(path) return sorted(paths) # note the content.fileManager.MakeDirectory doesn't return a Task so need to keep an eye on this for side effect # it might be that these legacy methods do the folder creation in a sync way (vs a task) def folder_create(self, folder_name): folder_path = f'[{self.name}]/{folder_name}' content = self.sdk.content() datacenter = self.sdk.datacenter() content.fileManager.MakeDirectory(name=folder_path, datacenter=datacenter, createParentDirectories=True) # this method doesn't return a task #Task().wait_for_task(task) return True def folder_delete(self, folder_name): return self.delete(folder_name) @index_by @group_by def folders(self, match_pattern="*"): search_function = self.datastore().browser.SearchSubFolders query_folder = pyVmomi.vim.host.DatastoreBrowser.FolderQuery() search_spec = pyVmomi.vim.host.DatastoreBrowser.SearchSpec(query=[query_folder]) search_spec.matchPattern = match_pattern search_results = self.execute_search_task(search_function, search_spec) return self.get_search_data__for_folders(search_results[0].file) def folders_names(self, match_pattern="*"): return sorted(list(set(self.folders(match_pattern, index_by="FolderName")))) def sizeof_fmt(self, num): """ Returns the human readable version of a file size :param num: :return: """ for item in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0: return "%3.1f %s" % (num, item) num /= 1024.0 return "%3.1f %s" % (num, 'TB')
def __init__(self, name="datastore1", datacenter='ha-datacenter'): self.name = name self.datacenter = datacenter self.sdk = Sdk()
class Esxi_Power: """ Contains method to start or stop VM based on input conditions. """ def __init__(self): load_dotenv() self.mode_tag = environ.get("mode_tag", None) self.start_shut_tag = environ.get("start_shut_tag", None) self.not_shutdown_tag = environ.get("not_shutdown_tag", None) self.auto = int(environ.get("auto", 0)) self.sdk = Sdk() self.dt_format = "%Y-%m-%d %I:%M%p" self.action_maps = {"start": "power_on", "shutdown": "power_off"} def _get_vms(self): return self.sdk.vms() def get_targets(self): vms = self._get_vms() print(f"total vms : {len(vms)}") return vms def do_action(self, action, vm): vm_name = vm.name() if action not in self.action_maps.values(): print(f"invalid action : {action}") return print(f"{vm_name} : {action}") try: f = getattr(vm, self.action_maps.get(action)) # f() except Exception as ex: raise Exception(str(ex)) return vm_name def process_vm(self, vm): altered = False summary = vm.summary() notes = summary.config.annotation.lower() # print(f"Processing VM : {vm}, Note: {notes}") if not notes: print("No notes present on VM") return False if self.not_shutdown_tag: if self.not_shutdown_tag.lower() in notes: return False tag_present = self.start_shut_tag.lower() in notes action_present = self.mode_tag in self.action_maps.keys() if tag_present and action_present: altered = self.do_action(self.mode_tag, vm) return altered def process(self): altered_vms = [] vms = self.get_targets() for vm in vms: altered = self.process_vm(vm) if altered: altered_vms.append(altered) if altered_vms: print("Altered VMs: ") print("=============") print("\n".join(altered_vms)) else: print("No VM was Altered !") def validate_scheduled_mode(self): expected_dt = None if self.mode_tag == "start": expected_dt = environ.get("scheduled_start", None) elif self.mode_tag == "shutdown": expected_dt = environ.get("scheduled_stop", None) if not expected_dt: raise Exception( "`scheduled_start` or `scheduled_stop` not provided") return expected_dt def start(self): if not self.mode_tag or not self.start_shut_tag: print("`mode_tag` or `start_shut_tag` is not defined on env vars") return if self.mode_tag == "" or self.start_shut_tag == "": print("`mode_tag` or `start_shut_tag` should not be blank") return process = True if self.auto == 1: print("scheduled mode...") expected_dt = self.validate_scheduled_mode() expected_dt = Utils.format_expected_date(expected_dt, self.dt_format) # wait until time current_dt = None while expected_dt != current_dt: print(expected_dt, current_dt) time.sleep(30) current_dt = datetime.datetime.strftime( datetime.datetime.now(), self.dt_format) if current_dt == expected_dt: process = True if process: self.process()
def setUp(self) -> None: self.config = Config() self.sdk = Sdk()
def __init__(self): self.sdk = Sdk()
class VM_Server_113_4: def __init__(self): self.sdk = Sdk() self.network = Network() self.server_details = Config().vsphere_server_details() # settings self.vswitch_name = 'vSwitch0' self.port_group_name = 'VM' def settings__check(self): switches = self.network.virtual_switches() assert len(switches) == 1 # there should only be one virtual switch assert switches[0].name == self.vswitch_name # confirm expected name def setup_network(self): if self.port_group_name not in self.network.networks_names(): self.network.port_group_create(self.port_group_name, self.vswitch_name) def setup_network__check(self): assert self.port_group_name in self.network.networks_names() def get_network(self): return self.network.network(self.port_group_name) # Ubuntu VM tests def create_ubuntu_vm(self): vm_name = "test_ubuntu" iso_ubuntu = "[datastore1] isos/ubuntu-20.04.1-live-server-amd64.iso" vm = self.sdk.find_by_name(vm_name) if(vm): vm.task().delete() vm_create = VM_Create(vm_name=vm_name) vm_create.add_device__nic(self.get_network()) vm = vm_create.create() vm_device = VM_Device(vm) vm_device.cdrom_iso_add_to_vm(iso_ubuntu) vm_device.disk_ide_add_to_vm(10) vm.task().power_on() def ubuntu_vm_run_commands(self): vm_name = "test_ubuntu" vm = self.sdk.find_by_name(vm_name) vm_process = VM_Process(vm) vm_process.set_vm_account_from_env("VM_UBUNTU") print(vm_process.vm_account) #print(vm_process.ls("/")) # misc vm tests def minio_test_setup_network(self): vm = self.sdk.find_by_name("test-vm-from-ovf") vm_process = VM_Process(vm) #print(vm_process.exec('/bin/ip', 'a')) #print(vm_process.exec('/bin/ip', 'addr add 10.102.66.200/24 dev enp0s25')) #print(vm_process.exec('/bin/cat', '/etc/shadow')) #print(vm_process.exec('/bin/bash', '-c "sudo /bin/cat /etc/shadow"')) print(vm_process.exec('/bin/bash', '-c "sudo ip addr add 78.159.113.32/26 dev eth0"')) # commands from https://ubuntu.com/server/docs/network-configuration print(vm_process.exec('/bin/bash', '-c "sudo ip route add default via 78.159.113.62"')) print(vm_process.exec('/bin/ip', 'a')) print(vm_process.exec('/bin/ip', 'route show'))
def setUp(self): self.sdk = Sdk()
class test_Sdk(TestCase_VM): vm_name = f"tests__unit__" + __name__ def setUp(self): self.sdk = Sdk() def test_about(self): content = self.sdk.about() assert content.vendor == "VMware, Inc." assert content.version == "6.7.0" assert content.licenseProductName == "VMware ESX Server" assert content.licenseProductName == "VMware ESX Server" assert content.licenseProductVersion == "6.0" def test_file_info(self): datastore_path = 'an data store' vmx_file = self.sdk.file_info(datastore_path) assert vmx_file.vmPathName == datastore_path # def test_find_iso(self): # vm = self.sdk.find_by_host_name('haproxy-icap') # #pprint(vm.info()) # #print(self.sdk.json_dump("VirtualMachine","42")) # #vim.vm.device.VirtualCdrom # print(vm.config().hardware) def test_find_by_host_name(self): for vm in self.sdk.vms(): host_name = vm.host_name() if host_name: assert self.sdk.find_by_host_name( host_name).host_name() == host_name return print( "Warning test ESX server had no VMs with host_names (dnsNames) setup" ) def test_find_by_name(self): assert self.sdk.find_by_name(self.vm_name).name() == self.vm_name assert self.sdk.find_by_name("AAA_BBB_CCC") is None def test_find_by_ip(self): for vm in self.sdk.vms(): ip = vm.ip() if ip: assert self.sdk.find_by_ip(ip).ip() == ip return print("Warning test ESX server had no VMs with IPs") def test_find_by_uuid(self): uuid = self.vm.uuid() assert self.sdk.find_by_uuid(uuid).uuid() == uuid def test_get_object(self): name = self.vm.name() vm = self.sdk.get_object(pyVmomi.vim.VirtualMachine, name) assert vm.name == name def test_get_objects_Datastore(self): datastores = self.sdk.get_objects_Datastore() assert len(datastores) > 0 def test_get_object_virtual_machine(self): name = self.vm.name() vm = VM(self.sdk.get_object_virtual_machine(name)) assert vm.name() == name def test_get_objects(self): objects = self.sdk.get_objects() assert len(objects) > 0 def test_folders(self): folders = self.sdk.folders() assert str(folders) == "['vim.Folder:ha-folder-vm']" def test_vms(self): vms = self.sdk.vms() assert len(vms) > 0 def test_names(self): names = self.sdk.vms_names() assert len(names) > 0 def test_service_instance(self): service_instance = self.sdk.service_instance() assert service_instance.content.about.apiVersion == '6.7.3' assert service_instance.content.about.licenseProductName == 'VMware ESX Server' assert service_instance.content.about.osType == 'vmnix-x86' def test_dump_json(self): obj_type = "VirtualMachine" moid = self.vm.moid() json_dump = self.sdk.json_dump(obj_type, moid) json_data = json.loads(json_dump) assert json_data['_vimid'] == moid assert json_data['_vimtype'] == "vim.VirtualMachine" def test_tasks( self ): # todo: find better way to do this since when running multiple tests the self.sdk.tasks_recent() can take multiple seconds to execute self.sdk.find_by_ip('aaaaaa') recent_tasks = self.sdk.tasks_recent() most_recent_one = recent_tasks.pop() assert most_recent_one['DescriptionId'] == 'SearchIndex.findByIp' assert most_recent_one[ 'Key'] == f"haTask--vim.SearchIndex.findByIp-{most_recent_one['EventChainId']}" assert most_recent_one['State'] == 'success' assert most_recent_one['Entity'] == 'None'
def __init__(self): self.url_core_iso = 'https://distro.ibiblio.org/tinycorelinux/11.x/x86/release/Core-current.iso' self.path_core_iso = '/tmp/core-currenet.iso' self.vm_name = 'tiny-core-linux' self.sdk = Sdk()