Changeset 145 for trunk/web/templates
- Timestamp:
- Oct 8, 2007, 7:17:34 AM (17 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/web/templates/main.py
r144 r145 22 22 23 23 class MyException(Exception): 24 """Base class for my exceptions""" 24 25 pass 25 26 27 class 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 36 class CodeError(MyException): 37 """Exception for internal errors or bad faith input.""" 38 pass 39 40 41 26 42 def helppopup(subj): 43 """Return HTML code for a (?) link to a specified help topic""" 27 44 return '<span class="helplink"><a href="help?subject='+subj+'&simple=true" target="_blank" onclick="return helppopup(\''+subj+'\')">(?)</a></span>' 28 45 … … 39 56 40 57 def uuidToString(u): 58 """Turn a numeric UUID to a hyphen-seperated one.""" 41 59 return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2, 42 60 "%02x" * 6]) % tuple(u) … … 51 69 MAX_VMS_ACTIVE = 4 52 70 53 def getMachinesOwner(owner): 71 def getMachinesByOwner(owner): 72 """Return the machines owned by a given owner.""" 54 73 return Machine.select_by(owner=owner) 55 74 56 75 def 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) 58 86 if on is None: 59 87 on = getUptimes(machines) … … 63 91 64 92 def maxDisk(user, machine=None): 65 machines = getMachines Owner(user.username)93 machines = getMachinesByOwner(user.username) 66 94 disk_usage = sum([sum([y.size for y in x.disks]) 67 95 for x in machines if x != machine]) … … 69 97 70 98 def canAddVm(user, on=None): 71 machines = getMachines Owner(user.username)99 machines = getMachinesByOwner(user.username) 72 100 if on is None: 73 101 on = getUptimes(machines) … … 77 105 78 106 def haveAccess(user, machine): 107 """Return whether a user has access to a machine""" 79 108 if user.username == 'moo': 80 109 return True … … 82 111 83 112 def error(op, user, fields, err): 113 """Print an error page when a CodeError occurs""" 84 114 d = dict(op=op, user=user, errorMessage=str(err)) 85 115 print Template(file='error.tmpl', searchList=[d, global_dict]); … … 104 134 e = p.wait() 105 135 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())) 107 137 108 138 def checkKinit(): … … 126 156 return p.stdout.read(), p.stderr.read() 127 157 if p.wait(): 128 raise MyException('ERROR on remctl %s: %s' %158 raise CodeError('ERROR on remctl %s: %s' % 129 159 (args, p.stderr.read())) 130 160 return p.stdout.read() … … 200 230 value_string, err_string = remctl('list-long', machine.name, err=True) 201 231 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,)) 203 233 elif 'does not exist' in err_string: 204 234 return None 205 235 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)) 207 237 status = parseStatus(value_string) 208 238 return status … … 224 254 try: 225 255 if memory > maxMemory(user): 226 raise MyException("Too much memory requested")256 raise InvalidInput("Too much memory requested") 227 257 if disk > maxDisk(user) * 1024: 228 raise MyException("Too much disk requested")258 raise InvalidInput("Too much disk requested") 229 259 if not canAddVm(user): 230 raise MyException("Too many VMs requested")260 raise InvalidInput("Too many VMs requested") 231 261 res = meta.engine.execute('select nextval(\'"machines_machine_id_seq"\')') 232 262 id = res.fetchone()[0] … … 246 276 open = NIC.select_by(machine_id=None) 247 277 if not open: #No IPs left! 248 r eturn "No IP addresses left! Contact sipb-xen-dev@mit.edu"278 raise CodeError("No IP addresses left! Contact sipb-xen-dev@mit.edu") 249 279 nic = open[0] 250 280 nic.machine_id = machine.machine_id … … 264 294 265 295 def validMemory(user, memory, machine=None): 296 """Parse and validate limits for memory for a given user and machine.""" 266 297 try: 267 298 memory = int(memory) … … 269 300 raise ValueError 270 301 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" % 272 303 MIN_MEMORY_SINGLE) 273 304 if memory > maxMemory(user, machine): 274 raise MyException("Too much memory requested")305 raise InvalidInput("Too much memory requested") 275 306 return memory 276 307 277 308 def validDisk(user, disk, machine=None): 309 """Parse and validate limits for disk for a given user and machine.""" 278 310 try: 279 311 disk = float(disk) 280 312 if disk > maxDisk(user, machine): 281 raise MyException("Too much disk requested")313 raise InvalidInput("Too much disk requested") 282 314 disk = int(disk * 1024) 283 315 if disk < MIN_DISK_SINGLE * 1024: 284 316 raise ValueError 285 317 except ValueError: 286 raise MyException("Invalid disk amount; minimum is %s GB" %318 raise InvalidInput("Invalid disk amount; minimum is %s GB" % 287 319 MIN_DISK_SINGLE) 288 320 return disk 289 321 290 322 def create(user, fields): 323 """Handler for create requests.""" 291 324 name = fields.getfirst('name') 292 325 if not validMachineName(name): 293 raise MyException("Invalid name '%s'" % name)326 raise InvalidInput("Invalid name '%s'" % name) 294 327 name = user.username + '_' + name.lower() 295 328 296 329 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) 298 331 299 332 memory = fields.getfirst('memory') … … 305 338 vm_type = fields.getfirst('vmtype') 306 339 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) 308 341 is_hvm = (vm_type == 'hvm') 309 342 310 343 cdrom = fields.getfirst('cdrom') 311 344 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) 313 346 314 347 machine = createVm(user, name, memory, disk, is_hvm, cdrom) 315 if isinstance(machine, basestring):316 raise MyException(machine)317 348 d = dict(user=user, 318 349 machine=machine) … … 321 352 322 353 def listVms(user, fields): 354 """Handler for list requests.""" 323 355 machines = [m for m in Machine.select() if haveAccess(user, m)] 324 356 on = {} … … 352 384 353 385 def 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 """ 354 390 if machineId is None: 355 raise MyException("No machine ID specified")391 raise CodeError("No machine ID specified") 356 392 try: 357 393 machineId = int(machineId) 358 394 except ValueError: 359 raise MyException("Invalid machine ID '%s'" % machineId)395 raise CodeError("Invalid machine ID '%s'" % machineId) 360 396 machine = Machine.get(machineId) 361 397 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) 365 401 return machine 366 402 … … 378 414 -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 379 415 -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 380 419 """ 381 420 machine = testMachineId(user, fields.getfirst('machine_id')) 382 #XXX fix383 421 384 422 TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN" … … 403 441 404 442 def 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 """ 405 448 data_dict['num_nics'] = len(machine.nics) 406 449 nic_fields_template = [('nic%s_hostname', 'NIC %s hostname'), … … 419 462 420 463 def 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 """ 421 469 data_dict['num_disks'] = len(machine.disks) 422 470 disk_fields_template = [('%s_size', '%s size')] … … 429 477 430 478 def deleteVM(machine): 479 """Delete a VM.""" 431 480 transaction = ctx.current.create_transaction() 432 481 delete_disk_pairs = [(machine.name, d.guest_device_name) for d in machine.disks] … … 448 497 449 498 def command(user, fields): 499 """Handler for running commands like boot and delete on a VM.""" 450 500 print time.time()-start_time 451 501 machine = testMachineId(user, fields.getfirst('machine_id')) … … 454 504 print time.time()-start_time 455 505 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) 457 507 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) 459 509 if action == 'Reboot': 460 510 if cdrom is not None: … … 464 514 elif action == 'Power on': 465 515 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") 467 517 bootMachine(machine, cdrom) 468 518 elif action == 'Power off': … … 480 530 481 531 def modify(user, fields): 532 """Handler for modifying attributes of a machine.""" 533 #XXX not written yet 482 534 machine = testMachineId(user, fields.getfirst('machine_id')) 483 535 484 536 def help(user, fields): 537 """Handler for help messages.""" 485 538 simple = fields.getfirst('simple') 486 539 subjects = fields.getlist('subject') … … 505 558 506 559 def info(user, fields): 560 """Handler for info on a single VM.""" 507 561 machine = testMachineId(user, fields.getfirst('machine_id')) 508 562 status = statusInfo(machine) … … 622 676 try: 623 677 fun(u, fields) 624 except MyException, err:678 except CodeError, err: 625 679 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.