Skip to content

Commit

Permalink
Merge pull request #60 from michaelrice/issue-13
Browse files Browse the repository at this point in the history
adding an example to show how to get virtual machine info FAST. fixes is...
  • Loading branch information
Shawn Hartsock committed Jun 26, 2014
2 parents cf5032a + 021c539 commit fa3cf87
Show file tree
Hide file tree
Showing 2 changed files with 180 additions and 0 deletions.
101 changes: 101 additions & 0 deletions samples/tools/pchelper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""
Property Collector helper module.
"""

import pyVmomi


# Shamelessly borrowed from:
# https://github.com/dnaeon/py-vconnector/blob/master/src/vconnector/core.py
def collect_properties(service_instance, view_ref, obj_type, path_set=None,
include_mors=False):
"""
Collect properties for managed objects from a view ref
Check the vSphere API documentation for example on retrieving
object properties:
- http://pubs.vmware.com/vsphere-50/index.jsp#com.vmware.wssdk.pg.doc_50/PG_Ch5_PropertyCollector.7.2.html
Args:
si (ServiceInstance): ServiceInstance connection
view_ref (pyVmomi.vim.view.*): Starting point of inventory navigation
obj_type (pyVmomi.vim.*): Type of managed object
path_set (list): List of properties to retrieve
include_mors (bool): If True include the managed objects
refs in the result
Returns:
A list of properties for the managed objects
"""
collector = service_instance.content.propertyCollector

# Create object specification to define the starting point of
# inventory navigation
obj_spec = pyVmomi.vmodl.query.PropertyCollector.ObjectSpec()
obj_spec.obj = view_ref
obj_spec.skip = True

# Create a traversal specification to identify the path for collection
traversal_spec = pyVmomi.vmodl.query.PropertyCollector.TraversalSpec()
traversal_spec.name = 'traverseEntities'
traversal_spec.path = 'view'
traversal_spec.skip = False
traversal_spec.type = view_ref.__class__
obj_spec.selectSet = [traversal_spec]

# Identify the properties to the retrieved
property_spec = pyVmomi.vmodl.query.PropertyCollector.PropertySpec()
property_spec.type = obj_type

if not path_set:
property_spec.all = True

property_spec.pathSet = path_set

# Add the object and property specification to the
# property filter specification
filter_spec = pyVmomi.vmodl.query.PropertyCollector.FilterSpec()
filter_spec.objectSet = [obj_spec]
filter_spec.propSet = [property_spec]

# Retrieve properties
props = collector.RetrieveContents([filter_spec])

data = []
for obj in props:
properties = {}
for prop in obj.propSet:
properties[prop.name] = prop.val

if include_mors:
properties['obj'] = obj.obj

data.append(properties)
return data


def get_container_view(service_instance, obj_type, container=None):
"""
Get a vSphere Container View reference to all objects of type 'obj_type'
It is up to the caller to take care of destroying the View when no longer needed.
Args:
obj_type (list): A list of managed object types
Returns:
A container view ref to the discovered managed objects
"""
if not container:
container = service_instance.content.rootFolder

view_ref = service_instance.content.viewManager.CreateContainerView(
container=container,
type=obj_type,
recursive=True
)
return view_ref

79 changes: 79 additions & 0 deletions samples/vminfo_quick.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""
Written by Michael Rice
Github: https://github.com/michaelrice
Website: https://michaelrice.github.io/
Blog: http://www.errr-online.com/
This code has been released under the terms of the MIT licenses
http://opensource.org/licenses/MIT
Script to quickly get all the VMs with a set of common properties.
"""
__author__ = 'errr'

from time import clock
from tools import cli
from tools import pchelper
from pyVim import connect
from pyVmomi import vim

import atexit

START = clock()


def endit():
"""
times how long it took for this script to run.
:return:
"""
end = clock()
total = end - START
print "Completion time: {} seconds.".format(total)

# List of properties.
# See: http://vijava.sourceforge.net/vSphereAPIDoc/ver5/ReferenceGuide/vim.VirtualMachine.html
# for all properties.
vm_properties = ["name", "config.uuid", "config.hardware.numCPU",
"config.hardware.memoryMB", "guest.guestState",
"config.guestFullName", "config.guestId",
"config.version"]

args = cli.get_args()
service_instance = None
try:
service_instance = connect.SmartConnect(host=args.host,
user=args.user,
pwd=args.password,
port=int(args.port))
atexit.register(connect.Disconnect, service_instance)
atexit.register(endit)
except IOError, e:
pass

if not service_instance:
raise SystemExit("Unable to connect to host with supplied info.")

root_folder = service_instance.content.rootFolder
view = pchelper.get_container_view(service_instance,
obj_type=[vim.VirtualMachine])
vm_data = pchelper.collect_properties(service_instance, view_ref=view,
obj_type=vim.VirtualMachine,
path_set=vm_properties,
include_mors=True)
for vm in vm_data:
print "-" * 70
print "Name: {}".format(vm["name"])
print "BIOS UUID: {}".format(vm["config.uuid"])
print "CPUs: {}".format(vm["config.hardware.numCPU"])
print "MemoryMB: {}".format(vm["config.hardware.memoryMB"])
print "Guest PowerState: {}".format(vm["guest.guestState"])
print "Guest Full Name: {}".format(vm["config.guestFullName"])
print "Guest Container Type: {}".format(vm["config.guestId"])
print "Container Version: {}".format(vm["config.version"])


print ""
print "Found {} VirtualMachines.".format(len(vm_data))

0 comments on commit fa3cf87

Please sign in to comment.