Changeset 572 for trunk/packages/sipb-xen-www/code/main.py
- Timestamp:
- Jun 2, 2008, 11:25:47 PM (16 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/packages/sipb-xen-www/code/main.py
r566 r572 42 42 import validation 43 43 import cache_acls 44 from webcommon import InvalidInput, CodeError, g44 from webcommon import InvalidInput, CodeError, state 45 45 import controls 46 46 … … 120 120 DEFAULT_HEADERS = {'Content-Type': 'text/html'} 121 121 122 def error(op, user , fields, err, emsg):122 def error(op, username, fields, err, emsg): 123 123 """Print an error page when a CodeError occurs""" 124 d = dict(op=op, user=user , errorMessage=str(err),124 d = dict(op=op, user=username, errorMessage=str(err), 125 125 stderr=emsg) 126 126 return templates.error(searchList=[d]) 127 127 128 def invalidInput(op, user , fields, err, emsg):128 def invalidInput(op, username, fields, err, emsg): 129 129 """Print an error page when an InvalidInput exception occurs""" 130 d = dict(op=op, user=user , err_field=err.err_field,130 d = dict(op=op, user=username, err_field=err.err_field, 131 131 err_value=str(err.err_value), stderr=emsg, 132 132 errorMessage=str(err)) … … 143 143 return False 144 144 145 def parseCreate(user, fields): 146 name = fields.getfirst('name') 147 if not validation.validMachineName(name): 148 raise InvalidInput('name', name, 'You must provide a machine name. Max 22 chars, alnum plus \'-\' and \'_\'.') 149 name = name.lower() 150 151 if Machine.get_by(name=name): 152 raise InvalidInput('name', name, 153 "Name already exists.") 154 155 owner = validation.testOwner(user, fields.getfirst('owner')) 156 157 memory = fields.getfirst('memory') 158 memory = validation.validMemory(owner, memory, on=True) 159 160 disk_size = fields.getfirst('disk') 161 disk_size = validation.validDisk(owner, disk_size) 162 163 vm_type = fields.getfirst('vmtype') 164 vm_type = validation.validVmType(vm_type) 165 166 cdrom = fields.getfirst('cdrom') 167 if cdrom is not None and not CDROM.get(cdrom): 168 raise CodeError("Invalid cdrom type '%s'" % cdrom) 169 170 clone_from = fields.getfirst('clone_from') 171 if clone_from and clone_from != 'ice3': 172 raise CodeError("Invalid clone image '%s'" % clone_from) 173 174 return dict(contact=user, name=name, memory=memory, disk_size=disk_size, 175 owner=owner, machine_type=vm_type, cdrom=cdrom, clone_from=clone_from) 176 177 def create(user, fields): 145 def parseCreate(username, state, fields): 146 kws = dict([(kw, fields.getfirst(kw)) for kw in 'name owner memory disksize vmtype cdrom clone_from'.split()]) 147 validate = validation.Validate(username, state, **kws) 148 return dict(contact=username, name=validate.name, memory=validate.memory, 149 disksize=validate.disksize, owner=validate.owner, machine_type=validate.vmtype, 150 cdrom=getattr(validate, 'cdrom', None), 151 clone_from=getattr(validate, 'clone_from', None)) 152 153 def create(username, state, fields): 178 154 """Handler for create requests.""" 179 155 try: 180 parsed_fields = parseCreate(user , fields)181 machine = controls.createVm( **parsed_fields)156 parsed_fields = parseCreate(username, state, fields) 157 machine = controls.createVm(username, **parsed_fields) 182 158 except InvalidInput, err: 183 159 pass 184 160 else: 185 161 err = None 186 g.clear() #Changed global state187 d = getListDict(user )162 state.clear() #Changed global state 163 d = getListDict(username) 188 164 d['err'] = err 189 165 if err: … … 195 171 196 172 197 def getListDict(user ):173 def getListDict(username, state): 198 174 """Gets the list of local variables used by list.tmpl.""" 199 175 checkpoint.checkpoint('Starting') 200 machines = g.machines176 machines = state.machines 201 177 checkpoint.checkpoint('Got my machines') 202 178 on = {} 203 179 has_vnc = {} 204 xmlist = g.xmlist180 xmlist = state.xmlist 205 181 checkpoint.checkpoint('Got uptimes') 206 can_clone = 'ice3' not in g.xmlist_raw182 can_clone = 'ice3' not in state.xmlist_raw 207 183 for m in machines: 208 184 if m not in xmlist: … … 217 193 else: 218 194 has_vnc[m] = "ParaVM"+helppopup("ParaVM Console") 219 max_memory = validation.maxMemory(user )220 max_disk = validation.maxDisk(user )195 max_memory = validation.maxMemory(username, state) 196 max_disk = validation.maxDisk(username) 221 197 checkpoint.checkpoint('Got max mem/disk') 222 198 defaults = Defaults(max_memory=max_memory, 223 199 max_disk=max_disk, 224 owner=user ,200 owner=username, 225 201 cdrom='gutsy-i386') 226 202 checkpoint.checkpoint('Got defaults') 227 203 def sortkey(machine): 228 return (machine.owner != user , machine.owner, machine.name)204 return (machine.owner != username, machine.owner, machine.name) 229 205 machines = sorted(machines, key=sortkey) 230 d = dict(user=user ,231 cant_add_vm=validation.cantAddVm(user ),206 d = dict(user=username, 207 cant_add_vm=validation.cantAddVm(username, state), 232 208 max_memory=max_memory, 233 209 max_disk=max_disk, … … 238 214 return d 239 215 240 def listVms(user , fields):216 def listVms(username, state, fields): 241 217 """Handler for list requests.""" 242 218 checkpoint.checkpoint('Getting list dict') 243 d = getListDict(user )219 d = getListDict(username, state) 244 220 checkpoint.checkpoint('Got list dict') 245 221 return templates.list(searchList=[d]) 246 222 247 def vnc(user , fields):223 def vnc(username, state, fields): 248 224 """VNC applet page. 249 225 … … 265 241 echo 1 > /proc/sys/net/ipv4/ip_forward 266 242 """ 267 machine = validation. testMachineId(user, fields.getfirst('machine_id'))243 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine 268 244 269 245 TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN" 270 246 271 247 data = {} 272 data["user"] = user 248 data["user"] = username 273 249 data["machine"] = machine.name 274 250 data["expires"] = time.time()+(5*60) … … 283 259 has_vnc = hasVnc(status) 284 260 285 d = dict(user=user ,261 d = dict(user=username, 286 262 on=status, 287 263 has_vnc=has_vnc, … … 342 318 return disk_fields 343 319 344 def command(user , fields):320 def command(username, state, fields): 345 321 """Handler for running commands like boot and delete on a VM.""" 346 322 back = fields.getfirst('back') 347 323 try: 348 d = controls.commandResult(user , fields)324 d = controls.commandResult(username, state, fields) 349 325 if d['command'] == 'Delete VM': 350 326 back = 'list' … … 352 328 if not back: 353 329 raise 354 #print >> sys.stderr, err330 print >> sys.stderr, err 355 331 result = err 356 332 else: … … 359 335 return templates.command(searchList=[d]) 360 336 if back == 'list': 361 g.clear() #Changed global state362 d = getListDict(user )337 state.clear() #Changed global state 338 d = getListDict(username) 363 339 d['result'] = result 364 340 return templates.list(searchList=[d]) 365 341 elif back == 'info': 366 machine = validation. testMachineId(user, fields.getfirst('machine_id'))342 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine 367 343 return ({'Status': '302', 368 344 'Location': '/info?machine_id=%d' % machine.machine_id}, … … 371 347 raise InvalidInput('back', back, 'Not a known back page.') 372 348 373 def modifyDict(user , fields):349 def modifyDict(username, state, fields): 374 350 """Modify a machine as specified by CGI arguments. 375 351 … … 379 355 transaction = ctx.current.create_transaction() 380 356 try: 381 machine = validation.testMachineId(user, fields.getfirst('machine_id')) 382 owner = validation.testOwner(user, fields.getfirst('owner'), machine) 383 admin = validation.testAdmin(user, fields.getfirst('administrator'), 384 machine) 385 contact = validation.testContact(user, fields.getfirst('contact'), 386 machine) 387 name = validation.testName(user, fields.getfirst('name'), machine) 357 kws = dict([(kw, fields.getfirst(kw)) for kw in 'machine_id owner admin contact name memory vmtype disksize'.split()]) 358 validate = validation.Validate(username, state, **kws) 359 machine = validate.machine 360 print >> sys.stderr, machine, machine.administrator, kws['admin'] 388 361 oldname = machine.name 389 command = "modify" 390 391 memory = fields.getfirst('memory') 392 if memory is not None: 393 memory = validation.validMemory(owner, memory, machine, on=False) 394 machine.memory = memory 395 396 vm_type = validation.validVmType(fields.getfirst('vmtype')) 397 if vm_type is not None: 398 machine.type = vm_type 399 400 disksize = validation.testDisk(owner, fields.getfirst('disk')) 401 if disksize is not None: 402 disksize = validation.validDisk(owner, disksize, machine) 362 363 if hasattr(validate, 'memory'): 364 machine.memory = validate.memory 365 366 if hasattr(validate, 'vmtype'): 367 machine.type = validate.vmtype 368 369 if hasattr(validate, 'disksize'): 370 disksize = validate.disksize 403 371 disk = machine.disks[0] 404 372 if disk.size != disksize: … … 408 376 409 377 update_acl = False 410 if owner is not None andowner != machine.owner:411 machine.owner = owner378 if hasattr(validate, 'owner') and validate.owner != machine.owner: 379 machine.owner = validate.owner 412 380 update_acl = True 413 if name is not None:381 if hasattr(validate, 'name'): 414 382 machine.name = name 415 if admin is not None andadmin != machine.administrator:416 machine.administrator = admin383 if hasattr(validate, 'admin') and validate.admin != machine.administrator: 384 machine.administrator = validate.admin 417 385 update_acl = True 418 if contact is not None:419 machine.contact = contact386 if hasattr(validate, 'contact'): 387 machine.contact = validate.contact 420 388 421 389 ctx.current.save(machine) 422 390 if update_acl: 391 print >> sys.stderr, machine, machine.administrator 423 392 cache_acls.refreshMachine(machine) 424 393 transaction.commit() … … 428 397 for diskname in olddisk: 429 398 controls.resizeDisk(oldname, diskname, str(olddisk[diskname])) 430 if name is not None:431 controls.renameMachine(machine, oldname, name)432 return dict(user=user ,433 command= command,399 if hasattr(validate, 'name'): 400 controls.renameMachine(machine, oldname, validate.name) 401 return dict(user=username, 402 command="modify", 434 403 machine=machine) 435 404 436 def modify(user , fields):405 def modify(username, state, fields): 437 406 """Handler for modifying attributes of a machine.""" 438 407 try: 439 modify_dict = modifyDict(user , fields)408 modify_dict = modifyDict(username, state, fields) 440 409 except InvalidInput, err: 441 410 result = None 442 machine = validation. testMachineId(user, fields.getfirst('machine_id'))411 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine 443 412 else: 444 413 machine = modify_dict['machine'] 445 414 result = 'Success!' 446 415 err = None 447 info_dict = infoDict(user , machine)416 info_dict = infoDict(username, machine) 448 417 info_dict['err'] = err 449 418 if err: … … 454 423 455 424 456 def helpHandler(user , fields):425 def helpHandler(username, state, fields): 457 426 """Handler for help messages.""" 458 427 simple = fields.getfirst('simple') … … 497 466 subjects = sorted(help_mapping.keys()) 498 467 499 d = dict(user=user ,468 d = dict(user=username, 500 469 simple=simple, 501 470 subjects=subjects, … … 509 478 raise CodeError("Unknown operation") 510 479 511 def infoDict(user , machine):480 def infoDict(username, machine): 512 481 """Get the variables used by info.tmpl.""" 513 482 status = controls.statusInfo(machine) … … 580 549 581 550 582 max_mem = validation.maxMemory(machine.owner, machine, False)551 max_mem = validation.maxMemory(machine.owner, state, machine, False) 583 552 checkpoint.checkpoint('Got mem') 584 553 max_disk = validation.maxDisk(machine.owner, machine) … … 589 558 defaults.disk = "%0.2f" % (machine.disks[0].size/1024.) 590 559 checkpoint.checkpoint('Got defaults') 591 d = dict(user=user ,560 d = dict(user=username, 592 561 on=status is not None, 593 562 machine=machine, … … 602 571 return d 603 572 604 def info(user , fields):573 def info(username, state, fields): 605 574 """Handler for info on a single VM.""" 606 machine = validation. testMachineId(user, fields.getfirst('machine_id'))607 d = infoDict(user , machine)575 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine 576 d = infoDict(username, machine) 608 577 checkpoint.checkpoint('Got infodict') 609 578 return templates.info(searchList=[d]) 610 579 611 def unauthFront(_, fields):580 def unauthFront(_, _2, fields): 612 581 """Information for unauth'd users.""" 613 582 return templates.unauth(searchList=[{'simple' : True}]) … … 629 598 630 599 631 def getUser( ):600 def getUser(environ): 632 601 """Return the current user based on the SSL environment variables""" 633 email = os.environ.get('SSL_CLIENT_S_DN_Email', None)602 email = environ.get('SSL_CLIENT_S_DN_Email', None) 634 603 if email is None: 635 604 return None 636 return email.split("@")[0] 637 638 def main(operation, user, fields): 605 if not email.endswith('@MIT.EDU'): 606 return None 607 return email[:-8] 608 609 def main(operation, username, state, fields): 639 610 start_time = time.time() 640 611 fun = mapping.get(operation, badOperation) … … 644 615 try: 645 616 checkpoint.checkpoint('Before') 646 output = fun(u , fields)617 output = fun(username, state, fields) 647 618 checkpoint.checkpoint('After') 648 619 … … 653 624 e = revertStandardError() 654 625 if e: 626 if isinstance(output, basestring): 627 sys.stderr = StringIO() 628 x = str(output) 629 print >> sys.stderr, x 630 print >> sys.stderr, 'XXX' 631 print >> sys.stderr, e 632 raise Exception() 655 633 output.addError(e) 656 634 printHeaders(headers) … … 659 637 print output_string 660 638 if fields.has_key('timedebug'): 661 print '<pre>%s</pre>' % c heckpoint639 print '<pre>%s</pre>' % cgi.escape(checkpoint) 662 640 except Exception, err: 663 641 if not fields.has_key('js'): … … 665 643 print 'Content-Type: text/html\n' 666 644 e = revertStandardError() 667 print error(operation, u, fields, err, e)645 print error(operation, state.username, fields, err, e) 668 646 sys.exit(1) 669 647 if isinstance(err, InvalidInput): 670 648 print 'Content-Type: text/html\n' 671 649 e = revertStandardError() 672 print invalidInput(operation, u, fields, err, e)650 print invalidInput(operation, state.username, fields, err, e) 673 651 sys.exit(1) 674 652 print 'Content-Type: text/plain\n' … … 690 668 logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.INFO) 691 669 692 u = getUser()693 g.user = u670 username = getUser(os.environ) 671 state.username = username 694 672 operation = os.environ.get('PATH_INFO', '') 695 673 if not operation: … … 697 675 print 'Location: ' + os.environ['SCRIPT_NAME']+'/\n' 698 676 sys.exit(0) 699 700 if u is None: 677 if username is None: 701 678 operation = 'unauth' 702 703 679 if operation.startswith('/'): 704 680 operation = operation[1:] … … 708 684 if os.getenv("SIPB_XEN_PROFILE"): 709 685 import profile 710 profile.run('main(operation, u , fields)', 'log-'+operation)711 else: 712 main(operation, u , fields)686 profile.run('main(operation, username, state, fields)', 'log-'+operation) 687 else: 688 main(operation, username, state, fields)
Note: See TracChangeset
for help on using the changeset viewer.