Add subscription and notification for resource changes; fix a bug while pserver node...
[pti/o2.git] / o2common / service / watcher / worker.py
1 # Copyright (C) 2021 Wind River Systems, Inc.\r
2 #\r
3 #  Licensed under the Apache License, Version 2.0 (the "License");\r
4 #  you may not use this file except in compliance with the License.\r
5 #  You may obtain a copy of the License at\r
6 #\r
7 #      http://www.apache.org/licenses/LICENSE-2.0\r
8 #\r
9 #  Unless required by applicable law or agreed to in writing, software\r
10 #  distributed under the License is distributed on an "AS IS" BASIS,\r
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
12 #  See the License for the specific language governing permissions and\r
13 #  limitations under the License.\r
14 \r
15 import time\r
16 import sched\r
17 # from o2common.service.unit_of_work import AbstractUnitOfWork\r
18 from o2common.service.watcher.base import WatcherTree\r
19 \r
20 from o2common.helper import o2logging\r
21 logger = o2logging.get_logger(__name__)\r
22 \r
23 \r
24 class PollWorker(object):\r
25     def __init__(self, interval=10, bus=None) -> None:\r
26         super().__init__()\r
27         self.watchers = []\r
28         self.schedinstance = sched.scheduler(time.time, time.sleep)\r
29         self.schedinterval = interval\r
30         self._stopped = True\r
31         self._bus = bus\r
32 \r
33     def set_interval(self, interval):\r
34         if interval > 0:\r
35             self.schedinterval = interval\r
36         else:\r
37             raise Exception("Invalid interval:" + interval)\r
38 \r
39     def add_watcher(self, watcher: WatcherTree):\r
40         self.watchers.append(watcher)\r
41 \r
42     def _repeat(self):\r
43         logger.debug("_repeat started")\r
44         if self._stopped:\r
45             return\r
46         for w in self.watchers:\r
47             try:\r
48                 # logger.debug("about to probe:"+w)\r
49                 w.probe(None)\r
50             except Exception as ex:\r
51                 logger.warning("Worker raises exception:" + str(ex))\r
52                 continue\r
53 \r
54         # handle events\r
55         if self._bus is not None:\r
56             events = self._bus.uow.collect_new_events()\r
57             for event in events:\r
58                 self._bus.handle(event)\r
59 \r
60         self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
61 \r
62     # note the sched run will block current thread\r
63     def start(self):\r
64         self._stopped = False\r
65         logger.debug('about to start sched task')\r
66         self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
67         self.schedinstance.run()\r
68 \r
69     def stop(self):\r
70         self._stopped = True\r