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