~asbalderson/+junk/virtio-test-auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python

# virtio test automation
# Copyright 2014 Canonical Ltd.

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import argparse
import libvirt
import yaml
import multiprocessing as mp
from jinja2 import Template
from event_server import start_server as start_event_server
from subprocess import call
from modules.monitor import check_timeout
import logging
import imp

base_path = os.getcwd()

log_path = base_path + '/log/'
cfg_path = base_path + '/config/'
tmpl_path = cfg_path + 'templates/'
dev_path = cfg_path + 'devices/'
role_path = cfg_path + 'roles/'

with open(cfg_path + 'parameters.conf') as f:
    config = imp.load_source('config', '', f)

logger = logging.getLogger('provision')

logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
fmt = logging.Formatter('%(asctime)s %(levelname)s: [provision] %(message)s', datefmt='%d/%m/%Y %T')
ch.setFormatter(fmt)
logger.addHandler(ch)


def net_setup(lv, net_tmpl, net_settings):
    with open(net_tmpl, 'r') as f:
        net_template = Template(f.read())

    net_xml = net_template.render(net_settings)

    try:
        vnet = lv.networkLookupByName(net_settings['name'])
        if vnet.isActive():
            logger.info("Network " + net_settings['name'] + " exists: Destroying and recreating")
            vnet.destroy()
        vnet.undefine()
    except libvirt.libvirtError:
        logger.info("Network " + net_settings['name'] + " doesn't exist: Creating")
    finally:
        try:
            vnet = lv.networkDefineXML(net_xml)
            vnet.setAutostart(True)
            vnet.create()
        except libvirt.libvirtError:
            logger.error("Failed creating network " + net_settings['name'] + "!")


def net_setup_all(lv, net_tmpl, net_cfg):
    with open(net_cfg, 'r') as f:
        net_settings = yaml.load(f)

    for net_setting in net_settings:
        net_setup(lv, net_tmpl, net_setting)


def os_setup(os_tmpl, os_version):
    with open(cfg_path + "os_repo.yml", 'r') as f:
        os_list = yaml.load(f)

    with open(os_tmpl, 'r') as f:
        template = Template(f.read())

    floppy_path = config.HOME_DIR + '/floppy' + os_version + '.img'

    os_yml = template.render(os_list['OS'][os_version], isorepo=config.ISO_PATH, floppy=floppy_path)

    # Customizing Autounattend.xml
    with open("./floppy_template/Autounattend_template.xml", 'r') as f:
        template = Template(f.read())

        autounattend = template.render(os_list['OS'][os_version])
        # print autounattend

    with open("./floppy_template/Autounattend.xml", "w") as f:
        f.write(autounattend)

    return os_yml


def vm_setup(lv, vm_tmpl, vm_settings):

    with open(vm_tmpl, 'r') as f:
        template = Template(f.read())

    vm_xml = template.render(vm_settings)

    try:
        vm = lv.lookupByName(vm_settings['name'])
        if vm.isActive():
            logger.info("VM " + vm_settings['name'] + " exists: Destroying and recreating")
            vm.destroy()
        vm.undefine()
    except libvirt.libvirtError:
        logger.info("VM " + vm_settings['name'] + " doesn't exist yet...")

    if os.path.isfile(vm_settings['disk']['file']):
        logger.info("Removing existing disk %s" % vm_settings['disk']['file'])
        os.unlink(vm_settings['disk']['file'])
    cmd = ' '.join(['qemu-img', 'create', '-f', vm_settings['disk']['type'], vm_settings['disk']['file'], vm_settings['disk']['size']])
    logger.info("Executing cmd: %s" % cmd)
    os.system(cmd)

    if (vm_settings.has_key('pvdisk')):
        if os.path.isfile(vm_settings['pvdisk']['file']):
            logger.info("Removing existing disk %s" % vm_settings['pvdisk']['file'])
            os.unlink(vm_settings['pvdisk']['file'])
        cmd = ' '.join(['qemu-img', 'create', '-f', vm_settings['pvdisk']['type'], vm_settings['pvdisk']['file'], vm_settings['pvdisk']['size']])
        logger.info("Executing cmd: %s" % cmd)
        os.system(cmd)

    if (vm_settings.has_key('pvscsi')):
        if os.path.isfile(vm_settings['pvscsi']['file']):
            logger.info("Removing existing disk %s" % vm_settings['pvscsi']['file'])
            os.unlink(vm_settings['pvscsi']['file'])
        cmd = ' '.join(['qemu-img', 'create', '-f', vm_settings['pvscsi']['type'], vm_settings['pvscsi']['file'], vm_settings['pvscsi']['size']])
        logger.info("Executing cmd: %s" % cmd)
        os.system(cmd)

    try:
        vm = lv.defineXML(vm_xml)
        vm.create()
        with open(log_path + vm_settings['name'] + ".xml", 'w') as f:
            f.write(vm_xml)
        logger.info("VM " + vm_settings['name'] + " has been created.")
    except libvirt.libvirtError:
        logger.error("Failed creating VM " + vm_settings['name'] + "!")


