root/trunk/ippToPsps/jython/ipptopsps.py @ 33790

Revision 33790, 5.6 KB (checked in by rhenders, 6 years ago)

now printing correct config to log if program run with 'edit' argument

Line 
1#!/usr/bin/env jython
2
3import signal
4import sys
5import os
6import time
7import logging
8import socket
9
10from config import Config
11from pslogger import PSLogger
12from ipptopspsdb import IppToPspsDb
13
14'''
15Abstract base class for all ippToPsps programs
16Handles command-line args, setting up of Config and logger objects, clean exiting etc
17'''
18class IppToPsps(object):
19
20    '''
21    Constructor
22    '''
23    def __init__(self, argv, logToStdout=1, logToFile=0):
24
25        # are the arsg ok? all programs require a config name
26        if len(sys.argv) < 2: 
27            self.printUsage()
28            self.exitProgram("Wrong args")
29           
30        # some class constants
31        self.PROGNAME = sys.argv[0]
32        CONFIGNAME = sys.argv[1]
33        self.HOST = socket.gethostname()
34        self.PID = os.getpid()
35        self.PAUSEPERIOD = 60
36        self.HOURS = None
37        self.MINUTES = None
38        self.SECONDS = None
39
40        self.createNewConfig = False
41        self.rotateConfigs = False
42        # a new config?
43        if CONFIGNAME == "edit": self.createNewConfig = True
44        # should we rotate configs for this program?
45        elif CONFIGNAME == "all": self.rotateConfigs = True
46
47        # set up config object
48        self.config = Config(self.PROGNAME, CONFIGNAME)
49        self.logger = self.config.getLogger(self.HOST, self.PID, logToStdout, logToFile)
50
51        # create connection to databases database
52        try:
53            self.ippToPspsDb = IppToPspsDb(self.logger, self.config)
54        except:
55            self.exitProgram("Could not connect to ipptopsps Db")
56            raise
57
58        self.checkClientStatus()
59
60        # catch Ctrl-C signal
61        signal.signal(signal.SIGINT, self.signal_handler)
62
63        # title for log
64        self.logger.infoSeparator()
65        self.logger.infoTitle("ippToPsps '" + self.PROGNAME + "' started")
66        self.logger.infoPair("Host", self.HOST)
67        self.logger.infoPair("PID", "%d" % self.PID)
68        self.logger.infoPair("Config", self.config.name)
69
70    '''
71    Parses a poll-time argument string and stored as class variables
72    '''
73    def parsePollTimeArg(self, hours):
74
75        try:
76            self.HOURS = float(hours)
77            self.MINUTES = self.HOURS * 60.0
78            self.SECONDS = self.MINUTES * 60.0
79        except:
80            pass
81
82    '''
83    Waits for user defined poll time
84    '''
85    def waitForPollTime(self):
86
87        # if not POLL time set, then return False
88        if not self.SECONDS: return False
89
90        if self.HOURS < 1.0:
91            str = "%.1f minutes" % self.MINUTES
92        else:
93            str = "%.1f hours" % self.HOURS
94
95        self.logger.infoPair("Waiting for", str)
96        time.sleep(self.SECONDS)
97
98        return True
99
100    '''
101    Prints usage to stdout
102    '''
103    def printUsage(self, extra=""):
104
105        # write message to log or stdout if no logger set up
106        msg = sys.argv[0] + " <configName|all|edit> " + extra
107        try:
108            self.logger.errorPair("Usage:", msg)
109        except: 
110            print "*** Usage: " + msg
111
112    '''
113    Refreshes the config then recreates objects with new settings
114    '''
115    def refreshConfig(self):
116
117        # new config?
118        if self.createNewConfig: 
119            self.ippToPspsDb.editConfig()
120            self.ippToPspsDb.setConfigForThisClient(self.config.name, self.HOST, self.PID)
121            self.createNewConfig = False
122
123        # if we are rotating configs, then look for next active one in list
124        if self.rotateConfigs:
125            self.ippToPspsDb.getConfigForThisClient(self.HOST, self.PID)
126            configs = self.ippToPspsDb.getActiveConfigList()
127             
128            i = 1
129            for config in configs:
130               if config == self.config.name: break
131               i += 1
132
133            if i >= len(configs): newConfig = configs[0]
134            else: newConfig = configs[i]
135
136            self.ippToPspsDb.setConfigForThisClient(newConfig, self.HOST, self.PID)
137
138        return self.ippToPspsDb.readConfig(self.HOST, self.PID)
139
140    '''
141    All implementing subclasses (programs) should call this method once in a while to see if it should be paused or killed, otherwise this updates the clients table with current time and reloads the config data
142    '''
143    def checkClientStatus(self):
144
145        self.ippToPspsDb.updateClient(self.PROGNAME, self.HOST, self.PID)
146
147        if self.ippToPspsDb.isKilled(self.HOST, self.PID): 
148            self.exitProgram("killed via Db")
149       
150        # this loop pauses the process if we have no config or we have set it to pause
151        firstTimeIn = True
152        while not self.refreshConfig() or self.ippToPspsDb.isPaused(self.HOST, self.PID):
153
154            self.ippToPspsDb.updateClient(self.PROGNAME, self.HOST, self.PID)
155            if self.ippToPspsDb.isKilled(self.HOST, self.PID): 
156                self.exitProgram("killed while paused")
157            if firstTimeIn: self.logger.infoPair("Paused. Will check again every", "%d secs" % self.PAUSEPERIOD)
158            firstTimeIn = False
159            time.sleep(self.PAUSEPERIOD)
160
161
162    '''
163    Handler for Ctrl-C signal
164    '''
165    def signal_handler(self, signal, frame):
166
167       self.exitProgram("Ctrl-C")
168
169
170    '''
171    Exits the program cleanly, removes info from ipptopsps database
172    '''
173    def exitProgram(self, exitReason="quit"):
174
175        # write message to log or stdout if no logger set up
176        try:
177            self.logger.infoPair(self.PROGNAME + " exited", exitReason)
178        except: 
179            print "*** Program exited: " + exitReason
180
181        # remove from database if possible
182        try:
183            self.ippToPspsDb.removeClient(self.HOST, self.PID)
184        except:
185            pass
186
187        sys.exit(0)
188   
189
Note: See TracBrowser for help on using the browser.