Sensible handling for YUM repositories.
[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()
620 {
621     local type="$1"
622
623     umask 022
624     echo "Copy base files"
625     copy_base_dir_substitute_templates "all"
626     if [ -n "$type" ] ; then
627         copy_base_dir_substitute_templates "$type"
628     fi
629
630     # this is needed as git doesn't store file permissions other
631     # than execute
632     chmod 600 mnt/etc/ssh/*key mnt/root/.ssh/*
633     chmod 700 mnt/etc/ssh mnt/root/.ssh mnt/root
634     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
635        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
636        cat "$HOME/.ssh/id_rsa.pub" >> mnt/root/.ssh/authorized_keys
637     fi
638     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
639        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
640        cat "$HOME/.ssh/id_dsa.pub" >> mnt/root/.ssh/authorized_keys
641     fi
642     echo "Adjusting grub.conf"
643     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
644     sed -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
645         -e "s/ nodmraid//" -e "s/ nompath//"  \
646         -e "s/quiet/noapic divider=10${o:+ }${o}/g" mnt/boot/grub/grub.conf -i.org
647 }
648
649 # setup various networking components
650 setup_network() {
651     echo "Setting up networks"
652
653     cat $hosts_file >>mnt/etc/hosts
654
655     echo "Setting up /etc/ctdb/nodes"
656     mkdir -p mnt/etc/ctdb
657     cp $nodes_file mnt/etc/ctdb/nodes
658
659     [ "$WEBPROXY" = "" ] || {
660         echo "export http_proxy=$WEBPROXY" >> mnt/etc/bashrc
661     }
662
663     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
664         echo "Enabling nfs mount of $NFSSHARE"
665         mkdir -p "mnt$NFS_MOUNTPOINT"
666         echo "$NFSSHARE $NFS_MOUNTPOINT nfs intr" >> mnt/etc/fstab
667     fi
668
669     mkdir -p mnt/etc/yum.repos.d
670     echo '@@@YUM_TEMPLATE@@@' | substitute_vars - > mnt/etc/yum.repos.d/autocluster.repo
671 }
672
673 setup_timezone() {
674     [ -z "$TIMEZONE" ] && {
675         [ -r /etc/timezone ] && {
676             TIMEZONE=`cat /etc/timezone`
677         }
678         [ -r /etc/sysconfig/clock ] && {
679             . /etc/sysconfig/clock
680             TIMEZONE="$ZONE"
681         }
682         TIMEZONE="${TIMEZONE// /_}"
683     }
684     [ -n "$TIMEZONE" ] || \
685         die "Unable to determine TIMEZONE - please set in config"
686 }
687
688 # substite a set of variables of the form @@XX@@ for the shell
689 # variables $XX in a file.
690 #
691 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
692 # contain a filename whose contents are substituted, with variable
693 # substitution applied to those contents.  If filename starts with '|'
694 # it is a command instead - however, quoting is extremely fragile.
695 substitute_vars() {(
696         infile="${1:-/dev/null}" # if empty then default to /dev/null
697         outfile="$2" # optional
698
699         instring=$(cat $infile)
700
701         # Handle any indirects by looping until nothing changes.
702         # However, only handle 10 levels of recursion.
703         count=0
704         while : ; do
705             outstring=$(_substitute_vars "$instring" "@@@")
706             [ $? -eq 0 ] || die "Failed to expand template $infile"
707
708             [ "$instring" = "$outstring" ] && break
709
710             count=$(($count + 1))
711             [ $count -lt 10 ] || \
712                 die "Recursion too deep in $infile - only 10 levels allowed!"
713
714             instring="$outstring"
715         done
716
717         # Now regular variables.
718         outstring=$(_substitute_vars "$instring" "@@")
719         [ $? -eq 0 ] || die "Failed to expand template $infile"
720
721         if [ -n "$outfile" ] ; then
722             echo "$outstring" > "$outfile"
723         else
724             echo "$outstring"
725         fi
726 )}
727
728
729 # Delimiter @@ means to substitute contents of variable.
730 # Delimiter @@@ means to substitute contents of file named by variable.
731 # @@@ supports leading '|' in variable value, which means to excute a
732 # command.
733 _substitute_vars() {(
734         instring="$1"
735         delimiter="${2:-@@}"
736
737         # get the list of variables used in the template
738         VARS=`echo "$instring" |
739               tr -cs "A-Z0-9_$delimiter" '\012' | 
740               sort -u |
741               sed -n -e "s#^${delimiter}\(.*\)${delimiter}\\$#\1#p"`
742
743         tmp=$(mktemp)
744         for v in $VARS; do
745             # variable variables are fun .....
746             [ "${!v+x}" ] || {
747                 rm -f $tmp
748                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
749             }
750             s=${!v}
751
752             if [ "$delimiter" = "@@@" ] ; then
753                 f=${s:-/dev/null}
754                 c="${f#|}" # Is is a command, signified by a leading '|'?
755                 if [ "$c" = "$f" ] ; then
756                     # No leading '|', cat file.
757                     s=$(cat -- "$f")
758                     [ $? -eq 0 ] || {
759                         rm -f $tmp
760                         die "Could not substitute contents of file $f"
761                     }
762                 else
763                     # Leading '|', execute command.
764                     # Quoting problems here - using eval "$c" doesn't help.
765                     s=$($c)
766                     [ $? -eq 0 ] || {
767                         rm -f $tmp
768                         die "Could not execute command $c"
769                     }
770                 fi
771             fi
772
773             # escape some pesky chars
774             s=${s//
775 /\\n}
776             s=${s//#/\\#}
777             s=${s//&/\\&}
778             echo "s#${delimiter}${v}${delimiter}#${s}#g"
779         done > $tmp
780
781         echo "$instring" | sed -f $tmp
782
783         rm -f $tmp
784 )}
785
786 check_command() {
787     which $1 > /dev/null || die "Please install $1 to continue"
788 }
789
790 # Set a variable if it isn't already set.  This allows environment
791 # variables to override default config settings.
792 defconf() {
793     local v="$1"
794     local e="$2"
795
796     [ "${!v+x}" ] || eval "$v=\"$e\""
797 }
798
799 load_config () {
800     local i
801
802     for i in "${installdir}/config.d/"*.defconf ; do
803         . "$i"
804     done
805 }
806
807 # Print the list of config variables defined in config.d/.
808 get_config_options () {( # sub-shell for local declaration of defconf()
809         local options=
810         defconf() { options="$options $1" ; }
811         load_config
812         echo $options
813 )}
814
815 # Produce a list of long options, suitable for use with getopt, that
816 # represent the config variables defined in config.d/.
817 getopt_config_options () {
818     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
819     echo "${x// /:,}:"
820 }
821
822 # Unconditionally set the config variable associated with the given
823 # long option.
824 setconf_longopt () {
825     local longopt="$1"
826     local e="$2"
827
828     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
829     # unset so defconf will set it
830     eval "unset $v"
831     defconf "$v" "$e"
832 }
833
834 # Dump all of the current config variables.
835 dump_config() {
836     local o
837     for o in $(get_config_options) ; do
838         echo "${o}=\"${!o}\""
839     done
840     exit 0
841 }
842
843 # $COLUMNS is set in interactive bash shells.  It probably isn't set
844 # in this shell, so let's set it if it isn't.
845 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
846 : ${COLUMNS:=80}
847 export COLUMNS
848
849 # Print text assuming it starts after other text in $startcol and
850 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
851 # Long "words" will extend past $COLUMNS - 2.
852 fill_text() {
853     local startcol="$1"
854     local text="$2"
855
856     local width=$(($COLUMNS - 2 - $startcol))
857     [ $width -lt 0 ] && width=$((78 - $startcol))
858
859     local out=""
860
861     local padding
862     if [ $startcol -gt 0 ] ; then
863         padding=$(printf "\n%${startcol}s" " ")
864     else
865         padding="
866 "
867     fi
868
869     while [ -n "$text" ] ; do
870         local orig="$text"
871
872         # If we already have output then arrange padding on the next line.
873         [ -n "$out" ] && out="${out}${padding}"
874
875         # Break the text at $width.
876         out="${out}${text:0:${width}}"
877         text="${text:${width}}"
878
879         # If we have left over text then the line break may be ugly,
880         # so let's check and try to break it on a space.
881         if [ -n "$text" ] ; then
882             # The 'x's stop us producing a special character like '(',
883             # ')' or '!'.  Yuck - there must be a better way.
884             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
885                 # We didn't break on a space.  Arrange for the
886                 # beginning of the broken "word" to appear on the next
887                 # line but not if it will make us loop infinitely.
888                 if [ "${orig}" != "${out##* }${text}" ] ; then
889                     text="${out##* }${text}"
890                     out="${out% *}"
891                 else
892                     # Hmmm, doing that would make us loop, so add the
893                     # rest of the word from the remainder of the text
894                     # to this line and let it extend past $COLUMNS - 2.
895                     out="${out}${text%% *}"
896                     if [ "${text# *}" != "$text" ] ; then
897                         # Remember the text after the next space for next time.
898                         text="${text# *}"
899                     else
900                         # No text after next space.
901                         text=""
902                     fi
903                 fi
904             else
905                 # We broke on a space.  If it will be at the beginning
906                 # of the next line then remove it.
907                 text="${text# }"
908             fi
909         fi
910     done
911
912     echo "$out"
913 }
914
915 # Display usage text, trying these approaches in order.
916 # 1. See if it all fits on one line before $COLUMNS - 2.
917 # 2. See if splitting before the default value and indenting it
918 #    to $startcol means that nothing passes $COLUMNS - 2.
919 # 3. Treat the message and default value as a string and just us fill_text()
920 #    to format it. 
921 usage_display_text () {
922     local startcol="$1"
923     local desc="$2"
924     local default="$3"
925     
926     local width=$(($COLUMNS - 2 - $startcol))
927     [ $width -lt 0 ] && width=$((78 - $startcol))
928
929     default="(default \"$default\")"
930
931     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
932         echo "${desc} ${default}"
933     else
934         local padding=$(printf "%${startcol}s" " ")
935
936         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
937             echo "$desc"
938             echo "${padding}${default}"
939         else
940             fill_text $startcol "${desc} ${default}"
941         fi
942     fi
943 }
944
945 # Display usage information for long config options.
946 usage_smart_display () {( # sub-shell for local declaration of defconf()
947         local startcol=33
948
949         defconf() {
950             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
951
952             printf "     --%-25s " "${longopt}=${3}"
953
954             usage_display_text $startcol "$4" "$2"
955         }
956
957         "$@"
958 )}
959
960
961 # Display usage information for long config options.
962 usage_config_options (){
963     usage_smart_display load_config
964 }
965
966 list_releases () {
967     local releases=$(cd $installdir/releases && echo *.release)
968     releases="${releases//.release}"
969     releases="${releases// /\", \"}"
970     echo "\"$releases\""
971 }
972
973 with_release () {
974     local release="$1"
975
976     # This simply loads an extra config file from $installdir/releases
977     f="${installdir}/releases/${release}.release"
978     if [ -r "$f" ] ; then
979         . "$f"
980     else
981         echo "Unknown release \"${release}\" specified to --with-release"
982         printf "%-25s" "Supported releases are: "
983         # The 70 is lazy but it will do.
984         fill_text 25 "$(list_releases)"
985         exit 1
986     fi
987
988 }
989
990 has_public_addresses_DEFAULT ()
991 {
992     false
993 }
994
995 # Build public address configuration.
996 # * 1st public IP:  unless specified, last octet is $FIRSTIP + $PUBLIC_IP_OFFSET
997 # * Excluded nodes: unless specified via comma-separated list of IP offsets,
998 #                   nodes are excluded via their node types
999 # * Number of public addresses per interface is either specified or $NUMNODES.
1000 make_public_addresses () {
1001     local firstip="${1:-$(($FIRSTIP + $PUBLIC_IP_OFFSET))}"
1002     local excluded_nodes="$2" 
1003     local num_addrs="${3:-${NUMNODES}}"
1004
1005     # For delimiting matches.
1006     excluded_nodes="${excluded_nodes:+,}${excluded_nodes}${excluded_nodes:+,}"
1007     # Avoid spaces
1008     excluded_nodes="${excluded_nodes// /}"
1009
1010     make_public_addresses_for_node ()
1011     {
1012         [ "$ctdb_node" = 1 ] || return 0
1013
1014         echo "[/etc/ctdb/public_addresses:${name}.${DOMAIN}]"
1015
1016         if [ -n "$excluded_nodes" -a \
1017             "${excluded_nodes/,${ip_offset},}" = "$excluded_nodes" ] ||
1018             ([ -z "$excluded_nodes" ] &&
1019                 call_func has_public_addresses "$node_type") ; then
1020
1021             local e i
1022             for e in "1" "2" ; do
1023                 for i in $(seq $firstip $(($firstip + $num_addrs - 1))) ; do
1024                     if [ $i -gt 254 ] ; then
1025                         die "make_public_addresses: octet > 254 - consider setting PUBLIC_IP_OFFSET"
1026                     fi
1027                     printf "\t${IPBASE}.${e}.${i}/24 eth${e}\n"
1028                 done
1029             done            
1030         fi
1031         echo 
1032     }
1033     hack_all_nodes_with make_public_addresses_for_node
1034 }
1035
1036 ######################################################################
1037
1038 load_config
1039
1040 ############################
1041 # parse command line options
1042 long_opts=$(getopt_config_options)
1043 getopt_output=$(getopt -n autocluster -o "c:e:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1044 [ $? != 0 ] && usage
1045
1046 use_default_config=true
1047
1048 # We do 2 passes of the options.  The first time we just handle usage
1049 # and check whether -c is being used.
1050 eval set -- "$getopt_output"
1051 while true ; do
1052     case "$1" in
1053         -c) shift 2 ; use_default_config=false ;;
1054         -e) shift 2 ;;
1055         --) shift ; break ;;
1056         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1057         --dump|-x) shift ;;
1058         -h|--help) usage ;; # Usage should be shown here for real defaults.
1059         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1060         *) usage ;; # shouldn't happen, so this is reasonable.
1061     esac
1062 done
1063
1064 config="./config"
1065 $use_default_config && [ -r "$config" ] && . "$config"
1066
1067 eval set -- "$getopt_output"
1068
1069 while true ; do
1070     case "$1" in
1071         # force at least ./local_file to avoid accidental file from $PATH
1072         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1073         -e) eval "$2" ; exit ;;
1074         --with-release)
1075             with_release "$2"
1076             shift 2
1077             ;;
1078         -x) set -x; shift ;;
1079         --dump) dump_config ;;
1080         --) shift ; break ;;
1081         -h|--help) usage ;; # Redundant.
1082         --*)
1083             # Putting --opt1|opt2|... into a variable and having case
1084             # match against it as a pattern doesn't work.  The | is
1085             # part of shell syntax, so we need to do this.  Look away
1086             # now to stop your eyes from bleeding! :-)
1087             x=",${long_opts}" # Now each option is surrounded by , and :
1088             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1089                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1090                 setconf_longopt "$1" "$2"; shift 2
1091             else
1092                 usage
1093             fi
1094             ;;
1095         *) usage ;; # shouldn't happen, so this is reasonable.
1096     esac
1097 done
1098
1099 # catch errors
1100 set -e
1101 set -E
1102 trap 'es=$?; 
1103       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1104       exit $es' ERR
1105
1106 # check for needed programs 
1107 check_command nbd-client
1108 check_command expect
1109 check_command $QEMU_NBD
1110
1111 [ $# -lt 1 ] && usage
1112
1113 command="$1"
1114 shift
1115
1116 case $command in
1117     create)
1118         type=$1
1119         shift
1120         case $type in
1121             base)
1122                 [ $# != 0 ] && usage
1123                 create_base
1124                 ;;
1125             cluster)
1126                 [ $# != 1 ] && usage
1127                 create_cluster "$1"
1128                 ;;
1129             node)
1130                 [ $# != 2 ] && usage
1131                 create_one_node "$1" "$2"
1132                 ;;
1133             *)
1134                 usage;
1135                 ;;
1136         esac
1137         ;;
1138     mount)
1139         [ $# != 1 ] && usage
1140         mount_disk "$1"
1141         ;;
1142     unmount)
1143         [ $# != 0 ] && usage
1144         unmount_disk
1145         ;;
1146     bootbase)
1147         boot_base;
1148         ;;
1149     testproxy)
1150         test_proxy;
1151         ;;
1152     *)
1153         usage;
1154         ;;
1155 esac