Ensure a single running instance of edit monitor
This cl ensures at most 1 instance of edit monitor running from the
same binary by killing any existing instance before starting.
Specifically, When an edit monitor process starts, it will write a pidfile containing its pid and if such pidfile already exists (which means there's another instance there), it will read the pid contained in that pidfile and kill the corresponding process first.
Test: atst daemon_manager_test
bug: 365617369
Change-Id: I76954344df649aa79a6ef07ce55a62985decdb53
diff --git a/tools/edit_monitor/daemon_manager.py b/tools/edit_monitor/daemon_manager.py
index c09c321..8ec2588 100644
--- a/tools/edit_monitor/daemon_manager.py
+++ b/tools/edit_monitor/daemon_manager.py
@@ -55,6 +55,7 @@
def start(self):
"""Writes the pidfile and starts the daemon proces."""
try:
+ self._stop_any_existing_instance()
self._write_pid_to_pidfile()
self._start_daemon_process()
except Exception as e:
@@ -71,6 +72,22 @@
except Exception as e:
logging.exception("Failed to stop daemon manager with error %s", e)
+ def _stop_any_existing_instance(self):
+ if not self.pid_file_path.exists():
+ logging.debug("No existing instances.")
+ return
+
+ ex_pid = self._read_pid_from_pidfile()
+
+ if ex_pid:
+ logging.info("Found another instance with pid %d.", ex_pid)
+ self._terminate_process(ex_pid)
+ self._remove_pidfile()
+
+ def _read_pid_from_pidfile(self):
+ with open(self.pid_file_path, "r") as f:
+ return int(f.read().strip())
+
def _write_pid_to_pidfile(self):
"""Creates a pidfile and writes the current pid to the file.