Statistics
| Branch: | Tag: | Revision:

mininet / util / vm / build.py @ 67f9d8f6

History | View | Annotate | Download (17.4 KB)

1
#!/usr/bin/python
2

    
3
"""
4
build.py: build a Mininet VM
5

6
Basic idea:
7

8
    prepare
9
    -> create base install image if it's missing
10
        - download iso if it's missing
11
        - install from iso onto image
12
    
13
    build
14
    -> create cow disk for new VM, based on base image
15
    -> boot it in qemu/kvm with text /serial console
16
    -> install Mininet
17

18
    test
19
    -> make codecheck
20
    -> make test
21

22
    release
23
    -> shut down VM
24
    -> shrink-wrap VM
25
    -> upload to storage
26

27
"""
28

    
29
import os
30
from os import stat, path
31
from stat import ST_MODE
32
from os.path import abspath
33
from sys import exit, argv
34
from glob import glob
35
from subprocess import check_output, call, Popen
36
from tempfile import mkdtemp
37
from time import time, strftime, localtime
38
import argparse
39

    
40
pexpect = None  # For code check - imported dynamically
41

    
42
# boot can be slooooow!!!! need to debug/optimize somehow
43
TIMEOUT=600
44

    
45
VMImageDir = os.environ[ 'HOME' ] + '/vm-images'
46

    
47
isoURLs = {
48
    'precise32server':
49
    'http://mirrors.kernel.org/ubuntu-releases/12.04/'
50
    'ubuntu-12.04.3-server-i386.iso',
51
    'precise64server':
52
    'http://mirrors.kernel.org/ubuntu-releases/12.04/'
53
    'ubuntu-12.04.3-server-amd64.iso',
54
    'quetzal32server':
55
    'http://mirrors.kernel.org/ubuntu-releases/12.10/'
56
    'ubuntu-12.10-server-i386.iso',
57
    'quetzal64server':
58
    'http://mirrors.kernel.org/ubuntu-releases/12.10/'
59
    'ubuntu-12.10-server-amd64.iso',
60
    'raring32server':
61
    'http://mirrors.kernel.org/ubuntu-releases/13.04/'
62
    'ubuntu-13.04-server-i386.iso',
63
    'raring64server':
64
    'http://mirrors.kernel.org/ubuntu-releases/13.04/'
65
    'ubuntu-13.04-server-amd64.iso',
66
}
67

    
68
logStartTime = time()
69

    
70
def log( *args, **kwargs ):
71
    """Simple log function: log( message along with local and elapsed time
72
       cr: False/0 for no CR"""
73
    cr = kwargs.get( 'cr', True )
74
    elapsed = time() - logStartTime
75
    clocktime = strftime( '%H:%M:%S', localtime() )
76
    msg = ' '.join( str( arg ) for arg in args )
77
    output = '%s [ %.3f ] %s' % ( clocktime, elapsed, msg )
78
    if cr:
79
        print output
80
    else:
81
        print output,
82

    
83

    
84
def run( cmd, **kwargs ):
85
    "Convenient interface to check_output"
86
    log( '-', cmd )
87
    cmd = cmd.split()
88
    return check_output( cmd, **kwargs )
89

    
90

    
91
def srun( cmd, **kwargs ):
92
    "Run + sudo"
93
    return run( 'sudo ' + cmd, **kwargs )
94

    
95

    
96
def depend():
97
    "Install package dependencies"
98
    log( '* Installing package dependencies' )
99
    run( 'sudo apt-get -y update' )
100
    run( 'sudo apt-get install -y'
101
         ' kvm cloud-utils genisoimage qemu-kvm qemu-utils'
102
         ' e2fsprogs '
103
         ' landscape-client'
104
         ' python-setuptools' )
105
    run( 'sudo easy_install pexpect' )
106

    
107

    
108
def popen( cmd ):
109
    "Convenient interface to popen"
110
    log( cmd )
111
    cmd = cmd.split()
112
    return Popen( cmd )
113

    
114

    
115
def remove( fname ):
116
    "rm -f fname"
117
    return run( 'rm -f %s' % fname )
118

    
119

    
120
def findiso( flavor ):
121
    "Find iso, fetching it if it's not there already"
122
    url = isoURLs[ flavor ]
123
    name = path.basename( url )
124
    iso = path.join( VMImageDir, name )
125
    if not path.exists( iso ) or ( stat( iso )[ ST_MODE ] & 0777 != 0444 ):
126
        log( '* Retrieving', url )
127
        run( 'curl -C - -o %s %s' % ( iso, url ) )
128
        if 'ISO' not in run( 'file ' + iso ):
