Remove ca-cert from docker image
[optf/osdf.git] / osdf / utils / interfaces.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 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 json
20 import requests
21 import yaml
22
23 from osdf.config.base import creds_prefixes
24 from osdf.config.base import osdf_config
25 from osdf.logging.osdf_logging import debug_log
26 from osdf.logging.osdf_logging import MH
27
28
29 def get_rest_client(request_json, service):
30     """Get a RestClient based on request_json's callback URL and osdf_config's credentials based on service name
31
32     :param request_json:
33     :param service: so or cm
34     :return: rc -- RestClient
35     """
36     callback_url = request_json["requestInfo"]["callbackUrl"]
37     prefix = creds_prefixes[service]
38     config = osdf_config.deployment
39     c_userid, c_passwd = config[prefix + "Username"], config[prefix + "Password"]
40     return RestClient(url=callback_url, userid=c_userid, passwd=c_passwd)
41
42
43 def json_from_file(file_name):
44     """Read a policy from a file"""
45     with open(file_name) as fid:
46         return json.load(fid)
47
48
49 def yaml_from_file(file_name):
50     """Read a policy from a file"""
51     with open(file_name) as fid:
52         return yaml.load(fid)
53
54
55 class RestClient(object):
56     """Simple REST Client that supports get/post and basic auth"""
57
58     def __init__(self, userid=None, passwd=None, log_func=None, url=None, timeout=None, headers=None,
59                  method="POST", req_id=None, verify=None):
60         self.auth = (userid, passwd) if userid and passwd else None
61         self.headers = headers if headers else {}
62         self.method = method
63         self.url = url
64         self.log_func = log_func
65         self.timeout = (30, 90) if timeout is None else timeout
66         self.req_id = req_id
67         self.verify = verify
68
69     def add_headers(self, headers):
70         self.headers.update(headers)
71
72     def request(self, url=None, method=None, asjson=True, ok_codes=(2, ),
73                 raw_response=False, noresponse=False, timeout=None, **kwargs):
74         """Sends http request to the specified url
75
76         :param url: REST end point to query
77         :param method: GET or POST (default is None => self.method)
78         :param asjson: whether the expected response is in json format
79         :param ok_codes: expected codes (prefix matching -- e.g. can be (20, 21, 32) or (2, 3))
80         :param noresponse: If no response is expected (as long as response codes are OK)
81         :param raw_response: If we need just the raw response (e.g. conductor sends transaction IDs in headers)
82         :param timeout: Connection and read timeouts
83         :param kwargs: Other parameters
84         :return:
85         """
86         if not self.req_id:
87             debug_log.debug("Requesting URL: {}".format(url or self.url))
88         else:
89             debug_log.debug("Requesting URL: {} for request ID: {}".format(url or self.url, self.req_id))
90
91         if not url:
92             url = self.url
93         if not self.verify and url.startswith("https"):
94             verify = osdf_config.deployment["aaf_ca_certs"]
95         else:
96             verify = self.verify
97
98         res = requests.request(url=url or self.url, method=method or self.method,
99                                auth=self.auth, headers=self.headers,
100                                timeout=timeout or self.timeout, verify=verify, **kwargs)
101
102         if self.log_func:
103             self.log_func(MH.received_http_response(res))
104
105         res_code = str(res.status_code)
106         if not any(res_code.startswith(x) for x in map(str, ok_codes)):
107             raise res.raise_for_status()
108
109         if raw_response:
110             return res
111         elif noresponse:
112             return None
113         elif asjson:
114             return res.json()
115         else:
116             return res.content