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