Serverkontroll för Sage math

Här diskuteras programmering och utveckling
Jam007
Inlägg: 52
Blev medlem: 27 aug 2010, 16:33
OS: Ubuntu
Utgåva: 24.04 Noble Numbat LTS

Serverkontroll för Sage math

Inlägg av Jam007 »

Gjorde en severkontroll för Sage math som kanske kan vara intressant för andra. Den går ju enkelt att modifiera för andra serverprogram också.
2 delar i Python.

Appindikator för aktivitetsfältet där man startar och stoppar servern:

Kod: Markera allt

'''
Created on 6 okt 2012

@author: andersm
'''
import gtk
import appindicator
import sage_server
import os
import time

buf = ["Starta server", "Stoppa server", "Avsluta"]
running_icon = os.getenv("HOME") + "/.sage/sagemath-running.png"
stopped_icon = os.getenv("HOME") + "/.sage/sagemath-stopped.png"
        
class SageControll(appindicator.Indicator):

    def menuitem_response(self, w, itmtxt):
        if itmtxt == buf[2] :
            print "Avslutar"
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                       gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO,
                                       "Avsluta?")
            dialog.set_title(":(")
    
            response = dialog.run()
            dialog.destroy()
            if response == gtk.RESPONSE_YES:
                gtk.main_quit()
        elif itmtxt == buf[1] :
            print "Stoppar server"
            sage_server.stop_server()
            self.set_status(appindicator.STATUS_ACTIVE)
        elif itmtxt == buf[0] :
            print "Startar server"
            sage_server.start_server()
	    rng = False
            while not rng :
                self.set_status(appindicator.STATUS_ACTIVE)
                time.sleep(0.5)
                rng = sage_server.get_server_status()
                self.set_status(appindicator.STATUS_ATTENTION)
                time.sleep(0.5)
        else :
            print "confused"
            
            
    def __init__(self):
        appindicator.Indicator.__init__(self, "sage control",
                              stopped_icon,
                              appindicator.CATEGORY_APPLICATION_STATUS)
        self.set_attention_icon(running_icon)
        self.set_status (appindicator.STATUS_ACTIVE)
                    # create a menu
        menu = gtk.Menu()
    
        # create items
        for i in range(len(buf)) :
            menu_items = gtk.MenuItem(buf[i])
            menu.append(menu_items)
            menu_items.connect("activate", self.menuitem_response, buf[i])
            menu_items.show()
    
        self.set_menu(menu)


if __name__ == "__main__":
    ind = SageControll()
    gtk.main()
Samt en modifiering av ett kontrollskript från Sages samlingar:

Kod: Markera allt

"""
Sage server starting and stopping script

AUTHORS:

    - Kwankyu Lee (2010-10-17): initial version

    """

    #*****************************************************************************
    #       Copyright (C) 2010 Kwankyu Lee <ekwankyu@gmail.com>
    #
    #  Distributed under the terms of the GNU General Public License (GPL)
    #                  http://www.gnu.org/licenses/
    #*****************************************************************************
#Modifierat av Anders Martinsson 2012

import os,sys
import pexpect
import time              
import subprocess,signal

from time import strftime


sage_server_root = os.environ['HOME'] + '/.sage'
conf_file_name = sage_server_root + '/sage_server.conf'
log_file_name = sage_server_root + '/sage_server.log'

UPGRADE_CONFIRM = r'Do you want to continue [y/N]?'

MAX_WAITING_TIME_BEFORE_KILLING = 30 # in seconds

def print_help():
    """
    Prints a short usage description.
    """

    print "Usage: sage-server [command]"
    print "Commands: start, stop, restart, upgrade, status"
    print ""
    print "The server configurations should be listed in the file `sage-server.conf'"
    print "in `.sage' directory under your home directory."

def get_config():
    arg=[]
    with open(conf_file_name) as f:
        for line in f: arg.append(line.strip())
    while arg.count('') > 0: arg.remove('')
    return arg

    
