debuggers.hg

changeset 21289:ca9519f09563

Remus: add file locking and modprobe utility functions

Signed-off-by: Brendan Cully <brendan@cs.ubc.ca>
author Keir Fraser <keir.fraser@citrix.com>
date Tue May 04 09:35:42 2010 +0100 (2010-05-04)
parents e1482f91b235
children 0f403a63ef6b
files tools/python/xen/remus/util.py
line diff
     1.1 --- a/tools/python/xen/remus/util.py	Tue May 04 09:35:18 2010 +0100
     1.2 +++ b/tools/python/xen/remus/util.py	Tue May 04 09:35:42 2010 +0100
     1.3 @@ -1,6 +1,6 @@
     1.4  # utility functions
     1.5  
     1.6 -import os, subprocess
     1.7 +import fcntl, os, subprocess
     1.8  
     1.9  class PipeException(Exception):
    1.10      def __init__(self, message, errno):
    1.11 @@ -8,9 +8,50 @@ class PipeException(Exception):
    1.12          message = '%s: %d, %s' % (message, errno, os.strerror(errno))
    1.13          Exception.__init__(self, message)
    1.14  
    1.15 +class Lock(object):
    1.16 +    """advisory lock"""
    1.17 +
    1.18 +    def __init__(self, filename):
    1.19 +        """lock using filename for synchronization"""
    1.20 +        self.filename = filename + '.lock'
    1.21 +
    1.22 +        self.fd = None
    1.23 +
    1.24 +        self.lock()
    1.25 +
    1.26 +    def __del__(self):
    1.27 +        self.unlock()
    1.28 +
    1.29 +    def lock(self):
    1.30 +        if self.fd:
    1.31 +            return
    1.32 +
    1.33 +        self.fd = open(self.filename, 'w')
    1.34 +        fcntl.lockf(self.fd, fcntl.LOCK_EX)
    1.35 +
    1.36 +    def unlock(self):
    1.37 +        if not self.fd:
    1.38 +            return
    1.39 +
    1.40 +        fcntl.lockf(self.fd, fcntl.LOCK_UN)
    1.41 +        self.fd = None
    1.42 +        try:
    1.43 +            os.remove(self.filename)
    1.44 +        except OSError:
    1.45 +            # harmless race
    1.46 +            pass
    1.47 +
    1.48  def canonifymac(mac):
    1.49      return ':'.join(['%02x' % int(field, 16) for field in mac.split(':')])
    1.50  
    1.51 +def checkpid(pid):
    1.52 +    """return True if pid is live"""
    1.53 +    try:
    1.54 +        os.kill(pid, 0)
    1.55 +        return True
    1.56 +    except OSError:
    1.57 +        return False
    1.58 +
    1.59  def runcmd(args, cwd=None):
    1.60      # TODO: stdin handling
    1.61      if type(args) == str:
    1.62 @@ -29,3 +70,11 @@ def runcmd(args, cwd=None):
    1.63          return stdout
    1.64      except (OSError, IOError), inst:
    1.65          raise PipeException('could not run %s' % args[0], inst.errno)
    1.66 +
    1.67 +def modprobe(modname):
    1.68 +    """attempt to load kernel module modname"""
    1.69 +    try:
    1.70 +        runcmd(['modprobe', '-q', modname])
    1.71 +        return True
    1.72 +    except PipeException:
    1.73 +        return False