Statistics
| Branch: | Tag: | Revision:

mininet / util / vm / build.py @ 28165f7b

History | View | Annotate | Download (16.2 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-server-i386.iso',
51
    'precise64server':
52
    'http://mirrors.kernel.org/ubuntu-releases/12.04/'
53
    'ubuntu-12.04-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
        # Write-protect iso, signaling it is complete
129
        log( '* Write-protecting iso', iso)
130
        os.chmod( iso, 0444 )
131
    log( '* Using iso', iso )
132
    return iso
133

    
134

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

    
152

    
153
def detachNBD( nbd ):
154
    "Detatch an nbd device"
155
    srun( 'qemu-nbd -d ' + nbd )
156

    
157

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

    
183

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

    
207

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

    
220
KickstartText ="""
221
#Generated by Kickstart Configurator
222
#platform=x86
223

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

    
260
# Tell the Ubuntu/Debian installer to stop asking stupid questions
261

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

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

    
292

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

    
305

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

    
348

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

    
376

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

    
438

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

    
443

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

    
452

    
453
def build( flavor='raring32server' ):
454
    "Build a Mininet VM"
455
    start = time()
456
    date = strftime( '%y%m%d-%H-%M-%S', localtime())
457
    dir = 'mn-%s-%s' % ( flavor, date )
458
    try:
459
        os.mkdir( dir )
460
    except:
461
        raise Exception( "Failed to create build directory %s" % dir )
462
    os.chdir( dir )
463
    log( '* Created working directory', dir )
464
    image, kernel, initrd = findBaseImage( flavor )
465
    volume = flavor + '.qcow2'
466
    run( 'qemu-img create -f qcow2 -b %s %s' % ( image, volume ) )
467
    log( '* VM image for', flavor, 'created as', volume )
468
    logfile = open( flavor + '.log', 'w+' )
469
    log( '* Logging results to', abspath( logfile.name ) )
470
    vm = boot( volume, kernel, initrd, logfile )
471
    interact( vm )
472
    vmdk = convert( volume, basename=flavor )
473
    log( '* Converted VM image stored as', abspath( vmdk ) )
474
    end = time()
475
    elapsed = end - start
476
    log( '* Results logged to', abspath( logfile.name ) )
477
    log( '* Completed in %.2f seconds' % elapsed )
478
    log( '* %s VM build DONE!!!!! :D' % flavor )
479
    os.chdir( '..' )
480

    
481

    
482
def listFlavors():
483
    "List valid build flavors"
484
    print '\nvalid build flavors:', ' '.join( isoURLs ), '\n'
485

    
486

    
487
def parseArgs():
488
    "Parse command line arguments and run"
489
    parser = argparse.ArgumentParser( description='Mininet VM build script' )
490
    parser.add_argument( '--depend', action='store_true',
491
                         help='install dependencies for this script' )
492
    parser.add_argument( '--list', action='store_true',
493
                         help='list valid build flavors' )
494
    parser.add_argument( '--clean', action='store_true',
495
                         help='clean up leftover build junk (e.g. qemu-nbd)' )
496
    parser.add_argument( 'flavor', nargs='*',
497
                         help='VM flavor to build (e.g. raring32server)' )
498
    args = parser.parse_args( argv )
499
    if args.depend:
500
        depend()
501
    if args.list:
502
        listFlavors()
503
    if args.clean:
504
        cleanup()
505
    flavors = args.flavor[ 1: ]
506
    for flavor in flavors:
507
        if flavor not in isoURLs:
508
            parser.print_help()
509
            listFlavors()
510
            break
511
        # try:
512
        build( flavor )
513
        # except Exception as e:
514
        # log( '* BUILD FAILED with exception: ', e )
515
        # exit( 1 )
516
    if not ( args.depend or args.list or args.clean or flavors ):
517
        parser.print_help()
518
        listFlavors()
519

    
520
if __name__ == '__main__':
521
    parseArgs()