Changeset 145 for trunk/web


Ignore:
Timestamp:
Oct 8, 2007, 7:17:34 AM (17 years ago)
Author:
ecprice
Message:

Documentation + cleaning up a little.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/web/templates/main.py

    r144 r145  
    2222
    2323class MyException(Exception):
     24    """Base class for my exceptions"""
    2425    pass
    2526
     27class InvalidInput(MyException):
     28    """Exception for user-provided input is invalid but maybe in good faith.
     29
     30    This would include setting memory to negative (which might be a
     31    typo) but not setting an invalid boot CD (which requires bypassing
     32    the select box).
     33    """
     34    pass
     35
     36class CodeError(MyException):
     37    """Exception for internal errors or bad faith input."""
     38    pass
     39
     40
     41
    2642def helppopup(subj):
     43    """Return HTML code for a (?) link to a specified help topic"""
    2744    return '<span class="helplink"><a href="help?subject='+subj+'&amp;simple=true" target="_blank" onclick="return helppopup(\''+subj+'\')">(?)</a></span>'
    2845
     
    3956
    4057def uuidToString(u):
     58    """Turn a numeric UUID to a hyphen-seperated one."""
    4159    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
    4260                     "%02x" * 6]) % tuple(u)
     
    5169MAX_VMS_ACTIVE = 4
    5270
    53 def getMachinesOwner(owner):
     71def getMachinesByOwner(owner):
     72    """Return the machines owned by a given owner."""
    5473    return Machine.select_by(owner=owner)
    5574
    5675def maxMemory(user, machine=None, on=None):
    57     machines = getMachinesOwner(user.username)
     76    """Return the maximum memory for a machine or a user.
     77
     78    If machine is None, return the memory available for a new
     79    machine.  Else, return the maximum that machine can have.
     80
     81    on is a dictionary from machines to booleans, whether a machine is
     82    on.  If None, it is recomputed. XXX make this global?
     83    """
     84
     85    machines = getMachinesByOwner(user.username)
    5886    if on is None:
    5987        on = getUptimes(machines)
     
    6391
    6492def maxDisk(user, machine=None):
    65     machines = getMachinesOwner(user.username)
     93    machines = getMachinesByOwner(user.username)
    6694    disk_usage = sum([sum([y.size for y in x.disks])
    6795                      for x in machines if x != machine])
     
    6997
    7098def canAddVm(user, on=None):
    71     machines = getMachinesOwner(user.username)
     99    machines = getMachinesByOwner(user.username)
    72100    if on is None:
    73101        on = getUptimes(machines)
     
    77105
    78106def haveAccess(user, machine):
     107    """Return whether a user has access to a machine"""
    79108    if user.username == 'moo':
    80109        return True
     
    82111
    83112def error(op, user, fields, err):
     113    """Print an error page when a CodeError occurs"""
    84114    d = dict(op=op, user=user, errorMessage=str(err))
    85115    print Template(file='error.tmpl', searchList=[d, global_dict]);
     
    104134    e = p.wait()
    105135    if e:
    106         raise MyException("Error %s in kinit: %s" % (e, p.stderr.read()))
     136        raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
    107137
    108138def checkKinit():
     
    126156        return p.stdout.read(), p.stderr.read()
    127157    if p.wait():
    128         raise MyException('ERROR on remctl %s: %s' %
     158        raise CodeError('ERROR on remctl %s: %s' %
    129159                          (args, p.stderr.read()))
    130160    return p.stdout.read()
     
    200230    value_string, err_string = remctl('list-long', machine.name, err=True)
    201231    if 'Unknown command' in err_string:
    202         raise MyException("ERROR in remctl list-long %s is not registered" % (machine.name,))
     232        raise CodeError("ERROR in remctl list-long %s is not registered" % (machine.name,))
    203233    elif 'does not exist' in err_string:
    204234        return None
    205235    elif err_string:
    206         raise MyException("ERROR in remctl list-long %s:  %s" % (machine.name, err_string))
     236        raise CodeError("ERROR in remctl list-long %s:  %s" % (machine.name, err_string))
    207237    status = parseStatus(value_string)
    208238    return status
     
    224254    try:
    225255        if memory > maxMemory(user):
    226             raise MyException("Too much memory requested")
     256            raise InvalidInput("Too much memory requested")
    227257        if disk > maxDisk(user) * 1024:
    228             raise MyException("Too much disk requested")
     258            raise InvalidInput("Too much disk requested")
    229259        if not canAddVm(user):
    230             raise MyException("Too many VMs requested")
     260            raise InvalidInput("Too many VMs requested")
    231261        res = meta.engine.execute('select nextval(\'"machines_machine_id_seq"\')')
    232262        id = res.fetchone()[0]
     
    246276        open = NIC.select_by(machine_id=None)
    247277        if not open: #No IPs left!
    248             return "No IP addresses left!  Contact sipb-xen-dev@mit.edu"
     278            raise CodeError("No IP addresses left!  Contact sipb-xen-dev@mit.edu")
    249279        nic = open[0]
    250280        nic.machine_id = machine.machine_id
     
    264294
    265295def validMemory(user, memory, machine=None):
     296    """Parse and validate limits for memory for a given user and machine."""
    266297    try:
    267298        memory = int(memory)
     
    269300            raise ValueError
    270301    except ValueError:
    271         raise MyException("Invalid memory amount; must be at least %s MB" %
     302        raise InvalidInput("Invalid memory amount; must be at least %s MB" %
    272303                          MIN_MEMORY_SINGLE)
    273304    if memory > maxMemory(user, machine):
    274         raise MyException("Too much memory requested")
     305        raise InvalidInput("Too much memory requested")
    275306    return memory
    276307
    277308def validDisk(user, disk, machine=None):
     309    """Parse and validate limits for disk for a given user and machine."""
    278310    try:
    279311        disk = float(disk)
    280312        if disk > maxDisk(user, machine):
    281             raise MyException("Too much disk requested")
     313            raise InvalidInput("Too much disk requested")
    282314        disk = int(disk * 1024)
    283315        if disk < MIN_DISK_SINGLE * 1024:
    284316            raise ValueError
    285317    except ValueError:
    286         raise MyException("Invalid disk amount; minimum is %s GB" %
     318        raise InvalidInput("Invalid disk amount; minimum is %s GB" %
    287319                          MIN_DISK_SINGLE)
    288320    return disk
    289321
    290322def create(user, fields):
     323    """Handler for create requests."""
    291324    name = fields.getfirst('name')
    292325    if not validMachineName(name):
    293         raise MyException("Invalid name '%s'" % name)
     326        raise InvalidInput("Invalid name '%s'" % name)
    294327    name = user.username + '_' + name.lower()
    295328
    296329    if Machine.get_by(name=name):
    297         raise MyException("A machine named '%s' already exists" % name)
     330        raise InvalidInput("A machine named '%s' already exists" % name)
    298331   
    299332    memory = fields.getfirst('memory')
     
    305338    vm_type = fields.getfirst('vmtype')
    306339    if vm_type not in ('hvm', 'paravm'):
    307         raise MyException("Invalid vm type '%s'"  % vm_type)   
     340        raise CodeError("Invalid vm type '%s'"  % vm_type)   
    308341    is_hvm = (vm_type == 'hvm')
    309342
    310343    cdrom = fields.getfirst('cdrom')
    311344    if cdrom is not None and not CDROM.get(cdrom):
    312         raise MyException("Invalid cdrom type '%s'" % cdrom)   
     345        raise CodeError("Invalid cdrom type '%s'" % cdrom)   
    313346   
    314347    machine = createVm(user, name, memory, disk, is_hvm, cdrom)
    315     if isinstance(machine, basestring):
    316         raise MyException(machine)
    317348    d = dict(user=user,
    318349             machine=machine)
     
    321352
    322353def listVms(user, fields):
     354    """Handler for list requests."""
    323355    machines = [m for m in Machine.select() if haveAccess(user, m)]   
    324356    on = {}
     
    352384
    353385def testMachineId(user, machineId, exists=True):
     386    """Parse, validate and check authorization for a given machineId.
     387
     388    If exists is False, don't check that it exists.
     389    """
    354390    if machineId is None:
    355         raise MyException("No machine ID specified")
     391        raise CodeError("No machine ID specified")
    356392    try:
    357393        machineId = int(machineId)
    358394    except ValueError:
    359         raise MyException("Invalid machine ID '%s'" % machineId)
     395        raise CodeError("Invalid machine ID '%s'" % machineId)
    360396    machine = Machine.get(machineId)
    361397    if exists and machine is None:
    362         raise MyException("No such machine ID '%s'" % machineId)
    363     if not haveAccess(user, machine):
    364         raise MyException("No access to machine ID '%s'" % machineId)
     398        raise CodeError("No such machine ID '%s'" % machineId)
     399    if machine is not None and not haveAccess(user, machine):
     400        raise CodeError("No access to machine ID '%s'" % machineId)
    365401    return machine
    366402
     
    378414    -t nat -A POSTROUTING -d 18.181.0.60 -o eth1 -p tcp -m tcp --dport 10003 -j SNAT --to-source 18.187.7.142
    379415    -A FORWARD -d 18.181.0.60 -i eth1 -o eth1 -p tcp -m tcp --dport 10003 -j ACCEPT
     416
     417    Remember to enable iptables!
     418    echo 1 > /proc/sys/net/ipv4/ip_forward
    380419    """
    381420    machine = testMachineId(user, fields.getfirst('machine_id'))
    382     #XXX fix
    383421   
    384422    TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN"
     
    403441
    404442def getNicInfo(data_dict, machine):
     443    """Helper function for info, get data on nics for a machine.
     444
     445    Modifies data_dict to include the relevant data, and returns a list
     446    of (key, name) pairs to display "name: data_dict[key]" to the user.
     447    """
    405448    data_dict['num_nics'] = len(machine.nics)
    406449    nic_fields_template = [('nic%s_hostname', 'NIC %s hostname'),
     
    419462
    420463def getDiskInfo(data_dict, machine):
     464    """Helper function for info, get data on disks for a machine.
     465
     466    Modifies data_dict to include the relevant data, and returns a list
     467    of (key, name) pairs to display "name: data_dict[key]" to the user.
     468    """
    421469    data_dict['num_disks'] = len(machine.disks)
    422470    disk_fields_template = [('%s_size', '%s size')]
     
    429477
    430478def deleteVM(machine):
     479    """Delete a VM."""
    431480    transaction = ctx.current.create_transaction()
    432481    delete_disk_pairs = [(machine.name, d.guest_device_name) for d in machine.disks]
     
    448497
    449498def command(user, fields):
     499    """Handler for running commands like boot and delete on a VM."""
    450500    print time.time()-start_time
    451501    machine = testMachineId(user, fields.getfirst('machine_id'))
     
    454504    print time.time()-start_time
    455505    if cdrom is not None and not CDROM.get(cdrom):
    456         raise MyException("Invalid cdrom type '%s'" % cdrom)   
     506        raise CodeError("Invalid cdrom type '%s'" % cdrom)   
    457507    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 'Delete VM'):
    458         raise MyException("Invalid action '%s'" % action)
     508        raise CodeError("Invalid action '%s'" % action)
    459509    if action == 'Reboot':
    460510        if cdrom is not None:
     
    464514    elif action == 'Power on':
    465515        if maxMemory(user) < machine.memory:
    466             raise MyException("You don't have enough free RAM quota")
     516            raise InvalidInput("You don't have enough free RAM quota")
    467517        bootMachine(machine, cdrom)
    468518    elif action == 'Power off':
     
    480530       
    481531def modify(user, fields):
     532    """Handler for modifying attributes of a machine."""
     533    #XXX not written yet
    482534    machine = testMachineId(user, fields.getfirst('machine_id'))
    483535   
    484536def help(user, fields):
     537    """Handler for help messages."""
    485538    simple = fields.getfirst('simple')
    486539    subjects = fields.getlist('subject')
     
    505558
    506559def info(user, fields):
     560    """Handler for info on a single VM."""
    507561    machine = testMachineId(user, fields.getfirst('machine_id'))
    508562    status = statusInfo(machine)
     
    622676    try:
    623677        fun(u, fields)
    624     except MyException, err:
     678    except CodeError, err:
    625679        error(operation, u, fields, err)
     680    except InvalidInput, err:
     681        error(operation, u, fields, err)
Note: See TracChangeset for help on using the changeset viewer.