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