Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 0 additions & 143 deletions TelegramBotAlertsPack/alerts.py

This file was deleted.

6 changes: 3 additions & 3 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ services:

my-app:
image: containers-monitoring-app
container_name: my-python-container
container_name: main-runner
restart: always
environment:
- DOCKER_HOST=tcp://host.docker.internal:2375
Expand All @@ -16,7 +16,7 @@ services:
ports:
- "9090:9090"
volumes:
- D:/ContainerMonitoringProgram/container-monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- D:/own_projects/Containers-monitoring-application/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
command:
- "--config.file=/etc/prometheus/prometheus.yml"
restart: always
Expand Down Expand Up @@ -48,7 +48,7 @@ services:
volumes:
- grafana-data:/var/lib/grafana
env_file:
- D:/ContainerMonitoringProgram/container-monitoring/.env
- D:/own_projects/Containers-monitoring-application/.env
restart: always

volumes:
Expand Down
File renamed without changes.
14 changes: 11 additions & 3 deletions LoggerPack/log_container.py → logger_setup/logger.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
"""
The module is responsible for creating logs for monitoring execution
"""

import sys
import logging

from logging.handlers import RotatingFileHandler
import sys


logger = logging.getLogger("ContainerMonitor")
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(asctime)s - %(name)s - \
%(levelname)s - %(message)s')

console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

file_handler = RotatingFileHandler("../container_monitor.log", maxBytes=1024 * 1024, backupCount=5)
file_handler = RotatingFileHandler("../container_monitor.log",
maxBytes=1024 * 1024, backupCount=5)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
28 changes: 19 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import LoggerPack.log_container as lc
from TelegramBotAlertsPack import alerts
import logger_setup.logger as lc
from telegram_bot_alerts import setup_alerts

def main_block():

def main() -> int:
"""
Main entry point of the application.

This function initializes the logger, starts the Telegram bot for alerts,
and returns 0 upon successful execution.

Steps:
1. Logs that the application has started.
2. Starts the Telegram bot using `setup_alerts.start_telegram_bot()`.
3. Returns 0 when execution completes successfully.
"""
lc.logger.info("The app has started!")
alerts.start_telegram_bot()
setup_alerts.start_telegram_bot()
return 0


if __name__ == "__main__":
ending_code = main_block()
if ending_code == 0:
END = main()
if END == 0:
lc.logger.info("The app is complete!")



File renamed without changes.
74 changes: 57 additions & 17 deletions MonitorPack/monitor.py → monitoring/setup_monitoring.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import LoggerPack.log_container as lc
import sys
import docker
from docker import errors
import sys
from typing import Optional

import logger_setup.logger as lc

if __name__ == "__main__":
lc.logger.error("This file cannot be run as main!")
Expand All @@ -11,10 +13,26 @@
try:
client = docker.from_env()
except errors.DockerException:
client = None
lc.logger.error("Docker is not working right now!")

def get_container_metrics():

def get_container_metrics() -> list[str]:
"""
Retrieve metrics for all running Docker containers.

For each container, this function collects:
- container name
- container status
- parent image
- creation time
- CPU usage percentage
- RAM usage in MB

Returns:
list[str]: A list of formatted strings containing metrics
for each container.
"""
containers = client.containers.list()
containers_stats = []
for container in containers:
Expand All @@ -33,31 +51,53 @@ def get_container_metrics():
f"~ RAM use: {mem_usage_mb:.2f} MB\n")
return containers_stats

def calculate_cpu_percent(stats):
cpu_delta = stats["cpu_stats"]["cpu_usage"]["total_usage"] - stats["precpu_stats"]["cpu_usage"]["total_usage"]
system_delta = stats["cpu_stats"]["system_cpu_usage"] - stats["precpu_stats"]["system_cpu_usage"]

def calculate_cpu_percent(stats) -> float:
"""
Calculate CPU usage percentage for a Docker container.

Args:
stats (dict): The container statistics dictionary
obtained from `container.stats(stream=False)`.

Returns:
float: The CPU usage percentage.
"""
cpu_delta = stats["cpu_stats"]["cpu_usage"]["total_usage"] - \
stats["precpu_stats"]["cpu_usage"]["total_usage"]
system_delta = stats["cpu_stats"]["system_cpu_usage"] - \
stats["precpu_stats"]["system_cpu_usage"]

if system_delta > 0:
return (cpu_delta / system_delta) * len(stats["cpu_stats"]["cpu_usage"]["percpu_usage"]) * 100.0
return (cpu_delta / system_delta) * \
len(stats["cpu_stats"]["cpu_usage"]["percpu_usage"]) * 100.0
return 0.0

def get_container_status_real_time():

def get_container_status_real_time() -> Optional[str]:
"""
Check running containers for high resource usage in real time.

This function monitors all containers and reports if:
- CPU usage exceeds 50%
- Memory usage exceeds 500 MB

Returns:
str or int: Warning message string if any container exceeds
thresholds; otherwise, returns None.
"""
containers = client.containers.list()

for container in containers:
stats = container.stats(stream=False)
cpu_percent = calculate_cpu_percent(stats)

if float(cpu_percent) > 50.00:
return f"The container {container.name} uses more than 50% of the available processor resources on the host"
return f"The container {container.name} uses more than 50% \
of the available processor resources on the host"

mem_usage_mb = stats["memory_stats"]["usage"] / (1024 * 1024)
if float(mem_usage_mb) > 500.00:
return f"The container {container.name} uses 500 MB of the available RAM resources on the host"

return 0





return f"The container {container.name} uses \
500 MB of the available RAM resources on the host"
return None
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
docker
pyTelegramBotAPI
python-dotenv
black
pylint
flake8
pytest
File renamed without changes.
Loading