Add functionality to support NSI selection
[optf/osdf.git] / apps / slice_selection / optimizers / conductor / remote_opt_processor.py
1 # -------------------------------------------------------------------------
2 #   Copyright (C) 2020 Wipro Limited.
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 """
20 Module for processing slice selection request
21 """
22
23 import json
24 import traceback
25 from requests import RequestException
26
27 from apps.slice_selection.optimizers.conductor.response_processor \
28     import conductor_response_processor, conductor_error_response_processor
29 from osdf.adapters.conductor import conductor
30 from osdf.adapters.policy.interface import get_policies
31 from osdf.adapters.policy.utils import group_policies_gen
32 from osdf.logging.osdf_logging import error_log, debug_log
33 from osdf.utils.mdc_utils import mdc_from_json
34
35
36 def process_nsi_selection_opt(request_json, osdf_config):
37     """Process the nsi selection request from API layer
38         :param request_json: api request
39         :param policies: flattened policies corresponding to this request
40         :param osdf_config: configuration specific to OSDF app
41         :return: response as a dictionary
42         """
43     req_info = request_json['requestInfo']
44     try:
45         mdc_from_json(request_json)
46
47         overall_recommendations = dict()
48         nst_info_map = dict()
49         for nst_info in request_json["NSTInfoList"]:
50             nst_name = nst_info["modelName"]
51             nst_info_map["nst_name"] = {"NSTName": nst_name,
52                                         "UUID": nst_info["modelVersionId"],
53                                         "invariantUUID": nst_info["modelInvariantId"]}
54
55             policy_request_json = request_json.copy()
56             policy_request_json['serviceInfo']['serviceName'] = nst_name
57
58             policies = get_policies(policy_request_json, "slice_selection")
59
60             demands = get_slice_demands(nst_name, policies, osdf_config.core)
61
62             request_parameters = {}
63             service_info = {}
64             req_info['numSolutions'] = 'all'
65             resp = conductor.request(req_info, demands, request_parameters, service_info, False,
66                                      osdf_config, policies)
67             debug_log.debug("Response from conductor {}".format(str(resp)))
68             overall_recommendations[nst_name] = resp["plans"][0].get("recommendations")
69
70         return conductor_response_processor(overall_recommendations, nst_info_map, req_info)
71
72     except Exception as ex:
73         error_log.error("Error for {} {}".format(req_info.get('requestId'),
74                                                  traceback.format_exc()))
75         if isinstance(ex, RequestException):
76             try:
77                 error_message = json.loads(ex.response)['plans'][0]['message']
78             except Exception:
79                 error_message = "Problem connecting to conductor"
80         else:
81             error_message = str(ex)
82         return conductor_error_response_processor(req_info, error_message)
83
84
85 def get_slice_demands(model_name, policies, config):
86     """
87     :param model_name: model name of the slice
88     :param policies: flattened polcies corresponding to the request
89     :param config: configuration specific to OSDF app
90     :return: list of demands for the request
91     """
92     group_policies = group_policies_gen(policies, config)
93     subscriber_policy_list = group_policies["onap.policies.optimization.SubscriberPolicy"]
94     slice_demands = list()
95     for subscriber_policy in subscriber_policy_list:
96         policy_properties = subscriber_policy[list(subscriber_policy.keys())[0]]['properties']
97         if model_name in policy_properties["services"]:
98             subnet_attributes = policy_properties["properties"]["subscriberRole"][0]
99             for subnet in policy_properties["properties"]["subscriberName"]:
100                 slice_demand = dict()
101                 slice_demand["resourceModuleName"] = subnet
102                 slice_demand['resourceModelInfo'] = subnet_attributes[subnet]
103                 slice_demands.append(slice_demand)
104     return slice_demands