From b330ac0b2ed0425805c2849ba11b83924ab958c0 Mon Sep 17 00:00:00 2001
From: Guido Trotter <ultrotter@google.com>
Date: Wed, 23 Jul 2008 14:23:31 +0000
Subject: [PATCH] Add utils.{Write,Remove}PidFile

WritePidFile is a helper function that writes the current pid in a
pidfile within the ganeti run directory. RemovePidFile tries to delete
it.

Reviewed-by: iustinp
---
 lib/utils.py | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/lib/utils.py b/lib/utils.py
index 05240eabb..e90035286 100644
--- a/lib/utils.py
+++ b/lib/utils.py
@@ -1051,6 +1051,42 @@ def Daemonize(logfile, noclose_fds=None):
   return 0
 
 
+def _DaemonPidFileName(name):
+  """Compute a ganeti pid file absolute path, given the daemon name.
+
+  """
+  return os.path.join(constants.RUN_GANETI_DIR, "%s.pid" % name)
+
+
+def WritePidFile(name):
+  """Write the current process pidfile.
+
+  The file will be written to constants.RUN_GANETI_DIR/name.pid
+
+  """
+  pid = os.getpid()
+  pidfilename = _DaemonPidFileName(name)
+  if IsPidFileAlive(pidfilename):
+    raise GenericError("%s contains a live process" % pidfilename)
+
+  WriteFile(pidfilename, data="%d\n" % pid)
+
+
+def RemovePidFile(name):
+  """Remove the current process pidfile.
+
+  Any errors are ignored.
+
+  """
+  pid = os.getpid()
+  pidfilename = _DaemonPidFileName(name)
+  # TODO: we could check here that the file contains our pid
+  try:
+    RemoveFile(pidfilename)
+  except:
+    pass
+
+
 def FindFile(name, search_path, test=os.path.exists):
   """Look for a filesystem object in a given path.
 
-- 
GitLab