Update O2app start with global ocloud ID 22/9322/5
authorZhang Rong(Jon) <rong.zhang@windriver.com>
Mon, 17 Oct 2022 15:14:32 +0000 (23:14 +0800)
committerBin Yang <bin.yang@windriver.com>
Thu, 20 Oct 2022 03:07:32 +0000 (03:07 +0000)
Issue-ID: INF-316

Signed-off-by: Zhang Rong(Jon) <rong.zhang@windriver.com>
Change-Id: If7e9d078494bd95e62a36dc9698a010348c3bcf9

configs/o2app.conf [new file with mode: 0644]
o2common/config/__init__.py
o2common/config/base.py [new file with mode: 0644]
o2common/config/config.py
o2ims/service/auditor/ocloud_handler.py
tests/unit/test_watcher.py
tox.ini

diff --git a/configs/o2app.conf b/configs/o2app.conf
new file mode 100644 (file)
index 0000000..2fab3ba
--- /dev/null
@@ -0,0 +1,11 @@
+[DEFAULT]
+
+ocloud_global_id = 4e24b97c-8c49-4c4f-b53e-3de5235a4e37
+smo_url = http://127.0.0.1:8090/register
+
+[API]
+test = "hello"
+
+[WATCHER]
+
+[PUBSUB]
index 813897e..e3004d4 100644 (file)
 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 #  See the License for the specific language governing permissions and
 #  limitations under the License.
+
+from o2common.config.base import Config
+from o2common.config.config import get_config_path
+
+
+conf = Config()
+conf.load(get_config_path())
diff --git a/o2common/config/base.py b/o2common/config/base.py
new file mode 100644 (file)
index 0000000..af49f30
--- /dev/null
@@ -0,0 +1,139 @@
+# Copyright (C) 2022 Wind River Systems, Inc.
+#
+#  Licensed under the Apache License, Version 2.0 (the "License");
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+import os
+import configparser
+
+
+class Error(Exception):
+    """Base class for cfg exceptions."""
+
+    def __init__(self, msg=None):
+        self.msg = msg
+
+    def __str__(self):
+        return self.msg
+
+
+class NoSuchOptError(Error, AttributeError):
+    """Raised if an opt which doesn't exist is referenced."""
+
+    def __init__(self, opt_name, group=None):
+        self.opt_name = opt_name
+        self.group = group
+
+    def __str__(self):
+        group_name = 'DEFAULT' if self.group is None else self.group.name
+        return "no such option %s in group [%s]" % (self.opt_name, group_name)
+
+
+class NoSuchConfigFile(Error):
+    """Raised if the config file does not exist."""
+
+    def __init__(self, file_path):
+        self.file_path = file_path
+
+    def __str__(self):
+        return "no such file %s exist" % self.file_path
+
+
+class Section:
+    def __init__(self, section: str) -> None:
+        self.group_name = section
+        self._options = {}
+
+    def _set(self, name, value):
+        opt = getattr(self, name)
+        if opt is None:
+            setattr(self, name, value)
+        if name not in self._options:
+            self._options[name] = value
+
+    def _get(self, name):
+        name = name.lower()
+        if name in self._options:
+            return self._options[name]
+
+    def __getattr__(self, name):
+        try:
+            return self._get(name)
+        except ValueError:
+            raise
+        except Exception:
+            raise NoSuchOptError(name, self.group_name)
+
+
+class Config:
+    def __init__(self) -> None:
+        self.__cache = {'b': 456}
+        self._sections = {}
+
+    def _set(self, section, name='', value=''):
+        group = getattr(self, section)
+        if group is None:
+            group = Section(section)
+            setattr(self, section, group)
+        if section not in self._sections:
+            self._sections[section] = group
+        if name != '':
+            setattr(group, name, value)
+        return group
+
+    def _get(self, name):
+        if name in self._sections:
+            return self._sections(name)
+
+        if name in self.__cache:
+            return self.__cache(name)
+
+    def __getattr__(self, name):
+        try:
+            return self._get(name)
+        except ValueError:
+            raise
+        except Exception:
+            raise NoSuchOptError(name)
+
+    def load(self, file_path):
+        if not os.path.exists(file_path):
+            raise NoSuchConfigFile(file_path)
+        conf = configparser.ConfigParser()
+        conf.read(file_path)
+        default_group = self._set('DEFAULT')
+        for option in conf['DEFAULT']:
+            print(option)
+            default_group._set(option, conf['DEFAULT'][option])
+        for section in conf.sections():
+            group = self._set(section)
+            for option in conf[section]:
+                group._set(option, conf[section][option])
+
+
+if __name__ == "__main__":
+    conf = Config()
+    # conf._set('default', 'a', 123)
+
+    # print(conf.default.a)
+    # print(conf.b)
+
+    # conf = configparser.ConfigParser()
+    # conf.read('configs/o2app.conf')
+    # print(conf)
+    # print(conf['DEFAULT'].__dict__)
+    # print(conf['DEFAULT']['test'])
+    conf.load('configs/o2app.conf')
+    print(conf.API.test)
+    print(conf.DEFAULT.test)
+    print(conf.PUBSUB.ooo)
+    print(conf.DEFAULT.oCloudGlobalID)
index e42c886..d3a076d 100644 (file)
@@ -24,6 +24,11 @@ _DEFAULT_DCMANAGER_URL = "http://192.168.204.1:8119/v1.0"
 _DEFAULT_STX_URL = "http://192.168.204.1:5000/v3"
 
 
