预备知识点:

1、vim.PerformanceManager.MetricId()    通过counter_id获取到metric_id

2、vim.PerformanceManager.QuerySpec()    通过对象、metric_id、起始时间进行装配

3、content.perfManager.QueryPerf()    通过QuerySpec获取对象的Statistics

4、content.perfManager.perfCounter   获取所有Performance Counter相关信息

示例1: 获取ESXI主机的网络利用率

  1. from pyVim.connect import SmartConnectNoSSL, Disconnect
  2. from pyVmomi import vim
  3. from datetime import timedelta
  4. import atexit
  5.  
  6. def connect_vc(host, user, pwd, port):
  7. si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
  8.  
  9. # disconnect this thing
  10. atexit.register(Disconnect, si)
  11. return si
  12.  
  13. def build_query(content, vc_time, counter_id, obj, interval):
  14. metric_id = vim.PerformanceManager.MetricId(counterId=counter_id, instance="")
  15. start_time = vc_time - timedelta(minutes=(interval + 1))
  16. end_time = vc_time - timedelta(minutes=1)
  17. query = vim.PerformanceManager.QuerySpec(intervalId=20,
  18. entity=obj,
  19. metricId=[metric_id],
  20. startTime=start_time,
  21. endTime=end_time)
  22. perf_results = content.perfManager.QueryPerf(querySpec=[query])
  23. if perf_results:
  24. return perf_results
  25. else:
  26. pass
  27.  
  28. def print_statistics(obj, content, vc_time, interval, perf_dict, ):
  29. stat_interval = interval * 3 # There are 3per 20s samples in each minute
  30.  
  31. # Network usage (Tx/Rx)
  32. # statNetworkTx = BuildQuery(content, vchtime, (stat_check(perf_dict, 'net.usage.maximum')), obj, interval)
  33. # networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 / 1024) / statInt)
  34. # statNetworkRx = BuildQuery(content, vchtime, (stat_check(perf_dict, 'net.usage.minimum')), obj, interval)
  35. # networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 / 1024) / statInt)
  36.  
  37. # Network utilization (combined transmit-rates and receive-rates) during the interval = 145
  38. network_usage = build_query(content, vc_time, stat_check(perf_dict, 'net.usage.average'), obj, interval)
  39. try:
  40. print('statNetworkThroughput:%sMB' % (round((((sum(network_usage[0].value[0].value)) / 1024) / stat_interval), 2)))
  41.  
  42. except TypeError:
  43. # 关机的ESXi主机无法获取到数据
  44. pass
  45.  
  46. def stat_check(perf_dict, counter_name):
  47. """通过performance counter名称获取counter id"""
  48. counter_id = perf_dict[counter_name]
  49. return counter_id
  50.  
  51. def main():
  52. username = 'administrator@vsphere.local'
  53. password = 'xxxxxx'
  54. vc_ip = '172.16.65.99'
  55. vc_port = ''
  56. statistics_interval_time = 10 # 分钟为单位
  57. si = connect_vc(host=vc_ip, user=username, pwd=password, port=vc_port)
  58. content = si.RetrieveContent()
  59.  
  60. # Get vCenter date and time for use as baseline when querying for counters
  61. vc_time = si.CurrentTime()
  62.  
  63. # 获取所有performance counter,并放入字典中
  64. perf_dict = {}
  65. perf_list = content.perfManager.perfCounter
  66. for counter in perf_list:
  67. counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
  68. perf_dict[counter_full] = counter.key  # perf_dict包含了所有的perfCounter
  69.  
  70. # 获取ESXi主机对象
  71. container_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True)
  72.  
  73. for obj in container_view.view:
  74. print_statistics(obj, content, vc_time, statistics_interval_time, perf_dict)
  75.  
  76. # Start program
  77. if __name__ == "__main__":
  78. main()

