dafc6058878aaa7d8c896e8b3cfb875e108acefe
[autocluster.git] / autocluster
1 #!/bin/bash
2 # main autocluster script
3 #
4 # Copyright (C) Andrew Tridgell  2008
5 # Copyright (C) Martin Schwenke  2008
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #   
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #   
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19
20 ##BEGIN-INSTALLDIR-MAGIC##
21 # There are better ways of doing this but not if you still want to be
22 # able to run straight out of a git tree.  :-)
23 if [ -f "$0" ]; then
24     autocluster="$0"
25 else
26     autocluster=$(which "$0")
27 fi
28 if [ -L "$autocluster" ] ; then
29     autocluster=$(readlink "$autocluster")
30 fi
31 installdir=$(dirname "$autocluster")
32 ##END-INSTALLDIR-MAGIC##
33
34 ####################
35 # show program usage
36 usage ()
37 {
38     cat <<EOF
39 Usage: autocluster [OPTION] ... <COMMAND>
40   options:
41      -c <file>                   specify config file (default is "config")
42      -e <expr>                   execute <expr> and exit
43      -E <expr>                   execute <expr> and continue
44      -x                          enable script debugging
45      --dump                      dump config settings and exit
46
47   configuration options:
48 EOF
49
50     usage_config_options
51
52     cat <<EOF
53
54   commands:
55      base [ create | boot ] ...
56
57      cluster [ build |
58                destroy | undefine |
59                create | update_hosts | boot | setup ] ...
60
61      create base
62            create a base image
63
64      create cluster [ CLUSTERNAME ]
65            create a full cluster
66
67      create node CLUSTERNAME IP_OFFSET
68            (re)create a single cluster node
69
70      mount DISK
71            mount a qemu disk on mnt/
72
73      unmount | umount
74            unmount a qemu disk from mnt/
75
76      bootbase
77            boot the base image
78 EOF
79     exit 1
80 }
81
82 ###############################
83
84 die () {
85     if [ "$no_sanity" = 1 ] ; then
86         fill_text 0 "WARNING: $*" >&2
87     else
88         fill_text 0 "ERROR: $*" >&2
89         exit 1
90     fi
91 }
92
93 announce ()
94 {
95     echo "######################################################################"
96     printf "# %-66s #\n" "$*"
97     echo "######################################################################"
98     echo ""
99 }
100
101 waitfor ()
102 {
103     local file="$1"
104     local msg="$2"
105     local timeout="$3"
106
107     local tmpfile=$(mktemp)
108
109     cat <<EOF >"$tmpfile"
110 spawn tail -n 10000 -f $file
111 expect -timeout $timeout -re "$msg"
112 EOF
113
114     export LANG=C
115     expect "$tmpfile"
116     rm -f "$tmpfile"
117
118     if ! grep -E "$msg" "$file" > /dev/null; then
119         echo "Failed to find \"$msg\" in \"$file\""
120         return 1
121     fi
122
123     return 0
124 }
125
126 ###############################
127
128 # Indirectly call a function named by ${1}_${2}
129 call_func () {
130     local func="$1" ; shift
131     local type="$1" ; shift
132
133     local f="${func}_${type}"
134     if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
135         "$f" "$@"
136     else
137         f="${func}_DEFAULT"
138         if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null  ; then
139             "$f" "$type" "$@"
140         else
141             die "No function defined for \"${func}\" \"${type}\""
142         fi
143     fi
144 }
145
146 # Note that this will work if you pass "call_func f" because the first
147 # element of the node tuple is the node type.  Nice...  :-)
148 for_each_node ()
149 {
150     local n
151     for n in $NODES ; do
152         "$@" $(IFS=: ; echo $n)
153     done
154 }
155
156 node_is_ctdb_node_DEFAULT ()
157 {
158     echo 0
159 }
160
161 hack_one_node_with ()
162 {
163     local filter="$1" ; shift
164
165     local node_type="$1"
166     local ip_offset="$2"
167     local name="$3"
168     local ctdb_node="$4"
169
170     $filter
171
172     local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
173     nodes="${nodes}${nodes:+ }${item}"
174 }
175
176 # This also gets used for non-filtering iteration.
177 hack_all_nodes_with ()
178 {
179     local filter="$1"
180
181     local nodes=""
182     for_each_node hack_one_node_with "$filter"
183     NODES="$nodes"
184 }
185
186 list_all_cluster_nodes ()
187 {
188     # Local function only defined in subshell
189     (
190         print_node_name ()
191         {
192             echo "$3"
193         }
194         for_each_node print_node_name
195     ) | sort
196 }
197
198 list_all_virsh_domains ()
199 {
200     local pattern="${CLUSTER_PATTERN:-${CLUSTER}[a-z]*[0-9]}"
201
202     local domains=$(virsh list --all | awk '{print $2}' | tail -n +3)
203     local d
204     for d in $domains ; do
205         case "$d" in
206             ($pattern) echo "$d" ;;
207         esac
208     done | sort
209 }
210
211 virsh_cluster ()
212 {
213     local command="$1"
214
215     local nodes=$(list_all_cluster_nodes)
216     local domains=$(list_all_virsh_domains)
217
218     if [ "$nodes" != "$domains" ] ; then
219         echo "WARNING: Found matching virsh domains that are not part of this cluster!"
220         echo
221     fi
222
223     local ret=0
224     local n
225     for n in $nodes ; do
226         virsh "$command" "$n" 2>&1 || ret=$?
227     done
228
229     return $ret
230 }
231
232 register_hook ()
233 {
234     local hook_var="$1"
235     local new_hook="$2"
236
237     eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
238 }
239
240 run_hooks ()
241 {
242     local hook_var="$1"
243     shift
244
245     local i
246     for i in ${!hook_var} ; do
247         $i "$@"
248     done
249 }
250
251 # Use with care, since this may clear some autocluster defaults.!
252 clear_hooks ()
253 {
254     local hook_var="$1"
255
256     eval "$hook_var=\"\""
257 }
258
259 ##############################
260
261 # These hooks are intended to customise the value of $DISK.  They have
262 # access to 1 argument ("base", "system", "shared") and the variables
263 # $VIRTBASE, $CLUSTER, $BASENAME (for "base"), $NAME (for "system"),
264 # $SHARED_DISK_NUM (for "shared").  A hook must be deterministic and
265 # should not be stateful, since they can be called multiple times for
266 # the same disk.
267 hack_disk_hooks=""
268
269 create_node_DEFAULT ()
270 {
271     local type="$1"
272     local ip_offset="$2"
273     local name="$3"
274     local ctdb_node="$4"
275
276     echo "Creating node \"$name\" (of type \"${type}\")"
277
278     create_node_COMMON "$name" "$ip_offset" "$type"
279 }
280
281 # common node creation stuff
282 create_node_COMMON ()
283 {
284     local NAME="$1"
285     local ip_offset="$2"
286     local type="$3"
287     local template_file="${4:-$NODE_TEMPLATE}"
288
289     if [ "$SYSTEM_DISK_FORMAT" != "qcow2" -a "$BASE_FORMAT" = "qcow2" ] ; then
290         die "Error: if BASE_FORMAT is \"qcow2\" then SYSTEM_DISK_FORMAT must also be \"qcow2\"."
291     fi
292
293     local IPNUM=$(($FIRSTIP + $ip_offset))
294     make_network_map
295
296     # Determine base image name.  We use $DISK temporarily to allow
297     # the path to be hacked.
298     local DISK="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
299     if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
300         DISK="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
301     fi
302     run_hooks hack_disk_hooks "base"
303     local base_disk="$DISK"
304
305     # Determine the system disk image name.
306     DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
307     run_hooks hack_disk_hooks "system"
308
309     local di="$DISK"
310     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
311         di=$(readlink "$DISK")
312     fi
313     rm -f "$di"
314     local di_dirname="${di%/*}"
315     mkdir -p "$di_dirname"
316
317     case "$SYSTEM_DISK_FORMAT" in
318         qcow2)
319             echo "Creating the disk..."
320             qemu-img create -b "$base_disk" -f qcow2 "$di"
321             create_node_configure_image "$DISK" "$type"
322             ;;
323         raw)
324             echo "Creating the disk..."
325             cp -v --sparse=always "$base_disk" "$di"
326             create_node_configure_image "$DISK" "$type"
327             ;;
328         reflink)
329             echo "Creating the disk..."
330             cp -v --reflink=always "$base_disk" "$di"
331             create_node_configure_image "$DISK" "$type"
332             ;;
333         mmclone)
334             echo "Creating the disk (using mmclone)..."
335             local base_snap="${base_disk}.snap"
336             [ -f "$base_snap" ] || mmclone snap "$base_disk" "$base_snap"
337             mmclone copy "$base_snap" "$di"
338             create_node_configure_image "$DISK" "$type"
339             ;;
340         none)
341             echo "Skipping disk image creation as requested"
342             ;;
343         *)
344             die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
345     esac
346
347     # Pull the UUID for this node out of the map.
348     UUID=$(awk "\$1 == $ip_offset {print \$2}" $uuid_map)
349     
350     mkdir -p tmp
351
352     echo "Creating $NAME.xml"
353     substitute_vars $template_file tmp/$NAME.xml
354     
355     # install the XML file
356     $VIRSH undefine $NAME > /dev/null 2>&1 || true
357     $VIRSH define tmp/$NAME.xml
358 }
359
360 create_node_configure_image ()
361 {
362     local disk="$1"
363     local type="$2"
364
365     diskimage mount "$disk"
366     setup_base "$type"
367     diskimage unmount
368 }
369
370 hack_network_map_hooks=""
371
372 # Uses: CLUSTER, NAME, NETWORKS, FIRSTIP, ip_offset
373 make_network_map ()
374 {
375     network_map="tmp/network_map.$NAME"
376
377     if [ -n "$CLUSTER" ] ; then
378         local md5=$(echo "$CLUSTER" | md5sum)
379         local nh=$(printf "%02x" $ip_offset)
380         local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
381     else
382         local mac_prefix="02:42:42:00:00:"
383     fi
384
385     local n
386     local count=1
387     for n in $NETWORKS ; do
388         local ch=$(printf "%02x" $count)
389         local mac="${mac_prefix}${ch}"
390
391         set -- ${n//,/ }
392         local ip_bits="$1" ; shift
393         local dev="$1" ; shift
394         local opts="$*"
395
396         local net="${ip_bits%/*}"
397         local netname="acnet_${net//./_}"
398
399         local ip="${net%.*}.${IPNUM}/${ip_bits#*/}"
400
401         local ipv6="fc00:${net//./:}::${IPNUM}/64"
402
403         # This can be used to override the variables in the echo
404         # statement below.  The hook can use any other variables
405         # available in this function.
406         run_hooks hack_network_map_hooks
407
408         echo "${netname} ${dev} ${ip} ${ipv6} ${mac} ${opts}"
409         count=$(($count + 1))
410     done >"$network_map"
411 }
412
413 ##############################
414
415 expand_nodes ()
416 {
417     # Expand out any abbreviations in NODES.
418     local ns=""
419     local n
420     for n in $NODES ; do
421         local t="${n%:*}"
422         local ips="${n#*:}"
423         case "$ips" in
424             *,*)
425                 local i
426                 for i in ${ips//,/ } ; do
427                     ns="${ns}${ns:+ }${t}:${i}"
428                 done
429                 ;;
430             *-*)
431                 local i
432                 for i in $(seq ${ips/-/ }) ; do
433                     ns="${ns}${ns:+ }${t}:${i}"
434                 done
435                 ;;
436             *)
437                 ns="${ns}${ns:+ }${n}"
438         esac
439     done
440     NODES="$ns"
441
442     # Check IP addresses for duplicates.
443     local ip_offsets=":"
444     # This function doesn't modify anything...
445     get_ip_offset ()
446     {
447         [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
448             die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
449         ip_offsets="${ip_offsets}${ip_offset}:"
450     }
451     hack_all_nodes_with get_ip_offset
452
453     # Determine node names and whether they're in the CTDB cluster
454     declare -A node_count
455     _get_name_ctdb_node ()
456     {
457         local count=$((${node_count[$node_type]:-0} + 1))
458         node_count[$node_type]=$count
459         name=$(call_func node_name_format "$node_type" "$CLUSTER" $count) || {
460             echo "ERROR: Node type \"${node_type}\" not defined!"
461             echo "Valid node types are:"
462             set | sed -n 's@^node_name_format_\(.*\) ().*@  \1@p'
463             exit 1
464         }
465         ctdb_node=$(call_func node_is_ctdb_node "$node_type")
466     }
467     hack_all_nodes_with _get_name_ctdb_node
468 }
469
470 ##############################
471
472 sanity_check_cluster_name ()
473 {
474     [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
475         die "Cluster names should be restricted to the characters A-Za-z0-9.  \
476 Some cluster filesystems have problems with other characters."
477 }
478
479 hosts_file=
480
481 cluster_nodelist_hacking ()
482 {
483     # Rework the NODES list
484     expand_nodes
485
486     # Build /etc/hosts and hack the names of the ctdb nodes
487     hosts_line_hack_name ()
488     {
489         local sname=""
490         local hosts_line
491         local ip_addr="${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
492
493         # Primary name for CTDB nodes is <CLUSTER>n<num>
494         if [ "$ctdb_node" = 1 ] ; then
495             num_ctdb_nodes=$(($num_ctdb_nodes + 1))
496             sname="${CLUSTER}n${num_ctdb_nodes}"
497             hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
498             name="$sname"
499         else
500             hosts_line="$ip_addr ${name}.${ld} $name"
501         fi
502
503         # This allows you to add a function to your configuration file
504         # to modify hostnames (and other aspects of nodes).  This
505         # function can access/modify $name (the existing name),
506         # $node_type and $ctdb_node (1, if the node is a member of the
507         # CTDB cluster, 0 otherwise).
508         if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
509             local old_name="$name"
510             $HOSTNAME_HACKING_FUNCTION
511             if [ "$name" != "$old_name" ] ; then
512                 hosts_line="$ip_addr ${name}.${ld} $name"
513             fi
514         fi
515
516         echo "$hosts_line"
517     }
518     hosts_file="tmp/hosts.$CLUSTER"
519     {
520         local num_ctdb_nodes=0
521         local ld=$(echo $DOMAIN | tr A-Z a-z)
522         echo "# autocluster $CLUSTER"
523         hack_all_nodes_with hosts_line_hack_name
524         echo
525     } >$hosts_file
526
527     # Build /etc/ctdb/nodes
528     ctdb_nodes_line ()
529     {
530         [ "$ctdb_node" = 1 ] || return 0
531         echo "${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
532         num_nodes=$(($num_nodes + 1))
533     }
534     nodes_file="tmp/nodes.$CLUSTER"
535     local num_nodes=0
536     hack_all_nodes_with ctdb_nodes_line >$nodes_file
537
538     # Build /etc/ctdb/nodes.ipv6
539     ctdb_nodes_line_ipv6 ()
540     {
541         [ "$ctdb_node" = 1 ] || return 0
542         echo "fc00:${NETWORK_PRIVATE_PREFIX//./:}::$(($FIRSTIP + $ip_offset))"
543         num_nodes=$(($num_nodes + 1))
544     }
545     nodes_file_ipv6="tmp/nodes.$CLUSTER.ipv6"
546     local num_nodes=0
547     hack_all_nodes_with ctdb_nodes_line_ipv6 >$nodes_file_ipv6
548
549     # Build UUID map
550     uuid_map="tmp/uuid_map.$CLUSTER"
551     uuid_map_line ()
552     {
553         echo "${ip_offset} $(uuidgen) ${node_type}"
554     }
555     hack_all_nodes_with uuid_map_line >$uuid_map
556 }
557
558 create_cluster_hooks=
559 cluster_created_hooks=
560
561 cluster_create ()
562 {
563     # Use $1.  If not set then use value from configuration file.
564     CLUSTER="${1:-${CLUSTER}}"
565     announce "cluster create \"${CLUSTER}\""
566     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
567
568     sanity_check_cluster_name
569
570     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
571
572     # Run hooks before doing anything else.
573     run_hooks create_cluster_hooks
574
575     for_each_node call_func create_node
576
577     echo "Cluster $CLUSTER created"
578     echo ""
579
580     run_hooks cluster_created_hooks
581 }
582
583 cluster_created_hosts_message ()
584 {
585     echo "You may want to add this to your /etc/hosts file:"
586     cat $hosts_file
587 }
588
589 register_hook cluster_created_hooks cluster_created_hosts_message
590
591 cluster_destroy ()
592 {
593     announce "cluster destroy \"${CLUSTER}\""
594     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
595
596     virsh_cluster destroy || true
597 }
598
599 cluster_undefine ()
600 {
601     announce "cluster undefine \"${CLUSTER}\""
602     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
603
604     virsh_cluster undefine || true
605 }
606
607 cluster_update_hosts ()
608 {
609     announce "cluster update_hosts \"${CLUSTER}\""
610     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
611
612     [ -n "$hosts_file" ] || hosts_file="tmp/hosts.${CLUSTER}"
613     [ -r "$hosts_file" ] || die "Missing hosts file \"${hosts_file}\""
614
615     # Building a general node name regexp is a bit cumbersome.  :-)
616     local name_regexp="("
617     for i in $(set | sed -n -e "s@^\(node_name_format_.*\) ().*@\1@p") ; do
618         # Format node name with placeholders (remembering that "_" is
619         # not valid in a real cluster name)
620         local t=$("$i" "_" "0")
621         # now replace the placeholders with regexps - order is
622         # important here, since the cluster name can contain digits
623         t=$(sed -r -e "s@[[:digit:]]+@[[:digit:]]+@" -e "s@_@${CLUSTER}@" <<<"$t")
624         # add to the regexp
625         name_regexp="${name_regexp}${t}|"
626     done
627     name_regexp="${name_regexp}${CLUSTER}n[[:digit:]]+)"
628
629     local pat="# autocluster ${CLUSTER}\$|[[:space:]]${name_regexp}"
630
631     local t="/etc/hosts.${CLUSTER}"
632     grep -E "$pat" /etc/hosts >"$t" || true
633     if diff -B "$t" "$hosts_file" >/dev/null ; then
634         rm "$t"
635         return
636     fi
637
638     local old=/etc/hosts.old.autocluster
639     cp /etc/hosts "$old"
640     local new=/etc/hosts.new
641     grep -Ev "$pat" "$old" |
642     cat -s - "$hosts_file" >"$new"
643
644     mv "$new" /etc/hosts
645
646     echo "Made these changes to /etc/hosts:"
647     diff -u "$old" /etc/hosts || true
648 }
649
650 cluster_boot ()
651 {
652     announce "cluster boot \"${CLUSTER}\""
653     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
654
655     virsh_cluster start || return $?
656
657     local nodes=$(list_all_cluster_nodes)
658
659     # Wait for each node
660     local i
661     for i in $nodes ; do
662         waitfor "${KVMLOG}/serial.$i" "login:" 300 || {
663             vircmd destroy "$CLUSTER_PATTERN"
664             die "Failed to create cluster"
665         }
666     done
667
668     # Move past the last line of log output
669     echo ""
670 }
671
672 cluster_setup_tasks_DEFAULT ()
673 {
674     local stage="$1"
675
676     # By default nodes have no tasks
677     case "$stage" in
678         install_packages) echo "" ;;
679         setup_clusterfs)  echo "" ;;
680         setup_node)       echo "" ;;
681         setup_cluster)    echo "" ;;
682     esac
683 }
684
685 cluster_setup ()
686 {
687     announce "cluster setup \"${CLUSTER}\""
688     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
689
690     local ssh="ssh -o StrictHostKeyChecking=no"
691     local setup_clusterfs_done=false
692     local setup_cluster_done=false
693
694     _cluster_setup_do_stage ()
695     {
696         local stage="$1"
697         local type="$2"
698         local ip_offset="$3"
699         local name="$4"
700         local ctdb_node="$5"
701
702         local tasks=$(call_func cluster_setup_tasks "$type" "$stage")
703
704         if [ -n "$tasks" ] ; then
705             # These tasks are only done on 1 node
706             case "$stage" in
707                 setup_clusterfs)
708                     if $setup_clusterfs_done ; then
709                         return
710                     else
711                         setup_clusterfs_done=true
712                     fi
713                     ;;
714                 setup_cluster)
715                     if $setup_cluster_done ; then
716                         return
717                     else
718                         setup_cluster_done=true
719                     fi
720                     ;;
721             esac
722
723             $ssh "$name" ./scripts/cluster_setup.sh "$stage" $tasks
724         fi
725
726     }
727
728     local stages="install_packages setup_clusterfs setup_node setup_cluster"
729     local stage
730     for stage in $stages ; do
731         for_each_node _cluster_setup_do_stage "$stage"
732     done
733 }
734
735 create_one_node ()
736 {
737     CLUSTER="$1"
738     local single_node_ip_offset="$2"
739
740     sanity_check_cluster_name
741
742     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
743
744     for n in $NODES ; do
745         set -- $(IFS=: ; echo $n)
746         [ $single_node_ip_offset -eq $2 ] || continue
747         call_func create_node "$@"
748         
749         echo "Requested node created"
750         echo ""
751         echo "You may want to update your /etc/hosts file:"
752         cat $hosts_file
753         
754         break
755     done
756 }
757
758 ###############################
759 # test the proxy setup
760 test_proxy() {
761     export http_proxy=$WEBPROXY
762     wget -O /dev/null $INSTALL_SERVER || \
763         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
764     echo "Proxy OK"
765 }
766
767 ###################
768
769 kickstart_floppy_create_hooks=
770
771 guess_install_network ()
772 {
773     # Figure out IP address to use during base install.  Default to
774     # the IP address of the 1st (private) network. If a gateway is
775     # specified then use the IP address associated with it.
776     INSTALL_IP=""
777     INSTALL_GW=""
778     local netname dev ip ipv6 mac opts
779     while read netname dev ip ipv6 mac opts; do
780         local o
781         for o in $opts ; do
782             case "$o" in
783                 gw\=*)
784                     INSTALL_GW="${o#gw=}"
785                     INSTALL_IP="$ip"
786             esac
787         done
788         [ -n "$INSTALL_IP" ] || INSTALL_IP="$ip"
789     done <"$network_map"
790 }
791
792 # create base image
793 base_create()
794 {
795     local NAME="$BASENAME"
796     local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
797     run_hooks hack_disk_hooks "base"
798
799     mkdir -p $KVMLOG
800
801     echo "Testing WEBPROXY $WEBPROXY"
802     test_proxy
803
804     local di="$DISK"
805     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
806         di=$(readlink "$DISK")
807     fi
808     rm -f "$di"
809     local di_dirname="${di%/*}"
810     mkdir -p "$di_dirname"
811
812     echo "Creating the disk"
813     qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
814
815     rm -rf tmp
816     mkdir -p mnt tmp tmp/ISO
817
818     setup_timezone
819
820     IPNUM=$FIRSTIP
821     make_network_map
822
823     guess_install_network
824
825     echo "Creating kickstart file from template"
826     substitute_vars "$KICKSTART" "tmp/ks.cfg"
827
828     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
829     case "$ISO" in
830         (/*) : ;;
831         (*) ISO="${ISO_DIR}/${ISO}"
832     esac
833     
834     echo "Creating kickstart floppy"
835     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
836     mkdosfs -n KICKSTART tmp/floppy.img
837     mount -o loop -t msdos tmp/floppy.img mnt
838     cp tmp/ks.cfg mnt
839     mount -o loop,ro $ISO tmp/ISO
840     
841     echo "Setting up bootloader"
842     cp tmp/ISO/isolinux/isolinux.bin tmp
843     cp tmp/ISO/isolinux/vmlinuz tmp
844     cp tmp/ISO/isolinux/initrd.img tmp
845
846     run_hooks kickstart_floppy_create_hooks
847
848     umount tmp/ISO
849     umount mnt
850
851     UUID=`uuidgen`
852
853     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
854
855     rm -f $KVMLOG/serial.$NAME
856
857     # boot the install CD
858     $VIRSH create tmp/$NAME.xml
859
860     echo "Waiting for install to start"
861     sleep 2
862     
863     # wait for the install to finish
864     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
865         $VIRSH destroy $NAME
866         die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
867 You may need to increase the value of CREATE_BASE_TIMEOUT.
868 Alternatively, the install might have completed but KS_DONE_MESSAGE
869 (currently \"${KS_DONE_MESSAGE}\")
870 may not have matched anything at the end of the kickstart output."
871     fi
872     
873     $VIRSH destroy $NAME
874
875     ls -l $DISK
876     cat <<EOF
877
878 Install finished, base image $DISK created
879
880 You may wish to run
881    chcon -t virt_content_t $DISK
882    chattr +i $DISK
883 To ensure that this image does not change
884
885 Note that the root password has been set to $ROOTPASSWORD
886
887 EOF
888 }
889
890 ###############################
891 # boot the base disk
892 base_boot() {
893     rm -rf tmp
894     mkdir -p tmp
895
896     NAME="$BASENAME"
897     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
898
899     IPNUM=$FIRSTIP
900
901     make_network_map
902
903     CLUSTER="base"
904
905     diskimage mount $DISK
906     setup_base
907     diskimage unmount
908
909     UUID=`uuidgen`
910     
911     echo "Creating $NAME.xml"
912     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
913     
914     # boot the base system
915     $VIRSH create tmp/$NAME.xml
916 }
917
918 ######################################################################
919
920 # Updating a disk image...
921
922 diskimage ()
923 {
924     local func="$1"
925     shift
926     call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
927 }
928
929 # setup the files from $BASE_TEMPLATES/, substituting any variables
930 # based on the config
931 copy_base_dir_substitute_templates ()
932 {
933     local dir="$1"
934
935     local d="$BASE_TEMPLATES/$dir"
936     [ -d "$d" ] || return 0
937
938     local f
939     for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
940         f="${f#./}" # remove leading "./" for clarity
941         if [ -d "$d/$f" ]; then
942             # Don't chmod existing directory
943             if diskimage is_directory "/$f" ; then
944                 continue
945             fi
946             diskimage mkdir_p "/$f"
947         else
948             echo " Install: $f"
949             diskimage substitute_vars "$d/$f" "/$f"
950         fi
951         diskimage chmod_reference "$d/$f" "/$f"
952     done
953 }
954
955 setup_base_hooks=
956
957 setup_base_ssh_keys ()
958 {
959     # this is needed as git doesn't store file permissions other
960     # than execute
961     # Note that we protect the wildcards from the local shell.
962     diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
963     diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
964     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
965        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
966        diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
967     fi
968     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
969        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
970        diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
971     fi
972 }
973
974 register_hook setup_base_hooks setup_base_ssh_keys
975
976 setup_base_grub_conf ()
977 {
978     echo "Adjusting grub.conf"
979     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
980     local grub_configs="/boot/grub/grub.conf"
981     if ! diskimage is_file "$grub_configs" ; then
982         grub_configs="/etc/default/grub /boot/grub2/grub.cfg"
983     fi
984     local c
985     for c in $grub_configs ; do
986         diskimage sed "$c" \
987             -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
988             -e "s/ console=tty1//" -e "s/ rhgb/ norhgb/"  \
989             -e "s/ nodmraid//" -e "s/ nompath//"  \
990             -e "s/quiet/noapic divider=10${o:+ }${o}/g"
991     done
992 }
993
994 register_hook setup_base_hooks setup_base_grub_conf
995
996 setup_base()
997 {
998     local type="$1"
999
1000     umask 022
1001     echo "Copy base files"
1002     copy_base_dir_substitute_templates "all"
1003     if [ -n "$type" ] ; then
1004         copy_base_dir_substitute_templates "$type"
1005     fi
1006
1007     run_hooks setup_base_hooks
1008 }
1009
1010 ipv4_prefix_to_netmask ()
1011 {
1012     local prefix="$1"
1013
1014     local div=$(($prefix / 8))
1015     local mod=$(($prefix % 8))
1016
1017     local octet
1018     for octet in 1 2 3 4 ; do
1019         if [ $octet -le $div ] ; then
1020             echo -n "255"
1021         elif [ $mod -ne 0 -a $octet -eq $(($div + 1)) ] ; then
1022             local shift=$((8 - $mod))
1023             echo -n $(( (255 >> $shift << $shift) ))
1024         else
1025             echo -n 0
1026         fi
1027         if [ $octet -lt 4 ] ; then
1028             echo -n '.'
1029         fi
1030     done
1031
1032     echo
1033 }
1034
1035 # setup various networking components
1036 setup_network()
1037 {
1038     # This avoids doing anything when we're called from boot_base().
1039     if [ -z "$hosts_file" ] ; then
1040         echo "Skipping network-related setup"
1041         return
1042     fi
1043
1044     echo "Setting up networks"
1045     diskimage append_text_file "$hosts_file" "/etc/hosts"
1046
1047     echo "Setting up /etc/ctdb/nodes"
1048     diskimage mkdir_p "/etc/ctdb"
1049     if [ "$NETWORK_STACK" = "ipv4" ] ; then
1050         diskimage put "$nodes_file" "/etc/ctdb/nodes"
1051     elif [ "$NETWORK_STACK" = "ipv6" ] ; then
1052         diskimage put "$nodes_file_ipv6" "/etc/ctdb/nodes"
1053     elif [ "$NETWORK_STACK" = "dual" ] ; then
1054         diskimage put "$nodes_file" "/etc/ctdb/nodes.ipv4"
1055         diskimage put "$nodes_file_ipv6" "/etc/ctdb/nodes.ipv6"
1056         diskimage put "$nodes_file" "/etc/ctdb/nodes"
1057     else
1058         die "Error: Invalid NETWORK_STACK value \"$NETWORK_STACK\"."
1059     fi
1060
1061     [ "$WEBPROXY" = "" ] || {
1062         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
1063     }
1064
1065     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
1066         echo "Enabling nfs mount of $NFSSHARE"
1067         diskimage mkdir_p "$NFS_MOUNTPOINT"
1068         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
1069     fi
1070
1071     diskimage mkdir_p "/etc/yum.repos.d"
1072     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
1073
1074     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
1075
1076     echo "Setting up network interfaces: "
1077     local netname dev ip ipv6 mac opts
1078     while read netname dev ip ipv6 mac opts; do
1079         echo "  $dev"
1080
1081         local o gw addr mask
1082         gw=""
1083         for o in $opts ; do
1084             case "$o" in
1085                 gw\=*)
1086                     gw="${o#gw=}"
1087             esac
1088         done
1089
1090         addr=${ip%/*}
1091         mask=$(ipv4_prefix_to_netmask ${ip#*/})
1092
1093         cat <<EOF | \
1094             diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
1095 DEVICE=$dev
1096 ONBOOT=yes
1097 TYPE=Ethernet
1098 IPADDR=$addr
1099 NETMASK=$mask
1100 HWADDR=$mac
1101 IPV6INIT=yes
1102 IPV6ADDR=$ipv6
1103 ${gw:+GATEWAY=}${gw}
1104 EOF
1105
1106         # This goes to 70-persistent-net.rules
1107         cat <<EOF
1108 # Generated by autocluster
1109 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
1110
1111 EOF
1112     done <"$network_map" |
1113     diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
1114 }
1115
1116 register_hook setup_base_hooks setup_network
1117
1118 setup_base_cluster_setup_config ()
1119 {
1120     local f
1121     {
1122         echo "# Generated by autocluster"
1123         echo
1124         # This is a bit of a hack.  Perhaps these script belong
1125         # elsewhere, since they no longer have templates?
1126         for f in $(find "${BASE_TEMPLATES}/all/root/scripts" -type f |
1127             xargs grep -l '^#config:') ; do
1128
1129             b=$(basename "$f")
1130             echo "# $b"
1131             local vs v
1132             vs=$(sed -n 's@^#config: *@@p' "$f")
1133             for v in $vs ; do
1134                 # This could substitute the values in directly using
1135                 # ${!v} but then no sanity checking is done to make
1136                 # sure variables are set.
1137                 echo "${v}=\"@@${v}@@\""
1138             done
1139             echo
1140         done
1141     } | diskimage substitute_vars - "/root/scripts/cluster_setup.config"
1142 }
1143
1144 register_hook setup_base_hooks setup_base_cluster_setup_config
1145
1146 setup_timezone() {
1147     [ -z "$TIMEZONE" ] && {
1148         [ -r /etc/timezone ] && {
1149             TIMEZONE=`cat /etc/timezone`
1150         }
1151         [ -r /etc/sysconfig/clock ] && {
1152             . /etc/sysconfig/clock
1153             TIMEZONE="$ZONE"
1154         }
1155         TIMEZONE="${TIMEZONE// /_}"
1156     }
1157     [ -n "$TIMEZONE" ] || \
1158         die "Unable to determine TIMEZONE - please set in config"
1159 }
1160
1161 # substite a set of variables of the form @@XX@@ for the shell
1162 # variables $XX in a file.
1163 #
1164 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
1165 # contain a filename whose contents are substituted, with variable
1166 # substitution applied to those contents.  If filename starts with '|'
1167 # it is a command instead - however, quoting is extremely fragile.
1168 substitute_vars() {(
1169         infile="${1:-/dev/null}" # if empty then default to /dev/null
1170         outfile="$2" # optional
1171
1172         tmp_out=$(mktemp)
1173         cat "$infile" >"$tmp_out"
1174
1175         # Handle any indirects by looping until nothing changes.
1176         # However, only handle 10 levels of recursion.
1177         count=0
1178         while : ; do
1179             if ! _substitute_vars "$tmp_out" "@@@" ; then
1180                 rm -f "$tmp_out"
1181                 die "Failed to expand template $infile"
1182             fi
1183
1184             # No old version of file means no changes made.
1185             if [ ! -f "${tmp_out}.old" ] ; then
1186                 break
1187             fi
1188
1189             rm -f "${tmp_out}.old"
1190
1191             count=$(($count + 1))
1192             if [ $count -ge 10 ] ; then
1193                 rm -f "$tmp_out"
1194                 die "Recursion too deep in $infile - only 10 levels allowed!"
1195             fi
1196         done
1197
1198         # Now regular variables.
1199         if ! _substitute_vars "$tmp_out" "@@" ; then
1200             rm -f "$tmp_out"
1201             die "Failed to expand template $infile"
1202         fi
1203         rm -f "${tmp_out}.old"
1204
1205         if [ -n "$outfile" ] ; then
1206             mv "$tmp_out" "$outfile"
1207         else
1208             cat "$tmp_out"
1209             rm -f "$tmp_out"
1210         fi
1211 )}
1212
1213
1214 # Delimiter @@ means to substitute contents of variable.
1215 # Delimiter @@@ means to substitute contents of file named by variable.
1216 # @@@ supports leading '|' in variable value, which means to excute a
1217 # command.
1218 _substitute_vars() {(
1219         tmp_out="$1"
1220         delimiter="${2:-@@}"
1221
1222         # Get the list of variables used in the template.  The grep
1223         # gets rid of any blank lines and lines with extraneous '@'s
1224         # next to template substitutions.
1225         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
1226             grep '^[A-Z0-9_][A-Z0-9_]*$' |
1227             sort -u)
1228
1229         tmp=$(mktemp)
1230         for v in $VARS; do
1231             # variable variables are fun .....
1232             [ "${!v+x}" ] || {
1233                 rm -f $tmp
1234                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
1235             }
1236             s=${!v}
1237
1238             if [ "$delimiter" = "@@@" ] ; then
1239                 f=${s:-/dev/null}
1240                 c="${f#|}" # Is is a command, signified by a leading '|'?
1241                 if [ "$c" = "$f" ] ; then
1242                     # No leading '|', cat file.
1243                     s=$(cat -- "$f")
1244                     [ $? -eq 0 ] || {
1245                         rm -f $tmp
1246                         die "Could not substitute contents of file $f"
1247                     }
1248                 else
1249                     # Leading '|', execute command.
1250                     # Quoting problems here - using eval "$c" doesn't help.
1251                     s=$($c)
1252                     [ $? -eq 0 ] || {
1253                         rm -f $tmp
1254                         die "Could not execute command $c"
1255                     }
1256                 fi
1257             fi
1258
1259             # escape some pesky chars
1260             # This first one can be too slow if done using a bash
1261             # variable pattern subsitution.
1262             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
1263             s=${s//#/\\#}
1264             s=${s//&/\\&}
1265             echo "s#${delimiter}${v}${delimiter}#${s}#g"
1266         done > $tmp
1267
1268         # Get the in-place sed to make a backup of the old file.
1269         # Remove the backup if it is the same as the resulting file -
1270         # this acts as a flag to the caller that no changes were made.
1271         sed -i.old -f $tmp "$tmp_out"
1272         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
1273             rm -f "${tmp_out}.old"
1274         fi
1275
1276         rm -f $tmp
1277 )}
1278
1279 check_command() {
1280     which $1 > /dev/null || die "Please install $1 to continue"
1281 }
1282
1283 # Set a variable if it isn't already set.  This allows environment
1284 # variables to override default config settings.
1285 defconf() {
1286     local v="$1"
1287     local e="$2"
1288
1289     [ "${!v+x}" ] || eval "$v=\"$e\""
1290 }
1291
1292 load_config () {
1293     local i
1294
1295     for i in "${installdir}/config.d/"*.defconf ; do
1296         . "$i"
1297     done
1298 }
1299
1300 # Print the list of config variables defined in config.d/.
1301 get_config_options () {( # sub-shell for local declaration of defconf()
1302         local options=
1303         defconf() { options="$options $1" ; }
1304         load_config
1305         echo $options
1306 )}
1307
1308 # Produce a list of long options, suitable for use with getopt, that
1309 # represent the config variables defined in config.d/.
1310 getopt_config_options () {
1311     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
1312     echo "${x// /:,}:"
1313 }
1314
1315 # Unconditionally set the config variable associated with the given
1316 # long option.
1317 setconf_longopt () {
1318     local longopt="$1"
1319     local e="$2"
1320
1321     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
1322     # unset so defconf will set it
1323     eval "unset $v"
1324     defconf "$v" "$e"
1325 }
1326
1327 # Dump all of the current config variables.
1328 dump_config() {
1329     local o
1330     for o in $(get_config_options) ; do
1331         echo "${o}=\"${!o}\""
1332     done
1333     exit 0
1334 }
1335
1336 # $COLUMNS is set in interactive bash shells.  It probably isn't set
1337 # in this shell, so let's set it if it isn't.
1338 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1339 : ${COLUMNS:=80}
1340 export COLUMNS
1341
1342 # Print text assuming it starts after other text in $startcol and
1343 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1344 # Long "words" will extend past $COLUMNS - 2.
1345 fill_text() {
1346     local startcol="$1"
1347     local text="$2"
1348
1349     local width=$(($COLUMNS - 2 - $startcol))
1350     [ $width -lt 0 ] && width=$((78 - $startcol))
1351
1352     local out=""
1353
1354     local padding
1355     if [ $startcol -gt 0 ] ; then
1356         padding=$(printf "\n%${startcol}s" " ")
1357     else
1358         padding="
1359 "
1360     fi
1361
1362     while [ -n "$text" ] ; do
1363         local orig="$text"
1364
1365         # If we already have output then arrange padding on the next line.
1366         [ -n "$out" ] && out="${out}${padding}"
1367
1368         # Break the text at $width.
1369         out="${out}${text:0:${width}}"
1370         text="${text:${width}}"
1371
1372         # If we have left over text then the line break may be ugly,
1373         # so let's check and try to break it on a space.
1374         if [ -n "$text" ] ; then
1375             # The 'x's stop us producing a special character like '(',
1376             # ')' or '!'.  Yuck - there must be a better way.
1377             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1378                 # We didn't break on a space.  Arrange for the
1379                 # beginning of the broken "word" to appear on the next
1380                 # line but not if it will make us loop infinitely.
1381                 if [ "${orig}" != "${out##* }${text}" ] ; then
1382                     text="${out##* }${text}"
1383                     out="${out% *}"
1384                 else
1385                     # Hmmm, doing that would make us loop, so add the
1386                     # rest of the word from the remainder of the text
1387                     # to this line and let it extend past $COLUMNS - 2.
1388                     out="${out}${text%% *}"
1389                     if [ "${text# *}" != "$text" ] ; then
1390                         # Remember the text after the next space for next time.
1391                         text="${text# *}"
1392                     else
1393                         # No text after next space.
1394                         text=""
1395                     fi
1396                 fi
1397             else
1398                 # We broke on a space.  If it will be at the beginning
1399                 # of the next line then remove it.
1400                 text="${text# }"
1401             fi
1402         fi
1403     done
1404
1405     echo "$out"
1406 }
1407
1408 # Display usage text, trying these approaches in order.
1409 # 1. See if it all fits on one line before $COLUMNS - 2.
1410 # 2. See if splitting before the default value and indenting it
1411 #    to $startcol means that nothing passes $COLUMNS - 2.
1412 # 3. Treat the message and default value as a string and just us fill_text()
1413 #    to format it. 
1414 usage_display_text () {
1415     local startcol="$1"
1416     local desc="$2"
1417     local default="$3"
1418     
1419     local width=$(($COLUMNS - 2 - $startcol))
1420     [ $width -lt 0 ] && width=$((78 - $startcol))
1421
1422     default="(default \"$default\")"
1423
1424     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1425         echo "${desc} ${default}"
1426     else
1427         local padding=$(printf "%${startcol}s" " ")
1428
1429         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1430             echo "$desc"
1431             echo "${padding}${default}"
1432         else
1433             fill_text $startcol "${desc} ${default}"
1434         fi
1435     fi
1436 }
1437
1438 # Display usage information for long config options.
1439 usage_smart_display () {( # sub-shell for local declaration of defconf()
1440         local startcol=33
1441
1442         defconf() {
1443             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1444
1445             printf "     --%-25s " "${longopt}=${3}"
1446
1447             usage_display_text $startcol "$4" "$2"
1448         }
1449
1450         "$@"
1451 )}
1452
1453
1454 # Display usage information for long config options.
1455 usage_config_options (){
1456     usage_smart_display load_config
1457 }
1458
1459 actions_init ()
1460 {
1461     actions=""
1462 }
1463
1464 actions_add ()
1465 {
1466     actions="${actions}${actions:+ }$*"
1467 }
1468
1469 actions_run ()
1470 {
1471     [ -n "$actions" ] || usage
1472
1473     local a
1474     for a in $actions ; do
1475         $a
1476     done
1477 }
1478
1479 ######################################################################
1480
1481 post_config_hooks=
1482
1483 ######################################################################
1484
1485 load_config
1486
1487 ############################
1488 # parse command line options
1489 long_opts=$(getopt_config_options)
1490 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump -l "$long_opts" -- "$@")
1491 [ $? != 0 ] && usage
1492
1493 use_default_config=true
1494
1495 # We do 2 passes of the options.  The first time we just handle usage
1496 # and check whether -c is being used.
1497 eval set -- "$getopt_output"
1498 while true ; do
1499     case "$1" in
1500         -c) shift 2 ; use_default_config=false ;;
1501         -e) shift 2 ;;
1502         -E) shift 2 ;;
1503         --) shift ; break ;;
1504         --dump|-x) shift ;;
1505         -h|--help) usage ;; # Usage should be shown here for real defaults.
1506         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1507         *) usage ;; # shouldn't happen, so this is reasonable.
1508     esac
1509 done
1510
1511 config="./config"
1512 $use_default_config && [ -r "$config" ] && . "$config"
1513
1514 eval set -- "$getopt_output"
1515
1516 while true ; do
1517     case "$1" in
1518         -c)
1519             b=$(basename $2)
1520             # force at least ./local_file to avoid accidental file
1521             # from $PATH
1522             . "$(dirname $2)/${b}"
1523             # If $CLUSTER is unset then try to base it on the filename
1524             if [ ! -n "$CLUSTER" ] ; then
1525                 case "$b" in
1526                     *.autocluster)
1527                         CLUSTER="${b%.autocluster}"
1528                 esac
1529             fi
1530             shift 2
1531             ;;
1532         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1533         -E) eval "$2" ; shift 2 ;;
1534         -x) set -x; shift ;;
1535         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1536         --) shift ; break ;;
1537         -h|--help) usage ;; # Redundant.
1538         --*)
1539             # Putting --opt1|opt2|... into a variable and having case
1540             # match against it as a pattern doesn't work.  The | is
1541             # part of shell syntax, so we need to do this.  Look away
1542             # now to stop your eyes from bleeding! :-)
1543             x=",${long_opts}" # Now each option is surrounded by , and :
1544             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1545                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1546                 setconf_longopt "$1" "$2"; shift 2
1547             else
1548                 usage
1549             fi
1550             ;;
1551         *) usage ;; # shouldn't happen, so this is reasonable.
1552     esac
1553 done
1554
1555 run_hooks post_config_hooks 
1556
1557 # catch errors
1558 set -e
1559 set -E
1560 trap 'es=$?; 
1561       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1562       exit $es' ERR
1563
1564 # check for needed programs 
1565 check_command expect
1566
1567 [ $# -lt 1 ] && usage
1568
1569 t="$1"
1570 shift
1571
1572 case "$t" in
1573     base)
1574         actions_init
1575         for t in "$@" ; do
1576             case "$t" in
1577                 create|boot) actions_add "base_${t}" ;;
1578                 *) usage ;;
1579             esac
1580         done
1581         actions_run
1582         ;;
1583
1584     cluster)
1585         actions_init
1586         for t in "$@" ; do
1587             case "$t" in
1588                 destroy|undefine|create|update_hosts|boot|setup)
1589                     actions_add "cluster_${t}" ;;
1590                 build)
1591                     for t in destroy undefine create update_hosts boot setup ; do
1592                         actions_add "cluster_${t}"
1593                     done
1594                     ;;
1595                 *) usage ;;
1596             esac
1597         done
1598         cluster_nodelist_hacking
1599         actions_run
1600         ;;
1601
1602     create)
1603         t="$1"
1604         shift
1605         case "$t" in
1606             base)
1607                 [ $# != 0 ] && usage
1608                 base_create
1609                 ;;
1610             cluster)
1611                 [ $# != 1 ] && usage
1612                 cluster_create "$1"
1613                 ;;
1614             node)
1615                 [ $# != 2 ] && usage
1616                 create_one_node "$1" "$2"
1617                 ;;
1618             *)
1619                 usage;
1620                 ;;
1621         esac
1622         ;;
1623     mount)
1624         [ $# != 1 ] && usage
1625         diskimage mount "$1"
1626         ;;
1627     unmount|umount)
1628         [ $# != 0 ] && usage
1629         diskimage unmount
1630         ;;
1631     bootbase)
1632         base_boot;
1633         ;;
1634     *)
1635         usage;
1636         ;;
1637 esac