87b848f621ba8e460c1945ea6689f9a08d5be78d
[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
384 create_cluster_hooks=
385 cluster_created_hooks=
386
387 create_cluster ()
388 {
389     CLUSTER="$1"
390
391     sanity_check_cluster_name
392
393     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
394
395     # Run hooks before doing anything else.
396     run_hooks create_cluster_hooks
397
398     common_nodelist_hacking
399
400     for_each_node call_func create_node
401
402     echo "Cluster $CLUSTER created"
403     echo "You may want to add this to your /etc/hosts file:"
404     cat $hosts_file
405
406     run_hooks cluster_created_hooks
407 }
408
409 create_one_node ()
410 {
411     CLUSTER="$1"
412     local single_node_ip_offset="$2"
413
414     sanity_check_cluster_name
415
416     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
417
418     common_nodelist_hacking
419
420     for n in $NODES ; do
421         set -- $(IFS=: ; echo $n)
422         [ $single_node_ip_offset -eq $2 ] || continue
423         call_func create_node "$@"
424         
425         echo "Requested node created"
426         echo "You may want to update your /etc/hosts file:"
427         cat $hosts_file
428         
429         break
430     done
431 }
432
433 ###############################
434 # test the proxy setup
435 test_proxy() {
436     export http_proxy=$WEBPROXY
437     wget -O /dev/null $INSTALL_SERVER || \
438         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
439     echo "Proxy OK"
440 }
441
442 ###################
443
444 kickstart_floppy_create_hooks=
445
446 # create base image
447 create_base() {
448
449     NAME="$BASENAME"
450     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
451
452     mkdir -p $KVMLOG
453
454     echo "Testing WEBPROXY $WEBPROXY"
455     test_proxy
456
457     echo "Creating the disk"
458     qemu-img create -f $BASE_FORMAT "$DISK" $DISKSIZE
459
460     rm -rf tmp
461     mkdir -p mnt tmp tmp/ISO
462
463     setup_timezone
464
465     echo "Creating kickstart file from template"
466     substitute_vars "$KICKSTART" "tmp/ks.cfg"
467
468     if [ $INSTALLKEY = "--skip" ]; then
469         cat <<EOF
470 --------------------------------------------------------------------------------------
471 WARNING: You have not entered an install key. Some RHEL packages will not be installed.
472
473 Please enter a valid RHEL install key in your config file like this:
474
475   INSTALLKEY="1234-5678-0123-4567"
476
477 The install will continue without an install key in 5 seconds
478 --------------------------------------------------------------------------------------
479 EOF
480         sleep 5
481     fi
482
483     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
484     case "$ISO" in
485         (/*) : ;;
486         (*) ISO="${ISO_DIR}/${ISO}"
487     esac
488     
489     echo "Creating kickstart floppy"
490     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
491     mkdosfs tmp/floppy.img
492     mount -o loop -t msdos tmp/floppy.img mnt
493     cp tmp/ks.cfg mnt
494     mount -o loop,ro $ISO tmp/ISO
495     
496     echo "Setting up bootloader"
497     cp tmp/ISO/isolinux/isolinux.bin tmp
498     cp tmp/ISO/isolinux/vmlinuz tmp
499     cp tmp/ISO/isolinux/initrd.img tmp
500
501     run_hooks kickstart_floppy_create_hooks
502
503     umount tmp/ISO
504     umount mnt
505
506     UUID=`uuidgen`
507
508     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
509
510     rm -f $KVMLOG/serial.$NAME
511
512     # boot the install CD
513     $VIRSH create tmp/$NAME.xml
514
515     echo "Waiting for install to start"
516     sleep 2
517     
518     # wait for the install to finish
519     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
520         $VIRSH destroy $NAME
521         die "Failed to create base image $DISK"
522     fi
523     
524     $VIRSH destroy $NAME
525
526     ls -l $DISK
527     cat <<EOF
528
529 Install finished, base image $DISK created
530
531 You may wish to run
532    chattr +i $DISK
533 To ensure that this image does not change
534
535 Note that the root password has been set to $ROOTPASSWORD
536
537 EOF
538 }
539
540 ###############################
541 # boot the base disk
542 boot_base() {
543     CLUSTER="$1"
544
545     NAME="$BASENAME"
546     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
547
548     rm -rf tmp
549     mkdir -p tmp
550
551     IPNUM=$FIRSTIP
552     CLUSTER="base"
553
554     mount_disk $DISK
555     setup_base
556     unmount_disk
557
558     UUID=`uuidgen`
559     
560     echo "Creating $NAME.xml"
561     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
562     
563     # boot the base system
564     $VIRSH create tmp/$NAME.xml
565 }
566
567 ######################################################################
568
569 # various functions...
570
571 # Set some MAC address variables based on a hash of the cluster name
572 # plus the node number and each adapter number.
573 set_macaddrs () {
574     local cname="$1"
575     local ip_offset="$2"
576
577     local md5=$(echo $cname | md5sum)
578     local nh=$(printf "%02x" $ip_offset)
579     local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
580
581     MAC1="${mac_prefix}01"
582     MAC2="${mac_prefix}02"
583     MAC3="${mac_prefix}03"
584     MAC4="${mac_prefix}04"
585     MAC5="${mac_prefix}05"
586     MAC6="${mac_prefix}06"
587 }
588
589 # mount a qemu image via nbd
590 connect_nbd() {    
591     echo "Connecting nbd to $1"
592     mkdir -p mnt
593     modprobe nbd
594     killall -9 -q $QEMU_NBD || true
595     $QEMU_NBD -p 1300 $1 &
596     sleep 1
597     [ -r $NBD_DEVICE ] || {
598         mknod $NBD_DEVICE b 43 0
599     }
600     umount mnt 2> /dev/null || true
601     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
602     killall -9 -q nbd-client || true
603     nbd-client localhost 1300 $NBD_DEVICE > /dev/null 2>&1 || true &
604     sleep 1
605 }
606
607 # disconnect nbd
608 disconnect_nbd() {
609     echo "Disconnecting nbd"
610     sync; sync
611     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
612     killall -9 -q nbd-client || true
613     killall -q $QEMU_NBD || true
614 }
615
616 setup_image ()
617 {
618     local disk="$1"
619
620     case "$SYSTEM_DISK_FORMAT" in
621         qcow2)
622             connect_nbd "$disk"
623             device=$NBD_DEVICE
624             extra_mount_options=""
625             ;;
626         raw)
627             device="$disk"
628             extra_mount_options=",loop"
629             ;;
630         *)
631             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
632     esac
633 }
634
635 cleanup_image ()
636 {
637     case "$SYSTEM_DISK_FORMAT" in
638         qcow2)
639             disconnect_nbd
640             ;;
641         raw)
642             :
643             ;;
644         *)
645             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
646     esac
647 }
648
649 # mount a qemu image via nbd
650 mount_disk()
651 {
652     local disk="$1"
653
654     local device extra_mount_options
655
656     setup_image "$disk"
657
658     echo "Mounting disk ${disk}..."
659     local m o
660     for m in $SYSTEM_DISK_MOUNTS ; do
661         local mount_ok=0
662         o="${m#*:}" # Offset is after colon
663         m="${m%:*}" # Mountpoint is before colon
664         echo " ${m} from offset ${o}"
665         local i
666         for i in $(seq 1 5); do
667             mount -o offset=${o}${extra_mount_options} $device "mnt${m}" && {
668                 mount_ok=1
669                 break
670             }
671             umount mnt 2>/dev/null || true
672             sleep 1
673         done
674         [ $mount_ok = 1 ] || die "Failed to mount $disk"
675     done
676
677     [ -d mnt/root ] || {
678         echo "Mounted directory does not look like a root filesystem"
679         ls -latr mnt
680         exit 1
681     }
682 }
683
684 # unmount a qemu image
685 unmount_disk() {
686     echo "Unmounting disk"
687     sync; sync;
688
689     # umounts are done in reverse.  Be lazy and construct a reverse
690     # list, since the shell will handle any strange whitespace for
691     # us...  ;-)
692     local umounts=""
693     local m
694     for m in $SYSTEM_DISK_MOUNTS ; do
695         umounts="${m%:*}${umounts:+ }${umounts)"
696     done
697     for m in $umounts ; do
698         umount "mnt${m}" || umount "mnt${m}" || true
699     done
700     cleanup_image
701 }
702
703 # setup the files from $BASE_TEMPLATES/, substituting any variables
704 # based on the config
705 copy_base_dir_substitute_templates ()
706 {
707     local dir="$1"
708
709     local d="$BASE_TEMPLATES/$dir"
710     [ -d "$d" ] || return 0
711
712     local f
713     for f in $(cd "$d" && find . \! -name '*~') ; do
714         if [ -d "$d/$f" ]; then
715             mkdir -p mnt/"$f"
716         else 
717             substitute_vars "$d/$f" "mnt/$f"
718         fi
719         chmod --reference="$d/$f" "mnt/$f"
720     done
721 }
722
723 setup_base_hooks=
724
725 setup_base_ssh_keys ()
726 {
727     # this is needed as git doesn't store file permissions other
728     # than execute
729     chmod 600 mnt/etc/ssh/*key mnt/root/.ssh/*
730     chmod 700 mnt/etc/ssh mnt/root/.ssh mnt/root
731     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
732        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
733        cat "$HOME/.ssh/id_rsa.pub" >> mnt/root/.ssh/authorized_keys
734     fi
735     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
736        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
737        cat "$HOME/.ssh/id_dsa.pub" >> mnt/root/.ssh/authorized_keys
738     fi
739 }
740
741 register_hook setup_base_hooks setup_base_ssh_keys
742
743 setup_base_grub_conf ()
744 {
745     echo "Adjusting grub.conf"
746     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
747     sed -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
748         -e "s/ nodmraid//" -e "s/ nompath//"  \
749         -e "s/quiet/noapic divider=10${o:+ }${o}/g" mnt/boot/grub/grub.conf -i.org
750 }
751
752 register_hook setup_base_hooks setup_base_grub_conf
753
754 setup_base()
755 {
756     local type="$1"
757
758     umask 022
759     echo "Copy base files"
760     copy_base_dir_substitute_templates "all"
761     if [ -n "$type" ] ; then
762         copy_base_dir_substitute_templates "$type"
763     fi
764
765     run_hooks setup_base_hooks
766 }
767
768 # setup various networking components
769 setup_network()
770 {
771     # This avoids doing anything when we're called from boot_base().
772     if [ -z "$hosts_file" ] ; then
773         echo "Skipping network-related setup"
774         return
775     fi
776
777     echo "Setting up networks"
778     cat $hosts_file >>mnt/etc/hosts
779
780     echo "Setting up /etc/ctdb/nodes"
781     mkdir -p mnt/etc/ctdb
782     cp $nodes_file mnt/etc/ctdb/nodes
783
784     [ "$WEBPROXY" = "" ] || {
785         echo "export http_proxy=$WEBPROXY" >> mnt/etc/bashrc
786     }
787
788     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
789         echo "Enabling nfs mount of $NFSSHARE"
790         mkdir -p "mnt$NFS_MOUNTPOINT"
791         echo "$NFSSHARE $NFS_MOUNTPOINT nfs intr" >> mnt/etc/fstab
792     fi
793
794     mkdir -p mnt/etc/yum.repos.d
795     echo '@@@YUM_TEMPLATE@@@' | substitute_vars - > mnt/etc/yum.repos.d/autocluster.repo
796 }
797
798 register_hook setup_base_hooks setup_network
799
800 setup_timezone() {
801     [ -z "$TIMEZONE" ] && {
802         [ -r /etc/timezone ] && {
803             TIMEZONE=`cat /etc/timezone`
804         }
805         [ -r /etc/sysconfig/clock ] && {
806             . /etc/sysconfig/clock
807             TIMEZONE="$ZONE"
808         }
809         TIMEZONE="${TIMEZONE// /_}"
810     }
811     [ -n "$TIMEZONE" ] || \
812         die "Unable to determine TIMEZONE - please set in config"
813 }
814
815 # substite a set of variables of the form @@XX@@ for the shell
816 # variables $XX in a file.
817 #
818 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
819 # contain a filename whose contents are substituted, with variable
820 # substitution applied to those contents.  If filename starts with '|'
821 # it is a command instead - however, quoting is extremely fragile.
822 substitute_vars() {(
823         infile="${1:-/dev/null}" # if empty then default to /dev/null
824         outfile="$2" # optional
825
826         instring=$(cat $infile)
827
828         # Handle any indirects by looping until nothing changes.
829         # However, only handle 10 levels of recursion.
830         count=0
831         while : ; do
832             outstring=$(_substitute_vars "$instring" "@@@")
833             [ $? -eq 0 ] || die "Failed to expand template $infile"
834
835             [ "$instring" = "$outstring" ] && break
836
837             count=$(($count + 1))
838             [ $count -lt 10 ] || \
839                 die "Recursion too deep in $infile - only 10 levels allowed!"
840
841             instring="$outstring"
842         done
843
844         # Now regular variables.
845         outstring=$(_substitute_vars "$instring" "@@")
846         [ $? -eq 0 ] || die "Failed to expand template $infile"
847
848         if [ -n "$outfile" ] ; then
849             echo "$outstring" > "$outfile"
850         else
851             echo "$outstring"
852         fi
853 )}
854
855
856 # Delimiter @@ means to substitute contents of variable.
857 # Delimiter @@@ means to substitute contents of file named by variable.
858 # @@@ supports leading '|' in variable value, which means to excute a
859 # command.
860 _substitute_vars() {(
861         instring="$1"
862         delimiter="${2:-@@}"
863
864         # get the list of variables used in the template
865         VARS=`echo "$instring" |
866               tr -cs "A-Z0-9_$delimiter" '\012' | 
867               sort -u |
868               sed -n -e "s#^${delimiter}\(.*\)${delimiter}\\$#\1#p"`
869
870         tmp=$(mktemp)
871         for v in $VARS; do
872             # variable variables are fun .....
873             [ "${!v+x}" ] || {
874                 rm -f $tmp
875                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
876             }
877             s=${!v}
878
879             if [ "$delimiter" = "@@@" ] ; then
880                 f=${s:-/dev/null}
881                 c="${f#|}" # Is is a command, signified by a leading '|'?
882                 if [ "$c" = "$f" ] ; then
883                     # No leading '|', cat file.
884                     s=$(cat -- "$f")
885                     [ $? -eq 0 ] || {
886                         rm -f $tmp
887                         die "Could not substitute contents of file $f"
888                     }
889                 else
890                     # Leading '|', execute command.
891                     # Quoting problems here - using eval "$c" doesn't help.
892                     s=$($c)
893                     [ $? -eq 0 ] || {
894                         rm -f $tmp
895                         die "Could not execute command $c"
896                     }
897                 fi
898             fi
899
900             # escape some pesky chars
901             s=${s//
902 /\\n}
903             s=${s//#/\\#}
904             s=${s//&/\\&}
905             echo "s#${delimiter}${v}${delimiter}#${s}#g"
906         done > $tmp
907
908         echo "$instring" | sed -f $tmp
909
910         rm -f $tmp
911 )}
912
913 check_command() {
914     which $1 > /dev/null || die "Please install $1 to continue"
915 }
916
917 # Set a variable if it isn't already set.  This allows environment
918 # variables to override default config settings.
919 defconf() {
920     local v="$1"
921     local e="$2"
922
923     [ "${!v+x}" ] || eval "$v=\"$e\""
924 }
925
926 load_config () {
927     local i
928
929     for i in "${installdir}/config.d/"*.defconf ; do
930         . "$i"
931     done
932 }
933
934 # Print the list of config variables defined in config.d/.
935 get_config_options () {( # sub-shell for local declaration of defconf()
936         local options=
937         defconf() { options="$options $1" ; }
938         load_config
939         echo $options
940 )}
941
942 # Produce a list of long options, suitable for use with getopt, that
943 # represent the config variables defined in config.d/.
944 getopt_config_options () {
945     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
946     echo "${x// /:,}:"
947 }
948
949 # Unconditionally set the config variable associated with the given
950 # long option.
951 setconf_longopt () {
952     local longopt="$1"
953     local e="$2"
954
955     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
956     # unset so defconf will set it
957     eval "unset $v"
958     defconf "$v" "$e"
959 }
960
961 # Dump all of the current config variables.
962 dump_config() {
963     local o
964     for o in $(get_config_options) ; do
965         echo "${o}=\"${!o}\""
966     done
967     exit 0
968 }
969
970 # $COLUMNS is set in interactive bash shells.  It probably isn't set
971 # in this shell, so let's set it if it isn't.
972 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
973 : ${COLUMNS:=80}
974 export COLUMNS
975
976 # Print text assuming it starts after other text in $startcol and
977 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
978 # Long "words" will extend past $COLUMNS - 2.
979 fill_text() {
980     local startcol="$1"
981     local text="$2"
982
983     local width=$(($COLUMNS - 2 - $startcol))
984     [ $width -lt 0 ] && width=$((78 - $startcol))
985
986     local out=""
987
988     local padding
989     if [ $startcol -gt 0 ] ; then
990         padding=$(printf "\n%${startcol}s" " ")
991     else
992         padding="
993 "
994     fi
995
996     while [ -n "$text" ] ; do
997         local orig="$text"
998
999         # If we already have output then arrange padding on the next line.
1000         [ -n "$out" ] && out="${out}${padding}"
1001
1002         # Break the text at $width.
1003         out="${out}${text:0:${width}}"
1004         text="${text:${width}}"
1005
1006         # If we have left over text then the line break may be ugly,
1007         # so let's check and try to break it on a space.
1008         if [ -n "$text" ] ; then
1009             # The 'x's stop us producing a special character like '(',
1010             # ')' or '!'.  Yuck - there must be a better way.
1011             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1012                 # We didn't break on a space.  Arrange for the
1013                 # beginning of the broken "word" to appear on the next
1014                 # line but not if it will make us loop infinitely.
1015                 if [ "${orig}" != "${out##* }${text}" ] ; then
1016                     text="${out##* }${text}"
1017                     out="${out% *}"
1018                 else
1019                     # Hmmm, doing that would make us loop, so add the
1020                     # rest of the word from the remainder of the text
1021                     # to this line and let it extend past $COLUMNS - 2.
1022                     out="${out}${text%% *}"
1023                     if [ "${text# *}" != "$text" ] ; then
1024                         # Remember the text after the next space for next time.
1025                         text="${text# *}"
1026                     else
1027                         # No text after next space.
1028                         text=""
1029                     fi
1030                 fi
1031             else
1032                 # We broke on a space.  If it will be at the beginning
1033                 # of the next line then remove it.
1034                 text="${text# }"
1035             fi
1036         fi
1037     done
1038
1039     echo "$out"
1040 }
1041
1042 # Display usage text, trying these approaches in order.
1043 # 1. See if it all fits on one line before $COLUMNS - 2.
1044 # 2. See if splitting before the default value and indenting it
1045 #    to $startcol means that nothing passes $COLUMNS - 2.
1046 # 3. Treat the message and default value as a string and just us fill_text()
1047 #    to format it. 
1048 usage_display_text () {
1049     local startcol="$1"
1050     local desc="$2"
1051     local default="$3"
1052     
1053     local width=$(($COLUMNS - 2 - $startcol))
1054     [ $width -lt 0 ] && width=$((78 - $startcol))
1055
1056     default="(default \"$default\")"
1057
1058     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1059         echo "${desc} ${default}"
1060     else
1061         local padding=$(printf "%${startcol}s" " ")
1062
1063         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1064             echo "$desc"
1065             echo "${padding}${default}"
1066         else
1067             fill_text $startcol "${desc} ${default}"
1068         fi
1069     fi
1070 }
1071
1072 # Display usage information for long config options.
1073 usage_smart_display () {( # sub-shell for local declaration of defconf()
1074         local startcol=33
1075
1076         defconf() {
1077             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1078
1079             printf "     --%-25s " "${longopt}=${3}"
1080
1081             usage_display_text $startcol "$4" "$2"
1082         }
1083
1084         "$@"
1085 )}
1086
1087
1088 # Display usage information for long config options.
1089 usage_config_options (){
1090     usage_smart_display load_config
1091 }
1092
1093 list_releases () {
1094     local releases=$(cd $installdir/releases && echo *.release)
1095     releases="${releases//.release}"
1096     releases="${releases// /\", \"}"
1097     echo "\"$releases\""
1098 }
1099
1100 with_release () {
1101     local release="$1"
1102     shift # subsequent args are passed to release file
1103
1104     # This simply loads an extra config file from $installdir/releases
1105     f="${installdir}/releases/${release}.release"
1106     if [ -r "$f" ] ; then
1107         . "$f"
1108     else
1109         f="${installdir}/releases/${release%%-*}.release"
1110         if [ -r "$f" ] ; then
1111             . "$f" "${release#*-}"
1112         else
1113             echo "Unknown release \"${release}\" specified to --with-release"
1114             printf "%-25s" "Supported releases are: "
1115             fill_text 25 "$(list_releases)"
1116             exit 1
1117         fi
1118     fi
1119
1120 }
1121
1122 has_public_addresses_DEFAULT ()
1123 {
1124     false
1125 }
1126
1127 # Build public address configuration.
1128 # * 1st public IP:  unless specified, last octet is $FIRSTIP + $PUBLIC_IP_OFFSET
1129 # * Excluded nodes: unless specified via comma-separated list of IP offsets,
1130 #                   nodes are excluded via their node types
1131 # * Number of public addresses per interface is either specified or $NUMNODES.
1132 make_public_addresses () {
1133     local firstip="${1:-$(($FIRSTIP + $PUBLIC_IP_OFFSET))}"
1134     local excluded_nodes="$2" 
1135     local num_addrs="${3:-${NUMNODES}}"
1136
1137     # For delimiting matches.
1138     excluded_nodes="${excluded_nodes:+,}${excluded_nodes}${excluded_nodes:+,}"
1139     # Avoid spaces
1140     excluded_nodes="${excluded_nodes// /}"
1141
1142     make_public_addresses_for_node ()
1143     {
1144         [ "$ctdb_node" = 1 ] || return 0
1145
1146         echo "[/etc/ctdb/public_addresses:${name}.${DOMAIN}]"
1147
1148         if [ -n "$excluded_nodes" -a \
1149             "${excluded_nodes/,${ip_offset},}" = "$excluded_nodes" ] ||
1150             ([ -z "$excluded_nodes" ] &&
1151                 call_func has_public_addresses "$node_type") ; then
1152
1153             local e i
1154             for e in "1" "2" ; do
1155                 for i in $(seq $firstip $(($firstip + $num_addrs - 1))) ; do
1156                     if [ $i -gt 254 ] ; then
1157                         die "make_public_addresses: octet > 254 - consider setting PUBLIC_IP_OFFSET"
1158                     fi
1159                     printf "\t${IPBASE}.${e}.${i}/24 eth${e}\n"
1160                 done
1161             done            
1162         fi
1163         echo 
1164     }
1165     hack_all_nodes_with make_public_addresses_for_node
1166 }
1167
1168 ######################################################################
1169
1170 load_config
1171
1172 ############################
1173 # parse command line options
1174 long_opts=$(getopt_config_options)
1175 getopt_output=$(getopt -n autocluster -o "c:e:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1176 [ $? != 0 ] && usage
1177
1178 use_default_config=true
1179
1180 # We do 2 passes of the options.  The first time we just handle usage
1181 # and check whether -c is being used.
1182 eval set -- "$getopt_output"
1183 while true ; do
1184     case "$1" in
1185         -c) shift 2 ; use_default_config=false ;;
1186         -e) shift 2 ;;
1187         --) shift ; break ;;
1188         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1189         --dump|-x) shift ;;
1190         -h|--help) usage ;; # Usage should be shown here for real defaults.
1191         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1192         *) usage ;; # shouldn't happen, so this is reasonable.
1193     esac
1194 done
1195
1196 config="./config"
1197 $use_default_config && [ -r "$config" ] && . "$config"
1198
1199 eval set -- "$getopt_output"
1200
1201 while true ; do
1202     case "$1" in
1203         # force at least ./local_file to avoid accidental file from $PATH
1204         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1205         -e) eval "$2" ; exit ;;
1206         --with-release)
1207             with_release "$2"
1208             shift 2
1209             ;;
1210         -x) set -x; shift ;;
1211         --dump) dump_config ;;
1212         --) shift ; break ;;
1213         -h|--help) usage ;; # Redundant.
1214         --*)
1215             # Putting --opt1|opt2|... into a variable and having case
1216             # match against it as a pattern doesn't work.  The | is
1217             # part of shell syntax, so we need to do this.  Look away
1218             # now to stop your eyes from bleeding! :-)
1219             x=",${long_opts}" # Now each option is surrounded by , and :
1220             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1221                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1222                 setconf_longopt "$1" "$2"; shift 2
1223             else
1224                 usage
1225             fi
1226             ;;
1227         *) usage ;; # shouldn't happen, so this is reasonable.
1228     esac
1229 done
1230
1231 # catch errors
1232 set -e
1233 set -E
1234 trap 'es=$?; 
1235       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1236       exit $es' ERR
1237
1238 # check for needed programs 
1239 check_command expect
1240 if [ "$SYSTEM_DISK_FORMAT" != "raw" ] ; then
1241     check_command $QEMU_NBD
1242     check_command nbd-client
1243 fi
1244
1245 [ $# -lt 1 ] && usage
1246
1247 command="$1"
1248 shift
1249
1250 case $command in
1251     create)
1252         type=$1
1253         shift
1254         case $type in
1255             base)
1256                 [ $# != 0 ] && usage
1257                 create_base
1258                 ;;
1259             cluster)
1260                 [ $# != 1 ] && usage
1261                 create_cluster "$1"
1262                 ;;
1263             node)
1264                 [ $# != 2 ] && usage
1265                 create_one_node "$1" "$2"
1266                 ;;
1267             *)
1268                 usage;
1269                 ;;
1270         esac
1271         ;;
1272     mount)
1273         [ $# != 1 ] && usage
1274         mount_disk "$1"
1275         ;;
1276     unmount)
1277         [ $# != 0 ] && usage
1278         unmount_disk
1279         ;;
1280     bootbase)
1281         boot_base;
1282         ;;
1283     testproxy)
1284         test_proxy;
1285         ;;
1286     *)
1287         usage;
1288         ;;
1289 esac