Index: trunk/web/templates/info.tmpl
===================================================================
--- trunk/web/templates/info.tmpl	(revision 120)
+++ trunk/web/templates/info.tmpl	(revision 133)
@@ -3,9 +3,76 @@
 
 #def title
-Created!
+Info on $machine.name
 #end def
+
 
 #def body
 <h1>Info</h1>
-<p>Info on ${machine.name}.</p>
+<p>Info on ${machine.name}:</p>
+<table>
+  #for $key, $value in $fields
+  <tr><td>$key:</td><td>$value</td></tr>
+  #end for
+</table>
+
+<p>Commands:</p>
+<form action="command">
+  <input type="hidden" name="machine_id" value="$machine.machine_id"/>
+  <table>
+    
+    <tr><td>
+	#if $on
+	#if $has_vnc
+	<a href="vnc?machine_id=$machine.machine_id">Console</a>
+	#else
+	VNC is not enabled
+	#end if
+	#else
+
+	#end if
+    </td></tr>
+      <tr>
+	#if $on
+	<td><input type="submit" class="button" name="action" value="Power off"/></td>
+	<td><input type="submit" class="button" name="action" value="Shutdown"/></td>
+	<td><input type="submit" class="button" name="action" value="Reboot"/></td>
+	#else
+	<td><input type="submit" class="button" name="action" value="Power on"/></td>
+	#end if
+      <td>Boot CD:</td>
+      <td><select name="cdrom">
+	  <option selected value="">None</option>
+	  #for $cdrom in $cdroms
+	  <option value="$cdrom.cdrom_id">
+	    $cdrom.description
+	  </option>
+	  #end for
+      </select></td>
+  </tr>
+    <tr>
+      <td><input type="submit" class="button" name="action" value="Delete VM"/></td>
+    </tr>
+  </table>
+</form>
+<p>Change settings:
+#if $on
+(To edit ram and disk size, turn off the machine first.)
+#end if
+</p>
+<form action="modify">
+  <input type="hidden" name="machine_id" value="$machine.machine_id"/>
+  <table>
+    <tr><td>Owner:</td><td><input type="text" value="$machine.owner"/></td></tr>
+    <tr><td>Contact email:</td><td><input type="text" value="$machine.contact"/></td></tr>
+#if $machine.nics
+    <tr><td>Hostname:</td><td><input type="text" value="$machine.nics[0].hostname"/>.servers.csail.mit.edu</td></tr>
+#end if
+#if not $on
+    <tr><td>Ram:</td><td><input type="text" size=3 value="$machine.memory"/>MB (max $maxmem)</td></tr>
+    <tr><td>Disk:</td><td><input type="text" size=3 value="${machine.disks[0].size/1024.}"/>GB (max $maxdisk)</td></tr>
+#end if
+    <tr><td><input type="submit" class="button" name="action" value="Change"/></td></tr>
+  </table>
+</form>
+
 #end def
Index: trunk/web/templates/list.tmpl
===================================================================
--- trunk/web/templates/list.tmpl	(revision 120)
+++ trunk/web/templates/list.tmpl	(revision 133)
@@ -19,5 +19,5 @@
 	<td>MAC Address</td>
 	<td>Hostname</td>
-	<td>Status</td>
+	<td>Uptime</td>
 	<td>VNC</td>
 	<td>Restart?</td>
@@ -37,12 +37,24 @@
 	<td></td>
 #end if
-	<td>Good!</td>
-	<td><a href="vnc?machine_id=$machine.machine_id">Console</a></td>
+<td>#slurp
+#if $uptimes.get($machine.name)
+$uptimes[$machine.name]#slurp
+#else
+Off#slurp
+#end if
+</td>
+	<td>#slurp
+#if $has_vnc.get($machine.name)
+<a href="vnc?machine_id=$machine.machine_id">Console</a>#slurp
+#else
+off#slurp
+#end if
+</td>
 	<td>
-	  <form action="restart">
+	  <form action="command">
 	    <input type="hidden" name="machine_id"
 		   value="$machine.machine_id"/>
 	    <input type="submit" class="button"
-		   value="restart"/>
+		   value="Reboot"/>
 	  </form>
 	</td>
