Merge "subprocess.call para stdout=PIPE is risky"
[yardstick.git] / api / resources / results.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 import logging
10 import uuid
11 import re
12
13 from api.utils import influx as influx_utils
14 from api.utils import common as common_utils
15 from api import conf
16
17 logger = logging.getLogger(__name__)
18
19
20 def default(args):
21     return getResult(args)
22
23
24 def getResult(args):
25     try:
26         measurement = args['measurement']
27         task_id = args['task_id']
28
29         if re.search("[^a-zA-Z0-9_-]", measurement):
30             raise ValueError('invalid measurement parameter')
31
32         uuid.UUID(task_id)
33     except KeyError:
34         message = 'measurement and task_id must be provided'
35         return common_utils.error_handler(message)
36
37     query_template = "select * from %s where task_id='%s'"
38     query_sql = query_template % ('tasklist', task_id)
39     data = common_utils.translate_to_str(influx_utils.query(query_sql))
40
41     def _unfinished():
42         return common_utils.result_handler(0, [])
43
44     def _finished():
45         query_sql = query_template % (conf.TEST_CASE_PRE + measurement,
46                                       task_id)
47         data = common_utils.translate_to_str(influx_utils.query(query_sql))
48         if not data:
49             query_sql = query_template % (measurement, task_id)
50             data = common_utils.translate_to_str(influx_utils.query(query_sql))
51
52         return common_utils.result_handler(1, data)
53
54     def _error():
55         return common_utils.result_handler(2, data[0]['error'])
56
57     try:
58         status = data[0]['status']
59
60         switcher = {
61             0: _unfinished,
62             1: _finished,
63             2: _error
64         }
65         return switcher.get(status, lambda: 'nothing')()
66     except IndexError:
67         return common_utils.error_handler('no such task')