ansible/roles/nfs-server/files/mknfsroledir.sh
Timo Makinen befa371fdc nfs-server: Allow role/home autocreation run more often
1. Implemented locking for scripts so only one instance is running
   simultaneously. This will also remove stale lock file if found.

2. Use LDAP contextCSN value to determine if we need to run script
   at all. Previous contextCSN is stored in state file which will
   be cleaned during reboots. If state file is not found direcotries
   are scanned in normal way.
2021-03-24 05:48:04 +00:00

93 lines
2.6 KiB
Bash
Executable file

#!/bin/bash
set -e
LOCKFILE="/run/$(basename "$0").pid"
STATEFILE="/run/$(basename "$0").state"
_basedn="$(awk '{ if ($1 == "BASE") print $2 }' /etc/openldap/ldap.conf)"
if [ -z "$_basedn" ]; then
logger -i -t "$(basename "$0")" -p user.error -s \
"ERROR: Failed to get LDAP basedn" 1>&2
exit 1
fi
if [ $# -eq 1 ]; then
_filter="(&(automountKey=$1)(objectClass=automount))"
elif [ $# -eq 0 ]; then
_filter="(objectClass=automount)"
else
echo "Usage: $(basename "$0") [role]" 1>&2
exit 1
fi
if [ -f "$LOCKFILE" ]; then
if kill -0 "$(cat "${LOCKFILE}")" ; then
_started=" ($(stat --format='%y' ${LOCKFILE}))"
logger -i -t "$(basename "$0")" -p user.notice -s \
"ERROR: Lockfile exists${_started}"
exit 1
else
logger -i -t "$(basename "$0")" -p user.notice -s \
"WARN: Removing stale lock file"
fi
fi
trap 'rm -f ${LOCKFILE}' INT TERM EXIT
echo "$$" > "$LOCKFILE"
_state="$(
ldapsearch -Q -LLL -s base contextCSN | awk '
BEGIN { csn=0 }
{
if ($1 == "contextCSN:") {
val=substr($2, 0, 21);
if (val > csn) {
csn = val
}
}
}
END { print csn }
'
)"
if [ -f "$STATEFILE" ]; then
if [ "$_state" == "$(cat "$STATEFILE")" ]; then
exit 0
fi
fi
ldapsearch -Q -LLL -b "ou=Groups,${_basedn}" "$_filter" automountInformation | \
awk -v_hostname="$(hostname -f)" '{
if ($1 == "automountInformation:") {
split($2, _, ":");
if (_[1] == _hostname) {
print _[2];
}
}
}' | while read -r _target ; do
_role="$(basename "$_target")"
_basedir="$(dirname "$_target")"
[ -d "$_target" ] && continue
if ! getent group "$_role" > /dev/null 2>&1 ; then
logger -i -t "$(basename "$0")" -p user.error -s \
"ERROR: Cannot find group '${_role}'" 1>&2
continue
fi
if [ ! -d "$_basedir" ]; then
logger -i -t "$(basename "$0")" -p user.error -s \
"ERROR: Cannot find base direcory '${_basedir}'"
continue
fi
logger -i -t "$(basename "$0")" -p user.info \
"Creating role directory '${_target}' for role '${_role}'"
install -d -o root -g "$_role" -m 2751 "$_target"
install -d -o root -g "$_role" -m 2770 "${_target}/development"
install -d -o root -g "$_role" -m 2770 "${_target}/external"
install -d -o root -g "$_role" -m 2770 "${_target}/library"
install -d -o root -g "$_role" -m 2775 "${_target}/public"
done
echo "$_state" > "$STATEFILE"