2 Functions to perform remctls.
5 from sipb_xen_database import Machine, Disk, Type, NIC, CDROM, ctx, meta
7 from webcommon import CodeError, InvalidInput
15 # ... and stolen from xend/uuid.py
17 """Generate a random UUID."""
19 return [ random.randint(0, 255) for _ in range(0, 16) ]
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)
27 def kinit(username = 'daemon/sipb-xen.mit.edu', keytab = '/etc/sipb-xen.keytab'):
28 """Kinit with a given username and keytab"""
30 p = subprocess.Popen(['kinit', "-k", "-t", keytab, username],
31 stderr=subprocess.PIPE)
34 raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
37 """If we lack tickets, kinit."""
38 p = subprocess.Popen(['klist', '-s'])
42 def remctl(*args, **kws):
43 """Perform a remctl and return the output.
45 kinits if necessary, and outputs errors to stderr.
48 p = subprocess.Popen(['remctl', 'black-mesa.mit.edu']
50 stdout=subprocess.PIPE,
51 stderr=subprocess.PIPE)
54 return p.stdout.read(), p.stderr.read()
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()
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))
66 def makeDisks(machine):
67 """Update the lvm partitions to add a disk."""
68 for disk in machine.disks:
69 lvcreate(machine, disk)
71 def bootMachine(machine, cdtype):
72 """Boot a machine with a given boot CD.
74 If cdtype is None, give no boot cd. Otherwise, it is the string
75 id of the CD (e.g. 'gutsy_i386')
77 if cdtype is not None:
78 out, err = remctl('control', machine.name, 'create',
81 out, err = remctl('control', machine.name, 'create',
83 if 'already exists' in out:
84 raise InvalidInput('action', 'create',
85 'VM %s is already on' % machine.name)
87 raise CodeError('"%s" on "control %s create %s'
88 % (err, machine.name, cdtype))
90 def registerMachine(machine):
91 """Register a machine to be controlled by the web interface"""
92 remctl('web', 'register', machine.name)
94 def unregisterMachine(machine):
95 """Unregister a machine to not be controlled by the web interface"""
96 remctl('web', 'unregister', machine.name)
98 def createVm(owner, contact, name, memory, disk_size, is_hvm, cdrom):
99 """Create a VM and put it in the database"""
100 # put stuff in the table
101 transaction = ctx.current.create_transaction()
103 validation.validMemory(owner, memory)
104 validation.validDisk(owner, disk_size * 1. / 1024)
105 validation.validAddVm(owner)
106 res = meta.engine.execute('select nextval('
107 '\'"machines_machine_id_seq"\')')
108 id = res.fetchone()[0]
110 machine.machine_id = id
112 machine.memory = memory
113 machine.owner = owner
114 machine.administrator = owner
115 machine.contact = contact
116 machine.uuid = uuidToString(randomUUID())
117 machine.boot_off_cd = True
118 machine_type = Type.get_by(hvm=is_hvm)
119 machine.type_id = machine_type.type_id
120 ctx.current.save(machine)
121 disk = Disk(machine_id=machine.machine_id,
122 guest_device_name='hda', size=disk_size)
123 open_nics = NIC.select_by(machine_id=None)
124 if not open_nics: #No IPs left!
125 raise CodeError("No IP addresses left! "
126 "Contact sipb-xen-dev@mit.edu")
128 nic.machine_id = machine.machine_id
130 ctx.current.save(nic)
131 ctx.current.save(disk)
132 cache_acls.refreshMachine(machine)
135 transaction.rollback()
137 registerMachine(machine)
139 # tell it to boot with cdrom
140 bootMachine(machine, cdrom)
143 def getUptimes(machines=None):
144 """Return a dictionary mapping machine names to uptime strings"""
145 value_string = remctl('web', 'listvms')
146 lines = value_string.splitlines()
151 uptime = ' '.join(lst[2:])
155 ans[m] = d.get(m.name)
159 """Parse a status string into nested tuples of strings.
161 s = output of xm list --long <machine_name>
163 values = re.split('([()])', s)
165 for v in values[2:-2]: #remove initial and final '()'
172 if len(stack[-1]) == 1:
174 stack[-2].append(stack[-1])
179 stack[-1].extend(v.split())
182 def statusInfo(machine):
183 """Return the status list for a given machine.
185 Gets and parses xm list --long
187 value_string, err_string = remctl('control', machine.name, 'list-long',
189 if 'Unknown command' in err_string:
190 raise CodeError("ERROR in remctl list-long %s is not registered" %
192 elif 'does not exist' in err_string:
195 raise CodeError("ERROR in remctl list-long %s: %s" %
196 (machine.name, err_string))
197 status = parseStatus(value_string)
200 def deleteVM(machine):
202 remctl('control', machine.name, 'destroy', err=True)
203 transaction = ctx.current.create_transaction()
204 delete_disk_pairs = [(machine.name, d.guest_device_name)
205 for d in machine.disks]
207 for nic in machine.nics:
208 nic.machine_id = None
210 ctx.current.save(nic)
211 for disk in machine.disks:
212 ctx.current.delete(disk)
213 for access in machine.acl:
214 ctx.current.delete(access)
215 ctx.current.delete(machine)
218 transaction.rollback()
220 for mname, dname in delete_disk_pairs:
221 remctl('web', 'lvremove', mname, dname)
222 unregisterMachine(machine)
224 def commandResult(user, fields):
226 machine = validation.testMachineId(user, fields.getfirst('machine_id'))
227 action = fields.getfirst('action')
228 cdrom = fields.getfirst('cdrom')
229 if cdrom is not None and not CDROM.get(cdrom):
230 raise CodeError("Invalid cdrom type '%s'" % cdrom)
231 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
233 raise CodeError("Invalid action '%s'" % action)
234 if action == 'Reboot':
235 if cdrom is not None:
236 out, err = remctl('control', machine.name, 'reboot', cdrom,
239 out, err = remctl('control', machine.name, 'reboot',
242 if re.match("Error: Domain '.*' does not exist.", err):
243 raise InvalidInput("action", "reboot",
246 print >> sys.stderr, 'Error on reboot:'
247 print >> sys.stderr, err
248 raise CodeError('ERROR on remctl')
250 elif action == 'Power on':
251 if validation.maxMemory(user, machine) < machine.memory:
252 raise InvalidInput('action', 'Power on',
253 "You don't have enough free RAM quota "
254 "to turn on this machine.")
255 bootMachine(machine, cdrom)
256 elif action == 'Power off':
257 out, err = remctl('control', machine.name, 'destroy', err=True)
259 if re.match("Error: Domain '.*' does not exist.", err):
260 raise InvalidInput("action", "Power off",
261 "Machine is not on.")
263 print >> sys.stderr, 'Error on power off:'
264 print >> sys.stderr, err
265 raise CodeError('ERROR on remctl')
266 elif action == 'Shutdown':
267 out, err = remctl('control', machine.name, 'shutdown', err=True)
269 if re.match("Error: Domain '.*' does not exist.", err):
270 raise InvalidInput("action", "Shutdown",
271 "Machine is not on.")
273 print >> sys.stderr, 'Error on Shutdown:'
274 print >> sys.stderr, err
275 raise CodeError('ERROR on remctl')
276 elif action == 'Delete VM':
284 def resizeDisk(machine_name, disk_name, new_size):
285 remctl("web", "lvresize", machine_name, disk_name, new_size)
287 def renameMachine(machine, old_name, new_name):
288 for disk in machine.disks:
289 remctl("web", "lvrename", old_name,
290 disk.guest_device_name, new_name)
291 remctl("web", "moveregister", old_name, new_name)