Changeset 133


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

Update

Location:
trunk/web/templates
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/web/templates/info.tmpl

    r113 r133  
    33
    44#def title
    5 Created!
     5Info on $machine.name
    66#end def
     7
    78
    89#def body
    910<h1>Info</h1>
    10 <p>Info on ${machine.name}.</p>
     11<p>Info on ${machine.name}:</p>
     12<table>
     13  #for $key, $value in $fields
     14  <tr><td>$key:</td><td>$value</td></tr>
     15  #end for
     16</table>
     17
     18<p>Commands:</p>
     19<form action="command">
     20  <input type="hidden" name="machine_id" value="$machine.machine_id"/>
     21  <table>
     22   
     23    <tr><td>
     24        #if $on
     25        #if $has_vnc
     26        <a href="vnc?machine_id=$machine.machine_id">Console</a>
     27        #else
     28        VNC is not enabled
     29        #end if
     30        #else
     31
     32        #end if
     33    </td></tr>
     34      <tr>
     35        #if $on
     36        <td><input type="submit" class="button" name="action" value="Power off"/></td>
     37        <td><input type="submit" class="button" name="action" value="Shutdown"/></td>
     38        <td><input type="submit" class="button" name="action" value="Reboot"/></td>
     39        #else
     40        <td><input type="submit" class="button" name="action" value="Power on"/></td>
     41        #end if
     42      <td>Boot CD:</td>
     43      <td><select name="cdrom">
     44          <option selected value="">None</option>
     45          #for $cdrom in $cdroms
     46          <option value="$cdrom.cdrom_id">
     47            $cdrom.description
     48          </option>
     49          #end for
     50      </select></td>
     51  </tr>
     52    <tr>
     53      <td><input type="submit" class="button" name="action" value="Delete VM"/></td>
     54    </tr>
     55  </table>
     56</form>
     57<p>Change settings:
     58#if $on
     59(To edit ram and disk size, turn off the machine first.)
     60#end if
     61</p>
     62<form action="modify">
     63  <input type="hidden" name="machine_id" value="$machine.machine_id"/>
     64  <table>
     65    <tr><td>Owner:</td><td><input type="text" value="$machine.owner"/></td></tr>
     66    <tr><td>Contact email:</td><td><input type="text" value="$machine.contact"/></td></tr>
     67#if $machine.nics
     68    <tr><td>Hostname:</td><td><input type="text" value="$machine.nics[0].hostname"/>.servers.csail.mit.edu</td></tr>
     69#end if
     70#if not $on
     71    <tr><td>Ram:</td><td><input type="text" size=3 value="$machine.memory"/>MB (max $maxmem)</td></tr>
     72    <tr><td>Disk:</td><td><input type="text" size=3 value="${machine.disks[0].size/1024.}"/>GB (max $maxdisk)</td></tr>
     73#end if
     74    <tr><td><input type="submit" class="button" name="action" value="Change"/></td></tr>
     75  </table>
     76</form>
     77
    1178#end def
  • trunk/web/templates/list.tmpl

    r113 r133  
    1919        <td>MAC Address</td>
    2020        <td>Hostname</td>
    21         <td>Status</td>
     21        <td>Uptime</td>
    2222        <td>VNC</td>
    2323        <td>Restart?</td>
     
    3737        <td></td>
    3838#end if
    39         <td>Good!</td>
    40         <td><a href="vnc?machine_id=$machine.machine_id">Console</a></td>
     39<td>#slurp
     40#if $uptimes.get($machine.name)
     41$uptimes[$machine.name]#slurp
     42#else
     43Off#slurp
     44#end if
     45</td>
     46        <td>#slurp
     47#if $has_vnc.get($machine.name)
     48<a href="vnc?machine_id=$machine.machine_id">Console</a>#slurp
     49#else
     50off#slurp
     51#end if
     52</td>
    4153        <td>
    42           <form action="restart">
     54          <form action="command">
    4355            <input type="hidden" name="machine_id"
    4456                   value="$machine.machine_id"/>
    4557            <input type="submit" class="button"
    46                    value="restart"/>
     58                   value="Reboot"/>
    4759          </form>
    4860        </td>
     
    5365
    5466    <p>Create a new VM:</p>
    55     <form action="create">
     67    <form action="create" method="POST">
    5668      <table>
    5769        <tr>
    5870          <td>Name</td>
    59           <td><input type="text" name="name" value="$user.username"/></td>
     71          <td>${user.username}_<input type="text" name="name" value=""/></td>
    6072        </tr>
    6173        <tr>
    62           #set $maxmem=256
    6374          <td>Memory</td>
    6475          <td><input type="text" name="memory" value="$maxmem" size=3/> megabytes ($maxmem max)</td>
    6576        </tr>
    6677        <tr>
    67           #set $maxdisk=1.5
    6878          <td>Disk</td>
    6979          <td><input type="text" name="disk" value="$maxdisk" size=3/> gigabytes ($maxdisk max)</td>
     
    7787        </tr>
    7888        <tr>
    79           <td>Initial Install</td>
     89          <td>Boot CD</td>
    8090          <td>
    8191            <select name="cdrom">
  • 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)
  • trunk/web/templates/vnc.tmpl

    r113 r133  
    1111<APPLET CODE="VncViewer.class" ARCHIVE="../VncViewer.jar"
    1212        WIDTH="800" HEIGHT="632">
     13<PARAM NAME="PASSWORD" VALUE="moocow">
    1314<PARAM NAME="PORT" VALUE="10003">
    1415<PARAM NAME="HOST" VALUE="$hostname">
Note: See TracChangeset for help on using the changeset viewer.