[113] | 1 | #!/usr/bin/python |
---|
[205] | 2 | """Main CGI script for web interface""" |
---|
[113] | 3 | |
---|
[2449] | 4 | from __future__ import with_statement |
---|
| 5 | |
---|
[205] | 6 | import base64 |
---|
| 7 | import cPickle |
---|
[113] | 8 | import cgi |
---|
[205] | 9 | import datetime |
---|
| 10 | import hmac |
---|
[770] | 11 | import random |
---|
[205] | 12 | import sha |
---|
| 13 | import sys |
---|
[2449] | 14 | import threading |
---|
[118] | 15 | import time |
---|
[447] | 16 | import urllib |
---|
[2186] | 17 | import socket |
---|
[2389] | 18 | import cherrypy |
---|
[2485] | 19 | from cherrypy import _cperror |
---|
[205] | 20 | from StringIO import StringIO |
---|
[2449] | 21 | |
---|
[205] | 22 | def printError(): |
---|
| 23 | """Revert stderr to stdout, and print the contents of stderr""" |
---|
| 24 | if isinstance(sys.stderr, StringIO): |
---|
| 25 | print revertStandardError() |
---|
| 26 | |
---|
| 27 | if __name__ == '__main__': |
---|
| 28 | import atexit |
---|
| 29 | atexit.register(printError) |
---|
| 30 | |
---|
[209] | 31 | import validation |
---|
[446] | 32 | import cache_acls |
---|
[1612] | 33 | from webcommon import State |
---|
[209] | 34 | import controls |
---|
[632] | 35 | from getafsgroups import getAfsGroupMembers |
---|
[865] | 36 | from invirt import database |
---|
[1001] | 37 | from invirt.database import Machine, CDROM, session, connect, MachineAccess, Type, Autoinstall |
---|
[863] | 38 | from invirt.config import structs as config |
---|
[1612] | 39 | from invirt.common import InvalidInput, CodeError |
---|
[2481] | 40 | import invirt.remctl |
---|
[113] | 41 | |
---|
[2485] | 42 | from view import View, revertStandardError |
---|
[2432] | 43 | import ajaxterm |
---|
[2390] | 44 | |
---|
[2484] | 45 | class InvirtUnauthWeb(View): |
---|
| 46 | @cherrypy.expose |
---|
| 47 | @cherrypy.tools.mako(filename="/unauth.mako") |
---|
| 48 | def index(self): |
---|
| 49 | return {'simple': True} |
---|
| 50 | |
---|
[2390] | 51 | class InvirtWeb(View): |
---|
| 52 | def __init__(self): |
---|
| 53 | super(self.__class__,self).__init__() |
---|
| 54 | connect() |
---|
[2391] | 55 | self._cp_config['tools.require_login.on'] = True |
---|
[2485] | 56 | self._cp_config['tools.catch_stderr.on'] = True |
---|
[2403] | 57 | self._cp_config['tools.mako.imports'] = ['from invirt.config import structs as config', |
---|
| 58 | 'from invirt import database'] |
---|
[2485] | 59 | self._cp_config['request.error_response'] = self.handle_error |
---|
[2390] | 60 | |
---|
[2485] | 61 | @cherrypy.expose |
---|
| 62 | @cherrypy.tools.mako(filename="/invalid.mako") |
---|
| 63 | def invalidInput(self): |
---|
| 64 | """Print an error page when an InvalidInput exception occurs""" |
---|
| 65 | err = cherrypy.request.prev.params["err"] |
---|
| 66 | emsg = cherrypy.request.prev.params["emsg"] |
---|
| 67 | d = dict(err_field=err.err_field, |
---|
| 68 | err_value=str(err.err_value), stderr=emsg, |
---|
| 69 | errorMessage=str(err)) |
---|
| 70 | return d |
---|
| 71 | |
---|
| 72 | @cherrypy.expose |
---|
| 73 | @cherrypy.tools.mako(filename="/error.mako") |
---|
| 74 | def error(self): |
---|
| 75 | """Print an error page when an exception occurs""" |
---|
| 76 | op = cherrypy.request.prev.path_info |
---|
| 77 | username = cherrypy.request.login |
---|
| 78 | err = cherrypy.request.prev.params["err"] |
---|
| 79 | emsg = cherrypy.request.prev.params["emsg"] |
---|
| 80 | traceback = cherrypy.request.prev.params["traceback"] |
---|
[2523] | 81 | d = dict(op=op, user=username, fields=cherrypy.request.prev.params, |
---|
[2485] | 82 | errorMessage=str(err), stderr=emsg, traceback=traceback) |
---|
[2486] | 83 | error_raw = cherrypy.request.lookup.get_template("/error_raw.mako") |
---|
[2485] | 84 | details = error_raw.render(**d) |
---|
| 85 | exclude = config.web.errormail_exclude |
---|
| 86 | if username not in exclude and '*' not in exclude: |
---|
| 87 | send_error_mail('xvm error on %s for %s: %s' % (op, cherrypy.request.login, err), |
---|
| 88 | details) |
---|
| 89 | d['details'] = details |
---|
| 90 | return d |
---|
| 91 | |
---|
[2482] | 92 | def __getattr__(self, name): |
---|
| 93 | if name in ("admin", "overlord"): |
---|
[2558] | 94 | if not cherrypy.request.login in getAfsGroupMembers(config.adminacl, config.authz.cells[0].cell): |
---|
[2482] | 95 | raise InvalidInput('username', cherrypy.request.login, |
---|
| 96 | 'Not in admin group %s.' % config.adminacl) |
---|
| 97 | cherrypy.request.state = State(cherrypy.request.login, isadmin=True) |
---|
| 98 | return self |
---|
| 99 | else: |
---|
| 100 | return super(InvirtWeb, self).__getattr__(name) |
---|
[2403] | 101 | |
---|
[2485] | 102 | def handle_error(self): |
---|
| 103 | err = sys.exc_info()[1] |
---|
| 104 | if isinstance(err, InvalidInput): |
---|
| 105 | cherrypy.request.params['err'] = err |
---|
[2524] | 106 | cherrypy.request.params['emsg'] = revertStandardError() |
---|
[2485] | 107 | raise cherrypy.InternalRedirect('/invalidInput') |
---|
| 108 | if not cherrypy.request.prev or 'err' not in cherrypy.request.prev.params: |
---|
| 109 | cherrypy.request.params['err'] = err |
---|
[2524] | 110 | cherrypy.request.params['emsg'] = revertStandardError() |
---|
[2485] | 111 | cherrypy.request.params['traceback'] = _cperror.format_exc() |
---|
| 112 | raise cherrypy.InternalRedirect('/error') |
---|
| 113 | # fall back to cherrypy default error page |
---|
| 114 | cherrypy.HTTPError(500).set_response() |
---|
| 115 | |
---|
[2390] | 116 | @cherrypy.expose |
---|
[2391] | 117 | @cherrypy.tools.mako(filename="/list.mako") |
---|
[2418] | 118 | def list(self, result=None): |
---|
[2391] | 119 | """Handler for list requests.""" |
---|
| 120 | checkpoint.checkpoint('Getting list dict') |
---|
[2396] | 121 | d = getListDict(cherrypy.request.login, cherrypy.request.state) |
---|
[2418] | 122 | if result is not None: |
---|
| 123 | d['result'] = result |
---|
[2391] | 124 | checkpoint.checkpoint('Got list dict') |
---|
[2395] | 125 | return d |
---|
[2391] | 126 | index=list |
---|
| 127 | |
---|
| 128 | @cherrypy.expose |
---|
[2409] | 129 | @cherrypy.tools.mako(filename="/help.mako") |
---|
| 130 | def help(self, subject=None, simple=False): |
---|
| 131 | """Handler for help messages.""" |
---|
| 132 | |
---|
| 133 | help_mapping = { |
---|
| 134 | 'Autoinstalls': """ |
---|
| 135 | The autoinstaller builds a minimal Debian or Ubuntu system to run as a |
---|
| 136 | ParaVM. You can access the resulting system by logging into the <a |
---|
| 137 | href="help?simple=true&subject=ParaVM+Console">serial console server</a> |
---|
| 138 | with your Kerberos tickets; there is no root password so sshd will |
---|
| 139 | refuse login.</p> |
---|
| 140 | |
---|
| 141 | <p>Under the covers, the autoinstaller uses our own patched version of |
---|
| 142 | xen-create-image, which is a tool based on debootstrap. If you log |
---|
| 143 | into the serial console while the install is running, you can watch |
---|
| 144 | it. |
---|
| 145 | """, |
---|
| 146 | 'ParaVM Console': """ |
---|
| 147 | ParaVM machines do not support local console access over VNC. To |
---|
| 148 | access the serial console of these machines, you can SSH with Kerberos |
---|
| 149 | to %s, using the name of the machine as your |
---|
| 150 | username.""" % config.console.hostname, |
---|
| 151 | 'HVM/ParaVM': """ |
---|
| 152 | HVM machines use the virtualization features of the processor, while |
---|
| 153 | ParaVM machines rely on a modified kernel to communicate directly with |
---|
| 154 | the hypervisor. HVMs support boot CDs of any operating system, and |
---|
| 155 | the VNC console applet. The three-minute autoinstaller produces |
---|
| 156 | ParaVMs. ParaVMs typically are more efficient, and always support the |
---|
| 157 | <a href="help?subject=ParaVM+Console">console server</a>.</p> |
---|
| 158 | |
---|
| 159 | <p>More details are <a |
---|
| 160 | href="https://xvm.scripts.mit.edu/wiki/Paravirtualization">on the |
---|
| 161 | wiki</a>, including steps to prepare an HVM guest to boot as a ParaVM |
---|
| 162 | (which you can skip by using the autoinstaller to begin with.)</p> |
---|
| 163 | |
---|
| 164 | <p>We recommend using a ParaVM when possible and an HVM when necessary. |
---|
| 165 | """, |
---|
| 166 | 'CPU Weight': """ |
---|
| 167 | Don't ask us! We're as mystified as you are.""", |
---|
| 168 | 'Owner': """ |
---|
| 169 | The owner field is used to determine <a |
---|
| 170 | href="help?subject=Quotas">quotas</a>. It must be the name of a |
---|
| 171 | locker that you are an AFS administrator of. In particular, you or an |
---|
| 172 | AFS group you are a member of must have AFS rlidwka bits on the |
---|
| 173 | locker. You can check who administers the LOCKER locker using the |
---|
| 174 | commands 'attach LOCKER; fs la /mit/LOCKER' on Athena.) See also <a |
---|
| 175 | href="help?subject=Administrator">administrator</a>.""", |
---|
| 176 | 'Administrator': """ |
---|
| 177 | The administrator field determines who can access the console and |
---|
| 178 | power on and off the machine. This can be either a user or a moira |
---|
| 179 | group.""", |
---|
| 180 | 'Quotas': """ |
---|
| 181 | Quotas are determined on a per-locker basis. Each locker may have a |
---|
| 182 | maximum of 512 mebibytes of active ram, 50 gibibytes of disk, and 4 |
---|
| 183 | active machines.""", |
---|
| 184 | 'Console': """ |
---|
| 185 | <strong>Framebuffer:</strong> At a Linux boot prompt in your VM, try |
---|
| 186 | setting <tt>fb=false</tt> to disable the framebuffer. If you don't, |
---|
| 187 | your machine will run just fine, but the applet's display of the |
---|
| 188 | console will suffer artifacts. |
---|
| 189 | """, |
---|
| 190 | 'Windows': """ |
---|
| 191 | <strong>Windows Vista:</strong> The Vista image is licensed for all MIT students and will automatically activate off the network; see <a href="/static/msca-email.txt">the licensing confirmation e-mail</a> for details. The installer requires 512 MiB RAM and at least 7.5 GiB disk space (15 GiB or more recommended).<br> |
---|
[2423] | 192 | <strong>Windows XP:</strong> This is the volume license CD image. You will need your own volume license key to complete the install. We do not have these available for the general MIT community; ask your department if they have one, or visit <a href="http://msca.mit.edu/">http://msca.mit.edu/</a> if you are staff/faculty to request one. |
---|
[2409] | 193 | """ |
---|
| 194 | } |
---|
| 195 | |
---|
| 196 | if not subject: |
---|
| 197 | subject = sorted(help_mapping.keys()) |
---|
| 198 | if not isinstance(subject, list): |
---|
| 199 | subject = [subject] |
---|
| 200 | |
---|
[2410] | 201 | return dict(simple=simple, |
---|
[2409] | 202 | subjects=subject, |
---|
| 203 | mapping=help_mapping) |
---|
| 204 | help._cp_config['tools.require_login.on'] = False |
---|
| 205 | |
---|
[2422] | 206 | def parseCreate(self, fields): |
---|
[2526] | 207 | kws = dict([(kw, fields[kw]) for kw in |
---|
[2525] | 208 | 'name description owner memory disksize vmtype cdrom autoinstall'.split() |
---|
[2526] | 209 | if fields[kw]]) |
---|
[2525] | 210 | validate = validation.Validate(cherrypy.request.login, |
---|
| 211 | cherrypy.request.state, |
---|
| 212 | strict=True, **kws) |
---|
| 213 | return dict(contact=cherrypy.request.login, name=validate.name, |
---|
| 214 | description=validate.description, memory=validate.memory, |
---|
| 215 | disksize=validate.disksize, owner=validate.owner, |
---|
| 216 | machine_type=getattr(validate, 'vmtype', Defaults.type), |
---|
[2422] | 217 | cdrom=getattr(validate, 'cdrom', None), |
---|
| 218 | autoinstall=getattr(validate, 'autoinstall', None)) |
---|
| 219 | |
---|
[2409] | 220 | @cherrypy.expose |
---|
[2422] | 221 | @cherrypy.tools.mako(filename="/list.mako") |
---|
| 222 | @cherrypy.tools.require_POST() |
---|
| 223 | def create(self, **fields): |
---|
| 224 | """Handler for create requests.""" |
---|
| 225 | try: |
---|
| 226 | parsed_fields = self.parseCreate(fields) |
---|
[2525] | 227 | machine = controls.createVm(cherrypy.request.login, |
---|
| 228 | cherrypy.request.state, **parsed_fields) |
---|
[2422] | 229 | except InvalidInput, err: |
---|
| 230 | pass |
---|
| 231 | else: |
---|
| 232 | err = None |
---|
| 233 | cherrypy.request.state.clear() #Changed global state |
---|
| 234 | d = getListDict(cherrypy.request.login, cherrypy.request.state) |
---|
| 235 | d['err'] = err |
---|
| 236 | if err: |
---|
[2526] | 237 | for field, value in fields.items(): |
---|
[2530] | 238 | setattr(d['defaults'], field, value) |
---|
[2422] | 239 | else: |
---|
| 240 | d['new_machine'] = parsed_fields['name'] |
---|
| 241 | return d |
---|
| 242 | |
---|
| 243 | @cherrypy.expose |
---|
[2391] | 244 | @cherrypy.tools.mako(filename="/helloworld.mako") |
---|
[2408] | 245 | def helloworld(self, **kwargs): |
---|
| 246 | return {'request': cherrypy.request, 'kwargs': kwargs} |
---|
[2391] | 247 | helloworld._cp_config['tools.require_login.on'] = False |
---|
[2390] | 248 | |
---|
[2428] | 249 | @cherrypy.expose |
---|
| 250 | def errortest(self): |
---|
| 251 | """Throw an error, to test the error-tracing mechanisms.""" |
---|
[2485] | 252 | print >>sys.stderr, "look ma, it's a stderr" |
---|
[2428] | 253 | raise RuntimeError("test of the emergency broadcast system") |
---|
| 254 | |
---|
[2413] | 255 | class MachineView(View): |
---|
[2534] | 256 | def __getattr__(self, name): |
---|
| 257 | """Synthesize attributes to allow RESTful URLs like |
---|
| 258 | /machine/13/info. This is hairy. CherryPy 3.2 adds a |
---|
| 259 | method called _cp_dispatch that allows you to explicitly |
---|
| 260 | handle URLs that can't be mapped, and it allows you to |
---|
| 261 | rewrite the path components and continue processing. |
---|
[2413] | 262 | |
---|
[2534] | 263 | This function gets the next path component being resolved |
---|
| 264 | as a string. _cp_dispatch will get an array of strings |
---|
| 265 | representing any subsequent path components as well.""" |
---|
| 266 | |
---|
[2413] | 267 | try: |
---|
[2527] | 268 | cherrypy.request.params['machine_id'] = int(name) |
---|
[2413] | 269 | return self |
---|
| 270 | except ValueError: |
---|
| 271 | return None |
---|
| 272 | |
---|
| 273 | @cherrypy.expose |
---|
| 274 | @cherrypy.tools.mako(filename="/info.mako") |
---|
| 275 | def info(self, machine_id): |
---|
| 276 | """Handler for info on a single VM.""" |
---|
[2525] | 277 | machine = validation.Validate(cherrypy.request.login, |
---|
| 278 | cherrypy.request.state, |
---|
| 279 | machine_id=machine_id).machine |
---|
[2413] | 280 | d = infoDict(cherrypy.request.login, cherrypy.request.state, machine) |
---|
| 281 | checkpoint.checkpoint('Got infodict') |
---|
| 282 | return d |
---|
| 283 | index = info |
---|
| 284 | |
---|
[2414] | 285 | @cherrypy.expose |
---|
[2483] | 286 | @cherrypy.tools.mako(filename="/info.mako") |
---|
| 287 | @cherrypy.tools.require_POST() |
---|
| 288 | def modify(self, machine_id, **fields): |
---|
| 289 | """Handler for modifying attributes of a machine.""" |
---|
| 290 | try: |
---|
[2525] | 291 | modify_dict = modifyDict(cherrypy.request.login, |
---|
| 292 | cherrypy.request.state, |
---|
| 293 | machine_id, fields) |
---|
[2483] | 294 | except InvalidInput, err: |
---|
| 295 | result = None |
---|
[2525] | 296 | machine = validation.Validate(cherrypy.request.login, |
---|
| 297 | cherrypy.request.state, |
---|
| 298 | machine_id=machine_id).machine |
---|
[2483] | 299 | else: |
---|
| 300 | machine = modify_dict['machine'] |
---|
| 301 | result = 'Success!' |
---|
| 302 | err = None |
---|
[2525] | 303 | info_dict = infoDict(cherrypy.request.login, |
---|
| 304 | cherrypy.request.state, machine) |
---|
[2483] | 305 | info_dict['err'] = err |
---|
| 306 | if err: |
---|
[2526] | 307 | for field, value in fields.items(): |
---|
| 308 | setattr(info_dict['defaults'], field, value) |
---|
[2483] | 309 | info_dict['result'] = result |
---|
| 310 | return info_dict |
---|
| 311 | |
---|
| 312 | @cherrypy.expose |
---|
[2414] | 313 | @cherrypy.tools.mako(filename="/vnc.mako") |
---|
| 314 | def vnc(self, machine_id): |
---|
| 315 | """VNC applet page. |
---|
| 316 | |
---|
| 317 | Note that due to same-domain restrictions, the applet connects to |
---|
| 318 | the webserver, which needs to forward those requests to the xen |
---|
| 319 | server. The Xen server runs another proxy that (1) authenticates |
---|
| 320 | and (2) finds the correct port for the VM. |
---|
| 321 | |
---|
| 322 | You might want iptables like: |
---|
| 323 | |
---|
| 324 | -t nat -A PREROUTING -s ! 18.181.0.60 -i eth1 -p tcp -m tcp \ |
---|
| 325 | --dport 10003 -j DNAT --to-destination 18.181.0.60:10003 |
---|
| 326 | -t nat -A POSTROUTING -d 18.181.0.60 -o eth1 -p tcp -m tcp \ |
---|
| 327 | --dport 10003 -j SNAT --to-source 18.187.7.142 |
---|
| 328 | -A FORWARD -d 18.181.0.60 -i eth1 -o eth1 -p tcp -m tcp \ |
---|
| 329 | --dport 10003 -j ACCEPT |
---|
| 330 | |
---|
| 331 | Remember to enable iptables! |
---|
| 332 | echo 1 > /proc/sys/net/ipv4/ip_forward |
---|
| 333 | """ |
---|
[2525] | 334 | machine = validation.Validate(cherrypy.request.login, |
---|
| 335 | cherrypy.request.state, |
---|
| 336 | machine_id=machine_id).machine |
---|
[2414] | 337 | token = controls.vnctoken(machine) |
---|
| 338 | host = controls.listHost(machine) |
---|
| 339 | if host: |
---|
| 340 | port = 10003 + [h.hostname for h in config.hosts].index(host) |
---|
| 341 | else: |
---|
| 342 | port = 5900 # dummy |
---|
| 343 | |
---|
| 344 | status = controls.statusInfo(machine) |
---|
| 345 | has_vnc = hasVnc(status) |
---|
| 346 | |
---|
| 347 | d = dict(on=status, |
---|
| 348 | has_vnc=has_vnc, |
---|
| 349 | machine=machine, |
---|
| 350 | hostname=cherrypy.request.local.name, |
---|
| 351 | port=port, |
---|
| 352 | authtoken=token) |
---|
| 353 | return d |
---|
[2528] | 354 | |
---|
[2418] | 355 | @cherrypy.expose |
---|
| 356 | @cherrypy.tools.mako(filename="/command.mako") |
---|
[2422] | 357 | @cherrypy.tools.require_POST() |
---|
[2418] | 358 | def command(self, command_name, machine_id, **kwargs): |
---|
| 359 | """Handler for running commands like boot and delete on a VM.""" |
---|
[2528] | 360 | back = kwargs.get('back') |
---|
[2418] | 361 | try: |
---|
[2525] | 362 | d = controls.commandResult(cherrypy.request.login, |
---|
| 363 | cherrypy.request.state, |
---|
| 364 | command_name, machine_id, kwargs) |
---|
[2418] | 365 | if d['command'] == 'Delete VM': |
---|
| 366 | back = 'list' |
---|
| 367 | except InvalidInput, err: |
---|
| 368 | if not back: |
---|
| 369 | raise |
---|
| 370 | print >> sys.stderr, err |
---|
[2485] | 371 | result = str(err) |
---|
[2418] | 372 | else: |
---|
| 373 | result = 'Success!' |
---|
| 374 | if not back: |
---|
| 375 | return d |
---|
| 376 | if back == 'list': |
---|
| 377 | cherrypy.request.state.clear() #Changed global state |
---|
[2525] | 378 | raise cherrypy.InternalRedirect('/list?result=%s' |
---|
| 379 | % urllib.quote(result)) |
---|
[2418] | 380 | elif back == 'info': |
---|
[2525] | 381 | raise cherrypy.HTTPRedirect(cherrypy.request.base |
---|
| 382 | + '/machine/%d/' % machine_id, |
---|
| 383 | status=303) |
---|
[2418] | 384 | else: |
---|
| 385 | raise InvalidInput('back', back, 'Not a known back page.') |
---|
[2414] | 386 | |
---|
[2432] | 387 | atmulti = ajaxterm.Multiplex() |
---|
| 388 | atsessions = {} |
---|
[2449] | 389 | atsessions_lock = threading.Lock() |
---|
[2432] | 390 | |
---|
| 391 | @cherrypy.expose |
---|
| 392 | @cherrypy.tools.mako(filename="/terminal.mako") |
---|
| 393 | def terminal(self, machine_id): |
---|
| 394 | machine = validation.Validate(cherrypy.request.login, cherrypy.request.state, machine_id=machine_id).machine |
---|
| 395 | |
---|
| 396 | status = controls.statusInfo(machine) |
---|
| 397 | has_vnc = hasVnc(status) |
---|
| 398 | |
---|
| 399 | d = dict(on=status, |
---|
| 400 | has_vnc=has_vnc, |
---|
| 401 | machine=machine, |
---|
| 402 | hostname=cherrypy.request.local.name) |
---|
| 403 | return d |
---|
| 404 | |
---|
[2433] | 405 | @cherrypy.expose |
---|
[2452] | 406 | @cherrypy.tools.require_POST() |
---|
[2440] | 407 | @cherrypy.tools.gzip() |
---|
[2454] | 408 | def at(self, machine_id, k=None, c=0, h=None): |
---|
[2433] | 409 | machine = validation.Validate(cherrypy.request.login, cherrypy.request.state, machine_id=machine_id).machine |
---|
[2449] | 410 | with self.atsessions_lock: |
---|
| 411 | if machine_id in self.atsessions: |
---|
| 412 | term = self.atsessions[machine_id] |
---|
| 413 | else: |
---|
| 414 | print >>sys.stderr, "spawning new session for terminal to ",machine_id |
---|
[2481] | 415 | invirt.remctl.checkKinit(principal='daemon/'+config.web.hostname) |
---|
[2450] | 416 | term = self.atmulti.create( |
---|
[2449] | 417 | ["ssh", "-e","none", "-l", machine.name, config.console.hostname] |
---|
| 418 | ) |
---|
[2450] | 419 | # Clear out old sessions when fd is reused |
---|
| 420 | for key in self.atsessions: |
---|
| 421 | if self.atsessions[key] == term: |
---|
| 422 | del self.atsessions[key] |
---|
| 423 | self.atsessions[machine_id] = term |
---|
[2449] | 424 | if k: |
---|
| 425 | self.atmulti.proc_write(term,k) |
---|
| 426 | time.sleep(0.002) |
---|
[2454] | 427 | dump=self.atmulti.dump(term,c,h) |
---|
[2449] | 428 | cherrypy.response.headers['Content-Type']='text/xml' |
---|
| 429 | if isinstance(dump,str): |
---|
| 430 | return dump |
---|
| 431 | else: |
---|
[2481] | 432 | print "Removing session for", machine_id,"because we received",repr(dump) |
---|
[2449] | 433 | del self.atsessions[machine_id] |
---|
| 434 | return '<?xml version="1.0"?><idem></idem>' |
---|
[2433] | 435 | |
---|
[2413] | 436 | machine = MachineView() |
---|
| 437 | |
---|
[235] | 438 | class Checkpoint: |
---|
| 439 | def __init__(self): |
---|
| 440 | self.start_time = time.time() |
---|
| 441 | self.checkpoints = [] |
---|
| 442 | |
---|
| 443 | def checkpoint(self, s): |
---|
| 444 | self.checkpoints.append((s, time.time())) |
---|
| 445 | |
---|
| 446 | def __str__(self): |
---|
| 447 | return ('Timing info:\n%s\n' % |
---|
| 448 | '\n'.join(['%s: %s' % (d, t - self.start_time) for |
---|
| 449 | (d, t) in self.checkpoints])) |
---|
| 450 | |
---|
| 451 | checkpoint = Checkpoint() |
---|
| 452 | |
---|
[205] | 453 | class Defaults: |
---|
| 454 | """Class to store default values for fields.""" |
---|
| 455 | memory = 256 |
---|
| 456 | disk = 4.0 |
---|
| 457 | cdrom = '' |
---|
[443] | 458 | autoinstall = '' |
---|
[205] | 459 | name = '' |
---|
[609] | 460 | description = '' |
---|
[2483] | 461 | administrator = '' |
---|
[515] | 462 | type = 'linux-hvm' |
---|
| 463 | |
---|
[205] | 464 | def __init__(self, max_memory=None, max_disk=None, **kws): |
---|
| 465 | if max_memory is not None: |
---|
| 466 | self.memory = min(self.memory, max_memory) |
---|
| 467 | if max_disk is not None: |
---|
[1964] | 468 | self.disk = min(self.disk, max_disk) |
---|
[205] | 469 | for key in kws: |
---|
| 470 | setattr(self, key, kws[key]) |
---|
| 471 | |
---|
[119] | 472 | def hasVnc(status): |
---|
[133] | 473 | """Does the machine with a given status list support VNC?""" |
---|
[119] | 474 | if status is None: |
---|
| 475 | return False |
---|
| 476 | for l in status: |
---|
| 477 | if l[0] == 'device' and l[1][0] == 'vfb': |
---|
| 478 | d = dict(l[1][1:]) |
---|
| 479 | return 'location' in d |
---|
| 480 | return False |
---|
| 481 | |
---|
[134] | 482 | |
---|
[572] | 483 | def getListDict(username, state): |
---|
[438] | 484 | """Gets the list of local variables used by list.tmpl.""" |
---|
[535] | 485 | checkpoint.checkpoint('Starting') |
---|
[572] | 486 | machines = state.machines |
---|
[235] | 487 | checkpoint.checkpoint('Got my machines') |
---|
[133] | 488 | on = {} |
---|
[119] | 489 | has_vnc = {} |
---|
[2424] | 490 | installing = {} |
---|
[572] | 491 | xmlist = state.xmlist |
---|
[235] | 492 | checkpoint.checkpoint('Got uptimes') |
---|
[136] | 493 | for m in machines: |
---|
[535] | 494 | if m not in xmlist: |
---|
[144] | 495 | has_vnc[m] = 'Off' |
---|
[535] | 496 | m.uptime = None |
---|
[136] | 497 | else: |
---|
[535] | 498 | m.uptime = xmlist[m]['uptime'] |
---|
| 499 | if xmlist[m]['console']: |
---|
| 500 | has_vnc[m] = True |
---|
| 501 | elif m.type.hvm: |
---|
| 502 | has_vnc[m] = "WTF?" |
---|
| 503 | else: |
---|
[2412] | 504 | has_vnc[m] = "ParaVM" |
---|
[2424] | 505 | if xmlist[m].get('autoinstall'): |
---|
| 506 | installing[m] = True |
---|
| 507 | else: |
---|
| 508 | installing[m] = False |
---|
[572] | 509 | max_memory = validation.maxMemory(username, state) |
---|
| 510 | max_disk = validation.maxDisk(username) |
---|
[235] | 511 | checkpoint.checkpoint('Got max mem/disk') |
---|
[205] | 512 | defaults = Defaults(max_memory=max_memory, |
---|
| 513 | max_disk=max_disk, |
---|
[1739] | 514 | owner=username) |
---|
[235] | 515 | checkpoint.checkpoint('Got defaults') |
---|
[424] | 516 | def sortkey(machine): |
---|
[572] | 517 | return (machine.owner != username, machine.owner, machine.name) |
---|
[424] | 518 | machines = sorted(machines, key=sortkey) |
---|
[572] | 519 | d = dict(user=username, |
---|
| 520 | cant_add_vm=validation.cantAddVm(username, state), |
---|
[205] | 521 | max_memory=max_memory, |
---|
[144] | 522 | max_disk=max_disk, |
---|
[205] | 523 | defaults=defaults, |
---|
[113] | 524 | machines=machines, |
---|
[540] | 525 | has_vnc=has_vnc, |
---|
[2424] | 526 | installing=installing) |
---|
[205] | 527 | return d |
---|
[113] | 528 | |
---|
[252] | 529 | def getHostname(nic): |
---|
[438] | 530 | """Find the hostname associated with a NIC. |
---|
| 531 | |
---|
| 532 | XXX this should be merged with the similar logic in DNS and DHCP. |
---|
| 533 | """ |
---|
[1976] | 534 | if nic.hostname: |
---|
| 535 | hostname = nic.hostname |
---|
[252] | 536 | elif nic.machine: |
---|
[1976] | 537 | hostname = nic.machine.name |
---|
[252] | 538 | else: |
---|
| 539 | return None |
---|
[1976] | 540 | if '.' in hostname: |
---|
| 541 | return hostname |
---|
| 542 | else: |
---|
| 543 | return hostname + '.' + config.dns.domains[0] |
---|
[252] | 544 | |
---|
[133] | 545 | def getNicInfo(data_dict, machine): |
---|
[145] | 546 | """Helper function for info, get data on nics for a machine. |
---|
| 547 | |
---|
| 548 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 549 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 550 | """ |
---|
[133] | 551 | data_dict['num_nics'] = len(machine.nics) |
---|
[227] | 552 | nic_fields_template = [('nic%s_hostname', 'NIC %s Hostname'), |
---|
[133] | 553 | ('nic%s_mac', 'NIC %s MAC Addr'), |
---|
| 554 | ('nic%s_ip', 'NIC %s IP'), |
---|
| 555 | ] |
---|
| 556 | nic_fields = [] |
---|
| 557 | for i in range(len(machine.nics)): |
---|
| 558 | nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template]) |
---|
[1976] | 559 | data_dict['nic%s_hostname' % i] = getHostname(machine.nics[i]) |
---|
[133] | 560 | data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr |
---|
| 561 | data_dict['nic%s_ip' % i] = machine.nics[i].ip |
---|
| 562 | if len(machine.nics) == 1: |
---|
| 563 | nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields] |
---|
| 564 | return nic_fields |
---|
| 565 | |
---|
| 566 | def getDiskInfo(data_dict, machine): |
---|
[145] | 567 | """Helper function for info, get data on disks for a machine. |
---|
| 568 | |
---|
| 569 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 570 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 571 | """ |
---|
[133] | 572 | data_dict['num_disks'] = len(machine.disks) |
---|
| 573 | disk_fields_template = [('%s_size', '%s size')] |
---|
| 574 | disk_fields = [] |
---|
| 575 | for disk in machine.disks: |
---|
| 576 | name = disk.guest_device_name |
---|
[438] | 577 | disk_fields.extend([(x % name, y % name) for x, y in |
---|
[205] | 578 | disk_fields_template]) |
---|
[211] | 579 | data_dict['%s_size' % name] = "%0.1f GiB" % (disk.size / 1024.) |
---|
[133] | 580 | return disk_fields |
---|
| 581 | |
---|
[2483] | 582 | def modifyDict(username, state, machine_id, fields): |
---|
[438] | 583 | """Modify a machine as specified by CGI arguments. |
---|
| 584 | |
---|
[2483] | 585 | Return a dict containing the machine that was modified. |
---|
[438] | 586 | """ |
---|
[177] | 587 | olddisk = {} |
---|
[1013] | 588 | session.begin() |
---|
[161] | 589 | try: |
---|
[2526] | 590 | kws = dict([(kw, fields[kw]) for kw in |
---|
[2525] | 591 | 'owner admin contact name description memory vmtype disksize'.split() |
---|
[2526] | 592 | if fields[kw]]) |
---|
[2483] | 593 | kws['machine_id'] = machine_id |
---|
[572] | 594 | validate = validation.Validate(username, state, **kws) |
---|
| 595 | machine = validate.machine |
---|
[161] | 596 | oldname = machine.name |
---|
[153] | 597 | |
---|
[572] | 598 | if hasattr(validate, 'memory'): |
---|
| 599 | machine.memory = validate.memory |
---|
[438] | 600 | |
---|
[572] | 601 | if hasattr(validate, 'vmtype'): |
---|
| 602 | machine.type = validate.vmtype |
---|
[440] | 603 | |
---|
[572] | 604 | if hasattr(validate, 'disksize'): |
---|
| 605 | disksize = validate.disksize |
---|
[177] | 606 | disk = machine.disks[0] |
---|
| 607 | if disk.size != disksize: |
---|
| 608 | olddisk[disk.guest_device_name] = disksize |
---|
| 609 | disk.size = disksize |
---|
[1013] | 610 | session.save_or_update(disk) |
---|
[438] | 611 | |
---|
[446] | 612 | update_acl = False |
---|
[572] | 613 | if hasattr(validate, 'owner') and validate.owner != machine.owner: |
---|
| 614 | machine.owner = validate.owner |
---|
[446] | 615 | update_acl = True |
---|
[572] | 616 | if hasattr(validate, 'name'): |
---|
[586] | 617 | machine.name = validate.name |
---|
[1977] | 618 | for n in machine.nics: |
---|
| 619 | if n.hostname == oldname: |
---|
| 620 | n.hostname = validate.name |
---|
[609] | 621 | if hasattr(validate, 'description'): |
---|
| 622 | machine.description = validate.description |
---|
[572] | 623 | if hasattr(validate, 'admin') and validate.admin != machine.administrator: |
---|
| 624 | machine.administrator = validate.admin |
---|
[446] | 625 | update_acl = True |
---|
[572] | 626 | if hasattr(validate, 'contact'): |
---|
| 627 | machine.contact = validate.contact |
---|
[438] | 628 | |
---|
[1013] | 629 | session.save_or_update(machine) |
---|
[446] | 630 | if update_acl: |
---|
| 631 | cache_acls.refreshMachine(machine) |
---|
[1013] | 632 | session.commit() |
---|
[161] | 633 | except: |
---|
[1013] | 634 | session.rollback() |
---|
[163] | 635 | raise |
---|
[177] | 636 | for diskname in olddisk: |
---|
[209] | 637 | controls.resizeDisk(oldname, diskname, str(olddisk[diskname])) |
---|
[572] | 638 | if hasattr(validate, 'name'): |
---|
| 639 | controls.renameMachine(machine, oldname, validate.name) |
---|
[2483] | 640 | return dict(machine=machine) |
---|
[438] | 641 | |
---|
[579] | 642 | def infoDict(username, state, machine): |
---|
[438] | 643 | """Get the variables used by info.tmpl.""" |
---|
[209] | 644 | status = controls.statusInfo(machine) |
---|
[235] | 645 | checkpoint.checkpoint('Getting status info') |
---|
[133] | 646 | has_vnc = hasVnc(status) |
---|
| 647 | if status is None: |
---|
| 648 | main_status = dict(name=machine.name, |
---|
| 649 | memory=str(machine.memory)) |
---|
[205] | 650 | uptime = None |
---|
| 651 | cputime = None |
---|
[133] | 652 | else: |
---|
| 653 | main_status = dict(status[1:]) |
---|
[662] | 654 | main_status['host'] = controls.listHost(machine) |
---|
[167] | 655 | start_time = float(main_status.get('start_time', 0)) |
---|
| 656 | uptime = datetime.timedelta(seconds=int(time.time()-start_time)) |
---|
| 657 | cpu_time_float = float(main_status.get('cpu_time', 0)) |
---|
| 658 | cputime = datetime.timedelta(seconds=int(cpu_time_float)) |
---|
[235] | 659 | checkpoint.checkpoint('Status') |
---|
[133] | 660 | display_fields = [('name', 'Name'), |
---|
[609] | 661 | ('description', 'Description'), |
---|
[133] | 662 | ('owner', 'Owner'), |
---|
[187] | 663 | ('administrator', 'Administrator'), |
---|
[133] | 664 | ('contact', 'Contact'), |
---|
[136] | 665 | ('type', 'Type'), |
---|
[133] | 666 | 'NIC_INFO', |
---|
| 667 | ('uptime', 'uptime'), |
---|
| 668 | ('cputime', 'CPU usage'), |
---|
[662] | 669 | ('host', 'Hosted on'), |
---|
[133] | 670 | ('memory', 'RAM'), |
---|
| 671 | 'DISK_INFO', |
---|
| 672 | ('state', 'state (xen format)'), |
---|
| 673 | ] |
---|
| 674 | fields = [] |
---|
| 675 | machine_info = {} |
---|
[147] | 676 | machine_info['name'] = machine.name |
---|
[609] | 677 | machine_info['description'] = machine.description |
---|
[136] | 678 | machine_info['type'] = machine.type.hvm and 'HVM' or 'ParaVM' |
---|
[133] | 679 | machine_info['owner'] = machine.owner |
---|
[187] | 680 | machine_info['administrator'] = machine.administrator |
---|
[133] | 681 | machine_info['contact'] = machine.contact |
---|
| 682 | |
---|
| 683 | nic_fields = getNicInfo(machine_info, machine) |
---|
| 684 | nic_point = display_fields.index('NIC_INFO') |
---|
[438] | 685 | display_fields = (display_fields[:nic_point] + nic_fields + |
---|
[205] | 686 | display_fields[nic_point+1:]) |
---|
[133] | 687 | |
---|
| 688 | disk_fields = getDiskInfo(machine_info, machine) |
---|
| 689 | disk_point = display_fields.index('DISK_INFO') |
---|
[438] | 690 | display_fields = (display_fields[:disk_point] + disk_fields + |
---|
[205] | 691 | display_fields[disk_point+1:]) |
---|
[438] | 692 | |
---|
[211] | 693 | main_status['memory'] += ' MiB' |
---|
[133] | 694 | for field, disp in display_fields: |
---|
[167] | 695 | if field in ('uptime', 'cputime') and locals()[field] is not None: |
---|
[133] | 696 | fields.append((disp, locals()[field])) |
---|
[147] | 697 | elif field in machine_info: |
---|
| 698 | fields.append((disp, machine_info[field])) |
---|
[133] | 699 | elif field in main_status: |
---|
| 700 | fields.append((disp, main_status[field])) |
---|
| 701 | else: |
---|
| 702 | pass |
---|
| 703 | #fields.append((disp, None)) |
---|
[235] | 704 | |
---|
| 705 | checkpoint.checkpoint('Got fields') |
---|
| 706 | |
---|
| 707 | |
---|
[572] | 708 | max_mem = validation.maxMemory(machine.owner, state, machine, False) |
---|
[235] | 709 | checkpoint.checkpoint('Got mem') |
---|
[566] | 710 | max_disk = validation.maxDisk(machine.owner, machine) |
---|
[209] | 711 | defaults = Defaults() |
---|
[609] | 712 | for name in 'machine_id name description administrator owner memory contact'.split(): |
---|
[2483] | 713 | if getattr(machine, name): |
---|
| 714 | setattr(defaults, name, getattr(machine, name)) |
---|
[516] | 715 | defaults.type = machine.type.type_id |
---|
[205] | 716 | defaults.disk = "%0.2f" % (machine.disks[0].size/1024.) |
---|
[235] | 717 | checkpoint.checkpoint('Got defaults') |
---|
[572] | 718 | d = dict(user=username, |
---|
[133] | 719 | on=status is not None, |
---|
| 720 | machine=machine, |
---|
[205] | 721 | defaults=defaults, |
---|
[133] | 722 | has_vnc=has_vnc, |
---|
| 723 | uptime=str(uptime), |
---|
| 724 | ram=machine.memory, |
---|
[144] | 725 | max_mem=max_mem, |
---|
| 726 | max_disk=max_disk, |
---|
[133] | 727 | fields = fields) |
---|
[205] | 728 | return d |
---|
[113] | 729 | |
---|
[598] | 730 | def send_error_mail(subject, body): |
---|
| 731 | import subprocess |
---|
[205] | 732 | |
---|
[863] | 733 | to = config.web.errormail |
---|
[598] | 734 | mail = """To: %s |
---|
[863] | 735 | From: root@%s |
---|
[598] | 736 | Subject: %s |
---|
| 737 | |
---|
| 738 | %s |
---|
[863] | 739 | """ % (to, config.web.hostname, subject, body) |
---|
[1718] | 740 | p = subprocess.Popen(['/usr/sbin/sendmail', '-f', to, to], |
---|
| 741 | stdin=subprocess.PIPE) |
---|
[598] | 742 | p.stdin.write(mail) |
---|
| 743 | p.stdin.close() |
---|
| 744 | p.wait() |
---|
| 745 | |
---|
[2529] | 746 | random.seed() #sigh |
---|