view runXena.py @ 34:a3fbe077a14c

replace wget with python method
author jingchunzhu <jingchunzhu@gmail.com>
date Thu, 23 Jul 2015 01:02:24 -0700
parents 7ceb967147c3
children
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, shlex
import sys
import time
import traceback
import xena_utils as xena

dirname = os.path.dirname(os.path.abspath(sys.argv[0]))

sys.path.insert(0, dirname + "/lockfile-0.10.2/")
sys.path.insert(0, dirname + "/python-daemon-2.0.5/")


#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 --no-gui --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 = xena.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 http://%s:%s\n" % (hostname, xenaPort))
        fp.write("\n")
        fp.write("You can add http://%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 http://%s:%s\n" % (hostname, xenaPort))
        fp.write("\n")
        fp.write("Use Xena Administration -> Check Status tool to review status.\n")
    else:
        fp.write("Xena VM already running on http://%s:%s\n" % (hostname, xenaPort))
        fp.write("\n")
        fp.write("You can add http://%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 http://%s:%s\n" % (hostname, xenaPort))
    else:
        fp.write("Xena VM is not currently running on %s\n" % (hostname)) 

elif sys.argv[1] == "version":
    # check the current xena status
    if xenaIsRunning:
        xenaVersionCmd = "java -jar %s --version" % (xena.jarPath())
        args =shlex.split(xenaVersionCmd)
        output, error = subprocess.Popen(args, stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
        fp.write("The current Xena server version is %s\n" % (output))
    else:
        fp.write("Xena Server is not currently running on %s, please start the server first, then you can check the server version.\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()