Add subscription and notification for resource changes; fix a bug while pserver node...
[pti/o2.git] / o2ims / service / event / notify_handler.py
diff --git a/o2ims/service/event/notify_handler.py b/o2ims/service/event/notify_handler.py
new file mode 100644 (file)
index 0000000..3ece84a
--- /dev/null
@@ -0,0 +1,99 @@
+# Copyright (C) 2021 Wind River Systems, Inc.\r
+#\r
+#  Licensed under the Apache License, Version 2.0 (the "License");\r
+#  you may not use this file except in compliance with the License.\r
+#  You may obtain a copy of the License at\r
+#\r
+#      http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+#  Unless required by applicable law or agreed to in writing, software\r
+#  distributed under the License is distributed on an "AS IS" BASIS,\r
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+#  See the License for the specific language governing permissions and\r
+#  limitations under the License.\r
+\r
+import json\r
+import redis\r
+# import requests\r
+import http.client\r
+from urllib.parse import urlparse\r
+\r
+from o2common.config import config\r
+from o2common.service.unit_of_work import AbstractUnitOfWork\r
+from o2ims.domain import commands\r
+from o2ims.domain.subscription_obj import Subscription, Message2SMO\r
+\r
+from o2common.helper import o2logging\r
+logger = o2logging.get_logger(__name__)\r
+\r
+# Maybe another MQ server\r
+r = redis.Redis(**config.get_redis_host_and_port())\r
+\r
+\r
+def notify_change_to_smo(\r
+    cmd: commands.PubMessage2SMO,\r
+    uow: AbstractUnitOfWork,\r
+):\r
+    logger.info('In notify_change_to_smo')\r
+    data = cmd.data\r
+    with uow:\r
+        subs = uow.subscriptions.list()\r
+        for sub in subs:\r
+            sub_data = sub.serialize()\r
+            logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))\r
+\r
+            try:\r
+                resource_filter = json.loads(sub_data['filter'])\r
+                if len(resource_filter) > 0:\r
+                    resource = uow.resources.get(data.id)\r
+                    logger.debug(type(resource))\r
+                    if resource:  # TODO deal with resource is empty\r
+                        res_type_id = resource.serialize()['resourceTypeId']\r
+                        resourcetype = uow.resource_types.get(res_type_id)\r
+                        logger.debug(resourcetype.name)\r
+                        if resourcetype.name not in resource_filter:\r
+                            continue\r
+            except json.decoder.JSONDecodeError as err:\r
+                logger.warning(\r
+                    'subscription filter decode json failed: {}'.format(err))\r
+\r
+            callback_smo(sub, data)\r
+\r
+\r
+def callback_smo(sub: Subscription, msg: Message2SMO):\r
+    sub_data = sub.serialize()\r
+    callback_data = json.dumps({\r
+        'consumerSubscriptionId': sub_data['consumerSubscriptionId'],\r
+        'notificationEventType': msg.notificationEventType,\r
+        'objectRef': msg.objectRef,\r
+        'updateTime': msg.updatetime\r
+    })\r
+    logger.info('URL: {}, data: {}'.format(\r
+        sub_data['callback'], callback_data))\r
+    # r.publish(sub_data['subscriptionId'], json.dumps({\r
+    #     'consumerSubscriptionId': sub_data['consumerSubscriptionId'],\r
+    #     'notificationEventType': msg.notificationEventType,\r
+    #     'objectRef': msg.objectRef\r
+    # }))\r
+    # try:\r
+    #     headers = {'User-Agent': 'Mozilla/5.0'}\r
+    #     resp = requests.post(sub_data['callback'], data=callback_data,\r
+    #                          headers=headers)\r
+    #     if resp.status_code == 202 or resp.status_code == 200:\r
+    #         logger.info('Notify to SMO successed')\r
+    #         return\r
+    #     logger.error('Response code is: {}'.format(resp.status_code))\r
+    # except requests.exceptions.HTTPError as err:\r
+    #     logger.error('request smo error: {}'.format(err))\r
+    o = urlparse(sub_data['callback'])\r
+    conn = http.client.HTTPConnection(o.netloc)\r
+    headers = {'Content-type': 'application/json'}\r
+    conn.request('POST', o.path, callback_data, headers)\r
+    resp = conn.getresponse()\r
+    data = resp.read().decode('utf-8')\r
+    # json_data = json.loads(data)\r
+    if resp.status == 202 or resp.status == 200:\r
+        logger.info('Notify to SMO successed, response code {} {}, data {}'.\r
+                    format(resp.status, resp.reason, data))\r
+        return\r
+    logger.error('Response code is: {}'.format(resp.status))\r