source: trunk/packages/invirt-web/code/controls.py @ 1682

Last change on this file since 1682 was 1682, checked in by broder, 15 years ago

Add a commented out line to disable the autoinstaller

File size: 9.4 KB
RevLine 
[209]1import validation
[1612]2from invirt.common import CodeError, InvalidInput
[209]3import random
4import sys
5import time
6import re
[265]7import cache_acls
[550]8import yaml
[209]9
[863]10from invirt.config import structs as config
[1001]11from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
[1614]12from invirt.remctl import remctl as gen_remctl
[863]13
[209]14# ... and stolen from xend/uuid.py
15def randomUUID():
16    """Generate a random UUID."""
17
18    return [ random.randint(0, 255) for _ in range(0, 16) ]
19
20def uuidToString(u):
21    """Turn a numeric UUID to a hyphen-seperated one."""
22    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
23                     "%02x" * 6]) % tuple(u)
24# end stolen code
25
[1614]26def remctl(*args, **kwargs):
[1618]27    return gen_remctl(config.remote.hostname,
[1614]28                      principal='daemon/'+config.web.hostname,
[1618]29                      *args, **kwargs)
[1614]30
[209]31def lvcreate(machine, disk):
32    """Create a single disk for a machine"""
33    remctl('web', 'lvcreate', machine.name,
34           disk.guest_device_name, str(disk.size))
35   
36def makeDisks(machine):
37    """Update the lvm partitions to add a disk."""
38    for disk in machine.disks:
39        lvcreate(machine, disk)
40
[629]41def getswap(disksize, memsize):
42    """Returns the recommended swap partition size."""
43    return int(min(disksize / 4, memsize * 1.5))
44
45def lvinstall(machine, autoinstall):
[1682]46    #raise InvalidInput('autoinstall', 'install',
47    #                   "The autoinstaller has been temporarily disabled")
[629]48    disksize = machine.disks[0].size
49    memsize = machine.memory
[1096]50    swapsize = getswap(disksize, memsize)
51    imagesize = disksize - swapsize
[629]52    ip = machine.nics[0].ip
[1096]53    remctl('control', machine.name, 'install', 
54           'dist=%s' % autoinstall.distribution,
55           'mirror=%s' % autoinstall.mirror,
56           'imagesize=%s' % imagesize)
[629]57
[340]58def lvcopy(machine_orig_name, machine, rootpw):
59    """Copy a golden image onto a machine's disk"""
60    remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
61
[209]62def bootMachine(machine, cdtype):
63    """Boot a machine with a given boot CD.
64
65    If cdtype is None, give no boot cd.  Otherwise, it is the string
66    id of the CD (e.g. 'gutsy_i386')
67    """
68    if cdtype is not None:
[261]69        out, err = remctl('control', machine.name, 'create', 
70                          cdtype, err=True)
[209]71    else:
[261]72        out, err = remctl('control', machine.name, 'create',
73                          err=True)
[695]74    if 'already running' in err:
[261]75        raise InvalidInput('action', 'create',
76                           'VM %s is already on' % machine.name)
77    elif err:
78        raise CodeError('"%s" on "control %s create %s' 
79                        % (err, machine.name, cdtype))
[209]80
[629]81def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
[209]82    """Create a VM and put it in the database"""
83    # put stuff in the table
[1013]84    session.begin()
[209]85    try:
[609]86        validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
[209]87        machine = Machine()
88        machine.name = name
[609]89        machine.description = description
[209]90        machine.memory = memory
[228]91        machine.owner = owner
92        machine.administrator = owner
93        machine.contact = contact
[209]94        machine.uuid = uuidToString(randomUUID())
95        machine.boot_off_cd = True
[1013]96        machine.type = machine_type
97        session.save_or_update(machine)
98        disk = Disk(machine=machine,
[572]99                    guest_device_name='hda', size=disksize)
[1013]100        nic = NIC.query().filter_by(machine_id=None).first()
101        if not nic: #No IPs left!
[209]102            raise CodeError("No IP addresses left!  "
[879]103                            "Contact %s." % config.web.errormail)
[1013]104        nic.machine = machine
[209]105        nic.hostname = name
[1013]106        session.save_or_update(nic)
107        session.save_or_update(disk)
[265]108        cache_acls.refreshMachine(machine)
[1013]109        session.commit()
[209]110    except:
[1013]111        session.rollback()
[209]112        raise
113    makeDisks(machine)
[629]114    if autoinstall:
115        lvinstall(machine, autoinstall)
[1140]116    else:
117        # tell it to boot with cdrom
118        bootMachine(machine, cdrom)
[209]119    return machine
120
[554]121def getList():
122    """Return a dictionary mapping machine names to dicts."""
[550]123    value_string = remctl('web', 'listvms')
[574]124    value_dict = yaml.load(value_string, yaml.CSafeLoader)
[554]125    return value_dict
[209]126
127def parseStatus(s):
128    """Parse a status string into nested tuples of strings.
129
130    s = output of xm list --long <machine_name>
131    """
132    values = re.split('([()])', s)
133    stack = [[]]
134    for v in values[2:-2]: #remove initial and final '()'
135        if not v:
136            continue
137        v = v.strip()
138        if v == '(':
139            stack.append([])
140        elif v == ')':
141            if len(stack[-1]) == 1:
142                stack[-1].append('')
143            stack[-2].append(stack[-1])
144            stack.pop()
145        else:
146            if not v:
147                continue
148            stack[-1].extend(v.split())
149    return stack[-1]
150
151def statusInfo(machine):
152    """Return the status list for a given machine.
153
154    Gets and parses xm list --long
155    """
156    value_string, err_string = remctl('control', machine.name, 'list-long', 
157                                      err=True)
158    if 'Unknown command' in err_string:
159        raise CodeError("ERROR in remctl list-long %s is not registered" % 
160                        (machine.name,))
[626]161    elif 'is not on' in err_string:
[209]162        return None
163    elif err_string:
164        raise CodeError("ERROR in remctl list-long %s%s" % 
165                        (machine.name, err_string))
166    status = parseStatus(value_string)
167    return status
168
[662]169def listHost(machine):
170    """Return the host a machine is running on"""
171    out, err = remctl('control', machine.name, 'listhost', err=True)
172    if err:
173        return None
[666]174    return out.strip()
[662]175
[1615]176def vnctoken(machine):
177    """Return a time-stamped VNC token"""
[1619]178    out, err = remctl('control', machine.name, 'vnctoken', err=True)
[1615]179    if err:
180        return None
181    return out.strip()
182
[209]183def deleteVM(machine):
184    """Delete a VM."""
185    remctl('control', machine.name, 'destroy', err=True)
[1013]186    session.begin()
[209]187    delete_disk_pairs = [(machine.name, d.guest_device_name) 
188                         for d in machine.disks]
189    try:
[1013]190        for mname, dname in delete_disk_pairs:
191            remctl('web', 'lvremove', mname, dname)
[209]192        for nic in machine.nics:
193            nic.machine_id = None
194            nic.hostname = None
[1013]195            session.save_or_update(nic)
[209]196        for disk in machine.disks:
[1013]197            session.delete(disk)
198        session.delete(machine)
199        session.commit()
[209]200    except:
[1013]201        session.rollback()
[209]202        raise
203
[572]204def commandResult(username, state, fields):
[209]205    start_time = 0
[572]206    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
[209]207    action = fields.getfirst('action')
208    cdrom = fields.getfirst('cdrom')
[1074]209    if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
[209]210        raise CodeError("Invalid cdrom type '%s'" % cdrom)   
211    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 
212                      'Delete VM'):
213        raise CodeError("Invalid action '%s'" % action)
214    if action == 'Reboot':
215        if cdrom is not None:
216            out, err = remctl('control', machine.name, 'reboot', cdrom,
217                              err=True)
218        else:
219            out, err = remctl('control', machine.name, 'reboot',
220                              err=True)
221        if err:
[692]222            if re.match("machine '.*' is not on", err):
[209]223                raise InvalidInput("action", "reboot", 
224                                   "Machine is not on")
225            else:
226                print >> sys.stderr, 'Error on reboot:'
227                print >> sys.stderr, err
228                raise CodeError('ERROR on remctl')
229               
230    elif action == 'Power on':
[572]231        if validation.maxMemory(username, state, machine) < machine.memory:
[209]232            raise InvalidInput('action', 'Power on',
233                               "You don't have enough free RAM quota "
234                               "to turn on this machine.")
235        bootMachine(machine, cdrom)
236    elif action == 'Power off':
237        out, err = remctl('control', machine.name, 'destroy', err=True)
238        if err:
[694]239            if re.match("machine '.*' is not on", err):
[209]240                raise InvalidInput("action", "Power off", 
241                                   "Machine is not on.")
242            else:
243                print >> sys.stderr, 'Error on power off:'
244                print >> sys.stderr, err
245                raise CodeError('ERROR on remctl')
246    elif action == 'Shutdown':
247        out, err = remctl('control', machine.name, 'shutdown', err=True)
248        if err:
[694]249            if re.match("machine '.*' is not on", err):
[209]250                raise InvalidInput("action", "Shutdown", 
251                                   "Machine is not on.")
252            else:
253                print >> sys.stderr, 'Error on Shutdown:'
254                print >> sys.stderr, err
255                raise CodeError('ERROR on remctl')
256    elif action == 'Delete VM':
257        deleteVM(machine)
258
[572]259    d = dict(user=username,
[209]260             command=action,
261             machine=machine)
262    return d
263
264def resizeDisk(machine_name, disk_name, new_size):
265    remctl("web", "lvresize", machine_name, disk_name, new_size)
266
267def renameMachine(machine, old_name, new_name):
268    for disk in machine.disks:
269        remctl("web", "lvrename", old_name, 
270               disk.guest_device_name, new_name)
271   
Note: See TracBrowser for help on using the repository browser.