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
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 lvcreate(machine, disk):
27 """Create a single disk for a machine"""
28 remctl('web', 'lvcreate', machine.name,
29 disk.guest_device_name, str(disk.size))
31 def makeDisks(machine):
32 """Update the lvm partitions to add a disk."""
33 for disk in machine.disks:
34 lvcreate(machine, disk)
36 def getswap(disksize, memsize):
37 """Returns the recommended swap partition size."""
38 return int(min(disksize / 4, memsize * 1.5))
40 def lvinstall(machine, autoinstall):
41 disksize = machine.disks[0].size
42 memsize = machine.memory
43 swapsize = getswap(disksize, memsize)
44 imagesize = disksize - swapsize
45 ip = machine.nics[0].ip
46 remctl('control', machine.name, 'install',
47 'dist=%s' % autoinstall.distribution,
48 'mirror=%s' % autoinstall.mirror,
49 'imagesize=%s' % imagesize)
51 def lvcopy(machine_orig_name, machine, rootpw):
52 """Copy a golden image onto a machine's disk"""
53 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
55 def bootMachine(machine, cdtype):
56 """Boot a machine with a given boot CD.
58 If cdtype is None, give no boot cd. Otherwise, it is the string
59 id of the CD (e.g. 'gutsy_i386')
61 if cdtype is not None:
62 out, err = remctl('control', machine.name, 'create',
65 out, err = remctl('control', machine.name, 'create',
67 if 'already running' in err:
68 raise InvalidInput('action', 'create',
69 'VM %s is already on' % machine.name)
71 raise CodeError('"%s" on "control %s create %s'
72 % (err, machine.name, cdtype))
74 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
75 """Create a VM and put it in the database"""
76 # put stuff in the table
79 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
82 machine.description = description
83 machine.memory = memory
85 machine.administrator = owner
86 machine.contact = contact
87 machine.uuid = uuidToString(randomUUID())
88 machine.boot_off_cd = True
89 machine.type = machine_type
90 session.save_or_update(machine)
91 disk = Disk(machine=machine,
92 guest_device_name='hda', size=disksize)
93 nic = NIC.query().filter_by(machine_id=None).first()
94 if not nic: #No IPs left!
95 raise CodeError("No IP addresses left! "
96 "Contact %s." % config.web.errormail)
99 session.save_or_update(nic)
100 session.save_or_update(disk)
101 cache_acls.refreshMachine(machine)
108 lvinstall(machine, autoinstall)
110 # tell it to boot with cdrom
111 bootMachine(machine, cdrom)
115 """Return a dictionary mapping machine names to dicts."""
116 value_string = remctl('web', 'listvms')
117 value_dict = yaml.load(value_string, yaml.CSafeLoader)
121 """Parse a status string into nested tuples of strings.
123 s = output of xm list --long <machine_name>
125 values = re.split('([()])', s)
127 for v in values[2:-2]: #remove initial and final '()'
134 if len(stack[-1]) == 1:
136 stack[-2].append(stack[-1])
141 stack[-1].extend(v.split())
144 def statusInfo(machine):
145 """Return the status list for a given machine.
147 Gets and parses xm list --long
149 value_string, err_string = remctl('control', machine.name, 'list-long',
151 if 'Unknown command' in err_string:
152 raise CodeError("ERROR in remctl list-long %s is not registered" %
154 elif 'is not on' in err_string:
157 raise CodeError("ERROR in remctl list-long %s: %s" %
158 (machine.name, err_string))
159 status = parseStatus(value_string)
162 def listHost(machine):
163 """Return the host a machine is running on"""
164 out, err = remctl('control', machine.name, 'listhost', err=True)
169 def deleteVM(machine):
171 remctl('control', machine.name, 'destroy', err=True)
173 delete_disk_pairs = [(machine.name, d.guest_device_name)
174 for d in machine.disks]
176 for mname, dname in delete_disk_pairs:
177 remctl('web', 'lvremove', mname, dname)
178 for nic in machine.nics:
179 nic.machine_id = None
181 session.save_or_update(nic)
182 for disk in machine.disks:
184 session.delete(machine)
190 def commandResult(username, state, fields):
192 machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
193 action = fields.getfirst('action')
194 cdrom = fields.getfirst('cdrom')
195 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
196 raise CodeError("Invalid cdrom type '%s'" % cdrom)
197 if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown',
199 raise CodeError("Invalid action '%s'" % action)
200 if action == 'Reboot':
201 if cdrom is not None:
202 out, err = remctl('control', machine.name, 'reboot', cdrom,
205 out, err = remctl('control', machine.name, 'reboot',
208 if re.match("machine '.*' is not on", err):
209 raise InvalidInput("action", "reboot",
212 print >> sys.stderr, 'Error on reboot:'
213 print >> sys.stderr, err
214 raise CodeError('ERROR on remctl')
216 elif action == 'Power on':
217 if validation.maxMemory(username, state, machine) < machine.memory:
218 raise InvalidInput('action', 'Power on',
219 "You don't have enough free RAM quota "
220 "to turn on this machine.")
221 bootMachine(machine, cdrom)
222 elif action == 'Power off':
223 out, err = remctl('control', machine.name, 'destroy', err=True)
225 if re.match("machine '.*' is not on", err):
226 raise InvalidInput("action", "Power off",
227 "Machine is not on.")
229 print >> sys.stderr, 'Error on power off:'
230 print >> sys.stderr, err
231 raise CodeError('ERROR on remctl')
232 elif action == 'Shutdown':
233 out, err = remctl('control', machine.name, 'shutdown', err=True)
235 if re.match("machine '.*' is not on", err):
236 raise InvalidInput("action", "Shutdown",
237 "Machine is not on.")
239 print >> sys.stderr, 'Error on Shutdown:'
240 print >> sys.stderr, err
241 raise CodeError('ERROR on remctl')
242 elif action == 'Delete VM':
245 d = dict(user=username,
250 def resizeDisk(machine_name, disk_name, new_size):
251 remctl("web", "lvresize", machine_name, disk_name, new_size)
253 def renameMachine(machine, old_name, new_name):
254 for disk in machine.disks:
255 remctl("web", "lvrename", old_name,
256 disk.guest_device_name, new_name)