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