+def get_config_path():
+    path = os.environ.get("O2APP_CONFIG", "/configs/o2app.conf")
+    return path
+
+
 def get_postgres_uri():
     host = os.environ.get("DB_HOST", "localhost")
     port = 54321 if host == "localhost" else 5432
index 4cc8ec7..d1e2fa7 100644 (file)
@@ -20,7 +20,7 @@ from __future__ import annotations
 # from typing import List, Dict, Callable, Type
 # TYPE_CHECKING
 
-from o2common.config import config
+from o2common.config import config, conf
 # from o2common.service.messagebus import MessageBus
 from o2common.service.unit_of_work import AbstractUnitOfWork
 from o2ims.domain import events, commands
@@ -82,13 +82,18 @@ def is_outdated(ocloud: Ocloud, stxobj: StxGenericModel):
 
 def create_by(stxobj: StxGenericModel) -> Ocloud:
     imsendpoint = config.get_api_url() + config.get_o2ims_api_base() + '/'
-    globalcloudId = stxobj.id  # to be updated
+    globalcloudId = conf.DEFAULT.ocloud_global_id
     description = "An ocloud"
     ocloud = Ocloud(stxobj.id, stxobj.name, imsendpoint,
                     globalcloudId, description, 1)
     ocloud.createtime = stxobj.createtime
     ocloud.updatetime = stxobj.updatetime
     ocloud.hash = stxobj.hash
+    ocloud.events.append(events.OcloudChanged(
+        id=stxobj.id,
+        notificationEventType=NotificationEventEnum.CREATE,
+        updatetime=stxobj.updatetime
+    ))
 
     return ocloud
 
index 5b1f5b4..4bb707f 100644 (file)
@@ -136,12 +136,12 @@ def create_fake_bus(uow):
             publish: Callable):
         return
 
-    fakeuow = FakeUnitOfWork()
+    fakeuow = FakeUnitOfWork()
     handlers.EVENT_HANDLERS = {}
     handlers.COMMAND_HANDLERS = {
         commands.UpdateOCloud: update_ocloud,
     }
-    bus = bootstrap.bootstrap(False, fakeuow)
+    bus = bootstrap.bootstrap(False, uow)
     return bus
 
 
diff --git a/tox.ini b/tox.ini
index 03f379c..14651d8 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -36,6 +36,8 @@ commands =
     flake8 o2common
 
 [testenv:code]
+setenv =
+        O2APP_CONFIG=configs/o2app.conf
 commands =
     pytest tests/unit