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