Skip to content

Commit

Permalink
Add pidfile support
Browse files Browse the repository at this point in the history
  • Loading branch information
joejulian committed Dec 22, 2012
1 parent efd62ad commit b260ca2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
34 changes: 34 additions & 0 deletions beaver/pidfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import fcntl
import os

class PidFile(object):
"""Context manager that locks a pid file. Implemented as class
not generator because daemon.py is calling .__exit__() with no parameters
instead of the None, None, None specified by PEP-343."""
# pylint: disable=R0903

def __init__(self, path):
self.path = path
self.pidfile = None

def __enter__(self):
self.pidfile = open(self.path, "a+")
try:
fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
raise SystemExit("Already running according to " + self.path)
self.pidfile.seek(0)
self.pidfile.truncate()
self.pidfile.write(str(os.getpid()))
self.pidfile.flush()
self.pidfile.seek(0)
return self.pidfile

def __exit__(self, exc_type=None, exc_value=None, exc_tb=None):
try:
self.pidfile.close()
except IOError as err:
# ok if file was just closed elsewhere
if err.errno != 9:
raise
os.remove(self.path)
7 changes: 6 additions & 1 deletion bin/beaver
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import argparse
import logging
import sys
import time
import lockfile

import beaver.file_config
import beaver.beaver_config
import beaver.transport
import beaver.utils
import beaver.worker
import beaver.pidfile

from beaver import __version__ as full_version

Expand Down Expand Up @@ -53,6 +55,7 @@ parser = argparse.ArgumentParser(description='Beaver logfile shipper',
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-c', '--configfile', help='ini config file path', dest='config', default='/dev/null')
parser.add_argument('-D', '--daemon', help='daemonize in the background', dest='daemon', default=False, action='store_true')
parser.add_argument('-P', '--pid', help='path to pid file', default=None, dest='pidfile')
parser.add_argument('-d', '--debug', help='enable debug mode', dest='debug', default=False, action='store_true')
parser.add_argument('-f', '--files', help='space-separated filelist to watch, can include globs (*.log). Overrides --path argument', dest='files', default=None, nargs='+')
parser.add_argument('--format', help='format to use when sending to transport', default=None, dest='format', choices=['json', 'msgpack', 'string'])
Expand Down Expand Up @@ -119,7 +122,9 @@ def main(args):

if __name__ == "__main__":
if args.daemon:
with daemon.DaemonContext():
with daemon.DaemonContext(
pidfile=beaver.pidfile.PidFile(args.pidfile),
):
main(args = args)
else:
main(args = args)

0 comments on commit b260ca2

Please sign in to comment.