From 5961e031e11880c2a8ff34ec6c5ec0940e66a8e9 Mon Sep 17 00:00:00 2001 From: Ying Xie Date: Tue, 29 Oct 2019 08:30:27 -0700 Subject: [PATCH] [hostname-config] improve hostname-config process (#3676) We noticed in tests/production that there is a low probability failure where /etc/hosts could have some garbage characters before the entry for local host name. The consequence is that all sudo command would be very slow. In extreme cases it would prevent some services from starting properly. I suspect that the /etc/hosts file might be opened by some process causing the issue. Editing contents with new file level and replace the whole file should be safer. Signed-off-by: Ying Xie --- files/image_config/hostname/hostname-config.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/files/image_config/hostname/hostname-config.sh b/files/image_config/hostname/hostname-config.sh index 6cb8f73cf4..e9f7fc1227 100755 --- a/files/image_config/hostname/hostname-config.sh +++ b/files/image_config/hostname/hostname-config.sh @@ -8,9 +8,15 @@ hostname -F /etc/hostname # Remove the old hostname entry from hosts file. # But, 'localhost' entry is used by multiple applications. Don't remove it altogether. +# Edit contents of /etc/hosts and put in /etc/hosts.new if [ $CURRENT_HOSTNAME != "localhost" ] || [ $CURRENT_HOSTNAME == $HOSTNAME ] ; then - sed -i "/\s$CURRENT_HOSTNAME$/d" /etc/hosts + sed "/\s$CURRENT_HOSTNAME$/d" /etc/hosts > /etc/hosts.new +else + cp -f /etc/hosts /etc/hosts.new fi -echo "127.0.0.1 $HOSTNAME" >> /etc/hosts +echo "127.0.0.1 $HOSTNAME" >> /etc/hosts.new +# Swap file: hosts.new and hosts +mv -f /etc/hosts /etc/hosts.old +mv -f /etc/hosts.new /etc/hosts