[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 <ying.xie@microsoft.com>
This commit is contained in:
Ying Xie 2019-10-29 08:30:27 -07:00 committed by Ying Xie
parent ff137a8e56
commit f764a167ac

View File

@ -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