0049834eba889b0ce7780f17741b7d448a44ffd9
[yardstick.git] / api / utils / daemonthread.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 absolute_import
10 import threading
11 import os
12 import errno
13
14 from api import conf
15 from api.database.handlers import TasksHandler
16
17
18 class DaemonThread(threading.Thread):
19
20     def __init__(self, method, args):
21         super(DaemonThread, self).__init__(target=method, args=args)
22         self.method = method
23         self.command_list = args[0]
24         self.task_dict = args[1]
25
26     def run(self):
27         self.task_dict['status'] = 0
28         task_id = self.task_dict['task_id']
29
30         try:
31             task_handler = TasksHandler()
32             task = task_handler.insert(self.task_dict)
33
34             self.method(self.command_list, task_id)
35
36             task_handler.update_status(task, 1)
37         except Exception as e:
38             task_handler.update_status(task, 2)
39             task_handler.update_error(task, str(e))
40         finally:
41             _handle_testsuite_file(task_id)
42
43
44 def _handle_testsuite_file(task_id):
45     try:
46         os.remove(os.path.join(conf.TEST_SUITE_PATH, task_id + '.yaml'))
47     except OSError as e:
48         if e.errno != errno.ENOENT:
49             raise