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