Commit 6cfdc78a authored by Tomas Hlavacek's avatar Tomas Hlavacek

Rework parameter passing to decorator methods.

Rework parameter passing from
(result,router=0,decorator_helper,resrange,...) to more compresehnsive
version (session,decorator_helper). The session contains or should
contain all the parameters needed but there is a certain indirection
because session is being defined later in ulg.py. The rationale is that
even thouhg ulg.py can no be imported into files containing decorators
it is stable part of the ULG and therefore it might be used for building
decorators based on classes defined there (even though the classes are
not directly accessible, which can be overcomed by passing instances or
using decorator_helper to do needed class instantiation.

Modules for BIRD as well as Cisco has been changed to reflect this
changes.
parent 53bc555d
......@@ -24,14 +24,14 @@ from genshi.template import TemplateLoader
from genshi.core import Markup
import cgi
import cgitb; cgitb.enable()
import random
import time
import md5
import pickle
import re
import fcntl
import urllib
import traceback
import urllib
import md5
import time
import random
import config
import defaults
......@@ -41,19 +41,30 @@ import ulgmodel
### CGI output handler
class Session(object):
def __init__(self,sessionid=None,routerid=None,commandid=None,parameters=[],result=None,finished=False,error=None,resrange=None):
if(sessionid == None):
self.sessionid = self.__genSessionId__()
def __init__(self,sessionid=None,routerid=None,commandid=None,parameters=[],result=None,finished=False,error=None,resrange=None,copy=None):
if(copy):
self.sessionid=copy.sessionid
self.routerid=copy.routerid
self.commandid=copy.commandid
self.parameters=copy.parameters
self.error=copy.error
self.finished=copy.finished
self.range=copy.range
self.resultlen=copy.resultlen
else:
self.sessionid=sessionid
if(sessionid == None):
self.sessionid = self.__genSessionId__()
else:
self.sessionid=sessionid
self.routerid=routerid
self.commandid=commandid
self.parameters=parameters
self.error=error
self.finished=finished
self.range=resrange
self.resultlen=0
self.routerid=routerid
self.commandid=commandid
self.parameters=parameters
self.error=error
self.finished=finished
self.range=resrange
self.resultlen=0
self.save()
......@@ -160,14 +171,14 @@ class Session(object):
except:
return None
def getDecoratedResult(self,decorator_helper,resrange=0):
def getDecoratedResult(self,decorator_helper,resrange=0,finished=False):
if(self.getError()):
# TODO
return decorator_helper.pre(self.getResult())
else:
result = self.getResult()
if(result):
dr = self.getCommand().decorateResult(result,self.getRouter(),decorator_helper,resrange)
dr = self.getCommand().decorateResult(self,decorator_helper)
self.resultlines = dr[1]
return dr[0]
else:
......@@ -221,6 +232,7 @@ class Session(object):
def getMaxRange(self):
return self.resultlines
class DecoratorHelper:
def __init__(self):
pass
......@@ -272,6 +284,10 @@ class DecoratorHelper:
def ahref(self,url,text):
return ('<a href=%s>%s</a>' % (str(url),str(text)))
def copy_session(self,session):
return Session(copy=session)
class ULGCgi:
def __init__(self):
self.loader=TemplateLoader(
......@@ -487,7 +503,7 @@ class ULGCgi:
session.setRange(int(resrange))
result_text = session.getDecoratedResult(self.decorator_helper,session.getRange())
result_text = session.getDecoratedResult(self.decorator_helper,session.getRange(),session.isFinished())
if(session.isFinished()):
refresh=None
......@@ -548,6 +564,18 @@ class ULGCgi:
getFormURL=self.decorator_helper.getRuncommandURL()
).render('html', doctype='html')
def getULGSpecialContent(self,sessionid,**params):
if(sessionid==None):
return self.HTTPRedirect(self.decorator_helper.getErrorURL())
session = Session.load(sessionid)
if(session == None):
return self.HTTPRedirect(self.decorator_helper.getErrorURL())
return session.getCommand().getSpecialContent(session,**params)
def index(self, **params):
if('sessionid' in params.keys()):
print self.renderULGIndex(sessionid=params['sessionid'])
......@@ -560,6 +588,9 @@ class ULGCgi:
def display(self,sessionid=None,**params):
print self.renderULGResult(sessionid,**params)
def getfile(self,sessionid=None,**params):
print self.getULGSpecialContent(sessionid,**params)
def error(self,sessionid=None,**params):
print self.renderULGError(sessionid,**params)
......@@ -585,6 +616,8 @@ if __name__=="__main__":
handler.runcommand(**params)
elif(action == 'display'):
handler.display(**params)
elif(action == 'getfile'):
handler.getfile(**params)
elif(action == 'error'):
handler.error(**params)
elif(action == 'debug'):
......
......@@ -132,19 +132,22 @@ class BirdShowProtocolsCommand(ulgmodel.TextCommand):
return tl
def decorateResult(self,result,router=None,decorator_helper=None,resrange=0):
if((not router) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % result
def decorateResult(self,session,decorator_helper=None):
if(not session):
raise Exception("Can not decorate result without valid session.")
if((not session.getRouter()) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % session.getResult()
else:
pr = parseBirdShowProtocols(result,resrange)
pr = parseBirdShowProtocols(session.getResult(),session.getRange())
table_header = pr[0]
table = []
for tl in pr[1][resrange:resrange+defaults.range_step]:
for tl in pr[1][session.getRange():session.getRange()+defaults.range_step]:
# skip when there is a filter and it does not match the protocol type
if(self.fltr) and (not re.match(self.fltr,tl[1])):
continue
table.append(self._decorateTableLine(tl,router,decorator_helper))
table.append(self._decorateTableLine(tl,session.getRouter(),decorator_helper))
return (ulgmodel.TableDecorator(table,table_header).decorate(),pr[2])
......@@ -210,9 +213,12 @@ class BirdShowRouteCommand(ulgmodel.TextCommand):
return result
def decorateResult(self,result,router=None,decorator_helper=None,resrange=0):
if((not router) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % result
def decorateResult(self,session,decorator_helper=None):
if(not session):
raise Exception("Can not decorate result without valid session.")
if((not session.getRouter()) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % session.getResult()
table=[]
table_header=['Prefix',
......@@ -223,10 +229,10 @@ class BirdShowRouteCommand(ulgmodel.TextCommand):
'Metric',
'Info',]
lines = str.splitlines(result)
lines = str.splitlines(session.getResult())
result_len = len(lines)
lines = lines[resrange:resrange+defaults.range_step]
table = self._genTable(lines,decorator_helper,router)
lines = lines[session.getRange():session.getRange()+defaults.range_step]
table = self._genTable(lines,decorator_helper,session.getRouter())
return (ulgmodel.TableDecorator(table,table_header).decorate(),result_len)
......
......@@ -272,11 +272,14 @@ class CiscoCommandBgpIPv46Sum(ulgmodel.TextCommand):
else:
raise Exception("Can not parse line: "+line)
def decorateResult(self,result,router=None,decorator_helper=None,resrange=0):
if((not router) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % result
def decorateResult(self,session,decorator_helper=None):
if(not session):
raise Exception('Can not decorate result without valid session.')
if((not session.getRouter()) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % session.getResult()
lines = str.splitlines(result)
lines = str.splitlines(session.getResult())
before=''
after=''
......@@ -289,7 +292,7 @@ class CiscoCommandBgpIPv46Sum(ulgmodel.TextCommand):
for l in lines:
if(tb):
# inside table body
table.append(self._decorateTableLine(l,decorator_helper,router))
table.append(self._decorateTableLine(l,decorator_helper,session.getRouter()))
else:
# should we switch to table body?
......@@ -302,7 +305,7 @@ class CiscoCommandBgpIPv46Sum(ulgmodel.TextCommand):
before = before + l + '\n'
result_len = len(table)
table = table[resrange:resrange+defaults.range_step]
table = table[session.getRange():session.getRange()+defaults.range_step]
return (ulgmodel.TableDecorator(table,table_header,before=decorator_helper.pre(before)).decorate(),result_len)
......@@ -324,12 +327,14 @@ class CiscoCommandBgpIPv6Sum(CiscoCommandBgpIPv46Sum):
def __init__(self,name=None,peer_address_command=None,peer_received_command=None):
return CiscoCommandBgpIPv46Sum.__init__(self,name,peer_address_command,peer_received_command)
def decorateResult(self,result,router=None,decorator_helper=None,resrange=0):
def decorateResult(self,session,decorator_helper=None):
res=''
for l in normalizeBGPIPv6SumSplitLines(str.splitlines(result)):
for l in normalizeBGPIPv6SumSplitLines(str.splitlines(session.getResult())):
res = res + "\n" + l
return super(CiscoCommandBgpIPv6Sum,self).decorateResult(res,router,decorator_helper,resrange)
s = decorator_helper.copy_session(session)
s.setResult(res)
return super(CiscoCommandBgpIPv6Sum,self).decorateResult(s,decorator_helper)
class CiscoCommandShowBgpIPv4Neigh(ulgmodel.TextCommand):
......@@ -398,11 +403,14 @@ class CiscoCommandShowBgpIPv46Select(ulgmodel.TextCommand):
])
return result
def decorateResult(self,result,router=None,decorator_helper=None,resrange=0):
if((not router) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % result
def decorateResult(self,session,decorator_helper=None):
if(not session):
raise Exception("Can not decorate result without valid session passed.")
if((not session.getRouter()) or (not decorator_helper)):
return "<pre>\n%s\n</pre>" % session.getResult()
lines = str.splitlines(result)
lines = str.splitlines(session.getResult())
before=''
after=None
......@@ -436,13 +444,14 @@ class CiscoCommandShowBgpIPv46Select(ulgmodel.TextCommand):
result_len = len(table_lines)
if(table_lines):
table = self._genTable(table_lines[resrange:resrange+defaults.range_step],decorator_helper,router)
table = self._genTable(table_lines[session.getRange():session.getRange()+defaults.range_step],
decorator_helper,session.getRouter())
if(after):
after=decorator_helper.pre(after)
return (ulgmodel.TableDecorator(table,table_header_descr,before=decorator_helper.pre(before),
after=after).decorate(), result_len)
after=after).decorate(),result_len)
class CiscoCommandShowBgpIPv4NeighAdv(CiscoCommandShowBgpIPv46Select):
......@@ -457,6 +466,26 @@ class CiscoCommandShowBgpIPv4NeighRecv(CiscoCommandShowBgpIPv46Select):
class CiscoCommandShowBgpIPv6NeighRecv(CiscoCommandShowBgpIPv46Select):
COMMAND_TEXT='show bgp ipv6 unicast neighbor %s received-routes'
class CiscoCommandGraphShowBgpIPv46Uni(ulgmodel.TextCommand):
TABLE_HEADER_REGEXP=BGP_PREFIX_TABLE_HEADER
LASTLINE_REGEXP='^\s*Total number of prefixes [0-9]+\s*$'
def __init__(self,peers,name=None):
ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[
ulgmodel.TextParameter(ulgmodel.TextParameter(IPV4_SUBNET_REGEXP,name=defaults.STRING_IPSUBNET))],
name=name)
def decorateResult(self,session,decorator_helper=None):
# TODO return img src=... to result when finished
# decorator_helper.getSpecialContentURL(session!!!)
pass
def getSpecialContent(self,session,**params):
return ''
class CiscoCommandGraphShowBgpIPv4Uni(CiscoCommandGraphShowBgpIPv46Uni):
COMMAND_TEXT='show bgp ipv4 unicast %s'
class CiscoRouter(ulgmodel.RemoteRouter):
PS_KEY_BGPV4 = '-bgpipv4'
PS_KEY_BGPV6 = '-bgpipv6'
......
......@@ -44,6 +44,7 @@ def debug(message):
log('DEBUG:' + message)
class PersistentStorage(object):
def __init__(self):
self.data = {}
......@@ -249,15 +250,18 @@ class TextCommand(object):
def rescanHook(self,router):
pass
def decorateResult(self,result,router=None,decorator_helper=None,resrange=None):
if(resrange != None):
s = str.splitlines(result)
def decorateResult(self,session,decorator_helper=None):
if(session.getRange() != None):
s = str.splitlines(session.getResult())
r=''
for sl in s[resrange:resrange+defaults.range_step+1]:
for sl in s[session.getRange():session.getRange()+defaults.range_step+1]:
r += sl + "\n"
return ("<pre>\n%s\n</pre>" % r, len(s))
else:
return ("<pre>\n%s\n</pre>" % result, len(str.splitlines(result)))
return ("<pre>\n%s\n</pre>" % session.getResult(), len(str.splitlines(session.getResult())))
def getSpecialContent(self,session,**params):
raise Exception("getSpecialContet() is not implemented in ulgmodel.TextCommand.")
class AnyCommand(TextCommand):
def __init__(self):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment