1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from __future__ import absolute_import
20 from six.moves import configparser
21 from oslo_serialization import jsonutils
23 from api import conf as api_conf
24 from api.database.handler import AsyncTaskHandler
25 from api.utils import influx
26 from api.utils.common import result_handler
27 from docker import Client
28 from yardstick.common import constants as config
29 from yardstick.common import utils as yardstick_utils
30 from yardstick.common.httpClient import HttpClient
32 logger = logging.getLogger(__name__)
33 logger.setLevel(logging.DEBUG)
36 def createGrafanaContainer(args):
37 task_id = str(uuid.uuid4())
39 thread = threading.Thread(target=_create_grafana, args=(task_id,))
42 return result_handler('success', {'task_id': task_id})
45 def _create_grafana(task_id):
48 client = Client(base_url=config.DOCKER_URL)
51 if not _check_image_exist(client, '%s:%s' % (config.GRAFANA_IMAGE,
52 config.GRAFANA_TAGS)):
53 client.pull(config.GRAFANA_IMAGE, config.GRAFANA_TAGS)
55 _create_grafana_container(client)
63 _update_task_status(task_id)
64 except Exception as e:
65 _update_task_error(task_id, str(e))
66 logger.debug('Error: %s', e)
69 def _create_dashboard():
70 url = 'http://admin:admin@%s:3000/api/dashboards/db' % api_conf.GATEWAY_IP
71 path = os.path.join(config.YARDSTICK_REPOS_DIR, 'dashboard',
74 for i in sorted(glob.iglob(path)):
76 data = jsonutils.load(f)
77 HttpClient().post(url, data)
80 def _create_data_source():
81 url = 'http://admin:admin@%s:3000/api/datasources' % api_conf.GATEWAY_IP
86 "url": "http://%s:8086" % api_conf.GATEWAY_IP,
89 "database": "yardstick",
91 "basicAuthUser": "admin",
92 "basicAuthPassword": "admin",
95 HttpClient().post(url, data)
98 def _create_grafana_container(client):
100 port_bindings = {k: k for k in ports}
101 host_config = client.create_host_config(port_bindings=port_bindings)
103 container = client.create_container(image='%s:%s' % (config.GRAFANA_IMAGE,
104 config.GRAFANA_TAGS),
108 host_config=host_config)
109 client.start(container)
112 def _check_image_exist(client, t):
113 return any(t in a['RepoTags'][0] for a in client.images() if a['RepoTags'])
116 def createInfluxDBContainer(args):
117 task_id = str(uuid.uuid4())
119 thread = threading.Thread(target=_create_influxdb, args=(task_id,))
122 return result_handler('success', {'task_id': task_id})
125 def _create_influxdb(task_id):
126 _create_task(task_id)
128 client = Client(base_url=config.DOCKER_URL)
131 _change_output_to_influxdb()
133 if not _check_image_exist(client, '%s:%s' % (config.INFLUXDB_IMAGE,
134 config.INFLUXDB_TAG)):
135 client.pull(config.INFLUXDB_IMAGE, tag=config.INFLUXDB_TAG)
137 _create_influxdb_container(client)
143 _update_task_status(task_id)
144 except Exception as e:
145 _update_task_error(task_id, str(e))
146 logger.debug('Error: %s', e)
149 def _create_influxdb_container(client):
152 port_bindings = {k: k for k in ports}
153 host_config = client.create_host_config(port_bindings=port_bindings)
155 container = client.create_container(image='%s:%s' % (config.INFLUXDB_IMAGE,
156 config.INFLUXDB_TAG),
160 host_config=host_config)
161 client.start(container)
164 def _config_influxdb():
166 client = influx.get_data_db_client()
167 client.create_user(config.USER, config.PASSWORD, config.DATABASE)
168 client.create_database(config.DATABASE)
169 logger.info('Success to config influxDB')
170 except Exception as e:
171 logger.debug('Failed to config influxDB: %s', e)
174 def _change_output_to_influxdb():
175 yardstick_utils.makedirs(config.YARDSTICK_CONFIG_DIR)
177 parser = configparser.ConfigParser()
178 parser.read(config.YARDSTICK_CONFIG_SAMPLE_FILE)
180 parser.set('DEFAULT', 'dispatcher', 'influxdb')
181 parser.set('dispatcher_influxdb', 'target',
182 'http://%s:8086' % api_conf.GATEWAY_IP)
184 with open(config.YARDSTICK_CONFIG_FILE, 'w') as f:
188 def prepareYardstickEnv(args):
189 task_id = str(uuid.uuid4())
191 thread = threading.Thread(target=_prepare_env_daemon, args=(task_id,))
194 return result_handler('success', {'task_id': task_id})
197 def _prepare_env_daemon(task_id):
198 _create_task(task_id)
200 installer_ip = os.environ.get('INSTALLER_IP', 'undefined')
201 installer_type = os.environ.get('INSTALLER_TYPE', 'undefined')
204 _check_variables(installer_ip, installer_type)
206 _create_directories()
208 rc_file = config.OPENSTACK_RC_FILE
210 _get_remote_rc_file(rc_file, installer_ip, installer_type)
212 _source_file(rc_file)
214 _append_external_network(rc_file)
216 # update the external_network
217 _source_file(rc_file)
223 _update_task_status(task_id)
224 except Exception as e:
225 _update_task_error(task_id, str(e))
226 logger.debug('Error: %s', e)
229 def _check_variables(installer_ip, installer_type):
231 if installer_ip == 'undefined':
232 raise SystemExit('Missing INSTALLER_IP')
234 if installer_type == 'undefined':
235 raise SystemExit('Missing INSTALLER_TYPE')
236 elif installer_type not in config.INSTALLERS:
237 raise SystemExit('INSTALLER_TYPE is not correct')
240 def _create_directories():
241 yardstick_utils.makedirs(config.YARDSTICK_CONFIG_DIR)
244 def _source_file(rc_file):
245 yardstick_utils.source_env(rc_file)
248 def _get_remote_rc_file(rc_file, installer_ip, installer_type):
250 os_fetch_script = os.path.join(config.RELENG_DIR, config.OS_FETCH_SCRIPT)
253 cmd = [os_fetch_script, '-d', rc_file, '-i', installer_type,
255 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
258 if p.returncode != 0:
259 logger.debug('Failed to fetch credentials from installer')
261 if e.errno != errno.EEXIST:
265 def _append_external_network(rc_file):
266 neutron_client = yardstick_utils.get_neutron_client()
267 networks = neutron_client.list_networks()['networks']
269 ext_network = next(n['name'] for n in networks if n['router:external'])
270 except StopIteration:
271 logger.warning("Can't find external network")
273 cmd = 'export EXTERNAL_NETWORK=%s' % ext_network
275 with open(rc_file, 'a') as f:
278 if e.errno != errno.EEXIST:
283 cmd = [config.CLEAN_IMAGES_SCRIPT]
284 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
285 cwd=config.YARDSTICK_REPOS_DIR)
286 output = p.communicate()[0]
287 logger.debug('The result is: %s', output)
291 cmd = [config.LOAD_IMAGES_SCRIPT]
292 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
293 cwd=config.YARDSTICK_REPOS_DIR)
294 output = p.communicate()[0]
295 logger.debug('The result is: %s', output)
298 def _create_task(task_id):
299 async_handler = AsyncTaskHandler()
304 async_handler.insert(task_dict)
307 def _update_task_status(task_id):
308 async_handler = AsyncTaskHandler()
310 task = async_handler.get_task_by_taskid(task_id)
311 async_handler.update_status(task, 1)
314 def _update_task_error(task_id, error):
315 async_handler = AsyncTaskHandler()
317 task = async_handler.get_task_by_taskid(task_id)
318 async_handler.update_status(task, 2)
319 async_handler.update_error(task, error)