1 # -*- coding: utf-8 -*-
3 # Copyright 2018 Whitestack, LLC
4 # *************************************************************
6 # This file is part of OSM RO module
7 # All Rights Reserved to Whitestack, LLC
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
13 # http://www.apache.org/licenses/LICENSE-2.0
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
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact: bdiaz@whitestack.com or glavado@whitestack.com
28 from requests
.auth
import HTTPBasicAuth
30 from osm_ro_plugin
.sdnconn
import SdnConnectorBase
, SdnConnectorError
33 class OnosVpls(SdnConnectorBase
):
35 https://wiki.onosproject.org/display/ONOS/VPLS+User+Guide
38 _WIM_LOGGER
= "ro.sdn.onosvpls"
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")
48 raise SdnConnectorError("'url' must be provided")
50 if not url
.startswith("http"):
53 if not url
.endswith("/"):
56 self
.url
= url
+ "onos/v1/network/configuration"
57 self
.logger
.info("ONOS VPLS Connector Initialized.")
59 def check_credentials(self
):
61 onos_config_req
= None
64 onos_config_req
= requests
.get(
65 self
.url
, auth
=HTTPBasicAuth(self
.user
, self
.password
)
67 onos_config_req
.raise_for_status()
68 except Exception as e
:
70 status_code
= onos_config_req
.status_code
72 self
.logger
.exception("Error checking credentials: {}".format(e
))
74 raise SdnConnectorError(
75 "Error checking credentials: {}".format(e
), http_code
=status_code
78 def get_connectivity_service_status(self
, service_uuid
, conn_info
=None):
80 onos_config
= self
._get
_onos
_netconfig
()
81 vpls_config
= onos_config
.get("apps", {}).get("org.onosproject.vpls")
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
}
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
)
91 return {"sdn_status": "ERROR", "error_msg": str(e
)}
93 def _get_onos_netconfig(self
):
95 onos_config_req
= requests
.get(
96 self
.url
, auth
=HTTPBasicAuth(self
.user
, self
.password
)
98 status_code
= onos_config_req
.status_code
100 if status_code
== requests
.codes
.ok
:
101 return onos_config_req
.json()
104 "Error obtaining network config, status code: {}".format(
109 raise SdnConnectorError(
110 "Error obtaining network config status code: {}".format(
113 http_code
=status_code
,
115 except requests
.exceptions
.ConnectionError
as e
:
116 self
.logger
.info("Exception connecting to onos: %s", e
)
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
)
122 raise SdnConnectorError(
123 "Exception getting onos network config: {}".format(e
)
126 def _post_onos_netconfig(self
, onos_config
):
128 onos_config_resp
= requests
.post(
129 self
.url
, json
=onos_config
, auth
=HTTPBasicAuth(self
.user
, self
.password
)
131 status_code
= onos_config_resp
.status_code
133 if status_code
!= requests
.codes
.ok
:
135 "Error updating network config, status code: {}".format(status_code
)
138 raise SdnConnectorError(
139 "Error obtaining network config status code: {}".format(
142 http_code
=status_code
,
144 except requests
.exceptions
.ConnectionError
as e
:
145 self
.logger
.info("Exception connecting to onos: %s", e
)
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
)
151 raise SdnConnectorError(
152 "Exception posting onos network config: {}".format(e
)
155 def create_connectivity_service(self
, service_type
, connection_points
, **kwargs
):
157 "create_connectivity_service, service_type: {}, connection_points: {}".format(
158 service_type
, connection_points
162 if service_type
.lower() == "etree":
163 raise SdnConnectorError(
164 "Only ELINE/ELAN network type is supported by ONOS VPLS."
167 # FIXME ¿must check number of connection_points?
168 service_uuid
= str(uuid
.uuid4())
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
)
176 # Create missing interfaces, append to created_items if returned, append_port_to_onos_config
177 # returns null if it was already created
180 for port
in connection_points
:
181 created_ifz
= self
._append
_port
_to
_onos
_config
(port
, onos_config
)
183 created_items
.append(created_ifz
[1])
185 self
._post
_onos
_netconfig
(onos_config
)
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
]
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"] = {
197 for vpls
in onos_config
["apps"]["org.onosproject.vpls"]["vpls"][
200 if vpls
["name"] == service_uuid
:
201 raise SdnConnectorError(
202 "Network {} already exists.".format(service_uuid
)
205 onos_config
["apps"]["org.onosproject.vpls"]["vpls"]["vplsList"].append(
207 "name": service_uuid
,
208 "interfaces": interfaces
,
209 "encapsulation": encapsulation
,
212 self
._pop
_last
_update
_time
(onos_config
)
214 onos_config
["apps"] = {
215 "org.onosproject.vpls": {
219 "name": service_uuid
,
220 "interfaces": interfaces
,
221 "encapsulation": encapsulation
,
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
)
232 "created connectivity_service, service_uuid: {}, created_items: {}".format(
233 service_uuid
, created_items
237 return service_uuid
, {"interfaces": created_items
}
238 except Exception as e
:
239 self
.logger
.error("Exception add connection_service: %s", e
)
241 # try to rollback push original config
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
)
248 if isinstance(e
, SdnConnectorError
):
251 raise SdnConnectorError(
252 "Exception create_connectivity_service: {}".format(e
)
255 def _get_encapsulation(self
, connection_points
):
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
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"
270 def edit_connectivity_service(
271 self
, service_uuid
, conn_info
=None, connection_points
=None, **kwargs
274 "edit connectivity service, service_uuid: {}, conn_info: {}, "
275 "connection points: {} ".format(service_uuid
, conn_info
, connection_points
)
278 conn_info
= conn_info
or {}
279 created_ifs
= conn_info
.get("interfaces", [])
281 # Obtain current configuration
282 onos_config_orig
= self
._get
_onos
_netconfig
()
283 onos_config
= copy
.deepcopy(onos_config_orig
)
285 # get current service data and check if it does not exists
287 onos_config
.get("apps", {})
288 .get("org.onosproject.vpls", {})
292 if vpls
["name"] == service_uuid
:
293 self
.logger
.debug("service exists")
294 curr_interfaces
= vpls
.get("interfaces", [])
295 curr_encapsulation
= vpls
.get("encapsulation")
298 raise SdnConnectorError(
299 "service uuid: {} does not exist".format(service_uuid
)
302 self
.logger
.debug("current interfaces: {}".format(curr_interfaces
))
303 self
.logger
.debug("current encapsulation: {}".format(curr_encapsulation
))
305 # new interfaces names
306 new_interfaces
= [port
["service_endpoint_id"] for port
in connection_points
]
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
))
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"]
323 new_port_name
= "of:{}/{}".format(
324 port
["service_endpoint_encapsulation_info"]["switch_dpid"],
325 port
["service_endpoint_encapsulation_info"]["switch_port"],
327 new_vlan
= port
["service_endpoint_encapsulation_info"]["vlan"]
329 if curr_port_name
!= new_port_name
or curr_vlan
!= new_vlan
:
331 "TODO: must update data interface: {}".format(
332 port
["service_endpoint_id"]
335 ifs_delete
.append(port
["service_endpoint_id"])
336 ifs_add
.append(port
["service_endpoint_id"])
338 new_encapsulation
= self
._get
_encapsulation
(connection_points
)
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
344 for port
in onos_config
["ports"].values():
345 for port_interface
in port
["interfaces"]:
346 interface_name
= port_interface
["name"]
348 "interface name: {}".format(port_interface
["name"])
352 interface_name
in ifs_delete
353 and interface_name
in created_ifs
356 "delete interface name: {}".format(interface_name
)
358 port
["interfaces"].remove(port_interface
)
359 created_ifs
.remove(interface_name
)
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
)
366 created_ifs
.append(created_ifz
[1])
368 self
._pop
_last
_update
_time
(onos_config
)
369 self
._post
_onos
_netconfig
(onos_config
)
372 "onos config after updating interfaces: {}".format(onos_config
)
375 "created_ifs after updating interfaces: {}".format(created_ifs
)
378 # Update interfaces list in vpls service
380 onos_config
.get("apps", {})
381 .get("org.onosproject.vpls", {})
385 if vpls
["name"] == service_uuid
:
386 vpls
["interfaces"] = new_interfaces
387 vpls
["encapsulation"] = new_encapsulation
389 self
._pop
_last
_update
_time
(onos_config
)
390 self
._post
_onos
_netconfig
(onos_config
)
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
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
)
401 if isinstance(e
, SdnConnectorError
):
404 raise SdnConnectorError(
405 "Exception create_connectivity_service: {}".format(e
)
408 def delete_connectivity_service(self
, service_uuid
, conn_info
=None):
409 self
.logger
.debug("delete_connectivity_service uuid: {}".format(service_uuid
))
411 conn_info
= conn_info
or {}
412 created_ifs
= conn_info
.get("interfaces", [])
413 # Obtain current config
414 onos_config
= self
._get
_onos
_netconfig
()
417 # Removes ports used by network from onos config
419 onos_config
.get("apps", {})
420 .get("org.onosproject.vpls", {})
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
:
433 "Delete ifz: {}".format(
434 port_interface
["name"]
437 port
["interfaces"].remove(port_interface
)
438 onos_config
["apps"]["org.onosproject.vpls"]["vpls"][
443 raise SdnConnectorError(
444 "service uuid: {} does not exist".format(service_uuid
)
447 self
._pop
_last
_update
_time
(onos_config
)
448 self
._post
_onos
_netconfig
(onos_config
)
450 "deleted connectivity service uuid: {}".format(service_uuid
)
452 except SdnConnectorError
:
454 except Exception as e
:
456 "Exception delete connection_service: %s", e
, exc_info
=True
459 raise SdnConnectorError(
460 "Exception delete connectivity service: {}".format(str(e
))
463 def _pop_last_update_time(self
, onos_config
):
465 Needed before post when there are already configured vpls services to apply changes
467 onos_config
["apps"]["org.onosproject.vpls"]["vpls"].pop("lastUpdateTime", None)
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"]
475 def _append_port_to_onos_config(self
, port
, onos_config
):
477 port_name
= "of:{}/{}".format(
478 port
["service_endpoint_encapsulation_info"]["switch_dpid"],
479 port
["service_endpoint_encapsulation_info"]["switch_port"],
481 interface_config
= {"name": port
["service_endpoint_id"]}
484 "vlan" in port
["service_endpoint_encapsulation_info"]
485 and port
["service_endpoint_encapsulation_info"]["vlan"]
487 interface_config
["vlan"] = port
["service_endpoint_encapsulation_info"][
492 port_name
in onos_config
["ports"]
493 and "interfaces" in onos_config
["ports"][port_name
]
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)
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"])
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"])
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"
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"
529 "service_endpoint_id": "switch1:ifz1",
530 "service_endpoint_encapsulation_type": "dot1q",
531 "service_endpoint_encapsulation_info": {
532 "switch_dpid": "0000000000000011",
538 "service_endpoint_id": "switch3:ifz1",
539 "service_endpoint_encapsulation_type": "dot1q",
540 "service_endpoint_encapsulation_info": {
541 "switch_dpid": "0000000000000031",
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)
552 conn_info
= {"interfaces": ["switch1:ifz1", "switch3:ifz1"]}
553 # onos_vpls.delete_connectivity_service("70248a41-11cb-44f3-9039-c41387394a30", conn_info)
556 "service_endpoint_id": "switch1:ifz1",
557 "service_endpoint_encapsulation_type": "dot1q",
558 "service_endpoint_encapsulation_info": {
559 "switch_dpid": "0000000000000011",
565 "service_endpoint_id": "switch1:ifz3",
566 "service_endpoint_encapsulation_type": "dot1q",
567 "service_endpoint_encapsulation_info": {
568 "switch_dpid": "0000000000000011",
574 "service_endpoint_id": "switch2:ifz2",
575 "service_endpoint_encapsulation_type": "dot1q",
576 "service_endpoint_encapsulation_info": {
577 "switch_dpid": "0000000000000022",
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)
587 service_status
= onos_vpls
.get_connectivity_service_status(
588 "c65d88be-73aa-4933-927d-57ec6bee6b41", conn_info
590 print("service status")
591 print(service_status
)