Add support to process NSI selection request
[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 from requests import RequestException
22 import time
23
24 from osdf.adapters.conductor.api_builder import conductor_api_builder
25 from osdf.logging.osdf_logging import debug_log
26 from osdf.operation.exceptions import BusinessException
27 from osdf.utils.interfaces import RestClient
28
29
30 def request(req_info, demands, request_parameters, service_info, template_fields,
31             osdf_config, flat_policies):
32     config = osdf_config.deployment
33     local_config = osdf_config.core
34     uid, passwd = config['conductorUsername'], config['conductorPassword']
35     conductor_url = config['conductorUrl']
36     req_id = req_info["requestId"]
37     transaction_id = req_info['transactionId']
38     headers = dict(transaction_id=transaction_id)
39     placement_ver_enabled = config.get('placementVersioningEnabled', False)
40
41     if placement_ver_enabled:
42         cond_minor_version = config.get('conductorMinorVersion', None)
43         if cond_minor_version is not None:
44             x_minor_version = str(cond_minor_version)
45             headers.update({'X-MinorVersion': x_minor_version})
46             debug_log.debug("Versions set in HTTP header to "
47                             "conductor: X-MinorVersion: {} ".format(x_minor_version))
48
49     max_retries = config.get('conductorMaxRetries', 30)
50     ping_wait_time = config.get('conductorPingWaitTime', 60)
51
52     rc = RestClient(userid=uid, passwd=passwd, method="GET", log_func=debug_log.debug,
53                     headers=headers)
54     conductor_req_json_str = conductor_api_builder(req_info, demands, request_parameters,
55                                                    service_info, template_fields, flat_policies,
56                                                    local_config)
57     conductor_req_json = json.loads(conductor_req_json_str)
58
59     debug_log.debug("Sending first Conductor request for request_id {}".format(req_id))
60
61     resp, raw_resp = initial_request_to_conductor(rc, conductor_url, conductor_req_json)
62     # Very crude way of keeping track of time.
63     # We are not counting initial request time, first call back, or time for HTTP request
64     total_time, ctr = 0, 2
65     client_timeout = req_info['timeout']
66     configured_timeout = max_retries * ping_wait_time
67     max_timeout = min(client_timeout, configured_timeout)
68
69     while True:  # keep requesting conductor till we get a result or we run out of time
70         if resp is not None:
71             if resp["plans"][0].get("status") in ["error"]:
72                 raise RequestException(response=raw_resp, request=raw_resp.request)
73
74             if resp["plans"][0].get("status") in ["done", "not found"]:
75                 return resp
76             new_url = resp['plans'][0]['links'][0][0]['href']  # TODO(krishna): check why a list of lists
77
78         if total_time >= max_timeout:
79             raise BusinessException("Conductor could not provide a solution within {} seconds,"
80                                     "this transaction is timing out".format(max_timeout))
81         time.sleep(ping_wait_time)
82         ctr += 1
83         debug_log.debug("Attempt number {} url {}; prior status={}"
84                         .format(ctr, new_url, resp['plans'][0]['status']))
85         total_time += ping_wait_time
86
87         try:
88             raw_resp = rc.request(new_url, raw_response=True)
89             resp = raw_resp.json()
90         except RequestException as e:
91             debug_log.debug("Conductor attempt {} for request_id {} has failed because {}"
92                             .format(ctr, req_id, str(e)))
93
94
95 def initial_request_to_conductor(rc, conductor_url, conductor_req_json):
96     """First steps in the request-redirect chain in making a call to Conductor
97
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)
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