Newer
Older
# Copyright 2022-2024 ETSI OSG/SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from confluent_kafka import KafkaException
from confluent_kafka.admin import AdminClient, NewTopic
LOGGER = logging.getLogger(__name__)
SERVER_IP = "127.0.0.1:9092"
ADMIN_CLIENT = AdminClient({'bootstrap.servers': SERVER_IP})
class KafkaTopic(Enum):
REQUEST = 'topic_request'
RESPONSE = 'topic_response'
RAW = 'topic_raw'
LABELED = 'topic_labeled'
VALUE = 'topic_value'
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@staticmethod
def create_all_topics() -> bool:
"""
Method to create Kafka topics defined as class members
"""
# LOGGER.debug("Topics to be created: {:}".format(KafkaTopic.__members__.values()))
# LOGGER.debug("Topics to be created: {:}".format(KafkaTopic.__members__.keys()))
# LOGGER.debug("Topics to be created: {:}".format([member.value for member in KafkaTopic]))
all_topics = [member.value for member in KafkaTopic]
if( KafkaTopic.create_new_topic_if_not_exists( all_topics )):
LOGGER.debug("All topics created sucsessfully")
return True
else:
LOGGER.debug("Error creating all topics")
return False
@staticmethod
def create_new_topic_if_not_exists(new_topics: list) -> bool:
"""
Method to create Kafka topic if it does not exist.
Args:
list of topic: containing the topic name(s) to be created on Kafka
"""
LOGGER.debug("Recevied topic List: {:}".format(new_topics))
for topic in new_topics:
try:
topic_metadata = KafkaConfig.ADMIN_CLIENT.value.list_topics(timeout=5)
if topic not in topic_metadata.topics:
# If the topic does not exist, create a new topic
print(f"Topic '{topic}' does not exist. Creating...")
LOGGER.debug("Topic {:} does not exist. Creating...".format(topic))
new_topic = NewTopic(topic, num_partitions=1, replication_factor=1)
KafkaConfig.ADMIN_CLIENT.value.create_topics([new_topic])
except Exception as e:
LOGGER.debug("Failed to create topic: {:}".format(e))
return False
return True
# create all topics after the deployments (Telemetry and Analytics)