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

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

Autoinstalls

File size: 10.0 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 getswap(disksize, memsize):
73    """Returns the recommended swap partition size."""
74    return int(min(disksize / 4, memsize * 1.5))
75
76def lvinstall(machine, autoinstall):
77    disksize = machine.disks[0].size
78    memsize = machine.memory
79    imagesize = disksize - getswap(disksize, memsize)
80    ip = machine.nics[0].ip
81    remctl('web', 'install', machine.name, autoinstall.distribution,
82           autoinstall.mirror, str(imagesize), ip)
83
84def lvcopy(machine_orig_name, machine, rootpw):
85    """Copy a golden image onto a machine's disk"""
86    remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
87
88def bootMachine(machine, cdtype):
89    """Boot a machine with a given boot CD.
90
91    If cdtype is None, give no boot cd.  Otherwise, it is the string
92    id of the CD (e.g. 'gutsy_i386')
93    """
94    if cdtype is not None:
95        out, err = remctl('control', machine.name, 'create', 
96                          cdtype, err=True)
97    else:
98        out, err = remctl('control', machine.name, 'create',
99                          err=True)
100    if 'already exists' in out:
101        raise InvalidInput('action', 'create',
102                           'VM %s is already on' % machine.name)
103    elif err:
104        raise CodeError('"%s" on "control %s create %s' 
105                        % (err, machine.name, cdtype))
106
107def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
108    """Create a VM and put it in the database"""
109    # put stuff in the table
110    transaction = ctx.current.create_transaction()
111    try:
112        validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
113        res = meta.engine.execute('select nextval('
114                                  '\'"machines_machine_id_seq"\')')
115        id = res.fetchone()[0]
116        machine = Machine()
117        machine.machine_id = id
118        machine.name = name
119        machine.description = description
120        machine.memory = memory
121        machine.owner = owner
122        machine.administrator = owner
123        machine.contact = contact
124        machine.uuid = uuidToString(randomUUID())
125        machine.boot_off_cd = True
126        machine.type_id = machine_type.type_id
127        ctx.current.save(machine)
128        disk = Disk(machine_id=machine.machine_id,
129                    guest_device_name='hda', size=disksize)
130        open_nics = NIC.select_by(machine_id=None)
131        if not open_nics: #No IPs left!
132            raise CodeError("No IP addresses left!  "
133                            "Contact xvm@mit.edu.")
134        nic = open_nics[0]
135        nic.machine_id = machine.machine_id
136        nic.hostname = name
137        ctx.current.save(nic)
138        ctx.current.save(disk)
139        cache_acls.refreshMachine(machine)
140        transaction.commit()
141    except:
142        transaction.rollback()
143        raise
144    makeDisks(machine)
145    if autoinstall:
146        lvinstall(machine, autoinstall)
147    # tell it to boot with cdrom
148    bootMachine(machine, cdrom)
149    return machine
150
151def getList():
152    """Return a dictionary mapping machine names to dicts."""
153    value_string = remctl('web', 'listvms')
154    value_dict = yaml.load(value_string, yaml.CSafeLoader)
155    return value_dict
156
157def parseStatus(s):
158    """Parse a status string into nested tuples of strings.
159
160    s = output of xm list --long <machine_name>
161    """
162    values = re.split('([()])', s)
163    stack = [[]]
164    for v in values[2:-2]: #remove initial and final '()'
165        if not v:
166            continue
167        v = v.strip()
168        if v == '(':
169            stack.append([])
170        elif v == ')':
171            if len(stack[-1]) == 1:
172                stack[-1].append('')
173            stack[-2].append(stack[-1])
174            stack.pop()
175        else:
176            if not v:
177                continue
178            stack[-1].extend(v.split())
179    return stack[-1]
180
181def statusInfo(machine):
182    """Return the status list for a given machine.
183
184    Gets and parses xm list --long
185    """
186    value_string, err_string = remctl('control', machine.name, 'list-long', 
187                                      err=True)
188    if 'Unknown command' in err_string:
189        raise CodeError("ERROR in remctl list-long %s is not registered" % 
190                        (machine.name,))
191    elif 'is not on' in err_string:
192        return None
193    elif err_string:
194        raise CodeError("ERROR in remctl list-long %s%s" % 
195                        (machine.name, err_string))
196    status = parseStatus(value_string)
197    return status
198
199def deleteVM(machine):
200    """Delete a VM."""
201    remctl('control', machine.name, 'destroy', err=True)
202    transaction = ctx.current.create_transaction()
203    delete_disk_pairs = [(machine.name, d.guest_device_name) 
204                         for d in machine.disks]
205    try:
206        for nic in machine.nics:
207            nic.machine_id = None
208            nic.hostname = None
209            ctx.current.save(nic)
210        for disk in machine.disks:
211            ctx.current.delete(disk)
212        ctx.current.delete(machine)
213        transaction.commit()
214    except:
215        transaction.rollback()
216        raise
217    for mname, dname in delete_disk_pairs:
218        remctl('web', 'lvremove', mname, dname)
219
220def commandResult(username, state, fields):
221    start_time = 0
222    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
223    action = fields.getfirst('action')
224    cdrom = fields.getfirst('cdrom')
225    if cdrom is not None and not CDROM.get(cdrom):
226        raise CodeError("Invalid cdrom type '%s'" % cdrom)   
227    if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 
228                      'Delete VM'):
229        raise CodeError("Invalid action '%s'" % action)
230    if action == 'Reboot':
231        if cdrom is not None:
232            out, err = remctl('control', machine.name, 'reboot', cdrom,
233                              err=True)
234        else:
235            out, err = remctl('control', machine.name, 'reboot',
236                              err=True)
237        if err:
238            if re.match("Error: Domain '.*' does not exist.", err):
239                raise InvalidInput("action", "reboot", 
240                                   "Machine is not on")
241            else:
242                print >> sys.stderr, 'Error on reboot:'
243                print >> sys.stderr, err
244                raise CodeError('ERROR on remctl')
245               
246    elif action == 'Power on':
247        if validation.maxMemory(username, state, machine) < machine.memory:
248            raise InvalidInput('action', 'Power on',
249                               "You don't have enough free RAM quota "
250                               "to turn on this machine.")
251        bootMachine(machine, cdrom)
252    elif action == 'Power off':
253        out, err = remctl('control', machine.name, 'destroy', err=True)
254        if err:
255            if re.match("Error: Domain '.*' does not exist.", err):
256                raise InvalidInput("action", "Power off", 
257                                   "Machine is not on.")
258            else:
259                print >> sys.stderr, 'Error on power off:'
260                print >> sys.stderr, err
261                raise CodeError('ERROR on remctl')
262    elif action == 'Shutdown':
263        out, err = remctl('control', machine.name, 'shutdown', err=True)
264        if err:
265            if re.match("Error: Domain '.*' does not exist.", err):
266                raise InvalidInput("action", "Shutdown", 
267                                   "Machine is not on.")
268            else:
269                print >> sys.stderr, 'Error on Shutdown:'
270                print >> sys.stderr, err
271                raise CodeError('ERROR on remctl')
272    elif action == 'Delete VM':
273        deleteVM(machine)
274
275    d = dict(user=username,
276             command=action,
277             machine=machine)
278    return d
279
280def resizeDisk(machine_name, disk_name, new_size):
281    remctl("web", "lvresize", machine_name, disk_name, new_size)
282
283def renameMachine(machine, old_name, new_name):
284    for disk in machine.disks:
285        remctl("web", "lvrename", old_name, 
286               disk.guest_device_name, new_name)
287   
Note: See TracBrowser for help on using the repository browser.