blob: 2067a3989835e4bdf850f40c4edbe8400c3cce86 [file] [log] [blame]
Siobhan Tully00353f72013-10-08 21:53:27 -04001from django.db import models
Scott Baker008a9962015-04-15 20:58:20 -07002from core.models import PlCoreBase,SingletonModel,PlCoreBaseManager
Tony Mackd84b1ff2015-03-09 13:03:56 -04003from core.models.plcorebase import StrippedCharField
Scott Bakerd921e1c2015-04-20 14:24:29 -07004from xos.exceptions import *
Scott Baker618a4892015-07-06 14:27:31 -07005from operator import attrgetter
Scott Bakerf57e5592015-04-14 17:18:51 -07006import json
Siobhan Tully00353f72013-10-08 21:53:27 -04007
Scott Baker82498c52015-07-13 13:07:27 -07008class AttributeMixin(object):
9 # helper for extracting things from a json-encoded service_specific_attribute
10 def get_attribute(self, name, default=None):
11 if self.service_specific_attribute:
12 attributes = json.loads(self.service_specific_attribute)
13 else:
14 attributes = {}
15 return attributes.get(name, default)
16
17 def set_attribute(self, name, value):
18 if self.service_specific_attribute:
19 attributes = json.loads(self.service_specific_attribute)
20 else:
21 attributes = {}
22 attributes[name]=value
23 self.service_specific_attribute = json.dumps(attributes)
24
25 def get_initial_attribute(self, name, default=None):
26 if self._initial["service_specific_attribute"]:
27 attributes = json.loads(self._initial["service_specific_attribute"])
28 else:
29 attributes = {}
30 return attributes.get(name, default)
31
Scott Baker74404fe2015-07-13 13:54:06 -070032 @classmethod
33 def setup_simple_attributes(cls):
34 for (attrname, default) in cls.simple_attributes:
Scott Baker096dce82015-07-13 14:27:51 -070035 setattr(cls, attrname, property(lambda self, attrname=attrname, default=default: self.get_attribute(attrname, default),
36 lambda self, value, attrname=attrname: self.set_attribute(attrname, value),
37 None,
38 attrname))
Scott Baker74404fe2015-07-13 13:54:06 -070039
Scott Baker82498c52015-07-13 13:07:27 -070040class Service(PlCoreBase, AttributeMixin):
Scott Baker008a9962015-04-15 20:58:20 -070041 # when subclassing a service, redefine KIND to describe the new service
42 KIND = "generic"
43
Siobhan Tully00353f72013-10-08 21:53:27 -040044 description = models.TextField(max_length=254,null=True, blank=True,help_text="Description of Service")
45 enabled = models.BooleanField(default=True)
Scott Baker008a9962015-04-15 20:58:20 -070046 kind = StrippedCharField(max_length=30, help_text="Kind of service", default=KIND)
Tony Mackd84b1ff2015-03-09 13:03:56 -040047 name = StrippedCharField(max_length=30, help_text="Service Name")
48 versionNumber = StrippedCharField(max_length=30, help_text="Version of Service Definition")
Siobhan Tullycf04fb62014-01-11 11:25:57 -050049 published = models.BooleanField(default=True)
Tony Mackd84b1ff2015-03-09 13:03:56 -040050 view_url = StrippedCharField(blank=True, null=True, max_length=1024)
51 icon_url = StrippedCharField(blank=True, null=True, max_length=1024)
Scott Baker68944742015-04-30 14:30:56 -070052 public_key = models.TextField(null=True, blank=True, max_length=1024, help_text="Public key string")
Siobhan Tully00353f72013-10-08 21:53:27 -040053
Scott Baker2f0828e2015-07-13 12:33:28 -070054 # Service_specific_attribute and service_specific_id are opaque to XOS
55 service_specific_id = StrippedCharField(max_length=30, blank=True, null=True)
56 service_specific_attribute = models.TextField(blank=True, null=True)
57
Scott Baker008a9962015-04-15 20:58:20 -070058 def __init__(self, *args, **kwargs):
59 # for subclasses, set the default kind appropriately
60 self._meta.get_field("kind").default = self.KIND
61 super(Service, self).__init__(*args, **kwargs)
62
63 @classmethod
64 def get_service_objects(cls):
65 return cls.objects.filter(kind = cls.KIND)
66
Siobhan Tully00353f72013-10-08 21:53:27 -040067 def __unicode__(self): return u'%s' % (self.name)
68
Tony Mack9d2ea092015-04-29 12:23:10 -040069 def can_update(self, user):
70 return user.can_update_service(self, allow=['admin'])
Scott Baker618a4892015-07-06 14:27:31 -070071
Scott Baker98436732015-05-11 16:36:41 -070072 def get_scalable_nodes(self, slice, max_per_node=None, exclusive_slices=[]):
73 """
74 Get a list of nodes that can be used to scale up a slice.
75
76 slice - slice to scale up
77 max_per_node - maximum numbers of slivers that 'slice' can have on a single node
78 exclusive_slices - list of slices that must have no nodes in common with 'slice'.
79 """
80
81 from core.models import Node, Sliver # late import to get around order-of-imports constraint in __init__.py
82
83 nodes = list(Node.objects.all())
84
85 conflicting_slivers = Sliver.objects.filter(slice__in = exclusive_slices)
86 conflicting_nodes = Node.objects.filter(slivers__in = conflicting_slivers)
87
88 nodes = [x for x in nodes if x not in conflicting_nodes]
89
90 # If max_per_node is set, then limit the number of slivers this slice
91 # can have on a single node.
92 if max_per_node:
93 acceptable_nodes = []
94 for node in nodes:
95 existing_count = node.slivers.filter(slice=slice).count()
96 if existing_count < max_per_node:
97 acceptable_nodes.append(node)
98 nodes = acceptable_nodes
99
100 return nodes
101
102 def pick_node(self, slice, max_per_node=None, exclusive_slices=[]):
103 # Pick the best node to scale up a slice.
104
105 nodes = self.get_scalable_nodes(slice, max_per_node, exclusive_slices)
106 nodes = sorted(nodes, key=lambda node: node.slivers.all().count())
107 if not nodes:
108 return None
109 return nodes[0]
110
111 def adjust_scale(self, slice_hint, scale, max_per_node=None, exclusive_slices=[]):
112 from core.models import Sliver # late import to get around order-of-imports constraint in __init__.py
113
114 slices = [x for x in self.slices.all() if slice_hint in x.name]
115 for slice in slices:
116 while slice.slivers.all().count() > scale:
117 s = slice.slivers.all()[0]
118 # print "drop sliver", s
119 s.delete()
120
121 while slice.slivers.all().count() < scale:
122 node = self.pick_node(slice, max_per_node, exclusive_slices)
123 if not node:
124 # no more available nodes
125 break
126
127 image = slice.default_image
128 if not image:
129 raise XOSConfigurationError("No default_image for slice %s" % slice.name)
130
131 flavor = slice.default_flavor
132 if not flavor:
133 raise XOSConfigurationError("No default_flavor for slice %s" % slice.name)
134
135 s = Sliver(slice=slice,
136 node=node,
137 creator=slice.creator,
138 image=image,
139 flavor=flavor,
140 deployment=node.site_deployment.deployment)
141 s.save()
142
143 # print "add sliver", s
Tony Mack9d2ea092015-04-29 12:23:10 -0400144
Siobhan Tully00353f72013-10-08 21:53:27 -0400145class ServiceAttribute(PlCoreBase):
146 name = models.SlugField(help_text="Attribute Name", max_length=128)
Tony Mackd84b1ff2015-03-09 13:03:56 -0400147 value = StrippedCharField(help_text="Attribute Value", max_length=1024)
Siobhan Tully00353f72013-10-08 21:53:27 -0400148 service = models.ForeignKey(Service, related_name='serviceattributes', help_text="The Service this attribute is associated with")
149
Tony Mack9d2ea092015-04-29 12:23:10 -0400150class ServiceRole(PlCoreBase):
151 ROLE_CHOICES = (('admin','Admin'),)
152 role = StrippedCharField(choices=ROLE_CHOICES, unique=True, max_length=30)
153
154 def __unicode__(self): return u'%s' % (self.role)
155
156class ServicePrivilege(PlCoreBase):
157 user = models.ForeignKey('User', related_name='serviceprivileges')
158 service = models.ForeignKey('Service', related_name='serviceprivileges')
159 role = models.ForeignKey('ServiceRole',related_name='serviceprivileges')
160
161 class Meta:
Tony Mack9ec754e2015-05-13 12:21:28 -0400162 unique_together = ('user', 'service', 'role')
Tony Mack9d2ea092015-04-29 12:23:10 -0400163
164 def __unicode__(self): return u'%s %s %s' % (self.service, self.user, self.role)
165
166 def can_update(self, user):
167 if not self.service.enabled:
168 raise PermissionDenied, "Cannot modify permission(s) of a disabled service"
169 return self.service.can_update(user)
170
171 def save(self, *args, **kwds):
172 if not self.service.enabled:
173 raise PermissionDenied, "Cannot modify permission(s) of a disabled service"
174 super(ServicePrivilege, self).save(*args, **kwds)
175
176 def delete(self, *args, **kwds):
177 if not self.service.enabled:
178 raise PermissionDenied, "Cannot modify permission(s) of a disabled service"
Scott Baker4587b822015-07-01 18:29:08 -0700179 super(ServicePrivilege, self).delete(*args, **kwds)
180
Tony Mack9d2ea092015-04-29 12:23:10 -0400181 @staticmethod
182 def select_by_user(user):
183 if user.is_admin:
184 qs = ServicePrivilege.objects.all()
185 else:
186 qs = SitePrivilege.objects.filter(user=user)
Scott Baker4587b822015-07-01 18:29:08 -0700187 return qs
188
Scott Baker82498c52015-07-13 13:07:27 -0700189class TenantRoot(PlCoreBase, AttributeMixin):
Scott Baker4587b822015-07-01 18:29:08 -0700190 """ A tenantRoot is one of the things that can sit at the root of a chain
191 of tenancy. This object represents a node.
192 """
193
194 KIND= "generic"
195 kind = StrippedCharField(max_length=30, default=KIND)
Scott Baker618a4892015-07-06 14:27:31 -0700196 name = StrippedCharField(max_length=255, help_text="name", blank=True, null=True)
Scott Baker4587b822015-07-01 18:29:08 -0700197
Scott Bakerefcec632015-07-07 12:12:42 -0700198 service_specific_attribute = models.TextField(blank=True, null=True)
199 service_specific_id = StrippedCharField(max_length=30, blank=True, null=True)
Scott Baker4587b822015-07-01 18:29:08 -0700200
Scott Bakerdb66fd32015-07-07 17:59:44 -0700201 def __init__(self, *args, **kwargs):
202 # for subclasses, set the default kind appropriately
203 self._meta.get_field("kind").default = self.KIND
204 super(TenantRoot, self).__init__(*args, **kwargs)
205
Scott Baker618a4892015-07-06 14:27:31 -0700206 def __unicode__(self):
207 if not self.name:
208 return u"%s-tenant_root-#%s" % (str(self.kind), str(self.id))
209 else:
210 return self.name
211
212 def can_update(self, user):
213 return user.can_update_tenant_root(self, allow=['admin'])
214
Scott Bakerefcec632015-07-07 12:12:42 -0700215 def get_subscribed_tenants(self, tenant_class):
216 ids = self.subscribed_tenants.filter(kind=tenant_class.KIND)
217 return tenant_class.objects.filter(id__in = ids)
218
219 def get_newest_subscribed_tenant(self, kind):
220 st = list(self.get_subscribed_tenants(kind))
221 if not st:
222 return None
223 return sorted(st, key=attrgetter('id'))[0]
224
225 @classmethod
226 def get_tenant_objects(cls):
227 return cls.objects.filter(kind = cls.KIND)
228
Scott Baker82498c52015-07-13 13:07:27 -0700229class Tenant(PlCoreBase, AttributeMixin):
Scott Baker8103d0f2015-04-10 16:42:26 -0700230 """ A tenant is a relationship between two entities, a subscriber and a
Scott Baker4587b822015-07-01 18:29:08 -0700231 provider. This object represents an edge.
Scott Baker8103d0f2015-04-10 16:42:26 -0700232
233 The subscriber can be a User, a Service, or a Tenant.
234
235 The provider is always a Service.
Scott Baker4587b822015-07-01 18:29:08 -0700236
237 TODO: rename "Tenant" to "Tenancy"
Scott Baker8103d0f2015-04-10 16:42:26 -0700238 """
Scott Baker008a9962015-04-15 20:58:20 -0700239
Scott Baker925a8fa2015-04-26 20:30:40 -0700240 CONNECTIVITY_CHOICES = (('public', 'Public'), ('private', 'Private'), ('na', 'Not Applicable'))
241
Scott Baker008a9962015-04-15 20:58:20 -0700242 # when subclassing a service, redefine KIND to describe the new service
243 KIND = "generic"
244
245 kind = StrippedCharField(max_length=30, default=KIND)
Scott Baker4587b822015-07-01 18:29:08 -0700246 provider_service = models.ForeignKey(Service, related_name='provided_tenants')
247
248 # The next four things are the various type of objects that can be subscribers of this Tenancy
249 # relationship. One and only one can be used at a time.
250 subscriber_service = models.ForeignKey(Service, related_name='subscribed_tenants', blank=True, null=True)
251 subscriber_tenant = models.ForeignKey("Tenant", related_name='subscribed_tenants', blank=True, null=True)
252 subscriber_user = models.ForeignKey("User", related_name='subscribed_tenants', blank=True, null=True)
253 subscriber_root = models.ForeignKey("TenantRoot", related_name="subscribed_tenants", blank=True, null=True)
254
255 # Service_specific_attribute and service_specific_id are opaque to XOS
Scott Baker76934d82015-05-06 19:49:31 -0700256 service_specific_id = StrippedCharField(max_length=30, blank=True, null=True)
257 service_specific_attribute = models.TextField(blank=True, null=True)
Scott Baker4587b822015-07-01 18:29:08 -0700258
259 # Connect_method is only used by Coarse tenants
Scott Baker925a8fa2015-04-26 20:30:40 -0700260 connect_method = models.CharField(null=False, blank=False, max_length=30, choices=CONNECTIVITY_CHOICES, default="na")
Scott Baker8103d0f2015-04-10 16:42:26 -0700261
Scott Baker008a9962015-04-15 20:58:20 -0700262 def __init__(self, *args, **kwargs):
263 # for subclasses, set the default kind appropriately
264 self._meta.get_field("kind").default = self.KIND
265 super(Tenant, self).__init__(*args, **kwargs)
266
Scott Baker8103d0f2015-04-10 16:42:26 -0700267 def __unicode__(self):
Scott Bakerf996b762015-05-20 20:42:04 -0700268 return u"%s-tenant-%s" % (str(self.kind), str(self.id))
Scott Baker8103d0f2015-04-10 16:42:26 -0700269
Scott Baker008a9962015-04-15 20:58:20 -0700270 @classmethod
271 def get_tenant_objects(cls):
272 return cls.objects.filter(kind = cls.KIND)
273
Scott Bakere7fc9f52015-05-05 17:52:03 -0700274 @classmethod
275 def get_deleted_tenant_objects(cls):
276 return cls.deleted_objects.filter(kind = cls.KIND)
277
Scott Bakerd921e1c2015-04-20 14:24:29 -0700278 # helper function to be used in subclasses that want to ensure service_specific_id is unique
279 def validate_unique_service_specific_id(self):
280 if self.pk is None:
281 if self.service_specific_id is None:
282 raise XOSMissingField("subscriber_specific_id is None, and it's a required field", fields={"service_specific_id": "cannot be none"})
283
284 conflicts = self.get_tenant_objects().filter(service_specific_id=self.service_specific_id)
285 if conflicts:
286 raise XOSDuplicateKey("service_specific_id %s already exists" % self.service_specific_id, fields={"service_specific_id": "duplicate key"})
287
Scott Baker618a4892015-07-06 14:27:31 -0700288 def save(self, *args, **kwargs):
289 subCount = sum( [1 for e in [self.subscriber_service, self.subscriber_tenant, self.subscriber_user, self.subscriber_root] if e is not None])
290 if (subCount > 1):
291 raise XOSConflictingField("Only one of subscriber_service, subscriber_tenant, subscriber_user, subscriber_root should be set")
292
293 super(Tenant, self).save(*args, **kwargs)
294
295 def get_subscribed_tenants(self, tenant_class):
296 ids = self.subscribed_tenants.filter(kind=tenant_class.KIND)
297 return tenant_class.objects.filter(id__in = ids)
298
299 def get_newest_subscribed_tenant(self, kind):
300 st = list(self.get_subscribed_tenants(kind))
301 if not st:
302 return None
303 return sorted(st, key=attrgetter('id'))[0]
304
305
Scott Baker925a8fa2015-04-26 20:30:40 -0700306class CoarseTenant(Tenant):
Scott Baker4587b822015-07-01 18:29:08 -0700307 """ TODO: rename "CoarseTenant" --> "StaticTenant" """
Scott Baker925a8fa2015-04-26 20:30:40 -0700308 class Meta:
309 proxy = True
Siobhan Tully00353f72013-10-08 21:53:27 -0400310
Scott Baker925a8fa2015-04-26 20:30:40 -0700311 KIND = "coarse"
312
313 def save(self, *args, **kwargs):
314 if (not self.subscriber_service):
315 raise XOSValidationError("subscriber_service cannot be null")
316 if (self.subscriber_tenant or self.subscriber_user):
317 raise XOSValidationError("subscriber_tenant and subscriber_user must be null")
318
319 super(CoarseTenant,self).save()
Scott Baker4587b822015-07-01 18:29:08 -0700320
321class Subscriber(TenantRoot):
322 """ Intermediate class for TenantRoots that are to be Subscribers """
323
324 class Meta:
325 proxy = True
326
327 KIND = "Subscriber"
328
329class Provider(TenantRoot):
330 """ Intermediate class for TenantRoots that are to be Providers """
331
332 class Meta:
333 proxy = True
334
335 KIND = "Provider"
336
337class TenantRootRole(PlCoreBase):
338 ROLE_CHOICES = (('admin','Admin'),)
339
340 role = StrippedCharField(choices=ROLE_CHOICES, unique=True, max_length=30)
341
342 def __unicode__(self): return u'%s' % (self.role)
343
344class TenantRootPrivilege(PlCoreBase):
345 user = models.ForeignKey('User', related_name="tenant_root_privileges")
346 tenant_root = models.ForeignKey('TenantRoot', related_name="tenant_root_privileges")
347 role = models.ForeignKey('TenantRootRole', related_name="tenant_root_privileges")
348
349 class Meta:
350 unique_together = ('user', 'tenant_root', 'role')
351
Scott Baker618a4892015-07-06 14:27:31 -0700352 def __unicode__(self): return u'%s %s %s' % (self.tenant_root, self.user, self.role)
Scott Baker4587b822015-07-01 18:29:08 -0700353
354 def save(self, *args, **kwds):
355 if not self.user.is_active:
356 raise PermissionDenied, "Cannot modify role(s) of a disabled user"
Scott Baker335882a2015-07-24 10:15:31 -0700357 super(TenantRootPrivilege, self).save(*args, **kwds)
Scott Baker4587b822015-07-01 18:29:08 -0700358
359 def can_update(self, user):
Scott Baker335882a2015-07-24 10:15:31 -0700360 return user.can_update_tenant_root_privilege(self)
Scott Baker4587b822015-07-01 18:29:08 -0700361
362 @staticmethod
363 def select_by_user(user):
364 if user.is_admin:
Scott Baker618a4892015-07-06 14:27:31 -0700365 qs = TenantRootPrivilege.objects.all()
Scott Baker4587b822015-07-01 18:29:08 -0700366 else:
Scott Baker618a4892015-07-06 14:27:31 -0700367 qs = TenantRootPrivilege.objects.filter(user=user)
Scott Baker4587b822015-07-01 18:29:08 -0700368 return qs
Scott Baker618a4892015-07-06 14:27:31 -0700369