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