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