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