129
            os.remove( iso )
130
            raise Exception( 'findiso: could not download iso from ' + url )
131
        # Write-protect iso, signaling it is complete
132
        log( '* Write-protecting iso', iso)
133
        os.chmod( iso, 0444 )
134
    log( '* Using iso', iso )
135
    return iso
136

    
137

    
138
def attachNBD( cow, flags='' ):
139
    """Attempt to attach a COW disk image and return its nbd device
140
        flags: additional flags for qemu-nbd (e.g. -r for readonly)"""
141
    # qemu-nbd requires an absolute path
142
    cow = abspath( cow )
143
    log( '* Checking for unused /dev/nbdX device ' )
144
    for i in range ( 0, 63 ):
145
        nbd = '/dev/nbd%d' % i
146
        # Check whether someone's already messing with that device
147
        if call( [ 'pgrep', '-f', nbd ] ) == 0:
148
            continue
149
        srun( 'modprobe nbd max-part=64' )
150
        srun( 'qemu-nbd %s -c %s %s' % ( flags, nbd, cow ) )
151
        print
152
        return nbd
153
    raise Exception( "Error: could not find unused /dev/nbdX device" )
154

    
155

    
156
def detachNBD( nbd ):
157
    "Detatch an nbd device"
158
    srun( 'qemu-nbd -d ' + nbd )
159

    
160

    
161
def extractKernel( image, flavor ):
162
    "Extract kernel and initrd from base image"
163
    kernel = path.join( VMImageDir, flavor + '-vmlinuz' )
164
    initrd = path.join( VMImageDir, flavor + '-initrd' )
165
    if path.exists( kernel ) and ( stat( image )[ ST_MODE ] & 0777 ) == 0444:
166
        # If kernel is there, then initrd should also be there
167
        return kernel, initrd
168
    log( '* Extracting kernel to', kernel )
169
    nbd = attachNBD( image, flags='-r' )
170
    print srun( 'partx ' + nbd )
171
    # Assume kernel is in partition 1/boot/vmlinuz*generic for now
172
    part = nbd + 'p1'
173
    mnt = mkdtemp()
174
    srun( 'mount -o ro %s %s' % ( part, mnt  ) )
175
    kernsrc = glob( '%s/boot/vmlinuz*generic' % mnt )[ 0 ]
176
    initrdsrc = glob( '%s/boot/initrd*generic' % mnt )[ 0 ]
177
    srun( 'cp %s %s' % ( initrdsrc, initrd ) )
178
    srun( 'chmod 0444 ' + initrd )
179
    srun( 'cp %s %s' % ( kernsrc, kernel ) )
180
    srun( 'chmod 0444 ' + kernel )
181
    srun( 'umount ' + mnt )
182
    run( 'rmdir ' + mnt )
183
    detachNBD( nbd )
184
    return kernel, initrd
185

    
186

    
187
def findBaseImage( flavor, size='8G' ):
188
    "Return base VM image and kernel, creating them if needed"
189
    image = path.join( VMImageDir, flavor + '-base.img' )
190
    if path.exists( image ):
191
        # Detect race condition with multiple builds
192
        perms = stat( image )[ ST_MODE ] & 0777
193
        if perms != 0444:
194
            raise Exception( 'Error - %s is writable ' % image +
195
                            '; are multiple builds running?' )
196
    else:
197
        # We create VMImageDir here since we are called first
198
        run( 'mkdir -p %s' % VMImageDir )
199
        iso = findiso( flavor )
200
        log( '* Creating image file', image )
201
        run( 'qemu-img create %s %s' % ( image, size ) )
202
        installUbuntu( iso, image )
203
        # Write-protect image, also signaling it is complete
204
        log( '* Write-protecting image', image)
205
        os.chmod( image, 0444 )
206
    kernel, initrd = extractKernel( image, flavor )
207
    log( '* Using base image', image, 'and kernel', kernel )
208
    return image, kernel, initrd
