1 # Copyright (C) 2021 Wind River Systems, Inc.
\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
7 # http://www.apache.org/licenses/LICENSE-2.0
\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
15 from o2ims.service.client.base_client import BaseClient
\r
16 from o2ims.domain.stx_object import StxGenericModel
\r
17 from o2ims.service.unit_of_work import AbstractUnitOfWork
\r
20 logger = logging.getLogger(__name__)
\r
23 class BaseWatcher(object):
\r
24 def __init__(self, client: BaseClient,
\r
25 uow: AbstractUnitOfWork) -> None:
\r
27 self._client = client
\r
30 def targetname(self) -> str:
\r
31 return self._targetname()
\r
33 def probe(self, parent: object = None):
\r
34 return self._probe(parent)
\r
36 def _probe(self, parent: object = None):
\r
37 raise NotImplementedError
\r
39 def _targetname(self):
\r
40 raise NotImplementedError
\r
42 def _compare_and_update(self, newmodel: StxGenericModel) -> bool:
\r
44 # localmodel = self._uow.stxobjects.get(ocloudmodel.id)
\r
45 localmodel = self._uow.stxobjects.get(str(newmodel.id))
\r
47 logger.info("add entry:" + newmodel.name)
\r
48 self._uow.stxobjects.add(newmodel)
\r
49 elif localmodel.is_outdated(newmodel):
\r
50 logger.info("update entry:" + newmodel.name)
\r
51 localmodel.update_by(newmodel)
\r
52 self._uow.stxobjects.update(localmodel)
\r
56 # node to organize watchers in tree hierachy
\r
57 class WatcherTree(object):
\r
58 def __init__(self, watcher: BaseWatcher) -> None:
\r
60 self.watcher = watcher
\r
63 def addchild(self, watcher: BaseWatcher) -> object:
\r
64 child = WatcherTree(watcher)
\r
65 self.children[watcher.targetname()] = child
\r
68 def removechild(self, targetname: str) -> object:
\r
69 return self.children.pop(targetname)
\r
71 # probe all resources by parent, depth = 0 for indefinite recursive
\r
72 def probe(self, parentresource=None, depth: int = 0):
\r
73 logger.debug("probe resources with watcher: "
\r
74 + self.watcher.targetname())
\r
75 childdepth = depth - 1 if depth > 0 else 0
\r
76 resources = self.watcher.probe(parentresource)
\r
77 logger.debug("probe returns " + str(len(resources)) + "resources")
\r
83 for res in resources:
\r
84 for targetname in self.children.keys():
\r
85 self.children[targetname].probe(res, childdepth)
\r