Ignore:
Timestamp:
Oct 8, 2007, 1:22:35 AM (17 years ago)
Author:
ecprice
Message:

Update

File:
1 edited

Legend:

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

    r120 r133  
    1212import sha
    1313import hmac
     14import datetime
    1415
    1516print 'Content-Type: text/html\n'
     
    3435                     "%02x" * 6]) % tuple(u)
    3536
    36 def maxMemory(user):
     37def maxMemory(user, machine=None):
    3738    return 256
    3839
    39 def maxDisk(user):
     40def maxDisk(user, machine=None):
    4041    return 10.0
    4142
     
    5960    """Kinit with a given username and keytab"""
    6061
    61     p = subprocess.Popen(['kinit', "-k", "-t", keytab, username])
     62    p = subprocess.Popen(['kinit', "-k", "-t", keytab, username],
     63                         stderr=subprocess.PIPE)
    6264    e = p.wait()
    6365    if e:
    64         raise MyException("Error %s in kinit" % e)
     66        raise MyException("Error %s in kinit: %s" % (e, p.stderr.read()))
    6567
    6668def checkKinit():
     
    107109    remctl('web', 'register', machine.name)
    108110
     111def unregisterMachine(machine):
     112    """Unregister a machine to not be controlled by the web interface"""
     113    remctl('web', 'unregister', machine.name)
     114
    109115def parseStatus(s):
    110116    """Parse a status string into nested tuples of strings.
     
    121127            stack.append([])
    122128        elif v == ')':
     129            if len(stack[-1]) == 1:
     130                stack[-1].append('')
    123131            stack[-2].append(stack[-1])
    124132            stack.pop()
     
    129137    return stack[-1]
    130138
     139def getUptimes(machines):
     140    """Return a dictionary mapping machine names to uptime strings"""
     141    value_string = remctl('web', 'listvms')
     142    lines = value_string.splitlines()
     143    d = {}
     144    for line in lines[1:]:
     145        lst = line.split()
     146        name, id = lst[:2]
     147        uptime = ' '.join(lst[2:])
     148        d[name] = uptime
     149    return d
     150
    131151def statusInfo(machine):
     152    """Return the status list for a given machine.
     153
     154    Gets and parses xm list --long
     155    """
    132156    value_string, err_string = remctl('list-long', machine.name, err=True)
    133157    if 'Unknown command' in err_string:
     
    141165
    142166def hasVnc(status):
     167    """Does the machine with a given status list support VNC?"""
    143168    if status is None:
    144169        return False
     
    150175
    151176def createVm(user, name, memory, disk, is_hvm, cdrom):
     177    """Create a VM and put it in the database"""
    152178    # put stuff in the table
    153179    transaction = ctx.current.create_transaction()
     
    191217    if not validMachineName(name):
    192218        raise MyException("Invalid name '%s'" % name)
    193     name = name.lower()
     219    name = user.username + '_' + name.lower()
    194220
    195221    if Machine.get_by(name=name):
     
    209235    try:
    210236        disk = float(disk)
     237        if disk > maxDisk(user):
     238            raise MyException("Too much disk requested")
    211239        disk = int(disk * 1024)
    212240        if disk <= 0:
     
    214242    except ValueError:
    215243        raise MyException("Invalid disk amount")
    216     if disk > maxDisk(user):
    217         raise MyException("Too much disk requested")
    218244   
    219245    vm_type = fields.getfirst('vmtype')
     
    236262def listVms(user, fields):
    237263    machines = Machine.select()
    238     status = statusInfo(machines)
     264    on = {}
    239265    has_vnc = {}
    240     for m in machines:
    241         on[m.name] = status[m.name] is not None
    242         has_vnc[m.name] = hasVnc(status[m.name])
     266    uptimes = getUptimes(machines)
     267    on = has_vnc = uptimes
     268    #     for m in machines:
     269    #         status = statusInfo(m)
     270    #         on[m.name] = status is not None
     271    #         has_vnc[m.name] = hasVnc(status)
    243272    d = dict(user=user,
    244273             maxmem=maxMemory(user),
    245274             maxdisk=maxDisk(user),
    246275             machines=machines,
    247              status=status,
    248276             has_vnc=has_vnc,
     277             uptimes=uptimes,
    249278             cdroms=CDROM.select())
    250279    print Template(file='list.tmpl', searchList=d)
     
    284313
    285314    data = {}
    286     data["user"] = user
     315    data["user"] = user.username
    287316    data["machine"]=machine.name
    288317    data["expires"]=time.time()+(5*60)
     
    301330                   searchList=d)
    302331
     332def getNicInfo(data_dict, machine):
     333    data_dict['num_nics'] = len(machine.nics)
     334    nic_fields_template = [('nic%s_hostname', 'NIC %s hostname'),
     335                           ('nic%s_mac', 'NIC %s MAC Addr'),
     336                           ('nic%s_ip', 'NIC %s IP'),
     337                           ]
     338    nic_fields = []
     339    for i in range(len(machine.nics)):
     340        nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template])
     341        data_dict['nic%s_hostname' % i] = machine.nics[i].hostname + '.servers.csail.mit.edu'
     342        data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr
     343        data_dict['nic%s_ip' % i] = machine.nics[i].ip
     344    if len(machine.nics) == 1:
     345        nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields]
     346    return nic_fields
     347
     348def getDiskInfo(data_dict, machine):
     349    data_dict['num_disks'] = len(machine.disks)
     350    disk_fields_template = [('%s_size', '%s size')]
     351    disk_fields = []
     352    for disk in machine.disks:
     353        name = disk.guest_device_name
     354        disk_fields.extend([(x % name, y % name) for x, y in disk_fields_template])
     355        data_dict['%s_size' % name] = "%0.1f GB" % (disk.size / 1024.)
     356    return disk_fields
     357
     358def deleteVM(machine):
     359    transaction = ctx.current.create_transaction()
     360    delete_disk_pairs = [(machine.name, d.guest_device_name) for d in machine.disks]
     361    try:
     362        for nic in machine.nics:
     363            nic.machine_id = None
     364            nic.hostname = None
     365            ctx.current.save(nic)
     366        for disk in machine.disks:
     367            ctx.current.delete(disk)
     368        ctx.current.delete(machine)
     369        transaction.commit()
     370    except:
     371        transaction.rollback()
     372        raise
     373    for mname, dname in delete_disk_pairs:
     374        remctl('web', 'lvremove', mname, dname)
     375    unregisterMachine(machine)
     376
     377def command(user, fields):
     378    print time.time()-start_time
     379    machine = testMachineId(user, fields.getfirst('machine_id'))
     380    action = fields.getfirst('action')
     381    cdrom = fields.getfirst('cdrom')
     382    print time.time()-start_time
     383    if cdrom is not None and not CDROM.get(cdrom):
     384        raise MyException("Invalid cdrom type '%s'" % cdrom)   
     385    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 'Delete VM'):
     386        raise MyException("Invalid action '%s'" % action)
     387    if action == 'Reboot':
     388        if cdrom is not None:
     389            remctl('reboot', machine.name, cdrom)
     390        else:
     391            remctl('reboot', machine.name)
     392    elif action == 'Power on':
     393        bootMachine(machine, cdrom)
     394    elif action == 'Power off':
     395        remctl('destroy', machine.name)
     396    elif action == 'Shutdown':
     397        remctl('shutdown', machine.name)
     398    elif action == 'Delete VM':
     399        deleteVM(machine)
     400    print time.time()-start_time
     401
     402    d = dict(user=user,
     403             command=action,
     404             machine=machine)
     405    print Template(file="command.tmpl", searchList=d)
     406       
     407def modify(user, fields):
     408    machine = testMachineId(user, fields.getfirst('machine_id'))
     409   
     410
    303411def info(user, fields):
    304412    machine = testMachineId(user, fields.getfirst('machine_id'))
     413    status = statusInfo(machine)
     414    has_vnc = hasVnc(status)
     415    if status is None:
     416        main_status = dict(name=machine.name,
     417                           memory=str(machine.memory))
     418    else:
     419        main_status = dict(status[1:])
     420    start_time = float(main_status.get('start_time', 0))
     421    uptime = datetime.timedelta(seconds=int(time.time()-start_time))
     422    cpu_time_float = float(main_status.get('cpu_time', 0))
     423    cputime = datetime.timedelta(seconds=int(cpu_time_float))
     424    display_fields = """name uptime memory state cpu_weight on_reboot
     425     on_poweroff on_crash on_xend_start on_xend_stop bootloader""".split()
     426    display_fields = [('name', 'Name'),
     427                      ('owner', 'Owner'),
     428                      ('contact', 'Contact'),
     429                      'NIC_INFO',
     430                      ('uptime', 'uptime'),
     431                      ('cputime', 'CPU usage'),
     432                      ('memory', 'RAM'),
     433                      'DISK_INFO',
     434                      ('state', 'state (xen format)'),
     435                      ('cpu_weight', 'CPU weight'),
     436                      ('on_reboot', 'Action on VM reboot'),
     437                      ('on_poweroff', 'Action on VM poweroff'),
     438                      ('on_crash', 'Action on VM crash'),
     439                      ('on_xend_start', 'Action on Xen start'),
     440                      ('on_xend_stop', 'Action on Xen stop'),
     441                      ('bootloader', 'Bootloader options'),
     442                      ]
     443    fields = []
     444    machine_info = {}
     445    machine_info['owner'] = machine.owner
     446    machine_info['contact'] = machine.contact
     447
     448    nic_fields = getNicInfo(machine_info, machine)
     449    nic_point = display_fields.index('NIC_INFO')
     450    display_fields = display_fields[:nic_point] + nic_fields + display_fields[nic_point+1:]
     451
     452    disk_fields = getDiskInfo(machine_info, machine)
     453    disk_point = display_fields.index('DISK_INFO')
     454    display_fields = display_fields[:disk_point] + disk_fields + display_fields[disk_point+1:]
     455   
     456    main_status['memory'] += ' MB'
     457    for field, disp in display_fields:
     458        if field in ('uptime', 'cputime'):
     459            fields.append((disp, locals()[field]))
     460        elif field in main_status:
     461            fields.append((disp, main_status[field]))
     462        elif field in machine_info:
     463            fields.append((disp, machine_info[field]))
     464        else:
     465            pass
     466            #fields.append((disp, None))
     467
    305468    d = dict(user=user,
    306              machine=machine)
     469             cdroms=CDROM.select(),
     470             on=status is not None,
     471             machine=machine,
     472             has_vnc=has_vnc,
     473             uptime=str(uptime),
     474             ram=machine.memory,
     475             maxmem=maxMemory(user, machine),
     476             maxdisk=maxDisk(user, machine),
     477             fields = fields)
    307478    print Template(file='info.tmpl',
    308479                   searchList=d)
     
    310481mapping = dict(list=listVms,
    311482               vnc=vnc,
     483               command=command,
     484               modify=modify,
    312485               info=info,
    313486               create=create)
    314487
    315488if __name__ == '__main__':
     489    start_time = time.time()
    316490    fields = cgi.FieldStorage()
    317     class C:
     491    class User:
    318492        username = "moo"
    319493        email = 'moo@cow.com'
    320     u = C()
     494    u = User()
    321495    connect('postgres://sipb-xen@sipb-xen-dev/sipb_xen')
    322496    operation = os.environ.get('PATH_INFO', '')
     
    333507                      lambda u, e:
    334508                          error(operation, u, e,
    335                                 "Invalid operation '%'" % operation))
     509                                "Invalid operation '%s'" % operation))
    336510    try:
    337511        fun(u, fields)
Note: See TracChangeset for help on using the changeset viewer.