dnaeon / py-vpoller

Distributed vSphere API Proxy
Other
83 stars 31 forks source link

Folder VM Get #280

Closed k05054 closed 2 years ago

k05054 commented 3 years ago

Hi @dnaeon. If you have some free time can you give me an advice. I'm trying to make a new method to discover VM's from their folders. As an example i took your resource.pool.vm.get method. But i got an error and i don't know what to do with it because data i'm getting looks right. So the code is:

@task(name='folder.vm.get', required=['name'])
def folder_vm_get(agent, msg):
    """
    Get properties for VMs objects from vim.Folder object
    Example client message would be:
        {
            "method":     "folder.vm.get",
            "hostname":   "vc01.example.org",
            "name":       "MyFolder",
            "properties": [
                "name",
            ]
        }
    Returns:
        The managed object properties in JSON format
    """
    folder_name = msg['name']
    properties = ['name']
    if 'properties' in msg and msg['properties']:
        properties.extend(msg['properties'])

    logger.debug(
        '[%s] Getting ChildEntity list from %s Folder',
        agent.host,
        folder_name,
    )

    # Find the Folder managed object and get the 'ChildEntity ' property
    data = _get_object_properties(
        agent=agent,
        properties=['childEntity'],
        obj_type=pyVmomi.vim.Folder,
        obj_property_name='name',
        obj_property_value=folder_name,
    )

    if data['success'] != 0:
        return data

    s1 = open('/tmp/data.txt', 'w')
    s1.write(str(data))
    s1.close()

    props = data['result'][0]
    vms = props['childEntity']

    s2 = open('/tmp/vms.txt', 'w')
    s2.write(str(vms))
    s2.close

    # Create a list view for the VirtualMachine managed objects
    view_ref = agent.get_list_view(obj='vms')
    result = agent.collect_properties(
        view_ref=view_ref,
        obj_type=pyVmomi.vim.VirtualMachine,
        path_set=properties,
    )

    view_ref.DestroyView()

    r = {
        'success': 0,
        'msg': 'Successfully discovered objects',
        'result': result,
    }

    return r

The error i got: {"msg": "Task folder.vm.get failed", "traceback": "Traceback (most recent call last):\n File \"build/bdist.linux-x86_64/egg/vpoller/task/decorators.py\", line 55, in wrapper\n result = fn(*args, **kwargs)\n File \"build/bdist.linux-x86_64/egg/vpoller/vsphere/tasks.py\", line 1561, in sp_ds_get\n view_ref = agent.get_list_view(obj='vms')\n File \"/usr/lib/python2.7/site-packages/vconnector/core.py\", line 377, in get_list_view\n view_ref = self.si.content.viewManager.CreateListView(obj=obj)\n File \"/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py\", line 706, in <lambda>\n self.f(*(self.args + (obj,) + args), **kwargs)\n File \"/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py\", line 511, in _InvokeMethod\n list(map(CheckField, info.params, args))\n File \"/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py\", line 1080, in CheckField\n CheckField(itemInfo, it)\n File \"/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py\", line 1098, in CheckField\n % (info.name, info.type.__name__, valType.__name__))\nTypeError: For \"obj\" expected type ManagedObject, but got str\n", "success": 1} And intermediate result i managed to get with print to file

{'msg': 'Successfully retrieved object properties', 'result': [{u'childEntity': (ManagedObject) [
   'vim.VirtualMachine:vm-4358',
   'vim.VirtualMachine:vm-1489',
   'vim.VirtualMachine:vm-28',
   'vim.VirtualMachine:vm-1026',
   'vim.VirtualMachine:vm-46',
   'vim.VirtualMachine:vm-1761',
   'vim.VirtualMachine:vm-30',
   'vim.VirtualMachine:vm-675',
   'vim.VirtualMachine:vm-17',
   'vim.VirtualMachine:vm-55',
   'vim.VirtualMachine:vm-1404'
]}], 'success': 0}

What am i doing wrong ?

k05054 commented 3 years ago

I got it by myself. I made some mistakes when i wrote this method. I'll leave the code here with some explanations i need it. So the explanation is very simple. I tried to divide all my VMs so that each group is associated with its project with the resource.pool.vm.get method but I got a problem. The problem is that if you have 2 or more clusters in your system you can create RPs with identical names and VMs discovery won't be complete. The problem is that vPoller will discover VMs only from RP it found first. The remaining objects will be skipped. But the folder names are unique and you can't make two or more folders with identical names in one vCenter. So i think i managed to accomplish my task with this new method. The right code is:

@task(name='folder.vm.get', required=['name'])
def folder_vm_get(agent, msg):
    """
    Get properties for VMs objects from vim.Folder object
    Example client message would be:
        {
            "method":     "folder.vm.get",
            "hostname":   "vc01.example.org",
            "name":       "MyFolder",
            "properties": [
                "name",
            ]
        }
    Returns:
        The managed object properties in JSON format
    """
    folder_name = msg['name']
    properties = ['name']
    if 'properties' in msg and msg['properties']:
        properties.extend(msg['properties'])

    logger.debug(
        '[%s] Getting ChildEntity list from %s Folder',
        agent.host,
        folder_name,
    )

    # Find the Folder managed object and get the 'ChildEntity ' property
    data = _get_object_properties(
        agent=agent,
        properties=['childEntity'],
        obj_type=pyVmomi.vim.Folder,
        obj_property_name='name',
        obj_property_value=folder_name,
    )

    if data['success'] != 0:
        return data

    props = data['result'][0]
    vms = props['childEntity']

   # Create a list view for the VirtualMachine managed objects
    view_ref = agent.get_list_view(obj=vms)
    result = agent.collect_properties(
        view_ref=view_ref,
        obj_type=pyVmomi.vim.VirtualMachine,
        path_set=properties,
    )

    view_ref.DestroyView()

    r = {
        'success': 0,
        'msg': 'Successfully discovered objects',
        'result': result,
    }

    return r
k05054 commented 3 years ago

Hi again. I reopened this issue because i need an advice. Now i want to discover VM's from folder AND it's child folders in one method. In vconnector i found a function get_container_view and want to use it. But i don't understand what value i need to put in 'container' property to discover all child folders from folder. test = agent.get_container_view(obj_type=[pyVmomi.vim.Folder], container=?????) Can anyone help me ?