try to shut off getty for good
[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" != "$(echo $lxc_version | cut -d'-' -f2)" ] ; 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 --disable-apparmor
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 }
261
262
263 function configure_fedora_systemd() {
264     unlink ${rootfs_path}/etc/systemd/system/default.target
265     ln -s /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
266     touch ${rootfs_path}/etc/fstab
267     ln -s /dev/null ${rootfs_path}/etc/systemd/system/udev.service
268 # Thierry - Feb 2013
269 # this was intended for f16 initially, in order to enable getty that otherwise would not start
270 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
271 # VM's that refuse to lxc-stop and VM's that run crazy getty's
272 # so, turning getty off for now instead
273 #   #dependency on a device unit fails it specially that we disabled udev
274 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
275     ln -s /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
276     ln -s /dev/null ${rootfs_path}/usr/lib/systemd/system/"getty@.service"
277     chroot ${rootfs_path} chkconfig network on
278 }
279
280 function download_fedora() {
281 set -x
282     # check the mini fedora was not already downloaded
283     INSTALL_ROOT=$cache/partial
284     echo $INSTALL_ROOT
285     mkdir -p $INSTALL_ROOT
286     if [ $? -ne 0 ]; then
287         echo "Failed to create '$INSTALL_ROOT' directory"
288         return 1
289     fi
290
291     # download a mini fedora into a cache
292     echo "Downloading fedora minimal ..."
293     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
294     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
295   
296     
297     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
298     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
299     # with fedora18 the rpms are scattered by first name
300     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
301     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
302     found=""
303     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
304         if curl -f $attempt -o $RELEASE_TARGET ; then
305             echo "Retrieved $attempt"
306             found=true
307             break
308         else
309             echo "Failed attempt $attempt"
310         fi
311     done
312     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
313     
314     mkdir -p $INSTALL_ROOT/var/lib/rpm
315     rpm --root $INSTALL_ROOT  --initdb
316     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
317     echo "$YUM install $PKG_LIST"
318     $YUM install $PKG_LIST
319
320     if [ $? -ne 0 ]; then
321         echo "Failed to download the rootfs, aborting."
322         return 1
323     fi
324
325     mv "$INSTALL_ROOT" "$cache/rootfs"
326     echo "Download complete."
327
328     return 0
329 }
330
331
332 function copy_fedora() {
333 set -x
334     # make a local copy of the minifedora
335     echo -n "Copying rootfs to $rootfs_path ..."
336     mkdir -p $rootfs_path
337     rsync -a $cache/rootfs/ $rootfs_path/
338     return 0
339 }
340
341
342 function update_fedora() {
343 set -x
344     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
345     $YUM update
346 }
347
348
349 function install_fedora() {
350     set -x
351
352     mkdir -p /var/lock/subsys/
353     (
354         flock -n -x 200
355         if [ $? -ne 0 ]; then
356             echo "Cache repository is busy."
357             return 1
358         fi
359
360         echo "Checking cache download in $cache/rootfs ... "
361         if [ ! -e "$cache/rootfs" ]; then
362             download_fedora
363             if [ $? -ne 0 ]; then
364                 echo "Failed to download 'fedora base'"
365                 return 1
366             fi
367         else
368             echo "Cache found. Updating..."
369             update_fedora
370             if [ $? -ne 0 ]; then
371                 echo "Failed to update 'fedora base', continuing with last known good cache"
372             else
373                 echo "Update finished"
374             fi
375         fi
376
377         echo "Copy $cache/rootfs to $rootfs_path ... "
378         copy_fedora
379         if [ $? -ne 0 ]; then
380             echo "Failed to copy rootfs"
381             return 1
382         fi
383
384         return 0
385
386         ) 200>/var/lock/subsys/lxc
387
388     return $?
389 }
390
391
392 function copy_configuration() {
393
394     mkdir -p $config_path
395     cat <<EOF >> $config_path/config
396 lxc.utsname = $lxc
397 lxc.arch = $arch2
398 lxc.tty = 4
399 lxc.pts = 1024
400 lxc.rootfs = $rootfs_path
401 lxc.mount  = $config_path/fstab
402 #networking
403 lxc.network.type = $lxc_network_type
404 lxc.network.flags = up
405 lxc.network.link = $lxc_network_link
406 lxc.network.name = $IFNAME
407 lxc.network.mtu = 1500
408 lxc.network.ipv4 = $IP/$CIDR
409 lxc.network.veth.pair = $veth_pair
410 #cgroups
411 #lxc.cgroup.devices.deny = a
412 # /dev/null and zero
413 lxc.cgroup.devices.allow = c 1:3 rwm
414 lxc.cgroup.devices.allow = c 1:5 rwm
415 # consoles
416 lxc.cgroup.devices.allow = c 5:1 rwm
417 lxc.cgroup.devices.allow = c 5:0 rwm
418 lxc.cgroup.devices.allow = c 4:0 rwm
419 lxc.cgroup.devices.allow = c 4:1 rwm
420 # /dev/{,u}random
421 lxc.cgroup.devices.allow = c 1:9 rwm
422 lxc.cgroup.devices.allow = c 1:8 rwm
423 lxc.cgroup.devices.allow = c 136:* rwm
424 lxc.cgroup.devices.allow = c 5:2 rwm
425 # rtc
426 lxc.cgroup.devices.allow = c 254:0 rwm
427 lxc.cgroup.devices.allow = b 255:0 rwm
428 EOF
429
430
431
432     cat <<EOF > $config_path/fstab
433 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
434 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
435 sysfs           $rootfs_path/sys          sysfs defaults  0 0
436 EOF
437     if [ $? -ne 0 ]; then
438         echo "Failed to add configuration"
439         return 1
440     fi
441
442     return 0
443 }
444
445
446
447
448 # overwrite lxc's internal yum config
449 function configure_yum_in_lxc () {
450     set -x 
451     set -e 
452     trap failure ERR INT
453
454     lxc=$1; shift
455     fcdistro=$1; shift
456     pldistro=$1; shift
457
458     echo "Initializing yum.repos.d in $lxc"
459     rm -f $rootfs_path/etc/yum.repos.d/*
460
461     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
462 [fedora]
463 name=Fedora $release - \$basearch
464 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
465 enabled=1
466 metadata_expire=7d
467 gpgcheck=1
468 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
469
470 [updates]
471 name=Fedora $release - \$basearch - Updates
472 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
473 enabled=1
474 metadata_expire=7d
475 gpgcheck=1
476 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
477 EOF
478     
479     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
480     # just mention 'none' as the repo url
481     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
482         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
483             echo "WARNING : cannot create myplc repo"
484         else
485             # exclude kernel from fedora repos 
486             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
487             for repo in $rootfs_path/etc/yum.repos.d/* ; do
488                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
489             done
490             # the build repo is not signed at this stage
491             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
492 [myplc]
493 name= MyPLC
494 baseurl=$REPO_URL
495 enabled=1
496 gpgcheck=0
497 EOF
498         fi
499     fi
500 }    
501
502 # return yum or debootstrap
503 function package_method () {
504     fcdistro=$1; shift
505     case $fcdistro in
506         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
507         lenny|etch) echo debootstrap ;;
508         *) echo Unknown distro $fcdistro ;;
509     esac 
510 }
511
512 # return arch from debian distro and personality
513 function canonical_arch () {
514     personality=$1; shift
515     fcdistro=$1; shift
516     case $(package_method $fcdistro) in
517         yum)
518             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
519         debootstrap)
520             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
521         *)
522             echo Unknown-arch-3 ;;
523     esac
524 }
525
526 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
527 function almost_empty () { 
528     dir="$1"; shift ; 
529     # non existing is fine
530     [ ! -d $dir ] && return 0; 
531     # need to have at most one file
532     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
533 }
534
535 function setup_lxc() {
536
537     set -x
538     set -e
539     #trap failure ERR INT
540
541     lxc=$1; shift
542     fcdistro=$1; shift
543     pldistro=$1; shift
544     personality=$1; shift
545
546     # create lxc container 
547     copy_configuration
548     if [ $? -ne 0 ]; then
549         echo "failed write configuration file"
550         exit 1
551     fi
552
553     install_fedora
554     if [ $? -ne 0 ]; then
555         echo "failed to install fedora"
556         exit 1
557     fi
558
559     configure_fedora
560     if [ $? -ne 0 ]; then
561         echo "failed to configure fedora for a container"
562         exit 1
563     fi
564
565     type /bin/systemd >/dev/null 2>&1
566     if [ $? -ne 0 ]; then
567         configure_fedora_init
568     else
569         configure_fedora_systemd
570     fi
571
572     # Enable cgroup
573     mkdir $rootfs_path/cgroup
574     
575     # set up resolv.conf
576     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
577     # and /etc/hosts for at least localhost
578     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
579     
580     # ssh access to lxc
581     mkdir $rootfs_path/root/.ssh
582     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
583     
584     # start container
585     lxc-start -d -n $lxc
586
587     echo $IP is up, waiting for ssh...
588
589     # wait max 5 min for sshd to start 
590     ssh_up=""
591     stop_time=$(($(date +%s) + 300))
592     current_time=$(date +%s)
593
594     while [ "$current_time" -lt "$stop_time" ] ; do
595          echo "ssh attempt ..."
596          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
597          sleep 10
598          current_time=$(($current_time + 10))
599     done
600
601     [ -z $ssh_up ] && echo "SSHD in container $lxc is not running"
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        
896         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
897         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
898         [[ -z "$HOSTNAME" ]] && usage
899         lxc_network_type=veth
900         lxc_network_link=br0
901         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
902     fi
903
904     CIDR=$(cidr_notation $NETMASK)
905     
906
907     if [ "$(id -u)" != "0" ]; then
908           echo "This script should be run as 'root'"
909           exit 1
910     fi
911
912     path=/var/lib/lxc
913     rootfs_path=$path/$lxc/rootfs
914     config_path=$path/$lxc
915     cache_base=/var/cache/lxc/fedora/$arch
916     cache=$cache_base/$release
917     root_password=root
918     
919     # check whether the rootfs directory is created to know if the container exists
920     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
921     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
922
923     setup_lxc $lxc $fcdistro $pldistro $personality 
924
925     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
926
927     post_install $lxc $personality
928     
929
930     echo $COMMAND Done
931 }
932
933 main "$@"