Merge "Add ML based optimization to PCI opt"
[optf/osdf.git] / osdf / adapters / conductor / conductor.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #   Copyright (C) 2020 Wipro Limited.
4 #
5 #   Licensed under the Apache License, Version 2.0 (the "License");
6 #   you may not use this file except in compliance with the License.
7 #   You may obtain a copy of the License at
8 #
9 #       http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #   Unless required by applicable law or agreed to in writing, software
12 #   distributed under the License is distributed on an "AS IS" BASIS,
13 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #   See the License for the specific language governing permissions and
15 #   limitations under the License.
16 #
17 # -------------------------------------------------------------------------
18 #
19
20 import json
21
22 from requests import RequestException
23 import time
24
25 from osdf.adapters.conductor.api_builder import conductor_api_builder
26 from osdf.logging.osdf_logging import debug_log
27 from osdf.utils.interfaces import RestClient
28 from osdf.operation.exceptions import BusinessException
29
30
31 def request(req_info, demands, request_parameters, service_info, location_enabled,
32             osdf_config, flat_policies):
33     config = osdf_config.deployment
34     local_config = osdf_config.core
35     uid, passwd = config['conductorUsername'], config['conductorPassword']
36     conductor_url = config['conductorUrl']
37     req_id = req_info["requestId"]
38     transaction_id = req_info['transactionId']
39     headers = dict(transaction_id=transaction_id)
40     placement_ver_enabled = config.get('placementVersioningEnabled', False)
41
42     if placement_ver_enabled:
43         cond_minor_version = config.get('conductorMinorVersion', None)
44         if cond_minor_version is not None:
45             x_minor_version = str(cond_minor_version)
46             headers.update({'X-MinorVersion': x_minor_version})
47             debug_log.debug("Versions set in HTTP header to "
48                             "conductor: X-MinorVersion: {} ".format(x_minor_version))
49
50     max_retries = config.get('conductorMaxRetries', 30)
51     ping_wait_time = config.get('conductorPingWaitTime', 60)
52
53     rc = RestClient(userid=uid, passwd=passwd, method="GET", log_func=debug_log.debug,
54                     headers=headers)
55     conductor_req_json_str = conductor_api_builder(req_info, demands, request_parameters,
56                                                    service_info, location_enabled, flat_policies,
57                                                    local_config)
58     conductor_req_json = json.loads(conductor_req_json_str)
59
60     debug_log.debug("Sending first Conductor request for request_id {}".format(req_id))
61
62     resp, raw_resp = initial_request_to_conductor(rc, conductor_url, conductor_req_json)
63     # Very crude way of keeping track of time.
64     # We are not counting initial request time, first call back, or time for HTTP request
65     total_time, ctr = 0, 2
66     client_timeout = req_info['timeout']
67     configured_timeout = max_retries * ping_wait_time
68     max_timeout = min(client_timeout, configured_timeout)
69
70     while True:  # keep requesting conductor till we get a result or we run out of time
71         if resp is not None:
72             if resp["plans"][0].get("status") in ["error"]:
73                 raise RequestException(response=raw_resp, request=raw_resp.request)
74
75             if resp["plans"][0].get("status") in ["done", "not found"]:
76                 return resp
77             new_url = resp['plans'][0]['links'][0][0]['href']  # TODO: check why a list of lists
78
79         if total_time >= max_timeout:
80             raise BusinessException("Conductor could not provide a solution within {} seconds,"
81                                     "this transaction is timing out".format(max_timeout))
82         time.sleep(ping_wait_time)
83         ctr += 1
84         debug_log.debug("Attempt number {} url {}; prior status={}"
85                         .format(ctr, new_url, resp['plans'][0]['status']))
86         total_time += ping_wait_time
87
88         try:
89             raw_resp = rc.request(new_url, raw_response=True)
90             resp = raw_resp.json()
91         except RequestException as e:
92             debug_log.debug("Conductor attempt {} for request_id {} has failed because {}"
93                             .format(ctr, req_id, str(e)))
94
95
96 def initial_request_to_conductor(rc, conductor_url, conductor_req_json):
97     """First steps in the request-redirect chain in making a call to Conductor
98     :param rc: REST client object for calling conductor
99     :param conductor_url: conductor's base URL to submit a placement request
100     :param conductor_req_json: request json object to send to Conductor
101     :return: URL to check for follow up (similar to redirects);
102              we keep checking these till we get a result/error
103     """
104     debug_log.debug("Payload to Conductor: {}".format(json.dumps(conductor_req_json)))
105     raw_resp = rc.request(url=conductor_url, raw_response=True, method="POST",
106                           json=conductor_req_json)
107     resp = raw_resp.json()
108     if resp["status"] != "template":
109         raise RequestException(response=raw_resp, request=raw_resp.request)
110     time.sleep(10)  # 10 seconds wait time to avoid being too quick!
111     plan_url = resp["links"][0][0]["href"]
112     debug_log.debug("Attempting to read the plan from "
113                     "the conductor provided url {}".format(plan_url))
114     raw_resp = rc.request(raw_response=True,
115                           url=plan_url)  # TODO: check why a list of lists for links
116     resp = raw_resp.json()
117
118     if resp["plans"][0]["status"] in ["error"]:
119         raise RequestException(response=raw_resp, request=raw_resp.request)
120     return resp, raw_resp  # now the caller of this will handle further follow-ups