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