Add ocloud watcher and tests
[pti/o2.git] / o2ims / service / watcher / base.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 from o2ims.service.client.base_client import BaseClient\r
16 from o2ims.domain.stx_object import StxGenericModel\r
17 from o2ims.adapter.ocloud_repository import OcloudRepository\r
18 \r
19 \r
20 class InvalidOcloudState(Exception):\r
21     pass\r
22 \r
23 \r
24 class BaseWatcher(object):\r
25     def __init__(self, client: BaseClient) -> None:\r
26         super().__init__()\r
27         self._client = client\r
28 \r
29     def probe(self):\r
30         self._probe()\r
31 \r
32     def _probe(self):\r
33         pass\r
34 \r
35 \r
36 class OcloudWather(BaseWatcher):\r
37     def __init__(self, ocloud_client: BaseClient,\r
38                  repo: OcloudRepository) -> None:\r
39         super().__init__(ocloud_client)\r
40         self._repo = repo\r
41 \r
42     def _probe(self):\r
43         ocloudmodel = self._client.get(None)\r
44         if ocloudmodel:\r
45             self._compare_and_update(ocloudmodel)\r
46 \r
47     def _compare_and_update(self, ocloudmodel: StxGenericModel) -> bool:\r
48         # localmodel = self._repo.get(ocloudmodel.id)\r
49         oclouds = self._repo.list()\r
50         if len(oclouds) > 1:\r
51             raise InvalidOcloudState("More than 1 ocloud is found")\r
52         if len(oclouds) == 0:\r
53             self._repo.add(ocloudmodel)\r
54         else:\r
55             localmodel = oclouds.pop()\r
56             if localmodel.is_outdated(ocloudmodel):\r
57                 localmodel.update_by(ocloudmodel)\r
58                 self._repo.update(localmodel)\r
59 \r
60 \r
61 class ResourcePoolWatcher(object):\r
62     def __init__(self) -> None:\r
63         super().__init__()\r
64 \r
65 \r
66 class ResourceWatcher(object):\r
67     def __init__(self) -> None:\r
68         super().__init__()\r