209

    
210

    
211
# Kickstart and Preseed files for Ubuntu/Debian installer
212
#
213
# Comments: this is really clunky and painful. If Ubuntu
214
# gets their act together and supports kickstart a bit better
215
# then we can get rid of preseed and even use this as a
216
# Fedora installer as well.
217
#
218
# Another annoying thing about Ubuntu is that it can't just
219
# install a normal system from the iso - it has to download
220
# junk from the internet, making this house of cards even
221
# more precarious.
222

    
223
KickstartText ="""
224
#Generated by Kickstart Configurator
225
#platform=x86
226

227
#System language
228
lang en_US
229
#Language modules to install
230
langsupport en_US
231
#System keyboard
232
keyboard us
233
#System mouse
234
mouse
235
#System timezone
236
timezone America/Los_Angeles
237
#Root password
238
rootpw --disabled
239
#Initial user
240
user mininet --fullname "mininet" --password "mininet"
241
#Use text mode install
242
text
243
#Install OS instead of upgrade
244
install
245
#Use CDROM installation media
246
cdrom
247
#System bootloader configuration
248
bootloader --location=mbr
249
#Clear the Master Boot Record
250
zerombr yes
251
#Partition clearing information
252
clearpart --all --initlabel
253
#Automatic partitioning
254
autopart
255
#System authorization infomation
256
auth  --useshadow  --enablemd5
257
#Firewall configuration
258
firewall --disabled
259
#Do not configure the X Window System
260
skipx
261
"""
262

    
263
# Tell the Ubuntu/Debian installer to stop asking stupid questions
264

    
265
PreseedText = """
266
d-i mirror/country string manual
267
d-i mirror/http/hostname string mirrors.kernel.org
268
d-i mirror/http/directory string /ubuntu
269
d-i mirror/http/proxy string
270
d-i partman/confirm_write_new_label boolean true
271
d-i partman/choose_partition select finish
272
d-i partman/confirm boolean true
273
d-i partman/confirm_nooverwrite boolean true
274
d-i user-setup/allow-password-weak boolean true
275
d-i finish-install/reboot_in_progress note
276
d-i debian-installer/exit/poweroff boolean true
277
"""
278

    
279
def makeKickstartFloppy():
280
    "Create and return kickstart floppy, kickstart, preseed"
281
    kickstart = 'ks.cfg'
282
    with open( kickstart, 'w' ) as f:
283
        f.write( KickstartText )
284
    preseed = 'ks.preseed'
285
    with open( preseed, 'w' ) as f:
286
        f.write( PreseedText )
287
    # Create floppy and copy files to it
288
    floppy = 'ksfloppy.img'
289
    run( 'qemu-img create %s 1440k' % floppy )
290
    run( 'mkfs -t msdos ' + floppy )
291
    run( 'mcopy -i %s %s ::/' % ( floppy, kickstart ) )
292
    run( 'mcopy -i %s %s ::/' % ( floppy, preseed ) )
293
    return floppy, kickstart, preseed
294

    
295

    
296
def kvmFor( filepath ):
297
    "Guess kvm version for file path"
298
    name = path.basename( filepath )
299
    if '64' in name:
300
        kvm = 'qemu-system-x86_64'
301
    elif 'i386' in name or '32' in name:
302
        kvm = 'qemu-system-i386'
303
    else:
304
        log( "Error: can't discern CPU for file name", name )
305
        exit( 1 )
306
    return kvm
307

    
308

    
309
def installUbuntu( iso, image, logfilename='install.log' ):
310
    "Install Ubuntu from iso onto image"
311
    kvm = kvmFor( iso )
312
    floppy, kickstart, preseed = makeKickstartFloppy()
313
    # Mount iso so we can use its kernel
314
    mnt = mkdtemp()
315
    srun( 'mount %s %s' % ( iso, mnt ) )
316
    kernel = path.join( mnt, 'install/vmlinuz' )
317
    initrd = path.join( mnt, 'install/initrd.gz' )
318
    cmd = [ 'sudo', kvm,
319
           '-machine', 'accel=kvm',
320
           '-nographic',
321
           '-netdev', 'user,id=mnbuild',
322
           '-device', 'virtio-net,netdev=mnbuild',
323
           '-m', '1024',
324
           '-k', 'en-us',
325
           '-fda', floppy,
326
           '-drive', 'file=%s,if=virtio' % image,
327
           '-cdrom', iso,
328
           '-kernel', kernel,
329
           '-initrd', initrd,
330
           '-append',
331
           ' ks=floppy:/' + kickstart +
332
           ' preseed/file=floppy://' + preseed +
333
           ' console=ttyS0' ]
334
    ubuntuStart = time()
335
    log( '* INSTALLING UBUNTU FROM', iso, 'ONTO', image )
336
    log( ' '.join( cmd ) )
337
    log( '* logging to', abspath( logfilename ) )
338
    logfile = open( logfilename, 'w' )
339
    vm = Popen( cmd, stdout=logfile, stderr=logfile )
340
    log( '* Waiting for installation to complete')
341
    vm.wait()
342
    logfile.close()
343
    elapsed = time() - ubuntuStart
344
    # Unmount iso and clean up
345
    srun( 'umount ' + mnt )
