Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # =======
- # Imports
- # =======
- import sys, os
- import jtvStreamsUpdater
- import pprint
- import subprocess
- # =======
- # Globals
- # =======
- PIDPATH = '/var/run'
- PYPATH = sys.executable
- RUNNING = 1
- STARTED = 2
- ALREADY_RUNNING = 3
- NOT_RUNNING = 4
- KILLED = 5
- # ==========
- # Exceptions
- # ==========
- class AlreadyStartedError(Exception):
- def __init__(self, pid):
- self.pid = pid
- class NotRunningError(Exception):
- pass
- # ===============
- # Configure paths
- # ===============
- # Get the absolute path of this folder
- FILEROOT = os.path.abspath(os.path.dirname(__file__))
- # Set working directory to this
- os.chdir(FILEROOT)
- # ==========================
- # Process handling functions
- # ==========================
- def startProcess(name, path):
- """
- Starts a process in the background and writes a PID file
- returns integer: pid
- """
- # Check if the process is already running
- status, pid = processStatus(name)
- if status == RUNNING:
- raise AlreadyStartedError(pid)
- # Start process
- command = (path).split(' ')
- process = subprocess.Popen(command, stdout='/dev/null', stderr='/dev/null')
- # Write PID file
- pidfilename = os.path.join(PIDPATH, name + '.pid')
- pidfile = open(pidfilename, 'w')
- pidfile.write(str(process.pid))
- pidfile.close()
- return process.pid
- def stopProcess(name):
- """
- Stops a process started by startProcess
- returns integer: RESULT
- """
- # Get the status of the input process
- status, pid = processStatus(name)
- # If it's not running, return
- if status == NOT_RUNNING:
- return NOT_RUNNING
- # If it's running, kill it and remove the PID file
- os.system('kill %s > /dev/null 2> /dev/null' % pid)
- os.system('rm ' + os.path.join(PIDPATH, name + '.pid'))
- return KILLED
- def processStatus(name):
- """
- Gets the status of a process started by startProcess
- returns tuple: ([RUNNING | NOT_RUNNING], pid)
- """
- pidfilename = os.path.join(PIDPATH, name + '.pid')
- # Try to open the PID file. If successfull, the process is running
- try:
- pidfile = open(pidfilename, 'r')
- pid = pidfile.read()
- except IOError as e:
- return (NOT_RUNNING, None)
- return (RUNNING, pid)
- # ===================
- # jtvDaemon functions
- # ===================
- def startjtv():
- """
- Starts the jtvStreamsUpdater loop in a background process
- returns tuple: (RESULT, pid)
- """
- # Check if process is already started
- status, pid = processStatus('jtvStreamUpdater')
- if status == RUNNING:
- return (ALREADY_RUNNING, pid)
- # Fork here
- pid = os.fork()
- # Write and return the child pid
- if pid:
- # Write PID to pid file
- pidfilepath = os.path.join(PIDPATH, 'jtvStreamsUpdater.pid')
- pidfile = open(pidfilepath, 'w')
- pidfile.write(str(pid))
- pidfile.close()
- return (STARTED, pid)
- # The child process should start the update loop
- else:
- # Don't output anything
- sys.stdout = open('/dev/null', 'w')
- from honsapp.jtvStreamsUpdater import mainUpdateLoop
- mainUpdateLoop()
- def stopjtv():
- """
- Stops the jtvStreamsUpdater loop
- returns int: RESULT
- """
- # Try to kill the process
- return stopProcess('jtvStreamsUpdater')
- # ================
- # Script execution
- # ================
- if __name__ == '__main__':
- import argparse
- commands = ['startall', 'stopall',
- 'startjtv', 'stopjtv', 'jtvstatus']
- help = """commands:
- startall Starts all refreshing daemons
- stopall Stops them
- startjtv Starts the justin.tv streams refresher
- stopjtv Stops it
- jtvstatus Shows it's current status"""
- parser = argparse.ArgumentParser(epilog=help,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- # Add the main positional argument; command
- parser.add_argument('command', metavar='command', type=str,
- choices=commands, help='The command to give the script')
- # Get the parser arguments
- args = parser.parse_args()
- # Abide the input command
- if args.command == 'startall':
- startallDaemons()
- elif args.command == 'stopall':
- stopallDaemons()
- elif args.command == 'startjtv':
- # Try to start the daemon
- result, pid = startjtv()
- if result == STARTED:
- print 'jtvStreamsUpdater started at ' + str(pid)
- elif result == ALREADY_RUNNING:
- print 'jtvStreamsUpdater already running at ' + str(pid)
- elif args.command == 'stopjtv':
- # Try to stop the daemon
- result = stopjtv()
- if result == KILLED:
- print 'jtvStreamsUpdater has been stopped'
- elif result == NOT_RUNNING:
- print 'jtvStreamsUpdater isn\'t running'
- elif args.command == 'jtvstatus':
- # Fetch the daemon status
- result, pid = processStatus('jtvStreamsUpdater')
- if result == RUNNING:
- print 'jtvStreamsUpdater is running at %s' % pid
- elif result == NOT_RUNNING:
- print 'jtvStreamsUpdater isn\'t running'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement