Старый postinstall

This commit is contained in:
commit 4337a3f94e
349 changed files with 21945 additions and 0 deletions

9
tests/__init__.py Normal file
View file

@ -0,0 +1,9 @@
import subprocess
def get_network_interfaces():
interfaces = str.split(subprocess.run(["ls", "/sys/class/net/"], capture_output=True, text=True).stdout, "\n")
return interfaces[:-1]
get_network_interfaces()

Binary file not shown.

Binary file not shown.

Binary file not shown.

132
tests/docker_config.py Normal file
View file

@ -0,0 +1,132 @@
import logging
import subprocess
import os
import re
REGISTRY_URL = "dr.gosrv.ru"
REGISTRY_LOGIN = "dr_admin"
REGISTRY_PASSWORD = "Qweasdzxc123C@"
DOCKER_COMPOSE_FILE_PATH = "/usr/local/share/postinstall/portainer/"
class DockerConfig:
def check_installed(self, command: str) -> bool:
try:
return (
subprocess.run(
["which", command], capture_output=True, text=True
).returncode
== 0
)
except subprocess.SubprocessError as e:
logging.error(f"Error checking if {command} is installed: {e}")
return False
def install_docker(self):
try:
if not self.check_installed("docker"):
logging.info("Установка Docker...")
subprocess.run(["apt-get", "update"], check=True)
subprocess.run(["apt-get", "install", "-y", "docker.io"], check=True)
logging.info("Docker успешно установился")
if not self.check_installed("docker-compose"):
logging.info("Установка Docker Compose...")
subprocess.run(
["apt-get", "install", "-y", "docker-compose"], check=True
)
logging.info("Docker Compose успешно установился")
except subprocess.CalledProcessError as e:
logging.error(f"Ошибка при установке Docker: {e}")
raise
def check_docker_login(self, registry_url):
try:
result = subprocess.run(
["docker", "login", registry_url, "--password-stdin"],
input=b"\n",
capture_output=True,
text=True,
check=True,
)
return "login succeeded" in result.stdout.lower()
except subprocess.CalledProcessError as e:
logging.error(f"Error checking Docker login: {e}")
return False
def login_to_registry(self):
try:
if not self.check_docker_login(REGISTRY_URL):
logging.info("Вход в Docker registry...")
subprocess.run(
["docker", "login", REGISTRY_URL],
input=f"{REGISTRY_LOGIN}\n{REGISTRY_PASSWORD}\n".encode(),
check=True,
)
logging.info("Успешный вход в Docker registry")
except subprocess.CalledProcessError as e:
logging.error(f"Ошибка при входе в Docker registry: {e}")
raise
def install_portainer(self, port, login, password, ip):
try:
if not self.check_docker_login(REGISTRY_URL):
self.login_to_registry()
os.makedirs(os.path.dirname(DOCKER_COMPOSE_FILE_PATH), exist_ok=True)
docker_compose_content = f"""
version: '3'
services:
portainer:
image: dr.gosrv.ru/portainer
container_name: portainer
restart: unless-stopped
security_opt:
- no-new-privileges:true
volumes:
- /etc/localtime:/etc/localtime:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
- portainer_data:/data
- ./portainer_password:{DOCKER_COMPOSE_FILE_PATH}/portainer_password
ports:
- "{ip}:{port}:9000"
environment:
- ADMIN_USER={login}
- ADMIN_PASSWORD_FILE={DOCKER_COMPOSE_FILE_PATH}/portainer_password
volumes:
portainer_data:
"""
with open(DOCKER_COMPOSE_FILE_PATH + "docker-compose.yml", "w") as f:
f.write(docker_compose_content)
subprocess.run(
["htpasswd", "-nb", login, password],
stdout=open(DOCKER_COMPOSE_FILE_PATH + "portainer_password", "w"),
check=True,
)
subprocess.run(
[
"docker-compose",
"-f",
DOCKER_COMPOSE_FILE_PATH + "docker-compose.yml",
"up",
"-d",
],
check=True,
)
logging.info("Portainer успешно установлен")
except subprocess.CalledProcessError as e:
logging.error(f"Ошибка при установке Portainer: {e}")
raise
except IOError as e:
logging.error(f"Ошибка при создании файла: {e}")
raise
def validate_input(self, value, pattern, error_message):
if not re.match(pattern, value):
return False
return True

67
tests/test_docker.py Normal file
View file

@ -0,0 +1,67 @@
import unittest
from unittest.mock import patch, MagicMock
from docker_config import DockerConfig, REGISTRY_URL, REGISTRY_LOGIN, REGISTRY_PASSWORD, DOCKER_COMPOSE_FILE_PATH
class TestDockerConfig(unittest.TestCase):
def setUp(self):
self.docker_config = DockerConfig()
@patch("subprocess.run")
def test_check_installed_true(self, mock_run):
mock_run.return_value.returncode = 0
self.assertTrue(self.docker_config.check_installed("docker"))
@patch("subprocess.run")
def test_check_installed_false(self, mock_run):
mock_run.return_value.returncode = 1
self.assertFalse(self.docker_config.check_installed("docker"))
@patch("subprocess.run")
def test_install_docker(self, mock_run):
self.docker_config.install_docker()
mock_run.assert_any_call(["apt-get", "update"], check=True)
mock_run.assert_any_call(["apt-get", "install", "-y", "docker.io"], check=True)
mock_run.assert_any_call(
["apt-get", "install", "-y", "docker-compose"], check=True
)
@patch("subprocess.run")
def test_check_docker_login_success(self, mock_run):
mock_run.return_value.stdout = "Login Succeeded"
self.assertTrue(self.docker_config.check_docker_login("registry_url"))
@patch("subprocess.run")
def test_check_docker_login_failure(self, mock_run):
mock_run.return_value.stdout = "Login Failed"
self.assertFalse(self.docker_config.check_docker_login("registry_url"))
@patch("subprocess.run")
@patch("docker_config.DockerConfig.check_docker_login")
def test_login_to_registry(self, mock_check_login, mock_run):
mock_check_login.return_value = False
self.docker_config.login_to_registry()
mock_run.assert_called_once()
@patch("subprocess.run")
@patch("docker_config.DockerConfig.check_docker_login")
@patch("docker_config.DockerConfig.login_to_registry")
@patch("builtins.open", new_callable=unittest.mock.mock_open)
def test_install_portainer(self, mock_open, mock_login, mock_check_login, mock_run):
mock_check_login.return_value = True
self.docker_config.install_portainer("9000", "admin", "password", "127.0.0.1")
mock_open.assert_called()
mock_run.assert_called()
def test_validate_input_success(self):
self.assertTrue(
self.docker_config.validate_input("admin", r"^[a-zA-Z0-9_-]+$", "Error")
)
def test_validate_input_failure(self):
self.assertFalse(
self.docker_config.validate_input("admin@", r"^[a-zA-Z0-9_-]+$", "Error")
)
if __name__ == "__main__":
unittest.main()