Rebase of ks.cfg due to upstream changes
[fuel.git] / build / f_isoroot / f_bootstrap / bootstrap_admin_node.sh.orig
1 #!/bin/bash
2 mkdir -p /var/log/puppet
3 exec > >(tee -i /var/log/puppet/bootstrap_admin_node.log)
4 exec 2>&1
5
6 FUEL_RELEASE=$(cat /etc/fuel_release)
7 ASTUTE_YAML='/etc/fuel/astute.yaml'
8 BOOTSTRAP_NODE_CONFIG="/etc/fuel/bootstrap_admin_node.conf"
9 bs_build_log='/var/log/fuel-bootstrap-image-build.log'
10 bs_status=0
11 # Backup network configs to this folder. Folder will be created only if
12 # backup process actually will be.
13 bup_folder="/var/bootstrap_admin_node_bup_$(date +%Y-%m-%d-%H-%M-%S)/"
14 ### Long messages inside code makes them more complicated to read...
15 # bootstrap messages
16 # FIXME fix help links
17 bs_skip_message="WARNING: Ubuntu bootstrap build has been skipped. \
18 Please build and activate bootstrap manually with CLI command \
19 \`fuel-bootstrap build --activate\`. \
20 While you don't activate any bootstrap - new nodes cannot be discovered \
21 and added to cluster. \
22 For more information please visit \
23 https://docs.mirantis.com/openstack/fuel/fuel-master/"
24 bs_error_message="WARNING: Failed to build the bootstrap image, see $bs_build_log \
25 for details. Perhaps your Internet connection is broken. Please fix the \
26 problem and run \`fuel-bootstrap build --activate\`. \
27 While you don\'t activate any bootstrap - new nodes cannot be discovered \
28 and added to cluster. \
29 For more information please visit \
30 https://docs.mirantis.com/openstack/fuel/fuel-master/"
31 bs_progress_message="There is no active bootstrap. Bootstrap image building \
32 is in progress. Usually it takes 15-20 minutes. It depends on your internet \
33 connection and hardware performance. Please reboot failed to discover nodes \
34 after bootstrap image become available."
35 bs_done_message="Default bootstrap image building done. Now you can boot new \
36 nodes over PXE, they will be discovered and become available for installing \
37 OpenStack on them"
38 bs_centos_message="WARNING: Deprecated Centos bootstrap has been chosen \
39 and activated. Now you can boot new nodes over PXE, they will be discovered \
40 and become available for installing OpenStack on them."
41 # Update issues messages
42 update_warn_message="There is an issue connecting to the Fuel update repository. \
43 Please fix your connection prior to applying any updates. \
44 Once the connection is fixed, we recommend reviewing and applying \
45 Maintenance Updates for this release of Mirantis OpenStack: \
46 https://docs.mirantis.com/openstack/fuel/fuel-${FUEL_RELEASE}/\
47 release-notes.html#maintenance-updates"
48 update_done_message="We recommend reviewing and applying Maintenance Updates \
49 for this release of Mirantis OpenStack: \
50 https://docs.mirantis.com/openstack/fuel/fuel-${FUEL_RELEASE}/\
51 release-notes.html#maintenance-updates"
52 fuelmenu_fail_message="Fuelmenu was not able to generate '/etc/fuel/astute.yaml' file! \
53 Please, restart it manualy using 'fuelmenu' command."
54
55 function countdown() {
56   local i
57   sleep 1
58   for ((i=$1-1; i>=1; i--)); do
59     printf '\b\b\b\b%04d' "$i"
60     sleep 1
61   done
62 }
63
64 function fail() {
65   echo "ERROR: Fuel node deployment FAILED! Check /var/log/puppet/bootstrap_admin_node.log for details" 1>&2
66   exit 1
67 }
68
69 function get_ethernet_interfaces() {
70   # Get list of all ethernet interfaces, non-virtual, not a wireless
71   for DEV in /sys/class/net/* ; do
72     # Take only links into account, skip files
73     if test ! -L $DEV ; then
74        continue
75     fi
76     DEVPATH=$(readlink -f $DEV)
77     # Avoid virtual devices like loopback, tunnels, bonding, vlans ...
78     case $DEVPATH in
79          */virtual/*)
80             continue
81          ;;
82     esac
83     IF=${DEVPATH##*/}
84     # Check ethernet only
85     case "`cat $DEV/type`" in
86          1)
87          # TYPE=1 is ethernet, may also be wireless, bond, tunnel ...
88          # Virtual lo, bound, vlan, tunneling has been skipped before
89          if test -d $DEV/wireless -o -L $DEV/phy80211 ;
90          then
91               continue
92          else
93          # Catch ethernet non-virtual device
94               echo $IF
95          fi
96          ;;
97          *) continue
98          ;;
99     esac
100   done
101 }
102
103 # Get value of a key from ifcfg-* files
104 # Usage:
105 #   get_ifcfg_value NAME /etc/sysconfig/network-scripts/ifcfg-eth0
106 function get_ifcfg_value {
107     local key=$1
108     local path=$2
109     local value=''
110     if [[ -f ${path} ]]; then
111         value=$(awk -F\= "\$1==\"${key}\" {print \$2}" ${path})
112         value=${value//\"/}
113     fi
114     echo ${value}
115 }
116
117 # Workaround to fix dracut network configuration approach:
118 #   Bring down all network interfaces which have the same IP
119 #   address statically configured as 'primary' interface
120 function ifdown_ethernet_interfaces {
121     local adminif_ipaddr
122     local if_config
123     local if_name
124     local if_ipaddr
125
126     adminif_ipaddr=$(get_ifcfg_value IPADDR /etc/sysconfig/network-scripts/ifcfg-${ADMIN_INTERFACE})
127     if [[ -z "${adminif_ipaddr}" ]]; then
128         return
129     fi
130     for if_config in $(find /etc/sysconfig/network-scripts -name 'ifcfg-*' ! -name 'ifcfg-lo'); do
131         if_name=$(get_ifcfg_value NAME $if_config)
132         if [[ "${if_name}" == "${ADMIN_INTERFACE}" ]]; then
133             continue
134         fi
135         if_ipaddr=$(get_ifcfg_value IPADDR $if_config)
136         if [[ "${if_ipaddr}" == "${adminif_ipaddr}" ]]; then
137             echo "Interface '${if_name}' uses the same ip '${if_ipaddr}' as admin interface '${ADMIN_INTERFACE}', removing ..."
138             ifdown ${if_name}
139             mkdir -p "${bup_folder}"
140             mv -f "${if_config}" "${bup_folder}"
141         fi
142     done
143 }
144
145 # Check if interface name is valid by checking that
146 # a config file with NAME equal to given name exists.
147 function ifname_valid {
148     local adminif_name=$1
149     local if_name
150     local if_config
151     for if_config in $(find /etc/sysconfig/network-scripts -name 'ifcfg-*' ! -name 'ifcfg-lo'); do
152         if_name=$(get_ifcfg_value NAME $if_config)
153         if [[ "${if_name}" == "${adminif_name}" ]]; then
154             return 0
155         fi
156     done
157     return 1
158 }
159
160
161 # LANG variable is a workaround for puppet-3.4.2 bug. See LP#1312758 for details
162 export LANG=en_US.UTF8
163 # Be sure, that network devices have been initialized
164 udevadm trigger --subsystem-match=net
165 udevadm settle
166
167 # Import bootstrap_admin_node.conf if exists
168 if [ -f "${BOOTSTRAP_NODE_CONFIG}" ]; then
169     source "${BOOTSTRAP_NODE_CONFIG}"
170 fi
171
172 # Set defaults to unset / empty variables
173 # Although eth0 is not always valid it's a good well-known default
174 # If there is no such interface it will fail to pass ifname_valid
175 # check and will be replaced.
176 OLD_ADMIN_INTERFACE=${ADMIN_INTERFACE}
177 ADMIN_INTERFACE=${ADMIN_INTERFACE:-'eth0'}
178 showmenu=${showmenu:-'no'}
179
180 # Now check that ADMIN_INTERFACE points to a valid interface
181 # If it doesn't fallback to getting the first interface name
182 # from a list of all available interfaces sorted alphabetically
183 if ! ifname_valid $ADMIN_INTERFACE; then
184     # Take the very first ethernet interface as an admin interface
185     ADMIN_INTERFACE=$(get_ethernet_interfaces | sort -V | head -1)
186 fi
187
188 if [[ "${OLD_ADMIN_INTERFACE}" != "${ADMIN_INTERFACE}" ]]; then
189   echo "Saving ADMIN_INTERFACE value"
190   sed -ie "s/^ADMIN_INTERFACE=.*/ADMIN_INTERFACE=${ADMIN_INTERFACE}/g" \
191     ${BOOTSTRAP_NODE_CONFIG}
192 fi
193
194 echo "Applying admin interface '$ADMIN_INTERFACE'"
195 export ADMIN_INTERFACE
196
197 echo "Bringing down ALL network interfaces except '${ADMIN_INTERFACE}'"
198 ifdown_ethernet_interfaces
199 systemctl restart network
200
201 echo "Applying default Fuel settings..."
202 set -x
203 fuelmenu --save-only --iface=$ADMIN_INTERFACE
204 set +x
205 echo "Done!"
206
207 if [[ "$showmenu" == "yes" || "$showmenu" == "YES" ]]; then
208   fuelmenu
209   else
210   #Give user 15 seconds to enter fuelmenu or else continue
211   echo
212   echo -n "Press a key to enter Fuel Setup (or press ESC to skip)...   15"
213   countdown 15 & pid=$!
214   if ! read -s -n 1 -t 15 key; then
215     echo -e "\nSkipping Fuel Setup..."
216   else
217     { kill "$pid"; wait $!; } 2>/dev/null
218     case "$key" in
219       $'\e')  echo "Skipping Fuel Setup.."
220               ;;
221       *)      echo -e "\nEntering Fuel Setup..."
222               fuelmenu
223               ;;
224     esac
225   fi
226 fi
227
228 if [ ! -f "${ASTUTE_YAML}" ]; then
229   echo ${fuelmenu_fail_message}
230   fail
231 fi
232
233 # Enable sshd
234 systemctl enable sshd
235 systemctl start sshd
236
237 # Enable iptables
238 systemctl enable iptables.service
239 systemctl start iptables.service
240
241
242 if [ "$wait_for_external_config" == "yes" ]; then
243   wait_timeout=3000
244   pidfile=/var/lock/wait_for_external_config
245   echo -n "Waiting for external configuration (or press ESC to skip)...
246 $wait_timeout"
247   countdown $wait_timeout & countdown_pid=$!
248   exec -a wait_for_external_config sleep $wait_timeout & wait_pid=$!
249   echo $wait_pid > $pidfile
250   while ps -p $countdown_pid &> /dev/null && ps -p $wait_pid &>/dev/null; do
251     read -s -n 1 -t 2 key
252     case "$key" in
253       $'\e')   echo -e "\b\b\b\b abort on user input"
254                break
255                ;;
256       *)       ;;
257     esac
258   done
259   { kill $countdown_pid $wait_pid & wait $!; }
260   rm -f $pidfile
261 fi
262
263
264 #Reread /etc/sysconfig/network to inform puppet of changes
265 . /etc/sysconfig/network
266 hostname "$HOSTNAME"
267
268 # XXX: ssh keys which should be included into the bootstrap image are
269 # generated during containers deployment. However cobbler checkfs for
270 # a kernel and initramfs when creating a profile, which poses chicken
271 # and egg problem. Fortunately cobbler is pretty happy with empty files
272 # so it's easy to break the loop.
273 make_ubuntu_bootstrap_stub () {
274         local bootstrap_dir='/var/www/nailgun/bootstraps/active_bootstrap'
275         local bootstrap_stub_dir='/var/www/nailgun/bootstraps/bootstrap_stub'
276         mkdir -p ${bootstrap_stub_dir}
277         for item in vmlinuz initrd.img; do
278                 touch "${bootstrap_stub_dir}/$item"
279         done
280         ln -s ${bootstrap_stub_dir} ${bootstrap_dir} || true
281 }
282
283 get_bootstrap_flavor () {
284         python <<-EOF
285         from yaml import safe_load
286         with open("$ASTUTE_YAML", 'r') as f:
287             conf = safe_load(f).get('BOOTSTRAP', {})
288         print(conf.get('flavor', 'centos').lower())
289         EOF
290 }
291
292 get_bootstrap_skip () {
293         python <<-EOF
294         from yaml import safe_load
295         with open("$ASTUTE_YAML", 'r') as f:
296             conf = safe_load(f).get('BOOTSTRAP', {})
297         print(conf.get('skip_default_img_build', False))
298         EOF
299 }
300
301 set_ui_bootstrap_error () {
302         # This notify can't be closed or removed by user.
303         # For remove notify - send empty string.
304         local message=$1
305         python <<-EOF
306         from fuel_bootstrap.utils import notifier
307         notifier.notify_webui('${message}')
308         EOF
309 }
310
311 # Actually build the bootstrap image
312 build_ubuntu_bootstrap () {
313         local ret=1
314         echo ${bs_progress_message} >&2
315         set_ui_bootstrap_error "${bs_progress_message}" >&2
316         if fuel-bootstrap -v --debug build --activate >>"$bs_build_log" 2>&1; then
317           ret=0
318           fuel notify --topic "done" --send "${bs_done_message}"
319         else
320           ret=1
321           set_ui_bootstrap_error "${bs_error_message}" >&2
322         fi
323         # perform hard-return from func
324         # this part will update input $1 variable
325         local  __resultvar=$1
326         eval $__resultvar="'${ret}'"
327         return $ret
328 }
329
330 # Create empty files to make cobbler happy
331 # (even if we don't use Ubuntu based bootstrap)
332 make_ubuntu_bootstrap_stub
333
334 service docker start
335
336 old_sysctl_vm_value=$(sysctl -n vm.min_free_kbytes)
337 if [ ${old_sysctl_vm_value} -lt 65535 ]; then
338   echo "Set vm.min_free_kbytes..."
339   sysctl -w vm.min_free_kbytes=65535
340 fi
341
342 if [ -f /root/.build_images ]; then
343   #Fail on all errors
344   set -e
345   trap fail EXIT
346
347   echo "Loading Fuel base image for Docker..."
348   docker load -i /var/www/nailgun/docker/images/fuel-images.tar
349
350   echo "Building Fuel Docker images..."
351   WORKDIR=$(mktemp -d /tmp/docker-buildXXX)
352   SOURCE=/var/www/nailgun/docker
353   REPO_CONT_ID=$(docker -D run -d -p 80 -v /var/www/nailgun:/var/www/nailgun fuel/centos sh -c 'mkdir -p /var/www/html/repo/os;ln -sf /var/www/nailgun/centos/x86_64 /var/www/html/repo/os/x86_64;ln -s /var/www/nailgun/mos-centos/x86_64 /var/www/html/mos-repo;/usr/sbin/apachectl -DFOREGROUND')
354   RANDOM_PORT=$(docker port $REPO_CONT_ID 80 | cut -d':' -f2)
355
356   for imagesource in /var/www/nailgun/docker/sources/*; do
357     if ! [ -f "$imagesource/Dockerfile" ]; then
358       echo "Skipping ${imagesource}..."
359       continue
360     fi
361     image=$(basename "$imagesource")
362     cp -R "$imagesource" $WORKDIR/$image
363     mkdir -p $WORKDIR/$image/etc
364     cp -R /etc/puppet /etc/fuel $WORKDIR/$image/etc
365     sed -e "s/_PORT_/${RANDOM_PORT}/" -i $WORKDIR/$image/Dockerfile
366     sed -r -e 's/^"?PRODUCTION"?:.*/PRODUCTION: "docker-build"/' -i $WORKDIR/$image/etc/fuel/astute.yaml
367     # FIXME(kozhukalov): Once this patch https://review.openstack.org/#/c/219581/ is merged
368     # remove this line. fuel-library is to use PRODUCTION value from astute.yaml instead of
369     # the same value from version.yaml. It is a part of version.yaml deprecation plan.
370     sed -e 's/production:.*/production: "docker-build"/' -i $WORKDIR/$image/etc/fuel/version.yaml
371     docker build -t fuel/${image}_${FUEL_RELEASE} $WORKDIR/$image
372   done
373   docker rm -f $REPO_CONT_ID
374   rm -rf "$WORKDIR"
375
376   #Remove trap for normal deployment
377   trap - EXIT
378   set +e
379 else
380   echo "Loading docker images. (This may take a while)"
381   docker load -i /var/www/nailgun/docker/images/fuel-images.tar
382 fi
383
384 if [ ${old_sysctl_vm_value} -lt 65535 ]; then
385   echo "Restore sysctl vm.min_free_kbytes value..."
386   sysctl -w vm.min_free_kbytes=${old_sysctl_vm_value}
387 fi
388
389 # apply puppet
390 puppet apply --detailed-exitcodes -d -v /etc/puppet/modules/nailgun/examples/host-only.pp
391 if [ $? -ge 4 ];then
392   fail
393 fi
394
395 # Sync time
396 systemctl stop ntpd
397 systemctl start ntpdate || echo "Failed to synchronize time with 'ntpdate'"
398 systemctl start ntpd
399
400 rmdir /var/log/remote && ln -s /var/log/docker-logs/remote /var/log/remote
401
402 dockerctl check || fail
403 bash /etc/rc.local
404
405 if [ "`get_bootstrap_flavor`" = "ubuntu" ]; then
406   if [ "`get_bootstrap_skip`" = "False" ]; then
407     build_ubuntu_bootstrap bs_status || true
408   else
409     fuel notify --topic "warning" --send "${bs_skip_message}"
410     bs_status=2
411   fi
412 else
413   fuel notify --topic "warning" --send "${bs_centos_message}"
414   bs_status=3
415 fi
416
417 # Enable updates repository
418 cat > /etc/yum.repos.d/mos${FUEL_RELEASE}-updates.repo << EOF
419 [mos${FUEL_RELEASE}-updates]
420 name=mos${FUEL_RELEASE}-updates
421 baseurl=http://mirror.fuel-infra.org/mos-repos/centos/mos${FUEL_RELEASE}-centos\$releasever-fuel/updates/x86_64/
422 gpgcheck=0
423 skip_if_unavailable=1
424 EOF
425
426 # Enable security repository
427 cat > /etc/yum.repos.d/mos${FUEL_RELEASE}-security.repo << EOF
428 [mos${FUEL_RELEASE}-security]
429 name=mos${FUEL_RELEASE}-security
430 baseurl=http://mirror.fuel-infra.org/mos-repos/centos/mos${FUEL_RELEASE}-centos\$releasever-fuel/security/x86_64/
431 gpgcheck=0
432 skip_if_unavailable=1
433 EOF
434
435 #Check if repo is accessible
436 echo "Checking for access to updates repository..."
437 repourl=$(yum repolist all -v | awk '{if ($1 ~ "baseurl" && $3 ~ "updates") print $3}' | head -1)
438 if urlaccesscheck check "$repourl" ; then
439   UPDATE_ISSUES=0
440 else
441   UPDATE_ISSUES=1
442 fi
443
444 if [ $UPDATE_ISSUES -eq 1 ]; then
445   message=${update_warn_message}
446   level="warning"
447 else
448   message=${update_done_message}
449   level="done"
450 fi
451 echo
452 echo "*************************************************"
453 echo -e "${message}"
454 echo "*************************************************"
455 fuel notify --topic "${level}" --send $(echo "${message}" | tr '\r\n' ' ') 2>&1
456
457 # Perform bootstrap messaging to stdout
458 case ${bs_status} in
459   1)
460   echo -e "${bs_error_message}"
461   echo "*************************************************"
462   ;;
463   2)
464   echo -e "${bs_skip_message}"
465   echo "*************************************************"
466   ;;
467   3)
468   echo -e "${bs_centos_message}"
469   echo "*************************************************"
470   ;;
471 esac
472
473 echo "Fuel node deployment complete!"
474 # Sleep for agetty autologon
475 sleep 3