vm.py 8.69 KB
Newer Older
tarokkk committed
1 2 3 4 5 6 7
import lxml.etree as ET

# VM Instance class


class VMInstance:
    name = None
tarokkk committed
8 9 10
    arch = None
    vm_type = None
    os_boot = None
tarokkk committed
11 12 13 14 15
    vcpu = None
    cpu_share = None
    memory_max = None
    network_list = list()
    disk_list = list()
16
    graphics = dict
Guba Sándor committed
17
    raw_data = None
tarokkk committed
18 19 20 21 22

    def __init__(self,
                 name,
                 vcpu,
                 memory_max,
23
                 emulator='/usr/bin/kvm',
24 25
                 memory=None,
                 cpu_share=100,
tarokkk committed
26
                 arch="x86_64",
27
                 boot_menu=False,
28
                 vm_type="test",
tarokkk committed
29 30
                 network_list=None,
                 disk_list=None,
31
                 graphics=None,
Guba Sándor committed
32
                 acpi=True,
33
                 raw_data="",
user committed
34 35
                 seclabel_type="dynamic",
                 seclabel_mode="apparmor"):
tarokkk committed
36
        '''Default Virtual Machine constructor
37 38 39
        name    - unique name for the instance
        vcpu    - nubmer of processors
        memory_max  - maximum virtual memory (actual memory maybe add late)
40
        memory
41 42 43 44 45 46 47 48
        cpu_share   - KVM process priority (0-100)
        arch        - libvirt arch parameter default x86_64
        os_boot     - boot device default hd
        vm_type     - hypervisor type default kvm
        network_list    - VMNetwork list
        disk_list   - VMDIsk list
        graphics    - Dict that keys are: type, listen, port, passwd
        acpi        - True/False to enable acpi
user committed
49 50
        seclabel_type - libvirt security label type
        seclabel_mode - libvirt security mode (selinux, apparmor)
tarokkk committed
51 52
        '''
        self.name = name
53
        self.emulator = emulator
tarokkk committed
54 55 56
        self.vcpu = vcpu
        self.cpu_share = cpu_share
        self.memory_max = memory_max
57 58 59 60
        if memory is None:
            self.memory = memory_max
        else:
            self.memory = memory
tarokkk committed
61
        self.arch = arch
62
        self.boot_menu = boot_menu
tarokkk committed
63
        self.vm_type = vm_type
tarokkk committed
64 65
        self.network_list = network_list
        self.disk_list = disk_list
66 67
        self.graphics = graphics
        self.acpi = acpi
Guba Sándor committed
68
        self.raw_data = raw_data
user committed
69 70
        self.seclabel_type = seclabel_type
        self.seclabel_mode = seclabel_mode
tarokkk committed
71

72 73 74
    @classmethod
    def deserialize(cls, desc):
        desc['disk_list'] = [VMDisk.deserialize(d) for d in desc['disk_list']]
75 76
        desc['network_list'] = [VMNetwork.deserialize(
            n) for n in desc['network_list']]
77 78
        return cls(**desc)

tarokkk committed
79 80 81 82 83 84 85 86 87 88 89 90
    def build_xml(self):
        '''Return the root Element Tree object
        '''
        ET.register_namespace(
            'qemu', 'http://libvirt.org/schemas/domain/qemu/1.0')
        xml_top = ET.Element(
            'domain',
            attrib={
                'type': self.vm_type
            })
        # Basic virtual machine paramaters
        ET.SubElement(xml_top, 'name').text = self.name
91 92 93
        ET.SubElement(xml_top, 'vcpu').text = str(self.vcpu)
        ET.SubElement(xml_top, 'memory').text = str(self.memory_max)
        ET.SubElement(xml_top, 'currentMemory').text = str(self.memory)
tarokkk committed
94 95
        # Cpu tune
        cputune = ET.SubElement(xml_top, 'cputune')
96
        ET.SubElement(cputune, 'shares').text = str(self.cpu_share)
tarokkk committed
97 98 99
        # Os specific options
        os = ET.SubElement(xml_top, 'os')
        ET.SubElement(os, 'type', attrib={'arch': self.arch}).text = "hvm"
100 101
        ET.SubElement(os, 'bootmenu', attrib={
                      'enable': "yes" if self.boot_menu else "no"})
tarokkk committed
102 103
        # Devices
        devices = ET.SubElement(xml_top, 'devices')
104
        ET.SubElement(devices, 'emulator').text = self.emulator
tarokkk committed
105 106 107 108
        for disk in self.disk_list:
            devices.append(disk.build_xml())
        for network in self.network_list:
            devices.append(network.build_xml())
109 110 111 112 113 114 115
        # Console/graphics section
        if self.graphics is not None:
            ET.SubElement(devices,
                          'graphics',
                          attrib={
                              'type': self.graphics['type'],
                              'listen': self.graphics['listen'],
116
                              'port': str(self.graphics['port']),
117 118
                              'passwd': self.graphics['passwd'],
                          })
Guba Sándor committed
119
        # Features (TODO: features as list)
120 121 122
        features = ET.SubElement(xml_top, 'features')
        if self.acpi:
            ET.SubElement(features, 'acpi')
Guba Sándor committed
123
        # Building raw data into xml
124
        if self.raw_data:
Guba Sándor committed
125
            xml_top.append(ET.fromstring(self.raw_data))
