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