a first attempt at getting rid of lxc-enter-namespace using ssh - and virsh net-dhcp...
[build.git] / lbuild-initvm.sh
1 #!/bin/bash
2 # -*-shell-*-
3
4 # close stdin, as with ubuntu and debian VMs this script tends to hang and wait for input ..
5 0<&-
6
7 #shopt -s huponexit
8
9 COMMAND=$(basename $0)
10 DIRNAME=$(dirname $0)
11 BUILD_DIR=$(pwd)
12
13 # pkgs parsing utilities + lbuild-bridge.sh
14 export PATH=$(dirname $0):$PATH
15
16 # old guests have e.g. mount in /bin but this is no longer part of 
17 # the standard PATH in recent hosts after usrmove, so let's keep it simple
18 export PATH=$PATH:/bin:/sbin
19
20 . build.common
21
22 # XXX fixme : when creating a 32bits VM we need to call linux32 as appropriate...s
23
24 DEFAULT_FCDISTRO=f21
25 DEFAULT_PLDISTRO=lxc
26 DEFAULT_PERSONALITY=linux64
27 DEFAULT_MEMORY=1024
28
29 ##########
30 # constant
31 PUBLIC_BRIDGE=br0
32
33 # the network interface name as seen from the container
34 VIF_GUEST=eth0
35
36 ##########
37 FEDORA_MIRROR_BASE="http://mirror.onelab.eu/fedora/"
38 FEDORA_MIRROR_KEYS="http://mirror.onelab.eu/keys/"
39 FEDORA_PREINSTALLED="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
40 DEBIAN_PREINSTALLED="openssh-server openssh-client"
41
42 ########## networking utilities
43 function gethostbyname () {
44     hostname=$1
45     python -c "import socket; print socket.gethostbyname('"$hostname"')" 2> /dev/null
46 }
47
48 # e.g. 21 -> 255.255.248.0
49 function masklen_to_netmask () {
50     masklen=$1; shift
51     python <<EOF
52 import sys
53 masklen=$masklen
54 if not (masklen>=1 and masklen<=32): 
55   print "Wrong masklen",masklen
56   exit(1)
57 result=[]
58 for i in range(4):
59     if masklen>=8:
60        result.append(8)
61        masklen-=8
62     else:
63        result.append(masklen)
64        masklen=0
65 print ".".join([ str(256-2**(8-i)) for i in result ])
66   
67 EOF
68 }
69
70 ##############################
71 # return yum or debootstrap
72 function package_method () {
73     fcdistro=$1; shift
74     case $fcdistro in
75         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
76         squeeze|wheezy|jessie|oneiric|precise|quantal|raring|saucy|trusty|utopic) echo debootstrap ;;
77         *) echo Unknown distro $fcdistro ;;
78     esac 
79 }
80
81 # return arch from debian distro and personality
82 function canonical_arch () {
83     personality=$1; shift
84     fcdistro=$1; shift
85     case $(package_method $fcdistro) in
86         yum)
87             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
88         debootstrap)
89             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
90         *)
91             echo Unknown-arch-3 ;;
92     esac
93 }
94
95 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
96 function almost_empty () { 
97     dir="$1"; shift ; 
98     # non existing is fine
99     [ ! -d $dir ] && return 0; 
100     # need to have at most one file
101     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
102 }
103
104 ##############################
105 function fedora_install() {
106     set -x
107     set -e
108
109     cache=/var/cache/lxc/fedora/$arch/$release
110     mkdir -p $cache
111     
112     (
113         flock --exclusive --timeout 60 200 || { echo "Cache repository is busy." ; return 1 ; }
114
115         if [ ! -e "$cache/rootfs" ]; then
116             echo "Getting cache download in $cache/rootfs ... "
117             fedora_download $cache || { echo "Failed to download 'fedora base'"; return 1; }
118         else
119             echo "Updating cache $cache/rootfs ..."
120             if ! yum --installroot $cache/rootfs -y --nogpgcheck update ; then
121                 echo "Failed to update 'fedora base', continuing with last known good cache"
122             else
123                 echo "Update finished"
124             fi
125         fi
126
127         echo "Filling $lxc_root from $cache/rootfs ... "
128         rsync -a $cache/rootfs/ $lxc_root/
129         
130         return 0
131
132         ) 200> $cache/lock
133
134     return $?
135 }
136
137 function fedora_download() {
138     set -x
139
140     cache=$1; shift
141
142     # check the mini fedora was not already downloaded
143     INSTALL_ROOT=$cache/partial
144     echo $INSTALL_ROOT
145
146     # download a mini fedora into a cache
147     echo "Downloading fedora minimal ..."
148
149     mkdir -p $INSTALL_ROOT || { echo "Failed to create '$INSTALL_ROOT' directory" ; return 1; }
150
151     mkdir -p $INSTALL_ROOT/etc/yum.repos.d   
152     mkdir -p $INSTALL_ROOT/dev
153     mknod -m 0444 $INSTALL_ROOT/dev/random c 1 8
154     mknod -m 0444 $INSTALL_ROOT/dev/urandom c 1 9
155
156     # copy yum config and repo files
157     cp /etc/yum.conf $INSTALL_ROOT/etc/
158     cp /etc/yum.repos.d/fedora* $INSTALL_ROOT/etc/yum.repos.d/
159
160     # append fedora repo files with desired $release and $basearch
161     for f in $INSTALL_ROOT/etc/yum.repos.d/* ; do
162       sed -i "s/\$basearch/$arch/g; s/\$releasever/$release/g;" $f
163     done 
164
165     MIRROR_URL=$FEDORA_MIRROR_BASE/releases/$release/Everything/$arch/os
166     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
167     # with fedora18 the rpms are scattered by first name
168     # first try the second version of fedora-release first
169     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-2.noarch.rpm"
170     RELEASE_URL3="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
171    
172     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
173     found=""
174     for attempt in $RELEASE_URL1 $RELEASE_URL2 $RELEASE_URL3; do
175         if curl -f $attempt -o $RELEASE_TARGET ; then
176             echo "Retrieved $attempt"
177             found=true
178             break
179         else
180             echo "Failed attempt $attempt"
181         fi
182     done
183     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
184     
185     mkdir -p $INSTALL_ROOT/var/lib/rpm
186     rpm --root $INSTALL_ROOT  --initdb
187     # when installing f12 this apparently is already present, so ignore result
188     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm || :
189     # however f12 root images won't get created on a f18 host
190     # (the issue here is the same as the one we ran into when dealing with a vs-box)
191     # in a nutshell, in f12 the glibc-common and filesystem rpms have an apparent conflict
192     # >>> file /usr/lib/locale from install of glibc-common-2.11.2-3.x86_64 conflicts 
193     #          with file from package filesystem-2.4.30-2.fc12.x86_64
194     # in fact this was - of course - allowed by f12's rpm but later on a fix was made 
195     #   http://rpm.org/gitweb?p=rpm.git;a=commitdiff;h=cf1095648194104a81a58abead05974a5bfa3b9a
196     # So ideally if we want to be able to build f12 images from f18 we need an rpm that has
197     # this patch undone, like we have in place on our f14 boxes (our f14 boxes need a f18-like rpm)
198
199     YUM="yum --installroot=$INSTALL_ROOT --nogpgcheck -y"
200     echo "$YUM install $FEDORA_PREINSTALLED"
201     $YUM install $FEDORA_PREINSTALLED || { echo "Failed to download rootfs, aborting." ; return 1; }
202
203     mv "$INSTALL_ROOT" "$cache/rootfs"
204     echo "Download complete."
205
206     return 0
207 }
208
209 ##############################
210 function fedora_configure() {
211
212     set -x
213     set -e
214
215     # disable selinux in fedora
216     mkdir -p $lxc_root/selinux
217     echo 0 > $lxc_root/selinux/enforce
218
219     # set the hostname
220     case "$fcdistro" in 
221         f18|f2?)
222             cat <<EOF > ${lxc_root}/etc/sysconfig/network
223 NETWORKING=yes
224 EOF
225             cat <<EOF > ${lxc_root}/etc/hostname
226 $GUEST_HOSTNAME
227 EOF
228             echo ;;
229         *)
230             cat <<EOF > ${lxc_root}/etc/sysconfig/network
231 NETWORKING=yes
232 HOSTNAME=$GUEST_HOSTNAME
233 EOF
234             # set minimal hosts
235             cat <<EOF > $lxc_root/etc/hosts
236 127.0.0.1 localhost $GUEST_HOSTNAME
237 EOF
238             echo ;;
239     esac
240
241     dev_path="${lxc_root}/dev"
242     rm -rf $dev_path
243     mkdir -p $dev_path
244     mknod -m 666 ${dev_path}/null c 1 3
245     mknod -m 666 ${dev_path}/zero c 1 5
246     mknod -m 666 ${dev_path}/random c 1 8
247     mknod -m 666 ${dev_path}/urandom c 1 9
248     mkdir -m 755 ${dev_path}/pts
249     mkdir -m 1777 ${dev_path}/shm
250     mknod -m 666 ${dev_path}/tty c 5 0
251     mknod -m 666 ${dev_path}/tty0 c 4 0
252     mknod -m 666 ${dev_path}/tty1 c 4 1
253     mknod -m 666 ${dev_path}/tty2 c 4 2
254     mknod -m 666 ${dev_path}/tty3 c 4 3
255     mknod -m 666 ${dev_path}/tty4 c 4 4
256     mknod -m 600 ${dev_path}/console c 5 1
257     mknod -m 666 ${dev_path}/full c 1 7
258     mknod -m 600 ${dev_path}/initctl p
259     mknod -m 666 ${dev_path}/ptmx c 5 2
260
261     if [ "$(echo $fcdistro | cut -d"f" -f2)" -le "14" ]; then
262         fedora_configure_init
263     else
264         fedora_configure_systemd
265     fi
266
267     guest_ifcfg=${lxc_root}/etc/sysconfig/network-scripts/ifcfg-$VIF_GUEST
268     ( [ -n "$NAT_MODE" ] && write_guest_ifcfg_natip || write_guest_ifcfg_publicip ) > $guest_ifcfg
269
270     [ -z "$IMAGE" ] && fedora_configure_yum $lxc $fcdistro $pldistro
271
272     return 0
273 }
274
275 function fedora_configure_init() {
276     set -e
277     set -x
278     sed -i 's|.sbin.start_udev||' ${lxc_root}/etc/rc.sysinit
279     sed -i 's|.sbin.start_udev||' ${lxc_root}/etc/rc.d/rc.sysinit
280     # don't mount devpts, for pete's sake
281     sed -i 's/^.*dev.pts.*$/#\0/' ${lxc_root}/etc/rc.sysinit
282     sed -i 's/^.*dev.pts.*$/#\0/' ${lxc_root}/etc/rc.d/rc.sysinit
283     chroot ${lxc_root} $personality chkconfig udev-post off
284     chroot ${lxc_root} $personality chkconfig network on
285 }
286
287 # this code of course is for guests that do run on systemd
288 function fedora_configure_systemd() {
289     set -e
290     set -x
291     # so ignore if we can't find /etc/systemd at all 
292     [ -d ${lxc_root}/etc/systemd ] || return 0
293     # otherwise let's proceed
294     ln -sf /lib/systemd/system/multi-user.target ${lxc_root}/etc/systemd/system/default.target
295     touch ${lxc_root}/etc/fstab
296     ln -sf /dev/null ${lxc_root}/etc/systemd/system/udev.service
297 # Thierry - Feb 2013 relying on getty is looking for trouble
298 # so, turning getty off for now instead
299 #    sed -i 's/After=dev-%i.device/After=/' ${lxc_root}/lib/systemd/system/getty\@.service
300     ln -sf /dev/null ${lxc_root}/etc/systemd/system/"getty@.service"
301     rm -f ${lxc_root}/etc/systemd/system/getty.target.wants/*service || :
302 # can't seem to handle this one with systemctl
303     chroot ${lxc_root} $personality chkconfig network on
304 }
305
306 # overwrite container yum config
307 function fedora_configure_yum () {
308     set -x 
309     set -e 
310     trap failure ERR INT
311
312     lxc=$1; shift
313     fcdistro=$1; shift
314     pldistro=$1; shift
315
316     # rpm --rebuilddb
317     chroot ${lxc_root} $personality rpm --rebuilddb
318
319     echo "Initializing yum.repos.d in $lxc"
320     rm -f $lxc_root/etc/yum.repos.d/*
321
322     cat > $lxc_root/etc/yum.repos.d/building.repo <<EOF
323 [fedora]
324 name=Fedora \$releasever - \$basearch
325 baseurl=$FEDORA_MIRROR_BASE/releases/\$releasever/Everything/\$basearch/os/
326 enabled=1
327 metadata_expire=7d
328 gpgcheck=1
329 gpgkey=$FEDORA_MIRROR_KEYS/RPM-GPG-KEY-fedora-$release-primary
330
331 [updates]
332 name=Fedora \$releasever - \$basearch - Updates
333 baseurl=$FEDORA_MIRROR_BASE/updates/\$releasever/\$basearch/
334 enabled=1
335 metadata_expire=7d
336 gpgcheck=1
337 gpgkey=$FEDORA_MIRROR_KEYS/RPM-GPG-KEY-fedora-$release-primary
338 EOF
339
340     # for using this script as a general-purpose lxc creation wrapper
341     # just mention 'none' as the repo url
342     if [ -n "$REPO_URL" ] ; then
343         if [ ! -d $lxc_root/etc/yum.repos.d ] ; then
344             echo "WARNING : cannot create myplc repo"
345         else
346             # exclude kernel from fedora repos 
347             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
348             for repo in $lxc_root/etc/yum.repos.d/* ; do
349                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
350             done
351             # the build repo is not signed at this stage
352             cat > $lxc_root/etc/yum.repos.d/myplc.repo <<EOF
353 [myplc]
354 name= MyPLC
355 baseurl=$REPO_URL
356 enabled=1
357 gpgcheck=0
358 EOF
359         fi
360     fi
361 }    
362
363 ##############################
364 # need to specify the right mirror for debian variants like ubuntu and the like
365 function debian_mirror () {
366     fcdistro=$1; shift
367     case $fcdistro in
368         squeeze|wheezy|jessie) 
369             echo http://ftp2.fr.debian.org/debian/ ;;
370         oneiric|precise|quantal|raring|saucy|trusty|utopic) 
371             echo http://mir1.ovh.net/ubuntu/ubuntu/ ;;
372         *) echo unknown distro $fcdistro; exit 1;;
373     esac
374 }
375
376 function debian_install () {
377     set -e
378     set -x
379     lxc=$1; shift
380     mkdir -p $lxc_root
381     arch=$(canonical_arch $personality $fcdistro)
382     mirror=$(debian_mirror $fcdistro)
383     debootstrap --arch $arch $fcdistro $lxc_root $mirror
384     # just like with fedora we ensure a few packages get installed as well
385     # not started yet
386     #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get update"
387     #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get -y install $DEBIAN_PREINSTALLED"
388     chroot ${lxc_root} $personality apt-get update
389     chroot ${lxc_root} $personality apt-get -y install $DEBIAN_PREINSTALLED
390     # configure hostname
391     cat <<EOF > ${lxc_root}/etc/hostname
392 $GUEST_HOSTNAME
393 EOF
394     
395 }
396
397 function debian_configure () {
398     guest_interfaces=${lxc_root}/etc/network/interfaces
399     ( [ -n "$NAT_MODE" ] && write_guest_interfaces_natip || write_guest_interfaces_publicip ) > $guest_interfaces
400 }
401
402 function write_guest_interfaces_natip () {
403     cat <<EOF
404 auto $VIF_GUEST
405 iface $VIF_GUEST inet dhcp
406 EOF
407 }
408
409 function write_guest_interfaces_publicip () {
410     cat <<EOF
411 auto $VIF_GUEST
412 iface $VIF_GUEST inet static
413 address $GUEST_IP
414 netmask $NETMASK
415 gateway $GATEWAY
416 EOF
417 }
418 ##############################
419 function setup_lxc() {
420
421     set -x
422     set -e
423     #trap failure ERR INT
424
425     lxc=$1; shift
426     fcdistro=$1; shift
427     pldistro=$1; shift
428     personality=$1; shift
429
430     # create lxc container 
431     
432     pkg_method=$(package_method $fcdistro)
433     case $pkg_method in
434         yum)
435             if [ -z "$IMAGE" ]; then
436                 fedora_install ||  { echo "failed to install fedora root image"; exit 1 ; }
437             fi
438             fedora_configure || { echo "failed to configure fedora for a container"; exit 1 ; }
439             ;;
440         debootstrap)
441             if [ -z "$IMAGE" ]; then
442                 debian_install $lxc || { echo "failed to install debian/ubuntu root image"; exit 1 ; }
443             fi
444             debian_configure || { echo "failed to configure debian/ubuntu for a container"; exit 1 ; }
445             ;;
446         *)
447             echo "$COMMAND:: unknown package_method - exiting"
448             exit 1
449             ;;
450     esac
451
452     # Enable cgroup -- xxx -- is this really useful ?
453     [ -d $lxc_root/cgroup ] || mkdir $lxc_root/cgroup
454     
455     ### set up resolv.conf from host
456     # ubuntu precise and on, /etc/resolv.conf is a symlink to ../run/resolvconf/resolv.conf
457     [ -h $lxc_root/etc/resolv.conf ] && rm -f $lxc_root/etc/resolv.conf
458     cp /etc/resolv.conf $lxc_root/etc/resolv.conf
459     ### and /etc/hosts for at least localhost
460     [ -f $lxc_root/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $lxc_root/etc/hosts
461     
462     # grant ssh access from host to guest
463     mkdir -p $lxc_root/root/.ssh
464     cat /root/.ssh/id_rsa.pub >> $lxc_root/root/.ssh/authorized_keys
465     chmod 700 $lxc_root/root/.ssh
466     chmod 600 $lxc_root/root/.ssh/authorized_keys
467
468     # don't keep the input xml, this can be retrieved at all times with virsh dumpxml
469     config_xml=/tmp/$lxc.xml
470     ( [ -n "$NAT_MODE" ] && write_lxc_xml_natip $lxc || write_lxc_xml_publicip $lxc ) > $config_xml
471     
472     # define lxc container for libvirt
473     virsh -c lxc:/// define $config_xml
474
475     return 0
476 }
477
478 # this part does not belong in a domain any more
479 # but goes in a network object of its own existence
480 #      <network>
481 #        <name>host-bridge</name>
482 #        <forward mode="bridge"/>
483 #        <bridge name="br0"/>
484 #      </network>
485 #
486
487 function write_lxc_xml_publicip () {
488     lxc=$1; shift
489     cat <<EOF
490 <domain type='lxc'>
491   <name>$lxc</name>
492   <memory>$MEMORY</memory>
493   <os>
494     <type arch='$arch2'>exe</type>
495     <init>/sbin/init</init>
496   </os>
497   <features>
498     <acpi/>
499   </features>
500   <vcpu>1</vcpu>
501   <clock offset='utc'/>
502   <on_poweroff>destroy</on_poweroff>
503   <on_reboot>restart</on_reboot>
504   <on_crash>destroy</on_crash>
505   <devices>
506     <emulator>/usr/libexec/libvirt_lxc</emulator>
507     <filesystem type='mount'>
508       <source dir='$lxc_root'/>
509       <target dir='/'/>
510     </filesystem>
511     <interface type="bridge">
512       <source bridge="$PUBLIC_BRIDGE"/>
513       <target dev='$VIF_HOST'/>
514     </interface>
515     <console type='pty' />
516   </devices>
517 </domain>
518 EOF
519 }
520
521 function write_lxc_xml_natip () { 
522     lxc=$1; shift
523     cat <<EOF
524 <domain type='lxc'>
525   <name>$lxc</name>
526   <memory>$MEMORY</memory>
527   <os>
528     <type arch='$arch2'>exe</type>
529     <init>/sbin/init</init>
530   </os>
531   <features>
532     <acpi/>
533   </features>
534   <vcpu>1</vcpu>
535   <clock offset='utc'/>
536   <on_poweroff>destroy</on_poweroff>
537   <on_reboot>restart</on_reboot>
538   <on_crash>destroy</on_crash>
539   <devices>
540     <emulator>/usr/libexec/libvirt_lxc</emulator>
541     <filesystem type='mount'>
542       <source dir='$lxc_root'/>
543       <target dir='/'/>
544     </filesystem>
545     <interface type="network">
546       <source network="default"/>
547     </interface>
548     <console type='pty' />
549   </devices>
550 </domain>
551 EOF
552 }
553
554 # this one is dhcp-based
555 function write_guest_ifcfg_natip () {
556     cat <<EOF
557 DEVICE=$VIF_GUEST
558 BOOTPROTO=dhcp
559 ONBOOT=yes
560 NM_CONTROLLED=no
561 TYPE=Ethernet
562 MTU=1500
563 EOF
564 }
565
566 # use fixed GUEST_IP as specified by GUEST_HOSTNAME
567 function write_guest_ifcfg_publicip () {
568     cat <<EOF
569 DEVICE=$VIF_GUEST
570 BOOTPROTO=static
571 ONBOOT=yes
572 HOSTNAME=$GUEST_HOSTNAME
573 IPADDR=$GUEST_IP
574 NETMASK=$NETMASK
575 GATEWAY=$GATEWAY
576 NM_CONTROLLED=no
577 TYPE=Ethernet
578 MTU=1500
579 EOF
580 }
581
582 function devel_or_test_tools () {
583
584     set -x 
585     set -e 
586     trap failure ERR INT
587
588     lxc=$1; shift
589     fcdistro=$1; shift
590     pldistro=$1; shift
591     personality=$1; shift
592
593     pkg_method=$(package_method $fcdistro)
594
595     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $PREINSTALLED)
596
597     ### install individual packages, then groups
598     # get target arch - use uname -i here (we want either x86_64 or i386)
599    
600     lxc_arch=$(chroot ${lxc_root} $personality uname -i)
601     # on debian systems we get arch through the 'arch' command
602     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot ${lxc_root} $personality arch)
603
604     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
605     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
606
607     case "$pkg_method" in
608         yum)
609             [ -n "$packages" ] && chroot ${lxc_root} $personality yum -y install $packages
610             for group_plus in $groups; do
611                 group=$(echo $group_plus | sed -e "s,+++, ,g")
612                 chroot ${lxc_root} $personality yum -y groupinstall "$group"
613             done
614             # store current rpm list in /init-lxc.rpms in case we need to check the contents
615             chroot ${lxc_root} $personality rpm -aq > $lxc_root/init-lxc.rpms
616             ;;
617         debootstrap)
618             # for ubuntu
619             if grep -iq ubuntu /vservers/$lxc/etc/lsb-release 2> /dev/null; then
620                 # on ubuntu, at this point we end up with a single feed in /etc/apt/sources.list
621                 # we need at least to add the 'universe' feed for python-rpm
622                 ( cd /vservers/$lxc/etc/apt ; head -1 sources.list | sed -e s,main,universe, > sources.list.d/universe.list )
623                 # also adding a link to updates sounds about right
624                 ( cd /vservers/$lxc/etc/apt ; head -1 sources.list | sed -e 's, main,-updates main,' > sources.list.d/updates.list )
625                 # tell apt about the changes
626                 chroot /vservers/$lxc apt-get update
627             fi
628             for package in $packages ; do
629                 # container not started yet
630                 #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get install -y $package" || :
631                 chroot ${lxc_root} $personality apt-get install -y $package || :
632             done
633             ### xxx todo install groups with apt..
634             ;;
635         *)
636             echo "unknown pkg_method $pkg_method"
637             ;;
638     esac
639
640     return 0
641 }
642
643 function post_install () {
644     lxc=$1; shift 
645     personality=$1; shift
646     # setup localtime from the host
647     cp /etc/localtime $lxc_root/etc/localtime
648     # post install hook
649     [ -n "$NAT_MODE" ] && post_install_natip $lxc $personality || post_install_myplc $lxc $personality
650     # start the VM unless specified otherwise
651     if [ -n "$START_VM" ] ; then
652         echo Starting guest $lxc
653         virsh -c lxc:/// start $lxc
654         if [ -n "$NAT_MODE" ] ; then
655             wait_for_ssh $lxc
656         else
657             wait_for_ssh $lxc $GUEST_IP
658         fi
659     fi
660 }
661
662 function post_install_natip () {
663
664     set -x 
665     set -e 
666     trap failure ERR INT
667
668     lxc=$1; shift
669     personality=$1; shift
670
671 ### From myplc-devel-native.spec
672 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
673     cat << EOF | chroot ${lxc_root} $personality bash -x
674     
675     # customize root's prompt
676     /bin/cat << PROFILE > /root/.profile
677 export PS1="[$lxc] \\w # "
678 PROFILE
679
680 EOF
681         
682 }
683
684 function post_install_myplc  () {
685     set -x 
686     set -e 
687     trap failure ERR INT
688
689     lxc=$1; shift
690     personality=$1; shift
691
692 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
693     cat << EOF | chroot ${lxc_root} $personality bash -x
694
695     # create /etc/sysconfig/network if missing
696     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
697
698     # turn off regular crond, as plc invokes plc_crond
699     /sbin/chkconfig crond off
700
701     # customize root's prompt
702     /bin/cat << PROFILE > /root/.profile
703 export PS1="[$lxc] \\w # "
704 PROFILE
705
706 EOF
707 }
708
709 # workaround for broken lxc-enter-namespace
710 # relies on virsh net-dhcp-leases
711 # when successful we store result in /vservers/<container>/ipv4
712 # because the lease expires afer a while 
713 function guest_ipv4_cached_or_from_virsh_leases() {
714     lxc=$1; shift
715     network=default
716     
717     # place to cache result
718     cache=/vservers/$lxc/ipv4
719     ipv4=$(cat $cache 2> /dev/null)
720     [ -z "$ipv4" ] && ipv4=$(virsh net-dhcp-leases $network | sed -e 's,  *, ,g' | grep " $lxc " | grep ipv4 |  cut -d' ' -f6 | cut -d/ -f1)
721     echo $ipv4
722     # cache if needed
723     [ -n "$ipv4" -a ! -f $cache ] && echo $ipv4 > $cache
724     # always return 0
725     return 0
726 }
727
728 function wait_for_ssh () {
729     set -x
730     set -e
731
732     lxc=$1; shift
733
734     # if run in public_ip mode, we know the IP of the guest and it is specified here
735     guest_ip=$1; shift
736
737     #wait max 2 min for sshd to start 
738     success=""
739     current_time=$(date +%s)
740     stop_time=$(($current_time + 120))
741     
742     counter=1
743     while [ "$current_time" -lt "$stop_time" ] ; do
744          echo "$counter-th attempt to reach sshd in container $lxc ..."
745          [ -z "$guest_ip" ] && guest_ip=$(guest_ipv4_cached_or_from_virsh_leases $lxc)
746          [ -n "$guest_ip" ] && ssh -o "StrictHostKeyChecking no" $guest_ip 'uname -i' && { 
747                  success=true; echo "SSHD in container $lxc is UP on IP $guest_ip"; break ; } || :
748          counter=$(($counter+1))
749          sleep 10
750          current_time=$(date +%s)
751     done
752
753     # Thierry: this is fatal, let's just exit with a failure here
754     [ -z $success ] && { echo "SSHD in container $lxc could not be reached (guest_ip=$guest_ip)" ; exit 1 ; } 
755     return 0
756 }
757
758 ####################
759 function failure () {
760     echo "$COMMAND : Bailing out"
761     exit 1
762 }
763
764 function usage () {
765     set +x 
766     echo "Usage: $COMMAND [options] lxc-name             (aka build mode)"
767     echo "Usage: $COMMAND -n hostname [options] lxc-name (aka test mode)"
768     echo "Description:"
769     echo "    This command creates a fresh lxc instance, for building, or running a test myplc"
770     echo "In its first form, spawned VM gets a private IP bridged with virbr0 over dhcp/nat"
771     echo "With the second form, spawned VM gets a public IP bridged on public bridge br0"
772     echo ""
773     echo "Supported options"
774     echo " -n hostname - the hostname to use in container"
775     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
776     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO - current support for fedoras debians ubuntus"
777     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
778     echo " -r repo-url - used to populate yum.repos.d - required in test mode"
779     echo " -P pkgs_file - defines a set of extra packages to install in guest"
780     echo "    by default we use devel.pkgs (build mode) or runtime.pkgs (test mode)"
781     echo " -i image - the location of the rootfs"
782     echo " -m memory - the amount of allocated memory in MB - defaults to $DEFAULT_MEMORY MB"
783     echo " -s do not start VM"
784     echo " -v be verbose"
785     exit 1
786 }
787
788 ### parse args and 
789 function main () {
790
791     #set -e
792     #trap failure ERR INT
793
794     if [ "$(id -u)" != "0" ]; then
795           echo "This script should be run as 'root'"
796           exit 1
797     fi
798
799     START_VM=true
800     while getopts "n:f:d:p:r:P:i:m:sv" opt ; do
801         case $opt in
802             n) GUEST_HOSTNAME=$OPTARG;;
803             f) fcdistro=$OPTARG;;
804             d) pldistro=$OPTARG;;
805             p) personality=$OPTARG;;
806             r) REPO_URL=$OPTARG;;
807             P) PREINSTALLED=$OPTARG;;
808             i) IMAGE=$OPTARG;;
809             m) MEMORY=$OPTARG;;
810             s) START_VM= ;;
811             v) VERBOSE=true; set -x;;
812             *) usage ;;
813         esac
814     done
815         
816     shift $(($OPTIND - 1))
817
818     # parse fixed arguments
819     [[ -z "$@" ]] && usage
820     lxc=$1 ; shift
821     lxc_root=/vservers/$lxc
822
823     # rainchecks
824     almost_empty $lxc_root || \
825         { echo "container $lxc already exists in $lxc_root - exiting" ; exit 1 ; }
826     virsh -c lxc:/// domuuid $lxc >& /dev/null && \
827         { echo "container $lxc already exists in libvirt - exiting" ; exit 1 ; }
828     mkdir -p $lxc_root
829
830     # if IMAGE, copy the provided rootfs to lxc_root
831     if [ -n "$IMAGE" ] ; then
832         [ ! -d "$IMAGE" ] && \
833         { echo "$IMAGE rootfs folder does not exist - exiting" ; exit 1 ; }
834         rsync -a $IMAGE/ $lxc_root/
835     fi
836
837
838     # check we've exhausted the arguments
839     [[ -n "$@" ]] && usage
840
841     # NAT_MODE is true unless we specified a hostname
842     [ -n "$GUEST_HOSTNAME" ] || NAT_MODE=true
843
844     # set default values
845     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
846     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
847     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
848     [ -z "$MEMORY" ] && MEMORY=$DEFAULT_MEMORY
849     
850     # set memory in KB
851     MEMORY=$(($MEMORY * 1024))
852     
853     # the set of preinstalled packages - depends on mode
854     if [ -z "$PREINSTALLED" ] ; then
855         if [ -n "$NAT_MODE" ] ; then
856             PREINSTALLED=devel.pkgs
857         else
858             PREINSTALLED=runtime.pkgs
859         fi
860     fi
861
862     if [ -n "$NAT_MODE" ] ; then
863         # we can now set GUEST_HOSTNAME safely
864         [ -z "$GUEST_HOSTNAME" ] && GUEST_HOSTNAME=$(echo $lxc | sed -e 's,\.,-,g')
865     else
866         # as this command can be used in other contexts, not specifying
867         # a repo is considered a warning
868         # use -r none to get rid of this warning
869         if [ "$REPO_URL" == "none" ] ; then
870             REPO_URL=""
871         elif [ -z "$REPO_URL" ] ; then
872             echo "WARNING -- setting up a yum repo is recommended" 
873         fi
874     fi
875
876     ##########
877     release=$(echo $fcdistro | cut -df -f2)
878
879     if [ "$personality" == "linux32" ]; then
880         arch=i386
881         arch2=i686
882     elif [ "$personality" == "linux64" ]; then
883         arch=x86_64
884         arch2=x86_64
885     else
886         echo "Unknown personality: $personality"
887     fi
888
889     # compute networking details for the test mode
890     # (build mode relies entirely on dhcp on the private subnet)
891     if [ -z "$NAT_MODE" ] ; then
892
893         #create_bridge_if_needed $PUBLIC_BRIDGE
894         lbuild-bridge.sh $PUBLIC_BRIDGE
895
896         GUEST_IP=$(gethostbyname $GUEST_HOSTNAME)
897         # use same NETMASK as bridge interface br0
898         masklen=$(ip addr show $PUBLIC_BRIDGE | grep -v inet6 | grep inet | awk '{print $2;}' | cut -d/ -f2)
899         NETMASK=$(masklen_to_netmask $masklen)
900         GATEWAY=$(ip route show | grep default | awk '{print $3}' | head -1)
901         VIF_HOST="vif$(echo $GUEST_HOSTNAME | cut -d. -f1)"
902     fi
903
904     setup_lxc $lxc $fcdistro $pldistro $personality 
905
906     # historically this command is for setting up a build or a test VM
907     # kind of patchy right now though
908     devel_or_test_tools $lxc $fcdistro $pldistro $personality
909
910     # container gets started here
911     post_install $lxc $personality
912     
913     echo $COMMAND Done
914
915     exit 0
916 }
917
918 main "$@"