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 |
|
|
18 |
1 |
import asyncio |
19 |
1 |
from http import HTTPStatus |
20 |
1 |
import logging |
21 |
1 |
import os |
22 |
1 |
from time import sleep |
23 |
|
|
24 |
1 |
from osm_common.msgbase import MsgBase, MsgException |
25 |
1 |
import yaml |
26 |
|
|
27 |
1 |
__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
28 |
|
""" |
29 |
|
This emulated kafka bus by just using a shared file system. Useful for testing or devops. |
30 |
|
One file is used per topic. Only one producer and one consumer is allowed per topic. Both consumer and producer |
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 |
|
|
35 |
|
|
36 |
1 |
class MsgLocal(MsgBase): |
37 |
1 |
def __init__(self, logger_name="msg", lock=False): |
38 |
1 |
super().__init__(logger_name, lock) |
39 |
1 |
self.path = None |
40 |
|
# create a different file for each topic |
41 |
1 |
self.files_read = {} |
42 |
1 |
self.files_write = {} |
43 |
1 |
self.buffer = {} |
44 |
1 |
self.loop = None |
45 |
|
|
46 |
1 |
def connect(self, config): |
47 |
0 |
try: |
48 |
0 |
if "logger_name" in config: |
49 |
0 |
self.logger = logging.getLogger(config["logger_name"]) |
50 |
0 |
self.path = config["path"] |
51 |
0 |
if not self.path.endswith("/"): |
52 |
0 |
self.path += "/" |
53 |
0 |
if not os.path.exists(self.path): |
54 |
0 |
os.mkdir(self.path) |
55 |
0 |
self.loop = config.get("loop") |
56 |
|
|
57 |
0 |
except MsgException: |
58 |
0 |
raise |
59 |
0 |
except Exception as e: # TODO refine |
60 |
0 |
raise MsgException(str(e), http_code=HTTPStatus.INTERNAL_SERVER_ERROR) |
61 |
|
|
62 |
1 |
def disconnect(self): |
63 |
0 |
for topic, f in self.files_read.items(): |
64 |
0 |
try: |
65 |
0 |
f.close() |
66 |
0 |
self.files_read[topic] = None |
67 |
0 |
except Exception as read_topic_error: |
68 |
0 |
if isinstance(read_topic_error, (IOError, FileNotFoundError)): |
69 |
0 |
self.logger.exception( |
70 |
|
f"{read_topic_error} occured while closing read topic files." |
71 |
|
) |
72 |
0 |
elif isinstance(read_topic_error, KeyError): |
73 |
0 |
self.logger.exception( |
74 |
|
f"{read_topic_error} occured while reading from files_read dictionary." |
75 |
|
) |
76 |
|
else: |
77 |
0 |
self.logger.exception( |
78 |
|
f"{read_topic_error} occured while closing read topics." |
79 |
|
) |
80 |
|
|
81 |
0 |
for topic, f in self.files_write.items(): |
82 |
0 |
try: |
83 |
0 |
f.close() |
84 |
0 |
self.files_write[topic] = None |
85 |
0 |
except Exception as write_topic_error: |
86 |
0 |
if isinstance(write_topic_error, (IOError, FileNotFoundError)): |
87 |
0 |
self.logger.exception( |
88 |
|
f"{write_topic_error} occured while closing write topic files." |
89 |
|
) |
90 |
0 |
elif isinstance(write_topic_error, KeyError): |
91 |
0 |
self.logger.exception( |
92 |
|
f"{write_topic_error} occured while reading from files_write dictionary." |
93 |
|
) |
94 |
|
else: |
95 |
0 |
self.logger.exception( |
96 |
|
f"{write_topic_error} occured while closing write topics." |
97 |
|
) |
98 |
|
|
99 |
1 |
def write(self, topic, key, msg): |
100 |
|
""" |
101 |
|
Insert a message into topic |
102 |
|
:param topic: topic |
103 |
|
:param key: key text to be inserted |
104 |
|
:param msg: value object to be inserted, can be str, object ... |
105 |
|
:return: None or raises and exception |
106 |
|
""" |
107 |
0 |
try: |
108 |
0 |
with self.lock: |
109 |
0 |
if topic not in self.files_write: |
110 |
0 |
self.files_write[topic] = open(self.path + topic, "a+") |
111 |
0 |
yaml.safe_dump( |
112 |
|
{key: msg}, |
113 |
|
self.files_write[topic], |
114 |
|
default_flow_style=True, |
115 |
|
width=20000, |
116 |
|
) |
117 |
0 |
self.files_write[topic].flush() |
118 |
0 |
except Exception as e: # TODO refine |
119 |
0 |
raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
120 |
|
|
121 |
1 |
def read(self, topic, blocks=True): |
122 |
|
""" |
123 |
|
Read from one or several topics. it is non blocking returning None if nothing is available |
124 |
|
:param topic: can be str: single topic; or str list: several topics |
125 |
|
:param blocks: indicates if it should wait and block until a message is present or returns None |
126 |
|
:return: topic, key, message; or None if blocks==True |
127 |
|
""" |
128 |
0 |
try: |
129 |
0 |
if isinstance(topic, (list, tuple)): |
130 |
0 |
topic_list = topic |
131 |
|
else: |
132 |
0 |
topic_list = (topic,) |
133 |
|
while True: |
134 |
0 |
for single_topic in topic_list: |
135 |
0 |
with self.lock: |
136 |
0 |
if single_topic not in self.files_read: |
137 |
0 |
self.files_read[single_topic] = open( |
138 |
|
self.path + single_topic, "a+" |
139 |
|
) |
140 |
0 |
self.buffer[single_topic] = "" |
141 |
0 |
self.buffer[single_topic] += self.files_read[ |
142 |
|
single_topic |
143 |
|
].readline() |
144 |
0 |
if not self.buffer[single_topic].endswith("\n"): |
145 |
0 |
continue |
146 |
0 |
msg_dict = yaml.safe_load(self.buffer[single_topic]) |
147 |
0 |
self.buffer[single_topic] = "" |
148 |
0 |
if len(msg_dict) != 1: |
149 |
0 |
raise ValueError( |
150 |
|
"Length of message dictionary is not equal to 1" |
151 |
|
) |
152 |
0 |
for k, v in msg_dict.items(): |
153 |
0 |
return single_topic, k, v |
154 |
0 |
if not blocks: |
155 |
0 |
return None |
156 |
0 |
sleep(2) |
157 |
0 |
except Exception as e: # TODO refine |
158 |
0 |
raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
159 |
|
|
160 |
1 |
async def aioread( |
161 |
|
self, topic, loop=None, callback=None, aiocallback=None, group_id=None, **kwargs |
162 |
|
): |
163 |
|
""" |
164 |
|
Asyncio read from one or several topics. It blocks |
165 |
|
:param topic: can be str: single topic; or str list: several topics |
166 |
|
:param loop: asyncio loop. To be DEPRECATED! in near future!!! loop must be provided inside config at connect |
167 |
|
:param callback: synchronous callback function that will handle the message |
168 |
|
:param aiocallback: async callback function that will handle the message |
169 |
|
:param group_id: group_id to use for load balancing. Can be False (set group_id to None), None (use general |
170 |
|
group_id provided at connect inside config), or a group_id string |
171 |
|
:param kwargs: optional keyword arguments for callback function |
172 |
|
:return: If no callback defined, it returns (topic, key, message) |
173 |
|
""" |
174 |
0 |
_loop = loop or self.loop |
175 |
0 |
try: |
176 |
|
while True: |
177 |
0 |
msg = self.read(topic, blocks=False) |
178 |
0 |
if msg: |
179 |
0 |
if callback: |
180 |
0 |
callback(*msg, **kwargs) |
181 |
0 |
elif aiocallback: |
182 |
0 |
await aiocallback(*msg, **kwargs) |
183 |
|
else: |
184 |
0 |
return msg |
185 |
0 |
await asyncio.sleep(2, loop=_loop) |
186 |
0 |
except MsgException: |
187 |
0 |
raise |
188 |
0 |
except Exception as e: # TODO refine |
189 |
0 |
raise MsgException(str(e), HTTPStatus.INTERNAL_SERVER_ERROR) |
190 |
|
|
191 |
1 |
async def aiowrite(self, topic, key, msg, loop=None): |
192 |
|
""" |
193 |
|
Asyncio write. It blocks |
194 |
|
:param topic: str |
195 |
|
:param key: str |
196 |
|
:param msg: message, can be str or yaml |
197 |
|
:param loop: asyncio loop |
198 |
|
:return: nothing if ok or raises an exception |
199 |
|
""" |
200 |
0 |
return self.write(topic, key, msg) |