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