502c8a0a7bedd81fa5b6df3c591681ef13db047e
[build.git] / lbuild-initvm.sh
1 #!/bin/bash
2 # -*-shell-*-
3
4 #shopt -s huponexit
5
6 COMMAND=$(basename $0)
7 DIRNAME=$(dirname $0)
8 BUILD_DIR=$(pwd)
9
10 # pkgs parsing utilities
11 PATH=$(dirname $0):$PATH export PATH
12 . build.common
13
14 DEFAULT_FCDISTRO=f20
15 DEFAULT_PLDISTRO=lxc
16 DEFAULT_PERSONALITY=linux64
17
18 COMMAND_LBUILD="lbuild-initvm.sh"
19 COMMAND_LTEST="ltest-initvm.sh"
20
21 ##########
22 # when creating build boxes we use private NAT'ed addresses for the VMs
23 # as per virbr0 that is taken care of by libvirt at startup
24 PRIVATE_BRIDGE="virbr0"
25 PRIVATE_PREFIX="192.168.122."
26 PRIVATE_GATEWAY="192.168.122.1"
27 # beware that changing this would break the logic of random_private_byte...
28 PRIVATE_MASKLEN=24
29
30 # we just try randomly in that range until a free IP address shows up
31 PRIVATE_ATTEMPTS=20
32
33 # constant
34 PUBLIC_BRIDGE=br0
35
36 # the network interface name as seen from the container
37 VIF_GUEST=eth0
38
39 ##############################
40 ## stolen from tests/system/template-qemu/qemu-bridge-init
41 # use /proc/net/dev instead of a hard-wired list
42 function gather_interfaces () {
43     python <<EOF
44 for line in file("/proc/net/dev"):
45     if ':' not in line: continue
46     ifname=line.replace(" ","").split(":")[0]
47     if ifname.find("lo")==0: continue
48     if ifname.find("br")==0: continue
49     if ifname.find("virbr")==0: continue
50     if ifname.find("tap")==0: continue
51     print ifname
52 EOF
53 }
54
55 function discover_interface () {
56     for ifname in $(gather_interfaces); do
57         ip link show $ifname | grep -qi 'state UP' && { echo $ifname; return; }
58     done
59     # still not found ? that's bad
60     echo unknown
61 }
62 ########## check for a free IP
63 function ip_is_busy () {
64     target=$1; shift
65     ping -c 1 -W 1 $target >& /dev/null
66 }
67
68 function random_private_byte () {
69     for attempt in $(seq $PRIVATE_ATTEMPTS); do
70         byte=$(($RANDOM % 256))
71         if [ "$byte" == 0 -o "$byte" == 1 ] ; then continue; fi
72         ip=${PRIVATE_PREFIX}${byte}
73         ip_is_busy $ip || { echo $byte; return; }
74     done
75     echo "Cannot seem to find a free IP address in range ${PRIVATE_PREFIX}.xx/24 after $PRIVATE_ATTEMPTS attempts - exiting"
76     exit 1
77 }
78
79 ########## networking -- ctd
80 function gethostbyname () {
81     hostname=$1
82     python -c "import socket; print socket.gethostbyname('"$hostname"')" 2> /dev/null
83 }
84
85 # e.g. 21 -> 255.255.248.0
86 function masklen_to_netmask () {
87     masklen=$1; shift
88     python <<EOF
89 import sys
90 masklen=$masklen
91 if not (masklen>=1 and masklen<=32): 
92   print "Wrong masklen",masklen
93   exit(1)
94 result=[]
95 for i in range(4):
96     if masklen>=8:
97        result.append(8)
98        masklen-=8
99     else:
100        result.append(masklen)
101        masklen=0
102 print ".".join([ str(256-2**(8-i)) for i in result ])
103   
104 EOF
105 }
106
107 #################### bridge initialization
108 function create_bridge_if_needed() {
109    
110     # turn on verbosity
111     set -x
112
113     # already created ? - we're done
114     ip addr show $PUBLIC_BRIDGE >& /dev/null && {
115         echo "Bridge already set up - skipping create_bridge_if_needed"
116         return 0
117     }
118
119     # find out the physical interface to bridge onto
120     if_lan=$(discover_interface)
121
122     ip addr show $if_lan &>/dev/null || {
123         echo "Cannot use interface $if_lan - exiting"
124         exit 1
125     }
126
127     #################### bride initialization
128     check_yum_installed bridge-utils
129
130     echo "========== $COMMAND: entering create_bridge - beg"
131     hostname
132     uname -a
133     ip addr show
134     ip route
135     echo "========== $COMMAND: entering create_bridge - end"
136
137     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
138     #
139     # another option would be to accept the all forward packages for
140     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
141     sysctl net.bridge.bridge-nf-call-iptables=0
142     sysctl net.bridge.bridge-nf-call-ip6tables=0
143     sysctl net.bridge.bridge-nf-call-arptables=0
144
145     
146     #Getting host IP/masklen
147     address=$(ip addr show $if_lan | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
148     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $if_lan" ; exit 1 ; }
149
150     broadcast=$(ip addr show $if_lan | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
151     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $if_lan"
152
153     gateway=$(ip route show | grep default | awk '{print $3;}')
154     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
155
156
157     # creating the bridge
158     echo "Creating bridge PUBLIC_BRIDGE=$PUBLIC_BRIDGE"
159     brctl addbr $PUBLIC_BRIDGE
160     brctl addif $PUBLIC_BRIDGE $if_lan
161     echo "Activating promiscuous mode if_lan=$if_lan"
162     ip link set $if_lan up promisc on
163     sleep 2
164     # rely on dhcp to re assign IP.. 
165     echo "Starting dhclient on $PUBLIC_BRIDGE"
166     dhclient $PUBLIC_BRIDGE
167     sleep 1
168
169     #Reconfigure the routing table
170     echo "Configuring gateway=$gateway"
171     ip route add default via $gateway dev $PUBLIC_BRIDGE
172     ip route del default via $gateway dev $if_lan
173     # at this point we have an extra route like e.g.
174     ## ip route show
175     #default via 138.96.112.250 dev br0
176     #138.96.112.0/21 dev em1  proto kernel  scope link  src 138.96.112.57
177     #138.96.112.0/21 dev br0  proto kernel  scope link  src 138.96.112.57
178     #192.168.122.0/24 dev virbr0  proto kernel  scope link  src 192.168.122.1
179     route_dest=$(ip route show | grep -v default | grep "dev $PUBLIC_BRIDGE" | awk '{print $1;}')
180     ip route del $route_dest dev $if_lan
181
182     echo "========== $COMMAND: exiting create_bridge - beg"
183     ip addr show
184     ip route show
185     echo "========== $COMMAND: exiting create_bridge - end"
186
187     # for safety
188     sleep 3
189     return 0
190
191 }
192
193
194 ##############################
195 function check_yum_installed () {
196     package=$1; shift
197     rpm -q $package >& /dev/null || yum -y install $package
198 }
199
200 function check_yumgroup_installed () {
201     group="$1"; shift
202     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
203 }
204
205 ##############################
206
207 function configure_fedora() {
208
209     # disable selinux in fedora
210     mkdir -p $rootfs_path/selinux
211     echo 0 > $rootfs_path/selinux/enforce
212
213     # set the hostname
214     case "$fcdistro" in 
215         f18|f2?)
216             cat <<EOF > ${rootfs_path}/etc/hostname
217 $GUEST_HOSTNAME
218 EOF
219             echo ;;
220         *)
221             cat <<EOF > ${rootfs_path}/etc/sysconfig/network
222 NETWORKING=yes
223 HOSTNAME=$GUEST_HOSTNAME
224 EOF
225             # set minimal hosts
226             cat <<EOF > $rootfs_path/etc/hosts
227 127.0.0.1 localhost $GUEST_HOSTNAME
228 EOF
229             echo ;;
230     esac
231
232     dev_path="${rootfs_path}/dev"
233     rm -rf $dev_path
234     mkdir -p $dev_path
235     mknod -m 666 ${dev_path}/null c 1 3
236     mknod -m 666 ${dev_path}/zero c 1 5
237     mknod -m 666 ${dev_path}/random c 1 8
238     mknod -m 666 ${dev_path}/urandom c 1 9
239     mkdir -m 755 ${dev_path}/pts
240     mkdir -m 1777 ${dev_path}/shm
241     mknod -m 666 ${dev_path}/tty c 5 0
242     mknod -m 666 ${dev_path}/tty0 c 4 0
243     mknod -m 666 ${dev_path}/tty1 c 4 1
244     mknod -m 666 ${dev_path}/tty2 c 4 2
245     mknod -m 666 ${dev_path}/tty3 c 4 3
246     mknod -m 666 ${dev_path}/tty4 c 4 4
247     mknod -m 600 ${dev_path}/console c 5 1
248     mknod -m 666 ${dev_path}/full c 1 7
249     mknod -m 600 ${dev_path}/initctl p
250     mknod -m 666 ${dev_path}/ptmx c 5 2
251
252     #echo "setting root passwd to $root_password"
253     #echo "root:$root_password" | chroot $rootfs_path chpasswd
254
255     return 0
256 }
257
258 function configure_fedora_init() {
259
260     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
261     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
262     # don't mount devpts, for pete's sake
263     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.sysinit
264     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.d/rc.sysinit
265     chroot ${rootfs_path} /sbin/chkconfig udev-post off
266     chroot ${rootfs_path} /sbin/chkconfig network on
267 }
268
269 # this code of course is for guests that do run on systemd
270 function configure_fedora_systemd() {
271     # so ignore if we can't find /etc/systemd at all 
272     [ -d ${rootfs_path}/etc/systemd ] || return 0
273     # otherwise let's proceed
274     ln -sf /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
275     touch ${rootfs_path}/etc/fstab
276     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/udev.service
277 # Thierry - Feb 2013
278 # this was intended for f16 initially, in order to enable getty that otherwise would not start
279 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
280 # VM's that refuse to lxc-stop and VM's that run crazy getty's
281 # so, turning getty off for now instead
282 #   #dependency on a device unit fails it specially that we disabled udev
283 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
284     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
285     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
286 # can't seem to handle this one with systemctl
287     chroot ${rootfs_path} /sbin/chkconfig network on
288 }
289
290 function download_fedora() {
291 set -x
292     # check the mini fedora was not already downloaded
293     INSTALL_ROOT=$cache/partial
294     echo $INSTALL_ROOT
295
296     # download a mini fedora into a cache
297     echo "Downloading fedora minimal ..."
298
299     mkdir -p $INSTALL_ROOT
300     if [ $? -ne 0 ]; then
301         echo "Failed to create '$INSTALL_ROOT' directory"
302         return 1
303     fi
304
305     mkdir -p $INSTALL_ROOT/etc/yum.repos.d   
306     mkdir -p $INSTALL_ROOT/dev
307     mknod -m 0444 $INSTALL_ROOT/dev/random c 1 8
308     mknod -m 0444 $INSTALL_ROOT/dev/urandom c 1 9
309
310     # copy yum config and repo files
311     cp /etc/yum.conf $INSTALL_ROOT/etc/
312     cp /etc/yum.repos.d/fedora* $INSTALL_ROOT/etc/yum.repos.d/
313
314     # append fedora repo files with desired $release and $basearch
315     for f in $INSTALL_ROOT/etc/yum.repos.d/*
316     do
317       sed -i "s/\$basearch/$arch/g; s/\$releasever/$release/g;" $f
318     done 
319
320     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
321     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
322     # with fedora18 the rpms are scattered by first name
323     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
324     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
325     found=""
326     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
327         if curl -f $attempt -o $RELEASE_TARGET ; then
328             echo "Retrieved $attempt"
329             found=true
330             break
331         else
332             echo "Failed attempt $attempt"
333         fi
334     done
335     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
336     
337     mkdir -p $INSTALL_ROOT/var/lib/rpm
338     rpm --root $INSTALL_ROOT  --initdb
339     # when installing f12 this apparently is already present, so ignore result
340     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm || :
341     # however f12 root images won't get created on a f18 host
342     # (the issue here is the same as the one we ran into when dealing with a vs-box)
343     # in a nutshell, in f12 the glibc-common and filesystem rpms have an apparent conflict
344     # >>> file /usr/lib/locale from install of glibc-common-2.11.2-3.x86_64 conflicts 
345     #          with file from package filesystem-2.4.30-2.fc12.x86_64
346     # in fact this was - of course - allowed by f12's rpm but later on a fix was made 
347     #   http://rpm.org/gitweb?p=rpm.git;a=commitdiff;h=cf1095648194104a81a58abead05974a5bfa3b9a
348     # So ideally if we want to be able to build f12 images from f18 we need an rpm that has
349     # this patch undone, like we have in place on our f14 boxes (our f14 boxes need a f18-like rpm)
350
351     YUM="yum --installroot=$INSTALL_ROOT --nogpgcheck -y"
352     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
353     echo "$YUM install $PKG_LIST"
354     $YUM install $PKG_LIST
355
356     if [ $? -ne 0 ]; then
357         echo "Failed to download the rootfs, aborting."
358         return 1
359     fi
360
361     mv "$INSTALL_ROOT" "$cache/rootfs"
362     echo "Download complete."
363
364     return 0
365 }
366
367
368 function copy_fedora() {
369 set -x
370     # make a local copy of the minifedora
371     echo -n "Copying rootfs to $rootfs_path ..."
372     mkdir -p $rootfs_path
373     rsync -a $cache/rootfs/ $rootfs_path/
374     return 0
375 }
376
377
378 function update_fedora() {
379 set -x
380     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
381     $YUM update
382 }
383
384
385 function install_fedora() {
386     set -x
387
388     mkdir -p /var/lock/subsys/
389     (
390         flock -n -x 200
391         if [ $? -ne 0 ]; then
392             echo "Cache repository is busy."
393             return 1
394         fi
395
396         echo "Checking cache download in $cache/rootfs ... "
397         if [ ! -e "$cache/rootfs" ]; then
398             download_fedora
399             if [ $? -ne 0 ]; then
400                 echo "Failed to download 'fedora base'"
401                 return 1
402             fi
403         else
404             echo "Cache found. Updating..."
405             update_fedora
406             if [ $? -ne 0 ]; then
407                 echo "Failed to update 'fedora base', continuing with last known good cache"
408             else
409                 echo "Update finished"
410             fi
411         fi
412
413         echo "Copy $cache/rootfs to $rootfs_path ... "
414         copy_fedora
415         if [ $? -ne 0 ]; then
416             echo "Failed to copy rootfs"
417             return 1
418         fi
419
420         return 0
421
422         ) 200>/var/lock/subsys/lxc
423
424     return $?
425 }
426
427
428 # overwrite lxc's internal yum config
429 function configure_yum_in_lxc () {
430     set -x 
431     set -e 
432     trap failure ERR INT
433
434     lxc=$1; shift
435     fcdistro=$1; shift
436     pldistro=$1; shift
437
438     echo "Initializing yum.repos.d in $lxc"
439     rm -f $rootfs_path/etc/yum.repos.d/*
440
441     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
442 [fedora]
443 name=Fedora $release - $arch
444 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os/
445 enabled=1
446 metadata_expire=7d
447 gpgcheck=1
448 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
449
450 [updates]
451 name=Fedora $release - $arch - Updates
452 baseurl=http://mirror.onelab.eu/fedora/updates/$release/$arch/
453 enabled=1
454 metadata_expire=7d
455 gpgcheck=1
456 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
457 EOF
458     
459     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
460     # just mention 'none' as the repo url
461     if [ -n "$REPO_URL" ] ; then
462         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
463             echo "WARNING : cannot create myplc repo"
464         else
465             # exclude kernel from fedora repos 
466             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
467             for repo in $rootfs_path/etc/yum.repos.d/* ; do
468                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
469             done
470             # the build repo is not signed at this stage
471             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
472 [myplc]
473 name= MyPLC
474 baseurl=$REPO_URL
475 enabled=1
476 gpgcheck=0
477 EOF
478         fi
479     fi
480 }    
481
482 # return yum or debootstrap
483 function package_method () {
484     fcdistro=$1; shift
485     case $fcdistro in
486         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
487         squeeze|wheezy|oneiric|precise|quantal|raring|saucy) echo debootstrap ;;
488         *) echo Unknown distro $fcdistro ;;
489     esac 
490 }
491
492 # return arch from debian distro and personality
493 function canonical_arch () {
494     personality=$1; shift
495     fcdistro=$1; shift
496     case $(package_method $fcdistro) in
497         yum)
498             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
499         debootstrap)
500             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
501         *)
502             echo Unknown-arch-3 ;;
503     esac
504 }
505
506 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
507 function almost_empty () { 
508     dir="$1"; shift ; 
509     # non existing is fine
510     [ ! -d $dir ] && return 0; 
511     # need to have at most one file
512     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
513 }
514
515 function setup_lxc() {
516
517     set -x
518     set -e
519     #trap failure ERR INT
520
521     lxc=$1; shift
522     fcdistro=$1; shift
523     pldistro=$1; shift
524     personality=$1; shift
525
526     # create lxc container 
527     
528     pkg_method=$(package_method $fcdistro)
529     case $pkg_method in
530         yum)
531             install_fedora || { echo "failed to install fedora"; exit 1 ; }
532             configure_fedora || { echo "failed to configure fedora for a container"; exit 1 ; }
533             if [ "$(echo $fcdistro | cut -d"f" -f2)" -le "14" ]; then
534                 configure_fedora_init
535             else
536                 configure_fedora_systemd
537             fi
538             ;;
539         debootstrap)
540             echo "$COMMAND: no support for debootstrap-based systems - yet"
541             exit 1
542             ;;
543         *)
544             echo "$COMMAND:: unknown package_method - exiting"
545             exit 1
546             ;;
547     esac
548
549     # rpm --rebuilddb
550     chroot $rootfs_path /bin/rpm --rebuilddb
551
552     configure_yum_in_lxc $lxc $fcdistro $pldistro
553
554     # Enable cgroup -- xxx -- is this really useful ?
555     mkdir $rootfs_path/cgroup
556     
557     # set up resolv.conf
558     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
559     # and /etc/hosts for at least localhost
560     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
561     
562     # grant ssh access from host to guest
563     mkdir $rootfs_path/root/.ssh
564     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
565     
566     config_xml=$config_path/"lxc.xml"
567     guest_ifcfg=${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$VIF_GUEST
568     if [ -n "$BUILD_MODE" ] ; then
569         write_lxc_xml_build $lxc > $config_xml
570         write_guest_ifcfg_build > $guest_ifcfg
571     else
572         write_lxc_xml_test $lxc > $config_xml
573         write_guest_ifcfg_test > $guest_ifcfg
574     fi
575     
576     # define lxc container for libvirt
577     virsh -c lxc:/// define $config_xml
578
579     return 0
580 }
581
582 function write_lxc_xml_test () {
583     lxc=$1; shift
584     cat <<EOF
585 <domain type='lxc'>
586   <name>$lxc</name>
587   <memory>524288</memory>
588   <os>
589     <type arch='$arch2'>exe</type>
590     <init>/sbin/init</init>
591   </os>
592   <features>
593     <acpi/>
594   </features>
595   <vcpu>1</vcpu>
596   <clock offset='utc'/>
597   <on_poweroff>destroy</on_poweroff>
598   <on_reboot>restart</on_reboot>
599   <on_crash>destroy</on_crash>
600   <devices>
601     <emulator>/usr/libexec/libvirt_lxc</emulator>
602     <filesystem type='mount'>
603       <source dir='$rootfs_path'/>
604       <target dir='/'/>
605     </filesystem>
606     <interface type="bridge">
607       <source bridge="$PUBLIC_BRIDGE"/>
608       <target dev='$VIF_HOST'/>
609     </interface>
610     <console type='pty' />
611   </devices>
612   <network>
613     <name>host-bridge</name>
614     <forward mode="bridge"/>
615     <bridge name="$PUBLIC_BRIDGE"/>
616   </network>
617 </domain>
618 EOF
619 }
620
621 function write_lxc_xml_build () { 
622     lxc=$1; shift
623     cat <<EOF
624 <domain type='lxc'>
625   <name>$lxc</name>
626   <memory>524288</memory>
627   <os>
628     <type arch='$arch2'>exe</type>
629     <init>/sbin/init</init>
630   </os>
631   <features>
632     <acpi/>
633   </features>
634   <vcpu>1</vcpu>
635   <clock offset='utc'/>
636   <on_poweroff>destroy</on_poweroff>
637   <on_reboot>restart</on_reboot>
638   <on_crash>destroy</on_crash>
639   <devices>
640     <emulator>/usr/libexec/libvirt_lxc</emulator>
641     <filesystem type='mount'>
642       <source dir='$rootfs_path'/>
643       <target dir='/'/>
644     </filesystem>
645     <interface type="network">
646       <source network="default"/>
647     </interface>
648     <console type='pty' />
649   </devices>
650 </domain>
651 EOF
652 }
653
654 # this one is dhcp-based
655 function write_guest_ifcfg_build () {
656     cat <<EOF
657 DEVICE=$VIF_GUEST
658 BOOTPROTO=dhcp
659 ONBOOT=yes
660 NM_CONTROLLED=no
661 TYPE=Ethernet
662 MTU=1500
663 EOF
664 }
665
666 # use fixed IP as specified by GUEST_HOSTNAME
667 function write_guest_ifcfg_test () {
668     cat <<EOF
669 DEVICE=$VIF_GUEST
670 BOOTPROTO=static
671 ONBOOT=yes
672 HOSTNAME=$GUEST_HOSTNAME
673 IPADDR=$IP
674 NETMASK=$NETMASK
675 GATEWAY=$GATEWAY
676 NM_CONTROLLED=no
677 TYPE=Ethernet
678 MTU=1500
679 EOF
680 }
681
682 function devel_or_vtest_tools () {
683
684     set -x 
685     set -e 
686     trap failure ERR INT
687
688     lxc=$1; shift
689     fcdistro=$1; shift
690     pldistro=$1; shift
691     personality=$1; shift
692
693     pkg_method=$(package_method $fcdistro)
694
695     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $PREINSTALLED)
696
697     ### install individual packages, then groups
698     # get target arch - use uname -i here (we want either x86_64 or i386)
699    
700     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
701     # on debian systems we get arch through the 'arch' command
702     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
703
704     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
705     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
706
707     case "$pkg_method" in
708         yum)
709             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
710             for group_plus in $groups; do
711                 group=$(echo $group_plus | sed -e "s,+++, ,g")
712                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
713             done
714             # store current rpm list in /init-lxc.rpms in case we need to check the contents
715             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
716             ;;
717         debootstrap)
718             chroot $rootfs_path /usr/bin/apt-get update
719             for package in $packages ; do 
720                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
721             done
722             ### xxx todo install groups with apt..
723             ;;
724         *)
725             echo "unknown pkg_method $pkg_method"
726             ;;
727     esac
728
729     return 0
730 }
731
732 function post_install () {
733     lxc=$1; shift 
734     personality=$1; shift
735     if [ -n "$BUILD_MODE" ] ; then
736         post_install_build $lxc $personality
737         lxc_start $lxc
738         # manually run dhclient in guest - somehow this network won't start on its own
739         virsh -c lxc:/// lxc-enter-namespace $lxc /usr/sbin/dhclient $VIF_GUEST
740     else
741         post_install_myplc $lxc $personality
742         lxc_start $lxc
743         wait_for_ssh $lxc
744     fi
745     # setup localtime from the host
746     cp /etc/localtime $rootfs_path/etc/localtime
747 }
748
749 function post_install_build () {
750
751     set -x 
752     set -e 
753     trap failure ERR INT
754
755     lxc=$1; shift
756     personality=$1; shift
757
758 ### From myplc-devel-native.spec
759 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
760     cat << EOF | chroot $rootfs_path /bin/bash -x
761     # set up /dev/loop* in lxc
762     for i in \$(seq 0 255) ; do
763         /bin/mknod -m 640 /dev/loop\$i b 7 \$i
764     done
765     
766     # create symlink for /dev/fd
767     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
768
769     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
770     /bin/sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
771     if [ -h "/sbin/new-kernel-pkg" ] ; then
772         filename=\$(/bin/readlink -f /sbin/new-kernel-pkg)
773         if [ "\$filename" == "/sbin/true" ] ; then
774                 /bin/echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
775                 /bin/echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
776                 /bin/echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
777                 exit 1
778         fi
779     fi
780     
781     # customize root's prompt
782     /bin/cat << PROFILE > /root/.profile
783 export PS1="[$lxc] \\w # "
784 PROFILE
785
786     uid=2000
787     gid=2000
788     
789     # add a "build" user to the system
790     builduser=\$(grep "^build:" /etc/passwd | wc -l)
791     if [ \$builduser -eq 0 ] ; then
792         groupadd -o -g \$gid build;
793         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
794     fi
795
796 # Allow build user to build certain RPMs as root
797     if [ -f /etc/sudoers ] ; then
798         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
799         if [ \$buildsudo -eq 0 ] ; then
800             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
801         fi
802         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
803     fi
804 #
805 EOF
806         
807 }
808
809 function post_install_myplc  () {
810     set -x 
811     set -e 
812     trap failure ERR INT
813
814     lxc=$1; shift
815     personality=$1; shift
816
817 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
818     cat << EOF | chroot $rootfs_path /bin/bash -x
819
820     # create /etc/sysconfig/network if missing
821     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
822
823     # create symlink for /dev/fd
824     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
825
826     # turn off regular crond, as plc invokes plc_crond
827     /sbin/chkconfig crond off
828
829     # take care of loginuid in /etc/pam.d 
830     /bin/sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
831
832     # customize root's prompt
833     /bin/cat << PROFILE > /root/.profile
834 export PS1="[$lxc] \\w # "
835 PROFILE
836
837 EOF
838 }
839
840 function lxc_start() {
841
842     set -x
843     set -e
844     #trap failure ERR INT
845
846     lxc=$1; shift
847   
848     virsh -c lxc:/// start $lxc
849   
850     return 0
851 }
852
853 function wait_for_ssh () {
854     set -x
855     set -e
856     #trap failure ERR INT
857
858     lxc=$1; shift
859   
860     echo $IP is up, waiting for ssh...
861
862     #wait max 5 min for sshd to start 
863     ssh_up=""
864     stop_time=$(($(date +%s) + 300))
865     current_time=$(date +%s)
866     
867     counter=1
868     while [ "$current_time" -lt "$stop_time" ] ; do
869          echo "$counter-th attempt to reach sshd in container $lxc ..."
870          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
871          sleep 10
872          current_time=$(($current_time + 10))
873          counter=$(($counter+1))
874     done
875
876     # Thierry: this is fatal, let's just exit with a failure here
877     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
878     return 0
879 }
880
881 ####################
882 function failure () {
883     echo "$COMMAND : Bailing out"
884     exit 1
885 }
886
887 function usage () {
888     set +x 
889     echo "Usage: $COMMAND_LBUILD [options] lxc-name"
890     echo "Usage: $COMMAND_LTEST [options] lxc-name"
891     echo "Description:"
892     echo "   This command creates a fresh lxc instance, for building, or running a test myplc"
893     echo "Supported options"
894     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
895     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
896     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
897     echo " -n hostname - the hostname to use in container - required with $COMMAND_LTEST"
898     echo " -r repo-url - used to populate yum.repos.d - required with $COMMAND_LTEST"
899     echo " -P pkgs_file - defines the set of extra pacakges"
900     echo "    by default we use vtest.pkgs or devel.pkgs according to $COMMAND"
901     echo " -v be verbose"
902     exit 1
903 }
904
905 ### parse args and 
906 function main () {
907
908     #set -e
909     #trap failure ERR INT
910
911     if [ "$(id -u)" != "0" ]; then
912           echo "This script should be run as 'root'"
913           exit 1
914     fi
915
916     case "$COMMAND" in
917         $COMMAND_LBUILD)
918             BUILD_MODE=true ;;
919         $COMMAND_LTEST)
920             TEST_MODE=true;;
921         *)
922             usage ;;
923     esac
924
925     echo 'build mode=' $BUILD_MODE 'test mode=' $TEST_MODE
926
927     # the set of preinstalled packages - depends on vbuild or vtest
928     if [ -n "$BUILD_MODE" ] ; then
929         PREINSTALLED=devel.pkgs
930     else
931         PREINSTALLED=vtest.pkgs
932     fi
933     while getopts "f:d:p:n:r:P:v" opt ; do
934         case $opt in
935             f) fcdistro=$OPTARG;;
936             d) pldistro=$OPTARG;;
937             p) personality=$OPTARG;;
938             n) GUEST_HOSTNAME=$OPTARG;;
939             r) REPO_URL=$OPTARG;;
940             P) PREINSTALLED=$OPTARG;;
941             v) VERBOSE=true; set -x;;
942             *) usage ;;
943         esac
944     done
945         
946     shift $(($OPTIND - 1))
947
948     # parse fixed arguments
949     [[ -z "$@" ]] && usage
950     lxc=$1 ; shift
951
952     # check we've exhausted the arguments
953     [[ -n "$@" ]] && usage
954
955     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
956     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
957     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
958     
959     if [ -n "$BUILD_MODE" ] ; then
960         [ -z "$GUEST_HOSTNAME" ] && GUEST_HOSTNAME=$lxc
961     else
962         [[ -z "$GUEST_HOSTNAME" ]] && usage
963         # use -r none to get rid of this warning
964         if [ "$REPO_URL" == "none" ] ; then
965             REPO_URL=""
966         elif [ -z "$REPO_URL" ] ; then
967             echo "WARNING -- setting up a yum repo is recommended" 
968         fi
969     fi
970
971     ##########
972     release=$(echo $fcdistro | cut -df -f2)
973
974     if [ "$personality" == "linux32" ]; then
975         arch=i386
976         arch2=i686
977     elif [ "$personality" == "linux64" ]; then
978         arch=x86_64
979         arch2=x86_64
980     else
981         echo "Unknown personality: $personality"
982     fi
983
984     if [ -n "$BUILD_MODE" ] ; then
985
986         # Bridge IP affectation
987         byte=$(random_private_byte)
988         IP=${PRIVATE_PREFIX}$byte
989         NETMASK=$(masklen_to_netmask $PRIVATE_MASKLEN)
990         GATEWAY=$PRIVATE_GATEWAY
991         VIF_HOST="i$byte"
992     else
993         [[ -z "GUEST_HOSTNAME" ]] && usage
994        
995         create_bridge_if_needed
996
997         IP=$(gethostbyname $GUEST_HOSTNAME)
998         # use same NETMASK as bridge interface br0
999         MASKLEN=$(ip addr show $PUBLIC_BRIDGE | grep -v inet6 | grep inet | awk '{print $2;}' | cut -d/ -f2)
1000         NETMASK=$(masklen_to_netmask $MASKLEN)
1001         GATEWAY=$(ip route show | grep default | awk '{print $3}')
1002         VIF_HOST="i$(echo $GUEST_HOSTNAME | cut -d. -f1)"
1003     fi
1004
1005     echo "the IP address of container $lxc is $IP, host virtual interface is $VIF_HOST"
1006
1007     path=/vservers
1008     [ ! -d $path ] && mkdir $path
1009     rootfs_path=$path/$lxc/rootfs
1010     config_path=$path/$lxc
1011     cache_base=/var/cache/lxc/fedora/$arch
1012     cache=$cache_base/$release
1013     root_password=root
1014     
1015     # check whether the rootfs directory is created to know if the container exists
1016     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
1017     [ -d $rootfs_path ] && \
1018         { echo "container $lxc already exists in filesystem - exiting" ; exit 1 ; }
1019     virsh -c lxc:/// domuuid $lxc >& /dev/null && \
1020         { echo "container $lxc already exists in libvirt - exiting" ; exit 1 ; }
1021
1022     setup_lxc $lxc $fcdistro $pldistro $personality 
1023
1024     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
1025
1026     post_install $lxc $personality
1027     
1028     echo $COMMAND Done
1029 }
1030
1031 main "$@"