Replace external waitfor script with a function
[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 | configure ] ...
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_configure ()
600 {
601     announce "cluster configure \"${CLUSTER}\""
602     [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
603
604     local n1="${CLUSTER}n1"
605     local ssh="ssh -o StrictHostKeyChecking=no"
606
607     case "$CLUSTER_TYPE" in
608         "build")
609             $ssh "$n1" ./scripts/install_packages.sh clusterfs build
610             $ssh "$n1" ./scripts/setup_cluster.sh build
611             ;;
612
613         "ad")
614             $ssh "$n1" ./scripts/install_packages.sh ad_server
615             $ssh "$n1" ./scripts/configure_cluster.sh ad_server
616             ;;
617
618         "samba")
619             [ -n "$CLUSTER_PATTERN" ] || CLUSTER_PATTERN="$CLUSTER"
620
621             local nodes=$(vircmd dominfo "$CLUSTER_PATTERN" 2>/dev/null | \
622                 sed -n -e 's/Name: *//p')
623
624             for i in $nodes ; do
625                 $ssh "$i" ./scripts/install_packages.sh clusterfs nas
626             done
627
628             $ssh "$n1" ./scripts/setup_cluster.sh clusterfs nas
629             ;;
630     esac
631 }
632
633 create_one_node ()
634 {
635     CLUSTER="$1"
636     local single_node_ip_offset="$2"
637
638     sanity_check_cluster_name
639
640     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
641
642     common_nodelist_hacking
643
644     for n in $NODES ; do
645         set -- $(IFS=: ; echo $n)
646         [ $single_node_ip_offset -eq $2 ] || continue
647         call_func create_node "$@"
648         
649         echo "Requested node created"
650         echo ""
651         echo "You may want to update your /etc/hosts file:"
652         cat $hosts_file
653         
654         break
655     done
656 }
657
658 ###############################
659 # test the proxy setup
660 test_proxy() {
661     export http_proxy=$WEBPROXY
662     wget -O /dev/null $INSTALL_SERVER || \
663         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
664     echo "Proxy OK"
665 }
666
667 ###################
668
669 kickstart_floppy_create_hooks=
670
671 guess_install_network ()
672 {
673     # Figure out IP address to use during base install.  Default to
674     # the IP address of the 1st (private) network. If a gateway is
675     # specified then use the IP address associated with it.
676     INSTALL_IP=""
677     INSTALL_GW=""
678     local netname dev ip mask mac opts
679     while read netname dev ip mask mac opts; do
680         local o
681         for o in $opts ; do
682             case "$o" in
683                 gw\=*)
684                     INSTALL_GW="${o#gw=}"
685                     INSTALL_IP="${ip}${FIRSTIP}"
686             esac
687         done
688         [ -n "$INSTALL_IP" ] || INSTALL_IP="$ip"
689     done <"$network_map"
690 }
691
692 # create base image
693 base_create()
694 {
695     local NAME="$BASENAME"
696     local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
697     run_hooks hack_disk_hooks "base"
698
699     mkdir -p $KVMLOG
700
701     echo "Testing WEBPROXY $WEBPROXY"
702     test_proxy
703
704     local di="$DISK"
705     if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
706         di=$(readlink "$DISK")
707     fi
708     rm -f "$di"
709     local di_dirname="${di%/*}"
710     mkdir -p "$di_dirname"
711
712     echo "Creating the disk"
713     qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
714
715     rm -rf tmp
716     mkdir -p mnt tmp tmp/ISO
717
718     setup_timezone
719
720     make_network_map
721
722     guess_install_network
723
724     echo "Creating kickstart file from template"
725     substitute_vars "$KICKSTART" "tmp/ks.cfg"
726
727     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
728     case "$ISO" in
729         (/*) : ;;
730         (*) ISO="${ISO_DIR}/${ISO}"
731     esac
732     
733     echo "Creating kickstart floppy"
734     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
735     mkdosfs -n KICKSTART tmp/floppy.img
736     mount -o loop -t msdos tmp/floppy.img mnt
737     cp tmp/ks.cfg mnt
738     mount -o loop,ro $ISO tmp/ISO
739     
740     echo "Setting up bootloader"
741     cp tmp/ISO/isolinux/isolinux.bin tmp
742     cp tmp/ISO/isolinux/vmlinuz tmp
743     cp tmp/ISO/isolinux/initrd.img tmp
744
745     run_hooks kickstart_floppy_create_hooks
746
747     umount tmp/ISO
748     umount mnt
749
750     UUID=`uuidgen`
751
752     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
753
754     rm -f $KVMLOG/serial.$NAME
755
756     # boot the install CD
757     $VIRSH create tmp/$NAME.xml
758
759     echo "Waiting for install to start"
760     sleep 2
761     
762     # wait for the install to finish
763     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
764         $VIRSH destroy $NAME
765         die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
766 You may need to increase the value of CREATE_BASE_TIMEOUT.
767 Alternatively, the install might have completed but KS_DONE_MESSAGE
768 (currently \"${KS_DONE_MESSAGE}\")
769 may not have matched anything at the end of the kickstart output."
770     fi
771     
772     $VIRSH destroy $NAME
773
774     ls -l $DISK
775     cat <<EOF
776
777 Install finished, base image $DISK created
778
779 You may wish to run
780    chcon -t virt_content_t $DISK
781    chattr +i $DISK
782 To ensure that this image does not change
783
784 Note that the root password has been set to $ROOTPASSWORD
785
786 EOF
787 }
788
789 ###############################
790 # boot the base disk
791 base_boot() {
792     rm -rf tmp
793     mkdir -p tmp
794
795     NAME="$BASENAME"
796     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
797
798     IPNUM=$FIRSTIP
799
800     make_network_map
801
802     CLUSTER="base"
803
804     diskimage mount $DISK
805     setup_base
806     diskimage unmount
807
808     UUID=`uuidgen`
809     
810     echo "Creating $NAME.xml"
811     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
812     
813     # boot the base system
814     $VIRSH create tmp/$NAME.xml
815 }
816
817 ######################################################################
818
819 # Updating a disk image...
820
821 diskimage ()
822 {
823     local func="$1"
824     shift
825     call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
826 }
827
828 # setup the files from $BASE_TEMPLATES/, substituting any variables
829 # based on the config
830 copy_base_dir_substitute_templates ()
831 {
832     local dir="$1"
833
834     local d="$BASE_TEMPLATES/$dir"
835     [ -d "$d" ] || return 0
836
837     local f
838     for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
839         f="${f#./}" # remove leading "./" for clarity
840         if [ -d "$d/$f" ]; then
841             # Don't chmod existing directory
842             if diskimage is_directory "/$f" ; then
843                 continue
844             fi
845             diskimage mkdir_p "/$f"
846         else
847             echo " Install: $f"
848             diskimage substitute_vars "$d/$f" "/$f"
849         fi
850         diskimage chmod_reference "$d/$f" "/$f"
851     done
852 }
853
854 setup_base_hooks=
855
856 setup_base_ssh_keys ()
857 {
858     # this is needed as git doesn't store file permissions other
859     # than execute
860     # Note that we protect the wildcards from the local shell.
861     diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
862     diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
863     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
864        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
865        diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
866     fi
867     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
868        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
869        diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
870     fi
871 }
872
873 register_hook setup_base_hooks setup_base_ssh_keys
874
875 setup_base_grub_conf ()
876 {
877     echo "Adjusting grub.conf"
878     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
879     local grub_configs="/boot/grub/grub.conf"
880     if ! diskimage is_file "$grub_configs" ; then
881         grub_configs="/etc/default/grub /boot/grub2/grub.cfg"
882     fi
883     local c
884     for c in $grub_configs ; do
885         diskimage sed "$c" \
886             -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
887             -e "s/ console=tty1//" -e "s/ rhgb/ norhgb/"  \
888             -e "s/ nodmraid//" -e "s/ nompath//"  \
889             -e "s/quiet/noapic divider=10${o:+ }${o}/g"
890     done
891 }
892
893 register_hook setup_base_hooks setup_base_grub_conf
894
895 setup_base()
896 {
897     local type="$1"
898
899     umask 022
900     echo "Copy base files"
901     copy_base_dir_substitute_templates "all"
902     if [ -n "$type" ] ; then
903         copy_base_dir_substitute_templates "$type"
904     fi
905
906     run_hooks setup_base_hooks
907 }
908
909 # setup various networking components
910 setup_network()
911 {
912     # This avoids doing anything when we're called from boot_base().
913     if [ -z "$hosts_file" ] ; then
914         echo "Skipping network-related setup"
915         return
916     fi
917
918     echo "Setting up networks"
919     diskimage append_text_file "$hosts_file" "/etc/hosts"
920
921     echo "Setting up /etc/ctdb/nodes"
922     diskimage mkdir_p "/etc/ctdb"
923     diskimage put "$nodes_file" "/etc/ctdb/nodes"
924
925     [ "$WEBPROXY" = "" ] || {
926         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
927     }
928
929     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
930         echo "Enabling nfs mount of $NFSSHARE"
931         diskimage mkdir_p "$NFS_MOUNTPOINT"
932         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
933     fi
934
935     diskimage mkdir_p "/etc/yum.repos.d"
936     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
937
938     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
939
940     echo "Setting up network interfaces: "
941     local netname dev ip mask mac opts
942     while read netname dev ip mask mac opts; do
943         echo "  $dev"
944
945         local o gw
946         gw=""
947         for o in $opts ; do
948             case "$o" in
949                 gw\=*)
950                     gw="${o#gw=}"
951             esac
952         done
953
954         cat <<EOF | \
955             diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
956 DEVICE=$dev
957 ONBOOT=yes
958 TYPE=Ethernet
959 IPADDR=$ip
960 NETMASK=$mask
961 HWADDR=$mac
962 ${gw:+GATEWAY=}${gw}
963 EOF
964
965         # This goes to 70-persistent-net.rules
966         cat <<EOF
967 # Generated by autocluster
968 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
969
970 EOF
971     done <"$network_map" |
972     diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
973 }
974
975 register_hook setup_base_hooks setup_network
976
977 setup_timezone() {
978     [ -z "$TIMEZONE" ] && {
979         [ -r /etc/timezone ] && {
980             TIMEZONE=`cat /etc/timezone`
981         }
982         [ -r /etc/sysconfig/clock ] && {
983             . /etc/sysconfig/clock
984             TIMEZONE="$ZONE"
985         }
986         TIMEZONE="${TIMEZONE// /_}"
987     }
988     [ -n "$TIMEZONE" ] || \
989         die "Unable to determine TIMEZONE - please set in config"
990 }
991
992 # substite a set of variables of the form @@XX@@ for the shell
993 # variables $XX in a file.
994 #
995 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
996 # contain a filename whose contents are substituted, with variable
997 # substitution applied to those contents.  If filename starts with '|'
998 # it is a command instead - however, quoting is extremely fragile.
999 substitute_vars() {(
1000         infile="${1:-/dev/null}" # if empty then default to /dev/null
1001         outfile="$2" # optional
1002
1003         tmp_out=$(mktemp)
1004         cat "$infile" >"$tmp_out"
1005
1006         # Handle any indirects by looping until nothing changes.
1007         # However, only handle 10 levels of recursion.
1008         count=0
1009         while : ; do
1010             if ! _substitute_vars "$tmp_out" "@@@" ; then
1011                 rm -f "$tmp_out"
1012                 die "Failed to expand template $infile"
1013             fi
1014
1015             # No old version of file means no changes made.
1016             if [ ! -f "${tmp_out}.old" ] ; then
1017                 break
1018             fi
1019
1020             rm -f "${tmp_out}.old"
1021
1022             count=$(($count + 1))
1023             if [ $count -ge 10 ] ; then
1024                 rm -f "$tmp_out"
1025                 die "Recursion too deep in $infile - only 10 levels allowed!"
1026             fi
1027         done
1028
1029         # Now regular variables.
1030         if ! _substitute_vars "$tmp_out" "@@" ; then
1031             rm -f "$tmp_out"
1032             die "Failed to expand template $infile"
1033         fi
1034         rm -f "${tmp_out}.old"
1035
1036         if [ -n "$outfile" ] ; then
1037             mv "$tmp_out" "$outfile"
1038         else
1039             cat "$tmp_out"
1040             rm -f "$tmp_out"
1041         fi
1042 )}
1043
1044
1045 # Delimiter @@ means to substitute contents of variable.
1046 # Delimiter @@@ means to substitute contents of file named by variable.
1047 # @@@ supports leading '|' in variable value, which means to excute a
1048 # command.
1049 _substitute_vars() {(
1050         tmp_out="$1"
1051         delimiter="${2:-@@}"
1052
1053         # Get the list of variables used in the template.  The grep
1054         # gets rid of any blank lines and lines with extraneous '@'s
1055         # next to template substitutions.
1056         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
1057             grep '^[A-Z0-9_][A-Z0-9_]*$' |
1058             sort -u)
1059
1060         tmp=$(mktemp)
1061         for v in $VARS; do
1062             # variable variables are fun .....
1063             [ "${!v+x}" ] || {
1064                 rm -f $tmp
1065                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
1066             }
1067             s=${!v}
1068
1069             if [ "$delimiter" = "@@@" ] ; then
1070                 f=${s:-/dev/null}
1071                 c="${f#|}" # Is is a command, signified by a leading '|'?
1072                 if [ "$c" = "$f" ] ; then
1073                     # No leading '|', cat file.
1074                     s=$(cat -- "$f")
1075                     [ $? -eq 0 ] || {
1076                         rm -f $tmp
1077                         die "Could not substitute contents of file $f"
1078                     }
1079                 else
1080                     # Leading '|', execute command.
1081                     # Quoting problems here - using eval "$c" doesn't help.
1082                     s=$($c)
1083                     [ $? -eq 0 ] || {
1084                         rm -f $tmp
1085                         die "Could not execute command $c"
1086                     }
1087                 fi
1088             fi
1089
1090             # escape some pesky chars
1091             # This first one can be too slow if done using a bash
1092             # variable pattern subsitution.
1093             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
1094             s=${s//#/\\#}
1095             s=${s//&/\\&}
1096             echo "s#${delimiter}${v}${delimiter}#${s}#g"
1097         done > $tmp
1098
1099         # Get the in-place sed to make a backup of the old file.
1100         # Remove the backup if it is the same as the resulting file -
1101         # this acts as a flag to the caller that no changes were made.
1102         sed -i.old -f $tmp "$tmp_out"
1103         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
1104             rm -f "${tmp_out}.old"
1105         fi
1106
1107         rm -f $tmp
1108 )}
1109
1110 check_command() {
1111     which $1 > /dev/null || die "Please install $1 to continue"
1112 }
1113
1114 # Set a variable if it isn't already set.  This allows environment
1115 # variables to override default config settings.
1116 defconf() {
1117     local v="$1"
1118     local e="$2"
1119
1120     [ "${!v+x}" ] || eval "$v=\"$e\""
1121 }
1122
1123 load_config () {
1124     local i
1125
1126     for i in "${installdir}/config.d/"*.defconf ; do
1127         . "$i"
1128     done
1129 }
1130
1131 # Print the list of config variables defined in config.d/.
1132 get_config_options () {( # sub-shell for local declaration of defconf()
1133         local options=
1134         defconf() { options="$options $1" ; }
1135         load_config
1136         echo $options
1137 )}
1138
1139 # Produce a list of long options, suitable for use with getopt, that
1140 # represent the config variables defined in config.d/.
1141 getopt_config_options () {
1142     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
1143     echo "${x// /:,}:"
1144 }
1145
1146 # Unconditionally set the config variable associated with the given
1147 # long option.
1148 setconf_longopt () {
1149     local longopt="$1"
1150     local e="$2"
1151
1152     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
1153     # unset so defconf will set it
1154     eval "unset $v"
1155     defconf "$v" "$e"
1156 }
1157
1158 # Dump all of the current config variables.
1159 dump_config() {
1160     local o
1161     for o in $(get_config_options) ; do
1162         echo "${o}=\"${!o}\""
1163     done
1164     exit 0
1165 }
1166
1167 # $COLUMNS is set in interactive bash shells.  It probably isn't set
1168 # in this shell, so let's set it if it isn't.
1169 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1170 : ${COLUMNS:=80}
1171 export COLUMNS
1172
1173 # Print text assuming it starts after other text in $startcol and
1174 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1175 # Long "words" will extend past $COLUMNS - 2.
1176 fill_text() {
1177     local startcol="$1"
1178     local text="$2"
1179
1180     local width=$(($COLUMNS - 2 - $startcol))
1181     [ $width -lt 0 ] && width=$((78 - $startcol))
1182
1183     local out=""
1184
1185     local padding
1186     if [ $startcol -gt 0 ] ; then
1187         padding=$(printf "\n%${startcol}s" " ")
1188     else
1189         padding="
1190 "
1191     fi
1192
1193     while [ -n "$text" ] ; do
1194         local orig="$text"
1195
1196         # If we already have output then arrange padding on the next line.
1197         [ -n "$out" ] && out="${out}${padding}"
1198
1199         # Break the text at $width.
1200         out="${out}${text:0:${width}}"
1201         text="${text:${width}}"
1202
1203         # If we have left over text then the line break may be ugly,
1204         # so let's check and try to break it on a space.
1205         if [ -n "$text" ] ; then
1206             # The 'x's stop us producing a special character like '(',
1207             # ')' or '!'.  Yuck - there must be a better way.
1208             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1209                 # We didn't break on a space.  Arrange for the
1210                 # beginning of the broken "word" to appear on the next
1211                 # line but not if it will make us loop infinitely.
1212                 if [ "${orig}" != "${out##* }${text}" ] ; then
1213                     text="${out##* }${text}"
1214                     out="${out% *}"
1215                 else
1216                     # Hmmm, doing that would make us loop, so add the
1217                     # rest of the word from the remainder of the text
1218                     # to this line and let it extend past $COLUMNS - 2.
1219                     out="${out}${text%% *}"
1220                     if [ "${text# *}" != "$text" ] ; then
1221                         # Remember the text after the next space for next time.
1222                         text="${text# *}"
1223                     else
1224                         # No text after next space.
1225                         text=""
1226                     fi
1227                 fi
1228             else
1229                 # We broke on a space.  If it will be at the beginning
1230                 # of the next line then remove it.
1231                 text="${text# }"
1232             fi
1233         fi
1234     done
1235
1236     echo "$out"
1237 }
1238
1239 # Display usage text, trying these approaches in order.
1240 # 1. See if it all fits on one line before $COLUMNS - 2.
1241 # 2. See if splitting before the default value and indenting it
1242 #    to $startcol means that nothing passes $COLUMNS - 2.
1243 # 3. Treat the message and default value as a string and just us fill_text()
1244 #    to format it. 
1245 usage_display_text () {
1246     local startcol="$1"
1247     local desc="$2"
1248     local default="$3"
1249     
1250     local width=$(($COLUMNS - 2 - $startcol))
1251     [ $width -lt 0 ] && width=$((78 - $startcol))
1252
1253     default="(default \"$default\")"
1254
1255     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1256         echo "${desc} ${default}"
1257     else
1258         local padding=$(printf "%${startcol}s" " ")
1259
1260         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1261             echo "$desc"
1262             echo "${padding}${default}"
1263         else
1264             fill_text $startcol "${desc} ${default}"
1265         fi
1266     fi
1267 }
1268
1269 # Display usage information for long config options.
1270 usage_smart_display () {( # sub-shell for local declaration of defconf()
1271         local startcol=33
1272
1273         defconf() {
1274             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1275
1276             printf "     --%-25s " "${longopt}=${3}"
1277
1278             usage_display_text $startcol "$4" "$2"
1279         }
1280
1281         "$@"
1282 )}
1283
1284
1285 # Display usage information for long config options.
1286 usage_config_options (){
1287     usage_smart_display load_config
1288 }
1289
1290 actions_init ()
1291 {
1292     actions=""
1293 }
1294
1295 actions_add ()
1296 {
1297     actions="${actions}${actions:+ }$*"
1298 }
1299
1300 actions_run ()
1301 {
1302     [ -n "$actions" ] || usage
1303
1304     local a
1305     for a in $actions ; do
1306         $a
1307     done
1308 }
1309
1310 ######################################################################
1311
1312 post_config_hooks=
1313
1314 ######################################################################
1315
1316 load_config
1317
1318 ############################
1319 # parse command line options
1320 long_opts=$(getopt_config_options)
1321 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump -l "$long_opts" -- "$@")
1322 [ $? != 0 ] && usage
1323
1324 use_default_config=true
1325
1326 # We do 2 passes of the options.  The first time we just handle usage
1327 # and check whether -c is being used.
1328 eval set -- "$getopt_output"
1329 while true ; do
1330     case "$1" in
1331         -c) shift 2 ; use_default_config=false ;;
1332         -e) shift 2 ;;
1333         -E) shift 2 ;;
1334         --) shift ; break ;;
1335         --dump|-x) shift ;;
1336         -h|--help) usage ;; # Usage should be shown here for real defaults.
1337         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1338         *) usage ;; # shouldn't happen, so this is reasonable.
1339     esac
1340 done
1341
1342 config="./config"
1343 $use_default_config && [ -r "$config" ] && . "$config"
1344
1345 eval set -- "$getopt_output"
1346
1347 while true ; do
1348     case "$1" in
1349         -c)
1350             b=$(basename $2)
1351             # force at least ./local_file to avoid accidental file
1352             # from $PATH
1353             . "$(dirname $2)/${b}"
1354             # If $CLUSTER is unset then try to base it on the filename
1355             if [ ! -n "$CLUSTER" ] ; then
1356                 case "$b" in
1357                     *.autocluster)
1358                         CLUSTER="${b%.autocluster}"
1359                 esac
1360             fi
1361             shift 2
1362             ;;
1363         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1364         -E) eval "$2" ; shift 2 ;;
1365         -x) set -x; shift ;;
1366         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1367         --) shift ; break ;;
1368         -h|--help) usage ;; # Redundant.
1369         --*)
1370             # Putting --opt1|opt2|... into a variable and having case
1371             # match against it as a pattern doesn't work.  The | is
1372             # part of shell syntax, so we need to do this.  Look away
1373             # now to stop your eyes from bleeding! :-)
1374             x=",${long_opts}" # Now each option is surrounded by , and :
1375             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1376                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1377                 setconf_longopt "$1" "$2"; shift 2
1378             else
1379                 usage
1380             fi
1381             ;;
1382         *) usage ;; # shouldn't happen, so this is reasonable.
1383     esac
1384 done
1385
1386 run_hooks post_config_hooks 
1387
1388 # catch errors
1389 set -e
1390 set -E
1391 trap 'es=$?; 
1392       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1393       exit $es' ERR
1394
1395 # check for needed programs 
1396 check_command expect
1397
1398 [ $# -lt 1 ] && usage
1399
1400 t="$1"
1401 shift
1402
1403 case "$t" in
1404     base)
1405         actions_init
1406         for t in "$@" ; do
1407             case "$t" in
1408                 create|boot) actions_add "base_${t}" ;;
1409                 *) usage ;;
1410             esac
1411         done
1412         actions_run
1413         ;;
1414
1415     cluster)
1416         actions_init
1417         for t in "$@" ; do
1418             case "$t" in
1419                 destroy|create|update_hosts|boot|configure)
1420                     actions_add "cluster_${t}" ;;
1421                 build)
1422                     for t in destroy create update_hosts boot configure ; do
1423                         actions_add "cluster_${t}"
1424                     done
1425                     ;;
1426                 *) usage ;;
1427             esac
1428         done
1429         actions_run
1430         ;;
1431
1432     create)
1433         t="$1"
1434         shift
1435         case "$t" in
1436             base)
1437                 [ $# != 0 ] && usage
1438                 base_create
1439                 ;;
1440             cluster)
1441                 [ $# != 1 ] && usage
1442                 cluster_create "$1"
1443                 ;;
1444             node)
1445                 [ $# != 2 ] && usage
1446                 create_one_node "$1" "$2"
1447                 ;;
1448             *)
1449                 usage;
1450                 ;;
1451         esac
1452         ;;
1453     mount)
1454         [ $# != 1 ] && usage
1455         diskimage mount "$1"
1456         ;;
1457     unmount|umount)
1458         [ $# != 0 ] && usage
1459         diskimage unmount
1460         ;;
1461     bootbase)
1462         base_boot;
1463         ;;
1464     *)
1465         usage;
1466         ;;
1467 esac