manage f18 hostname setting in vbuild-init-lxc.sh
[build.git] / vbuild-init-lxc.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=f16
15 DEFAULT_PLDISTRO=planetlab
16 DEFAULT_PERSONALITY=linux64
17 DEFAULT_IFNAME=eth0
18
19 COMMAND_VBUILD="vbuild-init-lxc.sh"
20 COMMAND_MYPLC="vtest-init-lxc.sh"
21
22 lxc_version="lxc-0.8.0"
23 lxc_git_repo="git://lxc.git.sourceforge.net/gitroot/lxc/lxc"
24
25 function bridge_init () {
26
27     # turn on verbosity
28     set -x
29
30     # constant
31     INTERFACE_BRIDGE=br0
32
33     # Default Value for INTERFACE_LAN
34     INTERFACE_LAN=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
35
36
37     echo "========== $COMMAND: entering start - beg"
38     hostname
39     uname -a
40     ifconfig
41     netstat -rn
42     echo "========== $COMMAND: entering start - end"
43
44     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
45     #
46     # another option would be to accept the all forward packages for
47     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
48     sysctl net.bridge.bridge-nf-call-iptables=0
49     sysctl net.bridge.bridge-nf-call-ip6tables=0
50     sysctl net.bridge.bridge-nf-call-arptables=0
51
52     # take extra arg for ifname, if provided
53     [ -n "$1" ] && { INTERFACE_LAN=$1; shift ; }
54
55     #if we have already configured the same host_box no need to do it again
56     /sbin/ifconfig $INTERFACE_BRIDGE &> /dev/null && {
57         echo "Bridge interface $INTERFACE_BRIDGE already set up - $COMMAND start exiting"
58         return 0
59     }
60     /sbin/ifconfig $INTERFACE_LAN &>/dev/null || {
61         echo "Cannot use interface $INTERFACE_LAN - exiting"
62         exit 1
63     }
64
65     
66     #Getting host IP/masklen
67     address=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
68     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $INTERFACE_LAN" ; exit 1 ; }
69
70 broadcast=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
71     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $INTERFACE_LAN"
72
73     gateway=$(netstat -rn | grep '^0.0.0.0' | awk '{print $2;}')
74     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
75
76     # creating the bridge
77     echo "Creating bridge INTERFACE_BRIDGE=$INTERFACE_BRIDGE"
78     brctl addbr $INTERFACE_BRIDGE
79     #brctl stp $INTERFACE_BRIDGE yes
80     brctl addif $INTERFACE_BRIDGE $INTERFACE_LAN
81     echo "Activating promiscuous mode INTERFACE_LAN=$INTERFACE_LAN"
82     /sbin/ifconfig $INTERFACE_LAN 0.0.0.0 promisc up
83     sleep 2
84     echo "Setting bridge address=$address broadcast=$broadcast"
85     # static
86     #/sbin/ifconfig $INTERFACE_BRIDGE $address broadcast $broadcast up
87     dhclient $INTERFACE_BRIDGE
88     sleep 1
89
90     #Reconfigure the routing table
91     echo "Configuring gateway=$gateway"
92     route add default gw $gateway
93
94     echo "========== $COMMAND: exiting start - beg"
95     ifconfig
96     netstat -rn
97     echo "========== $COMMAND: exiting start - end"
98
99
100 return 0
101
102 }
103
104
105 function failure () {
106     echo "$COMMAND : Bailing out"
107     exit 1
108 }
109
110 function cidr_notation () {
111
112 netmask=$1; shift
113 cidr=0
114 for i in $(seq 1 4) ; do
115     part=$(echo $netmask | cut -d. -f $i)
116     case $part in
117         "255") cidr=$((cidr + 8));;
118         "254") cidr=$((cidr + 7));;
119         "252") cidr=$((cidr + 6));;
120         "248") cidr=$((cidr + 5));;
121         "240") cidr=$((cidr + 4));;
122         "224") cidr=$((cidr + 3));;
123         "192") cidr=$((cidr + 2));;
124         "128") cidr=$((cidr + 1));;
125         "0") cidr=$((cidr + 0));;
126      esac
127 done
128 echo $cidr
129
130 }
131
132 function check_yum_installed () {
133     package=$1; shift
134     rpm -q $package >& /dev/null || yum -y install $package
135 }
136
137 function check_yumgroup_installed () {
138     group="$1"; shift
139     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
140 }
141
142 function prepare_host() {
143         
144     #################### lxc-tools : rebuild as current fedora release has flaws
145     #install development tools
146     check_yumgroup_installed "Development Tools"
147     #install libcap-devel, libvirt
148     check_yum_installed libcap-devel
149     check_yum_installed libvirt
150
151     #retrieve and install lxc from sources 
152     raw_version=$(lxc-version ||: )
153     lxc_installed_version=$(echo $raw_version | sed -e 's,.*: ,,')
154     if [ "$lxc_installed_version" != "$lxc_version" ] ; then
155         echo "Expecting version" '['$lxc_version']'
156         echo "Found version" '['$lxc_installed_version']'
157         echo "Installing lxc ..."
158         cd /root
159         [ -d lxc ] || git clone "$lxc_git_repo"
160         cd lxc
161         git pull
162         git checkout $lxc_version
163         ./autogen.sh
164         ./configure --prefix=/usr --exec-prefix=/usr
165         make
166         make install
167         mkdir -p /usr/var/lib/
168         [ -d /usr/var/lib/lxc ] || ln -s /var/lib/lxc /usr/var/lib/lxc
169         cd $BUILD_DIR
170     fi
171  
172 #    #create a placeholder (just a hack to make lxc works)
173 #    [ -d "/usr/local/var/lib" ] || mkdir -p /usr/local/var/lib
174
175     #################### bride initialization
176     check_yum_installed bridge-utils
177     #Bridge init
178     isInstalled=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
179     if [ "$isInstalled" != "br0" ] ; then
180         bridge_init
181         sleep 5
182     fi
183
184     return 0
185 }
186
187
188
189 function configure_fedora() {
190
191     # disable selinux in fedora
192     mkdir -p $rootfs_path/selinux
193     echo 0 > $rootfs_path/selinux/enforce
194
195    # configure the network 
196
197     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$IFNAME
198 DEVICE=$IFNAME
199 BOOTPROTO=static
200 ONBOOT=yes
201 HOSTNAME=$HOSTNAME
202 IPADDR=$IP
203 NETMASK=$NETMASK
204 GATEWAY=$GATEWAY
205 NM_CONTROLLED=no
206 TYPE=Ethernet
207 MTU=1500
208 EOF
209
210 # set the hostname
211 if [ "fcdistro" == "f18"]; then
212     cat <<EOF > ${rootfs_path}/etc/hostname
213 $HOSTNAME
214 EOF
215 else
216     cat <<EOF > ${rootfs_path}/etc/sysconfig/network
217 NETWORKING=yes
218 HOSTNAME=$HOSTNAME
219 EOF
220 fi
221
222     # set minimal hosts
223 #    cat <<EOF > $rootfs_path/etc/hosts
224 #127.0.0.1 localhost $HOSTNAME
225 #EOF
226
227     dev_path="${rootfs_path}/dev"
228     rm -rf $dev_path
229     mkdir -p $dev_path
230     mknod -m 666 ${dev_path}/null c 1 3
231     mknod -m 666 ${dev_path}/zero c 1 5
232     mknod -m 666 ${dev_path}/random c 1 8
233     mknod -m 666 ${dev_path}/urandom c 1 9
234     mkdir -m 755 ${dev_path}/pts
235     mkdir -m 1777 ${dev_path}/shm
236     mknod -m 666 ${dev_path}/tty c 5 0
237     mknod -m 666 ${dev_path}/tty0 c 4 0
238     mknod -m 666 ${dev_path}/tty1 c 4 1
239     mknod -m 666 ${dev_path}/tty2 c 4 2
240     mknod -m 666 ${dev_path}/tty3 c 4 3
241     mknod -m 666 ${dev_path}/tty4 c 4 4
242     mknod -m 600 ${dev_path}/console c 5 1
243     mknod -m 666 ${dev_path}/full c 1 7
244     mknod -m 600 ${dev_path}/initctl p
245     mknod -m 666 ${dev_path}/ptmx c 5 2
246
247     #echo "setting root passwd to $root_password"
248     #echo "root:$root_password" | chroot $rootfs_path chpasswd
249
250     return 0
251 }
252
253
254 function configure_fedora_init() {
255
256     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
257     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
258     chroot ${rootfs_path} chkconfig udev-post off
259     chroot ${rootfs_path} chkconfig network on
260     if [ "fcdistro" == "f18"]; then 
261        chroot ${rootfs_path} hostnamectl set-hostname $HOSTNAME
262 }
263
264
265 function configure_fedora_systemd() {
266
267     unlink ${rootfs_path}/etc/systemd/system/default.target
268     touch ${rootfs_path}/etc/fstab
269     chroot ${rootfs_path} ln -s /dev/null //etc/systemd/system/udev.service
270     chroot ${rootfs_path} ln -s /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
271     #dependency on a device unit fails it specially that we disabled udev
272     sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
273     chroot ${rootfs_path} chkconfig network on
274     if [ "fcdistro" == "f18"]; then
275        chroot ${rootfs_path} hostnamectl set-hostname $HOSTNAME
276     fi
277 }
278
279 function download_fedora() {
280 set -x
281     # check the mini fedora was not already downloaded
282     INSTALL_ROOT=$cache/partial
283     echo $INSTALL_ROOT
284     mkdir -p $INSTALL_ROOT
285     if [ $? -ne 0 ]; then
286         echo "Failed to create '$INSTALL_ROOT' directory"
287         return 1
288     fi
289
290     # download a mini fedora into a cache
291     echo "Downloading fedora minimal ..."
292     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
293     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
294   
295     
296     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
297     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
298     # with fedora18 the rpms are scattered by first name
299     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
300     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
301     found=""
302     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
303         if curl -f $attempt -o $RELEASE_TARGET ; then
304             echo "Retrieved $attempt"
305             found=true
306             break
307         else
308             echo "Failed attempt $attempt"
309         fi
310     done
311     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
312     
313     mkdir -p $INSTALL_ROOT/var/lib/rpm
314     rpm --root $INSTALL_ROOT  --initdb
315     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
316     echo "$YUM install $PKG_LIST"
317     $YUM install $PKG_LIST
318
319     if [ $? -ne 0 ]; then
320         echo "Failed to download the rootfs, aborting."
321         return 1
322     fi
323
324     mv "$INSTALL_ROOT" "$cache/rootfs"
325     echo "Download complete."
326
327     return 0
328 }
329
330
331 function copy_fedora() {
332 set -x
333     # make a local copy of the minifedora
334     echo -n "Copying rootfs to $rootfs_path ..."
335     mkdir -p $rootfs_path
336     rsync -a $cache/rootfs/ $rootfs_path/
337     return 0
338 }
339
340
341 function update_fedora() {
342 set -x
343     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
344     $YUM update
345 }
346
347
348 function install_fedora() {
349     set -x
350
351     mkdir -p /var/lock/subsys/
352     (
353         flock -n -x 200
354         if [ $? -ne 0 ]; then
355             echo "Cache repository is busy."
356             return 1
357         fi
358
359         echo "Checking cache download in $cache/rootfs ... "
360         if [ ! -e "$cache/rootfs" ]; then
361             download_fedora
362             if [ $? -ne 0 ]; then
363                 echo "Failed to download 'fedora base'"
364                 return 1
365             fi
366         else
367             echo "Cache found. Updating..."
368             update_fedora
369             if [ $? -ne 0 ]; then
370                 echo "Failed to update 'fedora base', continuing with last known good cache"
371             else
372                 echo "Update finished"
373             fi
374         fi
375
376         echo "Copy $cache/rootfs to $rootfs_path ... "
377         copy_fedora
378         if [ $? -ne 0 ]; then
379             echo "Failed to copy rootfs"
380             return 1
381         fi
382
383         return 0
384
385         ) 200>/var/lock/subsys/lxc
386
387     return $?
388 }
389
390
391 function copy_configuration() {
392
393     mkdir -p $config_path
394     cat <<EOF >> $config_path/config
395 lxc.utsname = $lxc
396 lxc.arch = $arch2
397 lxc.tty = 4
398 lxc.pts = 1024
399 lxc.rootfs = $rootfs_path
400 lxc.mount  = $config_path/fstab
401 #networking
402 lxc.network.type = $lxc_network_type
403 lxc.network.flags = up
404 lxc.network.link = $lxc_network_link
405 lxc.network.name = $IFNAME
406 lxc.network.mtu = 1500
407 lxc.network.ipv4 = $IP/$CIDR
408 lxc.network.veth.pair = $veth_pair
409 #cgroups
410 #lxc.cgroup.devices.deny = a
411 # /dev/null and zero
412 lxc.cgroup.devices.allow = c 1:3 rwm
413 lxc.cgroup.devices.allow = c 1:5 rwm
414 # consoles
415 lxc.cgroup.devices.allow = c 5:1 rwm
416 lxc.cgroup.devices.allow = c 5:0 rwm
417 lxc.cgroup.devices.allow = c 4:0 rwm
418 lxc.cgroup.devices.allow = c 4:1 rwm
419 # /dev/{,u}random
420 lxc.cgroup.devices.allow = c 1:9 rwm
421 lxc.cgroup.devices.allow = c 1:8 rwm
422 lxc.cgroup.devices.allow = c 136:* rwm
423 lxc.cgroup.devices.allow = c 5:2 rwm
424 # rtc
425 lxc.cgroup.devices.allow = c 254:0 rwm
426 lxc.cgroup.devices.allow = b 255:0 rwm
427 EOF
428
429
430
431     cat <<EOF > $config_path/fstab
432 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
433 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
434 sysfs           $rootfs_path/sys          sysfs defaults  0 0
435 EOF
436     if [ $? -ne 0 ]; then
437         echo "Failed to add configuration"
438         return 1
439     fi
440
441     return 0
442 }
443
444
445
446
447 # overwrite lxc's internal yum config
448 function configure_yum_in_lxc () {
449     set -x 
450     set -e 
451     trap failure ERR INT
452
453     lxc=$1; shift
454     fcdistro=$1; shift
455     pldistro=$1; shift
456
457     echo "Initializing yum.repos.d in $lxc"
458     rm -f $rootfs_path/etc/yum.repos.d/*
459
460     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
461 [fedora]
462 name=Fedora $release - \$basearch
463 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
464 enabled=1
465 metadata_expire=7d
466 gpgcheck=1
467 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
468
469 [updates]
470 name=Fedora $release - \$basearch - Updates
471 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
472 enabled=1
473 metadata_expire=7d
474 gpgcheck=1
475 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
476 EOF
477     
478     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
479     # just mention 'none' as the repo url
480     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
481         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
482             echo "WARNING : cannot create myplc repo"
483         else
484             # exclude kernel from fedora repos 
485             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
486             for repo in $rootfs_path/etc/yum.repos.d/* ; do
487                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
488             done
489             # the build repo is not signed at this stage
490             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
491 [myplc]
492 name= MyPLC
493 baseurl=$REPO_URL
494 enabled=1
495 gpgcheck=0
496 EOF
497         fi
498     fi
499 }    
500
501 # return yum or debootstrap
502 function package_method () {
503     fcdistro=$1; shift
504     case $fcdistro in
505         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
506         lenny|etch) echo debootstrap ;;
507         *) echo Unknown distro $fcdistro ;;
508     esac 
509 }
510
511 # return arch from debian distro and personality
512 function canonical_arch () {
513     personality=$1; shift
514     fcdistro=$1; shift
515     case $(package_method $fcdistro) in
516         yum)
517             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
518         debootstrap)
519             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
520         *)
521             echo Unknown-arch-3 ;;
522     esac
523 }
524
525 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
526 function almost_empty () { 
527     dir="$1"; shift ; 
528     # non existing is fine
529     [ ! -d $dir ] && return 0; 
530     # need to have at most one file
531     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
532 }
533
534 function setup_lxc() {
535
536     set -x
537     set -e
538     #trap failure ERR INT
539
540     lxc=$1; shift
541     fcdistro=$1; shift
542     pldistro=$1; shift
543     personality=$1; shift
544
545     # create lxc container 
546     copy_configuration
547     if [ $? -ne 0 ]; then
548         echo "failed write configuration file"
549         exit 1
550     fi
551
552     install_fedora
553     if [ $? -ne 0 ]; then
554         echo "failed to install fedora"
555         exit 1
556     fi
557
558     configure_fedora
559     if [ $? -ne 0 ]; then
560         echo "failed to configure fedora for a container"
561         exit 1
562     fi
563
564     type /bin/systemd >/dev/null 2>&1
565     if [ $? -ne 0 ]; then
566         configure_fedora_init
567     else
568         configure_fedora_systemd
569     fi
570
571     # Enable cgroup
572     mkdir $rootfs_path/cgroup
573     
574     # set up resolv.conf
575     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
576     # and /etc/hosts for at least localhost
577     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
578     
579     # ssh access to lxc
580     mkdir $rootfs_path/root/.ssh
581     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
582     
583     # start container
584     lxc-start -d -n $lxc
585
586     echo $IP is up, waiting for ssh...
587
588     # wait max 5 min for sshd to start 
589     ssh_up=""
590     stop_time=$(($(date +%s) + 300))
591     current_time=$(date +%s)
592
593     while [ "$current_time" -lt "$stop_time" ] ; do
594          echo "ssh attempt ..."
595          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
596          sleep 10
597          current_time=$(($current_time + 10))
598     done
599
600     [ -z $ssh_up ] && echo "SSHD in container $lxc is not running"
601      
602
603     # rpm --rebuilddb
604     chroot $rootfs_path rpm --rebuilddb
605     #ssh -o "StrictHostKeyChecking no" $IP "rpm --rebuilddb"
606
607     configure_yum_in_lxc $lxc $fcdistro $pldistro
608
609     return 0
610 }
611
612 function devel_or_vtest_tools () {
613
614     set -x 
615     set -e 
616     trap failure ERR INT
617
618     lxc=$1; shift
619     fcdistro=$1; shift
620     pldistro=$1; shift
621     personality=$1; shift
622
623     pkg_method=$(package_method $fcdistro)
624
625     # check for .pkgs file based on pldistro
626     if [ -n "$VBUILD_MODE" ] ; then
627         pkgsname=devel.pkgs
628     else
629         pkgsname=vtest.pkgs
630     fi
631     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
632
633     ### install individual packages, then groups
634     # get target arch - use uname -i here (we want either x86_64 or i386)
635    
636     lxc_arch=$(chroot $rootfs_path uname -i)
637     # on debian systems we get arch through the 'arch' command
638     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path arch)
639
640     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
641     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
642
643     case "$pkg_method" in
644         yum)
645             [ -n "$packages" ] && chroot $rootfs_path yum -y install $packages
646             for group_plus in $groups; do
647                 group=$(echo $group_plus | sed -e "s,+++, ,g")
648                 chroot $rootfs_path yum -y groupinstall "$group"
649             done
650             # store current rpm list in /init-lxc.rpms in case we need to check the contents
651             chroot $rootfs_path rpm -aq > $rootfs_path/init-lxc.rpms
652             ;;
653         debootstrap)
654             chroot $rootfs_path apt-get update
655             for package in $packages ; do 
656                 chroot $rootfs_path  apt-get install -y $package 
657             done
658             ### xxx todo install groups with apt..
659             ;;
660         *)
661             echo "unknown pkg_method $pkg_method"
662             ;;
663     esac
664
665     return 0
666 }
667
668 function post_install () {
669     if [ -n "$VBUILD_MODE" ] ; then
670         post_install_vbuild "$@" 
671     else
672         post_install_myplc "$@"
673     fi
674     # setup localtime from the host
675     lxc=$1; shift 
676     cp /etc/localtime $rootfs_path/etc/localtime
677 }
678
679 function post_install_vbuild () {
680
681     set -x 
682     set -e 
683     trap failure ERR INT
684
685     lxc=$1; shift
686     personality=$1; shift
687
688 ### From myplc-devel-native.spec
689 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
690     cat << EOF | chroot $rootfs_path bash -x
691     # set up /dev/loop* in lxc
692     for i in \$(seq 0 255) ; do
693         mknod -m 640 /dev/loop\$i b 7 \$i
694     done
695     
696     # create symlink for /dev/fd
697     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
698
699     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
700     sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
701     if [ -h "/sbin/new-kernel-pkg" ] ; then
702         filename=\$(readlink -f /sbin/new-kernel-pkg)
703         if [ "\$filename" == "/sbin/true" ] ; then
704                 echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
705                 echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
706                 echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
707                 exit 1
708         fi
709     fi
710     
711     # customize root's prompt
712     cat << PROFILE > /root/.profile
713 export PS1="[$lxc] \\w # "
714 PROFILE
715
716     uid=2000
717     gid=2000
718     
719     # add a "build" user to the system
720     builduser=\$(grep "^build:" /etc/passwd | wc -l)
721     if [ \$builduser -eq 0 ] ; then
722         groupadd -o -g \$gid build;
723         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
724     fi
725
726 # Allow build user to build certain RPMs as root
727     if [ -f /etc/sudoers ] ; then
728         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
729         if [ \$buildsudo -eq 0 ] ; then
730             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
731         fi
732         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
733     fi
734 #
735 EOF
736
737 }
738
739 function post_install_myplc  () {
740     set -x 
741     set -e 
742     trap failure ERR INT
743
744     lxc=$1; shift
745     personality=$1; shift
746
747 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
748     cat << EOF | chroot $rootfs_path bash -x
749
750     # create /etc/sysconfig/network if missing
751     [ -f /etc/sysconfig/network ] || echo NETWORKING=yes > /etc/sysconfig/network
752
753     # create symlink for /dev/fd
754     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
755
756     # turn off regular crond, as plc invokes plc_crond
757     chkconfig crond off
758
759     # take care of loginuid in /etc/pam.d 
760     sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
761
762     # customize root's prompt
763     cat << PROFILE > /root/.profile
764 export PS1="[$lxc] \\w # "
765 PROFILE
766
767 EOF
768 }
769
770 function usage () {
771     set +x 
772     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
773     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
774     echo "Description:"
775     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
776     echo "Supported options"
777     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
778     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
779     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
780     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
781     echo "-- lxc-options"
782     echo "  --netdev : interface to be defined inside lxc"
783     echo "  --interface : IP to be defined for the lxc"
784     echo "  --hostname : Hostname to be defined for the lxc"
785     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
786     echo "   myplc.repo does not get created"
787     exit 1
788 }
789
790 ### parse args and 
791 function main () {
792
793     #set -e
794     #trap failure ERR INT
795
796     case "$COMMAND" in
797         $COMMAND_VBUILD)
798             VBUILD_MODE=true ;;
799         $COMMAND_MYPLC)
800             MYPLC_MODE=true;;
801         *)
802             usage ;;
803     esac
804
805     VERBOSE=
806     RESISTANT=""
807     IFNAME=""
808     LXC_OPTIONS=""
809     while getopts "f:d:p:i:" opt ; do
810         case $opt in
811             f) fcdistro=$OPTARG;;
812             d) pldistro=$OPTARG;;
813             p) personality=$OPTARG;;
814             i) IFNAME=$OPTARG;;
815             *) usage ;;
816         esac
817     done
818         
819     shift $(($OPTIND - 1))
820
821     # parse fixed arguments
822     [[ -z "$@" ]] && usage
823     lxc=$1 ; shift
824     if [ -n "$MYPLC_MODE" ] ; then
825         [[ -z "$@" ]] && usage
826         REPO_URL=$1 ; shift
827     fi
828
829     # parse vserver options
830     if [[ -n "$@" ]] ; then
831         if [ "$1" == "--" ] ; then
832             shift
833             LXC_OPTIONS="$@"
834         else
835             usage
836         fi
837     fi
838
839     eval set -- "$LXC_OPTIONS"
840
841     while true
842      do
843         case "$1" in
844              --netdev)      IFNAME=$2; shift 2;;
845              --interface)   IP=$2; shift 2;;
846              --hostname)    HOSTNAME=$2; shift 2;;
847              *)             break ;;
848         esac
849       done
850
851    
852     if [ -n "$VBUILD_MODE" ] ; then
853         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
854         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
855     fi
856
857     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
858     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
859     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
860     
861     release=$(echo $fcdistro | cut -df -f2)
862
863     if [ "$personality" == "linux32" ]; then
864         arch=i386
865         arch2=x86
866     elif [ "$personality" == "linux64" ]; then
867         arch=x86_64
868         arch2=x86_64
869     else
870         echo "Unknown personality: $personality"
871     fi
872
873     # need lxc installed before we can run lxc-ls
874     # need bridge installed
875     prepare_host    
876
877     if [ -n "$VBUILD_MODE" ] ; then
878
879         # Bridge IP affectation
880         x=$(echo $personality | cut -dx -f2)
881         y=$(echo $fcdistro | cut -df -f2)
882         z=$(($x + $y))
883
884         IP="192.168.122.$z"
885         NETMASK="255.255.255.0"
886         GATEWAY="192.168.122.1"
887         
888         lxc_network_type=veth
889         lxc_network_link=virbr0
890         veth_pair="veth$z"
891         echo "the IP address of container $lxc is $IP "
892     else
893         [[ -z "$REPO_URL" ]] && usage
894         [[ -z "$IP" ]] && usage
895         NETMASK=$(ifconfig br0 | grep 'inet addr' | awk '{print $4}' | sed -e 's/.*://')
896         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
897         [[ -z "$HOSTNAME" ]] && usage
898         lxc_network_type=veth
899         lxc_network_link=br0
900         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
901     fi
902
903     CIDR=$(cidr_notation $NETMASK)
904     
905
906     if [ "$(id -u)" != "0" ]; then
907           echo "This script should be run as 'root'"
908           exit 1
909     fi
910
911     path=/var/lib/lxc
912     rootfs_path=$path/$lxc/rootfs
913     config_path=$path/$lxc
914     cache_base=/var/cache/lxc/fedora/$arch
915     cache=$cache_base/$release
916     root_password=root
917     
918     # check whether the rootfs directory is created to know if the container exists
919     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
920     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
921
922     setup_lxc $lxc $fcdistro $pldistro $personality 
923
924     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
925
926     post_install $lxc $personality
927     
928
929     echo $COMMAND Done
930 }
931
932 main "$@"