-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement functionality to manage configs of the Kafka-Connect connec…
…tors. - implement `kafka_connect` management command to manage connectors configurations. - implement `Connector` interface to define and publish configs. - implement `KafkaConnectClient` with several methods to talk to Kafka-Connect REST API. refs #16
- Loading branch information
Bogdan Radko
committed
Sep 27, 2024
1 parent
e666e8f
commit 78b5991
Showing
10 changed files
with
608 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,3 +10,4 @@ build/ | |
.bash_history | ||
db.sqlite3 | ||
.ruff_cache | ||
docker-compose.override.yaml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import requests | ||
from requests.auth import AuthBase | ||
|
||
from django_kafka.exceptions import DjangoKafkaError | ||
|
||
|
||
from urllib3.util import Retry | ||
from requests.adapters import HTTPAdapter | ||
|
||
|
||
from typing import TypedDict | ||
|
||
|
||
class RetryKwargs(TypedDict): | ||
connect: int | ||
read: int | ||
status: int | ||
backoff_factor: float | ||
status_forcelist: list[int] | ||
|
||
|
||
class KafkaConnectSession(requests.Session): | ||
def __init__(self, host: str, auth: tuple | AuthBase, retry: RetryKwargs, timeout: int = None): | ||
super().__init__() | ||
self.auth = auth | ||
self.host = host | ||
self.timeout = timeout | ||
self.mount(host, HTTPAdapter(max_retries=Retry(**retry))) | ||
|
||
def request(self, method, url, *args, **kwargs) -> requests.Response: | ||
kwargs.setdefault("timeout", self.timeout) | ||
return super().request(method, f"{self.host}{url}", *args, **kwargs) | ||
|
||
|
||
class KafkaConnectClient: | ||
""" | ||
https://kafka.apache.org/documentation/#connect_rest | ||
https://docs.confluent.io/platform/current/connect/references/restapi.html | ||
""" | ||
|
||
def __init__(self, host: str, auth: tuple | AuthBase, retry: RetryKwargs, timeout: int = None): | ||
self._requests = KafkaConnectSession(host, auth, retry, timeout) | ||
|
||
def update_or_create(self, connector_name: str, config: dict): | ||
return self._requests.put(f"/connectors/{connector_name}/config", json=config) | ||
|
||
def delete(self, connector_name: str): | ||
return self._requests.delete(f"/connectors/{connector_name}") | ||
|
||
def validate(self, config: dict): | ||
if not config.get('connector.class'): | ||
raise DjangoKafkaError("'connector.class' config is required for validation.") | ||
|
||
connector_class_name = config.get("connector.class").rsplit(".", 1)[-1] | ||
response = self._requests.put(f"/connector-plugins/{connector_class_name}/config/validate", json=config) | ||
return response | ||
|
||
def connector_status(self, connector_name: str): | ||
""" | ||
https://docs.confluent.io/platform/current/connect/references/restapi.html#get--connectors-(string-name)-status | ||
""" | ||
return self._requests.get(f"/connectors/{connector_name}/status") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
from abc import ABC, abstractmethod | ||
from enum import StrEnum | ||
|
||
from django_kafka.conf import settings | ||
from django_kafka.exceptions import DjangoKafkaError | ||
from django_kafka.connect.client import KafkaConnectClient | ||
|
||
__all__ = [ | ||
"Connector", | ||
"ConnectorStatus", | ||
] | ||
|
||
|
||
class ConnectorStatus(StrEnum): | ||
""" | ||
https://docs.confluent.io/platform/current/connect/monitoring.html#connector-and-task-status | ||
UNASSIGNED: The connector/task has not yet been assigned to a worker. | ||
RUNNING: The connector/task is running. | ||
PAUSED: The connector/task has been administratively paused. | ||
FAILED: The connector/task has failed (usually by raising an exception, which is reported in the status output). | ||
""" | ||
UNASSIGNED = "UNASSIGNED" | ||
RUNNING = "RUNNING" | ||
PAUSED = "PAUSED" | ||
|
||
|
||
class Connector(ABC): | ||
mark_for_removal = False | ||
|
||
@property | ||
def name(self) -> str: | ||
"""Name of the connector.""" | ||
return f"{self.__class__.__module__}.{self.__class__.__name__}" | ||
|
||
@property | ||
@abstractmethod | ||
def config(self) -> dict: | ||
"""Configurations for the connector.""" | ||
|
||
def __init__(self): | ||
self.client = KafkaConnectClient( | ||
host=settings.CONNECT["HOST"], | ||
auth=settings.CONNECT["AUTH"], | ||
retry=settings.CONNECT["RETRY"], | ||
timeout=settings.CONNECT["REQUESTS_TIMEOUT"], | ||
) | ||
|
||
def delete(self) -> bool: | ||
response = self.client.delete(self.name) | ||
|
||
if response.status_code == 404: | ||
return False | ||
|
||
if not response.ok: | ||
raise DjangoKafkaError(response.text) | ||
|
||
return True | ||
|
||
def submit(self): | ||
response = self.client.update_or_create(self.name, self.config) | ||
|
||
if not response.ok: | ||
raise DjangoKafkaError(response.text) | ||
|
||
return response.json() | ||
|
||
def is_valid(self, raise_exception=False) -> bool | None: | ||
response = self.client.validate(self.config) | ||
|
||
if raise_exception and not response.ok: | ||
raise DjangoKafkaError(response.text) | ||
|
||
return response.ok | ||
|
||
def status(self) -> ConnectorStatus: | ||
response = self.client.connector_status(self.name) | ||
|
||
if not response.ok: | ||
raise DjangoKafkaError(response.text) | ||
|
||
return response.json()["connector"]["state"] |
Oops, something went wrong.