# Path: credentials.py
# VMWARE_VCENTER_USERNAME = "domain\\username"
# 
# Path: credentials.py
# VMWARE_VCENTER_PASSWORD = "yourpassword"
# 
# Path: pchelper.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://goo.gl/erbFDz
# 
#     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
# 
# Path: pchelper.py
# 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


from credentials import VMWARE_VCENTER_USERNAME
from credentials import VMWARE_VCENTER_PASSWORD
from pyVim.connect import SmartConnect
from pchelper import collect_properties
from pchelper import get_container_view
import operator
import time
import json
import logging.config
import pyVmomi
import ssl
    # Disable certificate verification otherwise it will error
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    ssl_context.verify_mode = ssl.CERT_NONE

    server_instance = None
    try:
        logger.debug("Connecting to: " + vcenter_server)
        server_instance = SmartConnect(host=vcenter_server, user=vcenter_username,
                                       pwd=vcenter_password, sslContext=ssl_context)
        server_instance._stub.connectionPoolTimeout = -1    # Turn the connection timeout off (default 900 sec)
    except Exception as error:
        logger.error("Error connecting to " + vcenter_server + str(error))

    return server_instance


def update_host_data(server):
    """This function is called to update the HOST data for the specified vcenter server"""
    logger = logging.getLogger(__name__)
    # API:  HostSystem -
    # https://pubs.vmware.com/vsphere-51/index.jsp#com.vmware.wssdk.apiref.doc/vim.HostSystem.html
    # summary.overallStatus: general "health" value: gray, green, red, yellow
    # summary.quickStats.overallCpuUsage: Aggregated CPU usage across all cores on the host in MHz.
    # summary.quickStats.overallMemoryUsage: Physical memory usage on the host in MB.
    # hardware.memorySize:  Total available RAM in bytes.

    try:
        # Fast way of getting Host properties using PropertyCollector
        # https://github.com/vmware/pyvmomi/blob/master/docs/vmodl/query/PropertyCollector.rst
        logger.debug("Getting PropertyCollector for " + server["name"])

# Path: credentials.py
# VMWARE_VCENTER_USERNAME = "domain\\username"
# 
# Path: credentials.py
# VMWARE_VCENTER_PASSWORD = "yourpassword"
# 
# Path: pchelper.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://goo.gl/erbFDz
# 
#     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
# 
# Path: pchelper.py
# 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


# Path: vmware_host.py
from credentials import VMWARE_VCENTER_USERNAME
from credentials import VMWARE_VCENTER_PASSWORD
from pyVim.connect import SmartConnect
from pchelper import collect_properties
from pchelper import get_container_view
import operator
import time
import json
import logging.config
import pyVmomi
import ssl

    # Disable certificate verification otherwise it will error
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    ssl_context.verify_mode = ssl.CERT_NONE

    server_instance = None
    try:
        logger.debug("Connecting to: " + vcenter_server)
        server_instance = SmartConnect(host=vcenter_server, user=vcenter_username,
                                       pwd=vcenter_password, sslContext=ssl_context)
        server_instance._stub.connectionPoolTimeout = -1    # Turn the connection timeout off (default 900 sec)
    except Exception as error:
        logger.error("Error connecting to " + vcenter_server + str(error))

    return server_instance


def update_host_data(server):
    """This function is called to update the HOST data for the specified vcenter server"""
    logger = logging.getLogger(__name__)
    # API:  HostSystem -
    # https://pubs.vmware.com/vsphere-51/index.jsp#com.vmware.wssdk.apiref.doc/vim.HostSystem.html
    # summary.overallStatus: general "health" value: gray, green, red, yellow
    # summary.quickStats.overallCpuUsage: Aggregated CPU usage across all cores on the host in MHz.
    # summary.quickStats.overallMemoryUsage: Physical memory usage on the host in MB.
    # hardware.memorySize:  Total available RAM in bytes.

    try:
        # Fast way of getting Host properties using PropertyCollector
        # https://github.com/vmware/pyvmomi/blob/master/docs/vmodl/query/PropertyCollector.rst
        logger.debug("Getting PropertyCollector for " + server["name"])

        container_view = get_container_view(server["conn"], obj_type=[pyVmomi.vim.HostSystem])