source: trunk/packages/sipb-xen-www/code/controls.py @ 1001

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

Update (at least some of) the web code to work with newer a SQLAlchemy

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