Shutdown fails with mounted nfs filesystems under systemd

This issue “Shutdown problem unmounting NFS shares” still exists today. Since I use NFS shares a lot at home, this issue was a real pain for me… and it mostly resulted in me holding the shutdown button long enough to make my laptop to shutoff immediately. This is not nice for linux!j

In short

When shutting down linux, systemd does not manage to stop all services. This issue happenes because of mounted NFS shares. Shutting down linux is/should not be an issue when the shares are umounted before the shutdown process is started.

My solution

The solution is to automatically umount the NFS share before shutdown (or at the first possible moment during shutdown). This can be done using autofs and the likes, but when manually mounting NFS shares I present you a different solution.

This solution (currently) only works when LightDM is your display manager (login manager).

First create a file: root_nfs_umount.sh with the content:

#!/bin/bash
# Script by: Patrick Hanckmann (http://hanckmann.com)
#
# For:
#   /etc/lightdm/lightdm.conf
# set this script in the line:
#   session-cleanup-script = Script to run when quitting a user session (runs as root)
#
set -f; IFS=$'\n'
NFSMOUNTS=$(mount|grep nfs)
read -rd '' -a NFSMOUNTSARRAY <<<"$NFSMOUNTS"
set +f; unset IFS
for MOUNTLINE in "${NFSMOUNTSARRAY[@]}"
do
   read -rd '' -a MOUNTLINEARRAY <<<"$MOUNTLINE"
   umount ${MOUNTLINEARRAY[2]}
done

and make it executable:

$ chmod +x root_nfs_umount.sh

Then edit your lightdm.conf file (/etc/lightdm/lightdm.conf) and change the line:

# ...
# session-cleanup-script = Script to run when quitting a user session (runs as root)
# ...

into

# ...
session-cleanup-script = <path>/root_nfs_umount.sh
# ...

How it works

LightDM will run the script after each session (ie. after each logout). The script will find all mounted nfs shares via the mount command. Then it will umount all the found shares.

Pitfalls

This script umounts all nfs shares at each logout of any user. Hence, it is not ideal in a multi-user environment when more users mount NFS shares.

Conclusion

Although not perfect, this script solves my problem. I hope it can help you too.

~ Patrick