Changeset 133 for trunk/web/templates/main.py
- Timestamp:
- Oct 8, 2007, 1:22:35 AM (18 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/web/templates/main.py
r120 r133 12 12 import sha 13 13 import hmac 14 import datetime 14 15 15 16 print 'Content-Type: text/html\n' … … 34 35 "%02x" * 6]) % tuple(u) 35 36 36 def maxMemory(user ):37 def maxMemory(user, machine=None): 37 38 return 256 38 39 39 def maxDisk(user ):40 def maxDisk(user, machine=None): 40 41 return 10.0 41 42 … … 59 60 """Kinit with a given username and keytab""" 60 61 61 p = subprocess.Popen(['kinit', "-k", "-t", keytab, username]) 62 p = subprocess.Popen(['kinit', "-k", "-t", keytab, username], 63 stderr=subprocess.PIPE) 62 64 e = p.wait() 63 65 if e: 64 raise MyException("Error %s in kinit " % e)66 raise MyException("Error %s in kinit: %s" % (e, p.stderr.read())) 65 67 66 68 def checkKinit(): … … 107 109 remctl('web', 'register', machine.name) 108 110 111 def unregisterMachine(machine): 112 """Unregister a machine to not be controlled by the web interface""" 113 remctl('web', 'unregister', machine.name) 114 109 115 def parseStatus(s): 110 116 """Parse a status string into nested tuples of strings. … … 121 127 stack.append([]) 122 128 elif v == ')': 129 if len(stack[-1]) == 1: 130 stack[-1].append('') 123 131 stack[-2].append(stack[-1]) 124 132 stack.pop() … … 129 137 return stack[-1] 130 138 139 def 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 131 151 def statusInfo(machine): 152 """Return the status list for a given machine. 153 154 Gets and parses xm list --long 155 """ 132 156 value_string, err_string = remctl('list-long', machine.name, err=True) 133 157 if 'Unknown command' in err_string: … … 141 165 142 166 def hasVnc(status): 167 """Does the machine with a given status list support VNC?""" 143 168 if status is None: 144 169 return False … … 150 175 151 176 def createVm(user, name, memory, disk, is_hvm, cdrom): 177 """Create a VM and put it in the database""" 152 178 # put stuff in the table 153 179 transaction = ctx.current.create_transaction() … … 191 217 if not validMachineName(name): 192 218 raise MyException("Invalid name '%s'" % name) 193 name = name.lower()219 name = user.username + '_' + name.lower() 194 220 195 221 if Machine.get_by(name=name): … … 209 235 try: 210 236 disk = float(disk) 237 if disk > maxDisk(user): 238 raise MyException("Too much disk requested") 211 239 disk = int(disk * 1024) 212 240 if disk <= 0: … … 214 242 except ValueError: 215 243 raise MyException("Invalid disk amount") 216 if disk > maxDisk(user):217 raise MyException("Too much disk requested")218 244 219 245 vm_type = fields.getfirst('vmtype') … … 236 262 def listVms(user, fields): 237 263 machines = Machine.select() 238 status = statusInfo(machines)264 on = {} 239 265 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) 243 272 d = dict(user=user, 244 273 maxmem=maxMemory(user), 245 274 maxdisk=maxDisk(user), 246 275 machines=machines, 247 status=status,248 276 has_vnc=has_vnc, 277 uptimes=uptimes, 249 278 cdroms=CDROM.select()) 250 279 print Template(file='list.tmpl', searchList=d) … … 284 313 285 314 data = {} 286 data["user"] = user 315 data["user"] = user.username 287 316 data["machine"]=machine.name 288 317 data["expires"]=time.time()+(5*60) … … 301 330 searchList=d) 302 331 332 def 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 348 def 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 358 def 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 377 def 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 407 def modify(user, fields): 408 machine = testMachineId(user, fields.getfirst('machine_id')) 409 410 303 411 def info(user, fields): 304 412 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 305 468 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) 307 478 print Template(file='info.tmpl', 308 479 searchList=d) … … 310 481 mapping = dict(list=listVms, 311 482 vnc=vnc, 483 command=command, 484 modify=modify, 312 485 info=info, 313 486 create=create) 314 487 315 488 if __name__ == '__main__': 489 start_time = time.time() 316 490 fields = cgi.FieldStorage() 317 class C:491 class User: 318 492 username = "moo" 319 493 email = 'moo@cow.com' 320 u = C()494 u = User() 321 495 connect('postgres://sipb-xen@sipb-xen-dev/sipb_xen') 322 496 operation = os.environ.get('PATH_INFO', '') … … 333 507 lambda u, e: 334 508 error(operation, u, e, 335 "Invalid operation '% '" % operation))509 "Invalid operation '%s'" % operation)) 336 510 try: 337 511 fun(u, fields)
Note: See TracChangeset
for help on using the changeset viewer.