Commits (5)
apiVersion: apps/v1
kind: Deployment
metadata:
name: node-exporter
labels:
app: node-exporter
spec:
replicas: 1
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
containers:
- name: node-exporter
image: prom/node-exporter:latest
ports:
- containerPort: 9100
apiVersion: v1
kind: Service
metadata:
name: node-exporter
spec:
selector:
app: node-exporter
ports:
- protocol: TCP
port: 9100
targetPort: 9100
type: NodePort
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (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 NodeExporterProducer import KafkaNodeExporterProducer
class KafkaProducerController:
"""
Class to control Kafka producer functionality.
"""
def __init__(self):
kafka_configs = self.generate_kafka_configurations()
self.bootstrap_servers = kafka_configs['bootstrap_servers']
self.node_exporter_endpoint = kafka_configs['node_exporter_endpoint']
self.kafka_topic = kafka_configs['kafka_topic']
self.run_duration = kafka_configs['run_duration']
self.fetch_interval = kafka_configs['fetch_interval']
def generate_kafka_configurations(self):
"""
Method to generate Kafka configurations
"""
create_kafka_configuration = {
'bootstrap_servers' : '127.0.0.1:9092', # Kafka broker address - Replace with your Kafka broker address
'node_exporter_endpoint' : 'http://10.152.183.231:9100/metrics', # Node Exporter metrics endpoint - Replace with your Node Exporter endpoint
'kafka_topic' : 'metric-data', # Kafka topic to produce to
'run_duration' : 20, # Total duration to execute the producer
'fetch_interval' : 3 # Time between two fetch requests
}
return create_kafka_configuration
def run_producer(self):
"""
Method to create KafkaNodeExporterProducer object and start producer thread.
"""
# Create NodeExporterProducer object and run start_producer_thread
producer = KafkaNodeExporterProducer(self.bootstrap_servers, self.node_exporter_endpoint,
self.kafka_topic, self.run_duration, self.fetch_interval
)
# producer.start_producer_thread() # if threading is required
producer.produce_metrics() # if threading is not required
if __name__ == "__main__":
# Create Kafka producer controller object and run producer
kafka_controller = KafkaProducerController()
kafka_controller.run_producer()
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (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 Producer, KafkaException
from confluent_kafka.admin import AdminClient, NewTopic
import requests
import time
import threading
class KafkaNodeExporterProducer:
"""
Class to fetch metrics from Node Exporter and produce them to Kafka.
"""
def __init__(self, bootstrap_servers, node_exporter_endpoint, kafka_topic, run_duration, fetch_interval):
"""
Constructor to initialize Kafka producer parameters.
Args:
bootstrap_servers (str): Kafka broker address.
node_exporter_endpoint (str): Node Exporter metrics endpoint.
kafka_topic (str): Kafka topic to produce metrics to.
run_interval (int): Time interval in seconds to run the producer.
"""
self.bootstrap_servers = bootstrap_servers
self.node_exporter_endpoint = node_exporter_endpoint
self.kafka_topic = kafka_topic
self.run_duration = run_duration
self.fetch_interval = fetch_interval
def fetch_metrics(self):
"""
Method to fetch metrics from Node Exporter.
Returns:
str: Metrics fetched from Node Exporter.
"""
try:
response = requests.get(self.node_exporter_endpoint)
if response.status_code == 200:
print(f"Metrics fetched sucessfully...")
return response.text
else:
print(f"Failed to fetch metrics. Status code: {response.status_code}")
return None
except Exception as e:
print(f"Failed to fetch metrics: {str(e)}")
return None
def delivery_callback(self, err, msg):
"""
Callback function to handle message delivery status.
Args:
err (KafkaError): Kafka error object.
msg (Message): Kafka message object.
"""
if err:
print(f'Message delivery failed: {err}')
else:
print(f'Message delivered to topic {msg.topic()}')
def create_topic_if_not_exists(self, admin_client):
"""
Method to create Kafka topic if it does not exist.
Args:
admin_client (AdminClient): Kafka admin client.
"""
try:
topic_metadata = admin_client.list_topics(timeout=5)
if self.kafka_topic not in topic_metadata.topics:
# If the topic does not exist, create a new topic
print(f"Topic '{self.kafka_topic}' does not exist. Creating...")
new_topic = NewTopic(self.kafka_topic, num_partitions=1, replication_factor=1)
admin_client.create_topics([new_topic])
except KafkaException as e:
print(f"Failed to create topic: {e}")
def produce_metrics(self):
"""
Method to continuously produce metrics to Kafka topic.
"""
conf = {
'bootstrap.servers': self.bootstrap_servers,
}
admin_client = AdminClient(conf)
self.create_topic_if_not_exists(admin_client)
kafka_producer = Producer(conf)
try:
start_time = time.time()
while True:
metrics = self.fetch_metrics()
if metrics:
kafka_producer.produce(self.kafka_topic, metrics.encode('utf-8'), callback=self.delivery_callback)
kafka_producer.flush()
print("Metrics produced to Kafka topic")
# Check if the specified run duration has elapsed
if time.time() - start_time >= self.run_duration:
break
# waiting time until next fetch
time.sleep(self.fetch_interval)
except KeyboardInterrupt:
print("Keyboard interrupt detected. Exiting...")
finally:
kafka_producer.flush()
# kafka_producer.close() # this command generates ERROR
def start_producer_thread(self):
"""
Method to start the producer thread.
"""
producer_thread = threading.Thread(target=self.produce_metrics)
producer_thread.start()
anytree==2.8.0
APScheduler==3.10.1
attrs==23.2.0
certifi==2024.2.2
charset-normalizer==2.0.12
colorama==0.4.6
confluent-kafka==2.3.0
coverage==6.3
future-fstrings==1.2.0
grpcio==1.47.5
grpcio-health-checking==1.47.5
grpcio-tools==1.47.5
grpclib==0.4.4
h2==4.1.0
hpack==4.0.0
hyperframe==6.0.1
idna==3.7
influx-line-protocol==0.1.4
iniconfig==2.0.0
kafka-python==2.0.2
multidict==6.0.5
networkx==3.3
packaging==24.0
pluggy==1.5.0
prettytable==3.5.0
prometheus-client==0.13.0
protobuf==3.20.3
psycopg2-binary==2.9.3
py==1.11.0
py-cpuinfo==9.0.0
pytest==6.2.5
pytest-benchmark==3.4.1
pytest-depends==1.0.1
python-dateutil==2.8.2
python-json-logger==2.0.2
pytz==2024.1
questdb==1.0.1
requests==2.27.1
six==1.16.0
toml==0.10.2
tzlocal==5.2
urllib3==1.26.18
wcwidth==0.2.13
xmltodict==0.12.0