Default type in info page
[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, machine_type, 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_id = machine_type.type_id
123         ctx.current.save(machine)
124         disk = Disk(machine_id=machine.machine_id, 
125                     guest_device_name='hda', size=disk_size)
126         open_nics = NIC.select_by(machine_id=None)
127         if not open_nics: #No IPs left!
128             raise CodeError("No IP addresses left!  "
129                             "Contact sipb-xen@mit.edu.")
130         nic = open_nics[0]
131         nic.machine_id = machine.machine_id
132         nic.hostname = name
133         ctx.current.save(nic)    
134         ctx.current.save(disk)
135         cache_acls.refreshMachine(machine)
136         transaction.commit()
137     except:
138         transaction.rollback()
139         raise
140     registerMachine(machine)
141     makeDisks(machine)
142     if clone_from:
143         lvcopy(clone_from, machine, 'password')
144     # tell it to boot with cdrom
145     bootMachine(machine, cdrom)
146     return machine
147
148 def getUptimes(machines=None):
149     """Return a dictionary mapping machine names to uptime strings"""
150     value_string = remctl('web', 'listvms')
151     lines = value_string.splitlines()
152     d = {}
153     for line in lines:
154         lst = line.split()
155         name, id = lst[:2]
156         uptime = ' '.join(lst[2:])
157         d[name] = uptime
158     ans = {}
159     for m in machines:
160         ans[m] = d.get(m.name)
161     return ans
162
163 def parseStatus(s):
164     """Parse a status string into nested tuples of strings.
165
166     s = output of xm list --long <machine_name>
167     """
168     values = re.split('([()])', s)
169     stack = [[]]
170     for v in values[2:-2]: #remove initial and final '()'
171         if not v:
172             continue
173         v = v.strip()
174         if v == '(':
175             stack.append([])
176         elif v == ')':
177             if len(stack[-1]) == 1:
178                 stack[-1].append('')
179             stack[-2].append(stack[-1])
180             stack.pop()
181         else:
182             if not v:
183                 continue
184             stack[-1].extend(v.split())
185     return stack[-1]
186
187 def statusInfo(machine):
188     """Return the status list for a given machine.
189
190     Gets and parses xm list --long
191     """
192     value_string, err_string = remctl('control', machine.name, 'list-long', 
193                                       err=True)
194     if 'Unknown command' in err_string:
195         raise CodeError("ERROR in remctl list-long %s is not registered" % 
196                         (machine.name,))
197     elif 'does not exist' in err_string:
198         return None
199     elif err_string:
200         raise CodeError("ERROR in remctl list-long %s:  %s" % 
201                         (machine.name, err_string))
202     status = parseStatus(value_string)
203     return status
204
205 def deleteVM(machine):
206     """Delete a VM."""
207     remctl('control', machine.name, 'destroy', err=True)
208     transaction = ctx.current.create_transaction()
209     delete_disk_pairs = [(machine.name, d.guest_device_name) 
210                          for d in machine.disks]
211     try:
212         for nic in machine.nics:
213             nic.machine_id = None
214             nic.hostname = None
215             ctx.current.save(nic)
216         for disk in machine.disks:
217             ctx.current.delete(disk)
218         for access in machine.acl:
219             ctx.current.delete(access)
220         ctx.current.delete(machine)
221         transaction.commit()
222     except:
223         transaction.rollback()
224         raise
225     for mname, dname in delete_disk_pairs:
226         remctl('web', 'lvremove', mname, dname)
227     unregisterMachine(machine)
228
229 def commandResult(user, fields):
230     start_time = 0
231     machine = validation.testMachineId(user, fields.getfirst('machine_id'))
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:
247             if re.match("Error: Domain '.*' does not exist.", err):
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':
256         if validation.maxMemory(user, machine) < machine.memory:
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:
264             if re.match("Error: Domain '.*' does not exist.", err):
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:
274             if re.match("Error: Domain '.*' does not exist.", err):
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
284     d = dict(user=user,
285              command=action,
286              machine=machine)
287     return d
288
289 def resizeDisk(machine_name, disk_name, new_size):
290     remctl("web", "lvresize", machine_name, disk_name, new_size)
291
292 def 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     remctl("web", "moveregister", old_name, new_name)
297