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