2 Functions to perform remctls.
6 from webcommon import CodeError, InvalidInput
15 from invirt.config import structs as config
16 from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
18 # ... and stolen from xend/uuid.py
20 """Generate a random UUID."""
22 return [ random.randint(0, 255) for _ in range(0, 16) ]
25 """Turn a numeric UUID to a hyphen-seperated one."""
26 return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
27 "%02x" * 6]) % tuple(u)
31 """Kinit with a given username and keytab"""
32 p = subprocess.Popen(['kinit', "-k", "-t", '/etc/invirt/keytab',
33 'daemon/'+config.web.hostname],
34 stderr=subprocess.PIPE)
37 raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
40 """If we lack tickets, kinit."""
41 p = subprocess.Popen(['klist', '-s'])
45 def remctl(*args, **kws):
46 """Perform a remctl and return the output.
48 kinits if necessary, and outputs errors to stderr.
51 p = subprocess.Popen(['remctl', config.remote.hostname]
53 stdout=subprocess.PIPE,
54 stderr=subprocess.PIPE)
57 return p.stdout.read(), p.stderr.read()
59 print >> sys.stderr, 'Error', v, 'on remctl', args, ':'
60 print >> sys.stderr, p.stderr.read()
61 raise CodeError('ERROR on remctl')
62 return p.stdout.read()
64 def lvcreate(machine, disk):
65 """Create a single disk for a machine"""
66 remctl('web', 'lvcreate', machine.name,
67 disk.guest_device_name, str(disk.size))
69 def makeDisks(machine):
70 """Update the lvm partitions to add a disk."""
71 for disk in machine.disks:
72 lvcreate(machine, disk)
74 def getswap(disksize, memsize):
75 """Returns the recommended swap partition size."""
76 return int(min(disksize / 4, memsize * 1.5))
78 def lvinstall(machine, autoinstall):
79 disksize = machine.disks[0].size
80 memsize = machine.memory
81 swapsize = getswap(disksize, memsize)
82 imagesize = disksize - swapsize
83 ip = machine.nics[0].ip
84 remctl('control', machine.name, 'install',
85 'dist=%s' % autoinstall.distribution,
86 'mirror=%s' % autoinstall.mirror,
87 'imagesize=%s' % imagesize)
89 def lvcopy(machine_orig_name, machine, rootpw):
90 """Copy a golden image onto a machine's disk"""
91 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
93 def bootMachine(machine, cdtype):
94 """Boot a machine with a given boot CD.
96 If cdtype is None, give no boot cd. Otherwise, it is the string
97 id of the CD (e.g. 'gutsy_i386')
99 if cdtype is not None:
100 out, err = remctl('control', machine.name, 'create',
103 out, err = remctl('control', machine.name, 'create',
105 if 'already running' in err:
106 raise InvalidInput('action', 'create',
107 'VM %s is already on' % machine.name)
109 raise CodeError('"%s" on "control %s create %s'
110 % (err, machine.name, cdtype))
112 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
113 """Create a VM and put it in the database"""
114 # put stuff in the table
117 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
120 machine.description = description
121 machine.memory = memory
122 machine.owner = owner
123 machine.administrator = owner
124 machine.contact = contact
125 machine.uuid = uuidToString(randomUUID())
126 machine.boot_off_cd = True
127 machine.type = machine_type
128 session.save_or_update(machine)
129 disk = Disk(machine=machine,
130 guest_device_name='hda', size=disksize)
131 nic = NIC.query().filter_by(machine_id=None).first()
132 if not nic: #No IPs left!
133 raise CodeError("No IP addresses left! "
134 "Contact %s." % config.web.errormail)
135 nic.machine = machine
137 session.save_or_update(nic)
138 session.save_or_update(disk)
139 cache_acls.refreshMachine(machine)
146 lvinstall(machine, autoinstall)
147 # tell it to boot with cdrom
148 bootMachine(machine, cdrom)
152 """Return a dictionary mapping machine names to dicts."""
153 value_string = remctl('web', 'listvms')
154 value_dict = yaml.load(value_string, yaml.CSafeLoader)
158 """Parse a status string into nested tuples of strings.
160 s = output of xm list --long <machine_name>
162 values = re.split('([()])', s)
164 for v in values[2:-2]: #remove initial and final '()'
171 if len(stack[-1]) == 1:
173 stack[-2].append(stack[-1])
178 stack[-1].extend(v.split())
181 def statusInfo(machine):
182 """Return the status list for a given machine.
184 Gets and parses xm list --long
186 value_string, err_string = remctl('control', machine.name, 'list-long',
188 if 'Unknown command' in err_string:
189 raise CodeError("ERROR in remctl list-long %s is not registered" %
191 elif 'is not on' in err_string:
194 raise CodeError("ERROR in remctl list-long %s: %s" %
195 (machine.name, err_string))
196 status = parseStatus(value_string)
199 def listHost(machine):
200 """Return the host a machine is running on"""
201 out, err = remctl('control', machine.name, 'listhost', err=True)
206 def deleteVM(machine):
208 remctl('control', machine.name, 'destroy', err=True)
210 delete_disk_pairs = [(machine.name, d.guest_device_name)
211 for d in machine.disks]
213 for mname, dname in delete_disk_pairs:
214 remctl('web', 'lvremove', mname, dname)
215 for nic in machine.nics:
216 nic.machine_id = None
218 session.save_or_update(nic)
219 for disk in machine.disks:
221 session.delete(machine)
227 def commandResult(username, state, fields):
229 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
230 action = fields.getfirst('action')
231 cdrom = fields.getfirst('cdrom')
232 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
233 raise CodeError("Invalid cdrom type '%s'" % cdrom)
234 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
236 raise CodeError("Invalid action '%s'" % action)
237 if action == 'Reboot':
238 if cdrom is not None:
239 out, err = remctl('control', machine.name, 'reboot', cdrom,
242 out, err = remctl('control', machine.name, 'reboot',
245 if re.match("machine '.*' is not on", err):
246 raise InvalidInput("action", "reboot",
249 print >> sys.stderr, 'Error on reboot:'
250 print >> sys.stderr, err
251 raise CodeError('ERROR on remctl')
253 elif action == 'Power on':
254 if validation.maxMemory(username, state, machine) < machine.memory:
255 raise InvalidInput('action', 'Power on',
256 "You don't have enough free RAM quota "
257 "to turn on this machine.")
258 bootMachine(machine, cdrom)
259 elif action == 'Power off':
260 out, err = remctl('control', machine.name, 'destroy', err=True)
262 if re.match("machine '.*' is not on", err):
263 raise InvalidInput("action", "Power off",
264 "Machine is not on.")
266 print >> sys.stderr, 'Error on power off:'
267 print >> sys.stderr, err
268 raise CodeError('ERROR on remctl')
269 elif action == 'Shutdown':
270 out, err = remctl('control', machine.name, 'shutdown', err=True)
272 if re.match("machine '.*' is not on", err):
273 raise InvalidInput("action", "Shutdown",
274 "Machine is not on.")
276 print >> sys.stderr, 'Error on Shutdown:'
277 print >> sys.stderr, err
278 raise CodeError('ERROR on remctl')
279 elif action == 'Delete VM':
282 d = dict(user=username,
287 def resizeDisk(machine_name, disk_name, new_size):
288 remctl("web", "lvresize", machine_name, disk_name, new_size)
290 def renameMachine(machine, old_name, new_name):
291 for disk in machine.disks:
292 remctl("web", "lvrename", old_name,
293 disk.guest_device_name, new_name)