346
    run( 'rmdir ' + mnt )
347
    log( '* UBUNTU INSTALLATION COMPLETED FOR', image )
348
    log( '* Ubuntu installation completed in %.2f seconds ' % elapsed )
349

    
350

    
351
def boot( cow, kernel, initrd, logfile ):
352
    """Boot qemu/kvm with a COW disk and local/user data store
353
       cow: COW disk path
354
       kernel: kernel path
355
       logfile: log file for pexpect object
356
       returns: pexpect object to qemu process"""
357
    # pexpect might not be installed until after depend() is called
358
    global pexpect
359
    import pexpect
360
    kvm = kvmFor( kernel )
361
    cmd = [ 'sudo', kvm,
362
            '-machine accel=kvm',
363
            '-nographic',
364
            '-netdev user,id=mnbuild',
365
            '-device virtio-net,netdev=mnbuild',
366
            '-m 1024',
367
            '-k en-us',
368
            '-kernel', kernel,
369
            '-initrd', initrd,
370
            '-drive file=%s,if=virtio' % cow,
371
            '-append "root=/dev/vda1 init=/sbin/init console=ttyS0" ' ]
372
    cmd = ' '.join( cmd )
373
    log( '* BOOTING VM FROM', cow )
374
    log( cmd )
375
    vm = pexpect.spawn( cmd, timeout=TIMEOUT, logfile=logfile )
376
    return vm
377

    
378

    
379
def interact( vm ):
380
    "Interact with vm, which is a pexpect object"
381
    prompt = '\$ '
382
    log( '* Waiting for login prompt' )
383
    vm.expect( 'login: ' )
384
    log( '* Logging in' )
385
    vm.sendline( 'mininet' )
386
    log( '* Waiting for password prompt' )
387
    vm.expect( 'Password: ' )
388
    log( '* Sending password' )
389
    vm.sendline( 'mininet' )
390
    log( '* Waiting for login...' )
391
    vm.expect( prompt )
392
    log( '* Sending hostname command' )
393
    vm.sendline( 'hostname' )
394
    log( '* Waiting for output' )
395
    vm.expect( prompt )
396
    log( '* Fetching Mininet VM install script' )
397
    vm.sendline( 'wget '
398
                 'https://raw.github.com/mininet/mininet/master/util/vm/'
399
                 'install-mininet-vm.sh' )
400
    vm.expect( prompt )
401
    log( '* Running VM install script' )
402
    vm.sendline( 'bash install-mininet-vm.sh' )
403
    vm.expect ( 'password for mininet: ' )
404
    vm.sendline( 'mininet' )
405
    log( '* Waiting for script to complete... ' )
406
    # Gigantic timeout for now ;-(
407
    vm.expect( 'Done preparing Mininet', timeout=3600 )
408
    log( '* Completed successfully' )
409
    vm.expect( prompt )
410
    log( '* Testing Mininet' )
411
    vm.sendline( 'sudo mn --test pingall' )
412
    if vm.expect( [ ' 0% dropped', pexpect.TIMEOUT ], timeout=45 ) == 0:
413
        log( '* Sanity check OK' )
414
    else:
415
        log( '* Sanity check FAILED' )
416
    vm.expect( prompt )
417
    log( '* Making sure cgroups are mounted' )
418
    vm.sendline( 'sudo service cgroup-lite restart' )
419
    vm.expect( prompt )
420
    vm.sendline( 'sudo cgroups-mount' )
421
    vm.expect( prompt )
422
    log( '* Running make test' )
423
    vm.sendline( 'cd ~/mininet; sudo make test' )
424
    # We should change "make test" to report the number of
425
    # successful and failed tests. For now, we have to
426
    # know the time for each test, which means that this
427
    # script will have to change as we add more tests.
428
    for test in range( 0, 2 ):
429
        if vm.expect( [ 'OK', 'FAILED', pexpect.TIMEOUT ], timeout=60 ) == 0:
430
            log( '* Test', test, 'OK' )
431
        else:
432
            log( '* Test', test, 'FAILED' )
433
    vm.expect( prompt )
434
    log( '* Shutting down' )
435
    vm.sendline( 'sync; sudo shutdown -h now' )
436
    log( '* Waiting for EOF/shutdown' )
437
    vm.read()
438
    log( '* Interaction complete' )
439

    
440

    
441
def cleanup():
442
    "Clean up leftover qemu-nbd processes and other junk"
443
    call( [ 'sudo', 'pkill', '-9', 'qemu-nbd' ] )
444

    
445

    
446
def convert( cow, basename ):
447
    """Convert a qcow2 disk to a vmdk and put it a new directory
448
       basename: base name for output vmdk file"""
