2 Functions to perform remctls.
5 from sipb_xen_database import Machine, Disk, Type, NIC, CDROM, ctx, meta
7 from webcommon import CodeError, InvalidInput
16 # ... and stolen from xend/uuid.py
18 """Generate a random UUID."""
20 return [ random.randint(0, 255) for _ in range(0, 16) ]
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)
28 def kinit(username = 'daemon/sipb-xen.mit.edu', keytab = '/etc/sipb-xen.keytab'):
29 """Kinit with a given username and keytab"""
31 p = subprocess.Popen(['kinit', "-k", "-t", keytab, username],
32 stderr=subprocess.PIPE)
35 raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
38 """If we lack tickets, kinit."""
39 p = subprocess.Popen(['klist', '-s'])
43 def remctl(*args, **kws):
44 """Perform a remctl and return the output.
46 kinits if necessary, and outputs errors to stderr.
49 p = subprocess.Popen(['remctl', 'remote.mit.edu']
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE)
55 return p.stdout.read(), p.stderr.read()
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()
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))
67 def makeDisks(machine):
68 """Update the lvm partitions to add a disk."""
69 for disk in machine.disks:
70 lvcreate(machine, disk)
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)
76 def bootMachine(machine, cdtype):
77 """Boot a machine with a given boot CD.
79 If cdtype is None, give no boot cd. Otherwise, it is the string
80 id of the CD (e.g. 'gutsy_i386')
82 if cdtype is not None:
83 out, err = remctl('control', machine.name, 'create',
86 out, err = remctl('control', machine.name, 'create',
88 if 'already exists' in out:
89 raise InvalidInput('action', 'create',
90 'VM %s is already on' % machine.name)
92 raise CodeError('"%s" on "control %s create %s'
93 % (err, machine.name, cdtype))
95 def createVm(username, state, owner, contact, name, memory, disksize, 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()
100 validation.Validate(username, state, name=name, owner=owner, memory=memory, disksize=disksize/1024.)
101 res = meta.engine.execute('select nextval('
102 '\'"machines_machine_id_seq"\')')
103 id = res.fetchone()[0]
105 machine.machine_id = id
107 machine.memory = memory
108 machine.owner = owner
109 machine.administrator = owner
110 machine.contact = contact
111 machine.uuid = uuidToString(randomUUID())
112 machine.boot_off_cd = True
113 machine.type_id = machine_type.type_id
114 ctx.current.save(machine)
115 disk = Disk(machine_id=machine.machine_id,
116 guest_device_name='hda', size=disksize)
117 open_nics = NIC.select_by(machine_id=None)
118 if not open_nics: #No IPs left!
119 raise CodeError("No IP addresses left! "
120 "Contact xvm@mit.edu.")
122 nic.machine_id = machine.machine_id
124 ctx.current.save(nic)
125 ctx.current.save(disk)
126 cache_acls.refreshMachine(machine)
129 transaction.rollback()
133 lvcopy(clone_from, machine, 'password')
134 # tell it to boot with cdrom
135 bootMachine(machine, cdrom)
139 """Return a dictionary mapping machine names to dicts."""
140 value_string = remctl('web', 'listvms')
141 value_dict = yaml.load(value_string, yaml.CSafeLoader)
145 """Parse a status string into nested tuples of strings.
147 s = output of xm list --long <machine_name>
149 values = re.split('([()])', s)
151 for v in values[2:-2]: #remove initial and final '()'
158 if len(stack[-1]) == 1:
160 stack[-2].append(stack[-1])
165 stack[-1].extend(v.split())
168 def statusInfo(machine):
169 """Return the status list for a given machine.
171 Gets and parses xm list --long
173 value_string, err_string = remctl('control', machine.name, 'list-long',
175 if 'Unknown command' in err_string:
176 raise CodeError("ERROR in remctl list-long %s is not registered" %
178 elif 'does not exist' in err_string:
181 raise CodeError("ERROR in remctl list-long %s: %s" %
182 (machine.name, err_string))
183 status = parseStatus(value_string)
186 def deleteVM(machine):
188 remctl('control', machine.name, 'destroy', err=True)
189 transaction = ctx.current.create_transaction()
190 delete_disk_pairs = [(machine.name, d.guest_device_name)
191 for d in machine.disks]
193 for nic in machine.nics:
194 nic.machine_id = None
196 ctx.current.save(nic)
197 for disk in machine.disks:
198 ctx.current.delete(disk)
199 for access in machine.acl:
200 ctx.current.delete(access)
201 ctx.current.delete(machine)
204 transaction.rollback()
206 for mname, dname in delete_disk_pairs:
207 remctl('web', 'lvremove', mname, dname)
209 def commandResult(username, state, fields):
211 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
212 action = fields.getfirst('action')
213 cdrom = fields.getfirst('cdrom')
214 if cdrom is not None and not CDROM.get(cdrom):
215 raise CodeError("Invalid cdrom type '%s'" % cdrom)
216 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
218 raise CodeError("Invalid action '%s'" % action)
219 if action == 'Reboot':
220 if cdrom is not None:
221 out, err = remctl('control', machine.name, 'reboot', cdrom,
224 out, err = remctl('control', machine.name, 'reboot',
227 if re.match("Error: Domain '.*' does not exist.", err):
228 raise InvalidInput("action", "reboot",
231 print >> sys.stderr, 'Error on reboot:'
232 print >> sys.stderr, err
233 raise CodeError('ERROR on remctl')
235 elif action == 'Power on':
236 if validation.maxMemory(username, state, machine) < machine.memory:
237 raise InvalidInput('action', 'Power on',
238 "You don't have enough free RAM quota "
239 "to turn on this machine.")
240 bootMachine(machine, cdrom)
241 elif action == 'Power off':
242 out, err = remctl('control', machine.name, 'destroy', err=True)
244 if re.match("Error: Domain '.*' does not exist.", err):
245 raise InvalidInput("action", "Power off",
246 "Machine is not on.")
248 print >> sys.stderr, 'Error on power off:'
249 print >> sys.stderr, err
250 raise CodeError('ERROR on remctl')
251 elif action == 'Shutdown':
252 out, err = remctl('control', machine.name, 'shutdown', err=True)
254 if re.match("Error: Domain '.*' does not exist.", err):
255 raise InvalidInput("action", "Shutdown",
256 "Machine is not on.")
258 print >> sys.stderr, 'Error on Shutdown:'
259 print >> sys.stderr, err
260 raise CodeError('ERROR on remctl')
261 elif action == 'Delete VM':
264 d = dict(user=username,
269 def resizeDisk(machine_name, disk_name, new_size):
270 remctl("web", "lvresize", machine_name, disk_name, new_size)
272 def renameMachine(machine, old_name, new_name):
273 for disk in machine.disks:
274 remctl("web", "lvrename", old_name,
275 disk.guest_device_name, new_name)