use remote in web interface
[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', 'remote.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 createVm(owner, contact, name, memory, disk_size, machine_type, cdrom, clone_from):
95     """Create a VM and put it in the database"""
96     # put stuff in the table
97     transaction = ctx.current.create_transaction()
98     try:
99         validation.validMemory(owner, memory)
100         validation.validDisk(owner, disk_size  * 1. / 1024)
101         validation.validAddVm(owner)
102         res = meta.engine.execute('select nextval('
103                                   '\'"machines_machine_id_seq"\')')
104         id = res.fetchone()[0]
105         machine = Machine()
106         machine.machine_id = id
107         machine.name = name
108         machine.memory = memory
109         machine.owner = owner
110         machine.administrator = owner
111         machine.contact = contact
112         machine.uuid = uuidToString(randomUUID())
113         machine.boot_off_cd = True
114         machine.type_id = machine_type.type_id
115         ctx.current.save(machine)
116         disk = Disk(machine_id=machine.machine_id, 
117                     guest_device_name='hda', size=disk_size)
118         open_nics = NIC.select_by(machine_id=None)
119         if not open_nics: #No IPs left!
120             raise CodeError("No IP addresses left!  "
121                             "Contact sipb-xen@mit.edu.")
122         nic = open_nics[0]
123         nic.machine_id = machine.machine_id
124         nic.hostname = name
125         ctx.current.save(nic)    
126         ctx.current.save(disk)
127         cache_acls.refreshMachine(machine)
128         transaction.commit()
129     except:
130         transaction.rollback()
131         raise
132     makeDisks(machine)
133     if clone_from:
134         lvcopy(clone_from, machine, 'password')
135     # tell it to boot with cdrom
136     bootMachine(machine, cdrom)
137     return machine
138
139 def getUptimes(machines=None):
140     """Return a dictionary mapping machine names to uptime strings"""
141     value_string = remctl('web', 'listvms')
142     lines = value_string.splitlines()
143     d = {}
144     for line in lines:
145         lst = line.split()
146         name, id = lst[:2]
147         uptime = ' '.join(lst[2:])
148         d[name] = uptime
149     ans = {}
150     for m in machines:
151         ans[m] = d.get(m.name)
152     return ans
153
154 def parseStatus(s):
155     """Parse a status string into nested tuples of strings.
156
157     s = output of xm list --long <machine_name>
158     """
159     values = re.split('([()])', s)
160     stack = [[]]
161     for v in values[2:-2]: #remove initial and final '()'
162         if not v:
163             continue
164         v = v.strip()
165         if v == '(':
166             stack.append([])
167         elif v == ')':
168             if len(stack[-1]) == 1:
169                 stack[-1].append('')
170             stack[-2].append(stack[-1])
171             stack.pop()
172         else:
173             if not v:
174                 continue
175             stack[-1].extend(v.split())
176     return stack[-1]
177
178 def statusInfo(machine):
179     """Return the status list for a given machine.
180
181     Gets and parses xm list --long
182     """
183     value_string, err_string = remctl('control', machine.name, 'list-long', 
184                                       err=True)
185     if 'Unknown command' in err_string:
186         raise CodeError("ERROR in remctl list-long %s is not registered" % 
187                         (machine.name,))
188     elif 'does not exist' in err_string:
189         return None
190     elif err_string:
191         raise CodeError("ERROR in remctl list-long %s:  %s" % 
192                         (machine.name, err_string))
193     status = parseStatus(value_string)
194     return status
195
196 def deleteVM(machine):
197     """Delete a VM."""
198     remctl('control', machine.name, 'destroy', err=True)
199     transaction = ctx.current.create_transaction()
200     delete_disk_pairs = [(machine.name, d.guest_device_name) 
201                          for d in machine.disks]
202     try:
203         for nic in machine.nics:
204             nic.machine_id = None
205             nic.hostname = None
206             ctx.current.save(nic)
207         for disk in machine.disks:
208             ctx.current.delete(disk)
209         for access in machine.acl:
210             ctx.current.delete(access)
211         ctx.current.delete(machine)
212         transaction.commit()
213     except:
214         transaction.rollback()
215         raise
216     for mname, dname in delete_disk_pairs:
217         remctl('web', 'lvremove', mname, dname)
218
219 def commandResult(user, fields):
220     start_time = 0
221     machine = validation.testMachineId(user, fields.getfirst('machine_id'))
222     action = fields.getfirst('action')
223     cdrom = fields.getfirst('cdrom')
224     if cdrom is not None and not CDROM.get(cdrom):
225         raise CodeError("Invalid cdrom type '%s'" % cdrom)    
226     if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 
227                       'Delete VM'):
228         raise CodeError("Invalid action '%s'" % action)
229     if action == 'Reboot':
230         if cdrom is not None:
231             out, err = remctl('control', machine.name, 'reboot', cdrom,
232                               err=True)
233         else:
234             out, err = remctl('control', machine.name, 'reboot',
235                               err=True)
236         if err:
237             if re.match("Error: Domain '.*' does not exist.", err):
238                 raise InvalidInput("action", "reboot", 
239                                    "Machine is not on")
240             else:
241                 print >> sys.stderr, 'Error on reboot:'
242                 print >> sys.stderr, err
243                 raise CodeError('ERROR on remctl')
244                 
245     elif action == 'Power on':
246         if validation.maxMemory(user, machine) < machine.memory:
247             raise InvalidInput('action', 'Power on',
248                                "You don't have enough free RAM quota "
249                                "to turn on this machine.")
250         bootMachine(machine, cdrom)
251     elif action == 'Power off':
252         out, err = remctl('control', machine.name, 'destroy', err=True)
253         if err:
254             if re.match("Error: Domain '.*' does not exist.", err):
255                 raise InvalidInput("action", "Power off", 
256                                    "Machine is not on.")
257             else:
258                 print >> sys.stderr, 'Error on power off:'
259                 print >> sys.stderr, err
260                 raise CodeError('ERROR on remctl')
261     elif action == 'Shutdown':
262         out, err = remctl('control', machine.name, 'shutdown', err=True)
263         if err:
264             if re.match("Error: Domain '.*' does not exist.", err):
265                 raise InvalidInput("action", "Shutdown", 
266                                    "Machine is not on.")
267             else:
268                 print >> sys.stderr, 'Error on Shutdown:'
269                 print >> sys.stderr, err
270                 raise CodeError('ERROR on remctl')
271     elif action == 'Delete VM':
272         deleteVM(machine)
273
274     d = dict(user=user,
275              command=action,
276              machine=machine)
277     return d
278
279 def resizeDisk(machine_name, disk_name, new_size):
280     remctl("web", "lvresize", machine_name, disk_name, new_size)
281
282 def renameMachine(machine, old_name, new_name):
283     for disk in machine.disks:
284         remctl("web", "lvrename", old_name, 
285                disk.guest_device_name, new_name)
286