Completed
Push — master ( ca2760...4c7c7c )
by Manas
15s
created

VMUpdateNic._get_vnic_device()   B

Complexity

Conditions 7

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 7
dl 0
loc 16
rs 7.3333
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 import inventory
19
from vmwarelib.actions import BaseAction
20
21
22
class VMUpdateNic(BaseAction):
23
24
    def run(self, vm_id, network_id, vnic_key, ip, subnet, gateway=None, domain=None):
25
        # convert ids to stubs
26
        virtualmachine = inventory.get_virtualmachine(self.si_content, vm_id)
27
        network = inventory.get_network(self.si_content, network_id)
28
        vnic = self._get_vnic_device(virtualmachine, vnic_key)
29
30
        # add new vnic
31
        configspec = vim.vm.ConfigSpec()
32
        nic = vim.vm.device.VirtualDeviceSpec()
33
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
34
        nic.device = vim.vm.device.VirtualVmxnet3()
35
        nic.device.wakeOnLanEnabled = True
36
        nic.device.addressType = 'assigned'
37
        nic.device.key = vnic.key
38
        nic.device.deviceInfo = vim.Description()
39
        nic.device.deviceInfo.label = 'Network Adapter-%s' % (ip)
40
        nic.device.deviceInfo.summary = 'summary'
41
        nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
42
        nic.device.backing.port = vim.dvs.PortConnection()
43
        nic.device.backing.port.switchUuid = network.config.distributedVirtualSwitch.uuid
44
        nic.device.backing.port.portgroupKey = network.config.key
45
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
46
        nic.device.connectable.startConnected = True
47
        nic.device.connectable.allowGuestControl = True
48
        configspec.deviceChange = [nic]
49
        add_vnic_task = virtualmachine.ReconfigVM_Task(configspec)
50
        successfully_added_vnic = self._wait_for_task(add_vnic_task)
51
52
        if not successfully_added_vnic:
53
            return self._format_result(successfully_added_vnic, 'Failed to update nic.')
54
55
        adaptermap = vim.vm.customization.AdapterMapping()
56
        adaptermap.adapter = vim.vm.customization.IPSettings()
57
        adaptermap.adapter.ip = vim.vm.customization.FixedIp()
58
        adaptermap.adapter.ip.ipAddress = ip
59
        adaptermap.adapter.subnetMask = subnet
60
        adaptermap.adapter.gateway = gateway
61
        adaptermap.adapter.dnsDomain = domain
62
63
        globalip = vim.vm.customization.GlobalIPSettings()
64
65
        ident = vim.vm.customization.LinuxPrep()
66
        ident.domain = domain
67
        ident.hostName = vim.vm.customization.FixedName()
68
        ident.hostName.name = virtualmachine.name
69
70
        customspec = vim.vm.customization.Specification()
71
        customspec.identity = ident
72
        customspec.nicSettingMap = [adaptermap]
73
        customspec.globalIPSettings = globalip
74
75
        try:
76
            customize_task = virtualmachine.Customize(spec=customspec)
77
            successfully_customized = self._wait_for_task(customize_task)
78
        except:
79
            self.logger.exception('Failed to create customization spec.')
80
            raise
81
        msg = 'Updated nic and assigned IP.' if successfully_customized else 'Failed to assign ip.'
82
        return self._format_result(successfully_customized, msg=msg)
83
84
    @staticmethod
85
    def _get_vnic_device(vm, vnic_key=-1):
86
        verify_vnic = vnic_key != -1
87
        for device in vm.config.hardware.device:
88
            # If a key is passed in verify that it is a vnic else look for the first vnic.
89
            if verify_vnic and device.key == vnic_key:
90
                is_vnic = isinstance(device, vim.vm.device.VirtualEthernetCard)
91
                if not is_vnic:
92
                    raise Exception('Invalid device key %s' % str(vnic_key))
93
                return device
94
            elif not verify_vnic:
95
                is_vnic = isinstance(device, vim.vm.device.VirtualEthernetCard)
96
                if is_vnic:
97
                    return device
98
        # ending up here mean a bad key or no vnic.
99
        raise Exception('vnic for device %s not found' % str(vnic_key))
100
101
    @staticmethod
102
    def _format_result(state, msg=None):
103
        return {'state': state, 'msg': msg}
104