From ab783c82bf7fa25be568d635d3b40f4162338ec6 Mon Sep 17 00:00:00 2001
From: Eric Zillmann <zillmann@arocom.de>
Date: Tue, 19 Feb 2019 09:43:49 +0100
Subject: [PATCH] #2783 use lockfile instead of checking active processes as
 the lockfile is site specific; check to detect stale lock files

---
 templates/scripts/update/update-loop.jinja2 | 31 ++++++++++++++++-----
 1 file changed, 24 insertions(+), 7 deletions(-)

diff --git a/templates/scripts/update/update-loop.jinja2 b/templates/scripts/update/update-loop.jinja2
index 7546fd3..2f24772 100644
--- a/templates/scripts/update/update-loop.jinja2
+++ b/templates/scripts/update/update-loop.jinja2
@@ -1,17 +1,32 @@
 #!/usr/bin/env bash
 
+LOCKFILE={{ webRoot }}/.update-loop.lock;
+
+# Check if there is a lockfile.
+if [ -f "$LOCKFILE" ]; then
+  # Get the pid from the lockfile.
+  lockpid="$(head -n1 "$LOCKFILE")";
+  if ! echo "$lockpid" | grep "^[0-9][0-9]*$" >/dev/null; then
+    echo "> error reading lockfile";
+    exit 1;
+  fi;
+
+  # Check if the pid in the lockfile is still active.
+  if ps -eo pid,cmd | grep "^\s*$lockpid .*\/var\/www\/\.update-loop$" >/dev/null; then
+    echo '> locked';
+    exit;
+  fi;
+fi
+
 # Get our own process ID.
 mypid="$$";
-if [ "$mypid" = "" ] || ! echo "$mypid" | grep "^[0-9][0-9]*$" >/dev/null; then
-  echo "Error getting current PID.";
+if ! echo "$mypid" | grep "^[0-9][0-9]*$" >/dev/null; then
+  echo "> error getting current PID";
   exit 1;
 fi;
 
-# Check if there are other .update-loop processes.
-if ps -eo pid,cmd | grep "\/\.update-loop$" | grep -v "grep\|sudo\|^\s*$mypid\s" >/dev/null; then
-  echo "Skip: .update-loop is already running.";
-  exit 0;
-fi;
+# Store our pid as lockfile.
+echo "$mypid" >"$LOCKFILE"
 
 # Get path to the actual update script.
 scriptfile="$0";
@@ -28,3 +43,5 @@ while true; do
 
   sleep 5;
 done;
+
+rm "$LOCKFILE";
-- 
GitLab