GetVMs   B
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 146
rs 8.8
wmc 36

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __add_vm_properties_to_map_from_vm_array() 0 8 3
F run() 0 135 33
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
from pyVmomi import vim
17
18
from vmwarelib.actions import BaseAction
19
20
21
class GetVMs(BaseAction):
22
23
    def run(self, ids=None, names=None, datastores=None,
24
            datastore_clusters=None, resource_pools=None,
25
            vapps=None, hosts=None, folders=None, clusters=None,
26
            datacenters=None, virtual_switches=None,
27
            no_recursion=False, vsphere=None):
28
        # TODO: food for thought. PowerCli contains additional
29
        # parameters that are not present here for the folliwing reason:
30
        # <server> - we may need to bring it in if we decide to have
31
        #            connections to more than 1 VC.
32
        # <tag>    - Tags in VC are not the same as tags you see in Web
33
        #            Client for the reason, that those tags are stored
34
        #            in Inventory Service only. PowerCli somehow can access
35
        #            it, from vSphere SDK there is no way.
36
37
        self.establish_connection(vsphere)
38
39
        props = ['name', 'runtime.powerState']
40
        moid_to_vm = {}
41
42
        # getting vms by their ids
43
        vms_from_vmids = []
44
        if ids:
45
            vms_from_vmids = [vim.VirtualMachine(moid, stub=self.si._stub)
46
                              for moid in ids]
47
            GetVMs.__add_vm_properties_to_map_from_vm_array(moid_to_vm,
48
                                                            vms_from_vmids)
49
50
        # getting vms by their names
51
        vms_from_names = []
52
        if names:
53
            container = self.si_content.viewManager.CreateContainerView(
54
                self.si_content.rootFolder, [vim.VirtualMachine], True)
55
            for vm in container.view:
56
                if vm.name in names:
57
                    vms_from_names.append(vm)
58
            GetVMs.__add_vm_properties_to_map_from_vm_array(
59
                moid_to_vm, vms_from_names)
60
61
        # getting vms from datastore objects
62
        vms_from_datastores = []
63
        if datastores:
64
            vim_datastores = [vim.Datastore(moid, stub=self.si._stub)
65
                              for moid in datastores]
66
            for ds in vim_datastores:
67
                vms_from_datastores.extend(ds.vm)
68
            GetVMs.__add_vm_properties_to_map_from_vm_array(
69
                moid_to_vm, vms_from_datastores)
70
71
        # getting vms from datastore cluster objects
72
        vms_from_datastore_clusters = []
73
        if datastore_clusters:
74
            vim_datastore_clusters = [
75
                vim.StoragePod(moid, stub=self.si._stub)
76
                for moid in datastore_clusters
77
            ]
78
            for ds_cl in vim_datastore_clusters:
79
                for ds in ds_cl.childEntity:
80
                    vms_from_datastore_clusters.extend(ds.vm)
81
            GetVMs.__add_vm_properties_to_map_from_vm_array(
82
                moid_to_vm, vms_from_datastore_clusters)
83
84
        # getting vms from virtual switch objects
85
        vms_from_virtual_switches = []
86
        if virtual_switches:
87
            vim_virtual_switches = [
88
                vim.DistributedVirtualSwitch(moid, stub=self.si._stub)
89
                for moid in virtual_switches
90
            ]
91
            for vswitch in vim_virtual_switches:
92
                for pg in vswitch.portgroup:
93
                    vms_from_virtual_switches.extend(pg.vm)
94
            GetVMs.__add_vm_properties_to_map_from_vm_array(
95
                moid_to_vm, vms_from_virtual_switches)
96
97
        # getting vms from containers (location param)
98
        vms_from_containers = []
99
        containers = []
100
101
        if resource_pools:
102
            containers += [vim.ResourcePool(moid, stub=self.si._stub)
103
                           for moid in resource_pools]
104
105
        if vapps:
106
            containers += [vim.VirtualApp(moid, stub=self.si._stub)
107
                           for moid in vapps]
108
109
        if hosts:
110
            containers += [vim.HostSystem(moid, stub=self.si._stub)
111
                           for moid in hosts]
112
113
        if folders:
114
            containers += [vim.Folder(moid, stub=self.si._stub)
115
                           for moid in folders]
116
117
        if clusters:
118
            containers += [vim.ComputeResource(moid, stub=self.si._stub)
119
                           for moid in clusters]
120
121
        if datacenters:
122
            containers += [vim.Datacenter(moid, stub=self.si._stub)
123
                           for moid in datacenters]
124
125
        for cont in containers:
126
            objView = self.si_content.viewManager.CreateContainerView(
127
                cont, [vim.VirtualMachine], not no_recursion)
128
            tSpec = vim.PropertyCollector.TraversalSpec(
129
                name='tSpecName', path='view', skip=False,
130
                type=vim.view.ContainerView)
131
            pSpec = vim.PropertyCollector.PropertySpec(
132
                all=False, pathSet=props, type=vim.VirtualMachine)
133
            oSpec = vim.PropertyCollector.ObjectSpec(
134
                obj=objView, selectSet=[tSpec], skip=False)
135
            pfSpec = vim.PropertyCollector.FilterSpec(
136
                objectSet=[oSpec], propSet=[pSpec],
137
                reportMissingObjectsInResults=False)
138
            retOptions = vim.PropertyCollector.RetrieveOptions()
139
            retProps = self.si_content.propertyCollector.RetrievePropertiesEx(
140
                specSet=[pfSpec], options=retOptions)
141
            vms_from_containers += retProps.objects
142
            while retProps.token:
143
                retProps = self.si_content.propertyCollector.\
144
                    ContinueRetrievePropertiesEx(
145
                        token=retProps.token)
146
                vms_from_containers += retProps.objects
147
            objView.Destroy()
148
149
        for vm in vms_from_containers:
150
            if vm.obj._GetMoId() not in moid_to_vm:
151
                moid_to_vm[vm.obj._GetMoId()] = {
152
                    "moid": vm.obj._GetMoId(),
153
                    "name": vm.propSet[0].val,
154
                    "runtime.powerState": vm.propSet[1].val
155
                }
156
157
        return moid_to_vm.values()
158
159
    @staticmethod
160
    def __add_vm_properties_to_map_from_vm_array(vm_map, vm_array):
161
        for vm in vm_array:
162
            if vm._GetMoId() not in vm_map:
163
                vm_map[vm._GetMoId()] = {
164
                    "moid": vm._GetMoId(),
165
                    "name": vm.name,
166
                    "runtime.powerState": vm.runtime.powerState
167
                }
168