d03d4f9aafa867e2804e13cac9944c492f949317
[invirt/packages/invirt-web.git] / code / controls.py
1 import validation
2 from invirt.common import CodeError, InvalidInput
3 import random
4 import sys
5 import time
6 import re
7 import cache_acls
8 import yaml
9
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
13
14 # ... and stolen from xend/uuid.py
15 def randomUUID():
16     """Generate a random UUID."""
17
18     return [ random.randint(0, 255) for _ in range(0, 16) ]
19
20 def uuidToString(u):
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)
24 # end stolen code
25
26 def remctl(*args, **kwargs):
27     return gen_remctl(config.remote.hostname,
28                       principal='daemon/'+config.web.hostname,
29                       *args, **kwargs)
30
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))
35     
36 def makeDisks(machine):
37     """Update the lvm partitions to add a disk."""
38     for disk in machine.disks:
39         lvcreate(machine, disk)
40
41 def getswap(disksize, memsize):
42     """Returns the recommended swap partition size."""
43     return int(min(disksize / 4, memsize * 1.5))
44
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)
56
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)
60
61 def bootMachine(machine, cdtype):
62     """Boot a machine with a given boot CD.
63
64     If cdtype is None, give no boot cd.  Otherwise, it is the string
65     id of the CD (e.g. 'gutsy_i386')
66     """
67     try:
68         if cdtype is not None:
69             out = remctl('control', machine.name, 'create', 
70                               cdtype)
71         else:
72             out = remctl('control', machine.name, 'create')
73     except CodeError, e:
74         if 'already running' in e.message:
75             raise InvalidInput('action', 'create',
76                                'VM %s is already on' % machine.name)
77         else:
78         raise CodeError('"%s" on "control %s create %s' 
79                         % (err, machine.name, cdtype))
80
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
84     session.begin()
85     try:
86         validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
87         machine = Machine()
88         machine.name = name
89         machine.description = description
90         machine.memory = memory
91         machine.owner = owner
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
105         nic.hostname = name
106         session.save_or_update(nic)
107         session.save_or_update(disk)
108         cache_acls.refreshMachine(machine)
109         session.commit()
110     except:
111         session.rollback()
112         raise
113     makeDisks(machine)
114     try:
115         if autoinstall:
116             lvinstall(machine, autoinstall)
117         else:
118             # tell it to boot with cdrom
119             bootMachine(machine, cdrom)
120     except CodeError, e:
121         deleteVM(machine)
122         raise
123     return machine
124
125 def getList():
126     """Return a dictionary mapping machine names to dicts."""
127     value_string = remctl('web', 'listvms')
128     value_dict = yaml.load(value_string, yaml.CSafeLoader)
129     return value_dict
130
131 def parseStatus(s):
132     """Parse a status string into nested tuples of strings.
133
134     s = output of xm list --long <machine_name>
135     """
136     values = re.split('([()])', s)
137     stack = [[]]
138     for v in values[2:-2]: #remove initial and final '()'
139         if not v:
140             continue
141         v = v.strip()
142         if v == '(':
143             stack.append([])
144         elif v == ')':
145             if len(stack[-1]) == 1:
146                 stack[-1].append('')
147             stack[-2].append(stack[-1])
148             stack.pop()
149         else:
150             if not v:
151                 continue
152             stack[-1].extend(v.split())
153     return stack[-1]
154
155 def statusInfo(machine):
156     """Return the status list for a given machine.
157
158     Gets and parses xm list --long
159     """
160     try:
161         value_string = remctl('control', machine.name, 'list-long')
162     except CodeError, e:
163         if 'is not on' in e.message:
164             return None
165         else:
166             raise
167     status = parseStatus(value_string)
168     return status
169
170 def listHost(machine):
171     """Return the host a machine is running on"""
172     try:
173         out = remctl('control', machine.name, 'listhost')
174     except CodeError, e:
175         return None
176     return out.strip()
177
178 def vnctoken(machine):
179     """Return a time-stamped VNC token"""
180     try:
181         out = remctl('control', machine.name, 'vnctoken')
182     except CodeError, e:
183         return None
184     return out.strip()
185
186 def deleteVM(machine):
187     """Delete a VM."""
188     try:
189         remctl('control', machine.name, 'destroy')
190     except CodeError:
191         pass
192     session.begin()
193     delete_disk_pairs = [(machine.name, d.guest_device_name) 
194                          for d in machine.disks]
195     try:
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
200             nic.hostname = None
201             session.save_or_update(nic)
202         for disk in machine.disks:
203             session.delete(disk)
204         session.delete(machine)
205         session.commit()
206     except:
207         session.rollback()
208         raise
209
210 def commandResult(username, state, fields):
211     start_time = 0
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', 
218                       'Delete VM'):
219         raise CodeError("Invalid action '%s'" % action)
220     if action == 'Reboot':
221         try:
222             if cdrom is not None:
223                 out = remctl('control', machine.name, 'reboot', cdrom)
224             else:
225                 out = remctl('control', machine.name, 'reboot')
226         except CodeError, e:
227             if re.match("machine '.*' is not on", e.message):
228                 raise InvalidInput("action", "reboot", 
229                                    "Machine is not on")
230             else:
231                 raise
232                 
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':
240         try:
241             out = remctl('control', machine.name, 'destroy')
242         except CodeError, e:
243             if re.match("machine '.*' is not on", e.message):
244                 raise InvalidInput("action", "Power off", 
245                                    "Machine is not on.")
246             else:
247                 raise
248     elif action == 'Shutdown':
249         try:
250             out = remctl('control', machine.name, 'shutdown')
251         except CodeError, e:
252             if re.match("machine '.*' is not on", e.message):
253                 raise InvalidInput("action", "Shutdown", 
254                                    "Machine is not on.")
255             else:
256                 raise
257     elif action == 'Delete VM':
258         deleteVM(machine)
259
260     d = dict(user=username,
261              command=action,
262              machine=machine)
263     return d
264
265 def resizeDisk(machine_name, disk_name, new_size):
266     remctl("web", "lvresize", machine_name, disk_name, new_size)
267
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)
272