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

Last change on this file since 1613 was 1613, checked in by broder, 16 years ago

Move the remctl code into invirt.remctl

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