Exemple #1
0
 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.")
Exemple #2
0
    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
Exemple #3
0
    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
Exemple #4
0
 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())
Exemple #5
0
 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())
Exemple #6
0
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
Exemple #7
0
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
Exemple #8
0
 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.")
Exemple #9
0
 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()
Exemple #10
0
 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()
Exemple #11
0
    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
Exemple #12
0
    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
Exemple #13
0
    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.')
Exemple #14
0
    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.')
Exemple #15
0
 def run(self):
     ulgmodel.log('ULG cron run.')
     self.clearLog()
     self.rescanRouters()
     self.clearSessions()
     ulgmodel.log('ULG cron finished.')
Exemple #16
0
    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'):
Exemple #17
0
 def run(self):
     ulgmodel.log('ULG cron run.')
     self.clearLog()
     self.rescanRouters()
     self.clearSessions()
     ulgmodel.log('ULG cron finished.')
Exemple #18
0
# 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'):
Exemple #19
0
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