from pyVmomi import vim
from tools import cli
from pyVim.connect import SmartConnectNoSSL, Disconnect
import atexit
import getpass
import datetime
def main():
args = cli.get_args()
# Connect to the host without SSL signing
try:
si = SmartConnectNoSSL(
host=args.host,
user=args.user,
pwd=args.password,
port=int(args.port))
atexit.register(Disconnect, si)
except IOError as e:
pass
if not si:
raise SystemExit("Unable to connect to host with supplied info.")
content = si.RetrieveContent()
perfManager = content.perfManager
# create a mapping from performance stats to their counterIDs
# counterInfo: [performance stat => counterId]
# performance stat example: cpu.usagemhz.LATEST
# counterId example: 6
counterInfo = {}
for c in perfManager.perfCounter:
prefix = c.groupInfo.key
fullName = c.groupInfo.key + "." + c.nameInfo.key + "." + c.rollupType
counterInfo[fullName] = c.key
#print'fullName {}= {}'.format(fullName,c.key)
# create a list of vim.VirtualMachine objects so
# that we can query them for statistics
container = content.rootFolder
viewType = [vim.VirtualMachine]
recursive = True
containerView = content.viewManager.CreateContainerView(container,
viewType,
recursive)
children = containerView.view
#startTime = datetime.datetime.now() - datetime.timedelta(hours=24)
#endTime = datetime.datetime.now()
# Loop through all the VMs
for child in children:
# Get all available metric IDs for this VM
#counterIDs = [m.counterId for m in
# perfManager.QueryAvailablePerfMetric(child,None,None,20)]
#print("child counterIDS",counterIDs)
counterIDs = [146,147,470,471]
# Using the IDs form a list of MetricId
# objects for building the Query Spec
metricIDs = [vim.PerformanceManager.MetricId(counterId=c,
instance="")
for c in counterIDs]
#print("metricIDs ",metricIDs)
# Build the specification to be used
# for querying the performance manager
spec = vim.PerformanceManager.QuerySpec(maxSample=2,
entity=child,
metricId=metricIDs,
intervalId=20)
# Query the performance manager
# based on the metrics created above
result = perfManager.QueryStats(querySpec=[spec])
# Loop through the results and print the output
output = ""
for r in result:
print("the r is ",r)
output += "name: " + child.summary.config.name + "\n"
for val in result[0].value:
output += counterInfo.keys()[
counterInfo.values().index(val.id.counterId)]
output += ": " + str(val.value[0]) + "\n"
output += "\n"
print(output)
if __name__ == "__main__":
main()
说明: 1)因为我们要取的数据是明确的,就是要取
net.packetsRx.summation= 146
net.packetsTx.summation= 147
net.bytesRx.average= 470
net.bytesTx.average= 471
所以没有使用 perfManager.QueryAvailablePerfMetric(child,None,None,20) 查询虚拟机可以使用的countId
2) vim.PerformanceManager.MetricId(counterId=c,instance="")
instance 参数可以指定为 "*" 或者是空串 "",
空串返回结果时不会将主机的相关数据一起传回来,“*” 返回的结果是带有主机的相关数据的.
比如,对上面的countId, "*" 会返回,vmnic0,vmnic1,vmnic2,vmnic3,vmnic4,vmnic5,4000的数据
3) 构造PerfQuerySpec 对象时,需要加上 intervalId 参数,如果不加上这个参数,则会取不到实时数据,只能取到 net.usage.average= 143 数据(对网络来说)
调用perfManager.QueryAvailablePerfMetric(child) 方法反回的数组中没有 146,147,470,471,只有143