| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 1 | # -*- 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 | |
| aticig | 3dd0db6 | 2022-03-04 19:35:45 +0300 | [diff] [blame^] | 18 | import asyncio |
| 19 | from http import HTTPStatus |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 20 | import logging |
| 21 | import os |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 22 | from time import sleep |
| aticig | 3dd0db6 | 2022-03-04 19:35:45 +0300 | [diff] [blame^] | 23 | |
| 24 | from osm_common.msgbase import MsgBase, MsgException |
| 25 | import yaml |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 26 | |
| 27 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 28 | """ |
| 29 | This emulated kafka bus by just using a shared file system. Useful for testing or devops. |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 30 | One file is used per topic. Only one producer and one consumer is allowed per topic. Both consumer and producer |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 31 | access to the same file. e.g. same volume if running with docker. |
| 32 | One text line per message is used in yaml format. |
| 33 | """ |
| 34 | |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 35 | |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 36 | class MsgLocal(MsgBase): |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 37 | def __init__(self, logger_name="msg", lock=False): |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 38 | super().__init__(logger_name, lock) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 39 | self.path = None |
| 40 | # create a different file for each topic |
| tierno | e74238f | 2018-04-26 17:22:09 +0200 | [diff] [blame] | 41 | self.files_read = {} |
| 42 | self.files_write = {} |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 43 | self.buffer = {} |
| tierno | 05ede8f | 2019-01-28 16:20:18 +0000 | [diff] [blame] | 44 | self.loop = None |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 45 | |
| 46 | def connect(self, config): |
| 47 | try: |
| 48 | if "logger_name" in config: |
| 49 | self.logger = logging.getLogger(config["logger_name"]) |
| 50 | self.path = config["path"] |
| 51 | if not self.path.endswith("/"): |
| 52 | self.path += "/" |
| 53 | if not os.path.exists(self.path): |
| 54 | os.mkdir(self.path) |
| tierno | 05ede8f | 2019-01-28 16:20:18 +0000 | [diff] [blame] | 55 | self.loop = config.get("loop") |
| 56 | |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 57 | except MsgException: |
| 58 | raise |
| 59 | except Exception as e: # TODO refine |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 60 | raise MsgException(str(e), http_code=HTTPStatus.INTERNAL_SERVER_ERROR) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 61 | |
| 62 | def disconnect(self): |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 63 | for topic, f in self.files_read.items(): |
| tierno | e74238f | 2018-04-26 17:22:09 +0200 | [diff] [blame] | 64 | try: |
| 65 | f.close() |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 66 | self.files_read[topic] = None |
| tierno | e74238f | 2018-04-26 17:22:09 +0200 | [diff] [blame] | 67 | except Exception: # TODO refine |
| 68 | pass |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 69 | for topic, f in self.files_write.items(): |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 70 | try: |
| 71 | f.close() |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 72 | self.files_write[topic] = None |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 73 | except Exception: # TODO refine |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 74 | pass |
| 75 | |
| 76 | def write(self, topic, key, msg): |
| 77 | """ |
| 78 | Insert a message into topic |
| 79 | :param topic: topic |
| 80 | :param key: key text to be inserted |
| 81 | :param msg: value object to be inserted, can be str, object ... |
| 82 | :return: None or raises and exception |
| 83 | """ |
| 84 | try: |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 85 | with self.lock: |
| 86 | if topic not in self.files_write: |
| 87 | self.files_write[topic] = open(self.path + topic, "a+") |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 88 | yaml.safe_dump( |
| 89 | {key: msg}, |
| 90 | self.files_write[topic], |
| 91 | default_flow_style=True, |
| 92 | width=20000, |
| 93 | ) |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 94 | self.files_write[topic].flush() |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 95 | except Exception as e: # TODO refine |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 96 | raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 97 | |
| 98 | def read(self, topic, blocks=True): |
| 99 | """ |
| 100 | Read from one or several topics. it is non blocking returning None if nothing is available |
| 101 | :param topic: can be str: single topic; or str list: several topics |
| 102 | :param blocks: indicates if it should wait and block until a message is present or returns None |
| 103 | :return: topic, key, message; or None if blocks==True |
| 104 | """ |
| 105 | try: |
| 106 | if isinstance(topic, (list, tuple)): |
| 107 | topic_list = topic |
| 108 | else: |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 109 | topic_list = (topic,) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 110 | while True: |
| 111 | for single_topic in topic_list: |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 112 | with self.lock: |
| 113 | if single_topic not in self.files_read: |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 114 | self.files_read[single_topic] = open( |
| 115 | self.path + single_topic, "a+" |
| 116 | ) |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 117 | self.buffer[single_topic] = "" |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 118 | self.buffer[single_topic] += self.files_read[ |
| 119 | single_topic |
| 120 | ].readline() |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 121 | if not self.buffer[single_topic].endswith("\n"): |
| 122 | continue |
| tierno | 6472e2b | 2019-09-02 16:04:16 +0000 | [diff] [blame] | 123 | msg_dict = yaml.safe_load(self.buffer[single_topic]) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 124 | self.buffer[single_topic] = "" |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 125 | assert len(msg_dict) == 1 |
| 126 | for k, v in msg_dict.items(): |
| 127 | return single_topic, k, v |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 128 | if not blocks: |
| 129 | return None |
| 130 | sleep(2) |
| 131 | except Exception as e: # TODO refine |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 132 | raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 133 | |
| garciadeblas | 2644b76 | 2021-03-24 09:21:01 +0100 | [diff] [blame] | 134 | async def aioread( |
| 135 | self, topic, loop=None, callback=None, aiocallback=None, group_id=None, **kwargs |
| 136 | ): |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 137 | """ |
| 138 | Asyncio read from one or several topics. It blocks |
| 139 | :param topic: can be str: single topic; or str list: several topics |
| tierno | 10602af | 2019-02-18 14:53:54 +0000 | [diff] [blame] | 140 | :param loop: asyncio loop. To be DEPRECATED! in near future!!! loop must be provided inside config at connect |
| 141 | :param callback: synchronous callback function that will handle the message |
| 142 | :param aiocallback: async callback function that will handle the message |
| 143 | :param group_id: group_id to use for load balancing. Can be False (set group_id to None), None (use general |
| 144 | group_id provided at connect inside config), or a group_id string |
| 145 | :param kwargs: optional keyword arguments for callback function |
| 146 | :return: If no callback defined, it returns (topic, key, message) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 147 | """ |
| tierno | 05ede8f | 2019-01-28 16:20:18 +0000 | [diff] [blame] | 148 | _loop = loop or self.loop |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 149 | try: |
| 150 | while True: |
| 151 | msg = self.read(topic, blocks=False) |
| 152 | if msg: |
| tierno | 1452183 | 2018-10-24 10:53:37 +0200 | [diff] [blame] | 153 | if callback: |
| 154 | callback(*msg, **kwargs) |
| 155 | elif aiocallback: |
| 156 | await aiocallback(*msg, **kwargs) |
| 157 | else: |
| 158 | return msg |
| tierno | 05ede8f | 2019-01-28 16:20:18 +0000 | [diff] [blame] | 159 | await asyncio.sleep(2, loop=_loop) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 160 | except MsgException: |
| 161 | raise |
| 162 | except Exception as e: # TODO refine |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 163 | raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 164 | |
| 165 | async def aiowrite(self, topic, key, msg, loop=None): |
| 166 | """ |
| 167 | Asyncio write. It blocks |
| 168 | :param topic: str |
| 169 | :param key: str |
| 170 | :param msg: message, can be str or yaml |
| 171 | :param loop: asyncio loop |
| 172 | :return: nothing if ok or raises an exception |
| 173 | """ |
| 174 | return self.write(topic, key, msg) |