blob: 0c3b216e5349ac7bf4cb5a914adf749c8322e27a [file] [log] [blame]
tierno87858ca2018-10-08 16:30:15 +02001# -*- coding: utf-8 -*-
2
3# Copyright 2018 Telefonica S.A.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
aticig3dd0db62022-03-04 19:35:45 +030018import asyncio
19from http import HTTPStatus
tierno5c012612018-04-19 16:01:59 +020020import logging
21import os
tierno5c012612018-04-19 16:01:59 +020022from time import sleep
aticig3dd0db62022-03-04 19:35:45 +030023
24from osm_common.msgbase import MsgBase, MsgException
25import yaml
tierno5c012612018-04-19 16:01:59 +020026
27__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno5c012612018-04-19 16:01:59 +020028"""
29This emulated kafka bus by just using a shared file system. Useful for testing or devops.
tierno3054f782018-04-25 16:59:53 +020030One file is used per topic. Only one producer and one consumer is allowed per topic. Both consumer and producer
tierno5c012612018-04-19 16:01:59 +020031access to the same file. e.g. same volume if running with docker.
32One text line per message is used in yaml format.
33"""
34
tierno3054f782018-04-25 16:59:53 +020035
tierno5c012612018-04-19 16:01:59 +020036class MsgLocal(MsgBase):
garciadeblas2644b762021-03-24 09:21:01 +010037 def __init__(self, logger_name="msg", lock=False):
tierno1e9a3292018-11-05 18:18:45 +010038 super().__init__(logger_name, lock)
tierno5c012612018-04-19 16:01:59 +020039 self.path = None
40 # create a different file for each topic
tiernoe74238f2018-04-26 17:22:09 +020041 self.files_read = {}
42 self.files_write = {}
tierno5c012612018-04-19 16:01:59 +020043 self.buffer = {}
44
45 def connect(self, config):
46 try:
47 if "logger_name" in config:
48 self.logger = logging.getLogger(config["logger_name"])
49 self.path = config["path"]
50 if not self.path.endswith("/"):
51 self.path += "/"
52 if not os.path.exists(self.path):
53 os.mkdir(self.path)
tierno05ede8f2019-01-28 16:20:18 +000054
tierno5c012612018-04-19 16:01:59 +020055 except MsgException:
56 raise
57 except Exception as e: # TODO refine
tierno136f2952018-10-19 13:01:03 +020058 raise MsgException(str(e), http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
tierno5c012612018-04-19 16:01:59 +020059
60 def disconnect(self):
tierno1e9a3292018-11-05 18:18:45 +010061 for topic, f in self.files_read.items():
tiernoe74238f2018-04-26 17:22:09 +020062 try:
63 f.close()
tierno1e9a3292018-11-05 18:18:45 +010064 self.files_read[topic] = None
aticigd3b582a2022-08-24 22:41:56 +030065 except Exception as read_topic_error:
66 if isinstance(read_topic_error, (IOError, FileNotFoundError)):
67 self.logger.exception(
68 f"{read_topic_error} occured while closing read topic files."
69 )
70 elif isinstance(read_topic_error, KeyError):
71 self.logger.exception(
72 f"{read_topic_error} occured while reading from files_read dictionary."
73 )
74 else:
75 self.logger.exception(
76 f"{read_topic_error} occured while closing read topics."
77 )
78
tierno1e9a3292018-11-05 18:18:45 +010079 for topic, f in self.files_write.items():
tierno5c012612018-04-19 16:01:59 +020080 try:
81 f.close()
tierno1e9a3292018-11-05 18:18:45 +010082 self.files_write[topic] = None
aticigd3b582a2022-08-24 22:41:56 +030083 except Exception as write_topic_error:
84 if isinstance(write_topic_error, (IOError, FileNotFoundError)):
85 self.logger.exception(
86 f"{write_topic_error} occured while closing write topic files."
87 )
88 elif isinstance(write_topic_error, KeyError):
89 self.logger.exception(
90 f"{write_topic_error} occured while reading from files_write dictionary."
91 )
92 else:
93 self.logger.exception(
94 f"{write_topic_error} occured while closing write topics."
95 )
tierno5c012612018-04-19 16:01:59 +020096
97 def write(self, topic, key, msg):
98 """
99 Insert a message into topic
100 :param topic: topic
101 :param key: key text to be inserted
102 :param msg: value object to be inserted, can be str, object ...
103 :return: None or raises and exception
104 """
105 try:
tierno1e9a3292018-11-05 18:18:45 +0100106 with self.lock:
107 if topic not in self.files_write:
108 self.files_write[topic] = open(self.path + topic, "a+")
garciadeblas2644b762021-03-24 09:21:01 +0100109 yaml.safe_dump(
110 {key: msg},
111 self.files_write[topic],
112 default_flow_style=True,
113 width=20000,
114 )
tierno1e9a3292018-11-05 18:18:45 +0100115 self.files_write[topic].flush()
tierno5c012612018-04-19 16:01:59 +0200116 except Exception as e: # TODO refine
tierno136f2952018-10-19 13:01:03 +0200117 raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR)
tierno5c012612018-04-19 16:01:59 +0200118
119 def read(self, topic, blocks=True):
120 """
121 Read from one or several topics. it is non blocking returning None if nothing is available
122 :param topic: can be str: single topic; or str list: several topics
123 :param blocks: indicates if it should wait and block until a message is present or returns None
124 :return: topic, key, message; or None if blocks==True
125 """
126 try:
127 if isinstance(topic, (list, tuple)):
128 topic_list = topic
129 else:
garciadeblas2644b762021-03-24 09:21:01 +0100130 topic_list = (topic,)
tierno5c012612018-04-19 16:01:59 +0200131 while True:
132 for single_topic in topic_list:
tierno1e9a3292018-11-05 18:18:45 +0100133 with self.lock:
134 if single_topic not in self.files_read:
garciadeblas2644b762021-03-24 09:21:01 +0100135 self.files_read[single_topic] = open(
136 self.path + single_topic, "a+"
137 )
tierno1e9a3292018-11-05 18:18:45 +0100138 self.buffer[single_topic] = ""
garciadeblas2644b762021-03-24 09:21:01 +0100139 self.buffer[single_topic] += self.files_read[
140 single_topic
141 ].readline()
tierno1e9a3292018-11-05 18:18:45 +0100142 if not self.buffer[single_topic].endswith("\n"):
143 continue
tierno6472e2b2019-09-02 16:04:16 +0000144 msg_dict = yaml.safe_load(self.buffer[single_topic])
tierno5c012612018-04-19 16:01:59 +0200145 self.buffer[single_topic] = ""
aticigd3b582a2022-08-24 22:41:56 +0300146 if len(msg_dict) != 1:
147 raise ValueError(
148 "Length of message dictionary is not equal to 1"
149 )
tierno1e9a3292018-11-05 18:18:45 +0100150 for k, v in msg_dict.items():
151 return single_topic, k, v
tierno5c012612018-04-19 16:01:59 +0200152 if not blocks:
153 return None
154 sleep(2)
155 except Exception as e: # TODO refine
tierno136f2952018-10-19 13:01:03 +0200156 raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR)
tierno5c012612018-04-19 16:01:59 +0200157
garciadeblas2644b762021-03-24 09:21:01 +0100158 async def aioread(
Gulsum Aticia06b8542023-05-09 13:42:13 +0300159 self, topic, callback=None, aiocallback=None, group_id=None, **kwargs
garciadeblas2644b762021-03-24 09:21:01 +0100160 ):
tierno5c012612018-04-19 16:01:59 +0200161 """
162 Asyncio read from one or several topics. It blocks
163 :param topic: can be str: single topic; or str list: several topics
tierno10602af2019-02-18 14:53:54 +0000164 :param callback: synchronous callback function that will handle the message
165 :param aiocallback: async callback function that will handle the message
166 :param group_id: group_id to use for load balancing. Can be False (set group_id to None), None (use general
167 group_id provided at connect inside config), or a group_id string
168 :param kwargs: optional keyword arguments for callback function
169 :return: If no callback defined, it returns (topic, key, message)
tierno5c012612018-04-19 16:01:59 +0200170 """
171 try:
172 while True:
173 msg = self.read(topic, blocks=False)
174 if msg:
tierno14521832018-10-24 10:53:37 +0200175 if callback:
176 callback(*msg, **kwargs)
177 elif aiocallback:
178 await aiocallback(*msg, **kwargs)
179 else:
180 return msg
Gulsum Aticia06b8542023-05-09 13:42:13 +0300181 await asyncio.sleep(2)
tierno5c012612018-04-19 16:01:59 +0200182 except MsgException:
183 raise
184 except Exception as e: # TODO refine
tierno136f2952018-10-19 13:01:03 +0200185 raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR)
tiernoebbf3532018-05-03 17:49:37 +0200186
Gulsum Aticia06b8542023-05-09 13:42:13 +0300187 async def aiowrite(self, topic, key, msg):
tiernoebbf3532018-05-03 17:49:37 +0200188 """
189 Asyncio write. It blocks
190 :param topic: str
191 :param key: str
192 :param msg: message, can be str or yaml
tiernoebbf3532018-05-03 17:49:37 +0200193 :return: nothing if ok or raises an exception
194 """
195 return self.write(topic, key, msg)