Build a UUID map file in common_nodelist_hacking.
[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     installdir="`dirname \"$0\"`"
25 else
26     autocluster=`which $0`
27     installdir="`dirname \"$autocluster\"`"
28 fi
29 ##END-INSTALLDIR-MAGIC##
30
31 ####################
32 # show program usage
33 usage ()
34 {
35     cat <<EOF
36 Usage: autocluster [OPTION] ... <COMMAND>
37   options:
38      -c <file>                   specify config file (default is "config")
39 EOF
40
41     releases=$(list_releases)
42
43     usage_smart_display \
44         defconf "WITH_RELEASE" "" \
45         "<string>" "specify preset options for a release using a version string.  Possible values are: ${releases}."
46
47 cat <<EOF
48      -e <expr>                   execute <expr> and exit (advanced debugging)
49      -x                          enable script debugging
50      --dump                      dump config settings and exit
51
52   configuration options:
53 EOF
54
55     usage_config_options
56
57     cat <<EOF
58
59   commands:
60      create base
61            create a base image
62
63      create cluster CLUSTERNAME
64            create a full cluster
65
66      create node CLUSTERNAME IP_OFFSET
67            (re)create a single cluster node
68
69      mount DISK
70            mount a qemu disk on mnt/
71
72      unmount
73            unmount a qemu disk from mnt/
74
75      bootbase
76            boot the base image
77
78      testproxy
79            test your proxy setup
80 EOF
81     exit 1
82 }
83
84 ###############################
85
86 die () {
87     fill_text 0 "ERROR: $*" >&2
88     exit 1
89 }
90
91 ###############################
92
93 # Indirectly call a function named by ${1}_${2}
94 call_func () {
95     local func="$1" ; shift
96     local type="$1" ; shift
97
98     local f="${func}_${type}"
99     if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
100         "$f" "$@"
101     else
102         f="${func}_DEFAULT"
103         if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null  ; then
104             "$f" "$type" "$@"
105         else
106             die "No function defined for \"${func}\" \"${type}\""
107         fi
108     fi
109 }
110
111 # Note that this will work if you pass "call_func f" because the first
112 # element of the node tuple is the node type.  Nice...  :-)
113 for_each_node ()
114 {
115     local n
116     for n in $NODES ; do
117         "$@" $(IFS=: ; echo $n)
118     done
119 }
120
121 hack_one_node_with ()
122 {
123     local filter="$1" ; shift
124
125     local node_type="$1"
126     local ip_offset="$2"
127     local name="$3"
128     local ctdb_node="$4"
129
130     $filter
131
132     local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
133     nodes="${nodes}${nodes:+ }${item}"
134 }
135
136 # This also gets used for non-filtering iteration.
137 hack_all_nodes_with ()
138 {
139     local filter="$1"
140
141     local nodes=""
142     for_each_node hack_one_node_with "$filter"
143     NODES="$nodes"
144 }
145
146 register_hook ()
147 {
148     local hook_var="$1"
149     local new_hook="$2"
150
151     eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
152 }
153
154 run_hooks ()
155 {
156     local hook_var="$1"
157
158     local i
159     for i in ${!hook_var} ; do
160         $i
161     done
162 }
163
164 # Use with care, since this may clear some autocluster defaults.!
165 clear_hooks ()
166 {
167     local hook_var="$1"
168
169     eval "$hook_var=\"\""
170 }
171
172 ##############################
173
174 # common node creation stuff
175 create_node_COMMON ()
176 {
177     local NAME="$1"
178     local ip_offset="$2"
179     local type="$3"
180     local template_file="${4:-$NODE_TEMPLATE}"
181
182     if [ "$SYSTEM_DISK_FORMAT" = "raw" -a "$BASE_FORMAT" != "raw" ] ; then
183         die "Error: if SYSTEM_DISK_FORMAT is \"raw\" then BASE_FORMAT must also be \"raw\"."
184     fi
185
186     IPNUM=$(($FIRSTIP + $ip_offset))
187     DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
188     local base_disk="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
189
190     if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
191         base_disk="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
192     fi
193
194     mkdir -p $VIRTBASE/$CLUSTER tmp
195
196     rm -f "$DISK"
197     case "$SYSTEM_DISK_FORMAT" in
198         qcow2)
199             echo "Creating the disk..."
200             qemu-img create -b "$base_disk" -f qcow2 "$DISK"
201             create_node_configure_image "$DISK" "$type"
202             ;;
203         raw)
204             echo "Creating the disk..."
205             cp -v --sparse=always "$base_disk" "$DISK"
206             create_node_configure_image "$DISK" "$type"
207             ;;
208         none)
209             echo "Skipping disk image creation as requested"
210             ;;
211         *)
212             die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
213     esac
214
215     set_macaddrs $CLUSTER $ip_offset
216     UUID=`uuidgen`
217     
218     echo "Creating $NAME.xml"
219     substitute_vars $template_file tmp/$NAME.xml
220     
221     # install the XML file
222     $VIRSH undefine $NAME > /dev/null 2>&1 || true
223     $VIRSH define tmp/$NAME.xml
224 }
225
226 create_node_configure_image ()
227 {
228     local disk="$1"
229     local type="$2"
230
231     mount_disk "$disk"
232     setup_base "$type"
233     unmount_disk
234 }
235
236 # Provides an easy way of removing nodes from $NODE.
237 create_node_null () {
238     :
239 }
240
241 ##############################
242
243 hack_nodes_functions=
244
245 expand_nodes () {
246     # Expand out any abbreviations in NODES.
247     local ns=""
248     local n
249     for n in $NODES ; do
250         local t="${n%:*}"
251         local ips="${n#*:}"
252         case "$ips" in
253             *,*)
254                 local i
255                 for i in ${ips//,/ } ; do
256                     ns="${ns}${ns:+ }${t}:${i}"
257                 done
258                 ;;
259             *-*)
260                 local i
261                 for i in $(seq ${ips/-/ }) ; do
262                     ns="${ns}${ns:+ }${t}:${i}"
263                 done
264                 ;;
265             *)
266                 ns="${ns}${ns:+ }${n}"
267         esac
268     done
269     NODES="$ns"
270
271     # Apply nodes hacks.  Some of this is about backward compatibility
272     # but the hacks also fill in the node names and whether they're
273     # part of the CTDB cluster.  The order is the order that
274     # configuration modules register their hacks.
275     run_hooks hack_nodes_functions
276
277     if [ -n "$NUMNODES" ] ; then
278         # Attempt to respect NUMNODES.  Reduce the number of CTDB
279         # nodes to NUMNODES.
280         local numnodes=$NUMNODES
281
282         hack_filter ()
283         {
284             if [ "$ctdb_node" = 1 ] ; then
285                 if [ $numnodes -gt 0 ] ; then
286                     numnodes=$(($numnodes - 1))
287                 else
288                     node_type="null"
289                     ctdb_node=0
290                 fi
291             fi
292         }
293
294         hack_all_nodes_with hack_filter
295                         
296         [ $numnodes -gt 0 ] && \
297             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."
298     fi
299     
300     # Check IP addresses for duplicates.
301     local ip_offsets=":"
302     # This function doesn't modify anything...
303     get_ip_offset ()
304     {
305         [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
306             die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
307         ip_offsets="${ip_offsets}${ip_offset}:"
308     }
309     hack_all_nodes_with get_ip_offset
310 }
311
312 ##############################
313
314 sanity_check_cluster_name ()
315 {
316     [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
317         die "Cluster names should be restricted to the characters A-Za-z0-9.  \
318 Some cluster filesystems have problems with other characters."
319 }
320
321 hosts_file=
322
323 common_nodelist_hacking ()
324 {
325     # Rework the NODES list
326     expand_nodes
327
328     # Build /etc/hosts and hack the names of the ctdb nodes
329     hosts_line_hack_name ()
330     {
331         # Ignore nodes without names (e.g. "null")
332         [ "$node_type" != "null" -a -n "$name" ] || return 0
333
334         local sname=""
335         local hosts_line
336         local ip_addr="$IPBASE.0.$(($FIRSTIP + $ip_offset))"
337         
338         if [ "$ctdb_node" = 1 ] ; then
339             num_ctdb_nodes=$(($num_ctdb_nodes + 1))
340             sname="${CLUSTER}n${num_ctdb_nodes}"
341             hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
342             name="$sname"
343         else
344             hosts_line="$ip_addr ${name}.${ld} $name"
345         fi
346
347         # This allows you to add a function to your configuration file
348         # to modify hostnames (and other aspects of nodes).  This
349         # function can access/modify $name (the existing name),
350         # $node_type and $ctdb_node (1, if the node is a member of the
351         # CTDB cluster, 0 otherwise).
352         if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
353             local old_name="$name"
354             $HOSTNAME_HACKING_FUNCTION
355             if [ "$name" != "$old_name" ] ; then
356                 hosts_line="$ip_addr ${name}.${ld} $name"
357             fi
358         fi
359
360         echo "$hosts_line"
361     }
362     hosts_file="tmp/hosts.$CLUSTER"
363     {
364         local num_ctdb_nodes=0
365         local ld=$(echo $DOMAIN | tr A-Z a-z)
366         echo "# autocluster $CLUSTER"
367         hack_all_nodes_with hosts_line_hack_name
368         echo
369     } >$hosts_file
370
371     # Build /etc/ctdb/nodes
372     ctdb_nodes_line ()
373     {
374         [ "$ctdb_node" = 1 ] || return 0
375         echo "$IPBASE.0.$(($FIRSTIP + $ip_offset))"
376         num_nodes=$(($num_nodes + 1))
377     }
378     nodes_file="tmp/nodes.$CLUSTER"
379     local num_nodes=0
380     hack_all_nodes_with ctdb_nodes_line >$nodes_file
381     : "${NUMNODES:=${num_nodes}}"  # Set $NUMNODES if necessary
382
383     # Build UUID map
384     uuid_map="tmp/uuid_map.$CLUSTER"
385     uuid_map_line ()
386     {
387         echo "${ip_offset} $(uuidgen)"
388     }
389     hack_all_nodes_with uuid_map_line >$uuid_map
390 }
391
392 create_cluster_hooks=
393 cluster_created_hooks=
394
395 create_cluster ()
396 {
397     CLUSTER="$1"
398
399     sanity_check_cluster_name
400
401     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
402
403     # Run hooks before doing anything else.
404     run_hooks create_cluster_hooks
405
406     common_nodelist_hacking
407
408     for_each_node call_func create_node
409
410     echo "Cluster $CLUSTER created"
411     echo "You may want to add this to your /etc/hosts file:"
412     cat $hosts_file
413
414     run_hooks cluster_created_hooks
415 }
416
417 create_one_node ()
418 {
419     CLUSTER="$1"
420     local single_node_ip_offset="$2"
421
422     sanity_check_cluster_name
423
424     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
425
426     common_nodelist_hacking
427
428     for n in $NODES ; do
429         set -- $(IFS=: ; echo $n)
430         [ $single_node_ip_offset -eq $2 ] || continue
431         call_func create_node "$@"
432         
433         echo "Requested node created"
434         echo "You may want to update your /etc/hosts file:"
435         cat $hosts_file
436         
437         break
438     done
439 }
440
441 ###############################
442 # test the proxy setup
443 test_proxy() {
444     export http_proxy=$WEBPROXY
445     wget -O /dev/null $INSTALL_SERVER || \
446         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
447     echo "Proxy OK"
448 }
449
450 ###################
451
452 kickstart_floppy_create_hooks=
453
454 # create base image
455 create_base() {
456
457     NAME="$BASENAME"
458     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
459
460     mkdir -p $KVMLOG
461
462     echo "Testing WEBPROXY $WEBPROXY"
463     test_proxy
464
465     echo "Creating the disk"
466     qemu-img create -f $BASE_FORMAT "$DISK" $DISKSIZE
467
468     rm -rf tmp
469     mkdir -p mnt tmp tmp/ISO
470
471     setup_timezone
472
473     echo "Creating kickstart file from template"
474     substitute_vars "$KICKSTART" "tmp/ks.cfg"
475
476     if [ $INSTALLKEY = "--skip" ]; then
477         cat <<EOF
478 --------------------------------------------------------------------------------------
479 WARNING: You have not entered an install key. Some RHEL packages will not be installed.
480
481 Please enter a valid RHEL install key in your config file like this:
482
483   INSTALLKEY="1234-5678-0123-4567"
484
485 The install will continue without an install key in 5 seconds
486 --------------------------------------------------------------------------------------
487 EOF
488         sleep 5
489     fi
490
491     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
492     case "$ISO" in
493         (/*) : ;;
494         (*) ISO="${ISO_DIR}/${ISO}"
495     esac
496     
497     echo "Creating kickstart floppy"
498     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
499     mkdosfs tmp/floppy.img
500     mount -o loop -t msdos tmp/floppy.img mnt
501     cp tmp/ks.cfg mnt
502     mount -o loop,ro $ISO tmp/ISO
503     
504     echo "Setting up bootloader"
505     cp tmp/ISO/isolinux/isolinux.bin tmp
506     cp tmp/ISO/isolinux/vmlinuz tmp
507     cp tmp/ISO/isolinux/initrd.img tmp
508
509     run_hooks kickstart_floppy_create_hooks
510
511     umount tmp/ISO
512     umount mnt
513
514     UUID=`uuidgen`
515
516     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
517
518     rm -f $KVMLOG/serial.$NAME
519
520     # boot the install CD
521     $VIRSH create tmp/$NAME.xml
522
523     echo "Waiting for install to start"
524     sleep 2
525     
526     # wait for the install to finish
527     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
528         $VIRSH destroy $NAME
529         die "Failed to create base image $DISK"
530     fi
531     
532     $VIRSH destroy $NAME
533
534     ls -l $DISK
535     cat <<EOF
536
537 Install finished, base image $DISK created
538
539 You may wish to run
540    chattr +i $DISK
541 To ensure that this image does not change
542
543 Note that the root password has been set to $ROOTPASSWORD
544
545 EOF
546 }
547
548 ###############################
549 # boot the base disk
550 boot_base() {
551     CLUSTER="$1"
552
553     NAME="$BASENAME"
554     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
555
556     rm -rf tmp
557     mkdir -p tmp
558
559     IPNUM=$FIRSTIP
560     CLUSTER="base"
561
562     mount_disk $DISK
563     setup_base
564     unmount_disk
565
566     UUID=`uuidgen`
567     
568     echo "Creating $NAME.xml"
569     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
570     
571     # boot the base system
572     $VIRSH create tmp/$NAME.xml
573 }
574
575 ######################################################################
576
577 # various functions...
578
579 # Set some MAC address variables based on a hash of the cluster name
580 # plus the node number and each adapter number.
581 set_macaddrs () {
582     local cname="$1"
583     local ip_offset="$2"
584
585     local md5=$(echo $cname | md5sum)
586     local nh=$(printf "%02x" $ip_offset)
587     local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
588
589     MAC1="${mac_prefix}01"
590     MAC2="${mac_prefix}02"
591     MAC3="${mac_prefix}03"
592     MAC4="${mac_prefix}04"
593     MAC5="${mac_prefix}05"
594     MAC6="${mac_prefix}06"
595 }
596
597 # mount a qemu image via nbd
598 connect_nbd() {    
599     echo "Connecting nbd to $1"
600     mkdir -p mnt
601     modprobe nbd
602     killall -9 -q $QEMU_NBD || true
603     $QEMU_NBD -p 1300 $1 &
604     sleep 1
605     [ -r $NBD_DEVICE ] || {
606         mknod $NBD_DEVICE b 43 0
607     }
608     umount mnt 2> /dev/null || true
609     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
610     killall -9 -q nbd-client || true
611     nbd-client localhost 1300 $NBD_DEVICE > /dev/null 2>&1 || true &
612     sleep 1
613 }
614
615 # disconnect nbd
616 disconnect_nbd() {
617     echo "Disconnecting nbd"
618     sync; sync
619     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
620     killall -9 -q nbd-client || true
621     killall -q $QEMU_NBD || true
622 }
623
624 setup_image ()
625 {
626     local disk="$1"
627
628     case "$SYSTEM_DISK_FORMAT" in
629         qcow2)
630             connect_nbd "$disk"
631             device=$NBD_DEVICE
632             extra_mount_options=""
633             ;;
634         raw)
635             device="$disk"
636             extra_mount_options=",loop"
637             ;;
638         *)
639             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
640     esac
641 }
642
643 cleanup_image ()
644 {
645     case "$SYSTEM_DISK_FORMAT" in
646         qcow2)
647             disconnect_nbd
648             ;;
649         raw)
650             :
651             ;;
652         *)
653             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
654     esac
655 }
656
657 # mount a qemu image via nbd
658 mount_disk()
659 {
660     local disk="$1"
661
662     local device extra_mount_options
663
664     setup_image "$disk"
665
666     echo "Mounting disk ${disk}..."
667     local m o
668     for m in $SYSTEM_DISK_MOUNTS ; do
669         local mount_ok=0
670         o="${m#*:}" # Offset is after colon
671         m="${m%:*}" # Mountpoint is before colon
672         echo " mount ${m} from offset ${o}"
673         local i
674         for i in $(seq 1 5); do
675             mount -o offset=${o}${extra_mount_options} $device "mnt${m}" && {
676                 mount_ok=1
677                 break
678             }
679             umount mnt 2>/dev/null || true
680             sleep 1
681         done
682         [ $mount_ok = 1 ] || die "Failed to mount $disk"
683     done
684
685     [ -d mnt/root ] || {
686         echo "Mounted directory does not look like a root filesystem"
687         ls -latr mnt
688         exit 1
689     }
690 }
691
692 # unmount a qemu image
693 unmount_disk() {
694     echo "Unmounting disk"
695     sync; sync;
696
697     # umounts are done in reverse.  Be lazy and construct a reverse
698     # list, since the shell will handle any strange whitespace for
699     # us...  ;-)
700     local umounts=""
701     local m
702     for m in $SYSTEM_DISK_MOUNTS ; do
703         umounts="${m%:*}${umounts:+ }${umounts}"
704     done
705     for m in $umounts ; do
706         echo " umount ${m}"
707         umount "mnt${m}" || umount "mnt${m}" || true
708     done
709     cleanup_image
710 }
711
712 # setup the files from $BASE_TEMPLATES/, substituting any variables
713 # based on the config
714 copy_base_dir_substitute_templates ()
715 {
716     local dir="$1"
717
718     local d="$BASE_TEMPLATES/$dir"
719     [ -d "$d" ] || return 0
720
721     local f
722     for f in $(cd "$d" && find . \! -name '*~') ; do
723         if [ -d "$d/$f" ]; then
724             mkdir -p mnt/"$f"
725         else 
726             substitute_vars "$d/$f" "mnt/$f"
727         fi
728         chmod --reference="$d/$f" "mnt/$f"
729     done
730 }
731
732 setup_base_hooks=
733
734 setup_base_ssh_keys ()
735 {
736     # this is needed as git doesn't store file permissions other
737     # than execute
738     chmod 600 mnt/etc/ssh/*key mnt/root/.ssh/*
739     chmod 700 mnt/etc/ssh mnt/root/.ssh mnt/root
740     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
741        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
742        cat "$HOME/.ssh/id_rsa.pub" >> mnt/root/.ssh/authorized_keys
743     fi
744     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
745        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
746        cat "$HOME/.ssh/id_dsa.pub" >> mnt/root/.ssh/authorized_keys
747     fi
748 }
749
750 register_hook setup_base_hooks setup_base_ssh_keys
751
752 setup_base_grub_conf ()
753 {
754     echo "Adjusting grub.conf"
755     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
756     sed -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
757         -e "s/ nodmraid//" -e "s/ nompath//"  \
758         -e "s/quiet/noapic divider=10${o:+ }${o}/g" mnt/boot/grub/grub.conf -i.org
759 }
760
761 register_hook setup_base_hooks setup_base_grub_conf
762
763 setup_base()
764 {
765     local type="$1"
766
767     umask 022
768     echo "Copy base files"
769     copy_base_dir_substitute_templates "all"
770     if [ -n "$type" ] ; then
771         copy_base_dir_substitute_templates "$type"
772     fi
773
774     run_hooks setup_base_hooks
775 }
776
777 # setup various networking components
778 setup_network()
779 {
780     # This avoids doing anything when we're called from boot_base().
781     if [ -z "$hosts_file" ] ; then
782         echo "Skipping network-related setup"
783         return
784     fi
785
786     echo "Setting up networks"
787     cat $hosts_file >>mnt/etc/hosts
788
789     echo "Setting up /etc/ctdb/nodes"
790     mkdir -p mnt/etc/ctdb
791     cp $nodes_file mnt/etc/ctdb/nodes
792
793     [ "$WEBPROXY" = "" ] || {
794         echo "export http_proxy=$WEBPROXY" >> mnt/etc/bashrc
795     }
796
797     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
798         echo "Enabling nfs mount of $NFSSHARE"
799         mkdir -p "mnt$NFS_MOUNTPOINT"
800         echo "$NFSSHARE $NFS_MOUNTPOINT nfs intr" >> mnt/etc/fstab
801     fi
802
803     mkdir -p mnt/etc/yum.repos.d
804     echo '@@@YUM_TEMPLATE@@@' | substitute_vars - > mnt/etc/yum.repos.d/autocluster.repo
805 }
806
807 register_hook setup_base_hooks setup_network
808
809 setup_timezone() {
810     [ -z "$TIMEZONE" ] && {
811         [ -r /etc/timezone ] && {
812             TIMEZONE=`cat /etc/timezone`
813         }
814         [ -r /etc/sysconfig/clock ] && {
815             . /etc/sysconfig/clock
816             TIMEZONE="$ZONE"
817         }
818         TIMEZONE="${TIMEZONE// /_}"
819     }
820     [ -n "$TIMEZONE" ] || \
821         die "Unable to determine TIMEZONE - please set in config"
822 }
823
824 # substite a set of variables of the form @@XX@@ for the shell
825 # variables $XX in a file.
826 #
827 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
828 # contain a filename whose contents are substituted, with variable
829 # substitution applied to those contents.  If filename starts with '|'
830 # it is a command instead - however, quoting is extremely fragile.
831 substitute_vars() {(
832         infile="${1:-/dev/null}" # if empty then default to /dev/null
833         outfile="$2" # optional
834
835         instring=$(cat $infile)
836
837         # Handle any indirects by looping until nothing changes.
838         # However, only handle 10 levels of recursion.
839         count=0
840         while : ; do
841             outstring=$(_substitute_vars "$instring" "@@@")
842             [ $? -eq 0 ] || die "Failed to expand template $infile"
843
844             [ "$instring" = "$outstring" ] && break
845
846             count=$(($count + 1))
847             [ $count -lt 10 ] || \
848                 die "Recursion too deep in $infile - only 10 levels allowed!"
849
850             instring="$outstring"
851         done
852
853         # Now regular variables.
854         outstring=$(_substitute_vars "$instring" "@@")
855         [ $? -eq 0 ] || die "Failed to expand template $infile"
856
857         if [ -n "$outfile" ] ; then
858             echo "$outstring" > "$outfile"
859         else
860             echo "$outstring"
861         fi
862 )}
863
864
865 # Delimiter @@ means to substitute contents of variable.
866 # Delimiter @@@ means to substitute contents of file named by variable.
867 # @@@ supports leading '|' in variable value, which means to excute a
868 # command.
869 _substitute_vars() {(
870         instring="$1"
871         delimiter="${2:-@@}"
872
873         # get the list of variables used in the template
874         VARS=`echo "$instring" |
875               tr -cs "A-Z0-9_$delimiter" '\012' | 
876               sort -u |
877               sed -n -e "s#^${delimiter}\(.*\)${delimiter}\\$#\1#p"`
878
879         tmp=$(mktemp)
880         for v in $VARS; do
881             # variable variables are fun .....
882             [ "${!v+x}" ] || {
883                 rm -f $tmp
884                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
885             }
886             s=${!v}
887
888             if [ "$delimiter" = "@@@" ] ; then
889                 f=${s:-/dev/null}
890                 c="${f#|}" # Is is a command, signified by a leading '|'?
891                 if [ "$c" = "$f" ] ; then
892                     # No leading '|', cat file.
893                     s=$(cat -- "$f")
894                     [ $? -eq 0 ] || {
895                         rm -f $tmp
896                         die "Could not substitute contents of file $f"
897                     }
898                 else
899                     # Leading '|', execute command.
900                     # Quoting problems here - using eval "$c" doesn't help.
901                     s=$($c)
902                     [ $? -eq 0 ] || {
903                         rm -f $tmp
904                         die "Could not execute command $c"
905                     }
906                 fi
907             fi
908
909             # escape some pesky chars
910             s=${s//
911 /\\n}
912             s=${s//#/\\#}
913             s=${s//&/\\&}
914             echo "s#${delimiter}${v}${delimiter}#${s}#g"
915         done > $tmp
916
917         echo "$instring" | sed -f $tmp
918
919         rm -f $tmp
920 )}
921
922 check_command() {
923     which $1 > /dev/null || die "Please install $1 to continue"
924 }
925
926 # Set a variable if it isn't already set.  This allows environment
927 # variables to override default config settings.
928 defconf() {
929     local v="$1"
930     local e="$2"
931
932     [ "${!v+x}" ] || eval "$v=\"$e\""
933 }
934
935 load_config () {
936     local i
937
938     for i in "${installdir}/config.d/"*.defconf ; do
939         . "$i"
940     done
941 }
942
943 # Print the list of config variables defined in config.d/.
944 get_config_options () {( # sub-shell for local declaration of defconf()
945         local options=
946         defconf() { options="$options $1" ; }
947         load_config
948         echo $options
949 )}
950
951 # Produce a list of long options, suitable for use with getopt, that
952 # represent the config variables defined in config.d/.
953 getopt_config_options () {
954     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
955     echo "${x// /:,}:"
956 }
957
958 # Unconditionally set the config variable associated with the given
959 # long option.
960 setconf_longopt () {
961     local longopt="$1"
962     local e="$2"
963
964     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
965     # unset so defconf will set it
966     eval "unset $v"
967     defconf "$v" "$e"
968 }
969
970 # Dump all of the current config variables.
971 dump_config() {
972     local o
973     for o in $(get_config_options) ; do
974         echo "${o}=\"${!o}\""
975     done
976     exit 0
977 }
978
979 # $COLUMNS is set in interactive bash shells.  It probably isn't set
980 # in this shell, so let's set it if it isn't.
981 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
982 : ${COLUMNS:=80}
983 export COLUMNS
984
985 # Print text assuming it starts after other text in $startcol and
986 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
987 # Long "words" will extend past $COLUMNS - 2.
988 fill_text() {
989     local startcol="$1"
990     local text="$2"
991
992     local width=$(($COLUMNS - 2 - $startcol))
993     [ $width -lt 0 ] && width=$((78 - $startcol))
994
995     local out=""
996
997     local padding
998     if [ $startcol -gt 0 ] ; then
999         padding=$(printf "\n%${startcol}s" " ")
1000     else
1001         padding="
1002 "
1003     fi
1004
1005     while [ -n "$text" ] ; do
1006         local orig="$text"
1007
1008         # If we already have output then arrange padding on the next line.
1009         [ -n "$out" ] && out="${out}${padding}"
1010
1011         # Break the text at $width.
1012         out="${out}${text:0:${width}}"
1013         text="${text:${width}}"
1014
1015         # If we have left over text then the line break may be ugly,
1016         # so let's check and try to break it on a space.
1017         if [ -n "$text" ] ; then
1018             # The 'x's stop us producing a special character like '(',
1019             # ')' or '!'.  Yuck - there must be a better way.
1020             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1021                 # We didn't break on a space.  Arrange for the
1022                 # beginning of the broken "word" to appear on the next
1023                 # line but not if it will make us loop infinitely.
1024                 if [ "${orig}" != "${out##* }${text}" ] ; then
1025                     text="${out##* }${text}"
1026                     out="${out% *}"
1027                 else
1028                     # Hmmm, doing that would make us loop, so add the
1029                     # rest of the word from the remainder of the text
1030                     # to this line and let it extend past $COLUMNS - 2.
1031                     out="${out}${text%% *}"
1032                     if [ "${text# *}" != "$text" ] ; then
1033                         # Remember the text after the next space for next time.
1034                         text="${text# *}"
1035                     else
1036                         # No text after next space.
1037                         text=""
1038                     fi
1039                 fi
1040             else
1041                 # We broke on a space.  If it will be at the beginning
1042                 # of the next line then remove it.
1043                 text="${text# }"
1044             fi
1045         fi
1046     done
1047
1048     echo "$out"
1049 }
1050
1051 # Display usage text, trying these approaches in order.
1052 # 1. See if it all fits on one line before $COLUMNS - 2.
1053 # 2. See if splitting before the default value and indenting it
1054 #    to $startcol means that nothing passes $COLUMNS - 2.
1055 # 3. Treat the message and default value as a string and just us fill_text()
1056 #    to format it. 
1057 usage_display_text () {
1058     local startcol="$1"
1059     local desc="$2"
1060     local default="$3"
1061     
1062     local width=$(($COLUMNS - 2 - $startcol))
1063     [ $width -lt 0 ] && width=$((78 - $startcol))
1064
1065     default="(default \"$default\")"
1066
1067     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1068         echo "${desc} ${default}"
1069     else
1070         local padding=$(printf "%${startcol}s" " ")
1071
1072         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1073             echo "$desc"
1074             echo "${padding}${default}"
1075         else
1076             fill_text $startcol "${desc} ${default}"
1077         fi
1078     fi
1079 }
1080
1081 # Display usage information for long config options.
1082 usage_smart_display () {( # sub-shell for local declaration of defconf()
1083         local startcol=33
1084
1085         defconf() {
1086             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1087
1088             printf "     --%-25s " "${longopt}=${3}"
1089
1090             usage_display_text $startcol "$4" "$2"
1091         }
1092
1093         "$@"
1094 )}
1095
1096
1097 # Display usage information for long config options.
1098 usage_config_options (){
1099     usage_smart_display load_config
1100 }
1101
1102 list_releases () {
1103     local releases=$(cd $installdir/releases && echo *.release)
1104     releases="${releases//.release}"
1105     releases="${releases// /\", \"}"
1106     echo "\"$releases\""
1107 }
1108
1109 with_release () {
1110     local release="$1"
1111     shift # subsequent args are passed to release file
1112
1113     # This simply loads an extra config file from $installdir/releases
1114     f="${installdir}/releases/${release}.release"
1115     if [ -r "$f" ] ; then
1116         . "$f"
1117     else
1118         f="${installdir}/releases/${release%%-*}.release"
1119         if [ -r "$f" ] ; then
1120             . "$f" "${release#*-}"
1121         else
1122             echo "Unknown release \"${release}\" specified to --with-release"
1123             printf "%-25s" "Supported releases are: "
1124             fill_text 25 "$(list_releases)"
1125             exit 1
1126         fi
1127     fi
1128
1129 }
1130
1131 has_public_addresses_DEFAULT ()
1132 {
1133     false
1134 }
1135
1136 # Build public address configuration.
1137 # * 1st public IP:  unless specified, last octet is $FIRSTIP + $PUBLIC_IP_OFFSET
1138 # * Excluded nodes: unless specified via comma-separated list of IP offsets,
1139 #                   nodes are excluded via their node types
1140 # * Number of public addresses per interface is either specified or $NUMNODES.
1141 make_public_addresses () {
1142     local firstip="${1:-$(($FIRSTIP + $PUBLIC_IP_OFFSET))}"
1143     local excluded_nodes="$2" 
1144     local num_addrs="${3:-${NUMNODES}}"
1145
1146     # For delimiting matches.
1147     excluded_nodes="${excluded_nodes:+,}${excluded_nodes}${excluded_nodes:+,}"
1148     # Avoid spaces
1149     excluded_nodes="${excluded_nodes// /}"
1150
1151     make_public_addresses_for_node ()
1152     {
1153         [ "$ctdb_node" = 1 ] || return 0
1154
1155         echo "[/etc/ctdb/public_addresses:${name}.${DOMAIN}]"
1156
1157         if [ -n "$excluded_nodes" -a \
1158             "${excluded_nodes/,${ip_offset},}" = "$excluded_nodes" ] ||
1159             ([ -z "$excluded_nodes" ] &&
1160                 call_func has_public_addresses "$node_type") ; then
1161
1162             local e i
1163             for e in "1" "2" ; do
1164                 for i in $(seq $firstip $(($firstip + $num_addrs - 1))) ; do
1165                     if [ $i -gt 254 ] ; then
1166                         die "make_public_addresses: octet > 254 - consider setting PUBLIC_IP_OFFSET"
1167                     fi
1168                     printf "\t${IPBASE}.${e}.${i}/24 eth${e}\n"
1169                 done
1170             done            
1171         fi
1172         echo 
1173     }
1174     hack_all_nodes_with make_public_addresses_for_node
1175 }
1176
1177 ######################################################################
1178
1179 load_config
1180
1181 ############################
1182 # parse command line options
1183 long_opts=$(getopt_config_options)
1184 getopt_output=$(getopt -n autocluster -o "c:e:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1185 [ $? != 0 ] && usage
1186
1187 use_default_config=true
1188
1189 # We do 2 passes of the options.  The first time we just handle usage
1190 # and check whether -c is being used.
1191 eval set -- "$getopt_output"
1192 while true ; do
1193     case "$1" in
1194         -c) shift 2 ; use_default_config=false ;;
1195         -e) shift 2 ;;
1196         --) shift ; break ;;
1197         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1198         --dump|-x) shift ;;
1199         -h|--help) usage ;; # Usage should be shown here for real defaults.
1200         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1201         *) usage ;; # shouldn't happen, so this is reasonable.
1202     esac
1203 done
1204
1205 config="./config"
1206 $use_default_config && [ -r "$config" ] && . "$config"
1207
1208 eval set -- "$getopt_output"
1209
1210 while true ; do
1211     case "$1" in
1212         # force at least ./local_file to avoid accidental file from $PATH
1213         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1214         -e) eval "$2" ; exit ;;
1215         --with-release)
1216             with_release "$2"
1217             shift 2
1218             ;;
1219         -x) set -x; shift ;;
1220         --dump) dump_config ;;
1221         --) shift ; break ;;
1222         -h|--help) usage ;; # Redundant.
1223         --*)
1224             # Putting --opt1|opt2|... into a variable and having case
1225             # match against it as a pattern doesn't work.  The | is
1226             # part of shell syntax, so we need to do this.  Look away
1227             # now to stop your eyes from bleeding! :-)
1228             x=",${long_opts}" # Now each option is surrounded by , and :
1229             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1230                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1231                 setconf_longopt "$1" "$2"; shift 2
1232             else
1233                 usage
1234             fi
1235             ;;
1236         *) usage ;; # shouldn't happen, so this is reasonable.
1237     esac
1238 done
1239
1240 # catch errors
1241 set -e
1242 set -E
1243 trap 'es=$?; 
1244       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1245       exit $es' ERR
1246
1247 # check for needed programs 
1248 check_command expect
1249 if [ "$SYSTEM_DISK_FORMAT" != "raw" ] ; then
1250     check_command $QEMU_NBD
1251     check_command nbd-client
1252 fi
1253
1254 [ $# -lt 1 ] && usage
1255
1256 command="$1"
1257 shift
1258
1259 case $command in
1260     create)
1261         type=$1
1262         shift
1263         case $type in
1264             base)
1265                 [ $# != 0 ] && usage
1266                 create_base
1267                 ;;
1268             cluster)
1269                 [ $# != 1 ] && usage
1270                 create_cluster "$1"
1271                 ;;
1272             node)
1273                 [ $# != 2 ] && usage
1274                 create_one_node "$1" "$2"
1275                 ;;
1276             *)
1277                 usage;
1278                 ;;
1279         esac
1280         ;;
1281     mount)
1282         [ $# != 1 ] && usage
1283         mount_disk "$1"
1284         ;;
1285     unmount)
1286         [ $# != 0 ] && usage
1287         unmount_disk
1288         ;;
1289     bootbase)
1290         boot_base;
1291         ;;
1292     testproxy)
1293         test_proxy;
1294         ;;
1295     *)
1296         usage;
1297         ;;
1298 esac