def __get_esxi_host(self): '''get esxi host''' esxi_list = [] for ds_mor, name in self.s.get_hosts().items(): props = VIProperty(self.s, ds_mor) powerState = props.runtime.powerState # power status date = props.runtime.bootTime # boot time bootTime = "%s-%s-%s %s:%s:%s" % (date[0], date[1], date[2], date[3], date[4], date[5]) props._flush_cache() cpuUsage = props.summary.quickStats.overallCpuUsage # get esxi cpu Usage MemoryUsage = props.summary.quickStats.overallMemoryUsage CpuCores = props.hardware.cpuInfo.numCpuCores MemorySize = props.hardware.memorySize dt = { "HostID": ds_mor, "HostName": name, "powerState": powerState, "bootTime": bootTime, "cpuUsage": cpuUsage, "MemoryUsage": MemoryUsage, "CpuCores": CpuCores, "MemorySize": MemorySize } esxi_list.append(dt) dd = {"Esxi": esxi_list} self._baseData.append(dd)
def deploy_template(vsphere_client, guest, resource_pool, template_src, esxi, module, cluster_name, snapshot_to_clone): vmTemplate = vsphere_client.get_vm_by_name(template_src) vmTarget = None if esxi: datacenter = esxi['datacenter'] esxi_hostname = esxi['hostname'] # Datacenter managed object reference dclist = [ k for k, v in vsphere_client.get_datacenters().items() if v == datacenter ] if dclist: dcmor = dclist[0] else: vsphere_client.disconnect() module.fail_json(msg="Cannot find datacenter named: %s" % datacenter) dcprops = VIProperty(vsphere_client, dcmor) # hostFolder managed reference hfmor = dcprops.hostFolder._obj # Grab the computerResource name and host properties crmors = vsphere_client._retrieve_properties_traversal( property_names=['name', 'host'], from_node=hfmor, obj_type='ComputeResource') # Grab the host managed object reference of the esxi_hostname try: hostmor = [ k for k, v in vsphere_client.get_hosts().items() if v == esxi_hostname ][0] except IndexError, e: vsphere_client.disconnect() module.fail_json(msg="Cannot find esx host named: %s" % esxi_hostname) # Grab the computeResource managed object reference of the host we are # creating the VM on. crmor = None for cr in crmors: if crmor: break for p in cr.PropSet: if p.Name == "host": for h in p.Val.get_element_ManagedObjectReference(): if h == hostmor: crmor = cr.Obj break if crmor: break crprops = VIProperty(vsphere_client, crmor) rpmor = crprops.resourcePool._obj
def __init__(self, server, entity=None, recursion=None, types=None, chain_id=None): """Creates a Event History Collector that gathers Event objects. based on the provides filters. * server: the connected VIServer instance * entity: Entity MOR, if provided filters events related to this entity * recursion: If 'entity' is provided then recursion is mandatory. specification of related managed entities in the inventory hierarchy should be either: 'all', 'children', or 'self' * types: if provided, limits the set of collected events by their types. * chain_id: if provided, retrieves events by chain ID """ super(VIEventHistoryCollector, self).__init__(server) if entity and not VIMor.is_mor(entity): raise VIException("Entity should be a MOR object", FaultTypes.PARAMETER_ERROR) if entity and not recursion in [Recursion.ALL, Recursion.CHILDREN, Recursion.SELF]: raise VIException("Recursion should be either: " "'all', 'children', or 'self'", FaultTypes.PARAMETER_ERROR) try: event_manager = server._do_service_content.EventManager request = VI.CreateCollectorForEventsRequestMsg() _this = request.new__this(event_manager) _this.set_attribute_type(event_manager.get_attribute_type()) request.set_element__this(_this) _filter = request.new_filter() if types and not isinstance(types, list): types = [types] if types: _filter.set_element_eventTypeId(types) if chain_id is not None: _filter.set_element_eventChainId(chain_id) if entity: entity_filter = _filter.new_entity() mor_entity = entity_filter.new_entity(entity) mor_entity.set_attribute_type(entity.get_attribute_type()) entity_filter.set_element_entity(mor_entity) entity_filter.set_element_recursion(recursion) _filter.set_element_entity(entity_filter) request.set_element_filter(_filter) resp = server._proxy.CreateCollectorForEvents(request)._returnval except (VI.ZSI.FaultException) as e: raise VIApiException(e) self._mor = resp self._props = VIProperty(self._server, self._mor)
def __init__(self, server, entity=None, recursion=None, states=None): """Creates a Task History Collector that gathers Task info objects. based on the provides filters. * server: the connected VIServer instance * entity: Entity MOR, if provided filters tasks related to this entity * recursion: If 'entity' is provided then recursion is mandatory. specification of related managed entities in the inventory hierarchy should be either: 'all', 'children', or 'self' * states: if provided, limits the set of collected tasks by their states. Should be a list or one of 'queued', 'running', 'error', or 'success' """ self._server = server self._mor = None if entity and not VIMor.is_mor(entity): raise VIException("Entity should be a MOR object", FaultTypes.PARAMETER_ERROR) if entity and not recursion in [ Recursion.ALL, Recursion.CHILDREN, Recursion.SELF ]: raise VIException( "Recursion should be either: " "'all', 'children', or 'self'", FaultTypes.PARAMETER_ERROR) try: task_manager = server._do_service_content.TaskManager request = VI.CreateCollectorForTasksRequestMsg() _this = request.new__this(task_manager) _this.set_attribute_type(task_manager.get_attribute_type()) request.set_element__this(_this) _filter = request.new_filter() if states and not isinstance(states, list): states = [states] if states: _filter.set_element_state(states) if entity: entity_filter = _filter.new_entity() mor_entity = entity_filter.new_entity(entity) mor_entity.set_attribute_type(entity.get_attribute_type()) entity_filter.set_element_entity(mor_entity) entity_filter.set_element_recursion(recursion) _filter.set_element_entity(entity_filter) request.set_element_filter(_filter) resp = server._proxy.CreateCollectorForTasks(request)._returnval except (VI.ZSI.FaultException) as e: raise VIApiException(e) self._mor = resp self._props = VIProperty(self._server, self._mor)
def get_file_list(datastore, path="/", case_insensitive=True, folders_first=True, match_patterns=[]): ds = [k for k, v in s.get_datastores().items() if v == datastore][0] ds_browser = VIProperty(s, ds).browser._obj request = VI.SearchDatastore_TaskRequestMsg() _this = request.new__this(ds_browser) _this.set_attribute_type(ds_browser.get_attribute_type()) request.set_element__this(_this) request.set_element_datastorePath("[%s] %s" % (datastore, path)) search_spec = request.new_searchSpec() query = [ VI.ns0.FloppyImageFileQuery_Def('floppy').pyclass(), VI.ns0.FolderFileQuery_Def('folder').pyclass(), VI.ns0.IsoImageFileQuery_Def('iso').pyclass(), VI.ns0.VmConfigFileQuery_Def('vm').pyclass(), VI.ns0.TemplateConfigFileQuery_Def('template').pyclass(), VI.ns0.VmDiskFileQuery_Def('vm_disk').pyclass(), VI.ns0.VmLogFileQuery_Def('vm_log').pyclass(), VI.ns0.VmNvramFileQuery_Def('vm_ram').pyclass(), VI.ns0.VmSnapshotFileQuery_Def('vm_snapshot').pyclass() ] search_spec.set_element_query(query) details = search_spec.new_details() details.set_element_fileOwner(True) details.set_element_fileSize(True) details.set_element_fileType(True) details.set_element_modification(True) search_spec.set_element_details(details) search_spec.set_element_searchCaseInsensitive(case_insensitive) search_spec.set_element_sortFoldersFirst(folders_first) search_spec.set_element_matchPattern(match_patterns) request.set_element_searchSpec(search_spec) response = s._proxy.SearchDatastore_Task(request)._returnval task = VITask(response, s) if task.wait_for_state([task.STATE_ERROR, task.STATE_SUCCESS]) == task.STATE_ERROR: raise Exception(task.get_error_message()) info = task.get_result() if not hasattr(info, "file"): return [] return [ { 'path': fi.path, #'size':fi.fileSize, #'modified':fi.modification, #'owner':fi.owner } for fi in info.file ]
def list_files(self, path, case_insensitive=True, folders_first=True, match_patterns=[]): """Return a list of files in folder @path """ ds_name, file_name = re.match(self._re_path, path).groups() ds = [k for k,v in self._server.get_datastores().items() if v == ds_name][0] browser_mor = VIProperty(self._server, ds).browser._obj request = VI.SearchDatastore_TaskRequestMsg() _this = request.new__this(browser_mor) _this.set_attribute_type(browser_mor.get_attribute_type()) request.set_element__this(_this) request.set_element_datastorePath(path) search_spec = request.new_searchSpec() query = [VI.ns0.FloppyImageFileQuery_Def('floppy').pyclass(), VI.ns0.FileQuery_Def('file').pyclass(), VI.ns0.FolderFileQuery_Def('folder').pyclass(), VI.ns0.IsoImageFileQuery_Def('iso').pyclass(), VI.ns0.VmConfigFileQuery_Def('vm').pyclass(), VI.ns0.TemplateConfigFileQuery_Def('template').pyclass(), VI.ns0.VmDiskFileQuery_Def('vm_disk').pyclass(), VI.ns0.VmLogFileQuery_Def('vm_log').pyclass(), VI.ns0.VmNvramFileQuery_Def('vm_ram').pyclass(), VI.ns0.VmSnapshotFileQuery_Def('vm_snapshot').pyclass()] search_spec.set_element_query(query) details = search_spec.new_details() details.set_element_fileOwner(True) details.set_element_fileSize(True) details.set_element_fileType(True) details.set_element_modification(True) search_spec.set_element_details(details) search_spec.set_element_searchCaseInsensitive(case_insensitive) search_spec.set_element_sortFoldersFirst(folders_first) search_spec.set_element_matchPattern(match_patterns) request.set_element_searchSpec(search_spec) response = self._server._proxy.SearchDatastore_Task(request)._returnval vi_task = VITask(response, self._server) if vi_task.wait_for_state([vi_task.STATE_ERROR, vi_task.STATE_SUCCESS]) == vi_task.STATE_ERROR: raise VITaskException(vi_task.info.error) info = vi_task.get_result() # return info if not hasattr(info, "file"): return [] # for fi in info.file: # fi._get_all() return [{'type':fi._type, 'path':fi.path, 'size':fi.fileSize, 'modified':fi.modification, 'owner':fi.owner } for fi in info.file]
def test_property_types(self): hosts = self.server.get_hosts() for hmor, hname in hosts.items(): p = VIProperty(self.server, hmor) assert p.name == hname #string assert isinstance(p.name, str) #property mor assert VIMor.is_mor(p._obj) #nested properties assert isinstance(p.configManager, VIProperty) #bool assert isinstance(p.runtime.inMaintenanceMode, bool) #list assert isinstance(p.vm, list) #mor without traversing assert VIMor.is_mor(p.vm[0]._obj) #traversing assert isinstance(p.vm[0].name, str) #enum assert p.runtime.powerState in [ 'poweredOff', 'poweredOn', 'standBy', 'unknown' ] #int assert isinstance(p.summary.config.port, int) #long assert isinstance(p.hardware.memorySize, int) #short as int assert isinstance(p.hardware.cpuInfo.numCpuCores, int) #date as tuple assert isinstance(p.runtime.bootTime, tuple) #check property cache assert "runtime" in list(p.__dict__.keys()) assert "memorySize" in list(p.hardware.__dict__.keys()) assert "numCpuCores" in list(p.hardware.cpuInfo.__dict__.keys()) assert "name" in list(p.vm[0].__dict__.keys()) #check cache flush p._flush_cache() assert "runtime" not in list(p.__dict__.keys()) assert "memorySize" not in list(p.hardware.__dict__.keys()) assert "numCpuCores" not in list( p.hardware.cpuInfo.__dict__.keys()) assert "name" not in list(p.vm[0].__dict__.keys()) #check unexistent property try: p.hoochiemama except AttributeError: pass except: raise AssertionError("Attribute Error expected") else: raise AssertionError("Attribute Error expected")
def lease(http_nfc_lease, ovf_file_path, server): u"""Uploading request files. @param http_nfc_lease Lease @param server Insrance of VIServer """ # Import import time import threading from pysphere import VIProperty from pysphere.resources import VimService_services as VI go_on = True lease = VIProperty(server, http_nfc_lease) while lease.state == 'initializing': print lease.state lease._flush_cache() if lease.state != 'ready': print "something went wrong" exit() def keep_lease_alive(lease): u"""プロセスを継続させる @param leaese 仮のVM """ request = VI.HttpNfcLeaseProgressRequestMsg() _this = request.new__this(lease) _this.set_attribute_type(lease.get_attribute_type()) request.set_element__this(_this) request.set_element_percent(50) while go_on: server._proxy.HttpNfcLeaseProgress(request) time.sleep(5) t = threading.Thread(target=keep_lease_alive, args=(http_nfc_lease,)) t.start() # Upload print 'Uploading...' upload_format_file(lease, '.vmdk', ovf_file_path, server) go_on = False t.join() request = VI.HttpNfcLeaseCompleteRequestMsg() _this = request.new__this(http_nfc_lease) _this.set_attribute_type(http_nfc_lease.get_attribute_type()) request.set_element__this(_this) server._proxy.HttpNfcLeaseComplete(request)
def test_property_types(self): hosts = self.server.get_hosts() for hmor, hname in hosts.iteritems(): p = VIProperty(self.server, hmor) assert p.name == hname #string assert isinstance(p.name, basestring) #property mor assert VIMor.is_mor(p._obj) #nested properties assert isinstance(p.configManager, VIProperty) #bool assert isinstance(p.runtime.inMaintenanceMode, bool) #list assert isinstance(p.vm, list) #mor without traversing assert VIMor.is_mor(p.vm[0]._obj) #traversing assert isinstance(p.vm[0].name, basestring) #enum assert p.runtime.powerState in ['poweredOff', 'poweredOn', 'standBy', 'unknown'] #int assert isinstance(p.summary.config.port, int) #long assert isinstance(p.hardware.memorySize, long) #short as int assert isinstance(p.hardware.cpuInfo.numCpuCores, int) #date as tuple assert isinstance(p.runtime.bootTime, tuple) #check property cache assert "runtime" in p.__dict__.keys() assert "memorySize" in p.hardware.__dict__.keys() assert "numCpuCores" in p.hardware.cpuInfo.__dict__.keys() assert "name" in p.vm[0].__dict__.keys() #check cache flush p._flush_cache() assert "runtime" not in p.__dict__.keys() assert "memorySize" not in p.hardware.__dict__.keys() assert "numCpuCores" not in p.hardware.cpuInfo.__dict__.keys() assert "name" not in p.vm[0].__dict__.keys() #check unexistent property try: p.hoochiemama except AttributeError: pass except: raise AssertionError("Attribute Error expected") else: raise AssertionError("Attribute Error expected")
def find_vmfolder_by_name(folder_name): ret = None for dc in s.get_datacenters().keys(): dc_properties = VIProperty(s, dc) if dc_properties.vmFolder.name == folder_name: return dc_properties.vmFolder._obj raise ValueError("Couldn't find folder '%s'" % (folder_name))
def find_datastore(module, s, datastore, config_target): # Verify the datastore exists and put it in brackets if it does. ds = None if config_target: for d in config_target.Datastore: if (d.Datastore.Accessible and (datastore and d.Datastore.Name == datastore) or (not datastore)): ds = d.Datastore.Datastore datastore = d.Datastore.Name break else: for ds_mor, ds_name in server.get_datastores().items(): ds_props = VIProperty(s, ds_mor) if (ds_props.summary.accessible and (datastore and ds_name == datastore) or (not datastore)): ds = ds_mor datastore = ds_name if not ds: s.disconnect() module.fail_json(msg="Datastore: %s does not appear to exist" % (datastore)) datastore_name = "[%s]" % datastore return datastore_name, ds
def __read_events(self, max_count, next_page): """ Reads the 'scrollable view' from the current position. """ if not isinstance(max_count, int): raise VIException("max_count should be an integer", FaultTypes.PARAMETER_ERROR) if next_page: request = VI.ReadNextEventsRequestMsg() else: request = VI.ReadPreviousEventsRequestMsg() _this = request.new__this(self._mor) _this.set_attribute_type(self._mor.get_attribute_type()) request.set_element__this(_this) request.set_element_maxCount(max_count) try: if next_page: resp = self._server._proxy.ReadNextEvents(request)._returnval else: resp = self._server._proxy.ReadPreviousEvents(request)._returnval ret = [] for event in resp: ret.append(VIProperty(self._server,event)) except (VI.ZSI.FaultException), e: raise VIApiException(e)
def createGuest(host_con, guest_dc, guest_host, guest_name, guest_ver, guest_mem, guest_cpu, guest_iso, guest_os, guest_disk_gb, guest_ds, guest_networkg, guest_enterbios): #get dc MOR from list dc_list = [ k for k, v in host_con.get_datacenters().items() if v == guest_dc ] if dc_list: dc_mor = dc_list[0] else: host_con.disconnect() return "Cannot find dc: " + guest_dc dc_props = VIProperty(host_con, dc_mor) #get vmFolder vmf_mor = dc_props.vmFolder._obj #get hostfolder MOR hf_mor = dc_props.hostFolder._obj #get computer resources MORs cr_mors = host_con._retrieve_properties_traversal( property_names=['name', 'host'], from_node=hf_mor, obj_type='ComputeResource') #get host MOR try: host_mor = [ k for k, v in host_con.get_hosts().items() if v == guest_host ][0] except IndexError, e: host_con.disconnect() return "Cannot find host: " + guest_host
def GetDvsUuid(self,dc_name,portgroupKey): dcmor = [k for k,v in self.__s.get_datacenters().items() if v==dc_name][0] dcprops = VIProperty(self.__s, dcmor) nfmor = dcprops.networkFolder._obj # Grab the dvswitch uuid and portgroup properties dvswitch_mors = self.__s._retrieve_properties_traversal(property_names=['uuid','portgroup'], from_node=nfmor, obj_type='DistributedVirtualSwitch') dvswitch_mor = None # Get the appropriate dvswitches managed object for dvswitch in dvswitch_mors: if dvswitch_mor: break for p in dvswitch.PropSet: if p.Name == "portgroup": pg_mors = p.Val.ManagedObjectReference for pg_mor in pg_mors: if dvswitch_mor: break key_mor = self.__s._get_object_properties(pg_mor, property_names=['key']) for key in key_mor.PropSet: if key.Val == portgroupKey: dvswitch_mor = dvswitch # Get the switches uuid dvswitch_uuid = None for p in dvswitch_mor.PropSet: if p.Name == "uuid": dvswitch_uuid = p.Val return dvswitch_uuid
def create(self, name, numcpu, numinterfaces, diskmode1,disksize1, ds, memory, guestid, net1, net2=None, net3=None, net4=None, thin=False,distributed=False,diskmode2=None,disksize2=None,vnc=False): s = self.s memory = int(memory) numcpu = int(numcpu) disksize1 = int(disksize1) if disksize2: disksize2 = int(disksize2) numinterfaces = int(numinterfaces) if guestid in guests.keys(): guestid = guests[guestid] disksize1 = disksize1*1048576 disksizeg1 = convert(1000*disksize1) if disksize2: disksize2 = disksize2*1048576 disksizeg2 = convert(1000*disksize2) dclist = {} dslist = {} networklist = {} guestlist = [] si = self.si rootFolder = si.getRootFolder() dc = self.dc clu = self.clu #get datacenter dcmor = s._get_datacenters()[datacentername] dcprops = VIProperty(s, dcmor) #get host folder hfmor = dcprops.hostFolder._obj #get computer resources crmors = s._retrieve_properties_traversal(property_names=['name','host'], from_node=hfmor, obj_type='ComputeResource')
def get_portgroup_by_dvSwitchname(vCenterserver, username, password, datacentername, dvSwitchname): con = vs_connect(vCenterserver, username, password) dcmor = [ k for k, v in con.get_datacenters().items() if v == datacentername ][0] dcprops = VIProperty(con, dcmor) nfmor = dcprops.networkFolder._obj portgroup_mors = con._retrieve_properties_traversal( property_names=['name', 'portgroup'], from_node=nfmor, obj_type='VmwareDistributedVirtualSwitch') RespDic = {} for portgroup_mor in portgroup_mors: if (portgroup_mor.get_element_propSet()[0].get_element_val() == dvSwitchname): pgRefs = portgroup_mor.get_element_propSet()[1].get_element_val( ).ManagedObjectReference for pgRef in pgRefs: portgroup_mors = con._retrieve_properties_traversal( property_names=['name', 'key'], from_node=nfmor, obj_type='DistributedVirtualPortgroup') for portgroup_mor in portgroup_mors: ref = portgroup_mor.get_element_propSet()[0].get_element_val() if ref == pgRef: name = portgroup_mor.get_element_propSet()[1].get_element_val() RespDic[name] = pgRef return RespDic
def __get_dvs_uuid(self, dcmor, pgmor): dcprops = VIProperty(self.server, dcmor) nfmor = dcprops.networkFolder._obj # "Grab the dvswitch uuid and portgroup properties" dvswitch_mors = self.server._retrieve_properties_traversal( property_names=['uuid', 'portgroup'], from_node=nfmor, obj_type='DistributedVirtualSwitch') dvswitch_mor = None # "Get the appropriate dvswitches managed object" for dvswitch in dvswitch_mors: if dvswitch_mor: break for p in dvswitch.PropSet: if p.Name == "portgroup": pg_mors = p.Val.ManagedObjectReference for pg_mor in pg_mors: if dvswitch_mor: break key_mor = self.server._get_object_properties( pg_mor, property_names=['key']) for key in key_mor.PropSet: if key.Val == pgmor: dvswitch_mor = dvswitch # Get the switches uuid dvswitch_uuid = None if dvswitch_mor: for p in dvswitch_mor.PropSet: if p.Name == "uuid": dvswitch_uuid = p.Val return dvswitch_uuid
def UpdateNodeDisk(self): for ds_mor, name in self.__server.get_datastores().items(): props = VIProperty(self.__server, ds_mor) new = dict() new['name'] = name new['total'] = props.summary.capacity new['free'] = props.summary.freeSpace node_disk.objects.filter(datastore_id=ds_mor).update(**new)
def __init__(self): self.host = config.vmware_host self.user = config.vmware_user self.pwd = config.vmware_pass self.connection = VIServer() self.connection.connect(self.host, self.user, self.pwd) self.props = VIProperty(self.connection, self.connection._do_service_content.CustomFieldsManager) self.custom_fields = dict((cf.key, cf.name) for cf in self.props.field)
def test_if_all_hosts_arent_in_maintenance(self): """Are all the hosts out of the maintenance?""" hosts = self.server.get_hosts() for host in hosts: host_mor = VIMor(host, 'HostSystem') host_props = VIProperty(self.server, host_mor) self.assertFalse(host_props.runtime.inMaintenanceMode, u"Host Not Activated:{}".format( host))
def test_get_hosts_by_cluster(self): clusters = self.server.get_clusters() count_hosts1 = 0 count_hosts2 = 0 for cl in list(clusters.keys()): count_hosts1 += len(self.server.get_hosts(from_mor=cl)) prop = VIProperty(self.server, cl) count_hosts2 += len(prop.host) assert count_hosts1 == count_hosts2
def _get_host_config(self): # -> get Datacenter and it's properties dc_mor = [k for k, v in self._connection.get_datacenters().items() ][-1] # just take the last one .... good? dc_props = VIProperty(self._connection, dc_mor) # -> get computer resources MORs cr_mors = self._connection._retrieve_properties_traversal( property_names=['name', 'host'], from_node=dc_props.hostFolder._obj, # hostfolder mor obj_type='ComputeResource') # -> get host MOR host_mor = [k for k, v in self._connection.get_hosts().items() ][-1] # just take the last one .... good? # -> get computer resource MOR for host cr_mor = None for cr in cr_mors: if cr_mor: break for p in cr.PropSet: if p.Name == "host": for h in p.Val.get_element_ManagedObjectReference(): if h == host_mor: cr_mor = cr.Obj break if cr_mor: break # -> get Computer Ressources cr_props = VIProperty(self._connection, cr_mor) # -> create configuration request() request = VI.QueryConfigTargetRequestMsg() _this = request.new__this(cr_props.environmentBrowser._obj) _this.set_attribute_type( cr_props.environmentBrowser._obj.get_attribute_type()) request.set_element__this(_this) # -> get answer back! config_target = self._connection._proxy.QueryConfigTarget( request)._returnval return config_target, host_mor, dc_props, cr_props
def create_vm(vsphere_client, module, esxi, resource_pool, cluster_name, guest, vm_extra_config, vm_hardware, vm_disk, vm_nic, vm_hw_version, state): datacenter = esxi['datacenter'] esxi_hostname = esxi['hostname'] # Datacenter managed object reference dclist = [ k for k, v in vsphere_client.get_datacenters().items() if v == datacenter ] if dclist: dcmor = dclist[0] else: vsphere_client.disconnect() module.fail_json(msg="Cannot find datacenter named: %s" % datacenter) dcprops = VIProperty(vsphere_client, dcmor) # hostFolder managed reference hfmor = dcprops.hostFolder._obj # virtualmachineFolder managed object reference if vm_extra_config.get('folder'): if vm_extra_config[ 'folder'] not in vsphere_client._get_managed_objects( MORTypes.Folder).values(): vsphere_client.disconnect() module.fail_json(msg="Cannot find folder named: %s" % vm_extra_config['folder']) for mor, name in vsphere_client._get_managed_objects( MORTypes.Folder).iteritems(): if name == vm_extra_config['folder']: vmfmor = mor else: vmfmor = dcprops.vmFolder._obj # networkFolder managed object reference nfmor = dcprops.networkFolder._obj # Grab the computerResource name and host properties crmors = vsphere_client._retrieve_properties_traversal( property_names=['name', 'host'], from_node=hfmor, obj_type='ComputeResource') # Grab the host managed object reference of the esxi_hostname try: hostmor = [ k for k, v in vsphere_client.get_hosts().items() if v == esxi_hostname ][0] except IndexError, e: vsphere_client.disconnect() module.fail_json(msg="Cannot find esx host named: %s" % esxi_hostname)
def test_if_all_hosts_are_in_maintenance(self): """Todos os hosts estão em modo de manutenção?""" server = vcenter_connect() hosts = server.get_hosts() for host in hosts: host_mor = VIMor(host, 'HostSystem') host_props = VIProperty(server, host_mor) self.assertTrue(host_props.runtime.inMaintenanceMode, u"Nem todos os hosts estão desativados")
def GetDVS(self): try: s = self.__server for x, y in s.get_datacenters().items(): dcprops = VIProperty(s, x) dc = datacenter.objects.get(conn=self.__vc_id, name=y) hfmor = dcprops.networkFolder._obj dvpg_mors = s._retrieve_properties_traversal( property_names=['name', 'portgroup', 'summary.hostMember'], from_node=hfmor, obj_type='DistributedVirtualSwitch') for item in dvpg_mors: DVS = dict() for p in item.PropSet: if p.Name == 'name': DVS['name'] = p.Val if p.Name == 'portgroup': portgroup = list() pg_mors = p.Val.ManagedObjectReference for pg_mor in pg_mors: key_mor = s._get_object_properties( pg_mor, property_names=['config.name']) for key in key_mor.PropSet: portgroup.append(key.Val) DVS['portgroup'] = portgroup if p.Name == 'summary.hostMember': host = list() pg_mors = p.Val.ManagedObjectReference for pg_mor in pg_mors: key_mor = s._get_object_properties( pg_mor, property_names=['name']) for key in key_mor.PropSet: host.append(key.Val) DVS['host'] = host mysql_dvs = {'type': 1, 'conn': self.__vc_id} mysql_dvs['vswitch'] = DVS['name'] for q in DVS['portgroup']: mysql_dvs['name'] = q for w in DVS['host']: mysql_dvs['node'] = node.objects.get( name=str(w), conn=self.__vc_id) rs = node_network.objects.filter(**mysql_dvs) if rs.count() == 0: mysql_dvs['times'] = str(int(time.time())) mysql_dvs['vlan'] = 0 mysql_dvs['todc'] = dc node_network(**mysql_dvs).save() del mysql_dvs['times'] del mysql_dvs['vlan'] else: rs.update(times=str(int(time.time()))) except Exception, e: pass
def get_vswitch(server): """Return a list of vswitch dict with keys name, nicDevice""" mor, name = server.get_hosts().items()[0] prop = VIProperty(server, mor) ret_val = [] for v in prop.configManager.networkSystem.networkConfig.vswitch: name = v.name nicDevice = v.spec.bridge.nicDevice # this is a list ret_val.append({'name': name, 'nicDevice': nicDevice}) return ret_val
def find_network_by_name(network_name): ret = None for dc in s.get_datacenters().keys(): dc_properties = VIProperty(s, dc) for nw in dc_properties.network: if nw.name == network_name: ret = nw._obj break if ret: break if not ret: raise ValueError("Couldn't find network '%s'" % (network_name)) return ret
def get_datastores(server): """Return a list of datastore dict with keys name, capacity, freeSpace""" ret_val = [] for ds_mor, name in server.get_datastores().items(): props = VIProperty(server, ds_mor) capacity = props.summary.capacity / 1024 / 1024 freeSpace = props.summary.freeSpace / 1024 / 1024 ret_val.append({ 'name': name, 'capacity': capacity, 'freeSpace': freeSpace }) return ret_val
def __get_network_for_pgmor(self, dcmor, pgmor): dcprops = VIProperty(self.server, dcmor) # "networkFolder managed object reference" nfmor = dcprops.networkFolder._obj dvpg_mors = self.server._retrieve_properties_traversal( property_names=['name'], from_node=nfmor, obj_type='Network') # "get the portgroup managed object." for dvpg in dvpg_mors: logger.info('dvpg obj: %s' % dvpg._obj) if dvpg._obj == pgmor: for p in dvpg.PropSet: if p.Name == "name": return p.Val return None
def get_host_info(self): hosts = self.server.get_hosts() for host in hosts: p = VIProperty(self.server, host) overallCpuUsage = p.summary.quickStats.overallCpuUsage overallMemoryUsage = p.summary.quickStats.overallMemoryUsage averagedCpuSpeedPerCore = p.hardware.cpuInfo.hz numCpuCores = p.hardware.cpuInfo.numCpuCores totalCpuSpeed = averagedCpuSpeedPerCore * numCpuCores totalMemorySize = p.hardware.memorySize uptime = p.summary.quickStats.uptime uptime = uptime * 100 print "Host:%s | IP:%s | CpuUsage=%s MemoryUsage=%s" % (str(hosts.keys()[0]), str(hosts.values()[0]), str(overallCpuUsage), str(overallMemoryUsage))
def getstorage(self): s = self.s dc = s._get_datacenters()[self.dc] dcprop = VIProperty(s, dc) dc = dcprop.name dcs = s.get_datacenters() # for mor, name in dcs.items(): # if name == self.dc: # dcmor = mor # break # clusters = s.get_clusters(from_mor=dcmor) # for mor, name in clusters.items(): # if name == self.clu: # clumor = mor # break # hosts = s.get_hosts(from_mor=clumor) # for mor, name in hosts.items(): # print mor,name # hostprop = VIProperty(s, mor) # print hostprop.vm results = {} for dts in s.get_datastores(): props=VIProperty(s, dts) vms = props.vm clumember = False # for vm in vms: # print vm._obj # #vm = VIProperty(s, mor) # #vm = s.get_vm_by_name(vm.name) # #print vm.properties.runtime.host.name # break datastorename = props.name total = props.summary.capacity / 1024 / 1024 /1024 available = props.summary.freeSpace / 1024 / 1024 /1024 results[datastorename] = [total, available, dc] return results
def get_dvSwitchs_by_DCname(vCenterserver, username, password, datacentername): con = vs_connect(vCenterserver, username, password) dcmor = [ k for k, v in con.get_datacenters().items() if v == datacentername ][0] dcprops = VIProperty(con, dcmor) nfmor = dcprops.networkFolder._obj dvswitch_mors = con._retrieve_properties_traversal( property_names=['name'], from_node=nfmor, obj_type='DistributedVirtualSwitch') respdict = {} for dvswitch_mor in dvswitch_mors: respdict[dvswitch_mor.PropSet[0]._val] = dvswitch_mor.Obj return respdict
datastore, ovf, VAPP_NAME, host=host, network_mapping=NETWORK_MAPPING, ) LOGGER.debug("IMPORT_SPEC: %s", dir(import_spec)) if hasattr(import_spec, "Warning"): LOGGER.warning(str(import_spec.Warning[0].LocalizedMessage)) if hasattr(import_spec, "Error"): LOGGER.error(str(import_spec.Error[0].LocalizedMessage)) exit() http_nfc_lease = import_vapp(resource_pool, import_spec, host=host) LOGGER.debug("HTTP_NFC_LEASE: %s", dir(http_nfc_lease)) lease = VIProperty(s, http_nfc_lease) LOGGER.debug( """LEASE: %s DICT: %s VI_prop: %s""", dir(lease), lease.__dict__, dir(VIProperty)) while lease.state == 'initializing': LOGGER.debug('lease.state: %s', lease.state) lease._flush_cache() if lease.state != 'ready': LOGGER.debug("something went wrong: %s", lease.state) lease_error = lease._values['error'] LOGGER.err( '''%s FaultCause: %s FaultMsg: %s