Refactored the Aodh notifier class
[osm/MON.git] / osm_mon / plugins / OpenStack / common.py
1 # Copyright 2017 Intel Research and Development Ireland Limited
2 # *************************************************************
3
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Intel Corporation
6
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10
11 # http://www.apache.org/licenses/LICENSE-2.0
12
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact: helena.mcgough@intel.com or adrian.hoban@intel.com
21 ##
22 """Common methods for the OpenStack plugins."""
23 import json
24
25 import logging
26
27 from keystoneclient.v3 import client
28
29 from plugins.OpenStack.settings import Config
30
31 import requests
32
33 __author__ = "Helena McGough"
34
35 log = logging.getLogger(__name__)
36
37
38 class Common(object):
39 """Common calls for Gnocchi/Aodh plugins."""
40
41 def __init__(self):
42 """Create the common instance."""
43 self._auth_token = None
44 self._ks = None
45 self.openstack_url = None
46 self.user = None
47 self.password = None
48 self.tenant = None
49
50 def _authenticate(self, message=None):
51 """Authenticate and/or renew the authentication token."""
52 if self._auth_token is not None:
53 return self._auth_token
54
55 if message is not None:
56 values = json.loads(message.value)['access_config']
57 self.openstack_url = values['openstack_site']
58 self.user = values['user']
59 self.password = values['password']
60 self.tenant = values['vim_tenant_name']
61
62 try:
63 # try to authenticate with supplied access_credentials
64 self._ks = client.Client(auth_url=self.openstack_url,
65 username=self.user,
66 password=self.password,
67 tenant_name=self.tenant)
68 self._auth_token = self._ks.auth_token
69 log.info("Authenticating with access_credentials from SO.")
70 return self._auth_token
71 except Exception as exc:
72 log.warn("Authentication failed with access_credentials: %s",
73 exc)
74
75 else:
76 log.info("Access_credentials were not sent from SO.")
77
78 # If there are no access_credentials or they fail use env variables
79 try:
80 cfg = Config.instance()
81 self._ks = client.Client(auth_url=cfg.OS_AUTH_URL,
82 username=cfg.OS_USERNAME,
83 password=cfg.OS_PASSWORD,
84 tenant_name=cfg.OS_TENANT_NAME)
85 log.info("Authenticating with environment varialbles.")
86 self._auth_token = self._ks.auth_token
87 except Exception as exc:
88
89 log.warn("Authentication failed: %s", exc)
90
91 self._auth_token = None
92
93 return self._auth_token
94
95 def get_endpoint(self, service_type):
96 """Get the endpoint for Gnocchi/Aodh."""
97 try:
98 return self._ks.service_catalog.url_for(
99 service_type=service_type,
100 endpoint_type='internalURL',
101 region_name='RegionOne')
102 except Exception as exc:
103 log.warning("Failed to retreive endpoint for service due to: %s",
104 exc)
105 return None
106
107 @classmethod
108 def _perform_request(cls, url, auth_token,
109 req_type=None, payload=None, params=None):
110 """Perform the POST/PUT/GET/DELETE request."""
111 # request headers
112 headers = {'X-Auth-Token': auth_token,
113 'Content-type': 'application/json'}
114 # perform request and return its result
115 if req_type == "put":
116 response = requests.put(
117 url, data=payload, headers=headers,
118 timeout=1)
119 elif req_type == "get":
120 response = requests.get(
121 url, params=params, headers=headers, timeout=1)
122 elif req_type == "delete":
123 response = requests.delete(
124 url, headers=headers, timeout=1)
125 else:
126 response = requests.post(
127 url, data=payload, headers=headers,
128 timeout=1)
129
130 # Raises exception if there was an error
131 try:
132 response.raise_for_status()
133 # pylint: disable=broad-except
134 except Exception:
135 # Log out the result of the request for debugging purpose
136 log.debug(
137 'Result: %s, %s',
138 response.status_code, response.text)
139 return response