drop bootmanager:lxc_devel now that it's merged back in master/5.2
[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     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
277 # can't seem to handle this one with systemctl
278     chroot ${rootfs_path} chkconfig network on
279 }
280
281 function download_fedora() {
282 set -x
283     # check the mini fedora was not already downloaded
284     INSTALL_ROOT=$cache/partial
285     echo $INSTALL_ROOT
286     mkdir -p $INSTALL_ROOT
287     if [ $? -ne 0 ]; then
288         echo "Failed to create '$INSTALL_ROOT' directory"
289         return 1
290     fi
291
292     # download a mini fedora into a cache
293     echo "Downloading fedora minimal ..."
294     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
295     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
296   
297     
298     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
299     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
300     # with fedora18 the rpms are scattered by first name
301     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
302     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
303     found=""
304     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
305         if curl -f $attempt -o $RELEASE_TARGET ; then
306             echo "Retrieved $attempt"
307             found=true
308             break
309         else
310             echo "Failed attempt $attempt"
311         fi
312     done
313     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
314     
315     mkdir -p $INSTALL_ROOT/var/lib/rpm
316     rpm --root $INSTALL_ROOT  --initdb
317     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
318     echo "$YUM install $PKG_LIST"
319     $YUM install $PKG_LIST
320
321     if [ $? -ne 0 ]; then
322         echo "Failed to download the rootfs, aborting."
323         return 1
324     fi
325
326     mv "$INSTALL_ROOT" "$cache/rootfs"
327     echo "Download complete."
328
329     return 0
330 }
331
332
333 function copy_fedora() {
334 set -x
335     # make a local copy of the minifedora
336     echo -n "Copying rootfs to $rootfs_path ..."
337     mkdir -p $rootfs_path
338     rsync -a $cache/rootfs/ $rootfs_path/
339     return 0
340 }
341
342
343 function update_fedora() {
344 set -x
345     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
346     $YUM update
347 }
348
349
350 function install_fedora() {
351     set -x
352
353     mkdir -p /var/lock/subsys/
354     (
355         flock -n -x 200
356         if [ $? -ne 0 ]; then
357             echo "Cache repository is busy."
358             return 1
359         fi
360
361         echo "Checking cache download in $cache/rootfs ... "
362         if [ ! -e "$cache/rootfs" ]; then
363             download_fedora
364             if [ $? -ne 0 ]; then
365                 echo "Failed to download 'fedora base'"
366                 return 1
367             fi
368         else
369             echo "Cache found. Updating..."
370             update_fedora
371             if [ $? -ne 0 ]; then
372                 echo "Failed to update 'fedora base', continuing with last known good cache"
373             else
374                 echo "Update finished"
375             fi
376         fi
377
378         echo "Copy $cache/rootfs to $rootfs_path ... "
379         copy_fedora
380         if [ $? -ne 0 ]; then
381             echo "Failed to copy rootfs"
382             return 1
383         fi
384
385         return 0
386
387         ) 200>/var/lock/subsys/lxc
388
389     return $?
390 }
391
392
393 function copy_configuration() {
394
395     mkdir -p $config_path
396     cat <<EOF >> $config_path/config
397 lxc.utsname = $lxc
398 lxc.arch = $arch2
399 lxc.tty = 4
400 lxc.pts = 1024
401 lxc.rootfs = $rootfs_path
402 lxc.mount  = $config_path/fstab
403 #networking
404 lxc.network.type = $lxc_network_type
405 lxc.network.flags = up
406 lxc.network.link = $lxc_network_link
407 lxc.network.name = $IFNAME
408 lxc.network.mtu = 1500
409 lxc.network.ipv4 = $IP/$CIDR
410 lxc.network.veth.pair = $veth_pair
411 #cgroups
412 #lxc.cgroup.devices.deny = a
413 # /dev/null and zero
414 lxc.cgroup.devices.allow = c 1:3 rwm
415 lxc.cgroup.devices.allow = c 1:5 rwm
416 # consoles
417 lxc.cgroup.devices.allow = c 5:1 rwm
418 lxc.cgroup.devices.allow = c 5:0 rwm
419 lxc.cgroup.devices.allow = c 4:0 rwm
420 lxc.cgroup.devices.allow = c 4:1 rwm
421 # /dev/{,u}random
422 lxc.cgroup.devices.allow = c 1:9 rwm
423 lxc.cgroup.devices.allow = c 1:8 rwm
424 lxc.cgroup.devices.allow = c 136:* rwm
425 lxc.cgroup.devices.allow = c 5:2 rwm
426 # rtc
427 lxc.cgroup.devices.allow = c 254:0 rwm
428 lxc.cgroup.devices.allow = b 255:0 rwm
429 EOF
430
431
432
433     cat <<EOF > $config_path/fstab
434 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
435 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
436 sysfs           $rootfs_path/sys          sysfs defaults  0 0
437 EOF
438     if [ $? -ne 0 ]; then
439         echo "Failed to add configuration"
440         return 1
441     fi
442
443     return 0
444 }
445
446
447
448
449 # overwrite lxc's internal yum config
450 function configure_yum_in_lxc () {
451     set -x 
452     set -e 
453     trap failure ERR INT
454
455     lxc=$1; shift
456     fcdistro=$1; shift
457     pldistro=$1; shift
458
459     echo "Initializing yum.repos.d in $lxc"
460     rm -f $rootfs_path/etc/yum.repos.d/*
461
462     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
463 [fedora]
464 name=Fedora $release - \$basearch
465 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
466 enabled=1
467 metadata_expire=7d
468 gpgcheck=1
469 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
470
471 [updates]
472 name=Fedora $release - \$basearch - Updates
473 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
474 enabled=1
475 metadata_expire=7d
476 gpgcheck=1
477 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
478 EOF
479     
480     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
481     # just mention 'none' as the repo url
482     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
483         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
484             echo "WARNING : cannot create myplc repo"
485         else
486             # exclude kernel from fedora repos 
487             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
488             for repo in $rootfs_path/etc/yum.repos.d/* ; do
489                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
490             done
491             # the build repo is not signed at this stage
492             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
493 [myplc]
494 name= MyPLC
495 baseurl=$REPO_URL
496 enabled=1
497 gpgcheck=0
498 EOF
499         fi
500     fi
501 }    
502
503 # return yum or debootstrap
504 function package_method () {
505     fcdistro=$1; shift
506     case $fcdistro in
507         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
508         lenny|etch) echo debootstrap ;;
509         *) echo Unknown distro $fcdistro ;;
510     esac 
511 }
512
513 # return arch from debian distro and personality
514 function canonical_arch () {
515     personality=$1; shift
516     fcdistro=$1; shift
517     case $(package_method $fcdistro) in
518         yum)
519             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
520         debootstrap)
521             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
522         *)
523             echo Unknown-arch-3 ;;
524     esac
525 }
526
527 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
528 function almost_empty () { 
529     dir="$1"; shift ; 
530     # non existing is fine
531     [ ! -d $dir ] && return 0; 
532     # need to have at most one file
533     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
534 }
535
536 function setup_lxc() {
537
538     set -x
539     set -e
540     #trap failure ERR INT
541
542     lxc=$1; shift
543     fcdistro=$1; shift
544     pldistro=$1; shift
545     personality=$1; shift
546
547     # create lxc container 
548     copy_configuration
549     if [ $? -ne 0 ]; then
550         echo "failed write configuration file"
551         exit 1
552     fi
553
554     install_fedora
555     if [ $? -ne 0 ]; then
556         echo "failed to install fedora"
557         exit 1
558     fi
559
560     configure_fedora
561     if [ $? -ne 0 ]; then
562         echo "failed to configure fedora for a container"
563         exit 1
564     fi
565
566     type /bin/systemd >/dev/null 2>&1
567     if [ $? -ne 0 ]; then
568         configure_fedora_init
569     else
570         configure_fedora_systemd
571     fi
572
573     # Enable cgroup
574     mkdir $rootfs_path/cgroup
575     
576     # set up resolv.conf
577     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
578     # and /etc/hosts for at least localhost
579     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
580     
581     # ssh access to lxc
582     mkdir $rootfs_path/root/.ssh
583     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
584     
585     # start container
586     lxc-start -d -n $lxc
587
588     echo $IP is up, waiting for ssh...
589
590     # wait max 5 min for sshd to start 
591     ssh_up=""
592     stop_time=$(($(date +%s) + 300))
593     current_time=$(date +%s)
594
595     while [ "$current_time" -lt "$stop_time" ] ; do
596          echo "ssh attempt ..."
597          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
598          sleep 10
599          current_time=$(($current_time + 10))
600     done
601
602     [ -z $ssh_up ] && echo "SSHD in container $lxc is not running"
603    
604     # rpm --rebuilddb
605     chroot $rootfs_path rpm --rebuilddb
606     #ssh -o "StrictHostKeyChecking no" $IP "rpm --rebuilddb"
607
608     configure_yum_in_lxc $lxc $fcdistro $pldistro
609
610     return 0
611 }
612
613 function devel_or_vtest_tools () {
614
615     set -x 
616     set -e 
617     trap failure ERR INT
618
619     lxc=$1; shift
620     fcdistro=$1; shift
621     pldistro=$1; shift
622     personality=$1; shift
623
624     pkg_method=$(package_method $fcdistro)
625
626     # check for .pkgs file based on pldistro
627     if [ -n "$VBUILD_MODE" ] ; then
628         pkgsname=devel.pkgs
629     else
630         pkgsname=vtest.pkgs
631     fi
632     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
633
634     ### install individual packages, then groups
635     # get target arch - use uname -i here (we want either x86_64 or i386)
636    
637     lxc_arch=$(chroot $rootfs_path uname -i)
638     # on debian systems we get arch through the 'arch' command
639     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path arch)
640
641     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
642     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
643
644     case "$pkg_method" in
645         yum)
646             [ -n "$packages" ] && chroot $rootfs_path yum -y install $packages
647             for group_plus in $groups; do
648                 group=$(echo $group_plus | sed -e "s,+++, ,g")
649                 chroot $rootfs_path yum -y groupinstall "$group"
650             done
651             # store current rpm list in /init-lxc.rpms in case we need to check the contents
652             chroot $rootfs_path rpm -aq > $rootfs_path/init-lxc.rpms
653             ;;
654         debootstrap)
655             chroot $rootfs_path apt-get update
656             for package in $packages ; do 
657                 chroot $rootfs_path  apt-get install -y $package 
658             done
659             ### xxx todo install groups with apt..
660             ;;
661         *)
662             echo "unknown pkg_method $pkg_method"
663             ;;
664     esac
665
666     return 0
667 }
668
669 function post_install () {
670     if [ -n "$VBUILD_MODE" ] ; then
671         post_install_vbuild "$@" 
672     else
673         post_install_myplc "$@"
674     fi
675     # setup localtime from the host
676     lxc=$1; shift 
677     cp /etc/localtime $rootfs_path/etc/localtime
678 }
679
680 function post_install_vbuild () {
681
682     set -x 
683     set -e 
684     trap failure ERR INT
685
686     lxc=$1; shift
687     personality=$1; shift
688
689 ### From myplc-devel-native.spec
690 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
691     cat << EOF | chroot $rootfs_path bash -x
692     # set up /dev/loop* in lxc
693     for i in \$(seq 0 255) ; do
694         mknod -m 640 /dev/loop\$i b 7 \$i
695     done
696     
697     # create symlink for /dev/fd
698     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
699
700     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
701     sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
702     if [ -h "/sbin/new-kernel-pkg" ] ; then
703         filename=\$(readlink -f /sbin/new-kernel-pkg)
704         if [ "\$filename" == "/sbin/true" ] ; then
705                 echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
706                 echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
707                 echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
708                 exit 1
709         fi
710     fi
711     
712     # customize root's prompt
713     cat << PROFILE > /root/.profile
714 export PS1="[$lxc] \\w # "
715 PROFILE
716
717     uid=2000
718     gid=2000
719     
720     # add a "build" user to the system
721     builduser=\$(grep "^build:" /etc/passwd | wc -l)
722     if [ \$builduser -eq 0 ] ; then
723         groupadd -o -g \$gid build;
724         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
725     fi
726
727 # Allow build user to build certain RPMs as root
728     if [ -f /etc/sudoers ] ; then
729         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
730         if [ \$buildsudo -eq 0 ] ; then
731             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
732         fi
733         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
734     fi
735 #
736 EOF
737
738 }
739
740 function post_install_myplc  () {
741     set -x 
742     set -e 
743     trap failure ERR INT
744
745     lxc=$1; shift
746     personality=$1; shift
747
748 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
749     cat << EOF | chroot $rootfs_path bash -x
750
751     # create /etc/sysconfig/network if missing
752     [ -f /etc/sysconfig/network ] || echo NETWORKING=yes > /etc/sysconfig/network
753
754     # create symlink for /dev/fd
755     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
756
757     # turn off regular crond, as plc invokes plc_crond
758     chkconfig crond off
759
760     # take care of loginuid in /etc/pam.d 
761     sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
762
763     # customize root's prompt
764     cat << PROFILE > /root/.profile
765 export PS1="[$lxc] \\w # "
766 PROFILE
767
768 EOF
769 }
770
771 function usage () {
772     set +x 
773     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
774     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
775     echo "Description:"
776     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
777     echo "Supported options"
778     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
779     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
780     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
781     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
782     echo "-- lxc-options"
783     echo "  --netdev : interface to be defined inside lxc"
784     echo "  --interface : IP to be defined for the lxc"
785     echo "  --hostname : Hostname to be defined for the lxc"
786     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
787     echo "   myplc.repo does not get created"
788     exit 1
789 }
790
791 ### parse args and 
792 function main () {
793
794     #set -e
795     #trap failure ERR INT
796
797     case "$COMMAND" in
798         $COMMAND_VBUILD)
799             VBUILD_MODE=true ;;
800         $COMMAND_MYPLC)
801             MYPLC_MODE=true;;
802         *)
803             usage ;;
804     esac
805
806     VERBOSE=
807     RESISTANT=""
808     IFNAME=""
809     LXC_OPTIONS=""
810     while getopts "f:d:p:i:" opt ; do
811         case $opt in
812             f) fcdistro=$OPTARG;;
813             d) pldistro=$OPTARG;;
814             p) personality=$OPTARG;;
815             i) IFNAME=$OPTARG;;
816             *) usage ;;
817         esac
818     done
819         
820     shift $(($OPTIND - 1))
821
822     # parse fixed arguments
823     [[ -z "$@" ]] && usage
824     lxc=$1 ; shift
825     if [ -n "$MYPLC_MODE" ] ; then
826         [[ -z "$@" ]] && usage
827         REPO_URL=$1 ; shift
828     fi
829
830     # parse vserver options
831     if [[ -n "$@" ]] ; then
832         if [ "$1" == "--" ] ; then
833             shift
834             LXC_OPTIONS="$@"
835         else
836             usage
837         fi
838     fi
839
840     eval set -- "$LXC_OPTIONS"
841
842     while true
843      do
844         case "$1" in
845              --netdev)      IFNAME=$2; shift 2;;
846              --interface)   IP=$2; shift 2;;
847              --hostname)    HOSTNAME=$2; shift 2;;
848              *)             break ;;
849         esac
850       done
851
852    
853     if [ -n "$VBUILD_MODE" ] ; then
854         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
855         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
856     fi
857
858     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
859     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
860     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
861     
862     release=$(echo $fcdistro | cut -df -f2)
863
864     if [ "$personality" == "linux32" ]; then
865         arch=i386
866         arch2=x86
867     elif [ "$personality" == "linux64" ]; then
868         arch=x86_64
869         arch2=x86_64
870     else
871         echo "Unknown personality: $personality"
872     fi
873
874     # need lxc installed before we can run lxc-ls
875     # need bridge installed
876     prepare_host    
877
878     if [ -n "$VBUILD_MODE" ] ; then
879
880         # Bridge IP affectation
881         x=$(echo $personality | cut -dx -f2)
882         y=$(echo $fcdistro | cut -df -f2)
883         z=$(($x + $y))
884
885         IP="192.168.122.$z"
886         NETMASK="255.255.255.0"
887         GATEWAY="192.168.122.1"
888         
889         lxc_network_type=veth
890         lxc_network_link=virbr0
891         veth_pair="veth$z"
892         echo "the IP address of container $lxc is $IP "
893     else
894         [[ -z "$REPO_URL" ]] && usage
895         [[ -z "$IP" ]] && usage
896        
897         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
898         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
899         [[ -z "$HOSTNAME" ]] && usage
900         lxc_network_type=veth
901         lxc_network_link=br0
902         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
903     fi
904
905     CIDR=$(cidr_notation $NETMASK)
906     
907
908     if [ "$(id -u)" != "0" ]; then
909           echo "This script should be run as 'root'"
910           exit 1
911     fi
912
913     path=/var/lib/lxc
914     rootfs_path=$path/$lxc/rootfs
915     config_path=$path/$lxc
916     cache_base=/var/cache/lxc/fedora/$arch
917     cache=$cache_base/$release
918     root_password=root
919     
920     # check whether the rootfs directory is created to know if the container exists
921     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
922     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
923
924     setup_lxc $lxc $fcdistro $pldistro $personality 
925
926     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
927
928     post_install $lxc $personality
929     
930
931     echo $COMMAND Done
932 }
933
934 main "$@"