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