2 from invirt.common import CodeError, InvalidInput
10 from invirt.config import structs as config
11 from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
12 from invirt.remctl import remctl as gen_remctl
14 # ... and stolen from xend/uuid.py
16 """Generate a random UUID."""
18 return [ random.randint(0, 255) for _ in range(0, 16) ]
21 """Turn a numeric UUID to a hyphen-seperated one."""
22 return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
23 "%02x" * 6]) % tuple(u)
26 def remctl(*args, **kwargs):
27 return gen_remctl(config.remote.hostname,
28 principal='daemon/'+config.web.hostname,
31 def lvcreate(machine, disk):
32 """Create a single disk for a machine"""
33 remctl('web', 'lvcreate', machine.name,
34 disk.guest_device_name, str(disk.size))
36 def makeDisks(machine):
37 """Update the lvm partitions to add a disk."""
38 for disk in machine.disks:
39 lvcreate(machine, disk)
41 def getswap(disksize, memsize):
42 """Returns the recommended swap partition size."""
43 return int(min(disksize / 4, memsize * 1.5))
45 def lvinstall(machine, autoinstall):
46 #raise InvalidInput('autoinstall', 'install',
47 # "The autoinstaller has been temporarily disabled")
48 disksize = machine.disks[0].size
49 memsize = machine.memory
50 swapsize = getswap(disksize, memsize)
51 imagesize = disksize - swapsize
52 ip = machine.nics[0].ip
53 remctl('control', machine.name, 'install',
54 'dist=%s' % autoinstall.distribution,
55 'mirror=%s' % autoinstall.mirror,
56 'imagesize=%s' % imagesize)
58 def lvcopy(machine_orig_name, machine, rootpw):
59 """Copy a golden image onto a machine's disk"""
60 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
62 def bootMachine(machine, cdtype):
63 """Boot a machine with a given boot CD.
65 If cdtype is None, give no boot cd. Otherwise, it is the string
66 id of the CD (e.g. 'gutsy_i386')
68 if cdtype is not None:
69 out, err = remctl('control', machine.name, 'create',
72 out, err = remctl('control', machine.name, 'create',
74 if 'already running' in err:
75 raise InvalidInput('action', 'create',
76 'VM %s is already on' % machine.name)
78 raise CodeError('"%s" on "control %s create %s'
79 % (err, machine.name, cdtype))
81 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
82 """Create a VM and put it in the database"""
83 # put stuff in the table
86 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
89 machine.description = description
90 machine.memory = memory
92 machine.administrator = owner
93 machine.contact = contact
94 machine.uuid = uuidToString(randomUUID())
95 machine.boot_off_cd = True
96 machine.type = machine_type
97 session.save_or_update(machine)
98 disk = Disk(machine=machine,
99 guest_device_name='hda', size=disksize)
100 nic = NIC.query().filter_by(machine_id=None).first()
101 if not nic: #No IPs left!
102 raise CodeError("No IP addresses left! "
103 "Contact %s." % config.web.errormail)
104 nic.machine = machine
106 session.save_or_update(nic)
107 session.save_or_update(disk)
108 cache_acls.refreshMachine(machine)
115 lvinstall(machine, autoinstall)
117 # tell it to boot with cdrom
118 bootMachine(machine, cdrom)
122 """Return a dictionary mapping machine names to dicts."""
123 value_string = remctl('web', 'listvms')
124 value_dict = yaml.load(value_string, yaml.CSafeLoader)
128 """Parse a status string into nested tuples of strings.
130 s = output of xm list --long <machine_name>
132 values = re.split('([()])', s)
134 for v in values[2:-2]: #remove initial and final '()'
141 if len(stack[-1]) == 1:
143 stack[-2].append(stack[-1])
148 stack[-1].extend(v.split())
151 def statusInfo(machine):
152 """Return the status list for a given machine.
154 Gets and parses xm list --long
156 value_string, err_string = remctl('control', machine.name, 'list-long',
158 if 'Unknown command' in err_string:
159 raise CodeError("ERROR in remctl list-long %s is not registered" %
161 elif 'is not on' in err_string:
164 raise CodeError("ERROR in remctl list-long %s: %s" %
165 (machine.name, err_string))
166 status = parseStatus(value_string)
169 def listHost(machine):
170 """Return the host a machine is running on"""
171 out, err = remctl('control', machine.name, 'listhost', err=True)
176 def vnctoken(machine):
177 """Return a time-stamped VNC token"""
178 out, err = remctl('control', machine.name, 'vnctoken', err=True)
183 def deleteVM(machine):
185 remctl('control', machine.name, 'destroy', err=True)
187 delete_disk_pairs = [(machine.name, d.guest_device_name)
188 for d in machine.disks]
190 for mname, dname in delete_disk_pairs:
191 remctl('web', 'lvremove', mname, dname)
192 for nic in machine.nics:
193 nic.machine_id = None
195 session.save_or_update(nic)
196 for disk in machine.disks:
198 session.delete(machine)
204 def commandResult(username, state, fields):
206 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
207 action = fields.getfirst('action')
208 cdrom = fields.getfirst('cdrom')
209 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
210 raise CodeError("Invalid cdrom type '%s'" % cdrom)
211 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
213 raise CodeError("Invalid action '%s'" % action)
214 if action == 'Reboot':
215 if cdrom is not None:
216 out, err = remctl('control', machine.name, 'reboot', cdrom,
219 out, err = remctl('control', machine.name, 'reboot',
222 if re.match("machine '.*' is not on", err):
223 raise InvalidInput("action", "reboot",
226 print >> sys.stderr, 'Error on reboot:'
227 print >> sys.stderr, err
228 raise CodeError('ERROR on remctl')
230 elif action == 'Power on':
231 if validation.maxMemory(username, state, machine) < machine.memory:
232 raise InvalidInput('action', 'Power on',
233 "You don't have enough free RAM quota "
234 "to turn on this machine.")
235 bootMachine(machine, cdrom)
236 elif action == 'Power off':
237 out, err = remctl('control', machine.name, 'destroy', err=True)
239 if re.match("machine '.*' is not on", err):
240 raise InvalidInput("action", "Power off",
241 "Machine is not on.")
243 print >> sys.stderr, 'Error on power off:'
244 print >> sys.stderr, err
245 raise CodeError('ERROR on remctl')
246 elif action == 'Shutdown':
247 out, err = remctl('control', machine.name, 'shutdown', err=True)
249 if re.match("machine '.*' is not on", err):
250 raise InvalidInput("action", "Shutdown",
251 "Machine is not on.")
253 print >> sys.stderr, 'Error on Shutdown:'
254 print >> sys.stderr, err
255 raise CodeError('ERROR on remctl')
256 elif action == 'Delete VM':
259 d = dict(user=username,
264 def resizeDisk(machine_name, disk_name, new_size):
265 remctl("web", "lvresize", machine_name, disk_name, new_size)
267 def renameMachine(machine, old_name, new_name):
268 for disk in machine.disks:
269 remctl("web", "lvrename", old_name,
270 disk.guest_device_name, new_name)