]> review.fuel-infra Code Review - openstack-build/neutron-build.git/commitdiff
Make pid file locking non-blocking
authorRyan Moe <rmoe@mirantis.com>
Fri, 2 May 2014 20:08:45 +0000 (13:08 -0700)
committerRyan Moe <rmoe@mirantis.com>
Wed, 21 May 2014 20:29:01 +0000 (13:29 -0700)
fcntl.flock will block indefinitely if another process holds an exclusive
lock. A non-blocking flock operation will raise an error when a lock already
exists so we can fail immediately.

Closes-bug: 1315507
Change-Id: Icf97b1f8643157719b3d28ac2c0c1576a5069697

neutron/agent/linux/daemon.py
neutron/tests/unit/test_linux_daemon.py

index 38c1bb5db9bc789efc17c898f1013d7e489863ea..59bcd8eb0c04939367695b244f6c13c9ba2178a6 100644 (file)
@@ -29,16 +29,15 @@ LOG = logging.getLogger(__name__)
 
 class Pidfile(object):
     def __init__(self, pidfile, procname, uuid=None):
+        self.pidfile = pidfile
+        self.procname = procname
+        self.uuid = uuid
         try:
             self.fd = os.open(pidfile, os.O_CREAT | os.O_RDWR)
+            fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
         except IOError:
-            LOG.exception(_("Failed to open pidfile: %s"), pidfile)
+            LOG.exception(_("Error while handling pidfile: %s"), pidfile)
             sys.exit(1)
-        self.pidfile = pidfile
-        self.procname = procname
-        self.uuid = uuid
-        if not not fcntl.flock(self.fd, fcntl.LOCK_EX):
-            raise IOError(_('Unable to lock pid file'))
 
     def __str__(self):
         return self.pidfile
index 12e7d9f351e85973181e4b4f7aac99b9be7dc7e4..ab65a2bb295ea710f7f1d2d12f8b38cd198ac87a 100644 (file)
@@ -44,7 +44,8 @@ class TestPidfile(base.BaseTestCase):
 
         daemon.Pidfile('thefile', 'python')
         self.os.open.assert_called_once_with('thefile', os.O_CREAT | os.O_RDWR)
-        self.fcntl.flock.assert_called_once_with(FAKE_FD, self.fcntl.LOCK_EX)
+        self.fcntl.flock.assert_called_once_with(FAKE_FD, self.fcntl.LOCK_EX |
+                                                 self.fcntl.LOCK_NB)
 
     def test_init_open_fail(self):
         self.os.open.side_effect = IOError
@@ -61,7 +62,7 @@ class TestPidfile(base.BaseTestCase):
         p = daemon.Pidfile('thefile', 'python')
         p.unlock()
         self.fcntl.flock.assert_has_calls([
-            mock.call(FAKE_FD, self.fcntl.LOCK_EX),
+            mock.call(FAKE_FD, self.fcntl.LOCK_EX | self.fcntl.LOCK_NB),
             mock.call(FAKE_FD, self.fcntl.LOCK_UN)]
         )