Create API to get log for each task
authorLinda Wang <wangwulin@huawei.com>
Tue, 22 Aug 2017 04:01:38 +0000 (04:01 +0000)
committerLinda Wang <wangwulin@huawei.com>
Fri, 25 Aug 2017 01:16:21 +0000 (01:16 +0000)
API: /api/v1/functest/tasks/<task_id>/log
METHOD: GET

JIRA: FUNCTEST-867

Change-Id: I987cbf662e4da349bf7583e48da5d981a2f1e0fd
Signed-off-by: Linda Wang <wangwulin@huawei.com>
functest/api/base.py
functest/api/resources/v1/tasks.py
functest/api/resources/v1/testcases.py
functest/api/urls.py

index ffc5678..75f059b 100644 (file)
@@ -45,6 +45,11 @@ class ApiResource(Resource):
 
         return action, args
 
+    def _get_args(self):  # pylint: disable=no-self-use
+        """ Convert the unicode to string for request.args """
+        args = api_utils.change_to_str_in_dict(request.args)
+        return args
+
     def _dispatch_post(self):
         """ Dispatch request """
         action, args = self._post_args()
index 7086e70..e05db51 100644 (file)
 Resources to retrieve the task results
 """
 
-
+import errno
 import json
 import logging
+import os
 import uuid
 
 from flask import jsonify
@@ -21,13 +22,14 @@ from flask import jsonify
 from functest.api.base import ApiResource
 from functest.api.common import api_utils
 from functest.api.database.v1.handlers import TasksHandler
+from functest.utils.constants import CONST
 
 
 LOGGER = logging.getLogger(__name__)
 
 
-class V1Tasks(ApiResource):
-    """ V1Tasks Resource class"""
+class V1Task(ApiResource):
+    """ V1Task Resource class"""
 
     def get(self, task_id):  # pylint: disable=no-self-use
         """ GET the result of the task id """
@@ -56,3 +58,38 @@ class V1Tasks(ApiResource):
             result = {'status': status, 'result': json.loads(task.result)}
 
         return jsonify(result)
+
+
+class V1TaskLog(ApiResource):
+    """ V1TaskLog Resource class"""
+
+    def get(self, task_id):  # pylint: disable=no-self-use
+        """ GET the log of the task id """
+        try:
+            uuid.UUID(task_id)
+        except ValueError:
+            return api_utils.result_handler(status=1, data='Invalid task id')
+
+        task_handler = TasksHandler()
+        try:
+            task = task_handler.get_task_by_taskid(task_id)
+        except ValueError:
+            return api_utils.result_handler(status=1, data='No such task id')
+
+        task_log_dir = CONST.__getattribute__('dir_results')
+
+        try:
+            with open(os.path.join(task_log_dir,
+                                   '{}.log'.format(task_id)), 'r') as log_file:
+                data = log_file.readlines()
+        except OSError as err:
+            if err.errno == errno.ENOENT:
+                return api_utils.result_handler(
+                    status=1, data='Log file does not exist')
+
+            return api_utils.result_handler(
+                status=1, data='Error with log file')
+
+        return_data = {'data': data}
+
+        return api_utils.result_handler(status=task.status, data=return_data)
index f146c24..d708cf3 100644 (file)
 Resources to handle testcase related requests
 """
 
-import os
 import logging
+import os
+import pkg_resources
 import uuid
 
+import ConfigParser
 from flask import abort, jsonify
 
 from functest.api.base import ApiResource
@@ -84,6 +86,7 @@ class V1Testcase(ApiResource):
         """ The built_in function to run a test case """
 
         case_name = args.get('testcase')
+        self._update_logging_ini(args.get('task_id'))
 
         if not os.path.isfile(CONST.__getattribute__('env_active')):
             raise Exception("Functest environment is not ready.")
@@ -113,3 +116,17 @@ class V1Testcase(ApiResource):
             }
 
             return {'result': result}
+
+    def _update_logging_ini(self, task_id):  # pylint: disable=no-self-use
+        """ Update the log file for each task"""
+        config = ConfigParser.RawConfigParser()
+        config.read(
+            pkg_resources.resource_filename('functest', 'ci/logging.ini'))
+        log_path = os.path.join(CONST.__getattribute__('dir_results'),
+                                '{}.log'.format(task_id))
+        config.set('handler_file', 'args', '("{}",)'.format(log_path))
+
+        with open(
+            pkg_resources.resource_filename(
+                'functest', 'ci/logging.ini'), 'wb') as configfile:
+            config.write(configfile)
index f7bcae3..72c2c53 100644 (file)
@@ -62,5 +62,9 @@ URLPATTERNS = [
 
     # GET /api/v1/functest/tasks/<task_id>
     # => GET the result of the task id
-    Url('/api/v1/functest/tasks/<task_id>', 'v1_tasks')
+    Url('/api/v1/functest/tasks/<task_id>', 'v1_task'),
+
+    # GET /api/v1/functest/tasks/<task_id>/log
+    # => GET the log of the task
+    Url('/api/v1/functest/tasks/<task_id>/log', 'v1_task_log')
 ]