示例2: 获取VM相关的performance

  1. """
  2. Python program that generates various statistics for one or more virtual machines
  3. A list of virtual machines can be provided as a comma separated list.
  4. """
  5.  
  6. from __future__ import print_function
  7. from pyVim.connect import SmartConnectNoSSL, Disconnect
  8. from pyVmomi import vmodl, vim
  9. from datetime import timedelta, datetime
  10. import atexit
  11.  
  12. def connect_vc(host, user, pwd, port):
  13. si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
  14.  
  15. # disconnect this thing
  16. atexit.register(Disconnect, si)
  17. return si
  18.  
  19. def BuildQuery(content, vchtime, counterId, instance, vm, interval):
  20. perfManager = content.perfManager
  21. metricId = vim.PerformanceManager.MetricId(counterId=counterId, instance=instance)
  22. startTime = vchtime - timedelta(minutes=(interval + 1))
  23. endTime = vchtime - timedelta(minutes=1)
  24. query = vim.PerformanceManager.QuerySpec(intervalId=20, entity=vm, metricId=[metricId], startTime=startTime,
  25. endTime=endTime)
  26. perfResults = perfManager.QueryPerf(querySpec=[query])
  27. if perfResults:
  28. return perfResults
  29. else:
  30. print('ERROR: Performance results empty. TIP: Check time drift on source and vCenter server')
  31. print('Troubleshooting info:')
  32. print('vCenter/host date and time: {}'.format(vchtime))
  33. print('Start perf counter time : {}'.format(startTime))
  34. print('End perf counter time : {}'.format(endTime))
  35. print(query)
  36. exit()
  37.  
  38. def PrintVmInfo(vm, content, vchtime, interval, perf_dict, ):
  39. statInt = interval * 3 # There are 3 20s samples in each minute
  40. summary = vm.summary
  41. disk_list = []
  42. network_list = []
  43.  
  44. # Convert limit and reservation values from -1 to None
  45. if vm.resourceConfig.cpuAllocation.limit == -1:
  46. vmcpulimit = "None"
  47. else:
  48. vmcpulimit = "{} Mhz".format(vm.resourceConfig.cpuAllocation.limit)
  49. if vm.resourceConfig.memoryAllocation.limit == -1:
  50. vmmemlimit = "None"
  51. else:
  52. vmmemlimit = "{} MB".format(vm.resourceConfig.cpuAllocation.limit)
  53.  
  54. if vm.resourceConfig.cpuAllocation.reservation == 0:
  55. vmcpures = "None"
  56. else:
  57. vmcpures = "{} Mhz".format(vm.resourceConfig.cpuAllocation.reservation)
  58. if vm.resourceConfig.memoryAllocation.reservation == 0:
  59. vmmemres = "None"
  60. else:
  61. vmmemres = "{} MB".format(vm.resourceConfig.memoryAllocation.reservation)
  62.  
  63. vm_hardware = vm.config.hardware
  64. for each_vm_hardware in vm_hardware.device:
  65. if (each_vm_hardware.key >= 2000) and (each_vm_hardware.key < 3000):
  66. disk_list.append('{} | {:.1f}GB | Thin: {} | {}'.format(each_vm_hardware.deviceInfo.label,
  67. each_vm_hardware.capacityInKB/1024/1024,
  68. each_vm_hardware.backing.thinProvisioned,
  69. each_vm_hardware.backing.fileName))
  70. elif (each_vm_hardware.key >= 4000) and (each_vm_hardware.key < 5000):
  71. network_list.append('{} | {} | {}'.format(each_vm_hardware.deviceInfo.label,
  72. each_vm_hardware.deviceInfo.summary,
  73. each_vm_hardware.macAddress))
  74.  
  75. #CPU Ready Average
  76. statCpuReady = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'cpu.ready.summation')), "", vm, interval)
  77. cpuReady = (float(sum(statCpuReady[0].value[0].value)) / statInt)
  78. #CPU Usage Average % - NOTE: values are type LONG so needs divided by 100 for percentage
  79. statCpuUsage = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'cpu.usage.average')), "", vm, interval)
  80. cpuUsage = ((float(sum(statCpuUsage[0].value[0].value)) / statInt) / 100)
  81. #Memory Active Average MB
  82. statMemoryActive = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'mem.active.average')), "", vm, interval)
  83. memoryActive = (float(sum(statMemoryActive[0].value[0].value) / 1024) / statInt)
  84. #Memory Shared
  85. statMemoryShared = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'mem.shared.average')), "", vm, interval)
  86. memoryShared = (float(sum(statMemoryShared[0].value[0].value) / 1024) / statInt)
  87. #Memory Balloon
  88. statMemoryBalloon = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'mem.vmmemctl.average')), "", vm, interval)
  89. memoryBalloon = (float(sum(statMemoryBalloon[0].value[0].value) / 1024) / statInt)
  90. #Memory Swapped
  91. statMemorySwapped = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'mem.swapped.average')), "", vm, interval)
  92. memorySwapped = (float(sum(statMemorySwapped[0].value[0].value) / 1024) / statInt)
  93. #Datastore Average IO
  94. statDatastoreIoRead = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'datastore.numberReadAveraged.average')),
  95. "*", vm, interval)
  96. DatastoreIoRead = (float(sum(statDatastoreIoRead[0].value[0].value)) / statInt)
  97. statDatastoreIoWrite = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'datastore.numberWriteAveraged.average')),
  98. "*", vm, interval)
  99. DatastoreIoWrite = (float(sum(statDatastoreIoWrite[0].value[0].value)) / statInt)
  100. #Datastore Average Latency
  101. statDatastoreLatRead = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'datastore.totalReadLatency.average')),
  102. "*", vm, interval)
  103. DatastoreLatRead = (float(sum(statDatastoreLatRead[0].value[0].value)) / statInt)
  104. statDatastoreLatWrite = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'datastore.totalWriteLatency.average')),
  105. "*", vm, interval)
  106. DatastoreLatWrite = (float(sum(statDatastoreLatWrite[0].value[0].value)) / statInt)
  107.  
  108. #Network usage (Tx/Rx)
  109. statNetworkTx = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'net.transmitted.average')), "", vm, interval)
  110. networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 / 1024) / statInt)
  111. statNetworkRx = BuildQuery(content, vchtime, (StatCheck(perf_dict, 'net.received.average')), "", vm, interval)
  112. networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 / 1024) / statInt)
  113.  
  114. print('networkRx:', networkRx)
  115. print('networkTx:', networkTx)
  116. print('\nNOTE: Any VM statistics are averages of the last {} minutes\n'.format(statInt / 3))
  117. print('Server Name :', summary.config.name)
  118. print('Description :', summary.config.annotation)
  119. print('Guest :', summary.config.guestFullName)
  120. if vm.rootSnapshot:
  121. print('Snapshot Status : Snapshots present')
  122. else:
  123. print('Snapshot Status : No Snapshots')
  124. print('VM .vmx Path :', summary.config.vmPathName)
  125. try:
  126. print('Virtual Disks :', disk_list[0])
  127. if len(disk_list) > 1:
  128. disk_list.pop(0)
  129. for each_disk in disk_list:
  130. print(' ', each_disk)
  131. except IndexError:
  132. pass
  133. print('Virtual NIC(s) :', network_list[0])
  134. if len(network_list) > 1:
  135. network_list.pop(0)
  136. for each_vnic in network_list:
  137. print(' ', each_vnic)
  138. print('[VM] Limits : CPU: {}, Memory: {}'.format(vmcpulimit, vmmemlimit))
  139. print('[VM] Reservations : CPU: {}, Memory: {}'.format(vmcpures, vmmemres))
  140. print('[VM] Number of vCPUs :', summary.config.numCpu)
  141. print('[VM] CPU Ready : Average {:.1f} %, Maximum {:.1f} %'.format((cpuReady / 20000 * 100),
  142. ((float(max(
  143. statCpuReady[0].value[
  144. 0].value)) / 20000 * 100))))
  145. print('[VM] CPU (%) : {:.0f} %'.format(cpuUsage))
  146. print('[VM] Memory : {} MB ({:.1f} GB)'.format(summary.config.memorySizeMB, (float(summary.config.memorySizeMB) / 1024)))
  147. print('[VM] Memory Shared : {:.0f} %, {:.0f} MB'.format(
  148. ((memoryShared / summary.config.memorySizeMB) * 100), memoryShared))
  149. print('[VM] Memory Balloon : {:.0f} %, {:.0f} MB'.format(
  150. ((memoryBalloon / summary.config.memorySizeMB) * 100), memoryBalloon))
  151. print('[VM] Memory Swapped : {:.0f} %, {:.0f} MB'.format(
  152. ((memorySwapped / summary.config.memorySizeMB) * 100), memorySwapped))
  153. print('[VM] Memory Active : {:.0f} %, {:.0f} MB'.format(
  154. ((memoryActive / summary.config.memorySizeMB) * 100), memoryActive))
  155. print('[VM] Datastore Average IO : Read: {:.0f} IOPS, Write: {:.0f} IOPS'.format(DatastoreIoRead,
  156. DatastoreIoWrite))
  157. print('[VM] Datastore Average Latency : Read: {:.0f} ms, Write: {:.0f} ms'.format(DatastoreLatRead,
  158. DatastoreLatWrite))
  159. print('[VM] Overall Network Usage : Transmitted {:.3f} Mbps, Received {:.3f} Mbps'.format(networkTx, networkRx))
  160. print('[Host] Name : {}'.format(summary.runtime.host.name))
  161. print('[Host] CPU Detail : Processor Sockets: {}, Cores per Socket {}'.format(
  162. summary.runtime.host.summary.hardware.numCpuPkgs,
  163. (summary.runtime.host.summary.hardware.numCpuCores / summary.runtime.host.summary.hardware.numCpuPkgs)))
  164. print('[Host] CPU Type : {}'.format(summary.runtime.host.summary.hardware.cpuModel))
  165. print('[Host] CPU Usage : Used: {} Mhz, Total: {} Mhz'.format(
  166. summary.runtime.host.summary.quickStats.overallCpuUsage,
  167. (summary.runtime.host.summary.hardware.cpuMhz * summary.runtime.host.summary.hardware.numCpuCores)))
  168. print('[Host] Memory Usage : Used: {:.0f} GB, Total: {:.0f} GB\n'.format(
  169. (float(summary.runtime.host.summary.quickStats.overallMemoryUsage) / 1024),
  170. (float(summary.runtime.host.summary.hardware.memorySize) / 1024 / 1024 / 1024)))
  171.  
  172. def StatCheck(perf_dict, counter_name):
  173. counter_key = perf_dict[counter_name]
  174. return counter_key
  175.  
  176. def GetProperties(content, viewType, props, specType):
  177. # Build a view and get basic properties for all Virtual Machines
  178. objView = content.viewManager.CreateContainerView(content.rootFolder, viewType, True)
  179. tSpec = vim.PropertyCollector.TraversalSpec(name='tSpecName', path='view', skip=False, type=vim.view.ContainerView)
  180. pSpec = vim.PropertyCollector.PropertySpec(all=False, pathSet=props, type=specType)
  181. oSpec = vim.PropertyCollector.ObjectSpec(obj=objView, selectSet=[tSpec], skip=False)
  182. pfSpec = vim.PropertyCollector.FilterSpec(objectSet=[oSpec], propSet=[pSpec], reportMissingObjectsInResults=False)
  183. retOptions = vim.PropertyCollector.RetrieveOptions()
  184. totalProps = []
  185. retProps = content.propertyCollector.RetrievePropertiesEx(specSet=[pfSpec], options=retOptions)
  186. totalProps += retProps.objects
  187. while retProps.token:
  188. retProps = content.propertyCollector.ContinueRetrievePropertiesEx(token=retProps.token)
  189. totalProps += retProps.objects
  190. objView.Destroy()
  191. # Turn the output in retProps into a usable dictionary of values
  192. gpOutput = []
  193. for eachProp in totalProps:
  194. propDic = {}
  195. for prop in eachProp.propSet:
  196. propDic[prop.name] = prop.val
  197. propDic['moref'] = eachProp.obj
  198. gpOutput.append(propDic)
  199. return gpOutput
  200.  
  201. def main():
  202. username = 'administrator@vsphere.local'
  203. password = 'xxxxxx'
  204. vc_ip = '172.16.65.99'
  205. vc_port = ''
  206. customization_spec_name = 'Ubuntu_Customization'
  207.  
  208. si = connect_vc(host=vc_ip, user=username, pwd=password, port=vc_port)
  209.  
  210. content = si.RetrieveContent()
  211. # Get vCenter date and time for use as baseline when querying for counters
  212. vchtime = si.CurrentTime()
  213.  
  214. # Get all the performance counters
  215. perf_dict = {}
  216. perfList = content.perfManager.perfCounter
  217. for counter in perfList:
  218. counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
  219. perf_dict[counter_full] = counter.key
  220.  
  221. retProps = GetProperties(content, [vim.VirtualMachine], ['name', 'runtime.powerState'], vim.VirtualMachine)
  222.  
  223. #Find VM supplied as arg and use Managed Object Reference (moref) for the PrintVmInfo
  224. for vm in retProps:
  225. PrintVmInfo(vm['moref'], content, vchtime, 20, perf_dict)
  226. break
  227.  
  228. # Start program
  229. if __name__ == "__main__":
  230. main()

