Ignore:
Timestamp:
Jun 2, 2008, 11:25:47 PM (17 years ago)
Author:
ecprice
Message:

Put validation behind more abstraction.

Location:
trunk/packages/sipb-xen-www/code
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/packages/sipb-xen-www/code/controls.py

    r563 r572  
    9393                        % (err, machine.name, cdtype))
    9494
    95 def createVm(owner, contact, name, memory, disk_size, machine_type, cdrom, clone_from):
     95def createVm(username, state, owner, contact, name, memory, disksize, machine_type, cdrom, clone_from):
    9696    """Create a VM and put it in the database"""
    9797    # put stuff in the table
    9898    transaction = ctx.current.create_transaction()
    9999    try:
    100         validation.validMemory(owner, memory)
    101         validation.validDisk(owner, disk_size  * 1. / 1024)
    102         validation.validAddVm(owner)
     100        validation.Validate(username, state, owner=owner, memory=memory, disksize=disksize/1024.)
    103101        res = meta.engine.execute('select nextval('
    104102                                  '\'"machines_machine_id_seq"\')')
     
    116114        ctx.current.save(machine)
    117115        disk = Disk(machine_id=machine.machine_id,
    118                     guest_device_name='hda', size=disk_size)
     116                    guest_device_name='hda', size=disksize)
    119117        open_nics = NIC.select_by(machine_id=None)
    120118        if not open_nics: #No IPs left!
     
    141139    """Return a dictionary mapping machine names to dicts."""
    142140    value_string = remctl('web', 'listvms')
    143     value_dict = yaml.load(value_string, yaml.CSafeLoader)
     141    value_dict = yaml.load(value_string, yaml.SafeLoader)
    144142    return value_dict
    145143
     
    209207        remctl('web', 'lvremove', mname, dname)
    210208
    211 def commandResult(user, fields):
     209def commandResult(username, state, fields):
    212210    start_time = 0
    213     machine = validation.testMachineId(user, fields.getfirst('machine_id'))
     211    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
    214212    action = fields.getfirst('action')
    215213    cdrom = fields.getfirst('cdrom')
     
    236234               
    237235    elif action == 'Power on':
    238         if validation.maxMemory(user, machine) < machine.memory:
     236        if validation.maxMemory(username, state, machine) < machine.memory:
    239237            raise InvalidInput('action', 'Power on',
    240238                               "You don't have enough free RAM quota "
     
    264262        deleteVM(machine)
    265263
    266     d = dict(user=user,
     264    d = dict(user=username,
    267265             command=action,
    268266             machine=machine)
  • trunk/packages/sipb-xen-www/code/main.py

    r566 r572  
    4242import validation
    4343import cache_acls
    44 from webcommon import InvalidInput, CodeError, g
     44from webcommon import InvalidInput, CodeError, state
    4545import controls
    4646
     
    120120DEFAULT_HEADERS = {'Content-Type': 'text/html'}
    121121
    122 def error(op, user, fields, err, emsg):
     122def error(op, username, fields, err, emsg):
    123123    """Print an error page when a CodeError occurs"""
    124     d = dict(op=op, user=user, errorMessage=str(err),
     124    d = dict(op=op, user=username, errorMessage=str(err),
    125125             stderr=emsg)
    126126    return templates.error(searchList=[d])
    127127
    128 def invalidInput(op, user, fields, err, emsg):
     128def invalidInput(op, username, fields, err, emsg):
    129129    """Print an error page when an InvalidInput exception occurs"""
    130     d = dict(op=op, user=user, err_field=err.err_field,
     130    d = dict(op=op, user=username, err_field=err.err_field,
    131131             err_value=str(err.err_value), stderr=emsg,
    132132             errorMessage=str(err))
     
    143143    return False
    144144
    145 def parseCreate(user, fields):
    146     name = fields.getfirst('name')
    147     if not validation.validMachineName(name):
    148         raise InvalidInput('name', name, 'You must provide a machine name.  Max 22 chars, alnum plus \'-\' and \'_\'.')
    149     name = name.lower()
    150 
    151     if Machine.get_by(name=name):
    152         raise InvalidInput('name', name,
    153                            "Name already exists.")
    154 
    155     owner = validation.testOwner(user, fields.getfirst('owner'))
    156 
    157     memory = fields.getfirst('memory')
    158     memory = validation.validMemory(owner, memory, on=True)
    159 
    160     disk_size = fields.getfirst('disk')
    161     disk_size = validation.validDisk(owner, disk_size)
    162 
    163     vm_type = fields.getfirst('vmtype')
    164     vm_type = validation.validVmType(vm_type)
    165 
    166     cdrom = fields.getfirst('cdrom')
    167     if cdrom is not None and not CDROM.get(cdrom):
    168         raise CodeError("Invalid cdrom type '%s'" % cdrom)
    169 
    170     clone_from = fields.getfirst('clone_from')
    171     if clone_from and clone_from != 'ice3':
    172         raise CodeError("Invalid clone image '%s'" % clone_from)
    173 
    174     return dict(contact=user, name=name, memory=memory, disk_size=disk_size,
    175                 owner=owner, machine_type=vm_type, cdrom=cdrom, clone_from=clone_from)
    176 
    177 def create(user, fields):
     145def parseCreate(username, state, fields):
     146    kws = dict([(kw, fields.getfirst(kw)) for kw in 'name owner memory disksize vmtype cdrom clone_from'.split()])
     147    validate = validation.Validate(username, state, **kws)
     148    return dict(contact=username, name=validate.name, memory=validate.memory,
     149                disksize=validate.disksize, owner=validate.owner, machine_type=validate.vmtype,
     150                cdrom=getattr(validate, 'cdrom', None),
     151                clone_from=getattr(validate, 'clone_from', None))
     152
     153def create(username, state, fields):
    178154    """Handler for create requests."""
    179155    try:
    180         parsed_fields = parseCreate(user, fields)
    181         machine = controls.createVm(**parsed_fields)
     156        parsed_fields = parseCreate(username, state, fields)
     157        machine = controls.createVm(username, **parsed_fields)
    182158    except InvalidInput, err:
    183159        pass
    184160    else:
    185161        err = None
    186     g.clear() #Changed global state
    187     d = getListDict(user)
     162    state.clear() #Changed global state
     163    d = getListDict(username)
    188164    d['err'] = err
    189165    if err:
     
    195171
    196172
    197 def getListDict(user):
     173def getListDict(username, state):
    198174    """Gets the list of local variables used by list.tmpl."""
    199175    checkpoint.checkpoint('Starting')
    200     machines = g.machines
     176    machines = state.machines
    201177    checkpoint.checkpoint('Got my machines')
    202178    on = {}
    203179    has_vnc = {}
    204     xmlist = g.xmlist
     180    xmlist = state.xmlist
    205181    checkpoint.checkpoint('Got uptimes')
    206     can_clone = 'ice3' not in g.xmlist_raw
     182    can_clone = 'ice3' not in state.xmlist_raw
    207183    for m in machines:
    208184        if m not in xmlist:
     
    217193            else:
    218194                has_vnc[m] = "ParaVM"+helppopup("ParaVM Console")
    219     max_memory = validation.maxMemory(user)
    220     max_disk = validation.maxDisk(user)
     195    max_memory = validation.maxMemory(username, state)
     196    max_disk = validation.maxDisk(username)
    221197    checkpoint.checkpoint('Got max mem/disk')
    222198    defaults = Defaults(max_memory=max_memory,
    223199                        max_disk=max_disk,
    224                         owner=user,
     200                        owner=username,
    225201                        cdrom='gutsy-i386')
    226202    checkpoint.checkpoint('Got defaults')
    227203    def sortkey(machine):
    228         return (machine.owner != user, machine.owner, machine.name)
     204        return (machine.owner != username, machine.owner, machine.name)
    229205    machines = sorted(machines, key=sortkey)
    230     d = dict(user=user,
    231              cant_add_vm=validation.cantAddVm(user),
     206    d = dict(user=username,
     207             cant_add_vm=validation.cantAddVm(username, state),
    232208             max_memory=max_memory,
    233209             max_disk=max_disk,
     
    238214    return d
    239215
    240 def listVms(user, fields):
     216def listVms(username, state, fields):
    241217    """Handler for list requests."""
    242218    checkpoint.checkpoint('Getting list dict')
    243     d = getListDict(user)
     219    d = getListDict(username, state)
    244220    checkpoint.checkpoint('Got list dict')
    245221    return templates.list(searchList=[d])
    246222
    247 def vnc(user, fields):
     223def vnc(username, state, fields):
    248224    """VNC applet page.
    249225
     
    265241    echo 1 > /proc/sys/net/ipv4/ip_forward
    266242    """
    267     machine = validation.testMachineId(user, fields.getfirst('machine_id'))
     243    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
    268244
    269245    TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN"
    270246
    271247    data = {}
    272     data["user"] = user
     248    data["user"] = username
    273249    data["machine"] = machine.name
    274250    data["expires"] = time.time()+(5*60)
     
    283259    has_vnc = hasVnc(status)
    284260
    285     d = dict(user=user,
     261    d = dict(user=username,
    286262             on=status,
    287263             has_vnc=has_vnc,
     
    342318    return disk_fields
    343319
    344 def command(user, fields):
     320def command(username, state, fields):
    345321    """Handler for running commands like boot and delete on a VM."""
    346322    back = fields.getfirst('back')
    347323    try:
    348         d = controls.commandResult(user, fields)
     324        d = controls.commandResult(username, state, fields)
    349325        if d['command'] == 'Delete VM':
    350326            back = 'list'
     
    352328        if not back:
    353329            raise
    354         #print >> sys.stderr, err
     330        print >> sys.stderr, err
    355331        result = err
    356332    else:
     
    359335            return templates.command(searchList=[d])
    360336    if back == 'list':
    361         g.clear() #Changed global state
    362         d = getListDict(user)
     337        state.clear() #Changed global state
     338        d = getListDict(username)
    363339        d['result'] = result
    364340        return templates.list(searchList=[d])
    365341    elif back == 'info':
    366         machine = validation.testMachineId(user, fields.getfirst('machine_id'))
     342        machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
    367343        return ({'Status': '302',
    368344                 'Location': '/info?machine_id=%d' % machine.machine_id},
     
    371347        raise InvalidInput('back', back, 'Not a known back page.')
    372348
    373 def modifyDict(user, fields):
     349def modifyDict(username, state, fields):
    374350    """Modify a machine as specified by CGI arguments.
    375351
     
    379355    transaction = ctx.current.create_transaction()
    380356    try:
    381         machine = validation.testMachineId(user, fields.getfirst('machine_id'))
    382         owner = validation.testOwner(user, fields.getfirst('owner'), machine)
    383         admin = validation.testAdmin(user, fields.getfirst('administrator'),
    384                                      machine)
    385         contact = validation.testContact(user, fields.getfirst('contact'),
    386                                          machine)
    387         name = validation.testName(user, fields.getfirst('name'), machine)
     357        kws = dict([(kw, fields.getfirst(kw)) for kw in 'machine_id owner admin contact name memory vmtype disksize'.split()])
     358        validate = validation.Validate(username, state, **kws)
     359        machine = validate.machine
     360        print >> sys.stderr, machine, machine.administrator, kws['admin']
    388361        oldname = machine.name
    389         command = "modify"
    390 
    391         memory = fields.getfirst('memory')
    392         if memory is not None:
    393             memory = validation.validMemory(owner, memory, machine, on=False)
    394             machine.memory = memory
    395 
    396         vm_type = validation.validVmType(fields.getfirst('vmtype'))
    397         if vm_type is not None:
    398             machine.type = vm_type
    399 
    400         disksize = validation.testDisk(owner, fields.getfirst('disk'))
    401         if disksize is not None:
    402             disksize = validation.validDisk(owner, disksize, machine)
     362
     363        if hasattr(validate, 'memory'):
     364            machine.memory = validate.memory
     365
     366        if hasattr(validate, 'vmtype'):
     367            machine.type = validate.vmtype
     368
     369        if hasattr(validate, 'disksize'):
     370            disksize = validate.disksize
    403371            disk = machine.disks[0]
    404372            if disk.size != disksize:
     
    408376
    409377        update_acl = False
    410         if owner is not None and owner != machine.owner:
    411             machine.owner = owner
     378        if hasattr(validate, 'owner') and validate.owner != machine.owner:
     379            machine.owner = validate.owner
    412380            update_acl = True
    413         if name is not None:
     381        if hasattr(validate, 'name'):
    414382            machine.name = name
    415         if admin is not None and admin != machine.administrator:
    416             machine.administrator = admin
     383        if hasattr(validate, 'admin') and validate.admin != machine.administrator:
     384            machine.administrator = validate.admin
    417385            update_acl = True
    418         if contact is not None:
    419             machine.contact = contact
     386        if hasattr(validate, 'contact'):
     387            machine.contact = validate.contact
    420388
    421389        ctx.current.save(machine)
    422390        if update_acl:
     391            print >> sys.stderr, machine, machine.administrator
    423392            cache_acls.refreshMachine(machine)
    424393        transaction.commit()
     
    428397    for diskname in olddisk:
    429398        controls.resizeDisk(oldname, diskname, str(olddisk[diskname]))
    430     if name is not None:
    431         controls.renameMachine(machine, oldname, name)
    432     return dict(user=user,
    433                 command=command,
     399    if hasattr(validate, 'name'):
     400        controls.renameMachine(machine, oldname, validate.name)
     401    return dict(user=username,
     402                command="modify",
    434403                machine=machine)
    435404
    436 def modify(user, fields):
     405def modify(username, state, fields):
    437406    """Handler for modifying attributes of a machine."""
    438407    try:
    439         modify_dict = modifyDict(user, fields)
     408        modify_dict = modifyDict(username, state, fields)
    440409    except InvalidInput, err:
    441410        result = None
    442         machine = validation.testMachineId(user, fields.getfirst('machine_id'))
     411        machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
    443412    else:
    444413        machine = modify_dict['machine']
    445414        result = 'Success!'
    446415        err = None
    447     info_dict = infoDict(user, machine)
     416    info_dict = infoDict(username, machine)
    448417    info_dict['err'] = err
    449418    if err:
     
    454423
    455424
    456 def helpHandler(user, fields):
     425def helpHandler(username, state, fields):
    457426    """Handler for help messages."""
    458427    simple = fields.getfirst('simple')
     
    497466        subjects = sorted(help_mapping.keys())
    498467
    499     d = dict(user=user,
     468    d = dict(user=username,
    500469             simple=simple,
    501470             subjects=subjects,
     
    509478    raise CodeError("Unknown operation")
    510479
    511 def infoDict(user, machine):
     480def infoDict(username, machine):
    512481    """Get the variables used by info.tmpl."""
    513482    status = controls.statusInfo(machine)
     
    580549
    581550
    582     max_mem = validation.maxMemory(machine.owner, machine, False)
     551    max_mem = validation.maxMemory(machine.owner, state, machine, False)
    583552    checkpoint.checkpoint('Got mem')
    584553    max_disk = validation.maxDisk(machine.owner, machine)
     
    589558    defaults.disk = "%0.2f" % (machine.disks[0].size/1024.)
    590559    checkpoint.checkpoint('Got defaults')
    591     d = dict(user=user,
     560    d = dict(user=username,
    592561             on=status is not None,
    593562             machine=machine,
     
    602571    return d
    603572
    604 def info(user, fields):
     573def info(username, state, fields):
    605574    """Handler for info on a single VM."""
    606     machine = validation.testMachineId(user, fields.getfirst('machine_id'))
    607     d = infoDict(user, machine)
     575    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
     576    d = infoDict(username, machine)
    608577    checkpoint.checkpoint('Got infodict')
    609578    return templates.info(searchList=[d])
    610579
    611 def unauthFront(_, fields):
     580def unauthFront(_, _2, fields):
    612581    """Information for unauth'd users."""
    613582    return templates.unauth(searchList=[{'simple' : True}])
     
    629598
    630599
    631 def getUser():
     600def getUser(environ):
    632601    """Return the current user based on the SSL environment variables"""
    633     email = os.environ.get('SSL_CLIENT_S_DN_Email', None)
     602    email = environ.get('SSL_CLIENT_S_DN_Email', None)
    634603    if email is None:
    635604        return None
    636     return email.split("@")[0]
    637 
    638 def main(operation, user, fields):
     605    if not email.endswith('@MIT.EDU'):
     606        return None
     607    return email[:-8]
     608
     609def main(operation, username, state, fields):
    639610    start_time = time.time()
    640611    fun = mapping.get(operation, badOperation)
     
    644615    try:
    645616        checkpoint.checkpoint('Before')
    646         output = fun(u, fields)
     617        output = fun(username, state, fields)
    647618        checkpoint.checkpoint('After')
    648619
     
    653624        e = revertStandardError()
    654625        if e:
     626            if isinstance(output, basestring):
     627                sys.stderr = StringIO()
     628                x = str(output)
     629                print >> sys.stderr, x
     630                print >> sys.stderr, 'XXX'
     631                print >> sys.stderr, e
     632                raise Exception()
    655633            output.addError(e)
    656634        printHeaders(headers)
     
    659637        print output_string
    660638        if fields.has_key('timedebug'):
    661             print '<pre>%s</pre>' % checkpoint
     639            print '<pre>%s</pre>' % cgi.escape(checkpoint)
    662640    except Exception, err:
    663641        if not fields.has_key('js'):
     
    665643                print 'Content-Type: text/html\n'
    666644                e = revertStandardError()
    667                 print error(operation, u, fields, err, e)
     645                print error(operation, state.username, fields, err, e)
    668646                sys.exit(1)
    669647            if isinstance(err, InvalidInput):
    670648                print 'Content-Type: text/html\n'
    671649                e = revertStandardError()
    672                 print invalidInput(operation, u, fields, err, e)
     650                print invalidInput(operation, state.username, fields, err, e)
    673651                sys.exit(1)
    674652        print 'Content-Type: text/plain\n'
     
    690668        logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.INFO)
    691669
    692     u = getUser()
    693     g.user = u
     670    username = getUser(os.environ)
     671    state.username = username
    694672    operation = os.environ.get('PATH_INFO', '')
    695673    if not operation:
     
    697675        print 'Location: ' + os.environ['SCRIPT_NAME']+'/\n'
    698676        sys.exit(0)
    699 
    700     if u is None:
     677    if username is None:
    701678        operation = 'unauth'
    702 
    703679    if operation.startswith('/'):
    704680        operation = operation[1:]
     
    708684    if os.getenv("SIPB_XEN_PROFILE"):
    709685        import profile
    710         profile.run('main(operation, u, fields)', 'log-'+operation)
    711     else:
    712         main(operation, u, fields)
     686        profile.run('main(operation, username, state, fields)', 'log-'+operation)
     687    else:
     688        main(operation, username, state, fields)
  • trunk/packages/sipb-xen-www/code/templates/info.tmpl

    r539 r572  
    7878$helppopup("Administrator")#slurp
    7979#end filter
    80 :</td><td><input type="text" name="administrator", value="$defaults.administrator"/></td></tr>
     80:</td><td><input type="text" name="admin", value="$defaults.administrator"/></td></tr>
    8181#filter None
    8282$errorRow('administrator', $err)
     
    107107$errorRow('memory', $err)
    108108#end filter
    109     <tr><td>Disk:</td><td><input type="text" size=3 name="disk" value="$defaults.disk"/>GiB (max $max_disk)</td><td>WARNING: Modifying disk size may corrupt your data.</td></tr>
     109    <tr><td>Disk:</td><td><input type="text" size=3 name="disksize" value="$defaults.disk"/>GiB (max $max_disk)</td><td>WARNING: Modifying disk size may corrupt your data.</td></tr>
    110110#filter None
    111111$errorRow('disk', $err)
  • trunk/packages/sipb-xen-www/code/templates/list.tmpl

    r559 r572  
    4040        <tr>
    4141          <td>Disk</td>
    42           <td><input type="text" name="disk" value="$defaults.disk" size=3/> GiB (${"%0.1f" % ($max_disk-0.05)} max)</td>
     42          <td><input type="text" name="disksize" value="$defaults.disk" size=3/> GiB (${"%0.1f" % ($max_disk-0.05)} max)</td>
    4343        </tr>
    4444#filter None
  • trunk/packages/sipb-xen-www/code/validation.py

    r537 r572  
    66import string
    77from sipb_xen_database import Machine, NIC, Type, Disk
    8 from webcommon import InvalidInput, g
     8from webcommon import InvalidInput
    99
    1010MAX_MEMORY_TOTAL = 512
     
    1717MAX_VMS_ACTIVE = 4
    1818
    19 def getMachinesByOwner(user, machine=None):
     19class Validate:
     20    def __init__(self, username, state, machine_id=None, name=None, owner=None,
     21                 admin=None, contact=None, memory=None, disksize=None,
     22                 vmtype=None, cdrom=None, clone_from=None):
     23        # XXX Successive quota checks aren't a good idea, since you
     24        # can't necessarily change the locker and disk size at the
     25        # same time.
     26        created_new = (machine_id is None)
     27
     28        if machine_id is not None:
     29            self.machine = testMachineId(username, machine_id)
     30        machine = getattr(self, 'machine', None)
     31
     32        owner = testOwner(username, owner, machine)
     33        if owner is not None:
     34            self.owner = owner
     35        admin = testAdmin(username, admin, machine)
     36        if admin is not None:
     37            self.admin = admin
     38        contact = testContact(username, contact, machine)
     39        if contact is not None:
     40            self.contact = contact
     41        name = testName(username, name, machine)
     42        if name is not None:
     43            self.name = name
     44        if memory is not None:
     45            self.memory = validMemory(self.owner, state, memory, machine,
     46                                      on=not created_new)
     47        if disksize is not None:
     48            self.disksize = validDisk(self.owner, disksize, machine)
     49        if vmtype is not None:
     50            self.vmtype = validVmType(vmtype)
     51        if cdrom is not None:
     52            if not CDROM.get(cdrom):
     53                raise CodeError("Invalid cdrom type '%s'" % cdrom)
     54            self.cdrom = cdrom
     55        if clone_from is not None:
     56            if clone_from not in ('ice3', ):
     57                raise CodeError("Invalid clone image '%s'" % clone_from)
     58            self.clone_from = clone_from
     59
     60
     61def getMachinesByOwner(owner, machine=None):
    2062    """Return the machines owned by the same as a machine.
    2163
     
    2567    if machine:
    2668        owner = machine.owner
    27     else:
    28         owner = user
    2969    return Machine.select_by(owner=owner)
    3070
    31 def maxMemory(user, machine=None, on=True):
     71def maxMemory(owner, g, machine=None, on=True):
    3272    """Return the maximum memory for a machine or a user.
    3373
     
    4484    if not on:
    4585        return MAX_MEMORY_SINGLE
    46     machines = getMachinesByOwner(user, machine)
     86    machines = getMachinesByOwner(owner, machine)
    4787    active_machines = [x for x in machines if g.xmlist.get(x)]
    4888    mem_usage = sum([x.memory for x in active_machines if x != machine])
    4989    return min(MAX_MEMORY_SINGLE, MAX_MEMORY_TOTAL-mem_usage)
    5090
    51 def maxDisk(user, machine=None):
     91def maxDisk(owner, machine=None):
    5292    """Return the maximum disk that a machine can reach.
    5393
     
    60100        machine_id = None
    61101    disk_usage = Disk.query().filter_by(Disk.c.machine_id != machine_id,
    62                                         owner=user).sum(Disk.c.size) or 0
     102                                        owner=owner).sum(Disk.c.size) or 0
    63103    return min(MAX_DISK_SINGLE, MAX_DISK_TOTAL-disk_usage/1024.)
    64104
    65 def cantAddVm(user):
    66     machines = getMachinesByOwner(user)
     105def cantAddVm(owner, g):
     106    machines = getMachinesByOwner(owner)
    67107    active_machines = [x for x in machines if g.xmlist.get(x)]
    68108    if len(machines) >= MAX_VMS_TOTAL:
     
    72112                'To create more, turn one off.')
    73113    return False
    74 
    75 def validAddVm(user):
    76     reason = cantAddVm(user)
    77     if reason:
    78         raise InvalidInput('create', True, reason)
    79     return True
    80114
    81115def haveAccess(user, machine):
     
    99133    return True
    100134
    101 def validMemory(user, memory, machine=None, on=True):
    102     """Parse and validate limits for memory for a given user and machine.
     135def validMemory(owner, g, memory, machine=None, on=True):
     136    """Parse and validate limits for memory for a given owner and machine.
    103137
    104138    on is whether the memory must be valid after the machine is
     
    112146        raise InvalidInput('memory', memory,
    113147                           "Minimum %s MiB" % MIN_MEMORY_SINGLE)
    114     if memory > maxMemory(user, machine, on):
     148    max_val = maxMemory(owner, g, machine, on)
     149    if memory > max_val:
    115150        raise InvalidInput('memory', memory,
    116                            'Maximum %s MiB for %s' % (maxMemory(user, machine),
    117                                                       user))
     151                           'Maximum %s MiB for %s' % (max_val, owner))
    118152    return memory
    119153
    120 def validDisk(user, disk, machine=None):
    121     """Parse and validate limits for disk for a given user and machine."""
     154def validDisk(owner, disk, machine=None):
     155    """Parse and validate limits for disk for a given owner and machine."""
    122156    try:
    123157        disk = float(disk)
    124         if disk > maxDisk(user, machine):
     158        if disk > maxDisk(owner, machine):
    125159            raise InvalidInput('disk', disk,
    126                                "Maximum %s G" % maxDisk(user, machine))
     160                               "Maximum %s G" % maxDisk(owner, machine))
    127161        disk = int(disk * 1024)
    128162        if disk < MIN_DISK_SINGLE * 1024:
     
    191225    If machine is None, this is the owner of a new machine.
    192226    """
    193     if owner == user or machine is not None and owner == machine.owner:
     227    if owner == user:
    194228        return owner
     229    if machine is not None and owner in (machine.owner, None):
     230        return None
    195231    if owner is None:
    196232        raise InvalidInput('owner', owner, "Owner must be specified")
     
    214250
    215251def testName(user, name, machine=None):
    216     if name in (None, machine.name):
     252    if name is None:
     253        return None
     254    if machine is not None and name == machine.name:
    217255        return None
    218256    if not Machine.select_by(name=name):
     257        if not validMachineName(name):
     258            raise InvalidInput('name', name, 'You must provide a machine name.  Max 22 chars, alnum plus \'-\' and \'_\'.')
    219259        return name
    220260    raise InvalidInput('name', name, "Name is already taken.")
  • trunk/packages/sipb-xen-www/code/webcommon.py

    r554 r572  
    3737    return property(getter)
    3838
    39 class Global(object):
    40     """Global state of the system, to avoid duplicate remctls to get state"""
     39class State(object):
     40    """State for a request"""
    4141    def __init__(self, user):
    42         self.user = user
     42        self.username = user
    4343
    4444    machines = cachedproperty(lambda self:
    45                                   Machine.query().join('acl').select_by(user=self.user))
     45                                  Machine.query().join('acl').select_by(user=self.username))
    4646    xmlist_raw = cachedproperty(lambda self: controls.getList())
    4747    xmlist = cachedproperty(lambda self:
     
    5656                delattr(self, attr)
    5757
    58 g = Global(None)
     58state = State(None)
Note: See TracChangeset for help on using the changeset viewer.