Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / server / cmactivatorworker.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import logging
15 from threading import Thread
16
17
18 class CMActivatorWorker(Thread):
19     def __init__(self, activator, index, lock, parallel=False):
20         super(CMActivatorWorker, self).__init__()
21
22         self.activator = activator
23         self.index = index
24         self.lock = lock
25         self.parallel = parallel
26
27         self.daemon = True
28
29     def __str__(self):
30         return 'worker-{}'.format(self.index)
31
32     def _handle_work(self, work):
33         logging.debug('%s handling work: %s', self, work)
34         failures = {}
35         for handler in self.activator.get_handlers():
36             try:
37                 logging.info('%s activating using %s', self, handler.__class__.__name__)
38                 handler_failures = handler.activate(work)
39                 if handler_failures:
40                     logging.error('%s activation failed, error count=%s',
41                                   self,
42                                   len(handler_failures))
43                     failures[handler.__class__.__name__] = handler_failures
44             except Exception as exp:  # pylint: disable=broad-except
45                 logging.error('%s activation failed with error %s', self, str(exp))
46                 failures[handler.__class__.__name__] = str(exp)
47
48         logging.debug('%s handled work: %s', self, work)
49
50         work.add_result(failures)
51
52     def run(self):
53         while True:
54             if self.parallel:
55                 work = self.activator.get_parallel_work()
56                 with self.lock.reader():
57                     self._handle_work(work)
58             else:
59                 work = self.activator.get_work()
60                 with self.lock.writer():
61                     self._handle_work(work)