通过vSphere API获取对象Statistics的更多相关文章

  1. 利用腾讯企业邮箱开放API获取账户未读邮件数初探

    公司一直使用腾讯提供的免费企业邮箱服务,今天用管理员帐户登录后发现,原来现在腾讯的企业邮箱也开放了部分API 你可以通过开放接口实现以下功能: 数据同步 数据同步可以帮助你同步部门成员信息,你还可以创 ...

  2. JavaSE_ API常用对象 总目录(11~14)

    JavaSE学习总结第11天_开发工具 & API常用对象111.01 常见开发工具介绍11.02 Eclipse和MyEclipse的概述11.03 Eclipse的下载安装及卸载11.04 ...

  3. 在C#中调用API获取网络信息和流量

    原文 在C#中调用API获取网络信息和流量 最近一项目中要求显示网络流量,而且必须使用C#. 事实上,调用 IpHlpApi.dll 的 GetIfTable API 可以轻易获得网络信息和网络流量. ...

  4. C# 通过豆瓣网络编程API获取图书信息

    这篇文章主要是关于如何通过豆瓣API获取信息的书籍,起初,我看到了原来的想法的内容是"C# 网络编程之网页简单下载实现"中通过HttpWebResponse类下载源代码,再通过正則 ...

  5. 【转】百度API获取城市名地名(附源码)

    在做一个软件时,用到了定位功能.网上有很多关于google 的GPS定位,但网上关于google定位都没有用, 搜索下原因:(这里建议大家在中国就尽量不使用系统自带的定位) 因为Google的服务器不 ...

  6. 通过SDK和API获取阿里云RDS的监控数据

    阿里云的RDS自带的监控系统获取数据不怎么直观,想要通过API获取数据通过zabbix显示,因为网上资料缺乏和其他一些原因,获取API签名很困难,但使用阿里云的SDK可以完美避开获取签名的步骤. 阿里 ...

  7. 使用Vue.js和Axios从第三方API获取数据 — SitePoint

    更多的往往不是,建立你的JavaScript应用程序时,你会想把数据从远程源或消耗一个[ API ](https:/ /恩.维基百科.org /维基/ application_programming_ ...

  8. zabbix通过SDK和API获取阿里云RDS的监控数据

    阿里云的RDS自带的监控系统获取数据不怎么直观,想要通过API获取数据通过zabbix显示,因为网上资料缺乏和其他一些原因,获取API签名很困难,但使用阿里云的SDK可以完美避开获取签名的步骤. 阿里 ...

  9. ASP.NET Web API 路由对象介绍

    ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...

随机推荐

  1. ASP.NET CORE RAZOR :个性化显示

    https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/da1 我们的电影应用有个不错的开始,但是展示效果还不够理想. 我 ...

  2. file_put_contents执行返回false,file_put_contents false(linux服务器httpd)

    file_put_contents执行返回false,file_put_contents false(linux服务器httpd) 默认下selinux是开启的查看SELinux状态:1./usr/s ...

  3. php里面用魔术方法和匿名函数闭包函数动态的给类里面添加方法

    1.认识  __set  (在给不可访问属性赋值时,__set() 会被调用) 也就是说你再访问一个类里面没有的属性,会出发这个方法 class A{ private $aa = '11'; publ ...

  4. Amzaon EC2虚拟化技术演进:从 Xen 到 Nitro

      今年2月,由光环新网运营的 AWS 中国(北京)区域和由西云数据运营的 AWS 中国 (宁夏)区域发布新的实例类型,新的实例类型包括 C5.C5d.R5.R5d.除了这四种之外,在AWS国外部分区 ...

  5. GNU LD 脚本学习笔记

    LD脚本(linker script)是什么 GNU ld是链接器,ld实际并不是GCC的一部分,ld属于binutils软件包.但是嵌入式开发时,下载的linaro GCC工具集中是包含 arm-l ...

  6. mybatis 单一参数时的动态语句

    public void getBookList(String publisher,String author){ Map<String,Object> maps = new HashMap ...

  7. 经常使用的eclipse快捷键-也适合sts

    非常多内容来自互联网和已知文件,本人仅整理. 1. ctrl+shift+r:打开资源 这可能是全部快捷键组合中最省时间的了. 这组快捷键能够让你打开你的工作区中不论什么一个文件.而你仅仅须要按下文件 ...

  8. ios 10 sticker pack application

    看了WWDC2016直播,我们发现变得谨慎而开放的苹果在新一版四大平台系统中展示了很多变化,当然重中之重还是伟大的iOS.通过试用iOS10beta版,除了长大了的更强大的Siri主要感受到iMess ...

  9. Laravel开发:多用户登录验证(1)

    之前实现了一次,后来代码忘记放哪了,所以有跳了一次坑. 先贴上Laravel自带的验证代码: 路由:routes/web.php // Authentication Routes... $this-& ...

  10. DevExpress控件显示前弹出到期时间解决办法

    方法是,删除Properties下的license.licx文件,重新生成即可.