Add RHEL 6.8 ISO details
[autocluster.git] / autocluster
1 #!/bin/bash
2 # main autocluster script
3 #
4 # Copyright (C) Andrew Tridgell  2008
5 # Copyright (C) Martin Schwenke  2008
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #   
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #   
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19
20 ##BEGIN-INSTALLDIR-MAGIC##
21 # There are better ways of doing this but not if you still want to be
22 # able to run straight out of a git tree.  :-)
23 if [ -f "$0" ]; then
24     autocluster="$0"
25 else
26     autocluster=$(which "$0")
27 fi
28 if [ -L "$autocluster" ] ; then
29     autocluster=$(readlink "$autocluster")
30 fi
31 installdir=$(dirname "$autocluster")
32 ##END-INSTALLDIR-MAGIC##
33
34 ####################
35 # show program usage
36 usage ()
37 {
38     cat <<EOF
39 Usage: autocluster [OPTION] ... <COMMAND>
40   options:
41      -c <file>                   specify config file (default is "config")
42      -e <expr>                   execute <expr> and exit
43      -E <expr>                   execute <expr> and continue
44      -x                          enable script debugging
45      --dump                      dump config settings and exit
46
47   configuration options:
48 EOF
49
50     usage_config_options
51
52     cat <<EOF
53
54   commands:
55      base [ create | boot ] ...
56
57      cluster [ build |
58                destroy | undefine |
59                create | update_hosts | boot | setup ] ...
60
61      create base
62            create a base image
63
64      create cluster [ CLUSTERNAME ]
65            create a full cluster
66
67      create node CLUSTERNAME IP_OFFSET
68            (re)create a single cluster node
69
70      mount DISK
71            mount a qemu disk on mnt/
72
73      unmount | umount
74            unmount a qemu disk from mnt/
75
76      bootbase
77            boot the base image
78 EOF
79     exit 1
80 }
81
82 ###############################
83
84 die () {
85     if [ "$no_sanity" = 1 ] ; then
86         fill_text 0 "WARNING: $*" >&2
87     else
88         fill_text 0 "ERROR: $*" >&2
89         exit 1
90     fi
91 }
92
93 announce ()
94 {
95     echo "######################################################################"
96     printf "# %-66s #\n" "$*"
97     echo "######################################################################"
98     echo ""
99 }
100
101 waitfor ()
102 {
103     local file="$1"
104     local msg="$2"
105     local timeout="$3"
106
107     local tmpfile=$(mktemp)
108
109     cat <<EOF >"$tmpfile"
110 spawn tail -n 10000 -f $file
111 expect -timeout $timeout -re "$msg"
112 EOF
113
114     export LANG=C
115     expect "$tmpfile"
116     rm -f "$tmpfile"
117
118     if ! grep -E "$msg" "$file" > /dev/null; then
119         echo "Failed to find \"$msg\" in \"$file\""
120         return 1
121     fi
122
123     return 0
124 }
125
126 ###############################
127
128 # Indirectly call a function named by ${1}_${2}
129 call_func () {
130     local func="$1" ; shift
131     local type="$1" ; shift
132
133     local f="${func}_${type}"
134     if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
135         "$f" "$@"
136     else
137         f="${func}_DEFAULT"
138         if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null  ; then
139             "$f" "$type" "$@"
140         else
141             die "No function defined for \"${func}\" \"${type}\""
142         fi
143     fi
144 }
145
146 # Note that this will work if you pass "call_func f" because the first
147 # element of the node tuple is the node type.  Nice...  :-)
148 for_each_node ()
149 {
150     local n
151     for n in $NODES ; do
152         "$@" $(IFS=: ; echo $n)
153     done
154 }
155
156 node_is_ctdb_node_DEFAULT ()
157 {
158     echo 0
159 }
160
161 hack_one_node_with ()
162 {
163     local filter="$1" ; shift
164
165     local node_type="$1"
166     local ip_offset="$2"
167     local name="$3"
168     local ctdb_node="$4"
169
170     $filter
171
172     local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
173     nodes="${nodes}${nodes:+ }${item}"
174 }
175
176 # This also gets used for non-filtering iteration.
177 hack_all_nodes_with ()
178 {
179     local filter="$1"
180
181     local nodes=""
182     for_each_node hack_one_node_with "$filter"
183     NODES="$nodes"
184 }
185
186 list_all_cluster_nodes ()
187 {
188     # Local function only defined in subshell
189     (
190         print_node_name ()
191         {
192             echo "$3"
193         }
194         for_each_node print_node_name
195     ) | sort
196 }
197
198 list_all_virsh_domains ()
199 {
200     local pattern="${CLUSTER_PATTERN:-${CLUSTER}[a-z]*[0-9]}"
201
202     local domains=$(virsh list --all | awk '{print $2}' | tail -n +3)
203     local d
204     for d in $domains ; do
205         case "$d" in
206             ($pattern) echo "$d" ;;
207         esac
208     done | sort
209 }
210
211 virsh_cluster ()
212 {
213         local command="$1"
214         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     done
734 }
735
736 create_one_node ()
737 {
738     CLUSTER="$1"
739     local single_node_ip_offset="$2"
740
741     sanity_check_cluster_name
742
743     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
744
745     for n in $NODES ; do
746         set -- $(IFS=: ; echo $n)
747         [ $single_node_ip_offset -eq $2 ] || continue
748         call_func create_node "$@"
749         
750         echo "Requested node created"
751         echo ""
752         echo "You may want to update your /etc/hosts file:"
753         cat $hosts_file
754         
755         break
756     done
757 }
758
759 ###############################
760 # test the proxy setup
761 test_proxy() {
762     export http_proxy=$WEBPROXY
763     wget -O /dev/null $INSTALL_SERVER || \
764         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
765     echo "Proxy OK"
766 }
767
768 ###################
769
770 kickstart_floppy_create_hooks=
771
772 guess_install_network ()
773 {
774     # Figure out IP address to use during base install.  Default to
775     # the IP address of the 1st (private) network. If a gateway is
776     # specified then use the IP address associated with it.
777     INSTALL_IP=""
778     INSTALL_GW=""
779     local netname dev ip ipv6 mac opts
780     while read netname dev ip ipv6 mac opts; do
781         local o
782         for o in $opts ; do
783             case "$o" in
784                 gw\=*)
785                     INSTALL_GW="${o#gw=}"
786                     INSTALL_IP="$ip"
787             esac
788         done
789         [ -n "$INSTALL_IP" ] || INSTALL_IP="$ip"
790     done <"$network_map"
791 }
792
793 # create base image
794 base_create()
795 {
796     local NAME="$BASENAME"
797     local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
798     run_hooks hack_disk_hooks "base"
799
800     mkdir -p $KVMLOG
801
802     echo "Testing WEBPROXY $WEBPROXY"
803     test_proxy
804
805     local di="$DISK"
806     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
807         di=$(readlink "$DISK")
808     fi
809     rm -f "$di"
810     local di_dirname="${di%/*}"
811     mkdir -p "$di_dirname"
812
813     echo "Creating the disk"
814     qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
815
816     rm -rf tmp
817     mkdir -p mnt tmp tmp/ISO
818
819     setup_timezone
820
821     IPNUM=$FIRSTIP
822     make_network_map
823
824     guess_install_network
825
826     echo "Creating kickstart file from template"
827     substitute_vars "$KICKSTART" "tmp/ks.cfg"
828
829     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
830     case "$ISO" in
831         (/*) : ;;
832         (*) ISO="${ISO_DIR}/${ISO}"
833     esac
834     
835     echo "Creating kickstart floppy"
836     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
837     mkdosfs -n KICKSTART tmp/floppy.img
838     mount -o loop -t msdos tmp/floppy.img mnt
839     cp tmp/ks.cfg mnt
840     mount -o loop,ro $ISO tmp/ISO
841     
842     echo "Setting up bootloader"
843     cp tmp/ISO/isolinux/isolinux.bin tmp
844     cp tmp/ISO/isolinux/vmlinuz tmp
845     cp tmp/ISO/isolinux/initrd.img tmp
846
847     run_hooks kickstart_floppy_create_hooks
848
849     umount tmp/ISO
850     umount mnt
851
852     UUID=`uuidgen`
853
854     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
855
856     rm -f $KVMLOG/serial.$NAME
857
858     # boot the install CD
859     $VIRSH create tmp/$NAME.xml
860
861     echo "Waiting for install to start"
862     sleep 2
863     
864     # wait for the install to finish
865     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
866         $VIRSH destroy $NAME
867         die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
868 You may need to increase the value of CREATE_BASE_TIMEOUT.
869 Alternatively, the install might have completed but KS_DONE_MESSAGE
870 (currently \"${KS_DONE_MESSAGE}\")
871 may not have matched anything at the end of the kickstart output."
872     fi
873     
874     $VIRSH destroy $NAME
875
876     ls -l $DISK
877     cat <<EOF
878
879 Install finished, base image $DISK created
880
881 You may wish to run
882    chcon -t virt_content_t $DISK
883    chattr +i $DISK
884 To ensure that this image does not change
885
886 Note that the root password has been set to $ROOTPASSWORD
887
888 EOF
889 }
890
891 ###############################
892 # boot the base disk
893 base_boot() {
894     rm -rf tmp
895     mkdir -p tmp
896
897     NAME="$BASENAME"
898     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
899
900     IPNUM=$FIRSTIP
901
902     make_network_map
903
904     CLUSTER="base"
905
906     diskimage mount $DISK
907     setup_base
908     diskimage unmount
909
910     UUID=`uuidgen`
911     
912     echo "Creating $NAME.xml"
913     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
914     
915     # boot the base system
916     $VIRSH create tmp/$NAME.xml
917 }
918
919 ######################################################################
920
921 # Updating a disk image...
922
923 diskimage ()
924 {
925     local func="$1"
926     shift
927     call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
928 }
929
930 # setup the files from $BASE_TEMPLATES/, substituting any variables
931 # based on the config
932 copy_base_dir_substitute_templates ()
933 {
934     local dir="$1"
935
936     local d="$BASE_TEMPLATES/$dir"
937     [ -d "$d" ] || return 0
938
939     local f
940     for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
941         f="${f#./}" # remove leading "./" for clarity
942         if [ -d "$d/$f" ]; then
943             # Don't chmod existing directory
944             if diskimage is_directory "/$f" ; then
945                 continue
946             fi
947             diskimage mkdir_p "/$f"
948         else
949             echo " Install: $f"
950             diskimage substitute_vars "$d/$f" "/$f"
951         fi
952         diskimage chmod_reference "$d/$f" "/$f"
953     done
954 }
955
956 setup_base_hooks=
957
958 setup_base_ssh_keys ()
959 {
960     # this is needed as git doesn't store file permissions other
961     # than execute
962     # Note that we protect the wildcards from the local shell.
963     diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
964     diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
965     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
966        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
967        diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
968     fi
969     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
970        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
971        diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
972     fi
973 }
974
975 register_hook setup_base_hooks setup_base_ssh_keys
976
977 setup_base_grub_conf ()
978 {
979     echo "Adjusting grub.conf"
980     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
981     local grub_configs="/boot/grub/grub.conf"
982     if ! diskimage is_file "$grub_configs" ; then
983         grub_configs="/etc/default/grub /boot/grub2/grub.cfg"
984     fi
985     local c
986     for c in $grub_configs ; do
987         diskimage sed "$c" \
988             -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
989             -e "s/ console=tty1//" -e "s/ rhgb/ norhgb/"  \
990             -e "s/ nodmraid//" -e "s/ nompath//"  \
991             -e "s/quiet/noapic divider=10${o:+ }${o}/g"
992     done
993 }
994
995 register_hook setup_base_hooks setup_base_grub_conf
996
997 setup_base()
998 {
999     local type="$1"
1000
1001     umask 022
1002     echo "Copy base files"
1003     copy_base_dir_substitute_templates "all"
1004     if [ -n "$type" ] ; then
1005         copy_base_dir_substitute_templates "$type"
1006     fi
1007
1008     run_hooks setup_base_hooks
1009 }
1010
1011 ipv4_prefix_to_netmask ()
1012 {
1013     local prefix="$1"
1014
1015     local div=$(($prefix / 8))
1016     local mod=$(($prefix % 8))
1017
1018     local octet
1019     for octet in 1 2 3 4 ; do
1020         if [ $octet -le $div ] ; then
1021             echo -n "255"
1022         elif [ $mod -ne 0 -a $octet -eq $(($div + 1)) ] ; then
1023             local shift=$((8 - $mod))
1024             echo -n $(( (255 >> $shift << $shift) ))
1025         else
1026             echo -n 0
1027         fi
1028         if [ $octet -lt 4 ] ; then
1029             echo -n '.'
1030         fi
1031     done
1032
1033     echo
1034 }
1035
1036 # setup various networking components
1037 setup_network()
1038 {
1039     # This avoids doing anything when we're called from boot_base().
1040     if [ -z "$hosts_file" ] ; then
1041         echo "Skipping network-related setup"
1042         return
1043     fi
1044
1045     echo "Setting up networks"
1046     diskimage append_text_file "$hosts_file" "/etc/hosts"
1047
1048     echo "Setting up /etc/ctdb/nodes"
1049     diskimage mkdir_p "/etc/ctdb"
1050     if [ "$NETWORK_STACK" = "ipv4" ] ; then
1051         diskimage put "$nodes_file" "/etc/ctdb/nodes"
1052     elif [ "$NETWORK_STACK" = "ipv6" ] ; then
1053         diskimage put "$nodes_file_ipv6" "/etc/ctdb/nodes"
1054     elif [ "$NETWORK_STACK" = "dual" ] ; then
1055         diskimage put "$nodes_file" "/etc/ctdb/nodes.ipv4"
1056         diskimage put "$nodes_file_ipv6" "/etc/ctdb/nodes.ipv6"
1057         diskimage put "$nodes_file" "/etc/ctdb/nodes"
1058     else
1059         die "Error: Invalid NETWORK_STACK value \"$NETWORK_STACK\"."
1060     fi
1061
1062     [ "$WEBPROXY" = "" ] || {
1063         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
1064     }
1065
1066     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
1067         echo "Enabling nfs mount of $NFSSHARE"
1068         diskimage mkdir_p "$NFS_MOUNTPOINT"
1069         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
1070     fi
1071
1072     diskimage mkdir_p "/etc/yum.repos.d"
1073     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
1074
1075     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
1076
1077     echo "Setting up network interfaces: "
1078     local netname dev ip ipv6 mac opts
1079     while read netname dev ip ipv6 mac opts; do
1080         echo "  $dev"
1081
1082         local o gw addr mask
1083         gw=""
1084         for o in $opts ; do
1085             case "$o" in
1086                 gw\=*)
1087                     gw="${o#gw=}"
1088             esac
1089         done
1090
1091         addr=${ip%/*}
1092         mask=$(ipv4_prefix_to_netmask ${ip#*/})
1093
1094         cat <<EOF | \
1095             diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
1096 DEVICE=$dev
1097 ONBOOT=yes
1098 TYPE=Ethernet
1099 IPADDR=$addr
1100 NETMASK=$mask
1101 HWADDR=$mac
1102 IPV6INIT=yes
1103 IPV6ADDR=$ipv6
1104 ${gw:+GATEWAY=}${gw}
1105 EOF
1106
1107         # This goes to 70-persistent-net.rules
1108         cat <<EOF
1109 # Generated by autocluster
1110 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
1111
1112 EOF
1113     done <"$network_map" |
1114     diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
1115 }
1116
1117 register_hook setup_base_hooks setup_network
1118
1119 setup_base_cluster_setup_config ()
1120 {
1121     local f
1122     {
1123         echo "# Generated by autocluster"
1124         echo
1125         # This is a bit of a hack.  Perhaps these script belong
1126         # elsewhere, since they no longer have templates?
1127         for f in $(find "${BASE_TEMPLATES}/all/root/scripts" -type f |
1128             xargs grep -l '^#config:') ; do
1129
1130             b=$(basename "$f")
1131             echo "# $b"
1132             local vs v
1133             vs=$(sed -n 's@^#config: *@@p' "$f")
1134             for v in $vs ; do
1135                 # This could substitute the values in directly using
1136                 # ${!v} but then no sanity checking is done to make
1137                 # sure variables are set.
1138                 echo "${v}=\"@@${v}@@\""
1139             done
1140             echo
1141         done
1142     } | diskimage substitute_vars - "/root/scripts/cluster_setup.config"
1143 }
1144
1145 register_hook setup_base_hooks setup_base_cluster_setup_config
1146
1147 setup_timezone() {
1148     [ -z "$TIMEZONE" ] && {
1149         [ -r /etc/timezone ] && {
1150             TIMEZONE=`cat /etc/timezone`
1151         }
1152         [ -r /etc/sysconfig/clock ] && {
1153             . /etc/sysconfig/clock
1154             TIMEZONE="$ZONE"
1155         }
1156         TIMEZONE="${TIMEZONE// /_}"
1157     }
1158     [ -n "$TIMEZONE" ] || \
1159         die "Unable to determine TIMEZONE - please set in config"
1160 }
1161
1162 # substite a set of variables of the form @@XX@@ for the shell
1163 # variables $XX in a file.
1164 #
1165 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
1166 # contain a filename whose contents are substituted, with variable
1167 # substitution applied to those contents.  If filename starts with '|'
1168 # it is a command instead - however, quoting is extremely fragile.
1169 substitute_vars() {(
1170         infile="${1:-/dev/null}" # if empty then default to /dev/null
1171         outfile="$2" # optional
1172
1173         tmp_out=$(mktemp)
1174         cat "$infile" >"$tmp_out"
1175
1176         # Handle any indirects by looping until nothing changes.
1177         # However, only handle 10 levels of recursion.
1178         count=0
1179         while : ; do
1180             if ! _substitute_vars "$tmp_out" "@@@" ; then
1181                 rm -f "$tmp_out"
1182                 die "Failed to expand template $infile"
1183             fi
1184
1185             # No old version of file means no changes made.
1186             if [ ! -f "${tmp_out}.old" ] ; then
1187                 break
1188             fi
1189
1190             rm -f "${tmp_out}.old"
1191
1192             count=$(($count + 1))
1193             if [ $count -ge 10 ] ; then
1194                 rm -f "$tmp_out"
1195                 die "Recursion too deep in $infile - only 10 levels allowed!"
1196             fi
1197         done
1198
1199         # Now regular variables.
1200         if ! _substitute_vars "$tmp_out" "@@" ; then
1201             rm -f "$tmp_out"
1202             die "Failed to expand template $infile"
1203         fi
1204         rm -f "${tmp_out}.old"
1205
1206         if [ -n "$outfile" ] ; then
1207             mv "$tmp_out" "$outfile"
1208         else
1209             cat "$tmp_out"
1210             rm -f "$tmp_out"
1211         fi
1212 )}
1213
1214
1215 # Delimiter @@ means to substitute contents of variable.
1216 # Delimiter @@@ means to substitute contents of file named by variable.
1217 # @@@ supports leading '|' in variable value, which means to excute a
1218 # command.
1219 _substitute_vars() {(
1220         tmp_out="$1"
1221         delimiter="${2:-@@}"
1222
1223         # Get the list of variables used in the template.  The grep
1224         # gets rid of any blank lines and lines with extraneous '@'s
1225         # next to template substitutions.
1226         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
1227             grep '^[A-Z0-9_][A-Z0-9_]*$' |
1228             sort -u)
1229
1230         tmp=$(mktemp)
1231         for v in $VARS; do
1232             # variable variables are fun .....
1233             [ "${!v+x}" ] || {
1234                 rm -f $tmp
1235                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
1236             }
1237             s=${!v}
1238
1239             if [ "$delimiter" = "@@@" ] ; then
1240                 f=${s:-/dev/null}
1241                 c="${f#|}" # Is is a command, signified by a leading '|'?
1242                 if [ "$c" = "$f" ] ; then
1243                     # No leading '|', cat file.
1244                     s=$(cat -- "$f")
1245                     [ $? -eq 0 ] || {
1246                         rm -f $tmp
1247                         die "Could not substitute contents of file $f"
1248                     }
1249                 else
1250                     # Leading '|', execute command.
1251                     # Quoting problems here - using eval "$c" doesn't help.
1252                     s=$($c)
1253                     [ $? -eq 0 ] || {
1254                         rm -f $tmp
1255                         die "Could not execute command $c"
1256                     }
1257                 fi
1258             fi
1259
1260             # escape some pesky chars
1261             # This first one can be too slow if done using a bash
1262             # variable pattern subsitution.
1263             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
1264             s=${s//#/\\#}
1265             s=${s//&/\\&}
1266             echo "s#${delimiter}${v}${delimiter}#${s}#g"
1267         done > $tmp
1268
1269         # Get the in-place sed to make a backup of the old file.
1270         # Remove the backup if it is the same as the resulting file -
1271         # this acts as a flag to the caller that no changes were made.
1272         sed -i.old -f $tmp "$tmp_out"
1273         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
1274             rm -f "${tmp_out}.old"
1275         fi
1276
1277         rm -f $tmp
1278 )}
1279
1280 check_command() {
1281     which $1 > /dev/null || die "Please install $1 to continue"
1282 }
1283
1284 # Set a variable if it isn't already set.  This allows environment
1285 # variables to override default config settings.
1286 defconf() {
1287     local v="$1"
1288     local e="$2"
1289
1290     [ "${!v+x}" ] || eval "$v=\"$e\""
1291 }
1292
1293 load_config () {
1294     local i
1295
1296     for i in "${installdir}/config.d/"*.defconf ; do
1297         . "$i"
1298     done
1299 }
1300
1301 # Print the list of config variables defined in config.d/.
1302 get_config_options () {( # sub-shell for local declaration of defconf()
1303         local options=
1304         defconf() { options="$options $1" ; }
1305         load_config
1306         echo $options
1307 )}
1308
1309 # Produce a list of long options, suitable for use with getopt, that
1310 # represent the config variables defined in config.d/.
1311 getopt_config_options () {
1312     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
1313     echo "${x// /:,}:"
1314 }
1315
1316 # Unconditionally set the config variable associated with the given
1317 # long option.
1318 setconf_longopt () {
1319     local longopt="$1"
1320     local e="$2"
1321
1322     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
1323     # unset so defconf will set it
1324     eval "unset $v"
1325     defconf "$v" "$e"
1326 }
1327
1328 # Dump all of the current config variables.
1329 dump_config() {
1330     local o
1331     for o in $(get_config_options) ; do
1332         echo "${o}=\"${!o}\""
1333     done
1334     exit 0
1335 }
1336
1337 # $COLUMNS is set in interactive bash shells.  It probably isn't set
1338 # in this shell, so let's set it if it isn't.
1339 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1340 : ${COLUMNS:=80}
1341 export COLUMNS
1342
1343 # Print text assuming it starts after other text in $startcol and
1344 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1345 # Long "words" will extend past $COLUMNS - 2.
1346 fill_text() {
1347     local startcol="$1"
1348     local text="$2"
1349
1350     local width=$(($COLUMNS - 2 - $startcol))
1351     [ $width -lt 0 ] && width=$((78 - $startcol))
1352
1353     local out=""
1354
1355     local padding
1356     if [ $startcol -gt 0 ] ; then
1357         padding=$(printf "\n%${startcol}s" " ")
1358     else
1359         padding="
1360 "
1361     fi
1362
1363     while [ -n "$text" ] ; do
1364         local orig="$text"
1365
1366         # If we already have output then arrange padding on the next line.
1367         [ -n "$out" ] && out="${out}${padding}"
1368
1369         # Break the text at $width.
1370         out="${out}${text:0:${width}}"
1371         text="${text:${width}}"
1372
1373         # If we have left over text then the line break may be ugly,
1374         # so let's check and try to break it on a space.
1375         if [ -n "$text" ] ; then
1376             # The 'x's stop us producing a special character like '(',
1377             # ')' or '!'.  Yuck - there must be a better way.
1378             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1379                 # We didn't break on a space.  Arrange for the
1380                 # beginning of the broken "word" to appear on the next
1381                 # line but not if it will make us loop infinitely.
1382                 if [ "${orig}" != "${out##* }${text}" ] ; then
1383                     text="${out##* }${text}"
1384                     out="${out% *}"
1385                 else
1386                     # Hmmm, doing that would make us loop, so add the
1387                     # rest of the word from the remainder of the text
1388                     # to this line and let it extend past $COLUMNS - 2.
1389                     out="${out}${text%% *}"
1390                     if [ "${text# *}" != "$text" ] ; then
1391                         # Remember the text after the next space for next time.
1392                         text="${text# *}"
1393                     else
1394                         # No text after next space.
1395                         text=""
1396                     fi
1397                 fi
1398             else
1399                 # We broke on a space.  If it will be at the beginning
1400                 # of the next line then remove it.
1401                 text="${text# }"
1402             fi
1403         fi
1404     done
1405
1406     echo "$out"
1407 }
1408
1409 # Display usage text, trying these approaches in order.
1410 # 1. See if it all fits on one line before $COLUMNS - 2.
1411 # 2. See if splitting before the default value and indenting it
1412 #    to $startcol means that nothing passes $COLUMNS - 2.
1413 # 3. Treat the message and default value as a string and just us fill_text()
1414 #    to format it. 
1415 usage_display_text () {
1416     local startcol="$1"
1417     local desc="$2"
1418     local default="$3"
1419     
1420     local width=$(($COLUMNS - 2 - $startcol))
1421     [ $width -lt 0 ] && width=$((78 - $startcol))
1422
1423     default="(default \"$default\")"
1424
1425     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1426         echo "${desc} ${default}"
1427     else
1428         local padding=$(printf "%${startcol}s" " ")
1429
1430         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1431             echo "$desc"
1432             echo "${padding}${default}"
1433         else
1434             fill_text $startcol "${desc} ${default}"
1435         fi
1436     fi
1437 }
1438
1439 # Display usage information for long config options.
1440 usage_smart_display () {( # sub-shell for local declaration of defconf()
1441         local startcol=33
1442
1443         defconf() {
1444             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1445
1446             printf "     --%-25s " "${longopt}=${3}"
1447
1448             usage_display_text $startcol "$4" "$2"
1449         }
1450
1451         "$@"
1452 )}
1453
1454
1455 # Display usage information for long config options.
1456 usage_config_options (){
1457     usage_smart_display load_config
1458 }
1459
1460 actions_init ()
1461 {
1462     actions=""
1463 }
1464
1465 actions_add ()
1466 {
1467     actions="${actions}${actions:+ }$*"
1468 }
1469
1470 actions_run ()
1471 {
1472     [ -n "$actions" ] || usage
1473
1474     local a
1475     for a in $actions ; do
1476         $a
1477     done
1478 }
1479
1480 ######################################################################
1481
1482 post_config_hooks=
1483
1484 ######################################################################
1485
1486 load_config
1487
1488 ############################
1489 # parse command line options
1490 long_opts=$(getopt_config_options)
1491 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump -l "$long_opts" -- "$@")
1492 [ $? != 0 ] && usage
1493
1494 use_default_config=true
1495
1496 # We do 2 passes of the options.  The first time we just handle usage
1497 # and check whether -c is being used.
1498 eval set -- "$getopt_output"
1499 while true ; do
1500     case "$1" in
1501         -c) shift 2 ; use_default_config=false ;;
1502         -e) shift 2 ;;
1503         -E) shift 2 ;;
1504         --) shift ; break ;;
1505         --dump|-x) shift ;;
1506         -h|--help) usage ;; # Usage should be shown here for real defaults.
1507         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1508         *) usage ;; # shouldn't happen, so this is reasonable.
1509     esac
1510 done
1511
1512 config="./config"
1513 $use_default_config && [ -r "$config" ] && . "$config"
1514
1515 eval set -- "$getopt_output"
1516
1517 while true ; do
1518     case "$1" in
1519         -c)
1520             b=$(basename $2)
1521             # force at least ./local_file to avoid accidental file
1522             # from $PATH
1523             . "$(dirname $2)/${b}"
1524             # If $CLUSTER is unset then try to base it on the filename
1525             if [ ! -n "$CLUSTER" ] ; then
1526                 case "$b" in
1527                     *.autocluster)
1528                         CLUSTER="${b%.autocluster}"
1529                 esac
1530             fi
1531             shift 2
1532             ;;
1533         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1534         -E) eval "$2" ; shift 2 ;;
1535         -x) set -x; shift ;;
1536         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1537         --) shift ; break ;;
1538         -h|--help) usage ;; # Redundant.
1539         --*)
1540             # Putting --opt1|opt2|... into a variable and having case
1541             # match against it as a pattern doesn't work.  The | is
1542             # part of shell syntax, so we need to do this.  Look away
1543             # now to stop your eyes from bleeding! :-)
1544             x=",${long_opts}" # Now each option is surrounded by , and :
1545             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1546                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1547                 setconf_longopt "$1" "$2"; shift 2
1548             else
1549                 usage
1550             fi
1551             ;;
1552         *) usage ;; # shouldn't happen, so this is reasonable.
1553     esac
1554 done
1555
1556 run_hooks post_config_hooks 
1557
1558 # catch errors
1559 set -e
1560 set -E
1561 trap 'es=$?; 
1562       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1563       exit $es' ERR
1564
1565 # check for needed programs 
1566 check_command expect
1567
1568 [ $# -lt 1 ] && usage
1569
1570 t="$1"
1571 shift
1572
1573 case "$t" in
1574     base)
1575         actions_init
1576         for t in "$@" ; do
1577             case "$t" in
1578                 create|boot) actions_add "base_${t}" ;;
1579                 *) usage ;;
1580             esac
1581         done
1582         actions_run
1583         ;;
1584
1585     cluster)
1586         actions_init
1587         for t in "$@" ; do
1588             case "$t" in
1589                 destroy|undefine|create|update_hosts|boot|setup)
1590                     actions_add "cluster_${t}" ;;
1591                 build)
1592                     for t in destroy undefine create update_hosts boot setup ; do
1593                         actions_add "cluster_${t}"
1594                     done
1595                     ;;
1596                 *) usage ;;
1597             esac
1598         done
1599         cluster_nodelist_hacking
1600         actions_run
1601         ;;
1602
1603     create)
1604         t="$1"
1605         shift
1606         case "$t" in
1607             base)
1608                 [ $# != 0 ] && usage
1609                 base_create
1610                 ;;
1611             cluster)
1612                 [ $# != 1 ] && usage
1613                 cluster_create "$1"
1614                 ;;
1615             node)
1616                 [ $# != 2 ] && usage
1617                 create_one_node "$1" "$2"
1618                 ;;
1619             *)
1620                 usage;
1621                 ;;
1622         esac
1623         ;;
1624     mount)
1625         [ $# != 1 ] && usage
1626         diskimage mount "$1"
1627         ;;
1628     unmount|umount)
1629         [ $# != 0 ] && usage
1630         diskimage unmount
1631         ;;
1632     bootbase)
1633         base_boot;
1634         ;;
1635     *)
1636         usage;
1637         ;;
1638 esac