def clearLog(self): try: if(os.stat(defaults.log_file).st_size > LOGFILE_LIMIT): os.unlink(defaults.log_file) except OSError as e: ulgmodel.log('Error while checking/removing logfile '+defaults.log_file+' '+str(e)) ulgmodel.log("Logfile removed due to excessive size. Please set logrotate to keep the file size below "+str(LOGFILE_LIMIT)+" bytes.")
def increaseUsage(self): u = 0 try: # Open files if(os.path.isfile(defaults.usage_counter_file)): lf = open(defaults.usage_counter_file,'r+') u = int(lf.readline()) else: lf = open(defaults.usage_counter_file,'w') # Acquire lock fcntl.lockf(lf, fcntl.LOCK_EX) except (IOError,ValueError) as e: ulgmodel.log("Locking mechanism failure: "+str(e)) return False try: if(u < defaults.usage_limit): # write a new value and release lock lf.seek(0) lf.write(str(u+1)+'\n') lf.close() return True else: # release lock lf.close() return False except IOError as e: ulgmodel.log("Locking mechanism update failure: "+str(e)) return False
def save(self): try: fn = getSessionFileName(self.getSessionId()) f = open(fn,'wb') pickle.dump(self, f) f.close() except: ulgmodel.log("Saving session failed: " + traceback.format_exc())
def testULGLog(testmessage="Test message no. 1."): try: ulgmodel.log(testmessage) print "OK: Logging test. Check logfile for message: "+testmessage return True except Exception as e: print "FAIL: Logging test." print traceback.format_exc() return False
def clearLog(self): try: if (os.stat(defaults.log_file).st_size > LOGFILE_LIMIT): os.unlink(defaults.log_file) except OSError as e: ulgmodel.log('Error while checking/removing logfile ' + defaults.log_file + ' ' + str(e)) ulgmodel.log( "Logfile removed due to excessive size. Please set logrotate to keep the file size below " + str(LOGFILE_LIMIT) + " bytes.")
def commandThreadBody(session,decreaseUsageMethod): ulgmodel.debug("Running command: "+session.getCommand().getName()) try: session.getRouter().runAsyncCommand(session.getCommand(),session.getParameters(),FakeSessionFile(session)) session.getCommand().finishHook(session) except Exception as e: ulgmodel.log("ERROR: Exception occured while running a command:" + traceback.format_exc()) session.setResult("ERROR in commandThreadBody:\n"+traceback.format_exc()) finally: ulgmodel.debug("Command finished: "+session.getCommand().getName()) session.setFinished() decreaseUsageMethod()
def decreaseUsage(self): u = 1 try: # Open files if(os.path.isfile(defaults.usage_counter_file)): lf = open(defaults.usage_counter_file,'r+') u = int(lf.readline()) else: lf = open(defaults.usage_counter_file,'w') # Acquire lock fcntl.lockf(lf, fcntl.LOCK_EX) except IOError,ValueError: ulgmodel.log("Locking mechanism failure: "+str(e)) return False
def clearSessions(self): sre = re.compile(SESSION_FILE_REGEX) for file in os.listdir(defaults.session_dir): if sre.match(file): fp = defaults.session_dir+'/'+file now = datetime.datetime.now() if(datetime.datetime.fromtimestamp(os.path.getmtime(fp)) < now+datetime.timedelta(hours=-1)): ulgmodel.log('Removing file '+fp) try: os.unlink(fp) except OSError as e: ulgmodel.log('Error while removing file '+fp+' '+str(e)) else: ulgmodel.log('Not removing file '+fp+' because it is not at least 1 hour old.')
def clearSessions(self): sre = re.compile(SESSION_FILE_REGEX) for file in os.listdir(defaults.session_dir): if sre.match(file): fp = defaults.session_dir + '/' + file now = datetime.datetime.now() if (datetime.datetime.fromtimestamp(os.path.getmtime(fp)) < now + datetime.timedelta(hours=-1)): ulgmodel.log('Removing file ' + fp) try: os.unlink(fp) except OSError as e: ulgmodel.log('Error while removing file ' + fp + ' ' + str(e)) else: ulgmodel.log('Not removing file ' + fp + ' because it is not at least 1 hour old.')
def run(self): ulgmodel.log('ULG cron run.') self.clearLog() self.rescanRouters() self.clearSessions() ulgmodel.log('ULG cron finished.')
def debug(self,**params): self.print_text_html() print self.renderULGDebug(**params) # main if __name__=="__main__": try: form = cgi.FieldStorage() handler = ULGCgi() action = form.getvalue('action',None) params = dict([(k,form.getvalue(k)) for k in form.keys() if k != 'action']) if("REMOTE_ADDR" in os.environ): ulgmodel.log("Request from "+os.environ["REMOTE_ADDR"]+" with action="+str(action)+" params="+str(params)+'.') else: ulgmodel.log("Request from console with action="+str(action)+" params="+str(params)+'.') if(action): if(action == 'index'): handler.index(**params) elif(action == 'runcommand'): handler.runcommand(**params) elif(action == 'display'): handler.display(**params) elif(action == 'getfile'): handler.getfile(**params) elif(action == 'whois'): handler.whois(**params) elif(action == 'error'):
# main if __name__=="__main__": try: form = cgi.FieldStorage() user=None if 'REMOTE_USER' in os.environ: user=os.environ['REMOTE_USER'] handler = ULGCgi(user) action = form.getvalue('action',None) params = dict([(k,form.getvalue(k)) for k in form.keys() if k != 'action']) if("REMOTE_ADDR" in os.environ): ulgmodel.log("Request from "+os.environ["REMOTE_ADDR"]+" with action="+str(action)+" params="+str(params)+'.') else: ulgmodel.log("Request from console with action="+str(action)+" params="+str(params)+'.') if(action): if(action == 'index'): handler.index(**params) elif(action == 'runcommand'): handler.runcommand(**params) elif(action == 'display'): handler.display(**params) elif(action == 'getfile'): handler.getfile(**params) elif(action == 'whois'): handler.whois(**params) elif(action == 'error'):
class ULGCgi: def __init__(self,user=None): self.loader=TemplateLoader( os.path.join(os.path.dirname(__file__), defaults.template_dir), auto_reload=True ) self.decorator_helper = DecoratorHelper() self.user = user def print_text_html(self): print "Content-Type: text/html\n" def increaseUsage(self): u = 0 try: # Open files if(os.path.isfile(defaults.usage_counter_file)): lf = open(defaults.usage_counter_file,'r+') u = int(lf.readline()) else: lf = open(defaults.usage_counter_file,'w') # Acquire lock fcntl.lockf(lf, fcntl.LOCK_EX) except (IOError,ValueError) as e: ulgmodel.log("Locking mechanism failure: "+str(e)) return False try: if(u < defaults.usage_limit): # write a new value and release lock lf.seek(0) lf.write(str(u+1)+'\n') lf.close() return True else: # release lock lf.close() return False except IOError as e: ulgmodel.log("Locking mechanism update failure: "+str(e)) return False def decreaseUsage(self): u = 1 try: # Open files if(os.path.isfile(defaults.usage_counter_file)): lf = open(defaults.usage_counter_file,'r+') u = int(lf.readline()) else: lf = open(defaults.usage_counter_file,'w') # Acquire lock fcntl.lockf(lf, fcntl.LOCK_EX) except IOError,ValueError: ulgmodel.log("Locking mechanism failure: "+str(e)) return False try: if(u>0): # write a new value and release lock lf.seek(0) lf.write(str(u-1)+'\n') lf.close() return else: # release lock lf.close() return except IOError as e: ulgmodel.log("Locking mechanism update failure: "+str(e)) pass