user committed
126 127 128 129 130
        # Security label
        ET.SubElement(xml_top, 'seclabel', attrib={
            'type': self.seclabel_type,
            'mode': self.seclabel_mode
        })
tarokkk committed
131 132 133 134 135 136 137 138
        return xml_top

    def dump_xml(self):
        return ET.tostring(self.build_xml(),
                           encoding='utf8',
                           method='xml',
                           pretty_print=True)

tarokkk committed
139 140

class VMDisk:
tarokkk committed
141

tarokkk committed
142 143 144 145 146 147 148 149 150
    '''Virtual MAchine disk representing class
    '''
    name = None
    source = None
    disk_type = None
    disk_device = None
    driver_name = None
    driver_type = None
    driver_cache = None
tarokkk committed
151
    target_device = None
tarokkk committed
152 153 154 155 156 157 158

    def __init__(self,
                 source,
                 disk_type="file",
                 disk_device="disk",
                 driver_name="qemu",
                 driver_type="qcow2",
user committed
159
                 driver_cache="none",
160
                 target_device="vda"):
tarokkk committed
161 162 163 164 165 166
        self.source = source
        self.disk_type = disk_type
        self.disk_device = disk_device
        self.driver_name = driver_name
        self.driver_type = driver_type
        self.driver_cache = driver_cache
tarokkk committed
167
        self.target_device = target_device
tarokkk committed
168

169 170 171 172
    @classmethod
    def deserialize(cls, desc):
        return cls(**desc)

173
    def build_xml(self):
tarokkk committed
174 175 176 177 178
        xml_top = ET.Element('disk',
                             attrib={'type': self.disk_type,
                                     'device': self.disk_device})
        ET.SubElement(xml_top, 'source',
                      attrib={self.disk_type: self.source})
tarokkk committed
179 180 181 182 183 184 185 186
        ET.SubElement(xml_top, 'target',
                      attrib={'dev': self.target_device})
        ET.SubElement(xml_top, 'driver',
                      attrib={
                          'name': self.driver_name,
                          'type': self.driver_type,
                          'cache': self.driver_cache})
        return xml_top
tarokkk committed
187

188 189 190 191 192 193
    def dump_xml(self):
        return ET.tostring(self.build_xml(),
                           encoding='utf8',
                           method='xml',
                           pretty_print=True)

tarokkk committed
194 195

class VMNetwork:
196

tarokkk committed
197 198
    ''' Virtual Machine network representing class
    name            -- network device name
tarokkk committed
199
    bridge          -- bridg for the port
tarokkk committed
200
    mac             -- the MAC address of the quest interface
201 202
    ipv4            -- the IPv4 address of virtual machine (Flow control)
    ipv6            -- the IPv6 address of virtual machine (Flow controlo)
tarokkk committed
203
    vlan            -- Port VLAN configuration
tarokkk committed
204 205 206 207
    network_type    -- need to be "ethernet" by default
    model           -- available models in libvirt
    QoS             -- CIRCLE QoS class?
    comment         -- Any comment
Guba Sándor committed
208
    managed         -- Apply managed flow rules for spoofing prevent
tarokkk committed
209 210 211 212
    script          -- Executable network script /bin/true by default
    '''
    # Class attributes
    name = None
tarokkk committed
213
    bridge = None
tarokkk committed
214 215 216 217 218 219
    network_type = None
    mac = None
    model = None
    QoS = None
    script_exec = '/bin/true'
    comment = None
tarokkk committed
220
    vlan = 0
221 222
    ipv4 = None
    ipv6 = None
Guba Sándor committed
223
    managed = False
tarokkk committed
224 225 226 227

    def __init__(self,
                 name,
                 mac,
228
                 bridge="cloud",
229 230
                 ipv4=None,
                 ipv6=None,
tarokkk committed
231 232
                 network_type='ethernet',
                 model='virtio',
tarokkk committed
233
                 QoS=None,
Guba Sándor committed
234 235
                 vlan=0,
                 managed=False):
tarokkk committed
236
        self.name = name
tarokkk committed
237
        self.bridge = bridge
tarokkk committed
238 239
        self.network_type = network_type
        self.mac = mac
240 241
        self.ipv4 = ipv4
        self.ipv6 = ipv6
tarokkk committed
242 243
        self.model = model
        self.QoS = QoS
tarokkk committed
244
        self.vlan = vlan
Guba Sándor committed
245
        self.managed = managed
tarokkk committed
246

247 248 249 250
    @classmethod
    def deserialize(cls, desc):
        return cls(**desc)

tarokkk committed
251
    # XML dump
252
    def build_xml(self):
tarokkk committed
253 254 255 256 257
        xml_top = ET.Element('interface', attrib={'type': self.network_type})
        ET.SubElement(xml_top, 'target', attrib={'dev': self.name})
        ET.SubElement(xml_top, 'mac', attrib={'address': self.mac})
        ET.SubElement(xml_top, 'model', attrib={'type': self.model})
        ET.SubElement(xml_top, 'script', attrib={'path': self.script_exec})
258
        ET.SubElement(xml_top, 'rom', attrib={'bar': 'off'})
tarokkk committed
259
        return xml_top
260 261 262 263

    def dump_xml(self):
        return ET.tostring(self.build_xml(), encoding='utf8',
                           method='xml', pretty_print=True)