Refactoring: Made complete codebase PEP8 compatible.
[osm/vim-emu.git] / src / emuvim / api / openstack / resources / net.py
1 # Copyright (c) 2015 SONATA-NFV and Paderborn University
2 # ALL RIGHTS RESERVED.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # Neither the name of the SONATA-NFV, Paderborn University
17 # nor the names of its contributors may be used to endorse or promote
18 # products derived from this software without specific prior written
19 # permission.
20 #
21 # This work has been performed in the framework of the SONATA project,
22 # funded by the European Commission under Grant number 671517 through
23 # the Horizon 2020 and 5G-PPP programmes. The authors would like to
24 # acknowledge the contributions of their colleagues of the SONATA
25 # partner consortium (www.sonata-nfv.eu).
26 import re
27
28
29 class Net:
30 def __init__(self, name):
31 self.name = name
32 self.id = None
33 self.subnet_name = None
34 self.subnet_id = None
35 self.subnet_creation_time = None
36 self.subnet_update_time = None
37 self.gateway_ip = None
38 self.segmentation_id = None # not set
39 self._cidr = None
40 self.start_end_dict = None
41 self._issued_ip_addresses = dict()
42
43 def get_short_id(self):
44 """
45 Returns a shortened UUID, with only the first 6 characters.
46
47 :return: First 6 characters of the UUID
48 :rtype: ``str``
49 """
50 return str(self.id)[:6]
51
52 def get_new_ip_address(self, port_name):
53 """
54 Calculates the next unused IP Address which belongs to the subnet.
55
56 :param port_name: Specifies the port.
57 :type port_name: ``str``
58 :return: Returns a unused IP Address or none if all are in use.
59 :rtype: ``str``
60 """
61 if self.start_end_dict is None:
62 return None
63
64 # First address as network address not usable
65 int_start_ip = Net.ip_2_int(self.start_end_dict['start']) + 2
66 # Second one is for gateways only
67 # Last address for broadcasts
68 int_end_ip = Net.ip_2_int(self.start_end_dict['end']) - 1
69 while int_start_ip in self._issued_ip_addresses and int_start_ip <= int_end_ip:
70 int_start_ip += 1
71
72 if int_start_ip > int_end_ip:
73 return None
74
75 self._issued_ip_addresses[int_start_ip] = port_name
76 return Net.int_2_ip(int_start_ip) + '/' + self._cidr.rsplit('/', 1)[1]
77
78 def assign_ip_address(self, cidr, port_name):
79 """
80 Assigns the IP address to the port if it is currently NOT used.
81
82 :param cidr: The cidr used by the port - e.g. 10.0.0.1/24
83 :type cidr: ``str``
84 :param port_name: The port name
85 :type port_name: ``str``
86 :return: * *False*: If the IP address is already issued or if it is not within this subnet mask.
87 * *True*: Else
88 """
89 int_ip = Net.cidr_2_int(cidr)
90 if int_ip in self._issued_ip_addresses:
91 return False
92
93 # First address as network address not usable
94 int_start_ip = Net.ip_2_int(self.start_end_dict['start']) + 1
95 # Last address for broadcasts
96 int_end_ip = Net.ip_2_int(self.start_end_dict['end']) - 1
97 if int_ip < int_start_ip or int_ip > int_end_ip:
98 return False
99
100 self._issued_ip_addresses[int_ip] = port_name
101 return True
102
103 def is_my_ip(self, cidr, port_name):
104 """
105 Checks if the IP is registered for this port name.
106
107 :param cidr: The cidr used by the port - e.g. 10.0.0.1/24
108 :type cidr: ``str``
109 :param port_name: The port name
110 :type port_name: ``str``
111 :return: Returns true if the IP address belongs to the port name. Else it returns false.
112 """
113 int_ip = Net.cidr_2_int(cidr)
114
115 if int_ip not in self._issued_ip_addresses:
116 return False
117
118 if self._issued_ip_addresses[int_ip] == port_name:
119 return True
120 return False
121
122 def withdraw_ip_address(self, ip_address):
123 """
124 Removes the IP address from the list of issued addresses, thus other ports can use it.
125
126 :param ip_address: The issued IP address.
127 :type ip_address: ``str``
128 """
129 if ip_address is None:
130 return
131
132 if "/" in ip_address:
133 address, suffix = ip_address.rsplit('/', 1)
134 else:
135 address = ip_address
136 int_ip_address = Net.ip_2_int(address)
137 if int_ip_address in self._issued_ip_addresses.keys():
138 del self._issued_ip_addresses[int_ip_address]
139
140 def reset_issued_ip_addresses(self):
141 """
142 Resets all issued IP addresses.
143 """
144 self._issued_ip_addresses = dict()
145
146 def update_port_name_for_ip_address(self, ip_address, port_name):
147 """
148 Updates the port name of the issued IP address.
149
150 :param ip_address: The already issued IP address.
151 :type ip_address: ``str``
152 :param port_name: The new port name
153 :type port_name: ``str``
154 """
155 address, suffix = ip_address.rsplit('/', 1)
156 int_ip_address = Net.ip_2_int(address)
157 self._issued_ip_addresses[int_ip_address] = port_name
158
159 def set_cidr(self, cidr):
160 """
161 Sets the CIDR for the subnet. It previously checks for the correct CIDR format.
162
163 :param cidr: The new CIDR for the subnet.
164 :type cidr: ``str``
165 :return: * *True*: When the new CIDR was set successfully.
166 * *False*: If the CIDR format was wrong.
167 :rtype: ``bool``
168 """
169 if cidr is None:
170 if self._cidr is not None:
171 import emuvim.api.openstack.ip_handler as IP
172 IP.free_cidr(self._cidr, self.subnet_id)
173 self._cidr = None
174 self.reset_issued_ip_addresses()
175 self.start_end_dict = dict()
176 return True
177 if not Net.check_cidr_format(cidr):
178 return False
179
180 self.reset_issued_ip_addresses()
181 self.start_end_dict = Net.calculate_start_and_end_dict(cidr)
182 self._cidr = cidr
183 return True
184
185 def get_cidr(self):
186 """
187 Gets the CIDR.
188
189 :return: The CIDR
190 :rtype: ``str``
191 """
192 return self._cidr
193
194 def clear_cidr(self):
195 self._cidr = None
196 self.start_end_dict = dict()
197 self.reset_issued_ip_addresses()
198
199 def delete_subnet(self):
200 self.subnet_id = None
201 self.subnet_name = None
202 self.subnet_creation_time = None
203 self.subnet_update_time = None
204 self.set_cidr(None)
205
206 @staticmethod
207 def calculate_start_and_end_dict(cidr):
208 """
209 Calculates the start and end IP address for the subnet.
210
211 :param cidr: The CIDR for the subnet.
212 :type cidr: ``str``
213 :return: Dict with start and end ip address
214 :rtype: ``dict``
215 """
216 address, suffix = cidr.rsplit('/', 1)
217 int_suffix = int(suffix)
218 int_address = Net.ip_2_int(address)
219 address_space = 2 ** 32 - 1
220
221 for x in range(0, 31 - int_suffix):
222 address_space = ~(~address_space | (1 << x))
223
224 start = int_address & address_space
225 end = start + (2 ** (32 - int_suffix) - 1)
226
227 return {'start': Net.int_2_ip(start), 'end': Net.int_2_ip(end)}
228
229 @staticmethod
230 def cidr_2_int(cidr):
231 if cidr is None:
232 return None
233 ip = cidr.rsplit('/', 1)[0]
234 return Net.ip_2_int(ip)
235
236 @staticmethod
237 def ip_2_int(ip):
238 """
239 Converts a IP address to int.
240
241 :param ip: IP address
242 :type ip: ``str``
243 :return: IP address as int.
244 :rtype: ``int``
245 """
246 o = map(int, ip.split('.'))
247 res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
248 return res
249
250 @staticmethod
251 def int_2_ip(int_ip):
252 """
253 Converts a int IP address to string.
254
255 :param int_ip: Int IP address.
256 :type int_ip: ``int``
257 :return: IP address
258 :rtype: ``str``
259 """
260 o1 = int(int_ip / 16777216) % 256
261 o2 = int(int_ip / 65536) % 256
262 o3 = int(int_ip / 256) % 256
263 o4 = int(int_ip) % 256
264 return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()
265
266 @staticmethod
267 def check_cidr_format(cidr):
268 """
269 Checks the CIDR format. An valid example is: 192.168.0.0/29
270
271 :param cidr: CIDR to be checked.
272 :type cidr: ``str``
273 :return: * *True*: If the Format is correct.
274 * *False*: If it is not correct.
275 :rtype: ``bool``
276 """
277 r = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{2}')
278 if r.match(cidr):
279 return True
280 return False
281
282 def create_network_dict(self):
283 """
284 Creates the network description dictionary.
285
286 :return: Network description.
287 :rtype: ``dict``
288 """
289 network_dict = dict()
290 # TODO do we support inactive networks?
291 network_dict["status"] = "ACTIVE"
292 if self.subnet_id is None:
293 network_dict["subnets"] = []
294 else:
295 network_dict["subnets"] = [self.subnet_id]
296 network_dict["name"] = self.name
297 network_dict["admin_state_up"] = True # TODO is it always true?
298 # TODO what should go in here
299 network_dict["tenant_id"] = "abcdefghijklmnopqrstuvwxyz123456"
300 network_dict["id"] = self.id
301 network_dict["shared"] = False # TODO is it always false?
302 return network_dict
303
304 def create_subnet_dict(self):
305 """
306 Creates the subnet description dictionary.
307
308 :return: Subnet description.
309 :rtype: ``dict``
310 """
311 subnet_dict = dict()
312 subnet_dict["name"] = self.subnet_name
313 subnet_dict["network_id"] = self.id
314 # TODO what should go in here?
315 subnet_dict["tenant_id"] = "abcdefghijklmnopqrstuvwxyz123456"
316 subnet_dict["created_at"] = self.subnet_creation_time
317 subnet_dict["dns_nameservers"] = []
318 subnet_dict["allocation_pools"] = [self.start_end_dict]
319 subnet_dict["host_routers"] = []
320 subnet_dict["gateway_ip"] = self.gateway_ip
321 subnet_dict["ip_version"] = "4"
322 subnet_dict["cidr"] = self.get_cidr()
323 subnet_dict["updated_at"] = self.subnet_update_time
324 subnet_dict["id"] = self.subnet_id
325 subnet_dict["enable_dhcp"] = False # TODO do we support DHCP?
326 return subnet_dict
327
328 def __eq__(self, other):
329 if self.name == other.name and self.subnet_name == other.subnet_name and \
330 self.gateway_ip == other.gateway_ip and \
331 self.segmentation_id == other.segmentation_id and \
332 self._cidr == other._cidr and \
333 self.start_end_dict == other.start_end_dict:
334 return True
335 return False
336
337 def __hash__(self):
338 return hash((self.name,
339 self.subnet_name,
340 self.gateway_ip,
341 self.segmentation_id,
342 self._cidr,
343 self.start_end_dict))