view runXena.py @ 23:7c49d9f8687a

Deleted selected files, clearing up a merge problem.
author melissacline
date Tue, 02 Jun 2015 19:16:42 -0400
parents 14aaed60e07b
children 77f5d8cbac77
line wrap: on
line source

#!/usr/bin/env python
# To kick off the script, run the following from the python directory:
#   PYTHONPATH=`pwd` python testdaemon.py start

#standard python libs
import logging
import os
import signal
import subprocess
import sys
import time
import traceback
import xena_utils as xena

#third party libs
from daemon import runner
from lockfile import LockTimeout


class App():
    
    def __init__(self):
        xenaBaseDir = xena.baseDir()
        if not os.path.exists(xenaBaseDir):
            os.mkdir(xenaBaseDir)
        self.pidfile_path =  xenaBaseDir + "/xena-daemon.pid"
        
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/null'
        self.stderr_path = '/dev/null'
        self.pidfile_timeout = 5
            
    def run(self):
        while True:
            #Main code goes here ...
            #Note that logger level needs to be set to logging.DEBUG before this shows up in the logs
            xenaCmdline = "java -jar %s -r %s/files -d %s/db -t %s/tmp --logfile %s/xena.log -p %s -H 0.0.0.0" 
            xenaBaseDir = xena.baseDir()
            xenaCmd = xenaCmdline % (xena.jarPath(), xenaBaseDir, 
                                     xenaBaseDir, xenaBaseDir, 
                                     xenaBaseDir, xena.port())
            logger.debug("Invoking Xena VM with command %s" % (xenaCmd))
            xenaVm = subprocess.call(xenaCmd, shell=True)
            logger.info("Starting Xena VM")
            #logger.warn("Warning message")
            #logger.error("Error message")



def processListeningOnPort(portID):
    cmd = "lsof -t -i :%s -sTCP:LISTEN" % portID
    pid = subprocess.check_output(cmd, shell=True).rstrip()
    return(int(pid))


fp = open(sys.argv[2], "w")
    
app = App()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler(xena.baseDir() + "/xena-daemon.log")
handler.setFormatter(formatter)
logger.addHandler(handler)

hostname = subprocess.check_output("hostname -f", shell=True).rstrip()

#
# Check if there has been a Xena running on this system, and  
# what its port number is or was.
#
xenaPort = xena.port()
if xenaPort == None:
    # In this case, no Xena has been running on this sytem.
    xenaIsRunning = False
else:
    xenaIsRunning = xena.isRunning(xenaPort)
#rint "xena running", xenaIsRunning, "port", xenaPort


if sys.argv[1] == "status":
    #
    # When checking status, if Xena is running, then report that it's running
    # with hostname and port.  If it's not running, then report as such.
    #
    if xenaIsRunning:
        fp.write("Xena VM currently running on %s:%s\n" % (hostname, xenaPort))
        fp.write("You can add %s:%s to Xena Data Hub\n" % (hostname, xenaPort))
    else:
        fp.write("Xena VM is not currently running on %s\n" % (hostname))

elif sys.argv[1] == "start":
    #
    # When a start command came in, allocate a new port and prepare to start
    # xena if it's not already running.  If it is already running, then 
    # report as such.  In either case, close the output file before this
    # process goes into daemon mode.
    #
    if not xenaIsRunning:
        xenaPort = xena.port(testIfAvailable=True, findNewPort=True)
        fp.write("Starting Xena VM on %s:%s\n" % (hostname, xenaPort))
        fp.write("You can add %s:%s to Xena Data Hub\n" % (hostname, xenaPort))
    else:
        fp.write("Xena VM already running on %s:%s\n" % (hostname, xenaPort))
        fp.write("You can add %s:%s to Xena Data Hub\n" % (hostname, xenaPort))
    fp.close()

elif sys.argv[1] == "stop":
    #
    # When stopping Xena, if it's currently running, report that Xena
    # is being terminated and clean up the port.  If it's not running,
    # report as such.  
    #
    if xenaIsRunning:
        fp.write("Terminating Xena VM on %s:%s\n" % (hostname, xenaPort))
    else:
        fp.write("Xena VM is not currently running on %s\n" % (hostname)) 

else:
    fp.write(("Error: Unexpected command %s" % sys.argv[1]))


#
# Here is where the starting and stopping of the Xena daemon takes place.
#
if sys.argv[1] == "start" or (sys.argv[1] == "stop" and xenaIsRunning):
    daemon_runner = runner.DaemonRunner(app)
    # This ensures that the logger file handle does not get closed during daemonization
    daemon_runner.daemon_context.files_preserve=[handler.stream]
    try:
        daemon_runner.do_action()
    except LockTimeout:
        # Xena is already running.  No need to do anything special, but this
        # should be separated from the other exceptions.
        pass
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        allLines = ''.join('!! ' + line for line in lines)
        fp.write("Unsuccessful: error %s\n" % allLines)
    if sys.argv[1] == "stop":
        #
        # If the Xena stop command has been issued, then kill the Xena 
        # process.
        #
        xenaPid = processListeningOnPort(xenaPort)
        logger.debug("Attempting to kill process with PID %d" % xenaPid)
        os.kill(xenaPid, signal.SIGTERM)
if sys.argv[1] != "start":
    fp.close()