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

Last change on this file since 589 was 589, checked in by ecprice, 16 years ago

Set machine_access to be a private attribute of machine, so the acl is
deleted automatically when the machine is destroyed.

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