68ce4e68adb245c31ffe54a9a5f026d879610789
[osm/MON.git] / plugins / OpenStack / common.py
1 """Common methods for the Aodh Sender/Receiver."""
2
3 import logging as log
4
5 from keystoneclient.v3 import client
6
7 from plugins.OpenStack.settings import Config
8
9 import requests
10
11 # from keystoneauth1.identity.v3 import AuthMethod
12 # from keystoneclient.service_catalog import ServiceCatalog
13
14
15 class Common(object):
16 """Common calls for Gnocchi/Aodh plugins."""
17
18 def __init__(self):
19 """Create the common instance."""
20 self._auth_token = None
21 self._endpoint = None
22 self._ks = None
23
24 def _authenticate(self, tenant_id=None):
25 """Authenticate and/or renew the authentication token."""
26 if self._auth_token is not None:
27 return self._auth_token
28
29 try:
30 cfg = Config.instance()
31 self._ks = client.Client(auth_url=cfg.OS_AUTH_URL,
32 username=cfg.OS_USERNAME,
33 password=cfg.OS_PASSWORD,
34 tenant_name=cfg.OS_TENANT_NAME)
35 self._auth_token = self._ks.auth_token
36 except Exception as exc:
37
38 log.warn("Authentication failed with the following exception: %s",
39 exc)
40 self._auth_token = None
41
42 return self._auth_token
43
44 def get_endpoint(self, service_type):
45 """Get the endpoint for Gnocchi/Aodh."""
46 try:
47 return self._ks.service_catalog.url_for(
48 service_type=service_type,
49 endpoint_type='internalURL',
50 region_name='RegionOne')
51 except Exception as exc:
52 log.warning("Failed to retreive endpoint for Aodh due to: %s",
53 exc)
54 return None
55
56 @classmethod
57 def _perform_request(cls, url, auth_token,
58 req_type=None, payload=None, params=None):
59 """Perform the POST/PUT/GET/DELETE request."""
60 # request headers
61 headers = {'X-Auth-Token': auth_token,
62 'Content-type': 'application/json'}
63 # perform request and return its result
64 response = None
65 try:
66 if req_type == "put":
67 response = requests.put(
68 url, data=payload, headers=headers,
69 timeout=1)
70 elif req_type == "post":
71 response = requests.post(
72 url, data=payload, headers=headers,
73 timeout=1)
74 elif req_type == "get":
75 response = requests.get(
76 url, params=params, headers=headers, timeout=1)
77 elif req_type == "delete":
78 response = requests.delete(
79 url, headers=headers, timeout=1)
80 else:
81 log.warn("Invalid request type")
82
83 except Exception as e:
84 log.warn("Exception thrown on request", e)
85
86 return response