3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
11 Resources to retrieve the task results
20 from flask import jsonify
21 from flasgger.utils import swag_from
24 from functest.api.base import ApiResource
25 from functest.api.common import api_utils
26 from functest.api.database.v1.handlers import TasksHandler
27 from functest.utils import config
30 LOGGER = logging.getLogger(__name__)
33 class V1Task(ApiResource):
34 """ V1Task Resource class"""
36 @swag_from(pkg_resources.resource_filename(
37 'functest', 'api/swagger/task.yaml'))
38 def get(self, task_id): # pylint: disable=no-self-use
39 """ GET the result of the task id """
43 return api_utils.result_handler(status=1, data='Invalid task id')
45 task_handler = TasksHandler()
47 task = task_handler.get_task_by_taskid(task_id)
49 return api_utils.result_handler(status=1, data='No such task id')
52 LOGGER.debug('Task status is: %s', status)
54 if status not in ['IN PROGRESS', 'FAIL', 'FINISHED']:
55 return api_utils.result_handler(status=1,
56 data='internal server error')
58 switcher = {'IN PROGRESS': 0, 'FAIL': 1, 'FINISHED': 2}
59 if status == 'IN PROGRESS':
60 result = {'status': switcher.get(status), 'result': ''}
61 elif status == 'FAIL':
62 result = {'status': switcher.get(status), 'error': task.error}
64 result = {'status': switcher.get(status),
65 'result': json.loads(task.result)}
67 return jsonify(result)
70 class V1TaskLog(ApiResource):
71 """ V1TaskLog Resource class"""
73 @swag_from(pkg_resources.resource_filename(
74 'functest', 'api/swagger/task_log.yaml'))
75 def get(self, task_id): # pylint: disable=no-self-use
76 """ GET the log of the task id """
80 return api_utils.result_handler(status=1, data='Invalid task id')
82 task_handler = TasksHandler()
84 task = task_handler.get_task_by_taskid(task_id)
86 return api_utils.result_handler(status=1, data='No such task id')
88 task_log_dir = getattr(config.CONF, 'dir_results')
89 # pylint: disable=maybe-no-member
90 index = int(self._get_args().get('index', 0))
93 with open(os.path.join(task_log_dir,
94 '{}.log'.format(task_id)), 'r') as log_file:
96 data = log_file.readlines()
97 index = log_file.tell()
98 except OSError as err:
99 if err.errno == errno.ENOENT:
100 return api_utils.result_handler(
101 status=1, data='Log file does not exist')
103 return api_utils.result_handler(
104 status=1, data='Error with log file')
106 return_data = {'data': data, 'index': index}
108 switcher = {'IN PROGRESS': 0, 'FAIL': 1, 'FINISHED': 2}
110 return api_utils.result_handler(status=switcher.get(task.status),