diff options
-rw-r--r-- | apps/placement/models/api/placementRequest.py | 2 | ||||
-rwxr-xr-x | apps/placement/optimizers/conductor/conductor.py | 202 | ||||
-rw-r--r-- | apps/placement/optimizers/conductor/remote_opt_processor.py | 94 | ||||
-rw-r--r-- | osdf/adapters/conductor/__init__.py | 17 | ||||
-rw-r--r-- | osdf/adapters/conductor/api_builder.py (renamed from apps/placement/optimizers/conductor/api_builder.py) | 78 | ||||
-rw-r--r-- | osdf/adapters/conductor/conductor.py | 110 | ||||
-rwxr-xr-x | osdf/adapters/conductor/templates/conductor_interface.json (renamed from apps/placement/templates/conductor_interface.json) | 0 | ||||
-rw-r--r-- | osdf/adapters/conductor/translation.py (renamed from apps/placement/optimizers/conductor/translation.py) | 37 | ||||
-rw-r--r-- | test/conductor/test_conductor_calls.py | 15 | ||||
-rw-r--r-- | test/conductor/test_conductor_translation.py | 8 | ||||
-rw-r--r-- | test/test_ConductorApiBuilder.py | 19 | ||||
-rw-r--r-- | test/test_PolicyCalls.py | 8 | ||||
-rw-r--r-- | test/test_get_opt_query_data.py | 7 | ||||
-rw-r--r-- | test/test_process_placement_opt.py | 7 | ||||
-rw-r--r-- | test/test_so_response_gen.py | 5 |
15 files changed, 326 insertions, 283 deletions
diff --git a/apps/placement/models/api/placementRequest.py b/apps/placement/models/api/placementRequest.py index a0941cf..e04c2af 100644 --- a/apps/placement/models/api/placementRequest.py +++ b/apps/placement/models/api/placementRequest.py @@ -102,4 +102,4 @@ class PlacementAPI(OSDFModel): requestInfo = ModelType(RequestInfo, required=True) placementInfo = ModelType(PlacementInfo, required=True) licenseInfo = ModelType(LicenseInfo) - serviceInfo = ModelType(ServiceInfo, required=True) + serviceInfo = ModelType(ServiceInfo, required=True)
\ No newline at end of file diff --git a/apps/placement/optimizers/conductor/conductor.py b/apps/placement/optimizers/conductor/conductor.py deleted file mode 100755 index 05d1641..0000000 --- a/apps/placement/optimizers/conductor/conductor.py +++ /dev/null @@ -1,202 +0,0 @@ -# -------------------------------------------------------------------------
-# Copyright (c) 2015-2017 AT&T Intellectual Property
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-# -------------------------------------------------------------------------
-#
-
-"""
-This application generates conductor API calls using the information received from SO and Policy platform.
-"""
-
-import json
-import time
-
-from jinja2 import Template
-from requests import RequestException
-
-from apps.placement.optimizers.conductor.api_builder import conductor_api_builder
-from osdf.logging.osdf_logging import debug_log
-from osdf.utils.interfaces import RestClient
-from osdf.operation.exceptions import BusinessException
-
-
-def request(req_object, osdf_config, flat_policies):
- """
- Process a placement request from a Client (build Conductor API call, make the call, return result)
- :param req_object: Request parameters from the client
- :param osdf_config: Configuration specific to SNIRO application (core + deployment)
- :param flat_policies: policies related to placement (fetched based on request)
- :param prov_status: provStatus retrieved from Subscriber policy
- :return: response from Conductor (accounting for redirects from Conductor service
- """
- config = osdf_config.deployment
- local_config = osdf_config.core
- uid, passwd = config['conductorUsername'], config['conductorPassword']
- conductor_url = config['conductorUrl']
- req_id = req_object['requestInfo']['requestId']
- transaction_id = req_object['requestInfo']['transactionId']
- headers = dict(transaction_id=transaction_id)
- placement_ver_enabled = config.get('placementVersioningEnabled', False)
-
- if placement_ver_enabled:
- cond_minor_version = config.get('conductorMinorVersion', None)
- if cond_minor_version is not None:
- x_minor_version = str(cond_minor_version)
- headers.update({'X-MinorVersion': x_minor_version})
- debug_log.debug("Versions set in HTTP header to conductor: X-MinorVersion: {} ".format(x_minor_version))
-
- max_retries = config.get('conductorMaxRetries', 30)
- ping_wait_time = config.get('conductorPingWaitTime', 60)
-
- rc = RestClient(userid=uid, passwd=passwd, method="GET", log_func=debug_log.debug, headers=headers)
- conductor_req_json_str = conductor_api_builder(req_object, flat_policies, local_config)
- conductor_req_json = json.loads(conductor_req_json_str)
-
- debug_log.debug("Sending first Conductor request for request_id {}".format(req_id))
- resp, raw_resp = initial_request_to_conductor(rc, conductor_url, conductor_req_json)
- # Very crude way of keeping track of time.
- # We are not counting initial request time, first call back, or time for HTTP request
- total_time, ctr = 0, 2
- client_timeout = req_object['requestInfo']['timeout']
- configured_timeout = max_retries * ping_wait_time
- max_timeout = min(client_timeout, configured_timeout)
-
- while True: # keep requesting conductor till we get a result or we run out of time
- if resp is not None:
- if resp["plans"][0].get("status") in ["error"]:
- raise RequestException(response=raw_resp, request=raw_resp.request)
-
- if resp["plans"][0].get("status") in ["done", "not found"]:
- if resp["plans"][0].get("recommendations"):
- return conductor_response_processor(resp, raw_resp, req_id)
- else: # "solved" but no solutions found
- return conductor_no_solution_processor(resp, raw_resp, req_id)
- new_url = resp['plans'][0]['links'][0][0]['href'] # TODO: check why a list of lists
-
- if total_time >= max_timeout:
- raise BusinessException("Conductor could not provide a solution within {} seconds,"
- "this transaction is timing out".format(max_timeout))
- time.sleep(ping_wait_time)
- ctr += 1
- debug_log.debug("Attempt number {} url {}; prior status={}".format(ctr, new_url, resp['plans'][0]['status']))
- total_time += ping_wait_time
-
- try:
- raw_resp = rc.request(new_url, raw_response=True)
- resp = raw_resp.json()
- except RequestException as e:
- debug_log.debug("Conductor attempt {} for request_id {} has failed because {}".format(ctr, req_id, str(e)))
-
-
-def initial_request_to_conductor(rc, conductor_url, conductor_req_json):
- """First steps in the request-redirect chain in making a call to Conductor
- :param rc: REST client object for calling conductor
- :param conductor_url: conductor's base URL to submit a placement request
- :param conductor_req_json: request json object to send to Conductor
- :return: URL to check for follow up (similar to redirects); we keep checking these till we get a result/error
- """
- debug_log.debug("Payload to Conductor: {}".format(json.dumps(conductor_req_json)))
- raw_resp = rc.request(url=conductor_url, raw_response=True, method="POST", json=conductor_req_json)
- resp = raw_resp.json()
- if resp["status"] != "template":
- raise RequestException(response=raw_resp, request=raw_resp.request)
- time.sleep(10) # 10 seconds wait time to avoid being too quick!
- plan_url = resp["links"][0][0]["href"]
- debug_log.debug("Attempting to read the plan from the conductor provided url {}".format(plan_url))
- raw_resp = rc.request(raw_response=True, url=plan_url) # TODO: check why a list of lists for links
- resp = raw_resp.json()
-
- if resp["plans"][0]["status"] in ["error"]:
- raise RequestException(response=raw_resp, request=raw_resp.request)
- return resp, raw_resp # now the caller of this will handle further follow-ups
-
-
-def conductor_response_processor(conductor_response, raw_response, req_id):
- """Build a response object to be sent to client's callback URL from Conductor's response
- This includes Conductor's placement optimization response, and required ASDC license artifacts
-
- :param conductor_response: JSON response from Conductor
- :param raw_response: Raw HTTP response corresponding to above
- :param req_id: Id of a request
- :return: JSON object that can be sent to the client's callback URL
- """
- composite_solutions = []
- name_map = {"physical-location-id": "cloudClli", "host_id": "vnfHostName",
- "cloud_version": "cloudVersion", "cloud_owner": "cloudOwner",
- "cloud": "cloudRegionId", "service": "serviceInstanceId", "is_rehome": "isRehome",
- "location_id": "locationId", "location_type": "locationType", "directives": "oof_directives"}
- for reco in conductor_response['plans'][0]['recommendations']:
- for resource in reco.keys():
- c = reco[resource]['candidate']
- solution = {
- 'resourceModuleName': resource,
- 'serviceResourceId': reco[resource].get('service_resource_id', ""),
- 'solution': {"identifierType": name_map.get(c['inventory_type'], c['inventory_type']),
- 'identifiers': [c['candidate_id']],
- 'cloudOwner': c.get('cloud_owner', "")},
- 'assignmentInfo': []
- }
- for key, value in c.items():
- if key in ["location_id", "location_type", "is_rehome", "host_id"]:
- try:
- solution['assignmentInfo'].append({"key": name_map.get(key, key), "value": value})
- except KeyError:
- debug_log.debug("The key[{}] is not mapped and will not be returned in assignment info".format(key))
-
- for key, value in reco[resource]['attributes'].items():
- try:
- solution['assignmentInfo'].append({"key": name_map.get(key, key), "value": value})
- except KeyError:
- debug_log.debug("The key[{}] is not mapped and will not be returned in assignment info".format(key))
- composite_solutions.append(solution)
-
- request_status = "completed" if conductor_response['plans'][0]['status'] == "done" \
- else conductor_response['plans'][0]['status']
- transaction_id = raw_response.headers.get('transaction_id', "")
- status_message = conductor_response.get('plans')[0].get('message', "")
-
- solution_info = {}
- if composite_solutions:
- solution_info.setdefault('placementSolutions', [])
- solution_info['placementSolutions'].append(composite_solutions)
-
- resp = {
- "transactionId": transaction_id,
- "requestId": req_id,
- "requestStatus": request_status,
- "statusMessage": status_message,
- "solutions": solution_info
- }
- return resp
-
-
-def conductor_no_solution_processor(conductor_response, raw_response, request_id,
- template_placement_response="templates/plc_opt_response.jsont"):
- """Build a response object to be sent to client's callback URL from Conductor's response
- This is for case where no solution is found
-
- :param conductor_response: JSON response from Conductor
- :param raw_response: Raw HTTP response corresponding to above
- :param request_id: request Id associated with the client request (same as conductor response's "name")
- :param template_placement_response: the template for generating response to client (plc_opt_response.jsont)
- :return: JSON object that can be sent to the client's callback URL
- """
- status_message = conductor_response["plans"][0].get("message")
- templ = Template(open(template_placement_response).read())
- return json.loads(templ.render(composite_solutions=[], requestId=request_id, license_solutions=[],
- transactionId=raw_response.headers.get('transaction_id', ""),
- requestStatus="completed", statusMessage=status_message, json=json))
-
-
diff --git a/apps/placement/optimizers/conductor/remote_opt_processor.py b/apps/placement/optimizers/conductor/remote_opt_processor.py index a08f3a4..0b5cb16 100644 --- a/apps/placement/optimizers/conductor/remote_opt_processor.py +++ b/apps/placement/optimizers/conductor/remote_opt_processor.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,17 +17,95 @@ # ------------------------------------------------------------------------- # +import json +from jinja2 import Template from requests import RequestException import traceback from osdf.operation.error_handling import build_json_error_body -from osdf.logging.osdf_logging import metrics_log, MH, error_log -from apps.placement.optimizers.conductor import conductor +from osdf.logging.osdf_logging import metrics_log, MH, error_log, debug_log +from osdf.adapters.conductor import conductor from apps.license.optimizers.simple_license_allocation import license_optim from osdf.utils.interfaces import get_rest_client from osdf.utils.mdc_utils import mdc_from_json +def conductor_response_processor(conductor_response, req_id, transaction_id): + """Build a response object to be sent to client's callback URL from Conductor's response + This includes Conductor's placement optimization response, and required ASDC license artifacts + + :param conductor_response: JSON response from Conductor + :param raw_response: Raw HTTP response corresponding to above + :param req_id: Id of a request + :return: JSON object that can be sent to the client's callback URL + """ + composite_solutions = [] + name_map = {"physical-location-id": "cloudClli", "host_id": "vnfHostName", + "cloud_version": "cloudVersion", "cloud_owner": "cloudOwner", + "cloud": "cloudRegionId", "service": "serviceInstanceId", "is_rehome": "isRehome", + "location_id": "locationId", "location_type": "locationType", "directives": "oof_directives"} + for reco in conductor_response['plans'][0]['recommendations']: + for resource in reco.keys(): + c = reco[resource]['candidate'] + solution = { + 'resourceModuleName': resource, + 'serviceResourceId': reco[resource].get('service_resource_id', ""), + 'solution': {"identifierType": name_map.get(c['inventory_type'], c['inventory_type']), + 'identifiers': [c['candidate_id']], + 'cloudOwner': c.get('cloud_owner', "")}, + 'assignmentInfo': [] + } + for key, value in c.items(): + if key in ["location_id", "location_type", "is_rehome", "host_id"]: + try: + solution['assignmentInfo'].append({"key": name_map.get(key, key), "value": value}) + except KeyError: + debug_log.debug("The key[{}] is not mapped and will not be returned in assignment info".format(key)) + + for key, value in reco[resource]['attributes'].items(): + try: + solution['assignmentInfo'].append({"key": name_map.get(key, key), "value": value}) + except KeyError: + debug_log.debug("The key[{}] is not mapped and will not be returned in assignment info".format(key)) + composite_solutions.append(solution) + + request_status = "completed" if conductor_response['plans'][0]['status'] == "done" \ + else conductor_response['plans'][0]['status'] + status_message = conductor_response.get('plans')[0].get('message', "") + + solution_info = {} + if composite_solutions: + solution_info.setdefault('placementSolutions', []) + solution_info['placementSolutions'].append(composite_solutions) + + resp = { + "transactionId": transaction_id, + "requestId": req_id, + "requestStatus": request_status, + "statusMessage": status_message, + "solutions": solution_info + } + return resp + + +def conductor_no_solution_processor(conductor_response, request_id, transaction_id, + template_placement_response="templates/plc_opt_response.jsont"): + """Build a response object to be sent to client's callback URL from Conductor's response + This is for case where no solution is found + + :param conductor_response: JSON response from Conductor + :param raw_response: Raw HTTP response corresponding to above + :param request_id: request Id associated with the client request (same as conductor response's "name") + :param template_placement_response: the template for generating response to client (plc_opt_response.jsont) + :return: JSON object that can be sent to the client's callback URL + """ + status_message = conductor_response["plans"][0].get("message") + templ = Template(open(template_placement_response).read()) + return json.loads(templ.render(composite_solutions=[], requestId=request_id, license_solutions=[], + transactionId=transaction_id, + requestStatus="completed", statusMessage=status_message, json=json)) + + def process_placement_opt(request_json, policies, osdf_config): """Perform the work for placement optimization (e.g. call SDC artifact and make conductor request) NOTE: there is scope to make the requests to policy asynchronous to speed up overall performance @@ -51,7 +130,16 @@ def process_placement_opt(request_json, policies, osdf_config): # Conductor only handles placement, only call Conductor if placementDemands exist if request_json.get('placementInfo', {}).get('placementDemands'): metrics_log.info(MH.requesting("placement/conductor", req_id)) - placement_response = conductor.request(request_json, osdf_config, policies) + req_info = request_json['requestInfo'] + demands = request_json['placementInfo']['placementDemands'] + request_parameters = request_json['placementInfo']['requestParameters'] + service_info = request_json['serviceInfo'] + resp = conductor.request(req_info, demands, request_parameters, service_info, + osdf_config, policies) + if resp["plans"][0].get("recommendations"): + placement_response = conductor_response_processor(resp, req_id, transaction_id) + else: # "solved" but no solutions found + placement_response = conductor_no_solution_processor(resp, req_id, transaction_id) if license_info: # Attach license solution if it exists placement_response['solutionInfo']['licenseInfo'] = license_info else: # License selection only scenario diff --git a/osdf/adapters/conductor/__init__.py b/osdf/adapters/conductor/__init__.py new file mode 100644 index 0000000..6156206 --- /dev/null +++ b/osdf/adapters/conductor/__init__.py @@ -0,0 +1,17 @@ +# ------------------------------------------------------------------------- +# Copyright (c) 2017-2018 AT&T Intellectual Property +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +#
\ No newline at end of file diff --git a/apps/placement/optimizers/conductor/api_builder.py b/osdf/adapters/conductor/api_builder.py index 398db8d..17057d8 100644 --- a/apps/placement/optimizers/conductor/api_builder.py +++ b/osdf/adapters/conductor/api_builder.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,30 +17,30 @@ # ------------------------------------------------------------------------- # -import json - from jinja2 import Template +import json -import apps.placement.optimizers.conductor.translation as tr from osdf.adapters.policy.utils import group_policies_gen +import osdf.adapters.conductor.translation as tr from osdf.utils.programming_utils import list_flatten -def _build_parameters(group_policies, request_json): +def _build_parameters(group_policies, service_info, request_parameters): """ - Function prepares parameters section for has request - :param group_policies: filtered policies - :param request_json: parameter data received from a client - :return: - """ - initial_params = tr.get_opt_query_data(request_json, group_policies['onap.policies.optimization.QueryPolicy']) + Function prepares parameters section for has request + :param group_policies: filtered policies + :param service_info: service info + :param request_parameters: request parameters + :return: + """ + initial_params = tr.get_opt_query_data(request_parameters, group_policies['onap.policies.optimization.QueryPolicy']) params = dict() params.update({"REQUIRED_MEM": initial_params.pop("requiredMemory", "")}) params.update({"REQUIRED_DISK": initial_params.pop("requiredDisk", "")}) params.update({"customer_lat": initial_params.pop("customerLatitude", 0.0)}) params.update({"customer_long": initial_params.pop("customerLongitude", 0.0)}) - params.update({"service_name": request_json['serviceInfo']['serviceName']}) - params.update({"service_id": request_json['serviceInfo']['serviceInstanceId']}) + params.update({"service_name": service_info.get('serviceName', "")}) + params.update({"service_id": service_info.get('serviceInstanceId', "")}) for key, val in initial_params.items(): if val and val != "": @@ -48,50 +49,51 @@ def _build_parameters(group_policies, request_json): return params -def conductor_api_builder(request_json, flat_policies: list, local_config, - template="apps/placement/templates/conductor_interface.json"): +def conductor_api_builder(req_info, demands, request_parameters, service_info, flat_policies: list, local_config, + template="osdf/adapters/conductor/templates/conductor_interface.json"): """Build an OSDF southbound API call for HAS-Conductor/Placement optimization - :param request_json: parameter data received from a client - :param flat_policies: policy data received from the policy platform (flat policies) - :param template: template to generate southbound API call to conductor - :param local_config: local configuration file with pointers for the service specific information - :param prov_status: provStatus retrieved from Subscriber policy - :return: json to be sent to Conductor/placement optimization - """ + :param req_info: parameter data received from a client + :param demands: list of demands + :param request_parameters: request parameters + :param service_info: service info object + :param flat_policies: policy data received from the policy platform (flat policies) + :param template: template to generate southbound API call to conductor + :param local_config: local configuration file with pointers for the service specific information + :return: json to be sent to Conductor/placement optimization + """ + templ = Template(open(template).read()) gp = group_policies_gen(flat_policies, local_config) - demand_vnf_name_list = [] - for placementDemand in request_json['placementInfo']['placementDemands']: - demand_vnf_name_list.append(placementDemand['resourceModuleName'].lower()) - demand_list = tr.gen_demands( - request_json, gp['onap.policies.optimization.VnfPolicy']) + demand_name_list = [] + for demand in demands: + demand_name_list.append(demand['resourceModuleName'].lower()) + demand_list = tr.gen_demands(demands, gp['onap.policies.optimization.VnfPolicy']) attribute_policy_list = tr.gen_attribute_policy( - demand_vnf_name_list, gp['onap.policies.optimization.AttributePolicy']) + demand_name_list, gp['onap.policies.optimization.AttributePolicy']) distance_to_location_policy_list = tr.gen_distance_to_location_policy( - demand_vnf_name_list, gp['onap.policies.optimization.DistancePolicy']) + demand_name_list, gp['onap.policies.optimization.DistancePolicy']) inventory_policy_list = tr.gen_inventory_group_policy( - demand_vnf_name_list, gp['onap.policies.optimization.InventoryGroupPolicy']) + demand_name_list, gp['onap.policies.optimization.InventoryGroupPolicy']) resource_instance_policy_list = tr.gen_resource_instance_policy( - demand_vnf_name_list, gp['onap.policies.optimization.ResourceInstancePolicy']) + demand_name_list, gp['onap.policies.optimization.ResourceInstancePolicy']) resource_region_policy_list = tr.gen_resource_region_policy( - demand_vnf_name_list, gp['onap.policies.optimization.ResourceRegionPolicy']) + demand_name_list, gp['onap.policies.optimization.ResourceRegionPolicy']) zone_policy_list = tr.gen_zone_policy( - demand_vnf_name_list, gp['onap.policies.optimization.AffinityPolicy']) + demand_name_list, gp['onap.policies.optimization.AffinityPolicy']) optimization_policy_list = tr.gen_optimization_policy( - demand_vnf_name_list, gp['onap.policies.optimization.OptimizationPolicy']) + demand_name_list, gp['onap.policies.optimization.OptimizationPolicy']) reservation_policy_list = tr.gen_reservation_policy( - demand_vnf_name_list, gp['onap.policies.optimization.InstanceReservationPolicy']) + demand_name_list, gp['onap.policies.optimization.InstanceReservationPolicy']) capacity_policy_list = tr.gen_capacity_policy( - demand_vnf_name_list, gp['onap.policies.optimization.Vim_fit']) + demand_name_list, gp['onap.policies.optimization.Vim_fit']) hpa_policy_list = tr.gen_hpa_policy( - demand_vnf_name_list, gp['onap.policies.optimization.HpaPolicy']) - req_params_dict = _build_parameters(gp, request_json) + demand_name_list, gp['onap.policies.optimization.HpaPolicy']) + req_params_dict = _build_parameters(gp, service_info, request_parameters) conductor_policies = [attribute_policy_list, distance_to_location_policy_list, inventory_policy_list, resource_instance_policy_list, resource_region_policy_list, zone_policy_list, reservation_policy_list, capacity_policy_list, hpa_policy_list] filtered_policies = [x for x in conductor_policies if len(x) > 0] policy_groups = list_flatten(filtered_policies) - req_info = request_json['requestInfo'] request_type = req_info.get('requestType', None) rendered_req = templ.render( requestType=request_type, diff --git a/osdf/adapters/conductor/conductor.py b/osdf/adapters/conductor/conductor.py new file mode 100644 index 0000000..00069a4 --- /dev/null +++ b/osdf/adapters/conductor/conductor.py @@ -0,0 +1,110 @@ +# ------------------------------------------------------------------------- +# Copyright (c) 2015-2017 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ------------------------------------------------------------------------- +# + +import json + +from requests import RequestException +import time + +from osdf.adapters.conductor.api_builder import conductor_api_builder +from osdf.logging.osdf_logging import debug_log +from osdf.utils.interfaces import RestClient +from osdf.operation.exceptions import BusinessException + + +def request(req_info, demands, request_parameters, service_info, osdf_config, flat_policies): + config = osdf_config.deployment + local_config = osdf_config.core + uid, passwd = config['conductorUsername'], config['conductorPassword'] + conductor_url = config['conductorUrl'] + req_id = req_info["requestId"] + transaction_id = req_info['transactionId'] + headers = dict(transaction_id=transaction_id) + placement_ver_enabled = config.get('placementVersioningEnabled', False) + + if placement_ver_enabled: + cond_minor_version = config.get('conductorMinorVersion', None) + if cond_minor_version is not None: + x_minor_version = str(cond_minor_version) + headers.update({'X-MinorVersion': x_minor_version}) + debug_log.debug("Versions set in HTTP header to conductor: X-MinorVersion: {} ".format(x_minor_version)) + + max_retries = config.get('conductorMaxRetries', 30) + ping_wait_time = config.get('conductorPingWaitTime', 60) + + rc = RestClient(userid=uid, passwd=passwd, method="GET", log_func=debug_log.debug, headers=headers) + conductor_req_json_str = conductor_api_builder(req_info, demands, request_parameters, service_info, flat_policies, + local_config) + conductor_req_json = json.loads(conductor_req_json_str) + + debug_log.debug("Sending first Conductor request for request_id {}".format(req_id)) + + resp, raw_resp = initial_request_to_conductor(rc, conductor_url, conductor_req_json) + # Very crude way of keeping track of time. + # We are not counting initial request time, first call back, or time for HTTP request + total_time, ctr = 0, 2 + client_timeout = req_info['timeout'] + configured_timeout = max_retries * ping_wait_time + max_timeout = min(client_timeout, configured_timeout) + + while True: # keep requesting conductor till we get a result or we run out of time + if resp is not None: + if resp["plans"][0].get("status") in ["error"]: + raise RequestException(response=raw_resp, request=raw_resp.request) + + if resp["plans"][0].get("status") in ["done", "not found"]: + return resp + new_url = resp['plans'][0]['links'][0][0]['href'] # TODO: check why a list of lists + + if total_time >= max_timeout: + raise BusinessException("Conductor could not provide a solution within {} seconds," + "this transaction is timing out".format(max_timeout)) + time.sleep(ping_wait_time) + ctr += 1 + debug_log.debug("Attempt number {} url {}; prior status={}".format(ctr, new_url, resp['plans'][0]['status'])) + total_time += ping_wait_time + + try: + raw_resp = rc.request(new_url, raw_response=True) + resp = raw_resp.json() + except RequestException as e: + debug_log.debug("Conductor attempt {} for request_id {} has failed because {}".format(ctr, req_id, str(e))) + + +def initial_request_to_conductor(rc, conductor_url, conductor_req_json): + """First steps in the request-redirect chain in making a call to Conductor + :param rc: REST client object for calling conductor + :param conductor_url: conductor's base URL to submit a placement request + :param conductor_req_json: request json object to send to Conductor + :return: URL to check for follow up (similar to redirects); we keep checking these till we get a result/error + """ + debug_log.debug("Payload to Conductor: {}".format(json.dumps(conductor_req_json))) + raw_resp = rc.request(url=conductor_url, raw_response=True, method="POST", json=conductor_req_json) + resp = raw_resp.json() + if resp["status"] != "template": + raise RequestException(response=raw_resp, request=raw_resp.request) + time.sleep(10) # 10 seconds wait time to avoid being too quick! + plan_url = resp["links"][0][0]["href"] + debug_log.debug("Attempting to read the plan from the conductor provided url {}".format(plan_url)) + raw_resp = rc.request(raw_response=True, url=plan_url) # TODO: check why a list of lists for links + resp = raw_resp.json() + + if resp["plans"][0]["status"] in ["error"]: + raise RequestException(response=raw_resp, request=raw_resp.request) + return resp, raw_resp # now the caller of this will handle further follow-ups diff --git a/apps/placement/templates/conductor_interface.json b/osdf/adapters/conductor/templates/conductor_interface.json index 030d6a0..030d6a0 100755 --- a/apps/placement/templates/conductor_interface.json +++ b/osdf/adapters/conductor/templates/conductor_interface.json diff --git a/apps/placement/optimizers/conductor/translation.py b/osdf/adapters/conductor/translation.py index d637152..12dfc88 100644 --- a/apps/placement/optimizers/conductor/translation.py +++ b/osdf/adapters/conductor/translation.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -26,25 +27,23 @@ from osdf.utils.programming_utils import dot_notation policy_config_mapping = yaml.safe_load(open('config/has_config.yaml')).get('policy_config_mapping') -def get_opt_query_data(req_json, policies): - """ - Fetch service and order specific details from the requestParameters field of a request. - :param req_json: a request file - :param policies: A set of policies - :return: A dictionary with service and order-specific attributes. +def get_opt_query_data(request_parameters, policies): """ + Fetch service and order specific details from the requestParameters field of a request. + :param request_parameters: A list of request parameters + :param policies: A set of policies + :return: A dictionary with service and order-specific attributes. + """ req_param_dict = {} - if 'requestParameters' in req_json["placementInfo"]: - req_params = req_json["placementInfo"]["requestParameters"] + if request_parameters: for policy in policies: for queryProp in policy[list(policy.keys())[0]]['properties']['queryProperties']: attr_val = queryProp['value'] if 'value' in queryProp and queryProp['value'] != "" \ - else dot_notation(req_params, queryProp['attribute_location']) + else dot_notation(request_parameters, queryProp['attribute_location']) if attr_val is not None: req_param_dict.update({queryProp['attribute']: attr_val}) return req_param_dict - def gen_optimization_policy(vnf_list, optimization_policy): """Generate optimization policy details to pass to Conductor :param vnf_list: List of vnf's to used in placement request @@ -254,20 +253,20 @@ def get_demand_properties(demand, policies): for policy_property in get_policy_properties(demand, policies): prop = dict(inventory_provider=policy_property['inventoryProvider'], inventory_type=policy_property['inventoryType'], - service_type=demand['serviceResourceId'], - service_resource_id=demand['serviceResourceId']) + service_type=demand.get('serviceResourceId', ''), + service_resource_id=demand.get('serviceResourceId', '')) prop.update({'unique': policy_property['unique']} if 'unique' in policy_property and policy_property['unique'] else {}) prop['filtering_attributes'] = dict() prop['filtering_attributes'].update({'global-customer-id': policy_property['customerId']} - if policy_property['customerId'] else {}) + if policy_property['customerId'] else {}) prop['filtering_attributes'].update({'model-invariant-id': demand['resourceModelInfo']['modelInvariantId']} - if demand['resourceModelInfo']['modelInvariantId'] else {}) + if demand['resourceModelInfo']['modelInvariantId'] else {}) prop['filtering_attributes'].update({'model-version-id': demand['resourceModelInfo']['modelVersionId']} - if demand['resourceModelInfo']['modelVersionId'] else {}) + if demand['resourceModelInfo']['modelVersionId'] else {}) prop['filtering_attributes'].update({'equipment-role': policy_property['equipmentRole']} - if policy_property['equipmentRole'] else {}) + if policy_property['equipmentRole'] else {}) if policy_property.get('attributes'): for attr_key, attr_val in policy_property['attributes'].items(): @@ -302,14 +301,14 @@ def update_converted_attribute(attr_key, attr_val, properties, attribute_type): properties[attribute_type].update({key_value: attr_val}) -def gen_demands(req_json, vnf_policies): +def gen_demands(demands, vnf_policies): """Generate list of demands based on request and VNF policies - :param req_json: Request object from the client (e.g. MSO) + :param demands: A List of demands :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy']) :return: list of demand parameters to populate the Conductor API call """ demand_dictionary = {} - for demand in req_json['placementInfo']['placementDemands']: + for demand in demands: prop = get_demand_properties(demand, vnf_policies) if len(prop) > 0: demand_dictionary.update({demand['resourceModuleName']: prop}) diff --git a/test/conductor/test_conductor_calls.py b/test/conductor/test_conductor_calls.py index 52e0367..0042ecb 100644 --- a/test/conductor/test_conductor_calls.py +++ b/test/conductor/test_conductor_calls.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,7 +18,7 @@ # import unittest -from apps.placement.optimizers.conductor import conductor +from osdf.adapters.conductor import conductor import osdf.config.loader as config_loader from osdf.utils.interfaces import json_from_file from osdf.utils.programming_utils import DotDict @@ -41,12 +42,20 @@ class TestConductorCalls(unittest.TestCase): def test_request(self): req_json = json_from_file("./test/placement-tests/request.json") policies = pol.get_local_policies("test/policy-local-files/", self.lp) - conductor.request(req_json, self.osdf_config, policies) + req_info = req_json['requestInfo'] + demands = req_json['placementInfo']['placementDemands'] + request_parameters = req_json['placementInfo']['requestParameters'] + service_info = req_json['serviceInfo'] + conductor.request(req_info, demands, request_parameters, service_info, self.osdf_config, policies) def test_request_vfmod(self): req_json = json_from_file("./test/placement-tests/request_vfmod.json") policies = pol.get_local_policies("test/policy-local-files/", self.lp) - conductor.request(req_json, self.osdf_config, policies) + req_info = req_json['requestInfo'] + demands = req_json['placementInfo']['placementDemands'] + request_parameters = req_json['placementInfo']['requestParameters'] + service_info = req_json['serviceInfo'] + conductor.request(req_info, demands, request_parameters, service_info, self.osdf_config, policies) if __name__ == "__main__": diff --git a/test/conductor/test_conductor_translation.py b/test/conductor/test_conductor_translation.py index 3481b88..8b6c0a1 100644 --- a/test/conductor/test_conductor_translation.py +++ b/test/conductor/test_conductor_translation.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,7 +19,7 @@ import unittest from osdf.adapters.local_data import local_policies -from apps.placement.optimizers.conductor import translation as tr +from osdf.adapters.conductor import translation as tr from osdf.utils.interfaces import json_from_file @@ -46,14 +47,15 @@ class TestConductorTranslation(unittest.TestCase): # need to run this only on vnf policies vnf_policies = [x for x in self.policies if x[list(x.keys())[0]]["type"] == "onap.policies.optimization.VnfPolicy"] - res = tr.gen_demands(self.request_json, vnf_policies) + res = tr.gen_demands(self.request_json['placementInfo']['placementDemands'], vnf_policies) + assert res is not None def test_gen_vfmod_demands(self): # need to run this only on vnf policies vnf_policies = [x for x in self.policies if x[list(x.keys())[0]]["type"] == "onap.policies.optimization.VnfPolicy"] - res = tr.gen_demands(self.request_vfmod_json, vnf_policies) + res = tr.gen_demands(self.request_vfmod_json['placementInfo']['placementDemands'], vnf_policies) assert res is not None diff --git a/test/test_ConductorApiBuilder.py b/test/test_ConductorApiBuilder.py index 07cb3bb..44c14d8 100644 --- a/test/test_ConductorApiBuilder.py +++ b/test/test_ConductorApiBuilder.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,7 +20,7 @@ import unittest import json import yaml -from apps.placement.optimizers.conductor.api_builder import conductor_api_builder +from osdf.adapters.conductor.api_builder import conductor_api_builder from osdf.adapters.local_data import local_policies from osdf.utils.interfaces import json_from_file @@ -28,7 +29,7 @@ class TestConductorApiBuilder(unittest.TestCase): def setUp(self): self.main_dir = "" - self.conductor_api_template = self.main_dir + "apps/placement/templates/conductor_interface.json" + self.conductor_api_template = self.main_dir + "osdf/adapters/conductor/templates/conductor_interface.json" self.local_config_file = self.main_dir + "config/common_config.yaml" policy_data_path = self.main_dir + "test/policy-local-files" # "test/policy-local-files" @@ -48,7 +49,12 @@ class TestConductorApiBuilder(unittest.TestCase): request_json = self.request_json policies = self.policies local_config = yaml.safe_load(open(self.local_config_file)) - templ_string = conductor_api_builder(request_json, policies, local_config, self.conductor_api_template) + req_info = request_json['requestInfo'] + demands = request_json['placementInfo']['placementDemands'] + request_parameters = request_json['placementInfo']['requestParameters'] + service_info = request_json['serviceInfo'] + templ_string = conductor_api_builder(req_info, demands, request_parameters, service_info, policies, + local_config, self.conductor_api_template) templ_json = json.loads(templ_string) self.assertEqual(templ_json["name"], "yyy-yyy-yyyy") @@ -56,7 +62,12 @@ class TestConductorApiBuilder(unittest.TestCase): request_json = self.request_vfmod_json policies = self.policies local_config = yaml.safe_load(open(self.local_config_file)) - templ_string = conductor_api_builder(request_json, policies, local_config, self.conductor_api_template) + req_info = request_json['requestInfo'] + demands = request_json['placementInfo']['placementDemands'] + request_parameters = request_json['placementInfo']['requestParameters'] + service_info = request_json['serviceInfo'] + templ_string = conductor_api_builder(req_info, demands, request_parameters, service_info, policies, + local_config, self.conductor_api_template) templ_json = json.loads(templ_string) self.assertEqual(templ_json, self.request_placement_vfmod_json) diff --git a/test/test_PolicyCalls.py b/test/test_PolicyCalls.py index 0b17081..c41c487 100644 --- a/test/test_PolicyCalls.py +++ b/test/test_PolicyCalls.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,7 +25,7 @@ from osdf.adapters.policy import interface from osdf.utils.interfaces import RestClient, json_from_file import yaml from mock import patch -from apps.placement.optimizers.conductor import translation +from osdf.adapters.conductor import translation from osdf.operation.exceptions import BusinessException @@ -101,13 +102,14 @@ class TestPolicyCalls(unittest.TestCase): # need to run this only on vnf policies vnf_policies = [x for x in self.policies if x[list(x.keys())[0]]["type"] == "onap.policies.optimization.VnfPolicy"] - gen_demands = translation.gen_demands(req_json, vnf_policies) + gen_demands = translation.gen_demands(req_json['placementInfo']['placementDemands'], vnf_policies) + for action in req_json['placementInfo']['placementDemands']: actions_list.append(action['resourceModuleName']) for key2,value in gen_demands.items(): gen_demands_list.append(key2) self.assertListEqual(gen_demands_list, actions_list, 'generated demands are not equal to the passed input' - '[placementDemand][resourceModuleName] list') + '[placementDemand][resourceModuleName] list') def test_local_policy_location(self): req_json = json_from_file("./test/placement-tests/request.json") diff --git a/test/test_get_opt_query_data.py b/test/test_get_opt_query_data.py index a7a4d88..8e6c324 100644 --- a/test/test_get_opt_query_data.py +++ b/test/test_get_opt_query_data.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,7 +18,7 @@ # import unittest import json -from apps.placement.optimizers.conductor.translation import get_opt_query_data +from osdf.adapters.conductor.translation import get_opt_query_data class TestGetOptQueryData(unittest.TestCase): @@ -30,7 +31,7 @@ class TestGetOptQueryData(unittest.TestCase): query_policy_data_file = ["QueryPolicy_vCPE.json"] request_json = json.loads(open(parameter_data_file).read()) policies = [json.loads(open(policy_data_path + file).read()) for file in query_policy_data_file] - req_param_dict = get_opt_query_data(request_json, policies) + req_param_dict = get_opt_query_data(request_json['placementInfo']['requestParameters'], policies) self.assertTrue(req_param_dict is not None) @@ -42,7 +43,7 @@ class TestGetOptQueryData(unittest.TestCase): query_policy_data_file = ["QueryPolicy_vFW_TD.json"] request_json = json.loads(open(parameter_data_file).read()) policies = [json.loads(open(policy_data_path + file).read()) for file in query_policy_data_file] - req_param_dict = get_opt_query_data(request_json, policies) + req_param_dict = get_opt_query_data(request_json['placementInfo']['requestParameters'], policies) self.assertTrue(req_param_dict is not None) diff --git a/test/test_process_placement_opt.py b/test/test_process_placement_opt.py index 64b69a8..8a29100 100644 --- a/test/test_process_placement_opt.py +++ b/test/test_process_placement_opt.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,8 +31,10 @@ class TestProcessPlacementOpt(unittest.TestCase): def setUp(self): mock_req_accept_message = Response("Accepted Request", content_type='application/json; charset=utf-8') - self.patcher_req = patch('apps.placement.optimizers.conductor.conductor.request', - return_value={"solutionInfo": {"placementInfo": "dummy"}}) + conductor_response_file = 'test/placement-tests/conductor_response.json' + conductor_response = json_from_file(conductor_response_file) + self.patcher_req = patch('osdf.adapters.conductor.conductor.request', + return_value=conductor_response) self.patcher_req_accept = patch('osdf.operation.responses.osdf_response_for_request_accept', return_value=mock_req_accept_message) self.patcher_callback = patch( diff --git a/test/test_so_response_gen.py b/test/test_so_response_gen.py index 6705cc8..1e6079b 100644 --- a/test/test_so_response_gen.py +++ b/test/test_so_response_gen.py @@ -1,5 +1,6 @@ # ------------------------------------------------------------------------- # Copyright (c) 2017-2018 AT&T Intellectual Property +# Copyright (C) 2020 Wipro Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,7 +18,7 @@ # import unittest -from apps.placement.optimizers.conductor.conductor import conductor_response_processor +from apps.placement.optimizers.conductor.remote_opt_processor import conductor_response_processor from osdf.utils.interfaces import json_from_file from osdf.utils.interfaces import RestClient @@ -35,4 +36,4 @@ class TestSoResponseGen(unittest.TestCase): if __name__ == "__main__": - unittest.main()
\ No newline at end of file + unittest.main() |