codename utopic
[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=f20
25 DEFAULT_PLDISTRO=lxc
26 DEFAULT_PERSONALITY=linux64
27 DEFAULT_MEMORY=512
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     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
169     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
170     found=""
171     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
172         if curl -f $attempt -o $RELEASE_TARGET ; then
173             echo "Retrieved $attempt"
174             found=true
175             break
176         else
177             echo "Failed attempt $attempt"
178         fi
179     done
180     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
181     
182     mkdir -p $INSTALL_ROOT/var/lib/rpm
183     rpm --root $INSTALL_ROOT  --initdb
184     # when installing f12 this apparently is already present, so ignore result
185     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm || :
186     # however f12 root images won't get created on a f18 host
187     # (the issue here is the same as the one we ran into when dealing with a vs-box)
188     # in a nutshell, in f12 the glibc-common and filesystem rpms have an apparent conflict
189     # >>> file /usr/lib/locale from install of glibc-common-2.11.2-3.x86_64 conflicts 
190     #          with file from package filesystem-2.4.30-2.fc12.x86_64
191     # in fact this was - of course - allowed by f12's rpm but later on a fix was made 
192     #   http://rpm.org/gitweb?p=rpm.git;a=commitdiff;h=cf1095648194104a81a58abead05974a5bfa3b9a
193     # So ideally if we want to be able to build f12 images from f18 we need an rpm that has
194     # this patch undone, like we have in place on our f14 boxes (our f14 boxes need a f18-like rpm)
195
196     YUM="yum --installroot=$INSTALL_ROOT --nogpgcheck -y"
197     echo "$YUM install $FEDORA_PREINSTALLED"
198     $YUM install $FEDORA_PREINSTALLED || { echo "Failed to download rootfs, aborting." ; return 1; }
199
200     mv "$INSTALL_ROOT" "$cache/rootfs"
201     echo "Download complete."
202
203     return 0
204 }
205
206 ##############################
207 function fedora_configure() {
208
209     set -x
210     set -e
211
212     # disable selinux in fedora
213     mkdir -p $lxc_root/selinux
214     echo 0 > $lxc_root/selinux/enforce
215
216     # set the hostname
217     case "$fcdistro" in 
218         f18|f2?)
219             cat <<EOF > ${lxc_root}/etc/sysconfig/network
220 NETWORKING=yes
221 EOF
222             cat <<EOF > ${lxc_root}/etc/hostname
223 $GUEST_HOSTNAME
224 EOF
225             echo ;;
226         *)
227             cat <<EOF > ${lxc_root}/etc/sysconfig/network
228 NETWORKING=yes
229 HOSTNAME=$GUEST_HOSTNAME
230 EOF
231             # set minimal hosts
232             cat <<EOF > $lxc_root/etc/hosts
233 127.0.0.1 localhost $GUEST_HOSTNAME
234 EOF
235             echo ;;
236     esac
237
238     dev_path="${lxc_root}/dev"
239     rm -rf $dev_path
240     mkdir -p $dev_path
241     mknod -m 666 ${dev_path}/null c 1 3
242     mknod -m 666 ${dev_path}/zero c 1 5
243     mknod -m 666 ${dev_path}/random c 1 8
244     mknod -m 666 ${dev_path}/urandom c 1 9
245     mkdir -m 755 ${dev_path}/pts
246     mkdir -m 1777 ${dev_path}/shm
247     mknod -m 666 ${dev_path}/tty c 5 0
248     mknod -m 666 ${dev_path}/tty0 c 4 0
249     mknod -m 666 ${dev_path}/tty1 c 4 1
250     mknod -m 666 ${dev_path}/tty2 c 4 2
251     mknod -m 666 ${dev_path}/tty3 c 4 3
252     mknod -m 666 ${dev_path}/tty4 c 4 4
253     mknod -m 600 ${dev_path}/console c 5 1
254     mknod -m 666 ${dev_path}/full c 1 7
255     mknod -m 600 ${dev_path}/initctl p
256     mknod -m 666 ${dev_path}/ptmx c 5 2
257
258     if [ "$(echo $fcdistro | cut -d"f" -f2)" -le "14" ]; then
259         fedora_configure_init
260     else
261         fedora_configure_systemd
262     fi
263
264     guest_ifcfg=${lxc_root}/etc/sysconfig/network-scripts/ifcfg-$VIF_GUEST
265     ( [ -n "$BUILD_MODE" ] && write_guest_ifcfg_build || write_guest_ifcfg_test ) > $guest_ifcfg
266
267     [ -z "$IMAGE" ] && fedora_configure_yum $lxc $fcdistro $pldistro
268
269     return 0
270 }
271
272 function fedora_configure_init() {
273     set -e
274     set -x
275     sed -i 's|.sbin.start_udev||' ${lxc_root}/etc/rc.sysinit
276     sed -i 's|.sbin.start_udev||' ${lxc_root}/etc/rc.d/rc.sysinit
277     # don't mount devpts, for pete's sake
278     sed -i 's/^.*dev.pts.*$/#\0/' ${lxc_root}/etc/rc.sysinit
279     sed -i 's/^.*dev.pts.*$/#\0/' ${lxc_root}/etc/rc.d/rc.sysinit
280     chroot ${lxc_root} $personality chkconfig udev-post off
281     chroot ${lxc_root} $personality chkconfig network on
282 }
283
284 # this code of course is for guests that do run on systemd
285 function fedora_configure_systemd() {
286     set -e
287     set -x
288     # so ignore if we can't find /etc/systemd at all 
289     [ -d ${lxc_root}/etc/systemd ] || return 0
290     # otherwise let's proceed
291     ln -sf /lib/systemd/system/multi-user.target ${lxc_root}/etc/systemd/system/default.target
292     touch ${lxc_root}/etc/fstab
293     ln -sf /dev/null ${lxc_root}/etc/systemd/system/udev.service
294 # Thierry - Feb 2013
295 # this was intended for f16 initially, in order to enable getty that otherwise would not start
296 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
297 # VM's that refuse to lxc-stop and VM's that run crazy getty's
298 # so, turning getty off for now instead
299 #   #dependency on a device unit fails it specially that we disabled udev
300 #    sed -i 's/After=dev-%i.device/After=/' ${lxc_root}/lib/systemd/system/getty\@.service
301     ln -sf /dev/null ${lxc_root}/etc/systemd/system/"getty@.service"
302     rm -f ${lxc_root}/etc/systemd/system/getty.target.wants/*service || :
303 # can't seem to handle this one with systemctl
304     chroot ${lxc_root} $personality chkconfig network on
305 }
306
307 # overwrite container yum config
308 function fedora_configure_yum () {
309     set -x 
310     set -e 
311     trap failure ERR INT
312
313     lxc=$1; shift
314     fcdistro=$1; shift
315     pldistro=$1; shift
316
317     # rpm --rebuilddb
318     chroot ${lxc_root} $personality rpm --rebuilddb
319
320     echo "Initializing yum.repos.d in $lxc"
321     rm -f $lxc_root/etc/yum.repos.d/*
322
323     cat > $lxc_root/etc/yum.repos.d/building.repo <<EOF
324 [fedora]
325 name=Fedora \$releasever - \$basearch
326 baseurl=$FEDORA_MIRROR_BASE/releases/\$releasever/Everything/\$basearch/os/
327 enabled=1
328 metadata_expire=7d
329 gpgcheck=1
330 gpgkey=$FEDORA_MIRROR_KEYS/RPM-GPG-KEY-fedora-$release-primary
331
332 [updates]
333 name=Fedora \$releasever - \$basearch - Updates
334 baseurl=$FEDORA_MIRROR_BASE/updates/\$releasever/\$basearch/
335 enabled=1
336 metadata_expire=7d
337 gpgcheck=1
338 gpgkey=$FEDORA_MIRROR_KEYS/RPM-GPG-KEY-fedora-$release-primary
339 EOF
340
341     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
342     # just mention 'none' as the repo url
343     if [ -n "$REPO_URL" ] ; then
344         if [ ! -d $lxc_root/etc/yum.repos.d ] ; then
345             echo "WARNING : cannot create myplc repo"
346         else
347             # exclude kernel from fedora repos 
348             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
349             for repo in $lxc_root/etc/yum.repos.d/* ; do
350                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
351             done
352             # the build repo is not signed at this stage
353             cat > $lxc_root/etc/yum.repos.d/myplc.repo <<EOF
354 [myplc]
355 name= MyPLC
356 baseurl=$REPO_URL
357 enabled=1
358 gpgcheck=0
359 EOF
360         fi
361     fi
362 }    
363
364 ##############################
365 # need to specify the right mirror for debian variants like ubuntu and the like
366 function debian_mirror () {
367     fcdistro=$1; shift
368     case $fcdistro in
369         squeeze|wheezy|jessie) 
370             echo http://ftp2.fr.debian.org/debian/ ;;
371         oneiric|precise|quantal|raring|saucy|trusty|utopic) 
372             echo http://mir1.ovh.net/ubuntu/ubuntu/ ;;
373         *) echo unknown distro $fcdistro; exit 1;;
374     esac
375 }
376
377 function debian_install () {
378     set -e
379     set -x
380     lxc=$1; shift
381     mkdir -p $lxc_root
382     arch=$(canonical_arch $personality $fcdistro)
383     mirror=$(debian_mirror $fcdistro)
384     debootstrap --arch $arch $fcdistro $lxc_root $mirror
385     # just like with fedora we ensure a few packages get installed as well
386     # not started yet
387     #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get update"
388     #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get -y install $DEBIAN_PREINSTALLED"
389     chroot ${lxc_root} $personality apt-get update
390     chroot ${lxc_root} $personality apt-get -y install $DEBIAN_PREINSTALLED
391     # configure hostname
392     cat <<EOF > ${lxc_root}/etc/hostname
393 $GUEST_HOSTNAME
394 EOF
395     
396 }
397
398 function debian_configure () {
399     guest_interfaces=${lxc_root}/etc/network/interfaces
400     ( [ -n "$BUILD_MODE" ] && write_guest_interfaces_build || write_guest_interfaces_test ) > $guest_interfaces
401 }
402
403 function write_guest_interfaces_build () {
404     cat <<EOF
405 auto $VIF_GUEST
406 iface $VIF_GUEST inet dhcp
407 EOF
408 }
409
410 function write_guest_interfaces_test () {
411     cat <<EOF
412 auto $VIF_GUEST
413 iface $VIF_GUEST inet static
414 address $GUEST_IP
415 netmask $NETMASK
416 gateway $GATEWAY
417 EOF
418 }
419 ##############################
420 function setup_lxc() {
421
422     set -x
423     set -e
424     #trap failure ERR INT
425
426     lxc=$1; shift
427     fcdistro=$1; shift
428     pldistro=$1; shift
429     personality=$1; shift
430
431     # create lxc container 
432     
433     pkg_method=$(package_method $fcdistro)
434     case $pkg_method in
435         yum)
436             if [ -z "$IMAGE" ]; then
437                 fedora_install ||  { echo "failed to install fedora root image"; exit 1 ; }
438             fi
439             fedora_configure || { echo "failed to configure fedora for a container"; exit 1 ; }
440             ;;
441         debootstrap)
442             if [ -z "$IMAGE" ]; then
443                 debian_install $lxc || { echo "failed to install debian/ubuntu root image"; exit 1 ; }
444             fi
445             debian_configure || { echo "failed to configure debian/ubuntu for a container"; exit 1 ; }
446             ;;
447         *)
448             echo "$COMMAND:: unknown package_method - exiting"
449             exit 1
450             ;;
451     esac
452
453     # Enable cgroup -- xxx -- is this really useful ?
454     [ -d $lxc_root/cgroup ] || mkdir $lxc_root/cgroup
455     
456     # set up resolv.conf
457     cp /etc/resolv.conf $lxc_root/etc/resolv.conf
458     # and /etc/hosts for at least localhost
459     [ -f $lxc_root/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $lxc_root/etc/hosts
460     
461     # grant ssh access from host to guest
462     mkdir -p $lxc_root/root/.ssh
463     cat /root/.ssh/id_rsa.pub >> $lxc_root/root/.ssh/authorized_keys
464     chmod 700 $lxc_root/root/.ssh
465     chmod 600 $lxc_root/root/.ssh/authorized_keys
466
467     # don't keep the input xml, this can be retrieved at all times with virsh dumpxml
468     config_xml=/tmp/$lxc.xml
469     ( [ -n "$BUILD_MODE" ] && write_lxc_xml_build $lxc || write_lxc_xml_test $lxc ) > $config_xml
470     
471     # define lxc container for libvirt
472     virsh -c lxc:/// define $config_xml
473
474     return 0
475 }
476
477 function write_lxc_xml_test () {
478     lxc=$1; shift
479     cat <<EOF
480 <domain type='lxc'>
481   <name>$lxc</name>
482   <memory>$MEMORY</memory>
483   <os>
484     <type arch='$arch2'>exe</type>
485     <init>/sbin/init</init>
486   </os>
487   <features>
488     <acpi/>
489   </features>
490   <vcpu>1</vcpu>
491   <clock offset='utc'/>
492   <on_poweroff>destroy</on_poweroff>
493   <on_reboot>restart</on_reboot>
494   <on_crash>destroy</on_crash>
495   <devices>
496     <emulator>/usr/libexec/libvirt_lxc</emulator>
497     <filesystem type='mount'>
498       <source dir='$lxc_root'/>
499       <target dir='/'/>
500     </filesystem>
501     <interface type="bridge">
502       <source bridge="$PUBLIC_BRIDGE"/>
503       <target dev='$VIF_HOST'/>
504     </interface>
505     <console type='pty' />
506   </devices>
507   <network>
508     <name>host-bridge</name>
509     <forward mode="bridge"/>
510     <bridge name="$PUBLIC_BRIDGE"/>
511   </network>
512 </domain>
513 EOF
514 }
515
516 function write_lxc_xml_build () { 
517     lxc=$1; shift
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="network">
541       <source network="default"/>
542     </interface>
543     <console type='pty' />
544   </devices>
545 </domain>
546 EOF
547 }
548
549 # this one is dhcp-based
550 function write_guest_ifcfg_build () {
551     cat <<EOF
552 DEVICE=$VIF_GUEST
553 BOOTPROTO=dhcp
554 ONBOOT=yes
555 NM_CONTROLLED=no
556 TYPE=Ethernet
557 MTU=1500
558 EOF
559 }
560
561 # use fixed GUEST_IP as specified by GUEST_HOSTNAME
562 function write_guest_ifcfg_test () {
563     cat <<EOF
564 DEVICE=$VIF_GUEST
565 BOOTPROTO=static
566 ONBOOT=yes
567 HOSTNAME=$GUEST_HOSTNAME
568 IPADDR=$GUEST_IP
569 NETMASK=$NETMASK
570 GATEWAY=$GATEWAY
571 NM_CONTROLLED=no
572 TYPE=Ethernet
573 MTU=1500
574 EOF
575 }
576
577 function devel_or_vtest_tools () {
578
579     set -x 
580     set -e 
581     trap failure ERR INT
582
583     lxc=$1; shift
584     fcdistro=$1; shift
585     pldistro=$1; shift
586     personality=$1; shift
587
588     pkg_method=$(package_method $fcdistro)
589
590     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $PREINSTALLED)
591
592     ### install individual packages, then groups
593     # get target arch - use uname -i here (we want either x86_64 or i386)
594    
595     lxc_arch=$(chroot ${lxc_root} $personality uname -i)
596     # on debian systems we get arch through the 'arch' command
597     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot ${lxc_root} $personality arch)
598
599     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
600     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
601
602     case "$pkg_method" in
603         yum)
604             [ -n "$packages" ] && chroot ${lxc_root} $personality yum -y install $packages
605             for group_plus in $groups; do
606                 group=$(echo $group_plus | sed -e "s,+++, ,g")
607                 chroot ${lxc_root} $personality yum -y groupinstall "$group"
608             done
609             # store current rpm list in /init-lxc.rpms in case we need to check the contents
610             chroot ${lxc_root} $personality rpm -aq > $lxc_root/init-lxc.rpms
611             ;;
612         debootstrap)
613             # for ubuntu
614             if grep -iq ubuntu /vservers/$lxc/etc/lsb-release 2> /dev/null; then
615                 # on ubuntu, at this point we end up with a single feed in /etc/apt/sources.list
616                 # we need at least to add the 'universe' feed for python-rpm
617                 ( cd /vservers/$lxc/etc/apt ; head -1 sources.list | sed -e s,main,universe, > sources.list.d/universe.list )
618                 # also adding a link to updates sounds about right
619                 ( cd /vservers/$lxc/etc/apt ; head -1 sources.list | sed -e 's, main,-updates main,' > sources.list.d/updates.list )
620                 # tell apt about the changes
621                 chroot /vservers/$lxc apt-get update
622             fi
623             for package in $packages ; do
624                 # container not started yet
625                 #virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "apt-get install -y $package" || :
626                 chroot ${lxc_root} $personality apt-get install -y $package || :
627             done
628             ### xxx todo install groups with apt..
629             ;;
630         *)
631             echo "unknown pkg_method $pkg_method"
632             ;;
633     esac
634
635     return 0
636 }
637
638 function post_install () {
639     lxc=$1; shift 
640     personality=$1; shift
641     # setup localtime from the host
642     cp /etc/localtime $lxc_root/etc/localtime
643     if [ -n "$BUILD_MODE" ] ; then
644         post_install_build $lxc $personality
645         if [ -n "$START_VM" ] ; then
646             virsh -c lxc:/// start $lxc
647             # manually run dhclient in guest - somehow this network won't start on its own
648             virsh -c lxc:/// lxc-enter-namespace $lxc /usr/bin/$personality /bin/bash -c "dhclient $VIF_GUEST"
649         fi
650     else
651         post_install_myplc $lxc $personality
652         if [ -n "$START_VM" ] ; then
653             virsh -c lxc:/// start $lxc
654             # it sounds like we don't need ssh per se any more
655             # it still makes sense to wait for network readiness though
656             # some day maybe...
657             wait_for_ssh $lxc
658         fi
659     fi
660 }
661
662 function post_install_build () {
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 function wait_for_ssh () {
710     set -x
711     set -e
712     #trap failure ERR INT
713
714     lxc=$1; shift
715   
716     echo network in guest is up, waiting for ssh...
717
718     #wait max 2 min for sshd to start 
719     ssh_up=""
720     current_time=$(date +%s)
721     stop_time=$(($current_time + 120))
722     
723     counter=1
724     while [ "$current_time" -lt "$stop_time" ] ; do
725          echo "$counter-th attempt to reach sshd in container $lxc ..."
726          ssh -o "StrictHostKeyChecking no" $GUEST_IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
727          sleep 10
728          current_time=$(($current_time + 10))
729          counter=$(($counter+1))
730     done
731
732     # Thierry: this is fatal, let's just exit with a failure here
733     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
734     return 0
735 }
736
737 ####################
738 function failure () {
739     echo "$COMMAND : Bailing out"
740     exit 1
741 }
742
743 function usage () {
744     set +x 
745     echo "Usage: $COMMAND [options] lxc-name             (aka build mode)"
746     echo "Usage: $COMMAND -n hostname [options] lxc-name (aka test mode)"
747     echo "Description:"
748     echo "    This command creates a fresh lxc instance, for building, or running a test myplc"
749     echo "In its first form, spawned VM gets a private IP bridged with virbr0 over dhcp/nat"
750     echo "With the second form, spawned VM gets a public IP bridged on public bridge br0"
751     echo ""
752     echo "Supported options"
753     echo " -n hostname - the hostname to use in container"
754     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
755     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO - current support for fedoras debians ubuntus"
756     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
757     echo " -r repo-url - used to populate yum.repos.d - required in test mode"
758     echo " -P pkgs_file - defines a set of extra packages to install in guest"
759     echo "    by default we use devel.pkgs (build mode) or runtime.pkgs (test mode)"
760     echo " -i image - the location of the rootfs"
761     echo " -m memory - the amount of allocated memory in MB - defaults to $DEFAULT_MEMORY MB"
762     echo " -s do not start VM"
763     echo " -v be verbose"
764     exit 1
765 }
766
767 ### parse args and 
768 function main () {
769
770     #set -e
771     #trap failure ERR INT
772
773     if [ "$(id -u)" != "0" ]; then
774           echo "This script should be run as 'root'"
775           exit 1
776     fi
777
778     START_VM=true
779     while getopts "n:f:d:p:r:P:i:m:sv" opt ; do
780         case $opt in
781             n) GUEST_HOSTNAME=$OPTARG;;
782             f) fcdistro=$OPTARG;;
783             d) pldistro=$OPTARG;;
784             p) personality=$OPTARG;;
785             r) REPO_URL=$OPTARG;;
786             P) PREINSTALLED=$OPTARG;;
787             i) IMAGE=$OPTARG;;
788             m) MEMORY=$OPTARG;;
789             s) START_VM= ;;
790             v) VERBOSE=true; set -x;;
791             *) usage ;;
792         esac
793     done
794         
795     shift $(($OPTIND - 1))
796
797     # parse fixed arguments
798     [[ -z "$@" ]] && usage
799     lxc=$1 ; shift
800     lxc_root=/vservers/$lxc
801
802     # rainchecks
803     almost_empty $lxc_root || \
804         { echo "container $lxc already exists in $lxc_root - exiting" ; exit 1 ; }
805     virsh -c lxc:/// domuuid $lxc >& /dev/null && \
806         { echo "container $lxc already exists in libvirt - exiting" ; exit 1 ; }
807     mkdir -p $lxc_root
808
809     # if IMAGE, copy the provided rootfs to lxc_root
810     if [ -n "$IMAGE" ] ; then
811         [ ! -d "$IMAGE" ] && \
812         { echo "$IMAGE rootfs folder does not exist - exiting" ; exit 1 ; }
813         rsync -a $IMAGE/ $lxc_root/
814     fi
815
816
817     # check we've exhausted the arguments
818     [[ -n "$@" ]] && usage
819
820     # BUILD_MODE is true unless we specified a hostname
821     [ -n "$GUEST_HOSTNAME" ] || BUILD_MODE=true
822
823     # set default values
824     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
825     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
826     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
827     [ -z "$MEMORY" ] && MEMORY=$DEFAULT_MEMORY
828     
829     # set memory in KB
830     MEMORY=$(($MEMORY * 1024))
831     
832     # the set of preinstalled packages - depends on mode
833     if [ -z "$PREINSTALLED" ] ; then
834         if [ -n "$BUILD_MODE" ] ; then
835             PREINSTALLED=devel.pkgs
836         else
837             PREINSTALLED=runtime.pkgs
838         fi
839     fi
840
841     if [ -n "$BUILD_MODE" ] ; then
842         # we can now set GUEST_HOSTNAME safely
843         [ -z "$GUEST_HOSTNAME" ] && GUEST_HOSTNAME=$(echo $lxc | sed -e 's,\.,-,g')
844     else
845         # as this command can be used in other contexts, not specifying
846         # a repo is considered a warning
847         # use -r none to get rid of this warning
848         if [ "$REPO_URL" == "none" ] ; then
849             REPO_URL=""
850         elif [ -z "$REPO_URL" ] ; then
851             echo "WARNING -- setting up a yum repo is recommended" 
852         fi
853     fi
854
855     ##########
856     release=$(echo $fcdistro | cut -df -f2)
857
858     if [ "$personality" == "linux32" ]; then
859         arch=i386
860         arch2=i686
861     elif [ "$personality" == "linux64" ]; then
862         arch=x86_64
863         arch2=x86_64
864     else
865         echo "Unknown personality: $personality"
866     fi
867
868     # compute networking details for the test mode
869     # (build mode relies entirely on dhcp on the private subnet)
870     if [ -z "$BUILD_MODE" ] ; then
871
872         #create_bridge_if_needed $PUBLIC_BRIDGE
873         lbuild-bridge.sh $PUBLIC_BRIDGE
874
875         GUEST_IP=$(gethostbyname $GUEST_HOSTNAME)
876         # use same NETMASK as bridge interface br0
877         masklen=$(ip addr show $PUBLIC_BRIDGE | grep -v inet6 | grep inet | awk '{print $2;}' | cut -d/ -f2)
878         NETMASK=$(masklen_to_netmask $masklen)
879         GATEWAY=$(ip route show | grep default | awk '{print $3}' | head -1)
880         VIF_HOST="vif$(echo $GUEST_HOSTNAME | cut -d. -f1)"
881     fi
882
883     setup_lxc $lxc $fcdistro $pldistro $personality 
884
885     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
886
887     # container gets started here
888     post_install $lxc $personality
889     
890     echo $COMMAND Done
891
892     exit 0
893 }
894
895 main "$@"