Change-Id: Ifc06fa889fa0625c0ac32738f05dc9fca26ee42a
Signed-off-by: tierno <alfonso.tiernosepulveda@telefonica.com>
import requests
import json
import copy
import requests
import json
import copy
from time import time
from requests.exceptions import ConnectionError
from time import time
from requests.exceptions import ConnectionError
class HttpException(Exception):
pass
class HttpException(Exception):
pass
def _get_token(self, headers):
if self.auth_url:
def _get_token(self, headers):
if self.auth_url:
- self._logger.debug('Current Token:'.format(self.token))
+ self._logger.debug('Current Token: {}'.format(self.token))
auth_url = self.auth_url + 'auth/tokens'
if self.token is None or self._token_expired():
if not self.auth_url:
self.token = ""
resp = self._request_noauth(url=auth_url, op="POST", headers=headers,
auth_url = self.auth_url + 'auth/tokens'
if self.token is None or self._token_expired():
if not self.auth_url:
self.token = ""
resp = self._request_noauth(url=auth_url, op="POST", headers=headers,
self.token = resp.headers.get('x-subject-token')
self.last_token_time = time.time()
self.token = resp.headers.get('x-subject-token')
self.last_token_time = time.time()
- self._logger.debug('Obtained token: '.format(self.token))
+ self._logger.debug('Obtained token: {}'.format(self.token))
headers = http_headers.copy()
# Get authorization (include authentication headers)
headers = http_headers.copy()
# Get authorization (include authentication headers)
- # todo - aƱadir token de nuevo
- #token = self._get_token(headers)
+ # TODO add again token
+ # token = self._get_token(headers)
token = None
if token:
headers['X-Auth-Token'] = token
token = None
if token:
headers['X-Auth-Token'] = token
# Execute operation
try:
self._logger.info("Request METHOD: {} URL: {}".format(op, url))
# Execute operation
try:
self._logger.info("Request METHOD: {} URL: {}".format(op, url))
resp = self._http_get(url, headers, query_params=data)
resp = self._http_get(url, headers, query_params=data)
resp = self._http_post(url, headers, json_data=data)
resp = self._http_post(url, headers, json_data=data)
- elif (op == "POST_HEADERS"):
+ elif op == "POST_HEADERS":
resp = self._http_post_headers(url, headers, json_data=data)
resp = self._http_post_headers(url, headers, json_data=data)
resp = self._http_delete(url, headers, json_data=data)
else:
raise HttpException("Unsupported operation: {}".format(op))
resp = self._http_delete(url, headers, json_data=data)
else:
raise HttpException("Unsupported operation: {}".format(op))
def _http_delete(self, url, headers, json_data=None):
return requests.delete(url, json=json_data, headers=headers)
def _http_delete(self, url, headers, json_data=None):
return requests.delete(url, json=json_data, headers=headers)
from osm_ro.wim.sdnconn import SdnConnectorError
from osm_rosdn_juniper_contrail.rest_lib import ContrailHttp
from osm_rosdn_juniper_contrail.rest_lib import NotFound
from osm_ro.wim.sdnconn import SdnConnectorError
from osm_rosdn_juniper_contrail.rest_lib import ContrailHttp
from osm_rosdn_juniper_contrail.rest_lib import NotFound
-from osm_rosdn_juniper_contrail.rest_lib import DuplicateFound
-from osm_rosdn_juniper_contrail.rest_lib import HttpException
+# from osm_rosdn_juniper_contrail.rest_lib import DuplicateFound
+# from osm_rosdn_juniper_contrail.rest_lib import HttpException
+
class UnderlayApi:
""" Class with CRUD operations for the underlay API """
class UnderlayApi:
""" Class with CRUD operations for the underlay API """
self.logger.debug("Config parameters for the underlay controller: auth_url: {}, project: {},"
" domain: {}, user: {}, password: {}".format(self.auth_url, self.project,
self.logger.debug("Config parameters for the underlay controller: auth_url: {}, project: {},"
" domain: {}, user: {}, password: {}".format(self.auth_url, self.project,
- self.domain, self.user, self.password))
+ self.domain, self.user, self.password))
auth_dict = {}
auth_dict['auth'] = {}
auth_dict = {}
auth_dict['auth'] = {}
"operation": "DELETE"
}
endpoint = self.controller_url + "ref-update"
"operation": "DELETE"
}
endpoint = self.controller_url + "ref-update"
- resp = self.http.post_cmd(url=endpoint,
- headers=self.http_header,
- post_fields_dict=payload)
+ resp = self.http.post_cmd(url=endpoint, headers=self.http_header, post_fields_dict=payload)
return resp
# Aux methods to avoid code duplication of name conventions
return resp
# Aux methods to avoid code duplication of name conventions
return self.get_by_uuid(self.controller_url, "virtual-port-group", vpg_id)
def get_vpg_by_name(self, vpg_name):
return self.get_by_uuid(self.controller_url, "virtual-port-group", vpg_id)
def get_vpg_by_name(self, vpg_name):
- fq_name = [
- "default-global-system-config",
- self.fabric,
- vpg_name
- ]
+ fq_name = ["default-global-system-config",
+ self.fabric,
+ vpg_name
+ ]
return self.get_by_fq_name("virtual-port-group", fq_name)
def delete_vpg(self, vpg_id):
return self.get_by_fq_name("virtual-port-group", fq_name)
def delete_vpg(self, vpg_id):
def unref_vmi_vpg(self, vpg_id, vmi_id, vmi_fq_name):
self.delete_ref("virtual-port-group", vpg_id, "virtual-machine-interface", vmi_id, vmi_fq_name)
def unref_vmi_vpg(self, vpg_id, vmi_id, vmi_fq_name):
self.delete_ref("virtual-port-group", vpg_id, "virtual-machine-interface", vmi_id, vmi_fq_name)
import yaml
import random
from osm_ro.wim.sdnconn import SdnConnectorBase, SdnConnectorError
import yaml
import random
from osm_ro.wim.sdnconn import SdnConnectorBase, SdnConnectorError
-from osm_rosdn_juniper_contrail.rest_lib import ContrailHttp
-from osm_rosdn_juniper_contrail.rest_lib import NotFound
+# from osm_rosdn_juniper_contrail.rest_lib import ContrailHttp
+# from osm_rosdn_juniper_contrail.rest_lib import NotFound
from osm_rosdn_juniper_contrail.rest_lib import DuplicateFound
from osm_rosdn_juniper_contrail.rest_lib import HttpException
from osm_rosdn_juniper_contrail.rest_lib import DuplicateFound
from osm_rosdn_juniper_contrail.rest_lib import HttpException
from osm_rosdn_juniper_contrail.sdn_api import UnderlayApi
from osm_rosdn_juniper_contrail.sdn_api import UnderlayApi
whose API details can be found in these links:
- https://github.com/tonyliu0592/contrail/wiki/API-Configuration-REST
whose API details can be found in these links:
- https://github.com/tonyliu0592/contrail/wiki/API-Configuration-REST
- - https://www.juniper.net/documentation/en_US/contrail19/information-products/pathway-pages/api-guide-1910/tutorial_with_rest.html
+ - https://www.juniper.net/documentation/en_US/contrail19/information-products/pathway-pages/api-guide-1910/
+ tutorial_with_rest.html
- https://github.com/tonyliu0592/contrail-toolbox/blob/master/sriov/sriov
"""
_WIM_LOGGER = "openmano.sdnconn.junipercontrail"
- https://github.com/tonyliu0592/contrail-toolbox/blob/master/sriov/sriov
"""
_WIM_LOGGER = "openmano.sdnconn.junipercontrail"
self.user = wim_account.get("user")
self.password = wim_account.get("password")
self.user = wim_account.get("user")
self.password = wim_account.get("password")
- url = wim.get("wim_url") # underlay url
+ url = wim.get("wim_url") # underlay url
auth_url = None
self.project = None
self.domain = None
auth_url = None
self.project = None
self.domain = None
for vlanID_range in self.vni_range:
try:
for vlanID_range in self.vni_range:
try:
- start_vni , end_vni = map(int, vlanID_range.replace(" ", "").split("-"))
+ start_vni, end_vni = map(int, vlanID_range.replace(" ", "").split("-"))
for i in range(start_vni, end_vni + 1):
vni = random.randrange(start_vni, end_vni, 1)
if vni not in self.used_vni:
for i in range(start_vni, end_vni + 1):
vni = random.randrange(start_vni, end_vni, 1)
if vni not in self.used_vni:
except Exception as exp:
raise SdnConnectorError("Exception {} occurred while searching a free VNI.".format(exp))
else:
except Exception as exp:
raise SdnConnectorError("Exception {} occurred while searching a free VNI.".format(exp))
else:
- raise SdnConnectorError("Unable to create the virtual network."\
- " All VNI in VNI range {} are in use.".format(self.vni_range))
+ raise SdnConnectorError("Unable to create the virtual network."
+ " All VNI in VNI range {} are in use.".format(self.vni_range))
# Aux functions for testing
def get_url(self):
return self.url
# Aux functions for testing
def get_url(self):
return self.url
else:
num_vmis = len(vmi_list)
for vmi in vmi_list:
else:
num_vmis = len(vmi_list)
for vmi in vmi_list:
fqdn = vmi.get("to")
# check by name
if fqdn[2] == vmi_name:
fqdn = vmi.get("to")
# check by name
if fqdn[2] == vmi_name:
self.logger.error('Exception getting connectivity service info: %s', e, exc_info=True)
return {'sdn_status': 'ERROR', 'error_msg': str(e)}
self.logger.error('Exception getting connectivity service info: %s', e, exc_info=True)
return {'sdn_status': 'ERROR', 'error_msg': str(e)}
def create_connectivity_service(self, service_type, connection_points, **kwargs):
"""
Establish SDN/WAN connectivity between the endpoints
def create_connectivity_service(self, service_type, connection_points, **kwargs):
"""
Establish SDN/WAN connectivity between the endpoints
# 1.3 If more than one, ERROR
# Step 2. Modify the existing virtual network in the overlay controller
# 2.1 Add VNI (VxLAN Network Identifier - one free from the provided range)
# 1.3 If more than one, ERROR
# Step 2. Modify the existing virtual network in the overlay controller
# 2.1 Add VNI (VxLAN Network Identifier - one free from the provided range)
- # 2.2 Add RouteTarget (RT) ('ASN:VNI', ASN = Autonomous System Number, provided as param or read from controller config)
+ # 2.2 Add RouteTarget (RT) ('ASN:VNI', ASN = Autonomous System Number, provided as param or read from
+ # controller config)
# Step 3. Create a virtual network in the underlay controller
# 3.1 Create virtual network (name, VNI, RT)
# If the network already existed in the overlay controller, we should use the same name
# Step 3. Create a virtual network in the underlay controller
# 3.1 Create virtual network (name, VNI, RT)
# If the network already existed in the overlay controller, we should use the same name
# Initialize data
conn_info = None
# Initialize data
conn_info = None
# 1 - Filter connection_points (transform cp to a dictionary with no duplicates)
# This data will be returned even if no cp can be created if something is created
# 1 - Filter connection_points (transform cp to a dictionary with no duplicates)
# This data will be returned even if no cp can be created if something is created
work_cps = {}
for cp in connection_points:
switch_id = cp.get("service_endpoint_encapsulation_info").get("switch_dpid")
work_cps = {}
for cp in connection_points:
switch_id = cp.get("service_endpoint_encapsulation_info").get("switch_dpid")
"vlan": vlan}
work_cps[cp_name] = add_cp
else:
"vlan": vlan}
work_cps[cp_name] = add_cp
else:
- self.logger.warning("cp service_endpoint_id : {} has no vlan, ignore".format(service_endpoint_id))
+ self.logger.warning("cp service_endpoint_id : {} has no vlan, ignore".format(
+ service_endpoint_id))
else:
# add service_endpoint_id to list
service_endpoint_ids = add_cp["service_endpoint_ids"]
else:
# add service_endpoint_id to list
service_endpoint_ids = add_cp["service_endpoint_ids"]
"uuid": vnet_id,
"name": vnet_name
},
"uuid": vnet_id,
"name": vnet_name
},
- "connection_points": work_cps # dict with port_name as key
+ "connection_points": work_cps # dict with port_name as key
}
# 4 - Create a port for each endpoint
}
# 4 - Create a port for each endpoint
else:
self.logger.error("Error creating connectivity service: {}".format(e), exc_info=True)
else:
self.logger.error("Error creating connectivity service: {}".format(e), exc_info=True)
# If nothing is created raise error else return what has been created and mask as error
if not conn_info:
raise SdnConnectorError("Exception create connectivity service: {}".format(str(e)))
# If nothing is created raise error else return what has been created and mask as error
if not conn_info:
raise SdnConnectorError("Exception create connectivity service: {}".format(str(e)))
:raises: SdnConnectorException: In case of error. The parameter http_code must be filled
"""
self.logger.info("delete_connectivity_service vnet_name: {}, connection_points: {}".
:raises: SdnConnectorException: In case of error. The parameter http_code must be filled
"""
self.logger.info("delete_connectivity_service vnet_name: {}, connection_points: {}".
- format(service_uuid, conn_info))
+ format(service_uuid, conn_info))
try:
vnet_uuid = service_uuid
try:
vnet_uuid = service_uuid
- vnet_name = conn_info["vnet"]["name"] # always should exist as the network is the first thing created
+ # vnet_name = conn_info["vnet"]["name"] # always should exist as the network is the first thing created
work_cps = conn_info["connection_points"]
# 1: For each connection point delete vlan from vpg and it is is the
work_cps = conn_info["connection_points"]
# 1: For each connection point delete vlan from vpg and it is is the
# 2: Delete vnet
self.underlay_api.delete_virtual_network(vnet_uuid)
# 2: Delete vnet
self.underlay_api.delete_virtual_network(vnet_uuid)
- self.logger.info("deleted connectivity_service vnet_name: {}, connection_points: {}".
+ self.logger.info("deleted connectivity_service vnet_uuid: {}, connection_points: {}".
format(service_uuid, conn_info))
except SdnConnectorError:
raise
format(service_uuid, conn_info))
except SdnConnectorError:
raise
self.logger.error("Error deleting connectivity service: {}".format(e), exc_info=True)
raise SdnConnectorError("Exception deleting connectivity service: {}".format(str(e)))
self.logger.error("Error deleting connectivity service: {}".format(e), exc_info=True)
raise SdnConnectorError("Exception deleting connectivity service: {}".format(str(e)))
- def edit_connectivity_service(self, service_uuid, conn_info = None, connection_points = None, **kwargs):
+ def edit_connectivity_service(self, service_uuid, conn_info=None, connection_points=None, **kwargs):
""" Change an existing connectivity service.
This method's arguments and return value follow the same convention as
""" Change an existing connectivity service.
This method's arguments and return value follow the same convention as
# 3 - Delete unnecesary ports
# 4 - Add new ports
self.logger.info("edit connectivity service, service_uuid: {}, conn_info: {}, "
# 3 - Delete unnecesary ports
# 4 - Add new ports
self.logger.info("edit connectivity service, service_uuid: {}, conn_info: {}, "
- "connection points: {} ".format(service_uuid, conn_info, connection_points))
+ "connection points: {} ".format(service_uuid, conn_info, connection_points))
# conn_info should always exist and have connection_points and vnet elements
old_cp = conn_info.get("connection_points", {})
# conn_info should always exist and have connection_points and vnet elements
old_cp = conn_info.get("connection_points", {})
del old_cp[port]
# Delete sdn_status and sdn_info if exists (possibly marked as error)
del old_cp[port]
# Delete sdn_status and sdn_info if exists (possibly marked as error)
- if conn_info.get("vnet",{}).get("sdn_status"):
+ if conn_info.get("vnet", {}).get("sdn_status"):
del conn_info["vnet"]["sdn_status"]
except HttpException as e:
self.logger.error("Error trying to delete old ports marked as error: {}".format(e))
del conn_info["vnet"]["sdn_status"]
except HttpException as e:
self.logger.error("Error trying to delete old ports marked as error: {}".format(e))
cp = conn_info_cp[port_name]
switch_id = cp.get("switch_dpid")
switch_port = cp.get("switch_port")
cp = conn_info_cp[port_name]
switch_id = cp.get("switch_dpid")
switch_port = cp.get("switch_port")
- self.logger.debug("delete port switch_id, switch_port: {}".format(switch_id, switch_port))
+ self.logger.debug("delete port switch_id={}, switch_port={}".format(switch_id, switch_port))
self._delete_port(switch_id, switch_port, vlan)
deleted_ports.append(port_name)
self._delete_port(switch_id, switch_port, vlan)
deleted_ports.append(port_name)
switch_id = cp.get("switch_dpid")
switch_port = cp.get("switch_port")
vlan = cp.get("vlan")
switch_id = cp.get("switch_dpid")
switch_port = cp.get("switch_port")
vlan = cp.get("vlan")
- self.logger.debug("add port switch_id, switch_port: {}".format(switch_id, switch_port))
+ self.logger.debug("add port switch_id={}, switch_port={}".format(switch_id, switch_port))
vpg_id, vmi_id = self._create_port(switch_id, switch_port, vnet_name, vlan)
cp_added = cp.copy()
cp_added["vpg_id"] = vpg_id
vpg_id, vmi_id = self._create_port(switch_id, switch_port, vnet_name, vlan)
cp_added = cp.copy()
cp_added["vpg_id"] = vpg_id
handler = logging.StreamHandler()
handler.setFormatter(log_formatter)
logger = logging.getLogger('openmano.sdnconn.junipercontrail')
handler = logging.StreamHandler()
handler.setFormatter(log_formatter)
logger = logging.getLogger('openmano.sdnconn.junipercontrail')
- #logger.setLevel(level=logging.ERROR)
- #logger.setLevel(level=logging.INFO)
+ # logger.setLevel(level=logging.ERROR)
+ # logger.setLevel(level=logging.INFO)
logger.setLevel(level=logging.DEBUG)
logger.addHandler(handler)
logger.setLevel(level=logging.DEBUG)
logger.addHandler(handler)
vni = juniper_contrail._generate_vni()
juniper_contrail.used_vni.add(vni)
print(juniper_contrail.used_vni)
vni = juniper_contrail._generate_vni()
juniper_contrail.used_vni.add(vni)
print(juniper_contrail.used_vni)
- #juniper_contrail.used_vni.remove(1000003)
+ # juniper_contrail.used_vni.remove(1000003)
print(juniper_contrail.used_vni)
for i in range(2):
vni = juniper_contrail._generate_vni()
juniper_contrail.used_vni.add(vni)
print(juniper_contrail.used_vni)
print(juniper_contrail.used_vni)
for i in range(2):
vni = juniper_contrail._generate_vni()
juniper_contrail.used_vni.add(vni)
print(juniper_contrail.used_vni)
# 0. Check credentials
print('0. Check credentials')
# 0. Check credentials
print('0. Check credentials')
- #juniper_contrail.check_credentials()
+ # juniper_contrail.check_credentials()
# 1 - Create and delete connectivity service
conn_point_0 = {
# 1 - Create and delete connectivity service
conn_point_0 = {
logger.debug("Delete connectivity service 2")
juniper_contrail.delete_connectivity_service(service_id2, conn_info2)
logger.debug("Delete Ok")
logger.debug("Delete connectivity service 2")
juniper_contrail.delete_connectivity_service(service_id2, conn_info2)
logger.debug("Delete Ok")