Skip to content

Commit

Permalink
I am continuing to work on detailed information about containers
Browse files Browse the repository at this point in the history
  • Loading branch information
orenlab committed Jul 9, 2024
1 parent 44ab6ec commit 3f7d28e
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 52 deletions.
23 changes: 0 additions & 23 deletions app/core/adapters/containers_base_data.py

This file was deleted.

40 changes: 24 additions & 16 deletions app/core/adapters/docker_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from humanize import naturalsize, naturaltime

from app import config
from app.core.adapters.containers_base_data import ContainerData
from app.core.logs import bot_logger


Expand Down Expand Up @@ -113,33 +112,30 @@ def _naturaltime(timestamp: datetime) -> str:

def __list_containers(self) -> List[str]:
"""
List all docker containers and retrieve their image tags.
Retrieves a list of all running containers and returns their short IDs.
Returns:
List[str]: A list of image tags of all running containers.
List[str]: A list of short IDs of the running containers.
Raises:
FileNotFoundError: If the Docker executable is not found.
FileNotFoundError: If the Docker client cannot be created.
ConnectionError: If there is an error connecting to the Docker daemon.
"""
try:
# Create a Docker client instance
client = self.__create_docker_client()

# Retrieve a list of all running containers
containers_raw = client.containers.list(all=True)

# Extract the image tags
image_tags = [container.short_id for container in containers_raw]
containers_id_raw = client.containers.list(all=True)

# Store the image tags in the ContainerData class
ContainerData.container_id = image_tags
# Extract the container short IDs
containers_id = [container.short_id for container in containers_id_raw]

# Log the created container list
bot_logger.debug(f"Container list created: {image_tags}")
bot_logger.debug(f"Container list created: {containers_id}")

# Return the list of image tags
return image_tags
# Return the list of short IDs
return containers_id

except (FileNotFoundError, ConnectionError) as e:
# Log an error message if an exception occurs
Expand Down Expand Up @@ -235,16 +231,16 @@ def retrieve_image_details(self) -> Union[List[Dict[str, str]], Dict[None, None]

# Retrieve the list of containers
bot_logger.debug("Retrieving list of containers...")
containers = self.__list_containers()
containers_id = self.__list_containers()

if not containers:
if not containers_id:
# Log a message if no containers are found
bot_logger.debug("No containers found. Returning empty dictionary.")
return {}

# Retrieve details for each container
bot_logger.debug("Retrieving details for each container...")
details = [self.__aggregate_container_details(container) for container in containers]
details = [self.__aggregate_container_details(container_id) for container_id in containers_id]

# Log a message indicating successful retrieval of details
bot_logger.debug(f"Details retrieved successfully: {details}")
Expand All @@ -254,3 +250,15 @@ def retrieve_image_details(self) -> Union[List[Dict[str, str]], Dict[None, None]
# Log an error if an exception occurs
bot_logger.error(f"Failed at {__name__}: {e}")
return {}

def get_full_container_details(self, container_id: str) -> dict:
"""
Retrieve and return the attributes of a Docker container as a dictionary.
Args:
container_id (str): The ID of the container.
Returns:
dict: A dictionary containing the attributes of the Docker container.
"""
return self.__get_container_details(container_id).attrs
6 changes: 1 addition & 5 deletions app/core/handlers/default_handlers/containers_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from docker.errors import DockerException
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton

from app.core.adapters.containers_base_data import ContainersFactory
from app.core.adapters.docker_adapter import DockerAdapter
from app.core.handlers.handler import HandlerConstructor
from app.core.logs import bot_logger
Expand Down Expand Up @@ -151,14 +150,11 @@ def __build_inline_keyboard(container_names: List[str]) -> InlineKeyboardMarkup:
with buttons for each container name. The buttons are created using the InlineKeyboardButton
class and the callback_data is set to a specific format.
"""
# Get the containers factory
containers_factory = ContainersFactory().containers_factory

# Create a list of InlineKeyboardButton objects for each container name
buttons = [
InlineKeyboardButton(
text=container_name,
callback_data=containers_factory.new(container_id=container_name)
callback_data='__get_full__' + container_name
)
for container_name in container_names
]
Expand Down
18 changes: 10 additions & 8 deletions app/core/handlers/inline_handlers/containers_full_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
"""
from telebot.types import CallbackQuery

from app.core.adapters.containers_base_data import ContainerData, ContainersFactory
from app.core.adapters.docker_adapter import DockerAdapter
from app.core.handlers.handler import HandlerConstructor
from app.core.logs import logged_inline_handler_session


class InlineContainerFullInfoHandler(HandlerConstructor, ContainerData):
class InlineContainerFullInfoHandler(HandlerConstructor):

def handle(self):
"""
Expand All @@ -20,9 +20,7 @@ def handle(self):
edits the message text with the container ID, and removes the reply markup.
"""

containers_factory = ContainersFactory().containers_factory

@self.bot.callback_query_handler(func=None, config=containers_factory.filter())
@self.bot.callback_query_handler(func=lambda call: call.data.startswith('__get_full__'))
@logged_inline_handler_session
def handle_containers_full_info(call: CallbackQuery):
"""
Expand All @@ -33,13 +31,17 @@ def handle_containers_full_info(call: CallbackQuery):
Args:
call (CallbackQuery): The callback query object.
"""
# Retrieve the container ID from the callback data
container_id = containers_factory.parse(callback_data=call.data).get('container_id', '')

# Extract the container ID from the callback data
container_name = call.data.split("__get_full__")[1]

container_details = DockerAdapter().get_full_container_details(container_name.lower())
print(container_details)

# Edit the message text with the container ID
self.bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=container_id,
text=f"Some details about: {container_name}\n\n{container_details}",
reply_markup=None
)

0 comments on commit 3f7d28e

Please sign in to comment.