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 disksize = machine.disks[0].size
47 memsize = machine.memory
48 swapsize = getswap(disksize, memsize)
49 imagesize = disksize - swapsize
50 ip = machine.nics[0].ip
51 remctl('control', machine.name, 'install',
52 'dist=%s' % autoinstall.distribution,
53 'mirror=%s' % autoinstall.mirror,
54 'arch=%s' % autoinstall.arch,
55 'imagesize=%s' % imagesize)
57 def lvcopy(machine_orig_name, machine, rootpw):
58 """Copy a golden image onto a machine's disk"""
59 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
61 def bootMachine(machine, cdtype):
62 """Boot a machine with a given boot CD.
64 If cdtype is None, give no boot cd. Otherwise, it is the string
65 id of the CD (e.g. 'gutsy_i386')
68 if cdtype is not None:
69 out = remctl('control', machine.name, 'create',
72 out = remctl('control', machine.name, 'create')
74 if 'already running' in e.message:
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 = None
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)
116 lvinstall(machine, autoinstall)
118 # tell it to boot with cdrom
119 bootMachine(machine, cdrom)
126 """Return a dictionary mapping machine names to dicts."""
127 value_string = remctl('web', 'listvms')
128 value_dict = yaml.load(value_string, yaml.CSafeLoader)
132 """Parse a status string into nested tuples of strings.
134 s = output of xm list --long <machine_name>
136 values = re.split('([()])', s)
138 for v in values[2:-2]: #remove initial and final '()'
145 if len(stack[-1]) == 1:
147 stack[-2].append(stack[-1])
152 stack[-1].extend(v.split())
155 def statusInfo(machine):
156 """Return the status list for a given machine.
158 Gets and parses xm list --long
161 value_string = remctl('control', machine.name, 'list-long')
163 if 'is not on' in e.message:
167 status = parseStatus(value_string)
170 def listHost(machine):
171 """Return the host a machine is running on"""
173 out = remctl('control', machine.name, 'listhost')
178 def vnctoken(machine):
179 """Return a time-stamped VNC token"""
181 out = remctl('control', machine.name, 'vnctoken')
186 def deleteVM(machine):
189 remctl('control', machine.name, 'destroy')
193 delete_disk_pairs = [(machine.name, d.guest_device_name)
194 for d in machine.disks]
196 for mname, dname in delete_disk_pairs:
197 remctl('web', 'lvremove', mname, dname)
198 for nic in machine.nics:
199 nic.machine_id = None
201 session.save_or_update(nic)
202 for disk in machine.disks:
204 session.delete(machine)
210 def commandResult(username, state, fields):
212 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
213 action = fields.getfirst('action')
214 cdrom = fields.getfirst('cdrom')
215 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
216 raise CodeError("Invalid cdrom type '%s'" % cdrom)
217 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
219 raise CodeError("Invalid action '%s'" % action)
220 if action == 'Reboot':
222 if cdrom is not None:
223 out = remctl('control', machine.name, 'reboot', cdrom)
225 out = remctl('control', machine.name, 'reboot')
227 if re.match("machine '.*' is not on", e.message):
228 raise InvalidInput("action", "reboot",
233 elif action == 'Power on':
234 if validation.maxMemory(username, state, machine) < machine.memory:
235 raise InvalidInput('action', 'Power on',
236 "You don't have enough free RAM quota "
237 "to turn on this machine.")
238 bootMachine(machine, cdrom)
239 elif action == 'Power off':
241 out = remctl('control', machine.name, 'destroy')
243 if re.match("machine '.*' is not on", e.message):
244 raise InvalidInput("action", "Power off",
245 "Machine is not on.")
248 elif action == 'Shutdown':
250 out = remctl('control', machine.name, 'shutdown')
252 if re.match("machine '.*' is not on", e.message):
253 raise InvalidInput("action", "Shutdown",
254 "Machine is not on.")
257 elif action == 'Delete VM':
260 d = dict(user=username,
265 def resizeDisk(machine_name, disk_name, new_size):
266 remctl("web", "lvresize", machine_name, disk_name, new_size)
268 def renameMachine(machine, old_name, new_name):
269 for disk in machine.disks:
270 remctl("web", "lvrename", old_name,
271 disk.guest_device_name, new_name)