Skip to content

Commit

Permalink
fix(helper.py): using getpass.getuser() instead of os.getlogin() as i…
Browse files Browse the repository at this point in the history
…t is more robust and does not cause the "No such device or address" issue
  • Loading branch information
MRColorR committed Oct 29, 2024
1 parent 2320d19 commit 7937b0f
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions utils/helper.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
import os
import getpass
import platform
import subprocess
import logging
from colorama import Fore, Style


def is_user_root():
"""
Check if the current user is the root user on Linux.
On macOS and Windows, it always returns False since we don't manage Docker groups.
"""
return os.geteuid() == 0 if platform.system().lower() == 'linux' else False


def is_user_in_docker_group():
"""
Check if the current user is in the Docker group on Linux.
This function is skipped on Windows and macOS.
"""
if platform.system().lower() != 'linux':
return True

user = os.getlogin()
# use getpass.getuser() instead of os.getlogin() as it is more robust
user = getpass.getuser()
logging.info(f"Detected user: {user}")
logging.info(f"Checking if user '{user}' is in the Docker group...")
groups = subprocess.run(["groups", user], capture_output=True, text=True)
return "docker" in groups.stdout


def create_docker_group_if_needed():
"""
Create the Docker group if it doesn't exist and add the current user to it on Linux.
Expand All @@ -37,14 +43,16 @@ def create_docker_group_if_needed():
subprocess.run(["sudo", "groupadd", "docker"], check=True)
logging.info(f"{Fore.GREEN}Docker group created successfully.{Style.RESET_ALL}")

user = os.getlogin()
# use getpass.getuser() instead of os.getlogin() as it is more robust
user = getpass.getuser()
logging.info(f"Adding user '{user}' to Docker group...")
subprocess.run(["sudo", "usermod", "-aG", "docker", user], check=True)
logging.info(f"{Fore.GREEN}User '{user}' added to Docker group. Please log out and log back in.{Style.RESET_ALL}")
except subprocess.CalledProcessError as e:
logging.error(f"{Fore.RED}Failed to add user to Docker group: {e}{Style.RESET_ALL}")
raise RuntimeError("Failed to add user to Docker group.") from e


def run_docker_command(command, use_sudo=False):
"""
Run a Docker command, optionally using sudo.
Expand All @@ -60,6 +68,7 @@ def run_docker_command(command, use_sudo=False):
command.insert(0, "sudo")
return subprocess.run(command, check=True, capture_output=True, text=True)


def setup_service(service_name="docker.binfmt", service_file_path='./.resources/.files/docker.binfmt.service'):
"""
Set up a service on Linux systems, defaulting to setting up the Docker binfmt service.
Expand Down

0 comments on commit 7937b0f

Please sign in to comment.