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