d0fc75dd3681b29ce43109c0614fb302cd8832e1
[yardstick.git] / yardstick / cmd / commands / env.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
3 #
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 print_function
10 import time
11 import os
12 import sys
13
14 from yardstick.common.httpClient import HttpClient
15 from yardstick.common import constants as consts
16
17
18 class EnvCommand(object):
19     '''
20
21         Set of commands to prepare environment
22     '''
23     def do_influxdb(self, args):
24         data = {'action': 'createInfluxDBContainer'}
25         task_id = self._start_async_task(data)
26
27         start = '* creating influxDB'
28         self._check_status(task_id, start)
29
30     def do_grafana(self, args):
31         data = {'action': 'createGrafanaContainer'}
32         task_id = self._start_async_task(data)
33
34         start = '* creating grafana'
35         self._check_status(task_id, start)
36
37     def do_prepare(self, args):
38         data = {'action': 'prepareYardstickEnv'}
39         task_id = self._start_async_task(data)
40
41         start = '* preparing yardstick environment'
42         self._check_status(task_id, start)
43
44     def _start_async_task(self, data):
45         url = consts.ENV_ACTION_API
46         return HttpClient().post(url, data)['result']['task_id']
47
48     def _check_status(self, task_id, start):
49         self._print_status(start, '[]\r')
50         url = '{}?task_id={}'.format(consts.ASYNC_TASK_API, task_id)
51
52         CHECK_STATUS_RETRY = 20
53         CHECK_STATUS_DELAY = 5
54
55         for retry in xrange(CHECK_STATUS_RETRY):
56             response = HttpClient().get(url)
57             status = response['status']
58
59             if status:
60                 break
61
62             # wait until the async task finished
63             time.sleep(CHECK_STATUS_DELAY * (retry + 1))
64
65         switcher = {
66             0: 'Timeout',
67             1: 'Finished',
68             2: 'Error'
69         }
70         self._print_status(start, '[{}]'.format(switcher[status]))
71         if status == 2:
72             print(response['result'])
73             sys.stdout.flush()
74         return status
75
76     def _print_status(self, s, e):
77         try:
78             columns = int(os.popen('stty size', 'r').read().split()[1])
79             word = '{}{}{}'.format(s, ' ' * (columns - len(s) - len(e)), e)
80             sys.stdout.write(word)
81             sys.stdout.flush()
82         except IndexError:
83             pass