Allow --dump and -e options to ignore errors
[tridge/autocluster.git] / autocluster
1 #!/bin/bash
2 # main autocluster script
3 #
4 # Copyright (C) Andrew Tridgell  2008
5 # Copyright (C) Martin Schwenke  2008
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #   
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #   
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19
20 ##BEGIN-INSTALLDIR-MAGIC##
21 # There are better ways of doing this but not if you still want to be
22 # able to run straight out of a git tree.  :-)
23 if [ -f "$0" ]; then
24     autocluster="$0"
25 else
26     autocluster=$(which "$0")
27 fi
28 if [ -L "$autocluster" ] ; then
29     autocluster=$(readlink "$autocluster")
30 fi
31 installdir=$(dirname "$autocluster")
32 ##END-INSTALLDIR-MAGIC##
33
34 ####################
35 # show program usage
36 usage ()
37 {
38     cat <<EOF
39 Usage: autocluster [OPTION] ... <COMMAND>
40   options:
41      -c <file>                   specify config file (default is "config")
42      -e <expr>                   execute <expr> and exit
43      -E <expr>                   execute <expr> and continue
44      -x                          enable script debugging
45      --dump                      dump config settings and exit
46
47   configuration options:
48 EOF
49
50     usage_config_options
51
52     cat <<EOF
53
54   commands:
55      create base
56            create a base image
57
58      create cluster CLUSTERNAME
59            create a full cluster
60
61      create node CLUSTERNAME IP_OFFSET
62            (re)create a single cluster node
63
64      mount DISK
65            mount a qemu disk on mnt/
66
67      unmount | umount
68            unmount a qemu disk from mnt/
69
70      bootbase
71            boot the base image
72
73      testproxy
74            test your proxy setup
75 EOF
76     exit 1
77 }
78
79 ###############################
80
81 die () {
82     if [ "$no_sanity" = 1 ] ; then
83         fill_text 0 "WARNING: $*" >&2
84     else
85         fill_text 0 "ERROR: $*" >&2
86         exit 1
87     fi
88 }
89
90 ###############################
91
92 # Indirectly call a function named by ${1}_${2}
93 call_func () {
94     local func="$1" ; shift
95     local type="$1" ; shift
96
97     local f="${func}_${type}"
98     if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
99         "$f" "$@"
100     else
101         f="${func}_DEFAULT"
102         if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null  ; then
103             "$f" "$type" "$@"
104         else
105             die "No function defined for \"${func}\" \"${type}\""
106         fi
107     fi
108 }
109
110 # Note that this will work if you pass "call_func f" because the first
111 # element of the node tuple is the node type.  Nice...  :-)
112 for_each_node ()
113 {
114     local n
115     for n in $NODES ; do
116         "$@" $(IFS=: ; echo $n)
117     done
118 }
119
120 hack_one_node_with ()
121 {
122     local filter="$1" ; shift
123
124     local node_type="$1"
125     local ip_offset="$2"
126     local name="$3"
127     local ctdb_node="$4"
128
129     $filter
130
131     local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
132     nodes="${nodes}${nodes:+ }${item}"
133 }
134
135 # This also gets used for non-filtering iteration.
136 hack_all_nodes_with ()
137 {
138     local filter="$1"
139
140     local nodes=""
141     for_each_node hack_one_node_with "$filter"
142     NODES="$nodes"
143 }
144
145 register_hook ()
146 {
147     local hook_var="$1"
148     local new_hook="$2"
149
150     eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
151 }
152
153 run_hooks ()
154 {
155     local hook_var="$1"
156     shift
157
158     local i
159     for i in ${!hook_var} ; do
160         $i "$@"
161     done
162 }
163
164 # Use with care, since this may clear some autocluster defaults.!
165 clear_hooks ()
166 {
167     local hook_var="$1"
168
169     eval "$hook_var=\"\""
170 }
171
172 ##############################
173
174 # These hooks are intended to customise the value of $DISK.  They have
175 # access to 1 argument ("base", "system", "shared") and the variables
176 # $VIRTBASE, $CLUSTER, $BASENAME (for "base"), $NAME (for "system"),
177 # $SHARED_DISK_NUM (for "shared").  A hook must be deterministic and
178 # should not be stateful, since they can be called multiple times for
179 # the same disk.
180 hack_disk_hooks=""
181
182 # common node creation stuff
183 create_node_COMMON ()
184 {
185     local NAME="$1"
186     local ip_offset="$2"
187     local type="$3"
188     local template_file="${4:-$NODE_TEMPLATE}"
189
190     if [ "$SYSTEM_DISK_FORMAT" != "qcow2" -a "$BASE_FORMAT" = "qcow2" ] ; then
191         die "Error: if BASE_FORMAT is \"qcow2\" then SYSTEM_DISK_FORMAT must also be \"qcow2\"."
192     fi
193
194     local IPNUM=$(($FIRSTIP + $ip_offset))
195     make_network_map
196
197     # Determine base image name.  We use $DISK temporarily to allow
198     # the path to be hacked.
199     local DISK="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
200     if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
201         DISK="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
202     fi
203     run_hooks hack_disk_hooks "base"
204     local base_disk="$DISK"
205
206     # Determine the system disk image name.
207     DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
208     run_hooks hack_disk_hooks "system"
209
210     local di="$DISK"
211     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
212         di=$(readlink "$DISK")
213     fi
214     rm -f "$di"
215     local di_dirname="${di%/*}"
216     mkdir -p "$di_dirname"
217
218     case "$SYSTEM_DISK_FORMAT" in
219         qcow2)
220             echo "Creating the disk..."
221             qemu-img create -b "$base_disk" -f qcow2 "$di"
222             create_node_configure_image "$DISK" "$type"
223             ;;
224         raw)
225             echo "Creating the disk..."
226             cp -v --sparse=always "$base_disk" "$di"
227             create_node_configure_image "$DISK" "$type"
228             ;;
229         reflink)
230             echo "Creating the disk..."
231             cp -v --reflink=always "$base_disk" "$di"
232             create_node_configure_image "$DISK" "$type"
233             ;;
234         mmclone)
235             echo "Creating the disk (using mmclone)..."
236             local base_snap="${base_disk}.snap"
237             [ -f "$base_snap" ] || mmclone snap "$base_disk" "$base_snap"
238             mmclone copy "$base_snap" "$di"
239             create_node_configure_image "$DISK" "$type"
240             ;;
241         none)
242             echo "Skipping disk image creation as requested"
243             ;;
244         *)
245             die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
246     esac
247
248     # Pull the UUID for this node out of the map.
249     UUID=$(awk "\$1 == $ip_offset {print \$2}" $uuid_map)
250     
251     mkdir -p tmp
252
253     echo "Creating $NAME.xml"
254     substitute_vars $template_file tmp/$NAME.xml
255     
256     # install the XML file
257     $VIRSH undefine $NAME > /dev/null 2>&1 || true
258     $VIRSH define tmp/$NAME.xml
259 }
260
261 create_node_configure_image ()
262 {
263     local disk="$1"
264     local type="$2"
265
266     diskimage mount "$disk"
267     setup_base "$type"
268     diskimage unmount
269 }
270
271 # Provides an easy way of removing nodes from $NODE.
272 create_node_null () {
273     :
274 }
275
276 # Uses: CLUSTER, NAME, NETWORKS, FIRSTIP, ip_offset
277 make_network_map ()
278 {
279     network_map="tmp/network_map.$NAME"
280
281     if [ -n "$CLUSTER" ] ; then
282         local md5=$(echo "$CLUSTER" | md5sum)
283         local nh=$(printf "%02x" $ip_offset)
284         local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
285     else
286         local mac_prefix="02:42:42:00:00:"
287     fi
288
289     local n
290     local count=1
291     for n in $NETWORKS ; do
292         local ch=$(printf "%02x" $count)
293         local mac="${mac_prefix}${ch}"
294
295         set -- ${n//,/ }
296         local ip_bits="$1" ; shift
297         local dev="$1" ; shift
298         local opts="$*"
299
300         local net="${ip_bits%/*}"
301         local netname="acnet_${net//./_}"
302
303         local ip="${net%.*}.${IPNUM}"
304         local mask="255.255.255.0"
305         echo "${netname} ${dev} ${ip} ${mask} ${mac} ${opts}"
306         count=$(($count + 1))
307     done >"$network_map"
308 }
309
310 ##############################
311
312 hack_nodes_functions=
313
314 expand_nodes () {
315     # Expand out any abbreviations in NODES.
316     local ns=""
317     local n
318     for n in $NODES ; do
319         local t="${n%:*}"
320         local ips="${n#*:}"
321         case "$ips" in
322             *,*)
323                 local i
324                 for i in ${ips//,/ } ; do
325                     ns="${ns}${ns:+ }${t}:${i}"
326                 done
327                 ;;
328             *-*)
329                 local i
330                 for i in $(seq ${ips/-/ }) ; do
331                     ns="${ns}${ns:+ }${t}:${i}"
332                 done
333                 ;;
334             *)
335                 ns="${ns}${ns:+ }${n}"
336         esac
337     done
338     NODES="$ns"
339
340     # Apply nodes hacks.  Some of this is about backward compatibility
341     # but the hacks also fill in the node names and whether they're
342     # part of the CTDB cluster.  The order is the order that
343     # configuration modules register their hacks.
344     run_hooks hack_nodes_functions
345
346     if [ -n "$NUMNODES" ] ; then
347         # Attempt to respect NUMNODES.  Reduce the number of CTDB
348         # nodes to NUMNODES.
349         local numnodes=$NUMNODES
350
351         hack_filter ()
352         {
353             if [ "$ctdb_node" = 1 ] ; then
354                 if [ $numnodes -gt 0 ] ; then
355                     numnodes=$(($numnodes - 1))
356                 else
357                     node_type="null"
358                     ctdb_node=0
359                 fi
360             fi
361         }
362
363         hack_all_nodes_with hack_filter
364                         
365         [ $numnodes -gt 0 ] && \
366             die "Can't not use NUMNODES to increase the number of nodes over that specified by NODES.  You need to set NODES instead - please read the documentation."
367     fi
368     
369     # Check IP addresses for duplicates.
370     local ip_offsets=":"
371     # This function doesn't modify anything...
372     get_ip_offset ()
373     {
374         [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
375             die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
376         ip_offsets="${ip_offsets}${ip_offset}:"
377     }
378     hack_all_nodes_with get_ip_offset
379 }
380
381 ##############################
382
383 sanity_check_cluster_name ()
384 {
385     [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
386         die "Cluster names should be restricted to the characters A-Za-z0-9.  \
387 Some cluster filesystems have problems with other characters."
388 }
389
390 hosts_file=
391
392 common_nodelist_hacking ()
393 {
394     # Rework the NODES list
395     expand_nodes
396
397     # Build /etc/hosts and hack the names of the ctdb nodes
398     hosts_line_hack_name ()
399     {
400         # Ignore nodes without names (e.g. "null")
401         [ "$node_type" != "null" -a -n "$name" ] || return 0
402
403         local sname=""
404         local hosts_line
405         local ip_addr="${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
406         
407         if [ "$ctdb_node" = 1 ] ; then
408             num_ctdb_nodes=$(($num_ctdb_nodes + 1))
409             sname="${CLUSTER}n${num_ctdb_nodes}"
410             hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
411             name="$sname"
412         else
413             hosts_line="$ip_addr ${name}.${ld} $name"
414         fi
415
416         # This allows you to add a function to your configuration file
417         # to modify hostnames (and other aspects of nodes).  This
418         # function can access/modify $name (the existing name),
419         # $node_type and $ctdb_node (1, if the node is a member of the
420         # CTDB cluster, 0 otherwise).
421         if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
422             local old_name="$name"
423             $HOSTNAME_HACKING_FUNCTION
424             if [ "$name" != "$old_name" ] ; then
425                 hosts_line="$ip_addr ${name}.${ld} $name"
426             fi
427         fi
428
429         echo "$hosts_line"
430     }
431     hosts_file="tmp/hosts.$CLUSTER"
432     {
433         local num_ctdb_nodes=0
434         local ld=$(echo $DOMAIN | tr A-Z a-z)
435         echo "# autocluster $CLUSTER"
436         hack_all_nodes_with hosts_line_hack_name
437         echo
438     } >$hosts_file
439
440     # Build /etc/ctdb/nodes
441     ctdb_nodes_line ()
442     {
443         [ "$ctdb_node" = 1 ] || return 0
444         echo "${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
445         num_nodes=$(($num_nodes + 1))
446     }
447     nodes_file="tmp/nodes.$CLUSTER"
448     local num_nodes=0
449     hack_all_nodes_with ctdb_nodes_line >$nodes_file
450     : "${NUMNODES:=${num_nodes}}"  # Set $NUMNODES if necessary
451
452     # Build UUID map
453     uuid_map="tmp/uuid_map.$CLUSTER"
454     uuid_map_line ()
455     {
456         echo "${ip_offset} $(uuidgen) ${node_type}"
457     }
458     hack_all_nodes_with uuid_map_line >$uuid_map
459 }
460
461 create_cluster_hooks=
462 cluster_created_hooks=
463
464 create_cluster ()
465 {
466     CLUSTER="$1"
467
468     sanity_check_cluster_name
469
470     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
471
472     # Run hooks before doing anything else.
473     run_hooks create_cluster_hooks
474
475     common_nodelist_hacking
476
477     for_each_node call_func create_node
478
479     echo "Cluster $CLUSTER created"
480     echo ""
481
482     run_hooks cluster_created_hooks
483 }
484
485 cluster_created_hosts_message ()
486 {
487     echo "You may want to add this to your /etc/hosts file:"
488     cat $hosts_file
489 }
490
491 register_hook cluster_created_hooks cluster_created_hosts_message
492
493 create_one_node ()
494 {
495     CLUSTER="$1"
496     local single_node_ip_offset="$2"
497
498     sanity_check_cluster_name
499
500     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
501
502     common_nodelist_hacking
503
504     for n in $NODES ; do
505         set -- $(IFS=: ; echo $n)
506         [ $single_node_ip_offset -eq $2 ] || continue
507         call_func create_node "$@"
508         
509         echo "Requested node created"
510         echo ""
511         echo "You may want to update your /etc/hosts file:"
512         cat $hosts_file
513         
514         break
515     done
516 }
517
518 ###############################
519 # test the proxy setup
520 test_proxy() {
521     export http_proxy=$WEBPROXY
522     wget -O /dev/null $INSTALL_SERVER || \
523         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
524     echo "Proxy OK"
525 }
526
527 ###################
528
529 kickstart_floppy_create_hooks=
530
531 # create base image
532 create_base()
533 {
534     local NAME="$BASENAME"
535     local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
536     run_hooks hack_disk_hooks "base"
537
538     mkdir -p $KVMLOG
539
540     echo "Testing WEBPROXY $WEBPROXY"
541     test_proxy
542
543     local di="$DISK"
544     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
545         di=$(readlink "$DISK")
546     fi
547     rm -f "$di"
548     local di_dirname="${di%/*}"
549     mkdir -p "$di_dirname"
550
551     echo "Creating the disk"
552     qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
553
554     rm -rf tmp
555     mkdir -p mnt tmp tmp/ISO
556
557     setup_timezone
558
559     make_network_map
560
561     echo "Creating kickstart file from template"
562     substitute_vars "$KICKSTART" "tmp/ks.cfg"
563
564     if [ $INSTALLKEY = "--skip" ]; then
565         cat <<EOF
566 --------------------------------------------------------------------------------------
567 WARNING: You have not entered an install key. Some RHEL packages will not be installed.
568
569 Please enter a valid RHEL install key in your config file like this:
570
571   INSTALLKEY="1234-5678-0123-4567"
572
573 The install will continue without an install key in 5 seconds
574 --------------------------------------------------------------------------------------
575 EOF
576         sleep 5
577     fi
578
579     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
580     case "$ISO" in
581         (/*) : ;;
582         (*) ISO="${ISO_DIR}/${ISO}"
583     esac
584     
585     echo "Creating kickstart floppy"
586     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
587     mkdosfs tmp/floppy.img
588     mount -o loop -t msdos tmp/floppy.img mnt
589     cp tmp/ks.cfg mnt
590     mount -o loop,ro $ISO tmp/ISO
591     
592     echo "Setting up bootloader"
593     cp tmp/ISO/isolinux/isolinux.bin tmp
594     cp tmp/ISO/isolinux/vmlinuz tmp
595     cp tmp/ISO/isolinux/initrd.img tmp
596
597     run_hooks kickstart_floppy_create_hooks
598
599     umount tmp/ISO
600     umount mnt
601
602     UUID=`uuidgen`
603
604     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
605
606     rm -f $KVMLOG/serial.$NAME
607
608     # boot the install CD
609     $VIRSH create tmp/$NAME.xml
610
611     echo "Waiting for install to start"
612     sleep 2
613     
614     # wait for the install to finish
615     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
616         $VIRSH destroy $NAME
617         die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
618 You may need to increase the value of CREATE_BASE_TIMEOUT.
619 Alternatively, the install might have completed but KS_DONE_MESSAGE
620 (currently \"${KS_DONE_MESSAGE}\")
621 may not have matched anything at the end of the kickstart output."
622     fi
623     
624     $VIRSH destroy $NAME
625
626     ls -l $DISK
627     cat <<EOF
628
629 Install finished, base image $DISK created
630
631 You may wish to run
632    chattr +i $DISK
633 To ensure that this image does not change
634
635 Note that the root password has been set to $ROOTPASSWORD
636
637 EOF
638 }
639
640 ###############################
641 # boot the base disk
642 boot_base() {
643     rm -rf tmp
644     mkdir -p tmp
645
646     NAME="$BASENAME"
647     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
648
649     IPNUM=$FIRSTIP
650
651     make_network_map
652
653     CLUSTER="base"
654
655     diskimage mount $DISK
656     setup_base
657     diskimage unmount
658
659     UUID=`uuidgen`
660     
661     echo "Creating $NAME.xml"
662     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
663     
664     # boot the base system
665     $VIRSH create tmp/$NAME.xml
666 }
667
668 ######################################################################
669
670 # Updating a disk image...
671
672 diskimage ()
673 {
674     local func="$1"
675     shift
676     call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
677 }
678
679 # setup the files from $BASE_TEMPLATES/, substituting any variables
680 # based on the config
681 copy_base_dir_substitute_templates ()
682 {
683     local dir="$1"
684
685     local d="$BASE_TEMPLATES/$dir"
686     [ -d "$d" ] || return 0
687
688     local f
689     for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
690         f="${f#./}" # remove leading "./" for clarity
691         if [ -d "$d/$f" ]; then
692             # Don't chmod existing directory
693             if diskimage is_directory "/$f" ; then
694                 continue
695             fi
696             diskimage mkdir_p "/$f"
697         else
698             echo " Install: $f"
699             diskimage substitute_vars "$d/$f" "/$f"
700         fi
701         diskimage chmod_reference "$d/$f" "/$f"
702     done
703 }
704
705 setup_base_hooks=
706
707 setup_base_ssh_keys ()
708 {
709     # this is needed as git doesn't store file permissions other
710     # than execute
711     # Note that we protect the wildcards from the local shell.
712     diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
713     diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
714     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
715        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
716        diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
717     fi
718     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
719        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
720        diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
721     fi
722 }
723
724 register_hook setup_base_hooks setup_base_ssh_keys
725
726 setup_base_grub_conf ()
727 {
728     echo "Adjusting grub.conf"
729     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
730     diskimage sed "/boot/grub/grub.conf" \
731         -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
732         -e "s/ nodmraid//" -e "s/ nompath//"  \
733         -e "s/quiet/noapic divider=10${o:+ }${o}/g"
734 }
735
736 register_hook setup_base_hooks setup_base_grub_conf
737
738 setup_base()
739 {
740     local type="$1"
741
742     umask 022
743     echo "Copy base files"
744     copy_base_dir_substitute_templates "all"
745     if [ -n "$type" ] ; then
746         copy_base_dir_substitute_templates "$type"
747     fi
748
749     run_hooks setup_base_hooks
750 }
751
752 # setup various networking components
753 setup_network()
754 {
755     # This avoids doing anything when we're called from boot_base().
756     if [ -z "$hosts_file" ] ; then
757         echo "Skipping network-related setup"
758         return
759     fi
760
761     echo "Setting up networks"
762     diskimage append_text_file "$hosts_file" "/etc/hosts"
763
764     echo "Setting up /etc/ctdb/nodes"
765     diskimage mkdir_p "/etc/ctdb"
766     diskimage put "$nodes_file" "/etc/ctdb/nodes"
767
768     [ "$WEBPROXY" = "" ] || {
769         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
770     }
771
772     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
773         echo "Enabling nfs mount of $NFSSHARE"
774         diskimage mkdir_p "$NFS_MOUNTPOINT"
775         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
776     fi
777
778     diskimage mkdir_p "/etc/yum.repos.d"
779     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
780
781     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
782
783     echo "Setting up network interfaces: "
784     local netname dev ip mask mac opts
785     while read netname dev ip mask mac opts; do
786         echo "  $dev"
787         cat <<EOF | \
788             diskimage substitute_vars \
789             - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
790 DEVICE=$dev
791 ONBOOT=yes
792 TYPE=Ethernet
793 IPADDR=$ip
794 NETMASK=$mask
795 HWADDR=$mac
796 EOF
797     done <"$network_map"
798 }
799
800 register_hook setup_base_hooks setup_network
801
802 setup_timezone() {
803     [ -z "$TIMEZONE" ] && {
804         [ -r /etc/timezone ] && {
805             TIMEZONE=`cat /etc/timezone`
806         }
807         [ -r /etc/sysconfig/clock ] && {
808             . /etc/sysconfig/clock
809             TIMEZONE="$ZONE"
810         }
811         TIMEZONE="${TIMEZONE// /_}"
812     }
813     [ -n "$TIMEZONE" ] || \
814         die "Unable to determine TIMEZONE - please set in config"
815 }
816
817 # substite a set of variables of the form @@XX@@ for the shell
818 # variables $XX in a file.
819 #
820 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
821 # contain a filename whose contents are substituted, with variable
822 # substitution applied to those contents.  If filename starts with '|'
823 # it is a command instead - however, quoting is extremely fragile.
824 substitute_vars() {(
825         infile="${1:-/dev/null}" # if empty then default to /dev/null
826         outfile="$2" # optional
827
828         tmp_out=$(mktemp)
829         cat "$infile" >"$tmp_out"
830
831         # Handle any indirects by looping until nothing changes.
832         # However, only handle 10 levels of recursion.
833         count=0
834         while : ; do
835             if ! _substitute_vars "$tmp_out" "@@@" ; then
836                 rm -f "$tmp_out"
837                 die "Failed to expand template $infile"
838             fi
839
840             # No old version of file means no changes made.
841             if [ ! -f "${tmp_out}.old" ] ; then
842                 break
843             fi
844
845             rm -f "${tmp_out}.old"
846
847             count=$(($count + 1))
848             if [ $count -ge 10 ] ; then
849                 rm -f "$tmp_out"
850                 die "Recursion too deep in $infile - only 10 levels allowed!"
851             fi
852         done
853
854         # Now regular variables.
855         if ! _substitute_vars "$tmp_out" "@@" ; then
856             rm -f "$tmp_out"
857             die "Failed to expand template $infile"
858         fi
859         rm -f "${tmp_out}.old"
860
861         if [ -n "$outfile" ] ; then
862             mv "$tmp_out" "$outfile"
863         else
864             cat "$tmp_out"
865             rm -f "$tmp_out"
866         fi
867 )}
868
869
870 # Delimiter @@ means to substitute contents of variable.
871 # Delimiter @@@ means to substitute contents of file named by variable.
872 # @@@ supports leading '|' in variable value, which means to excute a
873 # command.
874 _substitute_vars() {(
875         tmp_out="$1"
876         delimiter="${2:-@@}"
877
878         # Get the list of variables used in the template.  The grep
879         # gets rid of any blank lines and lines with extraneous '@'s
880         # next to template substitutions.
881         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
882             grep '^[A-Z0-9_][A-Z0-9_]*$' |
883             sort -u)
884
885         tmp=$(mktemp)
886         for v in $VARS; do
887             # variable variables are fun .....
888             [ "${!v+x}" ] || {
889                 rm -f $tmp
890                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
891             }
892             s=${!v}
893
894             if [ "$delimiter" = "@@@" ] ; then
895                 f=${s:-/dev/null}
896                 c="${f#|}" # Is is a command, signified by a leading '|'?
897                 if [ "$c" = "$f" ] ; then
898                     # No leading '|', cat file.
899                     s=$(cat -- "$f")
900                     [ $? -eq 0 ] || {
901                         rm -f $tmp
902                         die "Could not substitute contents of file $f"
903                     }
904                 else
905                     # Leading '|', execute command.
906                     # Quoting problems here - using eval "$c" doesn't help.
907                     s=$($c)
908                     [ $? -eq 0 ] || {
909                         rm -f $tmp
910                         die "Could not execute command $c"
911                     }
912                 fi
913             fi
914
915             # escape some pesky chars
916             # This first one can be too slow if done using a bash
917             # variable pattern subsitution.
918             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
919             s=${s//#/\\#}
920             s=${s//&/\\&}
921             echo "s#${delimiter}${v}${delimiter}#${s}#g"
922         done > $tmp
923
924         # Get the in-place sed to make a backup of the old file.
925         # Remove the backup if it is the same as the resulting file -
926         # this acts as a flag to the caller that no changes were made.
927         sed -i.old -f $tmp "$tmp_out"
928         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
929             rm -f "${tmp_out}.old"
930         fi
931
932         rm -f $tmp
933 )}
934
935 check_command() {
936     which $1 > /dev/null || die "Please install $1 to continue"
937 }
938
939 # Set a variable if it isn't already set.  This allows environment
940 # variables to override default config settings.
941 defconf() {
942     local v="$1"
943     local e="$2"
944
945     [ "${!v+x}" ] || eval "$v=\"$e\""
946 }
947
948 load_config () {
949     local i
950
951     for i in "${installdir}/config.d/"*.defconf ; do
952         . "$i"
953     done
954 }
955
956 # Print the list of config variables defined in config.d/.
957 get_config_options () {( # sub-shell for local declaration of defconf()
958         local options=
959         defconf() { options="$options $1" ; }
960         load_config
961         echo $options
962 )}
963
964 # Produce a list of long options, suitable for use with getopt, that
965 # represent the config variables defined in config.d/.
966 getopt_config_options () {
967     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
968     echo "${x// /:,}:"
969 }
970
971 # Unconditionally set the config variable associated with the given
972 # long option.
973 setconf_longopt () {
974     local longopt="$1"
975     local e="$2"
976
977     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
978     # unset so defconf will set it
979     eval "unset $v"
980     defconf "$v" "$e"
981 }
982
983 # Dump all of the current config variables.
984 dump_config() {
985     local o
986     for o in $(get_config_options) ; do
987         echo "${o}=\"${!o}\""
988     done
989     exit 0
990 }
991
992 # $COLUMNS is set in interactive bash shells.  It probably isn't set
993 # in this shell, so let's set it if it isn't.
994 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
995 : ${COLUMNS:=80}
996 export COLUMNS
997
998 # Print text assuming it starts after other text in $startcol and
999 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1000 # Long "words" will extend past $COLUMNS - 2.
1001 fill_text() {
1002     local startcol="$1"
1003     local text="$2"
1004
1005     local width=$(($COLUMNS - 2 - $startcol))
1006     [ $width -lt 0 ] && width=$((78 - $startcol))
1007
1008     local out=""
1009
1010     local padding
1011     if [ $startcol -gt 0 ] ; then
1012         padding=$(printf "\n%${startcol}s" " ")
1013     else
1014         padding="
1015 "
1016     fi
1017
1018     while [ -n "$text" ] ; do
1019         local orig="$text"
1020
1021         # If we already have output then arrange padding on the next line.
1022         [ -n "$out" ] && out="${out}${padding}"
1023
1024         # Break the text at $width.
1025         out="${out}${text:0:${width}}"
1026         text="${text:${width}}"
1027
1028         # If we have left over text then the line break may be ugly,
1029         # so let's check and try to break it on a space.
1030         if [ -n "$text" ] ; then
1031             # The 'x's stop us producing a special character like '(',
1032             # ')' or '!'.  Yuck - there must be a better way.
1033             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1034                 # We didn't break on a space.  Arrange for the
1035                 # beginning of the broken "word" to appear on the next
1036                 # line but not if it will make us loop infinitely.
1037                 if [ "${orig}" != "${out##* }${text}" ] ; then
1038                     text="${out##* }${text}"
1039                     out="${out% *}"
1040                 else
1041                     # Hmmm, doing that would make us loop, so add the
1042                     # rest of the word from the remainder of the text
1043                     # to this line and let it extend past $COLUMNS - 2.
1044                     out="${out}${text%% *}"
1045                     if [ "${text# *}" != "$text" ] ; then
1046                         # Remember the text after the next space for next time.
1047                         text="${text# *}"
1048                     else
1049                         # No text after next space.
1050                         text=""
1051                     fi
1052                 fi
1053             else
1054                 # We broke on a space.  If it will be at the beginning
1055                 # of the next line then remove it.
1056                 text="${text# }"
1057             fi
1058         fi
1059     done
1060
1061     echo "$out"
1062 }
1063
1064 # Display usage text, trying these approaches in order.
1065 # 1. See if it all fits on one line before $COLUMNS - 2.
1066 # 2. See if splitting before the default value and indenting it
1067 #    to $startcol means that nothing passes $COLUMNS - 2.
1068 # 3. Treat the message and default value as a string and just us fill_text()
1069 #    to format it. 
1070 usage_display_text () {
1071     local startcol="$1"
1072     local desc="$2"
1073     local default="$3"
1074     
1075     local width=$(($COLUMNS - 2 - $startcol))
1076     [ $width -lt 0 ] && width=$((78 - $startcol))
1077
1078     default="(default \"$default\")"
1079
1080     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1081         echo "${desc} ${default}"
1082     else
1083         local padding=$(printf "%${startcol}s" " ")
1084
1085         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1086             echo "$desc"
1087             echo "${padding}${default}"
1088         else
1089             fill_text $startcol "${desc} ${default}"
1090         fi
1091     fi
1092 }
1093
1094 # Display usage information for long config options.
1095 usage_smart_display () {( # sub-shell for local declaration of defconf()
1096         local startcol=33
1097
1098         defconf() {
1099             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1100
1101             printf "     --%-25s " "${longopt}=${3}"
1102
1103             usage_display_text $startcol "$4" "$2"
1104         }
1105
1106         "$@"
1107 )}
1108
1109
1110 # Display usage information for long config options.
1111 usage_config_options (){
1112     usage_smart_display load_config
1113 }
1114
1115 list_releases () {
1116     local releases=$(cd $installdir/releases && echo *.release)
1117     releases="${releases//.release}"
1118     releases="${releases// /\", \"}"
1119     echo "\"$releases\""
1120 }
1121
1122 ######################################################################
1123
1124 post_config_hooks=
1125
1126 ######################################################################
1127
1128 load_config
1129
1130 ############################
1131 # parse command line options
1132 long_opts=$(getopt_config_options)
1133 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1134 [ $? != 0 ] && usage
1135
1136 use_default_config=true
1137
1138 # We do 2 passes of the options.  The first time we just handle usage
1139 # and check whether -c is being used.
1140 eval set -- "$getopt_output"
1141 while true ; do
1142     case "$1" in
1143         -c) shift 2 ; use_default_config=false ;;
1144         -e) shift 2 ;;
1145         -E) shift 2 ;;
1146         --) shift ; break ;;
1147         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1148         --dump|-x) shift ;;
1149         -h|--help) usage ;; # Usage should be shown here for real defaults.
1150         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1151         *) usage ;; # shouldn't happen, so this is reasonable.
1152     esac
1153 done
1154
1155 config="./config"
1156 $use_default_config && [ -r "$config" ] && . "$config"
1157
1158 eval set -- "$getopt_output"
1159
1160 while true ; do
1161     case "$1" in
1162         # force at least ./local_file to avoid accidental file from $PATH
1163         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1164         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1165         -E) eval "$2" ; shift 2 ;;
1166         -x) set -x; shift ;;
1167         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1168         --) shift ; break ;;
1169         -h|--help) usage ;; # Redundant.
1170         --*)
1171             # Putting --opt1|opt2|... into a variable and having case
1172             # match against it as a pattern doesn't work.  The | is
1173             # part of shell syntax, so we need to do this.  Look away
1174             # now to stop your eyes from bleeding! :-)
1175             x=",${long_opts}" # Now each option is surrounded by , and :
1176             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1177                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1178                 setconf_longopt "$1" "$2"; shift 2
1179             else
1180                 usage
1181             fi
1182             ;;
1183         *) usage ;; # shouldn't happen, so this is reasonable.
1184     esac
1185 done
1186
1187 run_hooks post_config_hooks 
1188
1189 # catch errors
1190 set -e
1191 set -E
1192 trap 'es=$?; 
1193       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1194       exit $es' ERR
1195
1196 # check for needed programs 
1197 check_command expect
1198
1199 [ $# -lt 1 ] && usage
1200
1201 command="$1"
1202 shift
1203
1204 case $command in
1205     create)
1206         type=$1
1207         shift
1208         case $type in
1209             base)
1210                 [ $# != 0 ] && usage
1211                 create_base
1212                 ;;
1213             cluster)
1214                 [ $# != 1 ] && usage
1215                 create_cluster "$1"
1216                 ;;
1217             node)
1218                 [ $# != 2 ] && usage
1219                 create_one_node "$1" "$2"
1220                 ;;
1221             *)
1222                 usage;
1223                 ;;
1224         esac
1225         ;;
1226     mount)
1227         [ $# != 1 ] && usage
1228         diskimage mount "$1"
1229         ;;
1230     unmount|umount)
1231         [ $# != 0 ] && usage
1232         diskimage unmount
1233         ;;
1234     bootbase)
1235         boot_base;
1236         ;;
1237     testproxy)
1238         test_proxy;
1239         ;;
1240     *)
1241         usage;
1242         ;;
1243 esac