@@ -53,17 +65,15 @@
 
     <p>Create a new VM:</p>
-    <form action="create">
+    <form action="create" method="POST">
       <table>
 	<tr>
 	  <td>Name</td>
-	  <td><input type="text" name="name" value="$user.username"/></td>
+	  <td>${user.username}_<input type="text" name="name" value=""/></td>
 	</tr>
 	<tr>
-	  #set $maxmem=256
 	  <td>Memory</td>
 	  <td><input type="text" name="memory" value="$maxmem" size=3/> megabytes ($maxmem max)</td>
 	</tr>
 	<tr>
-	  #set $maxdisk=1.5
 	  <td>Disk</td>
 	  <td><input type="text" name="disk" value="$maxdisk" size=3/> gigabytes ($maxdisk max)</td>
@@ -77,5 +87,5 @@
 	</tr>
 	<tr>
-	  <td>Initial Install</td>
+	  <td>Boot CD</td>
 	  <td>
 	    <select name="cdrom">
Index: trunk/web/templates/main.py
===================================================================
--- trunk/web/templates/main.py	(revision 120)
+++ trunk/web/templates/main.py	(revision 133)
@@ -12,4 +12,5 @@
 import sha
 import hmac
+import datetime
 
 print 'Content-Type: text/html\n'
@@ -34,8 +35,8 @@
                      "%02x" * 6]) % tuple(u)
 
-def maxMemory(user):
+def maxMemory(user, machine=None):
     return 256
 
-def maxDisk(user):
+def maxDisk(user, machine=None):
     return 10.0
 
@@ -59,8 +60,9 @@
     """Kinit with a given username and keytab"""
 
-    p = subprocess.Popen(['kinit', "-k", "-t", keytab, username])
+    p = subprocess.Popen(['kinit', "-k", "-t", keytab, username],
+                         stderr=subprocess.PIPE)
     e = p.wait()
     if e:
-        raise MyException("Error %s in kinit" % e)
+        raise MyException("Error %s in kinit: %s" % (e, p.stderr.read()))
 
 def checkKinit():
@@ -107,4 +109,8 @@
     remctl('web', 'register', machine.name)
 