def vm_settings(vm, cfg):
    # Get OS config and set floppy/cdrom paths to ISO
    os_version = cfg['vms'][vm]['os']
    os_config = os_setup(tmpl_path + 'external_iso_template.yml', os_version)
    settings = yaml.load(os_config)

    vm_role = cfg['vms'][vm]['role']

    # Get resource config (mem,ncpu...) based on machine role
    base_file = role_path + vm_role + '.yml'
    with open(base_file, 'r') as f:
        base_template = Template(f.read())

    base_config = yaml.load(base_template.render(cfg['vms'][vm], vmrepo=config.VM_PATH))
    settings = dict(dict(settings).items() + base_config.items())

    logger.info("- Preparing vm " + vm + ": " + os_version + " " + vm_role)

    if vm_role == "sut":
        # Get all device config of testing vms
        for device in cfg['vms'][vm]['devices']:
            dev_file = dev_path + device + '.yml'
            with open(dev_file, 'r') as f:
                f_template = Template(f.read())
                dev_config = yaml.load(f_template.render(cfg['vms'][vm], vmrepo=config.VM_PATH))

            settings = dict(dict(settings).items() + dev_config.items())
        return settings

    else:
        # All other roles don't require extra devices
        return settings


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    gparser = parser.add_mutually_exclusive_group()
    gparser.add_argument('-w', '--whql', help='Deploy WHQL testbed', action="store_true")
    gparser.add_argument('-s', '--svvp', help='Deploy SVVP testbed', action="store_true")
    gparser.add_argument('-c', '--custom', metavar='<config file>', help='Deploy testbed from custom file')
    opts = parser.parse_args()

    if opts.whql:
        top_yml = cfg_path + 'whql.yml'
        tmpl_path = tmpl_path + 'whql/'
    elif opts.svvp:
        top_yml = cfg_path + 'svvp.yml'
        tmpl_path = tmpl_path + 'svvp/'
    elif opts.custom:
        top_yml = opts.custom
        tmpl_path = tmpl_path + 'custom/'
    else:
        print("Select an option: WHQL, SVVP or Custom (See help for more info)")
        sys.exit(2)

    logger.info("- Using config file: %s" % top_yml)

    with open(top_yml, 'r') as f:
        cfg = yaml.load(f)

    lv = libvirt.open('qemu:///system')

    logger.info("- Setting up networks")
    net_setup_all(lv, tmpl_path + 'net_template.xml', cfg_path + cfg['net'])

    with open(cfg_path + "os_repo.yml", 'r') as f:
        os_list = yaml.load(f)

    logger.info("- Creating images")
    for vm in cfg['vms']:
        # Gather each VM config
        settings = vm_settings(vm, cfg)

        # Create just one floppy disk per OS
        os_version = cfg['vms'][vm]['os']
        floppy_path = config.HOME_DIR + '/floppy' + os_version + '.img'

        if os.path.exists(floppy_path) is False:
            with open(config.HOME_DIR + '/log/floppy_' + vm + '_contents.log', 'w+') as f:
                call(["./gen_floppy.sh", floppy_path], stdout=f)

        # Create VM
        logger.info("- Creating VM %s" % cfg['vms'][vm]['name'])
        vm_setup(lv, tmpl_path + 'dom_template.xml', settings)

    # Fork VMs Monitor
    wait_time = config.WIN_INSTALL_TIMEOUT
    logger.info("VM status will be checked in %d seconds" % wait_time)

    for vm in cfg['vms']:
        monitor_install = mp.Process(target=check_timeout, args=(cfg, cfg['vms'][vm]['name'], wait_time, "os_install"))
        monitor_install.start()

    ev_cfg = {
        'net_cfg': cfg_path + cfg['net']
    }
    # Fork event server
    event_server = mp.Process(target=start_event_server, args=(ev_cfg,))
    event_server.start()
    event_server.join()
    logger.info("The number of failed tests is %d" % event_server.exitcode)
    os._exit(int(event_server.exitcode))