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 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")
#print "IMPORT_SPEC: " + str(dir(import_spec)) if hasattr(import_spec, "Warning"): print "Warning:", import_spec.Warning[0].LocalizedMessage if hasattr(import_spec, "Error"): print "Error:", import_spec.Error[0].LocalizedMessage exit() http_nfc_lease = import_vapp(resource_pool, import_spec, host=host) print "HTTP_NFC_LEASE: " + str(dir(http_nfc_lease)) lease = VIProperty(s, http_nfc_lease) print "LEASE: " + str(dir(lease)) print "DICT: " + str(lease.__dict__) print "VI_prop: " + str(dir(VIProperty)) while lease.state == 'initializing': print lease.state lease._flush_cache() if lease.state != 'ready': print "something went wrong (" + str(lease.state) + ")" lease_error = lease._values['error'] print "Error: ", lease_error.LocalizedMessage print "FaultCause: ", lease_error.Fault.FaultCause print "FaultMsg: ", lease_error.Fault.FaultMessage print "Fault: ", str(dir(lease_error.Fault)) exit() t = threading.Thread(target=keep_lease_alive, args=(http_nfc_lease, )) t.start() for dev_url in lease.info.deviceUrl: filename = dev_url.targetId hostname = urlparse(s._proxy.binding.url).hostname upload_url = dev_url.ulr.replace("*", hostname)
class VITaskHistoryCollector(VIHistoryCollector): """ TaskHistoryCollector provides a mechanism for retrieving historical data and updates when the server appends new tasks. """ RECURSION = Recursion STATES = States 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' """ super(VITaskHistoryCollector, 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: 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_latest_tasks(self): """ Returns a list of task items in the 'viewable latest page'. As new tasks that match the collector's filter are created, they are added to this page, and the oldest tasks are removed from the collector to keep the size of the page. The "oldest task" is the one with the oldest creation time. The tasks in the returned page are unordered. """ self._props._flush_cache() if not hasattr(self._props, "latestPage"): return [] ret = [] for task in self._props.latestPage: ret.append(VITask(task.task._obj, self._server)) return ret def read_next_tasks(self, max_count): """ Reads the 'scrollable view' from the current position. The scrollable position is moved to the next newer page after the read. No item is returned when the end of the collector is reached. """ return self.__read_tasks(max_count, True) def read_previous_tasks(self, max_count): """ Reads the 'scrollable view' from the current position. The scrollable position is then moved to the next older page after the read. No item is returned when the head of the collector is reached. """ return self.__read_tasks(max_count, False) def __read_tasks(self, max_count, next_page): if not isinstance(max_count, int): raise VIException("max_count should be an integer", FaultTypes.PARAMETER_ERROR) if next_page: request = VI.ReadNextTasksRequestMsg() else: request = VI.ReadPreviousTasksRequestMsg() _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.ReadNextTasks(request)._returnval else: resp = self._server._proxy.ReadPreviousTasks( request)._returnval ret = [] for task in resp: ret.append(VITask(task.Task, self._server)) except (VI.ZSI.FaultException) as e: raise VIApiException(e) return ret
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 Fault: %s''', lease_error.LocalizedMessage, lease_error.Fault.FaultCause, lease_error.Fault.FaultMessage, dir(lease_error.Fault)) exit() t = threading.Thread(target=keep_lease_alive, args=(http_nfc_lease,))
class VIEventHistoryCollector(VIHistoryCollector): """ EventHistoryCollector provides a mechanism for retrieving historical data and updates when the server appends new events. """ RECURSION = Recursion 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 get_latest_events(self): """ Returns a list of event items in the 'viewable latest page'. As new events that match the collector's filter are created, they are added to this page, and the oldest events are removed from the collector to keep the size of the page. The "oldest event" is the one with the oldest creation time. The events in the returned page are unordered. """ self._props._flush_cache() if not hasattr(self._props, "latestPage"): return [] ret = [] for event in self._props.latestPage: ret.append(event) return ret def read_next_events(self, max_count): """ Reads the 'scrollable view' from the current position. The scrollable position is moved to the next newer page after the read. No item is returned when the end of the collector is reached. """ return self.__read_events(max_count, True) def read_previous_events(self, max_count): """ Reads the 'scrollable view' from the current position. The scrollable position is then moved to the next older page after the read. No item is returned when the head of the collector is reached. """ return self.__read_events(max_count, False) def reset(self): """ Moves the 'scrollable view' to the item immediately preceding the 'viewable latest page'. If you use 'read_previous_events' all items are retrieved from the newest item to the oldest item. """ request = VI.ResetCollectorRequestMsg() _this = request.new__this(self._mor) _this.set_attribute_type(self._mor.get_attribute_type()) request.set_element__this(_this) self._server._proxy.ResetCollector(request) def rewind(self): """ Moves the 'scrollable view' to the oldest item. If you use 'read_next_events', all items are retrieved from the oldest item to the newest item. This is the default setting when the collector is created. """ request = VI.RewindCollectorRequestMsg() _this = request.new__this(self._mor) _this.set_attribute_type(self._mor.get_attribute_type()) request.set_element__this(_this) self._server._proxy.RewindCollector(request) def __read_events(self, max_count, next_page): 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) as e: raise VIApiException(e) return ret