2020-09-04 00:24:21 +02:00
|
|
|
"""
|
|
|
|
Sample consumer.
|
|
|
|
"""
|
|
|
|
import asyncio
|
|
|
|
import json
|
2020-09-04 19:45:43 +02:00
|
|
|
import logging
|
2020-09-04 18:22:49 +02:00
|
|
|
from typing import Any, Dict
|
2020-09-04 00:24:21 +02:00
|
|
|
|
|
|
|
import aiokafka # type: ignore
|
|
|
|
import asyncpg # type: ignore
|
|
|
|
|
2020-09-05 00:06:57 +02:00
|
|
|
from chweb.base import Service
|
2020-09-04 18:22:49 +02:00
|
|
|
from chweb.models import Check
|
|
|
|
|
2020-09-04 00:24:21 +02:00
|
|
|
|
2020-09-05 00:06:57 +02:00
|
|
|
class Consumer(Service):
|
2020-09-04 00:24:21 +02:00
|
|
|
async def consume(self):
|
|
|
|
"""
|
2020-09-05 00:06:57 +02:00
|
|
|
Consumes messages from a kafka topic and writes them in the database.
|
2020-09-04 00:24:21 +02:00
|
|
|
"""
|
|
|
|
consumer = aiokafka.AIOKafkaConsumer(
|
2020-09-04 18:22:49 +02:00
|
|
|
self.config.kafka.topic,
|
2020-09-04 00:24:21 +02:00
|
|
|
loop=self.loop,
|
2020-09-04 18:22:49 +02:00
|
|
|
bootstrap_servers=self.config.kafka.servers)
|
2020-09-04 00:24:21 +02:00
|
|
|
|
|
|
|
await consumer.start()
|
|
|
|
try:
|
2020-09-05 00:06:57 +02:00
|
|
|
# Consume messages from the kafka topic.
|
2020-09-04 00:24:21 +02:00
|
|
|
async for msg in consumer:
|
2020-09-05 00:06:57 +02:00
|
|
|
check_info = Check(**json.loads(msg.value))
|
|
|
|
self.queue.put_nowait(check_info)
|
|
|
|
self.logger.info(check_info)
|
2020-09-04 00:24:21 +02:00
|
|
|
finally:
|
|
|
|
# Will leave consumer group; perform autocommit if enabled.
|
|
|
|
await consumer.stop()
|
|
|
|
|
2020-09-05 00:06:57 +02:00
|
|
|
def __call__(self) -> asyncio.Future:
|
|
|
|
return self.consume()
|
2020-09-04 00:24:21 +02:00
|
|
|
|
|
|
|
|
2020-09-05 00:06:57 +02:00
|
|
|
class Db:
|
|
|
|
async def consume_and_save(self):
|
2020-09-04 00:24:21 +02:00
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
status = await self.queue.get()
|
2020-09-05 00:06:57 +02:00
|
|
|
yield status
|
2020-09-04 00:24:21 +02:00
|
|
|
finally:
|
2020-09-05 00:06:57 +02:00
|
|
|
self.logger.info("Queue reader stopped.")
|