449
    vmdk = basename + '.vmdk'
450
    log( '* Converting qcow2 to vmdk' )
451
    run( 'qemu-img convert -f qcow2 -O vmdk %s %s' % ( cow, vmdk ) )
452
    return vmdk
453

    
454

    
455
# Template for virt-image(5) file
456

    
457
VirtImageXML = """
458
<?xml version="1.0" encoding="UTF-8"?>
459
<image>
460
    <name>%s</name>
461
    <domain>
462
        <boot type="hvm">
463
            <guest>
464
                <arch>%s/arch>
465
            </guest>
466
            <os>
467
                <loader dev="hd"/>
468
            </os>
469
            <drive disk="root.raw" target="hda"/>
470
        </boot>
471
        <devices>
472
            <vcpu>1</vcpu>
473
            <memory>%s</memory>
474
            <interface/>
475
            <graphics/>
476
        </devices>
477
    </domain>
478
        <storage>
479
            <disk file="%s" size="%s" format="vmdk"/>
480
        </storage>
481
</image>
482
"""
483

    
484
def genVirtImage( name, mem, diskname, disksize ):
485
    "Generate and return virt-image file name.xml"
486
    # Our strategy is going to be: create a
487
    # virt-image file and then use virt-convert to convert
488
    # it to an .ovf file
489
    xmlfile = name + '.xml'
490
    xmltext = VirtImageXML % ( name, mem, diskname, disksize )
491
    with open( xmlfile, 'w+' ) as f:
492
        f.write( xmltext )
493
    return xmlfile
494

    
495

    
496
def build( flavor='raring32server' ):
497
    "Build a Mininet VM"
498
    start = time()
499
    date = strftime( '%y%m%d-%H-%M-%S', localtime())
500
    dir = 'mn-%s-%s' % ( flavor, date )
501
    try:
502
        os.mkdir( dir )
503
    except:
504
        raise Exception( "Failed to create build directory %s" % dir )
505
    os.chdir( dir )
506
    log( '* Created working directory', dir )
507
    image, kernel, initrd = findBaseImage( flavor )
508
    volume = flavor + '.qcow2'
509
    run( 'qemu-img create -f qcow2 -b %s %s' % ( image, volume ) )
510
    log( '* VM image for', flavor, 'created as', volume )
511
    logfile = open( flavor + '.log', 'w+' )
512
    log( '* Logging results to', abspath( logfile.name ) )
513
    vm = boot( volume, kernel, initrd, logfile )
514
    interact( vm )
515
    vmdk = convert( volume, basename=flavor )
516
    log( '* Removing qcow2 volume', volume )
517
    os.remove( volume )
518
    log( '* Converted VM image stored as', abspath( vmdk ) )
519
    end = time()
520
    elapsed = end - start
521
    log( '* Results logged to', abspath( logfile.name ) )
522
    log( '* Completed in %.2f seconds' % elapsed )
523
    log( '* %s VM build DONE!!!!! :D' % flavor )
524
    os.chdir( '..' )
525

    
526

    
527
def listFlavors():
528
    "List valid build flavors"
529
    print '\nvalid build flavors:', ' '.join( isoURLs ), '\n'
530

    
531

    
532
def parseArgs():
533
    "Parse command line arguments and run"
534
    parser = argparse.ArgumentParser( description='Mininet VM build script' )
535
    parser.add_argument( '--depend', action='store_true',
536
                         help='install dependencies for this script' )
537
    parser.add_argument( '--list', action='store_true',
538
                         help='list valid build flavors' )
539
    parser.add_argument( '--clean', action='store_true',
540
                         help='clean up leftover build junk (e.g. qemu-nbd)' )
541
    parser.add_argument( 'flavor', nargs='*',
542
                         help='VM flavor to build (e.g. raring32server)' )
543
    args = parser.parse_args( argv )
544
    if args.depend:
545
        depend()
546
    if args.list:
547
        listFlavors()
548
    if args.clean:
549
        cleanup()
550
    flavors = args.flavor[ 1: ]
551
    for flavor in flavors:
552
        if flavor not in isoURLs:
553
            parser.print_help()
554
            listFlavors()
555
            break
556
        # try:
557
        build( flavor )
558
        # except Exception as e:
559
        # log( '* BUILD FAILED with exception: ', e )
560
        # exit( 1 )
561
    if not ( args.depend or args.list or args.clean or flavors ):
562
        parser.print_help()
563
        listFlavors()
564

    
565
if __name__ == '__main__':
566
    parseArgs()