def __init__(self, module): super(VMwareCluster, self).__init__(module) self.cluster_name = module.params['cluster_name'] self.datacenter_name = module.params['datacenter'] self.enable_vsan = module.params['enable_vsan'] self.datacenter = None self.cluster = None self.advanced_options = None self.datacenter = find_datacenter_by_name(self.content, self.datacenter_name) if self.datacenter is None: self.module.fail_json(msg="Datacenter %s does not exist." % self.datacenter_name) self.cluster = self.find_cluster_by_name( cluster_name=self.cluster_name, datacenter_name=self.datacenter) if self.cluster is None: self.module.fail_json(msg="Cluster %s does not exist." % self.cluster_name) if module.params['advanced_options'] is not None: self.advanced_options = module.params['advanced_options'] client_stub = self.si._GetStub() ssl_context = client_stub.schemeArgs.get('context') apiVersion = vsanapiutils.GetLatestVmodlVersion( module.params['hostname']) vcMos = vsanapiutils.GetVsanVcMos(client_stub, context=ssl_context, version=apiVersion) self.vsanClusterConfigSystem = vcMos['vsan-cluster-config-system']
def main(): argument_spec = vmware_argument_spec() argument_spec.update(cluster_name=dict(required=True, type='str'), fetch_from_cache=dict(required=False, type='bool', default=False)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PYVMOMI: module.fail_json(msg=missing_required_lib('PyVmomi'), exception=PYVMOMI_IMP_ERR) if not HAS_VSANPYTHONSDK: module.fail_json( msg=missing_required_lib('vSAN Management SDK for Python'), exception=VSANPYTHONSDK_IMP_ERR) if not HAS_PYVMOMIJSON: module.fail_json( msg= 'The installed version of pyvmomi lacks JSON output support; need pyvmomi>6.7.1' ) try: si, content = connect_to_api(module, True, True) except Exception as e: module.fail_json(msg=e.msg) client_stub = si._GetStub() ssl_context = client_stub.schemeArgs.get('context') cluster = find_cluster_by_name(content, module.params['cluster_name']) if not cluster: module.fail_json(msg="Failed to find cluster %s" % module.params['cluster_name']) apiVersion = vsanapiutils.GetLatestVmodlVersion(module.params['hostname']) vcMos = vsanapiutils.GetVsanVcMos(client_stub, context=ssl_context, version=apiVersion) vsanClusterHealthSystem = vcMos['vsan-cluster-health-system'] try: clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary( cluster=cluster, fetchFromCache=module.params['fetch_from_cache']) except vmodl.fault.NotFound as not_found: module.fail_json(msg=not_found.msg) except vmodl.fault.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) health = json.dumps(clusterHealth, cls=VmomiSupport.VmomiJSONEncoder, sort_keys=True, strip_dynamic=True) module.exit_json(changed=False, vsan_health_info=health)
def getHealth(args, tagsbase): # Don't check for valid certificate context = ssl._create_unverified_context() si, _, cluster_obj = connectvCenter(args, context) # Disconnect to vcenter at the end atexit.register(Disconnect, si) apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vsanClusterHealthSystem = vcMos['vsan-cluster-health-system'] try: clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary( cluster=cluster_obj ) except vmodl.fault.NotFound as e: print("Caught NotFound exception : " + str(e)) return -1 except vmodl.fault.RuntimeFault as e: print("Caught RuntimeFault exception : " + str(e)) return -1 timestamp = int(time.time() * 1000000000) for group in clusterHealth.groups: splitGroupId = group.groupId.split('.') testName = splitGroupId[-1] parseHealth(testName, group.groupHealth, tagsbase, timestamp)
def connectvCenter(args): # Don't check for valid certificate context = ssl._create_unverified_context() # Connect to vCenter try: si = SmartConnect(host=args.vcenter, user=args.user, pwd=args.password, port=int(args.port), sslContext=context) if not si: raise Exception( "Could not connect to the specified host using specified username and password" ) except vmodl.MethodFault as e: raise Exception("Caught vmodl fault : " + e.msg) except Exception as e: raise Exception("Caught exception : " + str(e)) # Get content informations content = si.RetrieveContent() # Get Info about cluster cluster_obj = getClusterInstance(args.clusterName, content) # Exit if the cluster provided in the arguments is not available if not cluster_obj: raise Exception( 'Inventory exception: Did not find the required cluster') # Disconnect to vcenter at the end atexit.register(Disconnect, si) apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vsanClusterConfigSystem = vcMos['vsan-cluster-config-system'] try: clusterConfig = vsanClusterConfigSystem.VsanClusterGetConfig( cluster=cluster_obj) except vmodl.fault.InvalidState as e: raise Exception("InvalidState exception: " + e.msg()) except vmodl.fault.RuntimeFault as e: raise Exception("RuntimeFault exception: " + e.msg()) if not clusterConfig.enabled: raise Exception( "Configuration exeption: vSAN is not enabled on cluster " + args.clusterName) return si, content, cluster_obj, vcMos
def main(): args = GetArgs() # login host with default ssl context context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE si = SmartConnect(host=args.host, user=args.username, pwd=args.password, port=int(args.port), sslContext=context) atexit.register(Disconnect, si) aboutInfo = si.content.about apiVersion = vsanapiutils.GetLatestVmodlVersion(args.host) if aboutInfo.apiType != VC_TYPE: sys.stdout.write("The host %s is not VMware VirtualCenter:\n" % args.host) return -1 sys.stdout.write("Successfully connected to vCenter!\n") # Get vSAN clusterConfigSystem from the vCenter Managed Object references. vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vccs = vcMos['vsan-cluster-config-system'] cluster = getClusterInstance(args.cluster, si) if cluster is None: sys.stdout.write("Cluster %s is not found for %s\n" % (args.cluster, args.host)) return -1 vcs = vcMos['vsan-vc-capability-system'] if not CheckVsanCapability(vcs, cluster, METRIC_CONFIG_FEATURE): sys.stdout.write("Cluster %s does not support token setup\n" % (args.cluster)) return -1 try: token = SetUpMetricToken(si, vccs, cluster) # the last line of output is the token value sys.stdout.write("Successfully generate a new token:\n") sys.stdout.write("%s\n" % token) return 0 except Exception as e: sys.stderr.write("Cannot setup cluster prometheus token: %s" % str(e)) return -1
def getCapacity(args, tagsbase): # Don't check for valid certificate context = ssl._create_unverified_context() si, _, cluster_obj = connectvCenter(args, context) # Disconnect to vcenter at the end atexit.register(Disconnect, si) apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vsanSpaceReportSystem = vcMos['vsan-cluster-space-report-system'] try: spaceReport = vsanSpaceReportSystem.VsanQuerySpaceUsage( cluster=cluster_obj ) except vmodl.fault.InvalidArgument as e: print("Caught InvalidArgument exception : " + str(e)) return -1 except vmodl.fault.NotSupported as e: print("Caught NotSupported exception : " + str(e)) return -1 except vmodl.fault.RuntimeFault as e: print("Caught RuntimeFault exception : " + str(e)) return -1 timestamp = int(time.time() * 1000000000) parseCapacity('global', spaceReport, tagsbase, timestamp) parseCapacity('summary', spaceReport, tagsbase, timestamp) if spaceReport.efficientCapacity: parseCapacity('efficientcapacity', spaceReport, tagsbase, timestamp) for object in spaceReport.spaceDetail.spaceUsageByObjectType: parseCapacity(object.objType, object, tagsbase, timestamp)
def __init__(self, module): super(VMwareCluster, self).__init__(module) self.cluster_name = module.params['cluster_name'] self.datacenter_name = module.params['datacenter'] self.enable_vsan = module.params['enable'] self.datacenter = None self.cluster = None self.advanced_options = None self.datacenter = find_datacenter_by_name(self.content, self.datacenter_name) if self.datacenter is None: self.module.fail_json(msg="Datacenter %s does not exist." % self.datacenter_name) self.cluster = self.find_cluster_by_name( cluster_name=self.cluster_name, datacenter_name=self.datacenter) if self.cluster is None: self.module.fail_json(msg="Cluster %s does not exist." % self.cluster_name) if module.params['advanced_options'] is not None: self.advanced_options = module.params['advanced_options'] client_stub = self.si._GetStub() ssl_context = client_stub.schemeArgs.get('context') apiVersion = vsanapiutils.GetLatestVmodlVersion( module.params['hostname']) vcMos = vsanapiutils.GetVsanVcMos(client_stub, context=ssl_context, version=apiVersion) self.vsanClusterConfigSystem = vcMos['vsan-cluster-config-system'] self.module.warn( "The default for enable will change from false to true in a future version to make the behavior more consistent with other modules." "Please make sure your playbooks don't rely on the default being false so you don't run into problems." )
def gather_info(self): datacenter_name = self.module.params.get('datacenter') if datacenter_name: self.datacenter = self.find_datacenter_by_name(datacenter_name) if self.datacenter is None: self.module.fail_json(msg="Datacenter %s does not exist." % datacenter_name) cluster_name = self.module.params.get('cluster_name') self.cluster = self.find_cluster_by_name(cluster_name=cluster_name, datacenter_name=self.datacenter) if self.cluster is None: self.module.fail_json(msg="Cluster %s does not exist." % cluster_name) fetch_from_cache = self.module.params.get('fetch_from_cache') client_stub = self.si._GetStub() ssl_context = client_stub.schemeArgs.get('context') api_version = vsanapiutils.GetLatestVmodlVersion(self.module.params['hostname']) vc_mos = vsanapiutils.GetVsanVcMos(client_stub, context=ssl_context, version=api_version) vsan_cluster_health_system = vc_mos['vsan-cluster-health-system'] cluster_health = {} try: cluster_health = vsan_cluster_health_system.VsanQueryVcClusterHealthSummary( cluster=self.cluster, fetchFromCache=fetch_from_cache, ) except vmodl.fault.NotFound as not_found: self.module.fail_json(msg=not_found.msg) except vmodl.fault.RuntimeFault as runtime_fault: self.module.fail_json(msg=runtime_fault.msg) health = json.dumps(cluster_health, cls=VmomiSupport.VmomiJSONEncoder, sort_keys=True, strip_dynamic=True) self.module.exit_json(changed=False, vsan_health_info=health)
def main(): # Don't check for valid certificate context = ssl._create_unverified_context() # Parse CLI arguments args = get_args() # Connect to vCenter try: si = SmartConnect(host=args.vcenter, user=args.user, pwd=args.password, port=int(args.port), sslContext=context) if not si: print( "Could not connect to the specified host using specified " "username and password") return -1 except vmodl.MethodFault as e: print("Caught vmodl fault : " + e.msg) return -1 except Exception as e: print("Caught exception : " + str(e)) return -1 # Disconnect to vcenter at the end atexit.register(Disconnect, si) # Get content informations content = si.RetrieveContent() # Get Info about cluster cluster_obj = getClusterInstance(args.clusterName, content) # Exit if the cluster provided in the arguments is not available if not cluster_obj: print 'The required cluster not found in inventory, validate input. Aborting test' exit() apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vsanPerfSystem = vcMos['vsan-performance-manager'] # Gather a list of the available entity types (ex: vsan-host-net) entityTypes = vsanPerfSystem.VsanPerfGetSupportedEntityTypes() if (args.format).lower() == 'raw': print entityTypes if (args.format).lower() == 'markdown': print "## Entity types" print "" print("|Name|Description|") print("|---|---|") for entities in entityTypes: print "|%s|%s|" % (entities.name, entities.description) print "" print "## Details" for entities in entityTypes: print "" print "### %s" % (entities.name) print "" print entities.description print "" print("|Label|Name|Unit|Description|") print("|---|---|---|---|") for entity in entities.graphs: unit = entity.unit for metric in entity.metrics: print "|%s|%s|%s|%s|" % (metric.label, metric.name, unit, metric.description) print "" if (args.format).lower() == 'html': print("<table>") print("<thead><tr><th>Name</th><th>Description</th></tr></thead>") print("<tbody>") for entities in entityTypes: print "<tr><th>%s</th><th>%s</th></tr>" % (entities.name, entities.description) print("</tbody>") print("</table>") print "" for entities in entityTypes: print "<h3> %s </h3>" % (entities.name) print "" print entities.description print "" print("<table>") print( "<thead><tr><th>Label</th><th>Name</th><th>Unit</th><th>Description</th></tr></thead>" ) print("<tbody>") for entity in entities.graphs: unit = entity.unit for metric in entity.metrics: print "<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>" % ( metric.label, metric.name, unit, metric.description) print("</tbody>") print("</table>") print "" return 0
def main(): # Don't check for valid certificate context = ssl._create_unverified_context() # Parse CLI arguments args = get_args() # Connect to vCenter try: si = SmartConnect(host=args.vcenter, user=args.user, pwd=args.password, port=int(args.port), sslContext=context) if not si: print( "Could not connect to the specified host using specified " "username and password") return -1 except vmodl.MethodFault as e: print("Caught vmodl fault : " + e.msg) return -1 except Exception as e: print("Caught exception : " + str(e)) return -1 # Disconnect to vcenter at the end atexit.register(Disconnect, si) # Get content informations content = si.RetrieveContent() # Get Info about cluster cluster_obj = getClusterInstance(args.clusterName, content) # Exit if the cluster provided in the arguments is not available if not cluster_obj: print 'The required cluster not found in inventory, validate input.' exit() # Initiate tags with vcenter and cluster name tagsbase = {} tagsbase['vcenter'] = args.vcenter tagsbase['cluster'] = args.clusterName apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) ## CAPACITY if args.capacity: vsanSpaceReportSystem = vcMos['vsan-cluster-space-report-system'] try: spaceReport = vsanSpaceReportSystem.VsanQuerySpaceUsage( cluster=cluster_obj) except vmodl.fault.InvalidArgument as e: print("Caught InvalidArgument exception : " + str(e)) return -1 except vmodl.fault.NotSupported as e: print("Caught NotSupported exception : " + str(e)) return -1 except vmodl.fault.RuntimeFault as e: print("Caught RuntimeFault exception : " + str(e)) return -1 timestamp = int(time.time() * 1000000000) parseCapacity('global', spaceReport, tagsbase, timestamp) parseCapacity('summary', spaceReport, tagsbase, timestamp) if spaceReport.efficientCapacity: parseCapacity('efficientcapacity', spaceReport, tagsbase, timestamp) for object in spaceReport.spaceDetail.spaceUsageByObjectType: parseCapacity(object.objType, object, tagsbase, timestamp) ## PERFORMANCE if args.performance: # Get VM uuid/names vms = getVMs(content) # Get disks uuid/names et hosts uuid/names diskinfos, hostinfos = getHostsInfos(cluster_obj) #### Witness vsanVcStretchedClusterSystem = vcMos['vsan-stretched-cluster-system'] # Retrieve Witness Host for given VSAN Cluster witnessHosts = vsanVcStretchedClusterSystem.VSANVcGetWitnessHosts( cluster=cluster_obj) for witnessHost in witnessHosts: host = (vim.HostSystem(witnessHost.host._moId, si._stub)) hostinfos[witnessHost.nodeUuid] = host.name diskWitness = host.configManager.vsanSystem.QueryDisksForVsan() for disk in diskWitness: if disk.state == 'inUse': diskinfos[disk.vsanUuid] = disk.disk.canonicalName vsanPerfSystem = vcMos['vsan-performance-manager'] # Gather a list of the available entity types (ex: vsan-host-net) entityTypes = vsanPerfSystem.VsanPerfGetSupportedEntityTypes() # query interval, last 10 minutes endTime = datetime.utcnow() startTime = endTime + timedelta(minutes=-10) splitSkipentitytypes = [] if args.skipentitytypes: splitSkipentitytypes = args.skipentitytypes.split(',') for entities in entityTypes: if entities.name not in splitSkipentitytypes: entitieName = entities.name labels = [] # Gather all labels related to the entity (ex: iopsread, iopswrite...) for entity in entities.graphs: for metric in entity.metrics: labels.append(metric.label) # Build entity entity = '%s:*' % (entities.name) # Build spec object spec = vim.cluster.VsanPerfQuerySpec(endTime=endTime, entityRefId=entity, labels=labels, startTime=startTime) # Get statistics try: metrics = vsanPerfSystem.VsanPerfQueryPerf( querySpecs=[spec], cluster=cluster_obj) except vmodl.fault.InvalidArgument as e: print("Caught InvalidArgument exception : " + str(e)) return -1 except vmodl.fault.NotFound as e: print("Caught NotFound exception : " + str(e)) return -1 except vmodl.fault.NotSupported as e: print("Caught NotSupported exception : " + str(e)) return -1 except vmodl.fault.RuntimeFault as e: print("Caught RuntimeFault exception : " + str(e)) return -1 except vmodl.fault.Timedout as e: print("Caught Timedout exception : " + str(e)) return -1 except vmodl.fault.VsanNodeNotMaster as e: print("Caught VsanNodeNotMaster exception : " + str(e)) return -1 for metric in metrics: if not metric.sampleInfo == "": measurement = entitieName sampleInfos = metric.sampleInfo.split(",") lenValues = len(sampleInfos) timestamp = convertStrToTimestamp( sampleInfos[lenValues - 1]) tags = parseEntityRefId(measurement, metric.entityRefId, hostinfos, vms, diskinfos) tags.update(tagsbase) fields = {} for value in metric.value: listValue = value.values.split(",") fields[value.metricId.label] = float( listValue[lenValues - 1]) printInfluxLineProtocol(measurement, tags, fields, timestamp) return 0
def main(): args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) # For python 2.7.9 and later, the default SSL context has more strict # connection handshaking rule. We may need turn of the hostname checking # and client side cert verification. context = None if sys.version_info[:3] > (2, 7, 8): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) atexit.register(Disconnect, si) # For detecting whether the host is vCenter or ESXi. aboutInfo = si.content.about apiVersion = vsanapiutils.GetLatestVmodlVersion(args.host) if aboutInfo.apiType == 'VirtualCenter': vcVersion = StrictVersion(aboutInfo.apiVersion) if vcVersion < StrictVersion('6.5'): print( 'The Virtual Center with version %s (lower than 6.5) is not ', 'supported.' % aboutInfo.apiVersion) return -1 else: print('The vSAN iSCSI service API are only accessible through ', 'vCenter') return -1 cluster = getClusterInstance(args.clusterName, si) if cluster is None: print("Cluster %s is not found for %s" % (args.clusterName, args.host)) return -1 vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vits = vcMos['vsan-cluster-iscsi-target-system'] vccs = vcMos['vsan-cluster-config-system'] # Fetch the storage policy ID for enable vSAN iSCSI service and # create the iSCSI home object. pbmSi = connectToSpbm(si._stub, context) vsanStoragePolicy = getVsanStoragePolicy(pbmSi) if vsanStoragePolicy is None: print('Cannot find the vSAN Storage Policy from the Virtual ' + 'Center server.') return -1 # Enable iSCSI service through vSAN Cluster Reconfiguration API on VC, and # the config port defaults to 3260 and can be customized. defaultVsanConfigSpec = vim.cluster.VsanIscsiTargetServiceDefaultConfigSpec( networkInterface="vmk0", port=2300) vitEnableSpec = vim.cluster.VsanIscsiTargetServiceSpec( homeObjectStoragePolicy=vsanStoragePolicy, defaultConfig=defaultVsanConfigSpec, enabled=True) clusterReconfigSpec = vim.vsan.ReconfigSpec(iscsiSpec=vitEnableSpec) vitEnableVsanTask = vccs.ReconfigureEx(cluster, clusterReconfigSpec) vitEnableVcTask = vsanapiutils.ConvertVsanTaskToVcTask( vitEnableVsanTask, si._stub) vsanapiutils.WaitForTasks([vitEnableVcTask], si) print('Enable vSAN iSCSI service task finished with status: %s' % vitEnableVcTask.info.state) # Create vSAN iSCSI targets and an associated LUN with the size of 1GB. targetAlias = "sampleTarget" targetSpec = vim.cluster.VsanIscsiTargetSpec( alias=targetAlias, iqn='iqn.2015-08.com.vmware:vit.target1') vsanTask = vits.AddIscsiTarget(cluster, targetSpec) vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub) vsanapiutils.WaitForTasks([vcTask], si) print('Create vSAN iSCSI target task finished with status: %s' % vcTask.info.state) lunSize = 1 * 1024 * 1024 * 1024 # 1GB lunSpec = vim.cluster.VsanIscsiLUNSpec(lunId=0, lunSize=lunSize, storagePolicy=vsanStoragePolicy) vsanTask = vits.AddIscsiLUN(cluster, targetAlias, lunSpec) vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub) vsanapiutils.WaitForTasks([vcTask], si) print('Create vSAN iSCSI LUN task finished with status: %s' % vcTask.info.state) # Remove vSAN iSCSI targets and LUN associated with the targets. vsanTask = vits.RemoveIscsiLUN(cluster, targetAlias, 0) vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub) vsanapiutils.WaitForTasks([vcTask], si) print("Remove vSAN iSCSI LUN task finished with status:%s" % vcTask.info.state) vsanTask = vits.RemoveIscsiTarget(cluster, targetAlias) vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub) vsanapiutils.WaitForTasks([vcTask], si) print("Remove vSAN iSCSI target task finished with status:%s" % vcTask.info.state) # Disable iSCSI service through vSAN iSCSI API on vCenter. vitDisableSpec = vim.cluster.VsanIscsiTargetServiceSpec(enabled=False) clusterReconfigSpec = vim.vsan.ReconfigSpec(iscsiSpec=vitDisableSpec) vitDisableVsanTask = vccs.ReconfigureEx(cluster, clusterReconfigSpec) vitDisableVcTask = vsanapiutils.ConvertVsanTaskToVcTask( vitDisableVsanTask, si._stub) vsanapiutils.WaitForTasks([vitDisableVcTask], si) print('Disable vSAN iSCSI service task finished with status: %s' % vitDisableVcTask.info.state)
def main(): args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host,args.user)) # For python 2.7.9 and later, the default SSL context has more strict # connection handshaking rule. We may need turn off the hostname checking # and client side cert verification. context = None if sys.version_info[:3] > (2,7,8): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) atexit.register(Disconnect, si) # Detecting whether the host is vCenter or ESXi. aboutInfo = si.content.about apiVersion = vsanapiutils.GetLatestVmodlVersion(args.host) if aboutInfo.apiType == 'VirtualCenter': majorApiVersion = aboutInfo.apiVersion.split('.')[0] if int(majorApiVersion) < 6: print('The Virtual Center with version %s (lower than 6.0) is not supported.' % aboutInfo.apiVersion) return -1 # Get vSAN health system from the vCenter Managed Object references. vcMos = vsanapiutils.GetVsanVcMos( si._stub, context=context, version=apiVersion) vhs = vcMos['vsan-cluster-health-system'] cluster = getClusterInstance(args.clusterName, si) if cluster is None: print("Cluster %s is not found for %s" % (args.clusterName, args.host)) return -1 # vSAN cluster health summary can be cached at vCenter. fetchFromCache = True fetchFromCacheAnswer = input( 'Do you want to fetch the cluster health from cache if exists?(y/n):') if fetchFromCacheAnswer.lower() == 'n': fetchFromCache = False print('Fetching cluster health from cached state: %s' % ('Yes' if fetchFromCache else 'No')) healthSummary = vhs.QueryClusterHealthSummary( cluster=cluster, includeObjUuids=True, fetchFromCache=fetchFromCache) clusterStatus = healthSummary.clusterStatus print("Cluster %s Status: %s" % (args.clusterName, clusterStatus.status)) for hostStatus in clusterStatus.trackedHostsStatus: print("Host %s Status: %s" % (hostStatus.hostname, hostStatus.status)) # Here is an example of how to track a task returned by the vSAN API. vsanTask = vhs.RepairClusterObjectsImmediate(cluster); # Convert to vCenter task and bind the MO with vCenter session. vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub) vsanapiutils.WaitForTasks([vcTask], si) print('Repairing cluster objects task completed with state: %s' % vcTask.info.state) if aboutInfo.apiType == 'HostAgent': majorApiVersion = aboutInfo.apiVersion.split('.')[0] if int(majorApiVersion) < 6: print('The ESXi with version %s (lower than 6.0) is not supported.' % aboutInfo.apiVersion) return -1 # Get vSAN health system from the ESXi Managed Object references. esxMos = vsanapiutils.GetVsanEsxMos( si._stub, context=context, version=apiVersion) vpm = esxMos['vsan-performance-manager'] nodeInfo = vpm.VsanPerfQueryNodeInformation()[0] print('Hostname: %s' % args.host) print(' version: %s' % nodeInfo.version) print(' isCmmdsMaster: %s' % nodeInfo.isCmmdsMaster) print(' isStatsMaster: %s' % nodeInfo.isStatsMaster) print(' vsanMasterUuid: %s' % nodeInfo.vsanMasterUuid) print(' vsanNodeUuid: %s' % nodeInfo.vsanNodeUuid)
def main(): args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) # For python 2.7.9 and later, the default SSL context has more strict # connection handshaking rule. We may need turn off the hostname checking # and client side cert verification. context = None if sys.version_info[:3] > (2, 7, 8): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) atexit.register(Disconnect, si) # Detecting whether the host is vCenter or ESXi. aboutInfo = si.content.about apiVersion = vsanapiutils.GetLatestVmodlVersion(args.host) if aboutInfo.apiType == 'VirtualCenter': majorApiVersion = aboutInfo.apiVersion.split('.')[0] if int(majorApiVersion) < 6: print( 'The Virtual Center with version %s (lower than 6.0) is not supported.' % aboutInfo.apiVersion) return -1 # Get vSAN health system from the vCenter Managed Object references. vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vhs = vcMos['vsan-cluster-health-system'] cluster = getClusterInstance(args.clusterName, si) if cluster is None: print("Cluster %s is not found for %s" % (args.clusterName, args.host)) return -1 # vSAN cluster health summary can be cached at vCenter. fetchFromCache = False healthSummary = vhs.QueryClusterHealthSummary( cluster=cluster, includeObjUuids=True, fetchFromCache=fetchFromCache) clusterStatus = healthSummary.clusterStatus groups = healthSummary.groups foundFailure = False import pprint for group in groups: if group.groupName == 'com.vmware.vsan.health.test.cluster': for test in group.groupTests: if test.testHealth != 'green': foundFailure = True break if not foundFailure: for hostStatus in clusterStatus.trackedHostsStatus: if hostStatus.status != 'green': foundFailure = True break pprint.pprint(foundFailure) return foundFailure
def getPerformance(args, tagsbase): result = "" # Don't check for valid certificate context = ssl._create_unverified_context() si, content, cluster_obj = connectvCenter(args, context) # Disconnect to vcenter at the end atexit.register(Disconnect, si) apiVersion = vsanapiutils.GetLatestVmodlVersion(args.vcenter) vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context, version=apiVersion) vsanVcStretchedClusterSystem = vcMos['vsan-stretched-cluster-system'] vsanPerfSystem = vcMos['vsan-performance-manager'] # Get VM uuid/names vms = getVMs(cluster_obj) # Get uuid/names relationship informations for hosts and disks uuid, disks = getInformations(content, cluster_obj) # Witness # Retrieve Witness Host for given VSAN Cluster witnessHosts = vsanVcStretchedClusterSystem.VSANVcGetWitnessHosts( cluster=cluster_obj ) for witnessHost in witnessHosts: host = (vim.HostSystem(witnessHost.host._moId, si._stub)) uuid[witnessHost.nodeUuid] = host.name diskWitness = host.configManager.vsanSystem.QueryDisksForVsan() for disk in diskWitness: if disk.state == 'inUse': uuid[disk.vsanUuid] = disk.disk.canonicalName disks[disk.vsanUuid] = host.name # Gather a list of the available entity types (ex: vsan-host-net) entityTypes = vsanPerfSystem.VsanPerfGetSupportedEntityTypes() # query interval, last 10 minutes -- UTC !!! endTime = datetime.utcnow() startTime = endTime + timedelta(minutes=-10) splitSkipentitytypes = [] if args.skipentitytypes: splitSkipentitytypes = args.skipentitytypes.split(',') for entities in entityTypes: if entities.name not in splitSkipentitytypes: entitieName = entities.name labels = [] # Gather all labels related to the entity (ex: iopsread, iopswrite...) for entity in entities.graphs: for metric in entity.metrics: labels.append(metric.label) # Build entity entity = '%s:*' % (entities.name) # Build spec object spec = vim.cluster.VsanPerfQuerySpec( endTime=endTime, entityRefId=entity, labels=labels, startTime=startTime ) # Get statistics try: metrics = vsanPerfSystem.VsanPerfQueryPerf( querySpecs=[spec], cluster=cluster_obj ) except vmodl.fault.InvalidArgument as e: print("Caught InvalidArgument exception : " + str(e)) return -1 except vmodl.fault.NotFound as e: print("Caught NotFound exception : " + str(e)) return -1 except vmodl.fault.NotSupported as e: print("Caught NotSupported exception : " + str(e)) return -1 except vmodl.fault.RuntimeFault as e: print("Caught RuntimeFault exception : " + str(e)) return -1 except vmodl.fault.Timedout as e: print("Caught Timedout exception : " + str(e)) return -1 except vmodl.fault.VsanNodeNotMaster as e: print("Caught VsanNodeNotMaster exception : " + str(e)) return -1 for metric in metrics: if not metric.sampleInfo == "": measurement = entitieName sampleInfos = metric.sampleInfo.split(",") lenValues = len(sampleInfos) timestamp = convertStrToTimestamp(sampleInfos[lenValues - 1]) tags = parseEntityRefId(measurement, metric.entityRefId, uuid, vms, disks) tags.update(tagsbase) fields = {} for value in metric.value: listValue = value.values.split(",") fields[value.metricId.label] = float(listValue[lenValues - 1]) result = result + formatInfluxLineProtocol(measurement, tags, fields, timestamp) print(result)