source: package_branches/invirt-web/cherrypy-rebased/code/main.py @ 2716

Last change on this file since 2716 was 2716, checked in by broder, 14 years ago

"Cherry-pick" r2557 (Re-arrange the authz configuration.) to the
cherrypy branch.

(It's somewhat tenuous to claim this is a cherry-pick, given that all
of the changes would have conflicted had I actually tried to
cherry-pick the change. Oh well)

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