1 # Copyright (C) 2021 Wind River Systems, Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # from logging import exception
16 # from cgtsclient import exc
17 from o2common.service.client.base_client import BaseClient
18 from o2common.domain import commands
19 from o2common.service.messagebus import MessageBus
20 from o2common.helper import o2logging
21 logger = o2logging.get_logger(__name__)
24 class BaseWatcher(object):
25 def __init__(self, client: BaseClient,
26 bus: MessageBus) -> None:
33 def targetname(self) -> str:
34 return self._targetname()
36 def probe(self, parent: commands.Command = None, tags: object = None):
39 parent.data if parent else None, tags)
43 # return self._probe(parent)
45 except Exception as ex:
46 logger.warning("Failed to probe resource due to: " + str(ex))
49 def _probe(self, parent: object = None, tags: object = None) \
51 raise NotImplementedError
53 def _targetname(self):
54 raise NotImplementedError
56 # def _compare_and_update(self, newmodel: StxGenericModel) -> bool:
58 # # localmodel = self._uow.stxobjects.get(ocloudmodel.id)
59 # localmodel = self._uow.stxobjects.get(str(newmodel.id))
61 # logger.info("add entry:" + newmodel.name)
62 # self._uow.stxobjects.add(newmodel)
63 # elif localmodel.is_outdated(newmodel):
64 # logger.info("update entry:" + newmodel.name)
65 # localmodel.update_by(newmodel)
66 # self._uow.stxobjects.update(localmodel)
70 # node to organize watchers in tree hierachy
71 class WatcherTree(object):
72 def __init__(self, watcher: BaseWatcher) -> None:
74 self.watcher = watcher
78 def addchild(self, watcher: BaseWatcher) -> object:
79 child = WatcherTree(watcher)
80 self.children[watcher.targetname()] = child
83 def removechild(self, targetname: str) -> object:
84 return self.children.pop(targetname)
86 # probe all resources by parent, depth = 0 for indefinite recursive
87 def probe(self, parentresource=None, depth: int = 0, tags: object = None):
88 logger.debug("probe resources with watcher: "
89 + self.watcher.targetname())
90 childdepth = depth - 1 if depth > 0 else 0
91 resources = self.watcher.probe(parentresource, tags)
92 logger.debug("probe returns " + str(len(resources)) + " resources")
93 if self.watcher._tags is not None:
94 tags = self.watcher._tags
100 for res in resources:
101 for targetname in self.children.keys():
102 self.children[targetname].probe(res, childdepth, tags)