def get_server_status():
    """
    Returns the status of the Sage server.
    """

    try:
        # if sage notebook server is running, "twist.pid" was created in the notebook directory.
        pid_file_name = sage_server_root + '/sage_notebook.sagenb/twistd.pid'
        pid_file = open(pid_file_name, 'r')
        pid = int(pid_file.read()) 
        pid_file.close()
    except IOError:                        
        return False
    except ValueError: # remove the invalid pid file
        os.remove(pid_file_name)
        return False

    # check validity of the pid by checking the pid belongs 
    # to the current user's sage twistd server process.
    c1 = subprocess.Popen(['ps','-p',str(pid),'-o','user='],stdout=subprocess.PIPE)
    c2 = subprocess.Popen(['ps','-p',str(pid),'-o','cmd='],stdout=subprocess.PIPE)
    if os.environ['USER'] in c1.communicate()[0] and 'twistd' in c2.communicate()[0]:
        return True
    else:
        return False

def start_server():
    """
    Starts the Sage server.
    """
    if get_server_status():
        print "The Sage server is already running."
        return

    try:
        print "Starting the Sage server..."
	proc = ['sage', '-notebook']
	proc.extend(get_config()) 
        subprocess.Popen(proc)
    except IOError:
        print "Failed to start the Sage server. Check the configuration file."
        sys.exit(os.EX_CONFIG)

def stop_server():                               
    """
    Stops the Sage server.
    """
    if not get_server_status():
        print "There is no Sage server running." 
        return

    pid_file_name = sage_server_root + '/sage_notebook.sagenb/twistd.pid'
    pid_file = open(pid_file_name, 'r')
    pid = int(pid_file.readline()) 
    pid_file.close()

    print "Stopping the Sage server..."
    os.kill(pid,signal.SIGTERM)
    elapsed_time = 0
    while os.path.isfile(pid_file) and elapsed_time < MAX_WAITING_TIME_BEFORE_KILLING:
        time.sleep(.1)
        elapsed_time += .1

    if os.path.isfile(pid_file): # assume the server process is malbehaving.
        print "Killing the errorneous Sage server process..." 
        os.kill(pid,signal.SIGKILL)
        os.remove(pid_file)

def upgrade_sage():
    """
    Upgrades the Sage skipping the upgrade confirmation.
    """
    print "Upgrading Sage..."
    child = pexpect.spawn(sage_root + '/sage -upgrade')
    child.logfile = sys.stdout

    while True:
        i = child.expect([pexpect.EOF,UPGRADE_CONFIRM,pexpect.TIMEOUT],timeout=1)
        if i == 0:
            print "Upgrading finished."
            return 
        elif i == 1: # confirm to upgrade
            child.sendline('y')
        elif i == 2: # upgrading is going on
            continue 
        else:
            print "Something wrong..."
            sys.exit(os.EX_SOFTWARE)

def log(log_file,message):
    """
    A function for logging.
    """
    current_time = strftime("%Y-%m-%d %H:%M:%S")
    log_file.write(current_time + ': ' + message + '\n')

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if os.environ.has_key('SAGE_ROOT'):
            sage_root = os.environ['SAGE_ROOT']
        else:
            print "The SAGE_ROOT environment variable is undefined."
            sys.exit(os.EX_CONFIG)

        try:
            log_file = open(log_file_name, 'a')
        except IOError:         
            print "Failed to open the log file."
            sys.exit(os.EX_IOERR)

        cmd = sys.argv[1]
        if cmd == 'start':
            start_server()
            log(file,'sage server started')
        elif cmd == 'stop':
            stop_server()
            log(file,'sage server stopped')
        elif cmd == 'restart':
            stop_server()
            start_server()
            log(file,'The sage server restarted')
        elif cmd == 'upgrade':
            running = get_server_status()
            if running:
                stop_server()
            log(file,'Upgrading the sage started')
            upgrade_sage()
            log(file,'Upgrading the sage finished')
            if running:
                start_server()
        elif cmd == 'status':
            status = get_server_status()
            if status:
                print "The Sage server is running."
            else:
                print "There is no Sage server running."
        else:
            print_help()
        file.close()
    else:
        print_help()
The worthwhile problems are the ones you can really solve or help solve, the ones you can really contribute something to. ... No problem is too small or too trivial if we can really do something about it. / R Feynman

Återgå till "Programmering och webbdesign"