blob: 7df78d247f570972e8e218a9f5d8b0ad3adf4f68 [file] [log] [blame]
tierno932499c2019-01-28 17:28:10 +00001# -*- coding: utf-8 -*-
2
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
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
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
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17This module implements a thread that reads from kafka bus implementing all the subscriptions.
18It is based on asyncio.
19To avoid race conditions it uses same engine class as the main module for database changes
20For the moment this module only deletes NS instances when they are terminated with the autoremove flag
21"""
22
23import logging
24import threading
25import asyncio
26from http import HTTPStatus
27from osm_common import dbmongo, dbmemory, msglocal, msgkafka
28from osm_common.dbbase import DbException
29from osm_common.msgbase import MsgException
30from engine import EngineException
31
32__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
33
34
35class SubscriptionException(Exception):
36
37 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
38 self.http_code = http_code
39 Exception.__init__(self, message)
40
41
42class SubscriptionThread(threading.Thread):
43
44 def __init__(self, config, engine):
45 """
46 Constructor of class
47 :param config: configuration parameters of database and messaging
48 :param engine: an instance of Engine class, used for deleting instances
49 """
50 threading.Thread.__init__(self)
tierno65ca36d2019-02-12 19:27:52 +010051 self.to_terminate = False
tierno932499c2019-01-28 17:28:10 +000052 self.config = config
53 self.db = None
54 self.msg = None
55 self.engine = engine
56 self.loop = None
57 self.logger = logging.getLogger("nbi.subscriptions")
58 self.aiomain_task = None # asyncio task for receiving kafka bus
59 self.internal_session = { # used for a session to the engine methods
60 "_id": "subscription",
61 "id": "subscription",
62 "project_id": "admin",
63 "admin": True
64 }
65
66 def run(self):
67 """
68 Start of the thread
69 :return: None
70 """
71 self.loop = asyncio.new_event_loop()
72 try:
73 if not self.db:
74 if self.config["database"]["driver"] == "mongo":
75 self.db = dbmongo.DbMongo()
76 self.db.db_connect(self.config["database"])
77 elif self.config["database"]["driver"] == "memory":
78 self.db = dbmemory.DbMemory()
79 self.db.db_connect(self.config["database"])
80 else:
81 raise SubscriptionException("Invalid configuration param '{}' at '[database]':'driver'".format(
82 self.config["database"]["driver"]))
83 if not self.msg:
84 config_msg = self.config["message"].copy()
85 config_msg["loop"] = self.loop
86 if config_msg["driver"] == "local":
87 self.msg = msglocal.MsgLocal()
88 self.msg.connect(config_msg)
89 elif config_msg["driver"] == "kafka":
90 self.msg = msgkafka.MsgKafka()
91 self.msg.connect(config_msg)
92 else:
93 raise SubscriptionException("Invalid configuration param '{}' at '[message]':'driver'".format(
94 config_msg["driver"]))
95
96 except (DbException, MsgException) as e:
97 raise SubscriptionException(str(e), http_code=e.http_code)
98
99 self.logger.debug("Starting")
tierno65ca36d2019-02-12 19:27:52 +0100100 while not self.to_terminate:
tierno932499c2019-01-28 17:28:10 +0000101 try:
Felipe Vicens09e65422019-01-22 15:06:46 +0100102 self.aiomain_task = asyncio.ensure_future(self.msg.aioread(("ns", "nsi"), loop=self.loop,
tierno932499c2019-01-28 17:28:10 +0000103 callback=self._msg_callback),
104 loop=self.loop)
105 self.loop.run_until_complete(self.aiomain_task)
tierno65ca36d2019-02-12 19:27:52 +0100106 # except asyncio.CancelledError:
107 # break # if cancelled it should end, breaking loop
tierno932499c2019-01-28 17:28:10 +0000108 except Exception as e:
tierno65ca36d2019-02-12 19:27:52 +0100109 if not self.to_terminate:
110 self.logger.exception("Exception '{}' at messaging read loop".format(e), exc_info=True)
tierno932499c2019-01-28 17:28:10 +0000111
112 self.logger.debug("Finishing")
113 self._stop()
114 self.loop.close()
115
116 def _msg_callback(self, topic, command, params):
117 """
118 Callback to process a received message from kafka
119 :param topic: topic received
120 :param command: command received
121 :param params: rest of parameters
122 :return: None
123 """
124 try:
125 if topic == "ns":
Felipe Vicens09e65422019-01-22 15:06:46 +0100126 if command == "terminated" and params["operationState"] in ("COMPLETED", "PARTIALLY_COMPLETED"):
tierno932499c2019-01-28 17:28:10 +0000127 self.logger.debug("received ns terminated {}".format(params))
128 if params.get("autoremove"):
129 self.engine.del_item(self.internal_session, "nsrs", _id=params["nsr_id"])
130 self.logger.debug("ns={} deleted from database".format(params["nsr_id"]))
131 return
Felipe Vicens09e65422019-01-22 15:06:46 +0100132 if topic == "nsi":
133 if command == "terminated" and params["operationState"] in ("COMPLETED", "PARTIALLY_COMPLETED"):
134 self.logger.debug("received nsi terminated {}".format(params))
135 if params.get("autoremove"):
136 self.engine.del_item(self.internal_session, "nsis", _id=params["nsir_id"])
137 self.logger.debug("nsis={} deleted from database".format(params["nsir_id"]))
138 return
tierno932499c2019-01-28 17:28:10 +0000139 except (EngineException, DbException, MsgException) as e:
140 self.logger.error("Error while processing topic={} command={}: {}".format(topic, command, e))
141 except Exception as e:
142 self.logger.exception("Exception while processing topic={} command={}: {}".format(topic, command, e),
143 exc_info=True)
144
145 def _stop(self):
146 """
147 Close all connections
148 :return: None
149 """
150 try:
151 if self.db:
152 self.db.db_disconnect()
153 if self.msg:
154 self.msg.disconnect()
155 except (DbException, MsgException) as e:
156 raise SubscriptionException(str(e), http_code=e.http_code)
157
158 def terminate(self):
159 """
160 This is a threading safe method to terminate this thread. Termination is done asynchronous afterwards,
161 but not immediately.
162 :return: None
163 """
tierno65ca36d2019-02-12 19:27:52 +0100164 self.to_terminate = True
tierno932499c2019-01-28 17:28:10 +0000165 self.loop.call_soon_threadsafe(self.aiomain_task.cancel)