1c68fe77ba4d440f78ad6776169a020c80c37ca2
[osm/RO.git] / RO-SDN-onos_vpls / osm_rosdn_onos_vpls / sdn_assist_onos_vpls.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018 Whitestack, LLC
4 # *************************************************************
5
6 # This file is part of OSM RO module
7 # All Rights Reserved to Whitestack, LLC
8
9 # Licensed under the Apache License, Version 2.0 (the "License"); you may
10 # not use this file except in compliance with the License. You may obtain
11 # a copy of the License at
12
13 # http://www.apache.org/licenses/LICENSE-2.0
14
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 # License for the specific language governing permissions and limitations
19 # under the License.
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact: bdiaz@whitestack.com or glavado@whitestack.com
22 ##
23 import logging
24 import uuid
25 import copy
26
27 import requests
28 from requests.auth import HTTPBasicAuth
29
30 from osm_ro_plugin.sdnconn import SdnConnectorBase, SdnConnectorError
31
32
33 class OnosVpls(SdnConnectorBase):
34 """
35 https://wiki.onosproject.org/display/ONOS/VPLS+User+Guide
36 """
37
38 _WIM_LOGGER = "ro.sdn.onosvpls"
39
40 def __init__(self, wim, wim_account, config=None, logger=None):
41 self.logger = logger or logging.getLogger(self._WIM_LOGGER)
42 super().__init__(wim, wim_account, config, logger)
43 self.user = wim_account.get("user")
44 self.password = wim_account.get("password")
45 url = wim.get("wim_url")
46
47 if not url:
48 raise SdnConnectorError("'url' must be provided")
49
50 if not url.startswith("http"):
51 url = "http://" + url
52
53 if not url.endswith("/"):
54 url = url + "/"
55
56 self.url = url + "onos/v1/network/configuration"
57 self.logger.info("ONOS VPLS Connector Initialized.")
58
59 def check_credentials(self):
60 status_code = 503
61 onos_config_req = None
62
63 try:
64 onos_config_req = requests.get(
65 self.url, auth=HTTPBasicAuth(self.user, self.password)
66 )
67 onos_config_req.raise_for_status()
68 except Exception as e:
69 if onos_config_req:
70 status_code = onos_config_req.status_code
71
72 self.logger.exception("Error checking credentials: {}".format(e))
73
74 raise SdnConnectorError(
75 "Error checking credentials: {}".format(e), http_code=status_code
76 )
77
78 def get_connectivity_service_status(self, service_uuid, conn_info=None):
79 try:
80 onos_config = self._get_onos_netconfig()
81 vpls_config = onos_config.get("apps", {}).get("org.onosproject.vpls")
82 if vpls_config:
83 for vpls in vpls_config.get("vpls", {}).get("vplsList"):
84 if vpls.get("name") == service_uuid:
85 return {"sdn_status": "ACTIVE", "sdn_info": vpls}
86
87 return {"sdn_status": "ERROR", "sdn_info": "not found"}
88 except Exception as e:
89 self.logger.error("Exception getting connectivity service info: %s", e)
90
91 return {"sdn_status": "ERROR", "error_msg": str(e)}
92
93 def _get_onos_netconfig(self):
94 try:
95 onos_config_req = requests.get(
96 self.url, auth=HTTPBasicAuth(self.user, self.password)
97 )
98 status_code = onos_config_req.status_code
99
100 if status_code == requests.codes.ok:
101 return onos_config_req.json()
102 else:
103 self.logger.info(
104 "Error obtaining network config, status code: {}".format(
105 status_code
106 )
107 )
108
109 raise SdnConnectorError(
110 "Error obtaining network config status code: {}".format(
111 status_code
112 ),
113 http_code=status_code,
114 )
115 except requests.exceptions.ConnectionError as e:
116 self.logger.info("Exception connecting to onos: %s", e)
117
118 raise SdnConnectorError("Error connecting to onos: {}".format(e))
119 except Exception as e:
120 self.logger.error("Exception getting onos network config: %s", e)
121
122 raise SdnConnectorError(
123 "Exception getting onos network config: {}".format(e)
124 )
125
126 def _post_onos_netconfig(self, onos_config):
127 try:
128 onos_config_resp = requests.post(
129 self.url, json=onos_config, auth=HTTPBasicAuth(self.user, self.password)
130 )
131 status_code = onos_config_resp.status_code
132
133 if status_code != requests.codes.ok:
134 self.logger.info(
135 "Error updating network config, status code: {}".format(status_code)
136 )
137
138 raise SdnConnectorError(
139 "Error obtaining network config status code: {}".format(
140 status_code
141 ),
142 http_code=status_code,
143 )
144 except requests.exceptions.ConnectionError as e:
145 self.logger.info("Exception connecting to onos: %s", e)
146
147 raise SdnConnectorError("Error connecting to onos: {}".format(e))
148 except Exception as e:
149 self.logger.info("Exception posting onos network config: %s", e)
150
151 raise SdnConnectorError(
152 "Exception posting onos network config: {}".format(e)
153 )
154
155 def create_connectivity_service(self, service_type, connection_points, **kwargs):
156 self.logger.debug(
157 "create_connectivity_service, service_type: {}, connection_points: {}".format(
158 service_type, connection_points
159 )
160 )
161
162 if service_type.lower() == "etree":
163 raise SdnConnectorError(
164 "Only ELINE/ELAN network type is supported by ONOS VPLS."
165 )
166
167 # FIXME ¿must check number of connection_points?
168 service_uuid = str(uuid.uuid4())
169
170 # Obtain current configuration
171 onos_config_orig = self._get_onos_netconfig()
172 # self.logger.debug("onos config: %s", onos_config_orig)
173 onos_config = copy.deepcopy(onos_config_orig)
174
175 try:
176 # Create missing interfaces, append to created_items if returned, append_port_to_onos_config
177 # returns null if it was already created
178 created_items = []
179
180 for port in connection_points:
181 created_ifz = self._append_port_to_onos_config(port, onos_config)
182 if created_ifz:
183 created_items.append(created_ifz[1])
184
185 self._post_onos_netconfig(onos_config)
186
187 # Add vpls service to config
188 encapsulation = self._get_encapsulation(connection_points)
189 interfaces = [port.get("service_endpoint_id") for port in connection_points]
190
191 if "org.onosproject.vpls" in onos_config["apps"]:
192 if "vpls" not in onos_config["apps"]["org.onosproject.vpls"]:
193 onos_config["apps"]["org.onosproject.vpls"]["vpls"] = {
194 "vplsList": []
195 }
196
197 for vpls in onos_config["apps"]["org.onosproject.vpls"]["vpls"][
198 "vplsList"
199 ]:
200 if vpls["name"] == service_uuid:
201 raise SdnConnectorError(
202 "Network {} already exists.".format(service_uuid)
203 )
204
205 onos_config["apps"]["org.onosproject.vpls"]["vpls"]["vplsList"].append(
206 {
207 "name": service_uuid,
208 "interfaces": interfaces,
209 "encapsulation": encapsulation,
210 }
211 )
212 self._pop_last_update_time(onos_config)
213 else:
214 onos_config["apps"] = {
215 "org.onosproject.vpls": {
216 "vpls": {
217 "vplsList": [
218 {
219 "name": service_uuid,
220 "interfaces": interfaces,
221 "encapsulation": encapsulation,
222 }
223 ]
224 }
225 }
226 }
227 # self.logger.debug("original config: %s", onos_config_orig)
228 # self.logger.debug("original config: %s", onos_config)
229 self._post_onos_netconfig(onos_config)
230
231 self.logger.debug(
232 "created connectivity_service, service_uuid: {}, created_items: {}".format(
233 service_uuid, created_items
234 )
235 )
236
237 return service_uuid, {"interfaces": created_items}
238 except Exception as e:
239 self.logger.error("Exception add connection_service: %s", e)
240
241 # try to rollback push original config
242 try:
243 self._post_onos_netconfig(onos_config_orig)
244 except Exception as e:
245 self.logger.error("Exception rolling back to original config: %s", e)
246
247 # raise exception
248 if isinstance(e, SdnConnectorError):
249 raise
250 else:
251 raise SdnConnectorError(
252 "Exception create_connectivity_service: {}".format(e)
253 )
254
255 def _get_encapsulation(self, connection_points):
256 """
257 Obtains encapsulation for the vpls service from the connection_points
258 FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is
259 defined at the service level so only one can be assigned
260 """
261 # check if encapsulation is vlan, check just one connection point
262 encapsulation = "NONE"
263 for connection_point in connection_points:
264 if connection_point.get("service_endpoint_encapsulation_type") == "dot1q":
265 encapsulation = "VLAN"
266 break
267
268 return encapsulation
269
270 def edit_connectivity_service(
271 self, service_uuid, conn_info=None, connection_points=None, **kwargs
272 ):
273 self.logger.debug(
274 "edit connectivity service, service_uuid: {}, conn_info: {}, "
275 "connection points: {} ".format(service_uuid, conn_info, connection_points)
276 )
277
278 conn_info = conn_info or {}
279 created_ifs = conn_info.get("interfaces", [])
280
281 # Obtain current configuration
282 onos_config_orig = self._get_onos_netconfig()
283 onos_config = copy.deepcopy(onos_config_orig)
284
285 # get current service data and check if it does not exists
286 for vpls in (
287 onos_config.get("apps", {})
288 .get("org.onosproject.vpls", {})
289 .get("vpls", {})
290 .get("vplsList", {})
291 ):
292 if vpls["name"] == service_uuid:
293 self.logger.debug("service exists")
294 curr_interfaces = vpls.get("interfaces", [])
295 curr_encapsulation = vpls.get("encapsulation")
296 break
297 else:
298 raise SdnConnectorError(
299 "service uuid: {} does not exist".format(service_uuid)
300 )
301
302 self.logger.debug("current interfaces: {}".format(curr_interfaces))
303 self.logger.debug("current encapsulation: {}".format(curr_encapsulation))
304
305 # new interfaces names
306 new_interfaces = [port["service_endpoint_id"] for port in connection_points]
307
308 # obtain interfaces to delete, list will contain port
309 ifs_delete = list(set(curr_interfaces) - set(new_interfaces))
310 ifs_add = list(set(new_interfaces) - set(curr_interfaces))
311 self.logger.debug("interfaces to delete: {}".format(ifs_delete))
312 self.logger.debug("interfaces to add: {}".format(ifs_add))
313
314 # check if some data of the interfaces that already existed has changed
315 # in that case delete it and add it again
316 ifs_remain = list(set(new_interfaces) & set(curr_interfaces))
317 for port in connection_points:
318 if port["service_endpoint_id"] in ifs_remain:
319 # check if there are some changes
320 curr_port_name, curr_vlan = self._get_current_port_data(
321 onos_config, port["service_endpoint_id"]
322 )
323 new_port_name = "of:{}/{}".format(
324 port["service_endpoint_encapsulation_info"]["switch_dpid"],
325 port["service_endpoint_encapsulation_info"]["switch_port"],
326 )
327 new_vlan = port["service_endpoint_encapsulation_info"]["vlan"]
328
329 if curr_port_name != new_port_name or curr_vlan != new_vlan:
330 self.logger.debug(
331 "TODO: must update data interface: {}".format(
332 port["service_endpoint_id"]
333 )
334 )
335 ifs_delete.append(port["service_endpoint_id"])
336 ifs_add.append(port["service_endpoint_id"])
337
338 new_encapsulation = self._get_encapsulation(connection_points)
339
340 try:
341 # Delete interfaces, only will delete interfaces that are in provided conn_info
342 # because these are the ones that have been created for this service
343 if ifs_delete:
344 for port in onos_config["ports"].values():
345 for port_interface in port["interfaces"]:
346 interface_name = port_interface["name"]
347 self.logger.debug(
348 "interface name: {}".format(port_interface["name"])
349 )
350
351 if (
352 interface_name in ifs_delete
353 and interface_name in created_ifs
354 ):
355 self.logger.debug(
356 "delete interface name: {}".format(interface_name)
357 )
358 port["interfaces"].remove(port_interface)
359 created_ifs.remove(interface_name)
360
361 # Add new interfaces
362 for port in connection_points:
363 if port["service_endpoint_id"] in ifs_add:
364 created_ifz = self._append_port_to_onos_config(port, onos_config)
365 if created_ifz:
366 created_ifs.append(created_ifz[1])
367
368 self._pop_last_update_time(onos_config)
369 self._post_onos_netconfig(onos_config)
370
371 self.logger.debug(
372 "onos config after updating interfaces: {}".format(onos_config)
373 )
374 self.logger.debug(
375 "created_ifs after updating interfaces: {}".format(created_ifs)
376 )
377
378 # Update interfaces list in vpls service
379 for vpls in (
380 onos_config.get("apps", {})
381 .get("org.onosproject.vpls", {})
382 .get("vpls", {})
383 .get("vplsList", {})
384 ):
385 if vpls["name"] == service_uuid:
386 vpls["interfaces"] = new_interfaces
387 vpls["encapsulation"] = new_encapsulation
388
389 self._pop_last_update_time(onos_config)
390 self._post_onos_netconfig(onos_config)
391
392 return {"interfaces": created_ifs}
393 except Exception as e:
394 self.logger.error("Exception add connection_service: %s", e)
395 # try to rollback push original config
396 try:
397 self._post_onos_netconfig(onos_config_orig)
398 except Exception as e2:
399 self.logger.error("Exception rolling back to original config: %s", e2)
400 # raise exception
401 if isinstance(e, SdnConnectorError):
402 raise
403 else:
404 raise SdnConnectorError(
405 "Exception create_connectivity_service: {}".format(e)
406 )
407
408 def delete_connectivity_service(self, service_uuid, conn_info=None):
409 self.logger.debug("delete_connectivity_service uuid: {}".format(service_uuid))
410
411 conn_info = conn_info or {}
412 created_ifs = conn_info.get("interfaces", [])
413 # Obtain current config
414 onos_config = self._get_onos_netconfig()
415
416 try:
417 # Removes ports used by network from onos config
418 for vpls in (
419 onos_config.get("apps", {})
420 .get("org.onosproject.vpls", {})
421 .get("vpls", {})
422 .get("vplsList", {})
423 ):
424 if vpls["name"] == service_uuid:
425 # iterate interfaces to check if must delete them
426 for interface in vpls["interfaces"]:
427 for port in onos_config["ports"].values():
428 for port_interface in port["interfaces"]:
429 if port_interface["name"] == interface:
430 # Delete only created ifzs
431 if port_interface["name"] in created_ifs:
432 self.logger.debug(
433 "Delete ifz: {}".format(
434 port_interface["name"]
435 )
436 )
437 port["interfaces"].remove(port_interface)
438 onos_config["apps"]["org.onosproject.vpls"]["vpls"][
439 "vplsList"
440 ].remove(vpls)
441 break
442 else:
443 raise SdnConnectorError(
444 "service uuid: {} does not exist".format(service_uuid)
445 )
446
447 self._pop_last_update_time(onos_config)
448 self._post_onos_netconfig(onos_config)
449 self.logger.debug(
450 "deleted connectivity service uuid: {}".format(service_uuid)
451 )
452 except SdnConnectorError:
453 raise
454 except Exception as e:
455 self.logger.error(
456 "Exception delete connection_service: %s", e, exc_info=True
457 )
458
459 raise SdnConnectorError(
460 "Exception delete connectivity service: {}".format(str(e))
461 )
462
463 def _pop_last_update_time(self, onos_config):
464 """
465 Needed before post when there are already configured vpls services to apply changes
466 """
467 onos_config["apps"]["org.onosproject.vpls"]["vpls"].pop("lastUpdateTime", None)
468
469 def _get_current_port_data(self, onos_config, interface_name):
470 for port_name, port in onos_config["ports"].items():
471 for port_interface in port["interfaces"]:
472 if port_interface["name"] == interface_name:
473 return port_name, port_interface["vlan"]
474
475 def _append_port_to_onos_config(self, port, onos_config):
476 created_item = None
477 port_name = "of:{}/{}".format(
478 port["service_endpoint_encapsulation_info"]["switch_dpid"],
479 port["service_endpoint_encapsulation_info"]["switch_port"],
480 )
481 interface_config = {"name": port["service_endpoint_id"]}
482
483 if (
484 "vlan" in port["service_endpoint_encapsulation_info"]
485 and port["service_endpoint_encapsulation_info"]["vlan"]
486 ):
487 interface_config["vlan"] = port["service_endpoint_encapsulation_info"][
488 "vlan"
489 ]
490
491 if (
492 port_name in onos_config["ports"]
493 and "interfaces" in onos_config["ports"][port_name]
494 ):
495 for interface in onos_config["ports"][port_name]["interfaces"]:
496 if interface["name"] == port["service_endpoint_id"]:
497 # self.logger.debug("interface with same name and port exits")
498 # interface already exists TODO ¿check vlan? ¿delete and recreate?
499 # by the moment use and do not touch
500 # onos_config['ports'][port_name]['interfaces'].remove(interface)
501 break
502 else:
503 # self.logger.debug("port with same name exits but not interface")
504 onos_config["ports"][port_name]["interfaces"].append(interface_config)
505 created_item = (port_name, port["service_endpoint_id"])
506 else:
507 # self.logger.debug("create port and interface")
508 onos_config["ports"][port_name] = {"interfaces": [interface_config]}
509 created_item = (port_name, port["service_endpoint_id"])
510
511 return created_item
512
513
514 if __name__ == "__main__":
515 logger = logging.getLogger("ro.sdn.onos_vpls")
516 logging.basicConfig()
517 logger.setLevel(getattr(logging, "DEBUG"))
518 # wim_url = "http://10.95.172.251:8181"
519 wim_url = "http://192.168.56.106:8181"
520 user = "karaf"
521 password = "karaf"
522 wim = {"wim_url": wim_url}
523 wim_account = {"user": user, "password": password}
524 onos_vpls = OnosVpls(wim=wim, wim_account=wim_account, logger=logger)
525 # conn_service = onos_vpls.get_connectivity_service_status("4e1f4c8a-a874-425d-a9b5-955cb77178f8")
526 # print(conn_service)
527 service_type = "ELAN"
528 conn_point_0 = {
529 "service_endpoint_id": "switch1:ifz1",
530 "service_endpoint_encapsulation_type": "dot1q",
531 "service_endpoint_encapsulation_info": {
532 "switch_dpid": "0000000000000011",
533 "switch_port": "1",
534 "vlan": "600",
535 },
536 }
537 conn_point_1 = {
538 "service_endpoint_id": "switch3:ifz1",
539 "service_endpoint_encapsulation_type": "dot1q",
540 "service_endpoint_encapsulation_info": {
541 "switch_dpid": "0000000000000031",
542 "switch_port": "3",
543 "vlan": "600",
544 },
545 }
546 connection_points = [conn_point_0, conn_point_1]
547 # service_uuid, conn_info = onos_vpls.create_connectivity_service(service_type, connection_points)
548 # print(service_uuid)
549 # print(conn_info)
550
551 # conn_info = None
552 conn_info = {"interfaces": ["switch1:ifz1", "switch3:ifz1"]}
553 # onos_vpls.delete_connectivity_service("70248a41-11cb-44f3-9039-c41387394a30", conn_info)
554
555 conn_point_0 = {
556 "service_endpoint_id": "switch1:ifz1",
557 "service_endpoint_encapsulation_type": "dot1q",
558 "service_endpoint_encapsulation_info": {
559 "switch_dpid": "0000000000000011",
560 "switch_port": "1",
561 "vlan": "500",
562 },
563 }
564 conn_point_2 = {
565 "service_endpoint_id": "switch1:ifz3",
566 "service_endpoint_encapsulation_type": "dot1q",
567 "service_endpoint_encapsulation_info": {
568 "switch_dpid": "0000000000000011",
569 "switch_port": "3",
570 "vlan": "500",
571 },
572 }
573 conn_point_3 = {
574 "service_endpoint_id": "switch2:ifz2",
575 "service_endpoint_encapsulation_type": "dot1q",
576 "service_endpoint_encapsulation_info": {
577 "switch_dpid": "0000000000000022",
578 "switch_port": "2",
579 "vlan": "500",
580 },
581 }
582 connection_points_2 = [conn_point_0, conn_point_3]
583 # conn_info = onos_vpls.edit_connectivity_service("c65d88be-73aa-4933-927d-57ec6bee6b41",
584 # conn_info, connection_points_2)
585 # print(conn_info)
586
587 service_status = onos_vpls.get_connectivity_service_status(
588 "c65d88be-73aa-4933-927d-57ec6bee6b41", conn_info
589 )
590 print("service status")
591 print(service_status)