blob: 554bbf5bb5d03bfeed575abca3af8ee06d0ebea9 [file] [log] [blame]
Scott Baker58a9c7a2013-07-29 15:43:07 -07001import os
2import socket
3from django.db import models
Tony Mack51c4a7d2014-11-30 15:33:35 -05004from core.models import PlCoreBase, Site, Slice, Sliver, Controller
5from core.models import ControllerLinkManager,ControllerLinkDeletionManager
Scott Baker58a9c7a2013-07-29 15:43:07 -07006from django.contrib.contenttypes.models import ContentType
7from django.contrib.contenttypes import generic
Scott Bakera289ed72014-10-17 16:22:20 -07008from django.core.exceptions import ValidationError
Scott Baker58a9c7a2013-07-29 15:43:07 -07009
10# If true, then IP addresses will be allocated by the model. If false, then
11# we will assume the observer handles it.
Scott Baker026bfe72013-07-29 16:03:50 -070012NO_OBSERVER=False
Scott Baker58a9c7a2013-07-29 15:43:07 -070013
Scott Bakera289ed72014-10-17 16:22:20 -070014def ParseNatList(ports):
15 """ Support a list of ports in the format "protocol:port, protocol:port, ..."
16 examples:
17 tcp 123
18 tcp 123:133
19 tcp 123, tcp 124, tcp 125, udp 201, udp 202
20
21 User can put either a "/" or a " " between protocol and ports
22 Port ranges can be specified with "-" or ":"
23 """
24 nats = []
25 if ports:
26 parts = ports.split(",")
27 for part in parts:
28 part = part.strip()
29 if "/" in part:
30 (protocol, ports) = part.split("/",1)
31 elif " " in part:
32 (protocol, ports) = part.split(None,1)
33 else:
34 raise TypeError('malformed port specifier %s, format example: "tcp 123, tcp 201:206, udp 333"' % part)
35
36 protocol = protocol.strip()
37 ports = ports.strip()
38
39 if not (protocol in ["udp", "tcp"]):
40 raise ValueError('unknown protocol %s' % protocol)
41
42 if "-" in ports:
43 (first, last) = ports.split("-")
44 first = int(first.strip())
45 last = int(last.strip())
46 portStr = "%d:%d" % (first, last)
47 elif ":" in ports:
48 (first, last) = ports.split(":")
49 first = int(first.strip())
50 last = int(last.strip())
51 portStr = "%d:%d" % (first, last)
52 else:
53 portStr = "%d" % int(ports)
54
55 nats.append( {"l4_protocol": protocol, "l4_port": portStr} )
56
57 return nats
58
59def ValidateNatList(ports):
60 try:
61 ParseNatList(ports)
62 except Exception,e:
63 raise ValidationError(str(e))
64
Scott Baker58a9c7a2013-07-29 15:43:07 -070065class NetworkTemplate(PlCoreBase):
66 VISIBILITY_CHOICES = (('public', 'public'), ('private', 'private'))
Scott Baker87e5e092013-08-07 18:58:10 -070067 TRANSLATION_CHOICES = (('none', 'none'), ('NAT', 'NAT'))
Scott Baker59078f82014-11-17 16:03:49 -080068 TOPOLOGY_CHOICES = (('bigswitch', 'BigSwitch'), ('physical', 'Physical'), ('custom', 'Custom'))
69 CONTROLLER_CHOICES = ((None, 'None'), ('onos', 'ONOS'), ('custom', 'Custom'))
Scott Baker58a9c7a2013-07-29 15:43:07 -070070
71 name = models.CharField(max_length=32)
72 description = models.CharField(max_length=1024, blank=True, null=True)
Scott Baker369f9b92015-01-03 12:03:38 -080073 guaranteed_bandwidth = models.IntegerField(default=0)
Scott Baker58a9c7a2013-07-29 15:43:07 -070074 visibility = models.CharField(max_length=30, choices=VISIBILITY_CHOICES, default="private")
Scott Baker87e5e092013-08-07 18:58:10 -070075 translation = models.CharField(max_length=30, choices=TRANSLATION_CHOICES, default="none")
Scott Baker369f9b92015-01-03 12:03:38 -080076 shared_network_name = models.CharField(max_length=30, blank=True, null=True)
77 shared_network_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum network")
78 topology_kind = models.CharField(null=False, blank=False, max_length=30, choices=TOPOLOGY_CHOICES, default="BigSwitch")
79 controller_kind = models.CharField(null=True, blank=True, max_length=30, choices=CONTROLLER_CHOICES, default=None)
Scott Baker58a9c7a2013-07-29 15:43:07 -070080
Scott Baker201f7da2014-12-23 10:56:06 -080081 def __init__(self, *args, **kwargs):
82 super(NetworkTemplate, self).__init__(*args, **kwargs)
83
84 # somehow these got set wrong inside of the live database. Remove this
85 # code after all is well...
Scott Baker369f9b92015-01-03 12:03:38 -080086 if (self.topology_kind=="BigSwitch"):
87 print "XXX warning: topology_kind invalid case"
88 self.topology_kind="bigswitch"
89 elif (self.topology_kind=="Physical"):
90 print "XXX warning: topology_kind invalid case"
91 self.topology_kind="physical"
92 elif (self.topology_kind=="Custom"):
93 print "XXX warning: topology_kind invalid case"
94 self.toplogy_kind="custom"
Scott Baker201f7da2014-12-23 10:56:06 -080095
Scott Baker58a9c7a2013-07-29 15:43:07 -070096 def __unicode__(self): return u'%s' % (self.name)
97
98class Network(PlCoreBase):
99 name = models.CharField(max_length=32)
100 template = models.ForeignKey(NetworkTemplate)
101 subnet = models.CharField(max_length=32, blank=True)
Scott Bakera289ed72014-10-17 16:22:20 -0700102 ports = models.CharField(max_length=1024, blank=True, null=True, validators=[ValidateNatList])
Scott Baker58a9c7a2013-07-29 15:43:07 -0700103 labels = models.CharField(max_length=1024, blank=True, null=True)
Siobhan Tullyce652d02013-10-08 21:52:35 -0400104 owner = models.ForeignKey(Slice, related_name="ownedNetworks", help_text="Slice that owns control of this Network")
Scott Baker58a9c7a2013-07-29 15:43:07 -0700105
Scott Baker549aa252015-01-03 12:29:29 -0800106 guaranteed_bandwidth = models.IntegerField(default=0)
107 permit_all_slices = models.BooleanField(default=False)
108 permitted_slices = models.ManyToManyField(Slice, blank=True, related_name="availableNetworks")
Scott Baker87191e72013-08-06 08:55:07 -0700109 slices = models.ManyToManyField(Slice, blank=True, related_name="networks", through="NetworkSlice")
Scott Baker58a9c7a2013-07-29 15:43:07 -0700110 slivers = models.ManyToManyField(Sliver, blank=True, related_name="networks", through="NetworkSliver")
111
Scott Baker549aa252015-01-03 12:29:29 -0800112 topology_parameters = models.TextField(null=True, blank=True)
113 controller_url = models.CharField(null=True, blank=True, max_length=1024)
114 controller_parameters = models.TextField(null=True, blank=True)
Scott Baker59078f82014-11-17 16:03:49 -0800115
Scott Baker87191e72013-08-06 08:55:07 -0700116 # for observer/manager
117 network_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum network")
118 router_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum router id")
119 subnet_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum subnet id")
120
Scott Baker58a9c7a2013-07-29 15:43:07 -0700121 def __unicode__(self): return u'%s' % (self.name)
122
123 def save(self, *args, **kwds):
124 if (not self.subnet) and (NO_OBSERVER):
125 from util.network_subnet_allocator import find_unused_subnet
126 self.subnet = find_unused_subnet(existing_subnets=[x.subnet for x in Network.objects.all()])
127 super(Network, self).save(*args, **kwds)
128
Tony Mack5b061472014-02-04 07:57:10 -0500129 def can_update(self, user):
Tony Mack31683c82014-04-02 15:39:32 -0400130 return self.owner.can_update(user)
Tony Mack5b061472014-02-04 07:57:10 -0500131
Scott Baker5bbaa232014-08-14 17:23:15 -0700132 @property
133 def nat_list(self):
Scott Bakera289ed72014-10-17 16:22:20 -0700134 return ParseNatList(self.ports)
Scott Baker5bbaa232014-08-14 17:23:15 -0700135
Tony Mack5b061472014-02-04 07:57:10 -0500136 @staticmethod
137 def select_by_user(user):
138 if user.is_admin:
139 qs = Network.objects.all()
140 else:
Tony Mack5efa1332014-04-02 15:45:48 -0400141 slices = Slice.select_by_user(user)
142 #slice_ids = [s.id for s in Slice.select_by_user(user)]
143 qs = Network.objects.filter(owner__in=slices)
Tony Mack5b061472014-02-04 07:57:10 -0500144 return qs
145
Tony Mack51c4a7d2014-11-30 15:33:35 -0500146class ControllerNetworks(PlCoreBase):
147 objects = ControllerLinkManager()
148 deleted_objects = ControllerLinkDeletionManager()
Sapan Bhatiaed7b83b2014-09-22 14:52:59 -0400149
Tony Mack51c4a7d2014-11-30 15:33:35 -0500150 # Stores the openstack ids at various controllers
151 network = models.ForeignKey(Network, related_name='controllernetworks')
152 controller = models.ForeignKey(Controller, related_name='controllernetworks')
Tony Mack457c84c2014-04-08 16:37:56 -0400153 net_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum network")
Tony Macke9b08692014-04-07 19:38:28 -0400154 router_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum router id")
Scott Baker95d81c72014-08-12 18:29:27 -0700155 subnet_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum subnet id")
156 subnet = models.CharField(max_length=32, blank=True)
Tony Macke9b08692014-04-07 19:38:28 -0400157
158 def can_update(self, user):
159 return user.is_admin
160
161 @staticmethod
162 def select_by_user(user):
163 if user.is_admin:
Tony Mack51c4a7d2014-11-30 15:33:35 -0500164 qs = NetworkControllers.objects.all()
Tony Macke9b08692014-04-07 19:38:28 -0400165 else:
166 slices = Slice.select_by_user(user)
167 networks = Network.objects.filter(owner__in=slices)
Tony Mack51c4a7d2014-11-30 15:33:35 -0500168 qs = NetworkControllers.objects.filter(network__in=networks)
Scott Baker95d81c72014-08-12 18:29:27 -0700169 return qs
Tony Macke9b08692014-04-07 19:38:28 -0400170
Scott Baker87191e72013-08-06 08:55:07 -0700171class NetworkSlice(PlCoreBase):
172 # This object exists solely so we can implement the permission check when
173 # adding slices to networks. It adds no additional fields to the relation.
174
Sapan Bhatia6bfa2ca2014-11-11 21:47:45 -0500175 network = models.ForeignKey(Network,related_name='networkslices')
176 slice = models.ForeignKey(Slice,related_name='networkslices')
Scott Baker87191e72013-08-06 08:55:07 -0700177
178 def save(self, *args, **kwds):
179 slice = self.slice
Scott Baker549aa252015-01-03 12:29:29 -0800180 if (slice not in self.network.permitted_slices.all()) and (slice != self.network.owner) and (not self.network.permitAllSlices):
Scott Baker87191e72013-08-06 08:55:07 -0700181 # to add a sliver to the network, then one of the following must be true:
182 # 1) sliver's slice is in network's permittedSlices list,
183 # 2) sliver's slice is network's owner, or
184 # 3) network's permitAllSlices is true
185 raise ValueError("Slice %s is not allowed to connect to network %s" % (str(slice), str(self.network)))
186
187 super(NetworkSlice, self).save(*args, **kwds)
188
189 def __unicode__(self): return u'%s-%s' % (self.network.name, self.slice.name)
190
Tony Mack5b061472014-02-04 07:57:10 -0500191 def can_update(self, user):
192 return self.slice.can_update(user)
193
Tony Mack5b061472014-02-04 07:57:10 -0500194 @staticmethod
195 def select_by_user(user):
196 if user.is_admin:
197 qs = NetworkSlice.objects.all()
198 else:
199 slice_ids = [s.id for s in Slice.select_by_user(user)]
200 qs = NetworkSlice.objects.filter(id__in=slice_ids)
201 return qs
202
Scott Baker58a9c7a2013-07-29 15:43:07 -0700203class NetworkSliver(PlCoreBase):
Sapan Bhatiaf83ea302014-11-11 22:01:30 -0500204 network = models.ForeignKey(Network,related_name='networkslivers')
205 sliver = models.ForeignKey(Sliver,related_name='networkslivers')
Scott Baker026bfe72013-07-29 16:03:50 -0700206 ip = models.GenericIPAddressField(help_text="Sliver ip address", blank=True, null=True)
Scott Bakerf4df9522013-08-19 17:56:45 -0700207 port_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum port id")
Scott Baker58a9c7a2013-07-29 15:43:07 -0700208
209 def save(self, *args, **kwds):
Scott Baker87191e72013-08-06 08:55:07 -0700210 slice = self.sliver.slice
Scott Baker549aa252015-01-03 12:29:29 -0800211 if (slice not in self.network.permitted_slices.all()) and (slice != self.network.owner) and (not self.network.permitAllSlices):
Scott Baker87191e72013-08-06 08:55:07 -0700212 # to add a sliver to the network, then one of the following must be true:
213 # 1) sliver's slice is in network's permittedSlices list,
214 # 2) sliver's slice is network's owner, or
215 # 3) network's permitAllSlices is true
216 raise ValueError("Slice %s is not allowed to connect to network %s" % (str(slice), str(self.network)))
217
Scott Baker58a9c7a2013-07-29 15:43:07 -0700218 if (not self.ip) and (NO_OBSERVER):
219 from util.network_subnet_allocator import find_unused_address
220 self.ip = find_unused_address(self.network.subnet,
221 [x.ip for x in self.network.networksliver_set.all()])
222 super(NetworkSliver, self).save(*args, **kwds)
223
224 def __unicode__(self): return u'%s-%s' % (self.network.name, self.sliver.instance_name)
225
Tony Mack5b061472014-02-04 07:57:10 -0500226 def can_update(self, user):
227 return self.sliver.can_update(user)
228
Tony Mack5b061472014-02-04 07:57:10 -0500229 @staticmethod
230 def select_by_user(user):
231 if user.is_admin:
232 qs = NetworkSliver.objects.all()
233 else:
234 sliver_ids = [s.id for s in NetworkSliver.select_by_user(user)]
235 qs = NetworkSliver.objects.filter(id__in=sliver_ids)
236 return qs
237
Scott Baker58a9c7a2013-07-29 15:43:07 -0700238class Router(PlCoreBase):
239 name = models.CharField(max_length=32)
240 owner = models.ForeignKey(Slice, related_name="routers")
241 permittedNetworks = models.ManyToManyField(Network, blank=True, related_name="availableRouters")
242 networks = models.ManyToManyField(Network, blank=True, related_name="routers")
243
244 def __unicode__(self): return u'%s' % (self.name)
245
246class NetworkParameterType(PlCoreBase):
247 name = models.SlugField(help_text="The name of this parameter", max_length=128)
248 description = models.CharField(max_length=1024)
249
250 def __unicode__(self): return u'%s' % (self.name)
251
252class NetworkParameter(PlCoreBase):
Sapan Bhatia6bfa2ca2014-11-11 21:47:45 -0500253 parameter = models.ForeignKey(NetworkParameterType, related_name="networkparameters", help_text="The type of the parameter")
Scott Baker58a9c7a2013-07-29 15:43:07 -0700254 value = models.CharField(help_text="The value of this parameter", max_length=1024)
255
256 # The required fields to do a ObjectType lookup, and object_id assignment
257 content_type = models.ForeignKey(ContentType)
258 object_id = models.PositiveIntegerField()
259 content_object = generic.GenericForeignKey('content_type', 'object_id')
260
261 def __unicode__(self):
262 return self.parameter.name
263
264