Adds support for OSMMON_DATABASE_COMMONKEY to decrypt vim passwords
[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 import logging
25
26 import requests
27 import yaml
28 from keystoneauth1 import session
29 from keystoneauth1.identity import v3
30 from keystoneclient.v3 import client
31
32 from osm_mon.core.auth import AuthManager
33 from osm_mon.core.settings import Config
34
35 __author__ = "Helena McGough"
36
37 log = logging.getLogger(__name__)
38 cfg = Config.instance()
39
40
41 class Common(object):
42 """Common calls for Gnocchi/Aodh plugins."""
43
44 def __init__(self):
45 """Create the common instance."""
46
47 @staticmethod
48 def get_auth_token(vim_uuid, verify_ssl=True):
49 """Authenticate and/or renew the authentication token."""
50 auth_manager = AuthManager()
51 creds = auth_manager.get_credentials(vim_uuid)
52 sess = session.Session(verify=verify_ssl)
53 ks = client.Client(session=sess)
54 token_dict = ks.get_raw_token_from_identity_service(auth_url=creds.url,
55 username=creds.user,
56 password=creds.password,
57 project_name=creds.tenant_name,
58 project_domain_id='default',
59 user_domain_id='default')
60 return token_dict['auth_token']
61
62 @staticmethod
63 def get_endpoint(service_type, vim_uuid, verify_ssl=True):
64 """
65 Gets the public endpoint for an OpenStack service in the configured region (default: RegionOne).
66 :param service_type: Service type name (eg. metric or alarming)
67 :param vim_uuid: VIM UUID generated by OSM
68 :param verify_ssl: If False, disables SSL validation. Useful when using self signed certs.
69 :return: Endpoint url string.
70
71 :raises ValueError If it can't find services, or if it can find services but no endpoint for specified region.
72 """
73 auth_manager = AuthManager()
74 creds = auth_manager.get_credentials(vim_uuid)
75 auth = v3.Password(auth_url=creds.url,
76 username=creds.user,
77 password=creds.password,
78 project_name=creds.tenant_name,
79 project_domain_id='default',
80 user_domain_id='default')
81 sess = session.Session(auth=auth, verify=verify_ssl)
82 ks = client.Client(session=sess, interface='public')
83 services = ks.services.list(type=service_type)
84 if not services:
85 raise ValueError("No services found for {}. Is the corresponding service enabled?".format(service_type))
86 service = services[0]
87 endpoints = ks.endpoints.list(service)
88 endpoint_type = 'publicURL'
89 region_name = 'RegionOne'
90 if creds.config is not None:
91 try:
92 config = json.loads(creds.config)
93 except ValueError:
94 config = yaml.safe_load(creds.config)
95 if 'endpoint_type' in config:
96 endpoint_type = config['endpoint_type']
97 if 'region_name' in config:
98 region_name = config['region_name']
99 for endpoint in endpoints:
100 if endpoint.interface in endpoint_type and endpoint.region == region_name:
101 return endpoint.url
102 raise ValueError("No endpoints found for service {} in region {}".format(service_type, region_name))
103
104 @staticmethod
105 def perform_request(url, auth_token,
106 req_type=None, payload=None, params=None, verify_ssl=True):
107 """Perform the POST/PUT/GET/DELETE request."""
108
109 timeout = cfg.REQUEST_TIMEOUT
110
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=timeout, verify=verify_ssl)
119 elif req_type == "get":
120 response = requests.get(
121 url, params=params, headers=headers, timeout=timeout, verify=verify_ssl)
122 elif req_type == "delete":
123 response = requests.delete(
124 url, headers=headers, timeout=timeout, verify=verify_ssl)
125 else:
126 response = requests.post(
127 url, data=payload, headers=headers,
128 timeout=timeout, verify=verify_ssl)
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
136 log.warning(
137 'Result: %s, %s',
138 response.status_code, response.text)
139 return response