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