Advertisement
Guest User

Untitled

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