Skip to content

Commit

Permalink
PID file support (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
kjagiello committed Apr 20, 2016
1 parent ca6460f commit 36d6656
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
36 changes: 33 additions & 3 deletions thunderpush/runner.py
Expand Up @@ -5,14 +5,38 @@

from sockjs.tornado import SockJSRouter

import os
import sys
import fcntl
import tornado.ioloop
import argparse
import logging

logger = logging.getLogger()


class PIDFile(object):
def __init__(self, path):
self.path = path

def __enter__(self):
self.pidfile = open(self.path, 'w+')
try:
fcntl.flock(self.pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
self.pidfile.seek(0)
self.pidfile.truncate()
self.pidfile.write(str(os.getpid()))
self.pidfile.flush()
except IOError:
# PID file exists and is held by another process
msg = 'Process already running (PID file: {}).'.format(self.path)
raise SystemExit(msg)

def __exit__(self, exc_type, exc_val, exc_tb):
self.pidfile.close()
os.remove(self.path)


def run_app():
# configure logging level
if settings.VERBOSE:
Expand Down Expand Up @@ -43,10 +67,10 @@ def run_app():
def update_settings(args):
args = vars(args)

for optname in ["PORT", "HOST", "VERBOSE", "DEBUG"]:
for optname in ["PORT", "HOST", "VERBOSE", "DEBUG", "PIDPATH"]:
value = args.get(optname, None)

if not value is None:
if value is not None:
setattr(settings, optname, value)

settings.APIKEY = args['clientkey']
Expand Down Expand Up @@ -76,6 +100,11 @@ def parse_args(args):
help='debug mode (useful for development)',
action="store_true", dest="DEBUG")

parser.add_argument('--pid-path',
default=settings.PIDPATH,
help='path to the PID file',
action='store', type=str, dest='PIDPATH')

parser.add_argument('-V', '--version',
action='version', version=__version__)

Expand All @@ -91,7 +120,8 @@ def parse_args(args):
def main():
args = parse_args(sys.argv[1:])
update_settings(args)
run_app()
with PIDFile(settings.PIDPATH):
run_app()

if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions thunderpush/settings.py
Expand Up @@ -23,3 +23,6 @@

# This sets the logging level to DEBUG.
VERBOSE = False

# Path to the PID file
PIDPATH = '/tmp/thunderpush.pid'

0 comments on commit 36d6656

Please sign in to comment.