Add cps client to PCI app
[optf/osdf.git] / apps / pci / optimizers / pci_opt_processor.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2018 AT&T 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 import traceback
20
21 from onaplogging.mdcContext import MDC
22 from requests import RequestException
23
24 from apps.pci.optimizers.config_request import request as config_request
25 from apps.pci.optimizers.solver.optimizer import pci_optimize as optimize
26 from apps.pci.optimizers.solver.pci_utils import get_cell_id
27 from apps.pci.optimizers.solver.pci_utils import get_pci_value
28 from osdf.logging.osdf_logging import error_log
29 from osdf.logging.osdf_logging import metrics_log
30 from osdf.logging.osdf_logging import MH
31 from osdf.operation.error_handling import build_json_error_body
32 from osdf.utils.interfaces import get_rest_client
33 from osdf.utils.mdc_utils import mdc_from_json
34
35 """
36 This application generates PCI Optimization API calls using the information received from PCI-Handler-MS, SDN-C
37 and Policy.
38 """
39
40
41 def process_pci_optimation(request_json, osdf_config, flat_policies):
42     """Process a PCI request from a Client (build config-db, policy and  API call, make the call, return result)
43
44     :param req_object: Request parameters from the client
45     :param osdf_config: Configuration specific to OSDF application (core + deployment)
46     :param flat_policies: policies related to pci (fetched based on request)
47     :return: response from PCI Opt
48     """
49     try:
50         mdc_from_json(request_json)
51         rc = get_rest_client(request_json, service="pcih")
52         req_id = request_json["requestInfo"]["requestId"]
53         cell_info_list, network_cell_info = config_request(request_json, osdf_config, flat_policies)
54         pci_response = get_solutions(cell_info_list, network_cell_info, request_json)
55
56         metrics_log.info(MH.inside_worker_thread(req_id))
57     except Exception as err:
58         error_log.error("Error for {} {}".format(req_id, traceback.format_exc()))
59
60         try:
61             body = build_json_error_body(err)
62             metrics_log.info(MH.sending_response(req_id, "ERROR"))
63             rc.request(json=body, noresponse=True)
64         except RequestException:
65             MDC.put('requestID', req_id)
66             error_log.error("Error sending asynchronous notification for {} {}".format(req_id, traceback.format_exc()))
67         raise err
68
69     try:
70         metrics_log.info(MH.calling_back_with_body(req_id, rc.url, pci_response))
71         error_log.error("pci response: {}".format(str(pci_response)))
72         rc.request(json=pci_response, noresponse=True)
73     except RequestException:  # can't do much here but log it and move on
74         error_log.error("Error sending asynchronous notification for {} {}".format(req_id, traceback.format_exc()))
75
76
77 def get_solutions(cell_info_list, network_cell_info, request_json):
78     status, pci_solutions, anr_solutions = build_solution_list(cell_info_list, network_cell_info, request_json)
79     return {
80         "transactionId": request_json['requestInfo']['transactionId'],
81         "requestId": request_json["requestInfo"]["requestId"],
82         "requestStatus": "completed",
83         "statusMessage": status,
84         "solutions": {
85             'networkId': request_json['cellInfo']['networkId'],
86             'pciSolutions': pci_solutions,
87             'anrSolutions': anr_solutions
88         }
89     }
90
91
92 def build_solution_list(cell_info_list, network_cell_info, request_json):
93     status = "success"
94     req_id = request_json["requestInfo"]["requestId"]
95     pci_solutions = []
96     anr_solutions = []
97     try:
98         opt_solution = optimize(network_cell_info, cell_info_list, request_json)
99         if opt_solution == 'UNSATISFIABLE':
100             status = 'inconsistent input'
101             return status, pci_solutions, anr_solutions
102         else:
103             pci_solutions = build_pci_solution(network_cell_info, opt_solution['pci'])
104             anr_solutions = build_anr_solution(network_cell_info, opt_solution.get('removables', {}))
105     except RuntimeError:
106         error_log.error("Failed finding solution for {} {}".format(req_id, traceback.format_exc()))
107         status = "failed"
108     return status, pci_solutions, anr_solutions
109
110
111 def build_pci_solution(network_cell_info, pci_solution):
112     pci_solutions = []
113     for k, v in pci_solution.items():
114         old_pci = get_pci_value(network_cell_info, k)
115         if old_pci != v:
116             response = {
117                 'cellId': get_cell_id(network_cell_info, k),
118                 'pci': v
119             }
120             pci_solutions.append(response)
121     return pci_solutions
122
123
124 def build_anr_solution(network_cell_info, removables):
125     anr_solutions = []
126     for k, v in removables.items():
127         response = {
128             'cellId': get_cell_id(network_cell_info, k),
129             'removeableNeighbors': list(map(lambda x: get_cell_id(network_cell_info, x), v))
130         }
131         anr_solutions.append(response)
132     return anr_solutions