6971c6dfe86fc73c7a718a69f7561016f5187816
[yardstick.git] / api / utils / common.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 collections
10 import logging
11
12 from flask import jsonify
13
14 from api.utils.daemonthread import DaemonThread
15 from yardstick.cmd.cli import YardstickCLI
16
17 logger = logging.getLogger(__name__)
18
19
20 def translate_to_str(object):
21     if isinstance(object, collections.Mapping):
22         return {str(k): translate_to_str(v) for k, v in object.items()}
23     elif isinstance(object, list):
24         return [translate_to_str(ele) for ele in object]
25     elif isinstance(object, unicode):
26         return str(object)
27     return object
28
29
30 def get_command_list(command_list, opts, args):
31
32     command_list.append(args)
33
34     command_list.extend(('--{}'.format(k) for k in opts if 'task-args' != k))
35
36     task_args = opts.get('task-args', '')
37     if task_args:
38         command_list.extend(['--task-args', str(task_args)])
39
40     return command_list
41
42
43 def exec_command_task(command_list, task_dict):   # pragma: no cover
44     daemonthread = DaemonThread(YardstickCLI().api, (command_list, task_dict))
45     daemonthread.start()
46
47
48 def error_handler(message):
49     logger.debug(message)
50     result = {
51         'status': 'error',
52         'message': message
53     }
54     return jsonify(result)
55
56
57 def result_handler(status, data):
58     result = {
59         'status': status,
60         'result': data
61     }
62     return jsonify(result)
63
64
65 class Url(object):
66
67     def __init__(self, url, resource, endpoint):
68         super(Url, self).__init__()
69         self.url = url
70         self.resource = resource
71         self.endpoint = endpoint