Missing callback in NST selection
[optf/osdf.git] / apps / nst / optimizers / nst_select_processor.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2020 Huawei Intellectual Property
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 This application generates NST SELECTION API calls using the information received from SO
20 """
21 import json
22 import os
23 from osdf.logging.osdf_logging import error_log
24 from osdf.utils.interfaces import get_rest_client
25 from requests import RequestException
26 from threading import Thread
27 import traceback
28 BASE_DIR = os.path.dirname(__file__)
29
30
31 # This is the class for NST Selection
32
33
34 class NstSelection(Thread):
35
36     def __init__(self, osdf_config, request_json):
37         super().__init__()
38         self.osdf_config = osdf_config
39         self.request_json = request_json
40         self.request_info = self.request_json['requestInfo']
41
42     def run(self):
43         self.process_nst_selection()
44
45     def process_nst_selection(self):
46         """Process a PCI request from a Client (build config-db, policy and  API call, make the call, return result)
47
48             :param req_object: Request parameters from the client
49             :param osdf_config: Configuration specific to OSDF application (core + deployment)
50             :return: response from NST Opt
51         """
52         try:
53             rest_client = get_rest_client(self.request_json, service='so')
54             solution = self.get_nst_solution()
55             solution = self.get_nst_selection_response(solution)
56         except Exception as err:
57             error_log.error("Error for {} {}".format(self.request_info.get('requestId'),
58                                                      traceback.format_exc()))
59             error_message = str(err)
60             solution = self.error_response(error_message)
61
62         try:
63             rest_client.request(json=solution, noresponse=True)
64         except RequestException:
65             error_log.error("Error sending asynchronous notification for {} {}".
66                             format(self.request_info['requestId'], traceback.format_exc()))
67
68     def get_nst_solution(self):
69         """the file is in the same folder for now will move it to the conf folder of the has once its
70
71            integrated there...
72         """
73
74         config_input_json = os.path.join(BASE_DIR, 'conf/configIinputs.json')
75         with open(config_input_json, 'r') as openfile:
76             service_profile = self.request_json["serviceProfile"]
77             nst_solution_list = []
78             resource_name = "NST"
79             nst_object = json.load(openfile)
80             for nst in nst_object[resource_name]:
81                 [(nst_name, nst_list)] = nst.items()
82                 individual_nst = dict()
83                 matchall = False
84                 for constraint_name in service_profile:
85                     constraint_value = nst_list.get(constraint_name)
86                     if not constraint_value:
87                         matchall = False
88                         break
89                     else:
90                         matchall = True
91                 if matchall:
92                     individual_nst["NSTName"] = nst_list.get("name")
93                     individual_nst["UUID"] = nst_list.get("modeluuid")
94                     individual_nst["invariantUUID"] = nst_list.get("modelinvariantuuid")
95                     individual_nst["individual_nst"] = 1
96                     nst_solution_list.append(individual_nst)
97
98         return nst_solution_list
99
100     def get_nst_selection_response(self, solutions):
101         """Get NST selection response from final solution
102
103             :param solutions: final solutions
104             :return: NST selection response to send back as dictionary
105         """
106         return {'requestId': self.request_info['requestId'],
107                 'transactionId': self.request_info['transactionId'],
108                 'requestStatus': 'completed',
109                 'statusMessage': '',
110                 'solutions': solutions}
111
112     def error_response(self, error_message):
113         """Form response message from the error message
114
115             :param error_message: error message while processing the request
116             :return: response json as dictionary
117         """
118         return {'requestId': self.request_info['requestId'],
119                 'transactionId': self.request_info['transactionId'],
120                 'requestStatus': 'error',
121                 'statusMessage': error_message}