+def unregisterMachine(machine):
+    """Unregister a machine to not be controlled by the web interface"""
+    remctl('web', 'unregister', machine.name)
+
 def parseStatus(s):
     """Parse a status string into nested tuples of strings.
@@ -121,4 +127,6 @@
             stack.append([])
         elif v == ')':
+            if len(stack[-1]) == 1:
+                stack[-1].append('')
             stack[-2].append(stack[-1])
             stack.pop()
@@ -129,5 +137,21 @@
     return stack[-1]
 
+def getUptimes(machines):
+    """Return a dictionary mapping machine names to uptime strings"""
+    value_string = remctl('web', 'listvms')
+    lines = value_string.splitlines()
+    d = {}
+    for line in lines[1:]:
+        lst = line.split()
+        name, id = lst[:2]
+        uptime = ' '.join(lst[2:])
+        d[name] = uptime
+    return d
+
 def statusInfo(machine):
+    """Return the status list for a given machine.
+
+    Gets and parses xm list --long
+    """
     value_string, err_string = remctl('list-long', machine.name, err=True)
     if 'Unknown command' in err_string:
@@ -141,4 +165,5 @@
 
 def hasVnc(status):
+    """Does the machine with a given status list support VNC?"""
     if status is None:
         return False
@@ -150,4 +175,5 @@
 
 def createVm(user, name, memory, disk, is_hvm, cdrom):
+    """Create a VM and put it in the database"""
     # put stuff in the table
     transaction = ctx.current.create_transaction()
@@ -191,5 +217,5 @@
     if not validMachineName(name):
         raise MyException("Invalid name '%s'" % name)
-    name = name.lower()
+    name = user.username + '_' + name.lower()
 
     if Machine.get_by(name=name):
@@ -209,4 +235,6 @@
     try:
         disk = float(disk)
+        if disk > maxDisk(user):
+            raise MyException("Too much disk requested")
         disk = int(disk * 1024)
         if disk <= 0:
@@ -214,6 +242,4 @@
     except ValueError:
         raise MyException("Invalid disk amount")
-    if disk > maxDisk(user):
-        raise MyException("Too much disk requested")
     
     vm_type = fields.getfirst('vmtype')
@@ -236,15 +262,18 @@
 def listVms(user, fields):
     machines = Machine.select()
-    status = statusInfo(machines)
+    on = {}
     has_vnc = {}
-    for m in machines:
-        on[m.name] = status[m.name] is not None
-        has_vnc[m.name] = hasVnc(status[m.name])
+    uptimes = getUptimes(machines)
+    on = has_vnc = uptimes
+    #     for m in machines:
+    #         status = statusInfo(m)
+    #         on[m.name] = status is not None
+    #         has_vnc[m.name] = hasVnc(status)
     d = dict(user=user,
              maxmem=maxMemory(user),
              maxdisk=maxDisk(user),
              machines=machines,
-             status=status,
              has_vnc=has_vnc,
+             uptimes=uptimes,
              cdroms=CDROM.select())
     print Template(file='list.tmpl', searchList=d)
@@ -284,5 +313,5 @@
 
     data = {}
-    data["user"] = user
+    data["user"] = user.username
     data["machine"]=machine.name
     data["expires"]=time.time()+(5*60)
@@ -301,8 +330,150 @@
                    searchList=d)
 
+def getNicInfo(data_dict, machine):
+    data_dict['num_nics'] = len(machine.nics)
+    nic_fields_template = [('nic%s_hostname', 'NIC %s hostname'),
+                           ('nic%s_mac', 'NIC %s MAC Addr'),
+                           ('nic%s_ip', 'NIC %s IP'),
+                           ]
+    nic_fields = []
+    for i in range(len(machine.nics)):
+        nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template])
+        data_dict['nic%s_hostname' % i] = machine.nics[i].hostname + '.servers.csail.mit.edu'
+        data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr
+        data_dict['nic%s_ip' % i] = machine.nics[i].ip
+    if len(machine.nics) == 1:
+        nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields]
+    return nic_fields
+
+def getDiskInfo(data_dict, machine):
+    data_dict['num_disks'] = len(machine.disks)
+    disk_fields_template = [('%s_size', '%s size')]
+    disk_fields = []
+    for disk in machine.disks:
+        name = disk.guest_device_name
+        disk_fields.extend([(x % name, y % name) for x, y in disk_fields_template])
+        data_dict['%s_size' % name] = "%0.1f GB" % (disk.size / 1024.)
+    return disk_fields
+
+def deleteVM(machine):
+    transaction = ctx.current.create_transaction()
+    delete_disk_pairs = [(machine.name, d.guest_device_name) for d in machine.disks]
+    try:
+        for nic in machine.nics:
+            nic.machine_id = None
+            nic.hostname = None
+            ctx.current.save(nic)
+        for disk in machine.disks:
+            ctx.current.delete(disk)
+        ctx.current.delete(machine)
+        transaction.commit()
+    except:
+        transaction.rollback()
+        raise
+    for mname, dname in delete_disk_pairs:
+        remctl('web', 'lvremove', mname, dname)
+    unregisterMachine(machine)
+
+def command(user, fields):
+    print time.time()-start_time
+    machine = testMachineId(user, fields.getfirst('machine_id'))
+    action = fields.getfirst('action')
+    cdrom = fields.getfirst('cdrom')
+    print time.time()-start_time
+    if cdrom is not None and not CDROM.get(cdrom):
+        raise MyException("Invalid cdrom type '%s'" % cdrom)    
+    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 'Delete VM'):
+        raise MyException("Invalid action '%s'" % action)
+    if action == 'Reboot':
+        if cdrom is not None:
+            remctl('reboot', machine.name, cdrom)
+        else:
+            remctl('reboot', machine.name)
+    elif action == 'Power on':
+        bootMachine(machine, cdrom)
+    elif action == 'Power off':
+        remctl('destroy', machine.name)
+    elif action == 'Shutdown':
+        remctl('shutdown', machine.name)
+    elif action == 'Delete VM':
+        deleteVM(machine)
+    print time.time()-start_time
+
+    d = dict(user=user,
+             command=action,
+             machine=machine)
+    print Template(file="command.tmpl", searchList=d)
+        
+def modify(user, fields):
+    machine = testMachineId(user, fields.getfirst('machine_id'))
+    
+
 def info(user, fields):
     machine = testMachineId(user, fields.getfirst('machine_id'))
+    status = statusInfo(machine)
+    has_vnc = hasVnc(status)
+    if status is None:
+        main_status = dict(name=machine.name,
+                           memory=str(machine.memory))
+    else:
+        main_status = dict(status[1:])
+    start_time = float(main_status.get('start_time', 0))
+    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))
+    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'),
+                      ('owner', 'Owner'),
+                      ('contact', 'Contact'),
+                      'NIC_INFO',
+                      ('uptime', 'uptime'),
+                      ('cputime', 'CPU usage'),
+                      ('memory', 'RAM'),
+                      'DISK_INFO',
+                      ('state', 'state (xen format)'),
+                      ('cpu_weight', 'CPU weight'),
+                      ('on_reboot', 'Action on VM reboot'),
+                      ('on_poweroff', 'Action on VM poweroff'),
+                      ('on_crash', 'Action on VM crash'),
+                      ('on_xend_start', 'Action on Xen start'),
+                      ('on_xend_stop', 'Action on Xen stop'),
+                      ('bootloader', 'Bootloader options'),
+                      ]
+    fields = []
+    machine_info = {}
+    machine_info['owner'] = machine.owner
+    machine_info['contact'] = machine.contact
+
+    nic_fields = getNicInfo(machine_info, machine)
+    nic_point = display_fields.index('NIC_INFO')
+    display_fields = display_fields[:nic_point] + nic_fields + display_fields[nic_point+1:]
+
+    disk_fields = getDiskInfo(machine_info, machine)
+    disk_point = display_fields.index('DISK_INFO')
+    display_fields = display_fields[:disk_point] + disk_fields + display_fields[disk_point+1:]
+    
+    main_status['memory'] += ' MB'
+    for field, disp in display_fields:
+        if field in ('uptime', 'cputime'):
+            fields.append((disp, locals()[field]))
+        elif field in main_status:
+            fields.append((disp, main_status[field]))
+        elif field in machine_info:
+            fields.append((disp, machine_info[field]))
+        else:
+            pass
+            #fields.append((disp, None))
+
     d = dict(user=user,
-             machine=machine)
+             cdroms=CDROM.select(),
+             on=status is not None,
+             machine=machine,
+             has_vnc=has_vnc,
+             uptime=str(uptime),
+             ram=machine.memory,
+             maxmem=maxMemory(user, machine),
+             maxdisk=maxDisk(user, machine),
+             fields = fields)
     print Template(file='info.tmpl',
                    searchList=d)
@@ -310,13 +481,16 @@
 mapping = dict(list=listVms,
                vnc=vnc,
+               command=command,
+               modify=modify,
                info=info,
                create=create)
 
 if __name__ == '__main__':
+    start_time = time.time()
     fields = cgi.FieldStorage()
-    class C:
+    class User:
         username = "moo"
         email = 'moo@cow.com'
-    u = C()
+    u = User()
     connect('postgres://sipb-xen@sipb-xen-dev/sipb_xen')
     operation = os.environ.get('PATH_INFO', '')
@@ -333,5 +507,5 @@
                       lambda u, e:
                           error(operation, u, e,
-                                "Invalid operation '%'" % operation))
+                                "Invalid operation '%s'" % operation))
     try:
         fun(u, fields)
Index: trunk/web/templates/vnc.tmpl
===================================================================
--- trunk/web/templates/vnc.tmpl	(revision 120)
+++ trunk/web/templates/vnc.tmpl	(revision 133)
@@ -11,4 +11,5 @@
 <APPLET CODE="VncViewer.class" ARCHIVE="../VncViewer.jar"
         WIDTH="800" HEIGHT="632">
+<PARAM NAME="PASSWORD" VALUE="moocow">
 <PARAM NAME="PORT" VALUE="10003">
 <PARAM NAME="HOST" VALUE="$hostname">
