Skip to contentSkip to conversation

main - lvmdbusd: Add lockfile

PATCH Tony Asleson 1 participant 1 message Sep 19, 2022

lore
Share & tools
lore
#0 lore raw
Gitweb:        https://sourceware.org/git/?p=lvm2.git;a=commitdiff;h=3fdf4493481ff8baae2ac5416dce6d05b69e6b28
Commit:        3fdf4493481ff8baae2ac5416dce6d05b69e6b28
Parent:        1a4384979cdf889bd63a932d83933079c53490ae
Author:        Tony Asleson <[email protected]>
AuthorDate:    Mon Aug 8 20:48:10 2022 -0500
Committer:     Tony Asleson <[email protected]>
CommitterDate: Fri Sep 16 10:49:36 2022 -0500

lvmdbusd: Add lockfile

The daemon cannot handle multiple copies of itself running at the same time, ensure this cannot happen.

---
 daemons/lvmdbusd/cfg.py   |   2 +
 daemons/lvmdbusd/main.py  | 111 +++++++++++++++++++++++-----------------------
 daemons/lvmdbusd/utils.py |  37 ++++++++++++++--
 3 files changed, 92 insertions(+), 58 deletions(-)
daemons/lvmdbusd/cfg.py +2 -0
index 684c2b208..ee4e41b30 100644
@@ -16,6 +16,8 @@ from lvmdbusd import path
 
 LVM_CMD = os.getenv('LVM_BINARY', path.LVM_BINARY)
 
+LOCK_FILE = os.getenv("LVM_DBUSD_LOCKFILE", "/var/lock/lvm/lvmdbusd")
+
 # This is the global object manager
 om = None
 
daemons/lvmdbusd/main.py +56 -55

117 lines not on this page · raw message

daemons/lvmdbusd/utils.py +34 -3
index f5bca1b46..d24a34935 100644
@@ -11,10 +11,12 @@ import xml.etree.ElementTree as Et
 import sys
 import inspect
 import ctypes
+import errno
+import fcntl
 import os
+import stat
 import string
 import datetime
-from fcntl import fcntl, F_GETFL, F_SETFL
 
 import dbus
 from lvmdbusd import cfg
@@ -690,8 +692,8 @@ def mt_remove_dbus_objects(objs):
 
 # Make stream non-blocking
 def make_non_block(stream):
-	flags = fcntl(stream, F_GETFL)
-	fcntl(stream, F_SETFL, flags | os.O_NONBLOCK)
+	flags = fcntl.fcntl(stream, fcntl.F_GETFL)
+	fcntl.fcntl(stream, fcntl.F_SETFL, flags | os.O_NONBLOCK)
 
 
 def read_decoded(stream):
@@ -699,3 +701,32 @@ def read_decoded(stream):
 	if tmp:
 		return tmp.decode("utf-8")
 	return ''
+
+
+class LockFile(object):
+	"""
+	Simple lock file class
+	Based on Pg.1144 "The Linux Programming Interface" by Michael Kerrisk
+	"""
+	def __init__(self, lock_file):
+		self.fd = 0
+		self.lock_file = lock_file
+
+	def __enter__(self):
+		try:
+			self.fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, stat.S_IRUSR | stat.S_IWUSR)
+
+			# Get and set the close on exec and lock the file
+			flags = fcntl.fcntl(self.fd, fcntl.F_GETFD)
+			flags |= fcntl.FD_CLOEXEC
+			fcntl.fcntl(self.fd, fcntl.F_SETFL, flags)
+			fcntl.lockf(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+		except OSError as e:
+			if e.errno == errno.EAGAIN:
+				log_error("Daemon already running, exiting!")
+			else:
+				log_error("Error during creation of lock file(%s): errno(%d), exiting!" % (self.lock_file, e.errno))
+			sys.exit(114)
+
+	def __exit__(self, _type, _value, _traceback):
+		os.close(self.fd)