add and respect 'adminable' column to machines
[invirt/packages/invirt-web.git] / code / validation.py
1 #!/usr/bin/python
2
3 import cache_acls
4 import getafsgroups
5 import re
6 import string
7 from invirt.database import Machine, NIC, Type, Disk, CDROM, Autoinstall
8 from webcommon import InvalidInput
9
10 MAX_MEMORY_TOTAL = 512
11 MAX_MEMORY_SINGLE = 256
12 MIN_MEMORY_SINGLE = 16
13 MAX_DISK_TOTAL = 50
14 MAX_DISK_SINGLE = 50
15 MIN_DISK_SINGLE = 0.1
16 MAX_VMS_TOTAL = 10
17 MAX_VMS_ACTIVE = 4
18
19 class Validate:
20     def __init__(self, username, state, machine_id=None, name=None, description=None, owner=None,
21                  admin=None, contact=None, memory=None, disksize=None,
22                  vmtype=None, cdrom=None, autoinstall=None, strict=False):
23         # XXX Successive quota checks aren't a good idea, since you
24         # can't necessarily change the locker and disk size at the
25         # same time.
26         created_new = (machine_id is None)
27
28         if strict:
29             if name is None:
30                 raise InvalidInput('name', name, "You must provide a machine name.")
31             if description is None:
32                 raise InvalidInput('description', description, "You must provide a description.")
33             if memory is None:
34                 raise InvalidInput('memory', memory, "You must provide a memory size.")
35             if disksize is None:
36                 raise InvalidInput('disk', disksize, "You must provide a disk size.")
37
38         if machine_id is not None:
39             self.machine = testMachineId(username, state, machine_id)
40         machine = getattr(self, 'machine', None)
41
42         owner = testOwner(username, owner, machine)
43         if owner is not None:
44             self.owner = owner
45         admin = testAdmin(username, admin, machine)
46         if admin is not None:
47             self.admin = admin
48         contact = testContact(username, contact, machine)
49         if contact is not None:
50             self.contact = contact
51         name = testName(username, name, machine)
52         if name is not None:
53             self.name = name
54         description = testDescription(username, description, machine)
55         if description is not None:
56             self.description = description
57         if memory is not None:
58             self.memory = validMemory(self.owner, state, memory, machine,
59                                       on=not created_new)
60         if disksize is not None:
61             self.disksize = validDisk(self.owner, state, disksize, machine)
62         if vmtype is not None:
63             self.vmtype = validVmType(vmtype)
64         if cdrom is not None:
65             if not CDROM.get(cdrom):
66                 raise CodeError("Invalid cdrom type '%s'" % cdrom)
67             self.cdrom = cdrom
68         if autoinstall is not None:
69             self.autoinstall = Autoinstall.get(autoinstall)
70
71
72 def getMachinesByOwner(owner, machine=None):
73     """Return the machines owned by the same as a machine.
74
75     If the machine is None, return the machines owned by the same
76     user.
77     """
78     if machine:
79         owner = machine.owner
80     return Machine.select_by(owner=owner)
81
82 def maxMemory(owner, g, machine=None, on=True):
83     """Return the maximum memory for a machine or a user.
84
85     If machine is None, return the memory available for a new
86     machine.  Else, return the maximum that machine can have.
87
88     on is whether the machine should be turned on.  If false, the max
89     memory for the machine to change to, if it is left off, is
90     returned.
91     """
92     if machine is not None and machine.memory > MAX_MEMORY_SINGLE:
93         # If they've been blessed, let them have it
94         return machine.memory
95     if not on:
96         return MAX_MEMORY_SINGLE
97     machines = getMachinesByOwner(owner, machine)
98     active_machines = [m for m in machines if m.name in g.xmlist_raw]
99     mem_usage = sum([x.memory for x in active_machines if x != machine])
100     return min(MAX_MEMORY_SINGLE, MAX_MEMORY_TOTAL-mem_usage)
101
102 def maxDisk(owner, machine=None):
103     """Return the maximum disk that a machine can reach.
104
105     If machine is None, the maximum disk for a new machine. Otherwise,
106     return the maximum that a given machine can be changed to.
107     """
108     if machine is not None:
109         machine_id = machine.machine_id
110     else:
111         machine_id = None
112     disk_usage = Disk.query().filter_by(Disk.c.machine_id != machine_id,
113                                         owner=owner).sum(Disk.c.size) or 0
114     return min(MAX_DISK_SINGLE, MAX_DISK_TOTAL-disk_usage/1024.)
115
116 def cantAddVm(owner, g):
117     machines = getMachinesByOwner(owner)
118     active_machines = [m for m in machines if m.name in g.xmlist_raw]
119     if len(machines) >= MAX_VMS_TOTAL:
120         return 'You have too many VMs to create a new one.'
121     if len(active_machines) >= MAX_VMS_ACTIVE:
122         return ('You already have the maximum number of VMs turned on.  '
123                 'To create more, turn one off.')
124     return False
125
126 def haveAccess(user, state, machine):
127     """Return whether a user has administrative access to a machine"""
128     return (user in cache_acls.accessList(machine)
129             or (machine.adminable and state.isadmin))
130
131 def owns(user, machine):
132     """Return whether a user owns a machine"""
133     return user in expandLocker(machine.owner)
134
135 def validMachineName(name):
136     """Check that name is valid for a machine name"""
137     if not name:
138         return False
139     charset = string.lowercase + string.digits + '-'
140     if '-' in (name[0], name[-1]) or len(name) > 63:
141         return False
142     for x in name:
143         if x not in charset:
144             return False
145     return True
146
147 def validMemory(owner, g, memory, machine=None, on=True):
148     """Parse and validate limits for memory for a given owner and machine.
149
150     on is whether the memory must be valid after the machine is
151     switched on.
152     """
153     try:
154         memory = int(memory)
155         if memory < MIN_MEMORY_SINGLE:
156             raise ValueError
157     except ValueError:
158         raise InvalidInput('memory', memory,
159                            "Minimum %s MiB" % MIN_MEMORY_SINGLE)
160     max_val = maxMemory(owner, g, machine, on)
161     if not g.isadmin and memory > max_val:
162         raise InvalidInput('memory', memory,
163                            'Maximum %s MiB for %s' % (max_val, owner))
164     return memory
165
166 def validDisk(owner, g, disk, machine=None):
167     """Parse and validate limits for disk for a given owner and machine."""
168     try:
169         disk = float(disk)
170         if not g.isadmin and disk > maxDisk(owner, machine):
171             raise InvalidInput('disk', disk,
172                                "Maximum %s G" % maxDisk(owner, machine))
173         disk = int(disk * 1024)
174         if disk < MIN_DISK_SINGLE * 1024:
175             raise ValueError
176     except ValueError:
177         raise InvalidInput('disk', disk,
178                            "Minimum %s GiB" % MIN_DISK_SINGLE)
179     return disk
180
181 def validVmType(vm_type):
182     if vm_type is None:
183         return None
184     t = Type.get(vm_type)
185     if t is None:
186         raise CodeError("Invalid vm type '%s'"  % vm_type)
187     return t
188
189 def testMachineId(user, state, machine_id, exists=True):
190     """Parse, validate and check authorization for a given user and machine.
191
192     If exists is False, don't check that it exists.
193     """
194     if machine_id is None:
195         raise InvalidInput('machine_id', machine_id,
196                            "Must specify a machine ID.")
197     try:
198         machine_id = int(machine_id)
199     except ValueError:
200         raise InvalidInput('machine_id', machine_id, "Must be an integer.")
201     machine = Machine.get(machine_id)
202     if exists and machine is None:
203         raise InvalidInput('machine_id', machine_id, "Does not exist.")
204     if machine is not None and not haveAccess(user, state, machine):
205         raise InvalidInput('machine_id', machine_id,
206                            "You do not have access to this machine.")
207     return machine
208
209 def testAdmin(user, admin, machine):
210     """Determine whether a user can set the admin of a machine to this value.
211
212     Return the value to set the admin field to (possibly 'system:' +
213     admin).  XXX is modifying this a good idea?
214     """
215     if admin is None:
216         return None
217     if machine is not None and admin == machine.administrator:
218         return None
219     if admin == user:
220         return admin
221     if ':' not in admin:
222         if cache_acls.isUser(admin):
223             return admin
224         admin = 'system:' + admin
225     try:
226         if user in getafsgroups.getAfsGroupMembers(admin, 'athena.mit.edu'):
227             return admin
228     except getafsgroups.AfsProcessError, e:
229         errmsg = str(e)
230         if errmsg.startswith("pts: User or group doesn't exist"):
231             errmsg = 'The group "%s" does not exist.' % admin
232         raise InvalidInput('administrator', admin, errmsg)
233     #XXX Should we require that user is in the admin group?
234     return admin
235
236 def testOwner(user, owner, machine=None):
237     """Determine whether a user can set the owner of a machine to this value.
238
239     If machine is None, this is the owner of a new machine.
240     """
241     if owner == user:
242         return owner
243     if machine is not None and owner in (machine.owner, None):
244         return machine.owner
245     if owner is None:
246         raise InvalidInput('owner', owner, "Owner must be specified")
247     try:
248         if user not in cache_acls.expandLocker(owner):
249             raise InvalidInput('owner', owner, 'You do not have access to the '
250                                + owner + ' locker')
251     except getafsgroups.AfsProcessError, e:
252         raise InvalidInput('owner', owner, str(e))
253     return owner
254
255 def testContact(user, contact, machine=None):
256     if contact is None or (machine is not None and contact == machine.contact):
257         return None
258     if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", contact, re.I):
259         raise InvalidInput('contact', contact, "Not a valid email.")
260     return contact
261
262 def testDisk(user, disksize, machine=None):
263     return disksize
264
265 def testName(user, name, machine=None):
266     if name is None:
267         return None
268     name = name.lower()
269     if machine is not None and name == machine.name:
270         return None
271     if not Machine.select_by(name=name):
272         if not validMachineName(name):
273             raise InvalidInput('name', name, 'You must provide a machine name.  Max 63 chars, alnum plus \'-\', does not begin or end with \'-\'.')
274         return name
275     raise InvalidInput('name', name, "Name is already taken.")
276
277 def testDescription(user, description, machine=None):
278     if description is None or description.strip() == '':
279         return None
280     return description.strip()
281
282 def testHostname(user, hostname, machine):
283     for nic in machine.nics:
284         if hostname == nic.hostname:
285             return hostname
286     # check if doesn't already exist
287     if NIC.select_by(hostname=hostname):
288         raise InvalidInput('hostname', hostname,
289                            "Already exists")
290     if not re.match("^[A-Z0-9-]{1,22}$", hostname, re.I):
291         raise InvalidInput('hostname', hostname, "Not a valid hostname; "
292                            "must only use number, letters, and dashes.")
293     return hostname