Skip to content

Commit

Permalink
Refactoring code
Browse files Browse the repository at this point in the history
  • Loading branch information
orenlab committed Jun 17, 2024
1 parent 39bcf45 commit 21f74ea
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 22 deletions.
32 changes: 18 additions & 14 deletions app/core/adapters/docker_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,33 +180,37 @@ def __aggregate_container_details(self, container_id: str) -> dict:
container_id (str): The ID of the container.
Returns:
dict: A dictionary containing container details.
dict: A dictionary containing container details. The dictionary contains the following keys:
- 'name' (str): The name of the container.
- 'image' (str): The image used by the container.
- 'created' (str): The date and time the container was created.
- 'mem_usage' (str): The memory usage of the container.
- 'run_at' (str): The date and time the container was started.
- 'status' (str): The status of the container.
Raises:
ValueError: If container details retrieval fails.
"""
# Get the container details
container_details = self.__get_container_details(container_id)

# Extract the attributes and stats from the container details
attrs = container_details.attrs
stats = container_details.stats(decode=None, stream=False)

# Convert the 'Created' attribute to a datetime object
# Extract the creation date and time
created_at = datetime.fromisoformat(attrs['Created'])
created_day = created_at.date()
created_time = created_at.time().strftime("%H:%M:%S")

# Extract the day and time from the datetime object
created_day, created_time = created_at.date(), created_at.time().strftime("%H:%M:%S")

# Return a dictionary containing the container details
# Return the container details as a dictionary
return {
'name': attrs['Name'].strip("/").title(),
'image': attrs['Config']['Image'],
'created': f"{created_day}, {created_time}",
'mem_usage': self._naturalsize(stats['memory_stats']['usage']),
'run_at': self._naturaltime(datetime.fromisoformat(attrs['State']['StartedAt'])),
'status': attrs['State']['Status'],
'name': attrs['Name'].strip("/").title(), # Remove leading slash and capitalize the name
'image': attrs['Config']['Image'], # Get the image used by the container
'created': f"{created_day}, {created_time}", # Format the creation date and time
'mem_usage': self._naturalsize(stats.get('memory_stats', {}).get('usage', 0)), # Get the memory usage
'run_at': self._naturaltime(datetime.fromisoformat(attrs.get('State', {}).get('StartedAt', ''))),
# Format the start date and time
'status': attrs.get('State', {}).get('Status', ''), # Get the status of the container
}

def retrieve_image_details(self) -> Union[List[Dict[str, str]], Dict[None, None]]:
Expand Down
16 changes: 8 additions & 8 deletions app/core/handlers/default_handlers/containers_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ def __init__(self, bot):

def _get_container_data(self):
"""
Use the DockerAdapter to gather information about containers.
Retrieve information about containers using the DockerAdapter.
Returns:
dict: The container information if successful, an empty dictionary otherwise.
dict: A dictionary containing container information if successful, otherwise an empty dictionary.
"""
try:
# Use the DockerAdapter to check the image details
data = self.docker_adapter.retrieve_image_details()
return data
except DockerException:
# Log an error if there is a DockerException
bot_logger.error(f'Failed at {__name__}: Error connecting to the Docker socket')
# Attempt to retrieve image details using the DockerAdapter
return self.docker_adapter.retrieve_image_details()
except DockerException as e:
# Log an error message if a DockerException occurs
error_msg = f'Failed at {__name__}: {e}'
bot_logger.error(error_msg)
return {}

def _compile_message(self) -> tuple[str, list[str] | None]:
Expand Down

0 comments on commit 21f74ea

Please sign in to comment.