3 from django.db import models
4 from core.models import PlCoreBase, Site, Slice, Sliver, Controller
5 from core.models import ControllerLinkManager,ControllerLinkDeletionManager
6 from django.contrib.contenttypes.models import ContentType
7 from django.contrib.contenttypes import generic
8 from django.core.exceptions import ValidationError
10 # If true, then IP addresses will be allocated by the model. If false, then
11 # we will assume the observer handles it.
14 def ParseNatList(ports):
15 """ Support a list of ports in the format "protocol:port, protocol:port, ..."
19 tcp 123, tcp 124, tcp 125, udp 201, udp 202
21 User can put either a "/" or a " " between protocol and ports
22 Port ranges can be specified with "-" or ":"
26 parts = ports.split(",")
30 (protocol, ports) = part.split("/",1)
32 (protocol, ports) = part.split(None,1)
34 raise TypeError('malformed port specifier %s, format example: "tcp 123, tcp 201:206, udp 333"' % part)
36 protocol = protocol.strip()
39 if not (protocol in ["udp", "tcp"]):
40 raise ValueError('unknown protocol %s' % protocol)
43 (first, last) = ports.split("-")
44 first = int(first.strip())
45 last = int(last.strip())
46 portStr = "%d:%d" % (first, last)
48 (first, last) = ports.split(":")
49 first = int(first.strip())
50 last = int(last.strip())
51 portStr = "%d:%d" % (first, last)
53 portStr = "%d" % int(ports)
55 nats.append( {"l4_protocol": protocol, "l4_port": portStr} )
59 def ValidateNatList(ports):
63 raise ValidationError(str(e))
65 class NetworkTemplate(PlCoreBase):
66 VISIBILITY_CHOICES = (('public', 'public'), ('private', 'private'))
67 TRANSLATION_CHOICES = (('none', 'none'), ('NAT', 'NAT'))
68 TOPOLOGY_CHOICES = (('bigswitch', 'BigSwitch'), ('physical', 'Physical'), ('custom', 'Custom'))
69 CONTROLLER_CHOICES = ((None, 'None'), ('onos', 'ONOS'), ('custom', 'Custom'))
71 name = models.CharField(max_length=32)
72 description = models.CharField(max_length=1024, blank=True, null=True)
73 guaranteedBandwidth = models.IntegerField(default=0)
74 visibility = models.CharField(max_length=30, choices=VISIBILITY_CHOICES, default="private")
75 translation = models.CharField(max_length=30, choices=TRANSLATION_CHOICES, default="none")
76 sharedNetworkName = models.CharField(max_length=30, blank=True, null=True)
77 sharedNetworkId = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum network")
78 topologyKind = models.CharField(null=False, blank=False, max_length=30, choices=TOPOLOGY_CHOICES, default="BigSwitch")
79 controllerKind = models.CharField(null=True, blank=True, max_length=30, choices=CONTROLLER_CHOICES, default=None)
81 def __init__(self, *args, **kwargs):
82 super(NetworkTemplate, self).__init__(*args, **kwargs)
84 # somehow these got set wrong inside of the live database. Remove this
85 # code after all is well...
86 if (self.topologyKind=="BigSwitch"):
87 print "XXX warning: topologyKind invalid case"
88 self.topologyKind="bigswitch"
89 elif (self.topologyKind=="Physical"):
90 print "XXX warning: topologyKind invalid case"
91 self.topologyKind="physical"
92 elif (self.topologyKind=="Custom"):
93 print "XXX warning: topologyKind invalid case"
94 self.toplogyKind="custom"
96 def __unicode__(self): return u'%s' % (self.name)
98 class Network(PlCoreBase):
99 name = models.CharField(max_length=32)
100 template = models.ForeignKey(NetworkTemplate)
101 subnet = models.CharField(max_length=32, blank=True)
102 ports = models.CharField(max_length=1024, blank=True, null=True, validators=[ValidateNatList])
103 labels = models.CharField(max_length=1024, blank=True, null=True)
104 owner = models.ForeignKey(Slice, related_name="ownedNetworks", help_text="Slice that owns control of this Network")
106 guaranteedBandwidth = models.IntegerField(default=0)
107 permitAllSlices = models.BooleanField(default=False)
108 permittedSlices = models.ManyToManyField(Slice, blank=True, related_name="availableNetworks")
109 slices = models.ManyToManyField(Slice, blank=True, related_name="networks", through="NetworkSlice")
110 slivers = models.ManyToManyField(Sliver, blank=True, related_name="networks", through="NetworkSliver")
112 topologyParameters = models.TextField(null=True, blank=True)
113 controllerUrl = models.CharField(null=True, blank=True, max_length=1024)
114 controllerParameters = models.TextField(null=True, blank=True)
116 # 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")
121 def __unicode__(self): return u'%s' % (self.name)
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)
129 def can_update(self, user):
130 return self.owner.can_update(user)
134 return ParseNatList(self.ports)
137 def select_by_user(user):
139 qs = Network.objects.all()
141 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)
146 class ControllerNetworks(PlCoreBase):
147 objects = ControllerLinkManager()
148 deleted_objects = ControllerLinkDeletionManager()
150 # Stores the openstack ids at various controllers
151 network = models.ForeignKey(Network, related_name='controllernetworks')
152 controller = models.ForeignKey(Controller, related_name='controllernetworks')
153 net_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum network")
154 router_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum router id")
155 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)
158 def can_update(self, user):
162 def select_by_user(user):
164 qs = NetworkControllers.objects.all()
166 slices = Slice.select_by_user(user)
167 networks = Network.objects.filter(owner__in=slices)
168 qs = NetworkControllers.objects.filter(network__in=networks)
171 class 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.
175 network = models.ForeignKey(Network,related_name='networkslices')
176 slice = models.ForeignKey(Slice,related_name='networkslices')
178 def save(self, *args, **kwds):
180 if (slice not in self.network.permittedSlices.all()) and (slice != self.network.owner) and (not self.network.permitAllSlices):
181 # 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)))
187 super(NetworkSlice, self).save(*args, **kwds)
189 def __unicode__(self): return u'%s-%s' % (self.network.name, self.slice.name)
191 def can_update(self, user):
192 return self.slice.can_update(user)
195 def select_by_user(user):
197 qs = NetworkSlice.objects.all()
199 slice_ids = [s.id for s in Slice.select_by_user(user)]
200 qs = NetworkSlice.objects.filter(id__in=slice_ids)
203 class NetworkSliver(PlCoreBase):
204 network = models.ForeignKey(Network,related_name='networkslivers')
205 sliver = models.ForeignKey(Sliver,related_name='networkslivers')
206 ip = models.GenericIPAddressField(help_text="Sliver ip address", blank=True, null=True)
207 port_id = models.CharField(null=True, blank=True, max_length=256, help_text="Quantum port id")
209 def save(self, *args, **kwds):
210 slice = self.sliver.slice
211 if (slice not in self.network.permittedSlices.all()) and (slice != self.network.owner) and (not self.network.permitAllSlices):
212 # 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)))
218 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)
224 def __unicode__(self): return u'%s-%s' % (self.network.name, self.sliver.instance_name)
226 def can_update(self, user):
227 return self.sliver.can_update(user)
230 def select_by_user(user):
232 qs = NetworkSliver.objects.all()
234 sliver_ids = [s.id for s in NetworkSliver.select_by_user(user)]
235 qs = NetworkSliver.objects.filter(id__in=sliver_ids)
238 class 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")
244 def __unicode__(self): return u'%s' % (self.name)
246 class NetworkParameterType(PlCoreBase):
247 name = models.SlugField(help_text="The name of this parameter", max_length=128)
248 description = models.CharField(max_length=1024)
250 def __unicode__(self): return u'%s' % (self.name)
252 class NetworkParameter(PlCoreBase):
253 parameter = models.ForeignKey(NetworkParameterType, related_name="networkparameters", help_text="The type of the parameter")
254 value = models.CharField(help_text="The value of this parameter", max_length=1024)
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')
261 def __unicode__(self):
262 return self.parameter.name