def_get_content(self): si = self._connect_vc() content = si.RetrieveContent() return content
def_get_obj_bymoId(self, content, vimtype, moId): obj = None container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True) for c in container.view: if moId: if c._moId == moId: obj = c break else: obj = None break return obj
defget_obj(self, content, vimtype, name): """ Return an object by name, if name is None the first found object is returned """ obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if name: if c.name == name: obj = c break else: obj = c break
return obj
def_wait_for_task(self, task): """ wait for a vCenter task to finish """ task_done = False whilenot task_done: if task.info.state == 'success': return {"result": True, "data": task.info.result} if task.info.state == 'error': return {"result": False, "data": task.info.error.msg}
content = si.RetrieveContent() logger.info('Searching for VM {}'.format(vmname)) vm_obj = self.get_obj(content, [vim.VirtualMachine], vmname)
if vm_obj: result = self.update_virtual_nic_state(vm_obj, unitnumber, state) logger.info('VM NIC {} successfully' \ ' state changed to {}'.format(unitnumber, state)) return {"result": result} else: logger.error('VM not found') return {"result": False, "message": "VM not found"}
defupdate_virtual_nic_state(self, vm_obj, nic_number, new_nic_state): """ :param vm_obj: Virtual Machine Object :param nic_number: Network Interface Controller Number :param new_nic_state: Either Connect, Disconnect or Delete :return: True if success """ nic_prefix_label = 'Network adapter ' nic_label = nic_prefix_label + str(nic_number) virtual_nic_device = None for dev in vm_obj.config.hardware.device: ifisinstance(dev, vim.vm.device.VirtualEthernetCard) \ and dev.deviceInfo.label == nic_label: virtual_nic_device = dev ifnot virtual_nic_device: raise RuntimeError('Virtual {} could not be found.'.format(nic_label))