Skip to content

Commit 09faabc

Browse files
authored
Merge pull request #22 from harena-lab/development
Development
2 parents 96b5ae7 + 638e984 commit 09faabc

File tree

4 files changed

+45
-17
lines changed

4 files changed

+45
-17
lines changed

readme.md renamed to README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@ flask run # running the application
8181
##### System dependencies
8282

8383
* flask
84-
* flask-restful
8584
* flask-cors
86-
* paho-mqtt
85+
* flask-restful
8786
* pymongo
87+
* kafka-python
88+
* coloredlogs
8889

8990
## Configuration
9091

src/dto.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import enums
2+
3+
class ArenaLoggerDtoValidator():
4+
@staticmethod
5+
def validateDto(message):
6+
if 'harena-log-stream-version' not in message :
7+
message['harena-log-stream-version'] = str(enums.StreamVersionSpecialCodes.NOT_IDENTIFIED.value)
8+
9+
#TODO: create an exception handler with custom exceptions
10+
if 'harena-log-stream' not in message:
11+
raise ValueError('Message does not contains harena-log-stream')
12+
13+
for harena_stream_log_value in message['harena-log-stream']:
14+
if 'topic' not in harena_stream_log_value:
15+
raise ValueError('One or more harena-log-stream items does not contains topic')
16+
break
17+
18+
if 'payload' not in harena_stream_log_value:
19+
raise ValueError("One or more harena-log-stream items does not contains payload")
20+
break
21+
22+
if not bool(harena_stream_log_value['payload']):
23+
raise ValueError("One or more harena-log-stream items does not contains key-value pair")
24+

src/enums.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import enum
2+
3+
class StreamVersionSpecialCodes(enum.Enum):
4+
NOT_IDENTIFIED = 99
5+
ERROR = 100

src/server.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import logging
99
import coloredlogs
1010

11+
from dto import ArenaLoggerDtoValidator
1112
from flask import Flask, request, jsonify
1213
from flask_restful import Resource, Api
1314
from config import Config
@@ -44,6 +45,7 @@ def run(self):
4445
mongodb_collection = mongodb_db[self.mongodb_collection]
4546

4647
print("Checking for newly streamed messages during at least {} seconds...".format(self.delay))
48+
4749
try:
4850
for message in self.kafka_consumer:
4951
print()
@@ -52,10 +54,9 @@ def run(self):
5254
for event in message.value['harena-log-stream']:
5355
mongodb_collection.insert_one(event)
5456
print()
55-
except:
57+
except Exception as e:
5658
print("Object is not a JSON or does not have an 'harena-log-stream' array")
57-
print()
58-
59+
print("Exception trace message: "+str(e))
5960

6061
print("Waiting time ({} seconds) for new messages ended.".format(self.delay))
6162
mongodb_client.close()
@@ -69,7 +70,6 @@ def __init__(self, kafka_producer):
6970

7071
LOGGER.debug("IndexResource initialized")
7172

72-
7373
def get(self):
7474
message = {"message": "Welcome to the Harena Logger module",
7575
"kafka_bootstrap_connected" : self.kafka_producer.bootstrap_connected()
@@ -84,25 +84,27 @@ def __init__(self, kafka_producer, target_topic):
8484
self.target_topic=target_topic
8585

8686

87-
8887
@cross_origin(origin='*')
8988
def post(self):
9089

9190
try:
9291
# To do: properly evaluate message body parsing
9392
message = request.get_json()
9493
message['server_timestamp'] = "{}".format(int(round(time.time() * 1000)))
95-
94+
95+
ArenaLoggerDtoValidator.validateDto(message)
9696
# Asynchronous by default
9797
future = self.kafka_producer.send(self.target_topic, json.dumps(message).encode('utf-8'))
9898

9999
# Block for 'synchronous' sends
100100
record_metadata = future.get(timeout=10)
101-
except KafkaError:
101+
except KafkaError as ke:
102102
# Decide what to do if produce request failed...
103-
log.exception()
104-
except:
103+
logging.exception(ke)
104+
except Exception as e:
105105
print("could not validate the json")
106+
print("Exception trace message: " + str(e))
107+
logging.exception(e)
106108

107109
# Successful result returns assigned partition and offset
108110
# print(future)
@@ -120,14 +122,11 @@ def get(self):
120122
}
121123
return message
122124

123-
124125
if __name__ == '__main__':
125126

126-
127127
kafka_producer = None
128128
kafka_consumer = None
129129

130-
131130
while True:
132131
try:
133132
kafka_producer = KafkaProducer(bootstrap_servers=Config.HARENA_LOGGER_KAFKA_BROKERS)
@@ -137,15 +136,14 @@ def get(self):
137136
value_deserializer=lambda m: json.loads(m.decode('utf-8')),
138137
consumer_timeout_ms=Config.HARENA_LOGGER_INTERVAL_S*1000)
139138
break
140-
except:
139+
except Exception as e:
140+
print("Exception trace message: "+ str(e))
141141
pass
142142

143143
print("Could not exchange metadata with Kafka bootstrap servers for the first time. Retrying...")
144144
time.sleep(1)
145145

146146

147-
148-
149147
consumer_thread = KafkaMongodbAppender(mongodb_server_url=Config.HARENA_LOGGER_MONGODB_URL,
150148
mongodb_database=Config.HARENA_LOGGER_MONGODB_DB,
151149
mongodb_collection=Config.HARENA_LOGGER_MONGODB_COLLECTION,

0 commit comments

Comments
 (0)