sys.path.append('/home/ecprice/.local/lib/python2.5/site-packages')
+import templates
from Cheetah.Template import Template
from sipb_xen_database import Machine, CDROM, ctx, connect
import validation
from webcommon import InvalidInput, CodeError, g
import controls
+class Checkpoint:
+ def __init__(self):
+ self.start_time = time.time()
+ self.checkpoints = []
+
+ def checkpoint(self, s):
+ self.checkpoints.append((s, time.time()))
+
+ def __str__(self):
+ return ('Timing info:\n%s\n' %
+ '\n'.join(['%s: %s' % (d, t - self.start_time) for
+ (d, t) in self.checkpoints]))
+
+checkpoint = Checkpoint()
+
+
def helppopup(subj):
"""Return HTML code for a (?) link to a specified help topic"""
return ('<span class="helplink"><a href="help?subject=' + subj +
"""Print an error page when a CodeError occurs"""
d = dict(op=op, user=user, errorMessage=str(err),
stderr=emsg)
- return Template(file='error.tmpl', searchList=[d])
+ return templates.error(searchList=[d])
def invalidInput(op, user, fields, err, emsg):
"""Print an error page when an InvalidInput exception occurs"""
d = dict(op=op, user=user, err_field=err.err_field,
err_value=str(err.err_value), stderr=emsg,
errorMessage=str(err))
- return Template(file='invalid.tmpl', searchList=[d])
+ return templates.invalid(searchList=[d])
def hasVnc(status):
"""Does the machine with a given status list support VNC?"""
setattr(d['defaults'], field, fields.getfirst(field))
else:
d['new_machine'] = parsed_fields['name']
- return Template(file='list.tmpl', searchList=[d])
+ return templates.list(searchList=[d])
def getListDict(user):
machines = [m for m in Machine.select()
if validation.haveAccess(user, m)]
+ checkpoint.checkpoint('Got my machines')
on = {}
has_vnc = {}
on = g.uptimes
+ checkpoint.checkpoint('Got uptimes')
for m in machines:
m.uptime = g.uptimes.get(m)
if not on[m]:
has_vnc[m] = "ParaVM"+helppopup("paravm_console")
max_memory = validation.maxMemory(user)
max_disk = validation.maxDisk(user)
+ checkpoint.checkpoint('Got max mem/disk')
defaults = Defaults(max_memory=max_memory,
max_disk=max_disk,
owner=user,
cdrom='gutsy-i386')
+ checkpoint.checkpoint('Got defaults')
d = dict(user=user,
cant_add_vm=validation.cantAddVm(user),
max_memory=max_memory,
def listVms(user, fields):
"""Handler for list requests."""
+ checkpoint.checkpoint('Getting list dict')
d = getListDict(user)
- return Template(file='list.tmpl', searchList=[d])
+ checkpoint.checkpoint('Got list dict')
+ return templates.list(searchList=[d])
def vnc(user, fields):
"""VNC applet page.
machine=machine,
hostname=os.environ.get('SERVER_NAME', 'localhost'),
authtoken=token)
- return Template(file='vnc.tmpl', searchList=[d])
+ return templates.vnc(searchList=[d])
def getNicInfo(data_dict, machine):
"""Helper function for info, get data on nics for a machine.
else:
result = 'Success!'
if not back:
- return Template(file='command.tmpl', searchList=[d])
+ return templates.command(searchList=[d])
if back == 'list':
g.clear() #Changed global state
d = getListDict(user)
d['result'] = result
- return Template(file='list.tmpl', searchList=[d])
+ return templates.list(searchList=[d])
elif back == 'info':
machine = validation.testMachineId(user, fields.getfirst('machine_id'))
d = infoDict(user, machine)
d['result'] = result
- return Template(file='info.tmpl', searchList=[d])
+ return templates.info(searchList=[d])
else:
- raise InvalidInput('back', back, 'Not a known back page.')
+ raise InvalidInput
+ ('back', back, 'Not a known back page.')
def modifyDict(user, fields):
olddisk = {}
for field in fields.keys():
setattr(info_dict['defaults'], field, fields.getfirst(field))
info_dict['result'] = result
- return Template(file='info.tmpl', searchList=[info_dict])
+ return templates.info(searchList=[info_dict])
def helpHandler(user, fields):
subjects=subjects,
mapping=help_mapping)
- return Template(file="help.tmpl", searchList=[d])
+ return templates.help(searchList=[d])
def badOperation(u, e):
def infoDict(user, machine):
status = controls.statusInfo(machine)
+ checkpoint.checkpoint('Getting status info')
has_vnc = hasVnc(status)
if status is None:
main_status = dict(name=machine.name,
uptime = datetime.timedelta(seconds=int(time.time()-start_time))
cpu_time_float = float(main_status.get('cpu_time', 0))
cputime = datetime.timedelta(seconds=int(cpu_time_float))
+ checkpoint.checkpoint('Status')
display_fields = """name uptime memory state cpu_weight on_reboot
on_poweroff on_crash on_xend_start on_xend_stop bootloader""".split()
display_fields = [('name', 'Name'),
else:
pass
#fields.append((disp, None))
- max_mem = validation.maxMemory(user, machine)
+
+ checkpoint.checkpoint('Got fields')
+
+
+ max_mem = validation.maxMemory(user, machine, False)
+ checkpoint.checkpoint('Got mem')
max_disk = validation.maxDisk(user, machine)
defaults = Defaults()
for name in 'machine_id name administrator owner memory contact'.split():
setattr(defaults, name, getattr(machine, name))
defaults.disk = "%0.2f" % (machine.disks[0].size/1024.)
+ checkpoint.checkpoint('Got defaults')
d = dict(user=user,
cdroms=CDROM.select(),
on=status is not None,
"""Handler for info on a single VM."""
machine = validation.testMachineId(user, fields.getfirst('machine_id'))
d = infoDict(user, machine)
- return Template(file='info.tmpl', searchList=[d])
+ checkpoint.checkpoint('Got infodict')
+ return templates.info(searchList=[d])
mapping = dict(list=listVms,
vnc=vnc,
return 'moo'
def main(operation, user, fields):
+ start_time = time.time()
fun = mapping.get(operation, badOperation)
if fun not in (helpHandler, ):
connect('postgres://sipb-xen@sipb-xen-dev.mit.edu/sipb_xen')
try:
+ checkpoint.checkpoint('Before')
output = fun(u, fields)
+ checkpoint.checkpoint('After')
headers = dict(DEFAULT_HEADERS)
if isinstance(output, tuple):
new_headers, output = output
headers.update(new_headers)
-
e = revertStandardError()
if e:
output.addError(e)
printHeaders(headers)
- print output
+ output_string = str(output)
+ checkpoint.checkpoint('output as a string')
+ print output_string
+ print '<pre>%s</pre>' % checkpoint
except Exception, err:
if not fields.has_key('js'):
if isinstance(err, CodeError):
raise
if __name__ == '__main__':
- start_time = time.time()
fields = cgi.FieldStorage()
u = getUser()
g.user = u
if not operation:
operation = 'list'
- main(operation, u, fields)
+ #main(operation, u, fields)
+ import profile
+ profile.run('main(operation, u, fields)', 'log-'+operation)
+++ /dev/null
-#!/usr/bin/env python
-
-
-
-
-##################################################
-## DEPENDENCIES
-import sys
-import os
-import os.path
-from os.path import getmtime, exists
-import time
-import types
-import __builtin__
-from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
-from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
-from Cheetah.Template import Template
-from Cheetah.DummyTransaction import DummyTransaction
-from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
-from Cheetah.CacheRegion import CacheRegion
-import Cheetah.Filters as Filters
-import Cheetah.ErrorCatchers as ErrorCatchers
-
-##################################################
-## MODULE CONSTANTS
-try:
- True, False
-except NameError:
- True, False = (1==1), (1==0)
-VFFSL=valueFromFrameOrSearchList
-VFSL=valueFromSearchList
-VFN=valueForName
-currentTime=time.time
-__CHEETAH_version__ = '2.0rc8'
-__CHEETAH_versionTuple__ = (2, 0, 0, 'candidate', 8)
-__CHEETAH_genTime__ = 1191715796.9141691
-__CHEETAH_genTimestamp__ = 'Sat Oct 6 20:09:56 2007'
-__CHEETAH_src__ = 'mainpage.tmpl'
-__CHEETAH_srcLastModified__ = 'Sat Oct 6 20:09:44 2007'
-__CHEETAH_docstring__ = 'Autogenerated by CHEETAH: The Python-Powered Template Engine'
-
-if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
- raise AssertionError(
- 'This template was compiled with Cheetah version'
- ' %s. Templates compiled before version %s must be recompiled.'%(
- __CHEETAH_version__, RequiredCheetahVersion))
-
-##################################################
-## CLASSES
-
-class mainpage(Template):
-
- ##################################################
- ## CHEETAH GENERATED METHODS
-
-
- def __init__(self, *args, **KWs):
-
- Template.__init__(self, *args, **KWs)
- if not self._CHEETAH__instanceInitialized:
- cheetahKWArgs = {}
- allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
- for k,v in KWs.items():
- if k in allowedKWs: cheetahKWArgs[k] = v
- self._initCheetahInstance(**cheetahKWArgs)
-
-
- def respond(self, trans=None):
-
-
-
- ## CHEETAH: main method generated for this template
- if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
- trans = self.transaction # is None unless self.awake() was called
- if not trans:
- trans = DummyTransaction()
- _dummyTrans = True
- else: _dummyTrans = False
- write = trans.response().write
- SL = self._CHEETAH__searchList
- _filter = self._CHEETAH__currentFilter
-
- ########################################
- ## START - generated method body
-
- write('''<html>
-<head><title>Status for order #''')
- _v = VFFSL(SL,"order.id",True) # '$order.id' on line 2, col 32
- if _v is not None: write(_filter(_v, rawExpr='$order.id')) # from line 2, col 32.
- write('''</title></head>
-<body>
-<p>[You are logged in as ''')
- _v = VFN(VFFSL(SL,"user",True),"getFullName",False)() # '$user.getFullName()' on line 4, col 26
- if _v is not None: write(_filter(_v, rawExpr='$user.getFullName()')) # from line 4, col 26.
- write('''.]</p>
-<p>
-''')
- if (VFN(VFFSL(SL,"order",True),"hasShipped",False)()): # generated from line 6, col 1
- write(''' Your order has shipped. Your tracking number is ''')
- _v = VFFSL(SL,"order.trackingNumber",True) # '$order.trackingNumber' on line 7, col 50
- if _v is not None: write(_filter(_v, rawExpr='$order.trackingNumber')) # from line 7, col 50.
- write('''.
-''')
- else: # generated from line 8, col 1
- write(''' Your order has not yet shipped.
-''')
- write('''</p>
-<p>Order #''')
- _v = VFFSL(SL,"order.id",True) # '$order.id' on line 12, col 11
- if _v is not None: write(_filter(_v, rawExpr='$order.id')) # from line 12, col 11.
- write(''' contains the following items:</p>
-<ul>
-''')
- for purchased, quantity in VFN(VFFSL(SL,"order.purchased",True),"items",False)(): # generated from line 14, col 1
- write(''' <li>''')
- _v = VFFSL(SL,"purchased.name",True) # '$purchased.name' on line 15, col 6
- if _v is not None: write(_filter(_v, rawExpr='$purchased.name')) # from line 15, col 6.
- write(''': ''')
- _v = VFFSL(SL,"quantity",True) # '$quantity' on line 15, col 23
- if _v is not None: write(_filter(_v, rawExpr='$quantity')) # from line 15, col 23.
- write(''' unit''')
- if (VFFSL(SL,"quantity",True) != 1): # generated from line 16, col 1
- write('''s
-''')
- write('''</li>
-''')
- write('''</ul>
-<hr />
-Served by Online Store v1.0
-</body>
-</html>
-''')
-
- ########################################
- ## END - generated method body
-
- return _dummyTrans and trans.response().getvalue() or ""
-
- ##################################################
- ## CHEETAH GENERATED ATTRIBUTES
-
-
- _CHEETAH__instanceInitialized = False
-
- _CHEETAH_version = __CHEETAH_version__
-
- _CHEETAH_versionTuple = __CHEETAH_versionTuple__
-
- _CHEETAH_genTime = __CHEETAH_genTime__
-
- _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
-
- _CHEETAH_src = __CHEETAH_src__
-
- _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
-
- _mainCheetahMethod_for_mainpage= 'respond'
-
-## END CLASS DEFINITION
-
-if not hasattr(mainpage, '_initCheetahAttributes'):
- templateAPIClass = getattr(mainpage, '_CHEETAH_templateClass', Template)
- templateAPIClass._addCheetahPlumbingCodeToClass(mainpage)
-
-
-# CHEETAH was developed by Tavis Rudd and Mike Orr
-# with code, advice and input from many other volunteers.
-# For more information visit http://www.CheetahTemplate.org/
-
-##################################################
-## if run from command line:
-if __name__ == '__main__':
- from Cheetah.TemplateCmdLineIface import CmdLineIface
- CmdLineIface(templateObj=mainpage()).run()
-
-