]> gitweb.fluxo.info Git - hydra.git/commitdiff
Feat: hydractl: sync-media: lock file handling
authorSilvio Rhatto <rhatto@riseup.net>
Sat, 27 Sep 2025 18:26:23 +0000 (15:26 -0300)
committerSilvio Rhatto <rhatto@riseup.net>
Sat, 27 Sep 2025 18:26:23 +0000 (15:26 -0300)
share/hydractl/sync-media

index 498b247018f3246de058f1dd4eeb9dc88b3a7181..08d62809f8dd43c5c6237928f74d0d4b12df8e9e 100755 (executable)
@@ -17,6 +17,7 @@ CACHE="/var/cache/$HOST/media"
 MEDIA="media.$DOMAIN"
 INCOMING="$CACHE/incoming"
 WHOAMI="`whoami`"
+LOCK=".sync-media.lock"
 OPTIONS="$*"
 
 # Dependencies
@@ -24,6 +25,56 @@ hydra_install_package rsync
 hydra_install_package unison
 hydra_install_package git-annex
 
+# Fatal error
+# Adapted from borger
+function fatal {
+  info [fatal] $*
+  exit 1;
+}
+
+# Create lockfile
+# Adapted from borger
+function sync_media_set_lockfile {
+  if [ ! -z "$LOCKFILE" ]; then
+    mkdir -p `dirname $LOCKFILE`
+
+    if ( set -o noclobber; echo "$$" > "$LOCKFILE" ) &> /dev/null; then
+      trap 'sync_media_unset_lockfile' INT TERM EXIT
+    else
+      fatal "Could not create lockfile $LOCKFILE, exiting"
+    fi
+  fi
+}
+
+# Remove lockfile
+# Adapted from borger
+function sync_media_unset_lockfile {
+  if [ ! -z "$LOCKFILE" ]; then
+    rm -f $LOCKFILE || echo "Could not remove lockfile $LOCKFILE"
+  fi
+}
+
+# Check lockfile
+# Adapted from borger
+function sync_media_check_lockfile {
+  local pid process
+
+  if [ ! -z "$LOCKFILE" ] && [ -f "$LOCKFILE" ]; then
+    pid="`cat $LOCKFILE`"
+    process="`ps --no-headers -o comm $pid`"
+
+    git annex unannex $LOCK
+    git ignore $LOCK
+
+    if [ "$?" == "0" ] && [ "`ps --no-headers -o comm $$`" == "$process" ]; then
+      fatal "Another program is running for $LOCKFILE, skipping run"
+    else
+      echo "Found old lockfile $LOCKFILE, removing it"
+      sync_media_unset_lockfile
+    fi
+  fi
+}
+
 # Fix identity
 function sync_media_identity {
   if [ -z "`git config --local user.email`" ] || [ -z "`git config --local user.name`" ]; then
@@ -223,6 +274,8 @@ fi
 
 # Iterate over existing repositories in the local cache
 for folder in $REPOSITORIES; do
+  LOCKFILE="$CACHE/$folder/$LOCK"
+
   # Sync each repository in the local cache
   if [ -d "$CACHE/$folder/.git/annex" ]; then
     if [ "`git -C $CACHE/$folder config sync-media.skip`" == "true" ]; then
@@ -233,6 +286,10 @@ for folder in $REPOSITORIES; do
     cd $CACHE/$folder
     echo "Syncing $CACHE/$folder..."
 
+    # Lockfile handling
+    sync_media_check_lockfile
+    sync_media_set_lockfile
+
     # Ensure the removable volume is in the list of remotes
     sync_media_ensure_remote $REMOTE $VOLUME/$MEDIA/$folder
 
@@ -266,6 +323,9 @@ for folder in $REPOSITORIES; do
     sync_media_dropunused
     git prune
     git gc
+
+    # Unset the lockfile
+    sync_media_unset_lockfile
     )
   fi