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