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 ##############################################################################
19 from docker import Client
21 from yardstick.common import constants as config
22 from yardstick.common import utils as yardstick_utils
23 from yardstick.common.httpClient import HttpClient
24 from api import conf as api_conf
25 from api.utils import influx
26 from api.utils.common import result_handler
27 from api.database.handler import AsyncTaskHandler
29 logger = logging.getLogger(__name__)
30 logger.setLevel(logging.DEBUG)
33 def createGrafanaContainer(args):
34 task_id = str(uuid.uuid4())
36 thread = threading.Thread(target=_create_grafana, args=(task_id,))
39 return result_handler('success', {'task_id': task_id})
42 def _create_grafana(task_id):
45 client = Client(base_url=config.DOCKER_URL)
48 if not _check_image_exist(client, '%s:%s' % (config.GRAFANA_IMAGE,
49 config.GRAFANA_TAGS)):
50 client.pull(config.GRAFANA_IMAGE, config.GRAFANA_TAGS)
52 _create_grafana_container(client)
60 _update_task_status(task_id)
61 except Exception as e:
62 _update_task_error(task_id, str(e))
63 logger.debug('Error: %s', e)
66 def _create_dashboard():
67 url = 'http://admin:admin@%s:3000/api/dashboards/db' % api_conf.GATEWAY_IP
68 with open('../dashboard/ping_dashboard.json') as dashboard_json:
69 data = json.load(dashboard_json)
70 HttpClient().post(url, data)
73 def _create_data_source():
74 url = 'http://admin:admin@%s:3000/api/datasources' % api_conf.GATEWAY_IP
79 "url": "http://%s:8086" % api_conf.GATEWAY_IP,
82 "database": "yardstick",
84 "basicAuthUser": "admin",
85 "basicAuthPassword": "admin",
88 HttpClient().post(url, data)
91 def _create_grafana_container(client):
93 port_bindings = {k: k for k in ports}
94 host_config = client.create_host_config(port_bindings=port_bindings)
96 container = client.create_container(image='%s:%s' % (config.GRAFANA_IMAGE,
101 host_config=host_config)
102 client.start(container)
105 def _check_image_exist(client, t):
106 return any(t in a['RepoTags'][0] for a in client.images() if a['RepoTags'])
109 def createInfluxDBContainer(args):
110 task_id = str(uuid.uuid4())
112 thread = threading.Thread(target=_create_influxdb, args=(task_id,))
115 return result_handler('success', {'task_id': task_id})
118 def _create_influxdb(task_id):
119 _create_task(task_id)
121 client = Client(base_url=config.DOCKER_URL)
124 _change_output_to_influxdb()
126 if not _check_image_exist(client, '%s:%s' % (config.INFLUXDB_IMAGE,
127 config.INFLUXDB_TAG)):
128 client.pull(config.INFLUXDB_IMAGE, tag=config.INFLUXDB_TAG)
130 _create_influxdb_container(client)
136 _update_task_status(task_id)
137 except Exception as e:
138 _update_task_error(task_id, str(e))
139 logger.debug('Error: %s', e)
142 def _create_influxdb_container(client):
145 port_bindings = {k: k for k in ports}
146 host_config = client.create_host_config(port_bindings=port_bindings)
148 container = client.create_container(image='%s:%s' % (config.INFLUXDB_IMAGE,
149 config.INFLUXDB_TAG),
153 host_config=host_config)
154 client.start(container)
157 def _config_influxdb():
159 client = influx.get_data_db_client()
160 client.create_user(config.USER, config.PASSWORD, config.DATABASE)
161 client.create_database(config.DATABASE)
162 logger.info('Success to config influxDB')
163 except Exception as e:
164 logger.debug('Failed to config influxDB: %s', e)
167 def _change_output_to_influxdb():
168 yardstick_utils.makedirs(config.YARDSTICK_CONFIG_DIR)
170 parser = ConfigParser.ConfigParser()
171 parser.read(config.YARDSTICK_CONFIG_SAMPLE_FILE)
173 parser.set('DEFAULT', 'dispatcher', 'influxdb')
174 parser.set('dispatcher_influxdb', 'target',
175 'http://%s:8086' % api_conf.GATEWAY_IP)
177 with open(config.YARDSTICK_CONFIG_FILE, 'w') as f:
181 def prepareYardstickEnv(args):
182 task_id = str(uuid.uuid4())
184 thread = threading.Thread(target=_prepare_env_daemon, args=(task_id,))
187 return result_handler('success', {'task_id': task_id})
190 def _prepare_env_daemon(task_id):
191 _create_task(task_id)
193 installer_ip = os.environ.get('INSTALLER_IP', 'undefined')
194 installer_type = os.environ.get('INSTALLER_TYPE', 'undefined')
197 _check_variables(installer_ip, installer_type)
199 _create_directories()
201 rc_file = config.OPENSTACK_RC_FILE
203 _get_remote_rc_file(rc_file, installer_ip, installer_type)
205 _source_file(rc_file)
207 _append_external_network(rc_file)
209 # update the external_network
210 _source_file(rc_file)
216 _update_task_status(task_id)
217 except Exception as e:
218 _update_task_error(task_id, str(e))
219 logger.debug('Error: %s', e)
222 def _check_variables(installer_ip, installer_type):
224 if installer_ip == 'undefined':
225 raise SystemExit('Missing INSTALLER_IP')
227 if installer_type == 'undefined':
228 raise SystemExit('Missing INSTALLER_TYPE')
229 elif installer_type not in config.INSTALLERS:
230 raise SystemExit('INSTALLER_TYPE is not correct')
233 def _create_directories():
234 yardstick_utils.makedirs(config.YARDSTICK_CONFIG_DIR)
237 def _source_file(rc_file):
238 yardstick_utils.source_env(rc_file)
241 def _get_remote_rc_file(rc_file, installer_ip, installer_type):
243 os_fetch_script = os.path.join(config.RELENG_DIR, config.OS_FETCH_SCRIPT)
246 cmd = [os_fetch_script, '-d', rc_file, '-i', installer_type,
248 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
251 if p.returncode != 0:
252 logger.debug('Failed to fetch credentials from installer')
254 if e.errno != errno.EEXIST:
258 def _append_external_network(rc_file):
259 neutron_client = yardstick_utils.get_neutron_client()
260 networks = neutron_client.list_networks()['networks']
262 ext_network = next(n['name'] for n in networks if n['router:external'])
263 except StopIteration:
264 logger.warning("Can't find external network")
266 cmd = 'export EXTERNAL_NETWORK=%s' % ext_network
268 with open(rc_file, 'a') as f:
271 if e.errno != errno.EEXIST:
276 cmd = [config.CLEAN_IMAGES_SCRIPT]
277 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
278 cwd=config.YARDSTICK_REPOS_DIR)
279 output = p.communicate()[0]
280 logger.debug('The result is: %s', output)
284 cmd = [config.LOAD_IMAGES_SCRIPT]
285 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
286 cwd=config.YARDSTICK_REPOS_DIR)
287 output = p.communicate()[0]
288 logger.debug('The result is: %s', output)
291 def _create_task(task_id):
292 async_handler = AsyncTaskHandler()
297 async_handler.insert(task_dict)
300 def _update_task_status(task_id):
301 async_handler = AsyncTaskHandler()
303 task = async_handler.get_task_by_taskid(task_id)
304 async_handler.update_status(task, 1)
307 def _update_task_error(task_id, error):
308 async_handler = AsyncTaskHandler()
310 task = async_handler.get_task_by_taskid(task_id)
311 async_handler.update_status(task, 2)
312 async_handler.update_error(task, error)