3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
20 API_NAME = 'resthandler'
21 LOG = logging.getLogger(__name__)
23 def make_instance(instance):
24 return RestRequest(instance)
26 class RestRequest(object):
27 """ RestRequest object
28 This module can be used in the context of hostcli rest implementations.
30 def take_action(self, parsed_args):
31 req = self.app.client_manager.resthandler
32 ret = req.get("has/v1/cluster", decode_json=True)
34 columns = ('admin-state',
38 data = (status['admin-state'],
39 status['running-state'],
42 return (columns, data)
44 This module will fill the needed information for authentication.
45 The authentication will be based on keystone.
47 The object will fill the prefix to the request. So it's not mandatory
48 to write it. This information will be populated from the endpoint of rest frame.
50 def __init__(self, app_instance):
51 self.instance = app_instance
52 if self.instance._auth_required:
53 self.token = self.instance.auth_ref.auth_token
54 self.auth_ref = self.instance.auth_ref
55 self.url = self.auth_ref.service_catalog.url_for(service_type="restfulapi",
56 service_name="restfulframework",
57 interface=self.instance.interface)
59 if 'OS_REST_URL' in os.environ:
60 self.url = os.environ['OS_REST_URL']
62 raise Exception("OS_REST_URL environment variable missing")
64 def get(self, url, data=None, params=None, decode_json=True):
65 return self._operation("get", url, data=data, params=params, decode_json=decode_json)
67 def post(self, url, data=None, params=None, decode_json=True):
68 return self._operation("post", url, data=data, params=params, decode_json=decode_json)
70 def put(self, url, data=None, params=None, decode_json=True):
71 return self._operation("put", url, data=data, params=params, decode_json=decode_json)
73 def patch(self, url, data=None, params=None, decode_json=True):
74 return self._operation("patch", url, data=data, params=params, decode_json=decode_json)
76 def delete(self, url, data=None, params=None, decode_json=True):
77 return self._operation("delete", url, data=data, params=params, decode_json=decode_json)
79 def _operation(self, oper, url, data=None, params=None, decode_json=True):
81 operation = getattr(requests, oper, None)
84 raise NameError("Operation %s not found" % oper)
86 if not url.startswith("http"):
87 url = self.url + '/' + url
89 LOG.debug("Working with url %s" % url)
91 # Disable request debug logs
92 logging.getLogger("requests").setLevel(logging.WARNING)
94 # HACK:Check if the authentication will expire and if so then renew it
95 if self.instance._auth_required and self.auth_ref.will_expire_soon():
96 LOG.debug("Session will expire soon... Renewing token")
97 self.instance._auth_setup_completed = False
98 self.instance._auth_ref = None
99 self.token = self.instance.auth_ref.auth_token
101 LOG.debug("Session is solid. Using existing token.")
103 # Add security headers
105 headers = {'User-Agent': 'HostCli'}
107 if self.instance._auth_required:
108 headers.update({'X-Auth-Token': self.token})
111 if isinstance(data, dict):
112 arguments["json"] = data
113 headers["Content-Type"] = "application/json"
115 arguments["data"] = data
116 headers["Content-Type"] = "text/plain"
118 arguments["headers"] = headers
121 arguments["params"] = params
123 ret = operation(url, **arguments)
126 ret.raise_for_status()