[209] | 1 | #!/usr/bin/python |
---|
| 2 | |
---|
[411] | 3 | import cache_acls |
---|
[209] | 4 | import getafsgroups |
---|
| 5 | import re |
---|
| 6 | import string |
---|
[1473] | 7 | import dns.resolver |
---|
[2132] | 8 | from invirt.database import Machine, NIC, Type, Disk, CDROM, Autoinstall, Owner |
---|
[879] | 9 | from invirt.config import structs as config |
---|
[2064] | 10 | from invirt.common import InvalidInput, CodeError |
---|
[209] | 11 | |
---|
| 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 | |
---|
[572] | 19 | class Validate: |
---|
[609] | 20 | def __init__(self, username, state, machine_id=None, name=None, description=None, owner=None, |
---|
[572] | 21 | admin=None, contact=None, memory=None, disksize=None, |
---|
[629] | 22 | vmtype=None, cdrom=None, autoinstall=None, strict=False): |
---|
[572] | 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 | |
---|
[577] | 28 | if strict: |
---|
| 29 | if name is None: |
---|
| 30 | raise InvalidInput('name', name, "You must provide a machine name.") |
---|
[609] | 31 | if description is None: |
---|
| 32 | raise InvalidInput('description', description, "You must provide a description.") |
---|
[577] | 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 | |
---|
[572] | 38 | if machine_id is not None: |
---|
[632] | 39 | self.machine = testMachineId(username, state, machine_id) |
---|
[572] | 40 | machine = getattr(self, 'machine', None) |
---|
| 41 | |
---|
| 42 | owner = testOwner(username, owner, machine) |
---|
| 43 | if owner is not None: |
---|
| 44 | self.owner = owner |
---|
[1709] | 45 | self.admin = testAdmin(username, admin, machine) |
---|
[572] | 46 | contact = testContact(username, contact, machine) |
---|
| 47 | if contact is not None: |
---|
| 48 | self.contact = contact |
---|
| 49 | name = testName(username, name, machine) |
---|
| 50 | if name is not None: |
---|
| 51 | self.name = name |
---|
[609] | 52 | description = testDescription(username, description, machine) |
---|
| 53 | if description is not None: |
---|
| 54 | self.description = description |
---|
[572] | 55 | if memory is not None: |
---|
| 56 | self.memory = validMemory(self.owner, state, memory, machine, |
---|
| 57 | on=not created_new) |
---|
| 58 | if disksize is not None: |
---|
[632] | 59 | self.disksize = validDisk(self.owner, state, disksize, machine) |
---|
[572] | 60 | if vmtype is not None: |
---|
| 61 | self.vmtype = validVmType(vmtype) |
---|
| 62 | if cdrom is not None: |
---|
[1013] | 63 | if not CDROM.query().get(cdrom): |
---|
[572] | 64 | raise CodeError("Invalid cdrom type '%s'" % cdrom) |
---|
| 65 | self.cdrom = cdrom |
---|
[629] | 66 | if autoinstall is not None: |
---|
[1721] | 67 | #raise InvalidInput('autoinstall', 'install', |
---|
| 68 | # "The autoinstaller has been temporarily disabled") |
---|
[1013] | 69 | self.autoinstall = Autoinstall.query().get(autoinstall) |
---|
[572] | 70 | |
---|
| 71 | |
---|
| 72 | def getMachinesByOwner(owner, machine=None): |
---|
[209] | 73 | """Return the machines owned by the same as a machine. |
---|
[440] | 74 | |
---|
[209] | 75 | If the machine is None, return the machines owned by the same |
---|
| 76 | user. |
---|
| 77 | """ |
---|
| 78 | if machine: |
---|
| 79 | owner = machine.owner |
---|
[1001] | 80 | return Machine.query().filter_by(owner=owner) |
---|
[209] | 81 | |
---|
[572] | 82 | def maxMemory(owner, g, machine=None, on=True): |
---|
[209] | 83 | """Return the maximum memory for a machine or a user. |
---|
| 84 | |
---|
[440] | 85 | If machine is None, return the memory available for a new |
---|
[209] | 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 | """ |
---|
[2132] | 92 | (quota_total, quota_single) = Owner.getQuotas(machine.owner if machine else owner) |
---|
| 93 | |
---|
[253] | 94 | if not on: |
---|
[2132] | 95 | return quota_single |
---|
[572] | 96 | machines = getMachinesByOwner(owner, machine) |
---|
[575] | 97 | active_machines = [m for m in machines if m.name in g.xmlist_raw] |
---|
[209] | 98 | mem_usage = sum([x.memory for x in active_machines if x != machine]) |
---|
[2132] | 99 | return min(quota_single, quota_total-mem_usage) |
---|
[209] | 100 | |
---|
[572] | 101 | def maxDisk(owner, machine=None): |
---|
[440] | 102 | """Return the maximum disk that a machine can reach. |
---|
| 103 | |
---|
| 104 | If machine is None, the maximum disk for a new machine. Otherwise, |
---|
| 105 | return the maximum that a given machine can be changed to. |
---|
| 106 | """ |
---|
[535] | 107 | if machine is not None: |
---|
| 108 | machine_id = machine.machine_id |
---|
| 109 | else: |
---|
| 110 | machine_id = None |
---|
[1001] | 111 | disk_usage = Disk.query().filter(Disk.c.machine_id != machine_id).\ |
---|
| 112 | join('machine').\ |
---|
| 113 | filter_by(owner=owner).sum(Disk.c.size) or 0 |
---|
[209] | 114 | return min(MAX_DISK_SINGLE, MAX_DISK_TOTAL-disk_usage/1024.) |
---|
| 115 | |
---|
[572] | 116 | def cantAddVm(owner, g): |
---|
| 117 | machines = getMachinesByOwner(owner) |
---|
[575] | 118 | active_machines = [m for m in machines if m.name in g.xmlist_raw] |
---|
[1001] | 119 | if machines.count() >= MAX_VMS_TOTAL: |
---|
[209] | 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 | |
---|
[632] | 126 | def haveAccess(user, state, machine): |
---|
[235] | 127 | """Return whether a user has administrative access to a machine""" |
---|
[874] | 128 | return (user in cache_acls.accessList(machine) |
---|
| 129 | or (machine.adminable and state.isadmin)) |
---|
[209] | 130 | |
---|
| 131 | def owns(user, machine): |
---|
| 132 | """Return whether a user owns a machine""" |
---|
[411] | 133 | return user in expandLocker(machine.owner) |
---|
[209] | 134 | |
---|
| 135 | def validMachineName(name): |
---|
| 136 | """Check that name is valid for a machine name""" |
---|
| 137 | if not name: |
---|
| 138 | return False |
---|
[648] | 139 | charset = string.lowercase + string.digits + '-' |
---|
| 140 | if '-' in (name[0], name[-1]) or len(name) > 63: |
---|
[209] | 141 | return False |
---|
| 142 | for x in name: |
---|
| 143 | if x not in charset: |
---|
| 144 | return False |
---|
| 145 | return True |
---|
| 146 | |
---|
[572] | 147 | def validMemory(owner, g, memory, machine=None, on=True): |
---|
| 148 | """Parse and validate limits for memory for a given owner and machine. |
---|
[209] | 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: |
---|
[440] | 158 | raise InvalidInput('memory', memory, |
---|
[211] | 159 | "Minimum %s MiB" % MIN_MEMORY_SINGLE) |
---|
[572] | 160 | max_val = maxMemory(owner, g, machine, on) |
---|
[867] | 161 | if not g.isadmin and memory > max_val: |
---|
[209] | 162 | raise InvalidInput('memory', memory, |
---|
[572] | 163 | 'Maximum %s MiB for %s' % (max_val, owner)) |
---|
[209] | 164 | return memory |
---|
| 165 | |
---|
[632] | 166 | def validDisk(owner, g, disk, machine=None): |
---|
[572] | 167 | """Parse and validate limits for disk for a given owner and machine.""" |
---|
[209] | 168 | try: |
---|
| 169 | disk = float(disk) |
---|
[867] | 170 | if not g.isadmin and disk > maxDisk(owner, machine): |
---|
[209] | 171 | raise InvalidInput('disk', disk, |
---|
[572] | 172 | "Maximum %s G" % maxDisk(owner, machine)) |
---|
[209] | 173 | disk = int(disk * 1024) |
---|
| 174 | if disk < MIN_DISK_SINGLE * 1024: |
---|
| 175 | raise ValueError |
---|
| 176 | except ValueError: |
---|
| 177 | raise InvalidInput('disk', disk, |
---|
[211] | 178 | "Minimum %s GiB" % MIN_DISK_SINGLE) |
---|
[209] | 179 | return disk |
---|
[437] | 180 | |
---|
| 181 | def validVmType(vm_type): |
---|
[440] | 182 | if vm_type is None: |
---|
| 183 | return None |
---|
[1013] | 184 | t = Type.query().get(vm_type) |
---|
[440] | 185 | if t is None: |
---|
[437] | 186 | raise CodeError("Invalid vm type '%s'" % vm_type) |
---|
[440] | 187 | return t |
---|
[437] | 188 | |
---|
[632] | 189 | def testMachineId(user, state, machine_id, exists=True): |
---|
[209] | 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: |
---|
[440] | 195 | raise InvalidInput('machine_id', machine_id, |
---|
[209] | 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.") |
---|
[1013] | 201 | machine = Machine.query().get(machine_id) |
---|
[209] | 202 | if exists and machine is None: |
---|
| 203 | raise InvalidInput('machine_id', machine_id, "Does not exist.") |
---|
[632] | 204 | if machine is not None and not haveAccess(user, state, machine): |
---|
[209] | 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): |
---|
[411] | 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 | """ |
---|
[575] | 215 | if admin is None: |
---|
[209] | 216 | return None |
---|
[575] | 217 | if machine is not None and admin == machine.administrator: |
---|
[1709] | 218 | return admin |
---|
[228] | 219 | if admin == user: |
---|
[209] | 220 | return admin |
---|
[411] | 221 | if ':' not in admin: |
---|
| 222 | if cache_acls.isUser(admin): |
---|
| 223 | return admin |
---|
| 224 | admin = 'system:' + admin |
---|
[413] | 225 | try: |
---|
[879] | 226 | if user in getafsgroups.getAfsGroupMembers(admin, config.authz[0].cell): |
---|
[413] | 227 | return admin |
---|
| 228 | except getafsgroups.AfsProcessError, e: |
---|
[431] | 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) |
---|
[413] | 233 | #XXX Should we require that user is in the admin group? |
---|
[209] | 234 | return admin |
---|
[440] | 235 | |
---|
[228] | 236 | def testOwner(user, owner, machine=None): |
---|
[411] | 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 | """ |
---|
[572] | 241 | if machine is not None and owner in (machine.owner, None): |
---|
[573] | 242 | return machine.owner |
---|
[228] | 243 | if owner is None: |
---|
| 244 | raise InvalidInput('owner', owner, "Owner must be specified") |
---|
[411] | 245 | try: |
---|
| 246 | if user not in cache_acls.expandLocker(owner): |
---|
| 247 | raise InvalidInput('owner', owner, 'You do not have access to the ' |
---|
| 248 | + owner + ' locker') |
---|
| 249 | except getafsgroups.AfsProcessError, e: |
---|
| 250 | raise InvalidInput('owner', owner, str(e)) |
---|
| 251 | return owner |
---|
[209] | 252 | |
---|
| 253 | def testContact(user, contact, machine=None): |
---|
[576] | 254 | if contact is None or (machine is not None and contact == machine.contact): |
---|
[209] | 255 | return None |
---|
| 256 | if not re.match("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", contact, re.I): |
---|
| 257 | raise InvalidInput('contact', contact, "Not a valid email.") |
---|
| 258 | return contact |
---|
| 259 | |
---|
| 260 | def testDisk(user, disksize, machine=None): |
---|
| 261 | return disksize |
---|
| 262 | |
---|
| 263 | def testName(user, name, machine=None): |
---|
[572] | 264 | if name is None: |
---|
[209] | 265 | return None |
---|
[647] | 266 | name = name.lower() |
---|
[572] | 267 | if machine is not None and name == machine.name: |
---|
| 268 | return None |
---|
[1473] | 269 | try: |
---|
[1492] | 270 | hostname = '%s.%s.' % (name, config.dns.domains[0]) |
---|
[1542] | 271 | resolver = dns.resolver.Resolver() |
---|
| 272 | resolver.nameservers = ['127.0.0.1'] |
---|
[1492] | 273 | try: |
---|
[1542] | 274 | resolver.query(hostname, 'A') |
---|
[1492] | 275 | except dns.resolver.NoAnswer, e: |
---|
| 276 | # If we can get the TXT record, then we can verify it's |
---|
| 277 | # reserved. If this lookup fails, let it bubble up and be |
---|
| 278 | # dealt with |
---|
[1542] | 279 | answer = resolver.query(hostname, 'TXT') |
---|
[1492] | 280 | txt = answer[0].strings[0] |
---|
[1495] | 281 | if txt.startswith('reserved'): |
---|
[1492] | 282 | raise InvalidInput('name', name, 'The name you have requested has been %s. For more information, contact us at %s' % (txt, config.dns.contact)) |
---|
| 283 | |
---|
[1473] | 284 | # If the hostname didn't exist, it would have thrown an |
---|
| 285 | # exception by now - error out |
---|
| 286 | raise InvalidInput('name', name, 'Name is already taken.') |
---|
| 287 | except dns.resolver.NXDOMAIN, e: |
---|
[572] | 288 | if not validMachineName(name): |
---|
[649] | 289 | raise InvalidInput('name', name, 'You must provide a machine name. Max 63 chars, alnum plus \'-\', does not begin or end with \'-\'.') |
---|
[209] | 290 | return name |
---|
[1473] | 291 | except InvalidInput: |
---|
| 292 | raise |
---|
| 293 | except: |
---|
| 294 | # Any other error is a validation failure |
---|
| 295 | raise InvalidInput('name', name, 'We were unable to verify that this name is available. If you believe this is in error, please contact us at %s' % config.dns.contact) |
---|
[209] | 296 | |
---|
[609] | 297 | def testDescription(user, description, machine=None): |
---|
| 298 | if description is None or description.strip() == '': |
---|
| 299 | return None |
---|
| 300 | return description.strip() |
---|
| 301 | |
---|
[209] | 302 | def testHostname(user, hostname, machine): |
---|
| 303 | for nic in machine.nics: |
---|
| 304 | if hostname == nic.hostname: |
---|
| 305 | return hostname |
---|
| 306 | # check if doesn't already exist |
---|
| 307 | if NIC.select_by(hostname=hostname): |
---|
| 308 | raise InvalidInput('hostname', hostname, |
---|
| 309 | "Already exists") |
---|
| 310 | if not re.match("^[A-Z0-9-]{1,22}$", hostname, re.I): |
---|
| 311 | raise InvalidInput('hostname', hostname, "Not a valid hostname; " |
---|
| 312 | "must only use number, letters, and dashes.") |
---|
| 313 | return hostname |
---|