import sys
import os
#from threading import Thread
#from queue import Queue, Empty

from py_module.whiptail import Whiptail
import py_module.yaml as yaml
import py_module.docker as docker
import py_module.jinja2 as jinja
import subprocess
import string
#from .services.base_service import Base_service
from .base import Base
from .services import base_service

from .docker_installer import Docker_installer
from .services import *
#####
class DS_Only(Base):
    def preload(self):
        with Docker_installer(logger_level = self.logger_level) as run:
            pass
        self.menu = (
            ('ds-rabbitmq','Р7-ДС: Служба базы данных','ON'),
            ('ds-postgres','Р7-ДС: MQTT-служба очередей','ON'),
            ('ds-redis','Р7-ДС: Сервер кэширования','ON'),
            ('ds-docserver','Р7-ДС: Служба документ-сервера','ON'),
            ('ds-frontend','Р7-ДС: Веб-интерфейс','ON')
        );
#        self.services = {}
#        for service in self.menu:
#            getattr(self,"services")[service[0].replace('-','_')] = getattr(globals()[service[0].replace('-','_')], service[0].replace('-','_'))()

#            setattr(self, "class_" + service[0].replace('-','_'), getattr(globals()[service[0].replace('-','_')], service[0].replace('-','_'))())
#        dumper.dump(vars(self));

        self.logger.info('Инициализирую основные переменные')
##########################################################################
##            DEFAULT ENVIRONMENT FOR INSTALLATION                      ##
##                                                                      ##
##       self.ENV_NAME = list(default_value, select_value)              ##
##                                                                      ##
##########################################################################

        if not self.DETALIZATION:
            self.DETALIZATION = 1
        self.INSTALL_DUMP_PATH='./images'
        self.INSTALL_CONF_PATH='./configs'
        self.BACK_MENU=[False]

##########################################################################
##            DEFAULT ENVIRONMENT FOR IMAGE DOCKER                      ##
##                                                                      ##
##       self.ENV_NAME = list(default_value, select_value)              ##
##                                                                      ##
##########################################################################

### ENVIRONMENT GERENAL
#        self.DETALIZATION = 1
#        self.CS_VERSION=['latest']
        self.CS_VERSION=['2025.3.12.15877']
#        self.DS_VERSION=['latest']
        self.DS_VERSION=['2025.3.1.923']
        self.MAIL_VERSION=['1.0.35-swarm']
        self.PREFIX_CS=['cs']
        self.PREFIX_DS=['ds']
        self.PREFIX_MAIL=['mail']
        self.PREFIX_TEAM=['team']

#        self.NODE_FRONTEND_CERT_WILDCARD
        self.GENERAL_NODE_LOGS_STORAGE=['./support_logs']

        self.CS_NODE_FRONTEND_CERT_CRT_PATH=['./configs/ssl']
        self.CS_NODE_FRONTEND_CERT_CRT_FILE=['fullchain.crt']
        self.CS_NODE_FRONTEND_CERT_KEY_PATH=['./configs/ssl']
        self.CS_NODE_FRONTEND_CERT_KEY_FILE=['privkey.key']

        self.CS_NODE_PSQL_STORAGE=['./data/db/cs_database']
        self.CS_NODE_FILE_STORAGE=['./data/cs_storage/root']
        self.CS_NODE_INDEX_STORAGE=['./data/search_index']

        self.DS_NODE_PSQL_STORAGE=['./data/db/ds_database']
        self.DS_NODE_FILE_STORAGE=['./data/ds_storage']
        self.DS_NODE_LICENSE_FILE=['./license/license.lic']

        self.MAIL_NODE_PSQL_STORAGE=['./data/db/mail_database']
        self.MAIL_NODE_MAILDIR_STORAGE=['./data/mail_storage/maildir']
        self.MAIL_NODE_DKIM_STORAGE=['./data/mail_storage/dkim_keys']

#env for published port of services on node
        self.CS_NODE_API_PORT_PUBLISHED=['38033']
        self.CS_NODE_RABBIT_PORT_PUBLISHED=['5672']
        self.CS_NODE_PSQL_PORT_PUBLISHED=['5432']
        self.CS_NODE_DRAW_PORT_PUBLISHED=['3005']
        self.CS_NODE_FILESTORAGE_PORT_HTTP_PUBLISHED=['11580']
        self.CS_NODE_FILESTORAGE_PORT_TCP_PUBLISHED=['11581']
        self.CS_NODE_SEARCH_PORT_PUBLISHED=['2664']
        self.CS_NODE_SSO_PORT_PUBLISHED=['38034']
        self.CS_NODE_REGISTRY_PORT_PUBLISHED=['7777']

        self.DS_NODE_DOCSERVER_PORT_PUBLISHED=['8000']
        self.DS_NODE_RABBIT_PORT_PUBLISHED=['5673']
        self.DS_NODE_PSQL_PORT_PUBLISHED=['5433']
        self.DS_NODE_REDIS_PORT_PUBLISHED=['6379']

        self.MAIL_NODE_API_PORT_PUBLISHED=['8891']
        self.MAIL_NODE_PSQL_PORT_PUBLISHED=['5434']
        self.MAIL_NODE_DKIM_PORT_PUBLISHED=['8891']
        self.MAIL_NODE_MTA_PORT_SMTP_PUBLISHED=['25']
        self.MAIL_NODE_MTA_PORT_SMTPS_PUBLISHED=['465']
        self.MAIL_NODE_MTA_PORT_SMTPS_TLS_PUBLISHED=['587']
        self.MAIL_NODE_MDA_PORT_POP3_PUBLISHED=['110']
        self.MAIL_NODE_MDA_PORT_POP3S_PUBLISHED=['995']
        self.MAIL_NODE_MDA_PORT_IMAP_PUBLISHED=['143']
        self.MAIL_NODE_MDA_PORT_IMAPS_PUBLISHED=['993']

### ENVIRONMENT CS
#env for frontend
        self.CS_FRONTEND_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-frontend']
        self.CS_FRONTEND_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_FRONTEND_CONTAINER_NAME=['cs-frontend']

        self.CS_FRONTEND_HOST=['cs-frontend']
        self.CS_FRONTEND_SCHEME=['https']
        self.CS_FRONTEND_SCHEME_REDIRECT=[True]
        self.CS_FRONTEND_DOMAIN=['domain.ru']
        self.CS_FRONTEND_HTTP_PORT=['80']
        self.CS_FRONTEND_HTTPS_PORT=['443']
        self.CS_FRONTEND_PREFIX_CDDISK=['disk','disk']
        self.CS_FRONTEND_PREFIX_PAYMENTS=['payments','payments']
        self.CS_FRONTEND_PREFIX_PAGES=['pages','pages']
        self.CS_FRONTEND_PREFIX_FORMS=['forms','forms']
        self.CS_FRONTEND_PREFIX_DRAW=['draw','draw']
        self.CS_FRONTEND_PREFIX_ADMIN=['admin','admin']
        self.CS_FRONTEND_PREFIX_CDMAIL=['mail','mail']
        self.CS_FRONTEND_PREFIX_CONTACTS=['contacts','contacts']
        self.CS_FRONTEND_PREFIX_CALENDAR=['calendar','calendar']
        self.CS_FRONTEND_PREFIX_PROJECTS=['projects','projects']
        self.CS_FRONTEND_STORAGE=['/app']
        self.CS_FRONTEND_CERT_PATH=['/etc/nginx/ssl']
        self.CS_FRONTEND_CERT_CRT_FILE=['fullchain.crt']
        self.CS_FRONTEND_CERT_KEY_FILE=['privkey.key']
#env for rabbit
        self.CS_RABBIT_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-rabbitmq']
        self.CS_RABBIT_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_RABBIT_CONTAINER_NAME=['cs-rabbitmq']

        self.CS_RABBIT_HOST=['cs-rabbit']
        self.CS_RABBIT_USER=['guest']
        self.CS_RABBIT_PWD=['guest']
        self.CS_RABBIT_PORT=['5672']
        self.CS_RABBIT_CLIENT_TIMEOUT=['10']
#env for psql
        self.CS_PSQL_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-postgres']
        self.CS_PSQL_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_PSQL_CONTAINER_NAME=['cs-psql']

        self.CS_TEAM_CLIENT_ID=['','']
        self.CS_TEAM_CLIENT_SECRET=['','']
        self.CS_PAGES_CLIENT_ID=['','']
        self.CS_PAGES_CLIENT_SECRET=['','']
        self.CS_FORMS_CLIENT_ID=['','']
        self.CS_FORMS_CLIENT_SECRET=['','']

        self.CS_PSQL_HOST=['cs-psql']
        self.CS_PSQL_DB=['postgres']
        self.CS_PSQL_USER=['postgres']
        self.CS_PSQL_PWD=['pg_pass']
        self.CS_PSQL_PORT=['5432']
        self.CS_PSQL_DATA=['/var/lib/postgresql/data']
        self.CS_PSQL_CORE_MACHINE_KEY=['empty']
#env for draw
        self.CS_DRAW_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-draw']
        self.CS_DRAW_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_DRAW_CONTAINER_NAME=['cs-draw']

        self.CS_DRAW_HOST=['cs-draw']
        self.CS_DRAW_PORT=['3005']
#env for api
        self.CS_API_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-api']
        self.CS_API_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_API_CONTAINER_NAME=['cs-api']

        self.CS_API_HOST=['cs-api']
        self.CS_API_PORT=['38033']
        self.CS_API_LOGLEVEL=['Trace']
        self.CS_API_INTERFACE=['+']
        self.CS_API_ALLOWHOSTS=['*']
        self.CS_API_HTTP_TIMEOUT=['00:10:00']
        self.CS_API_CERT_OAUTH_FILE=['domain.pfx']
        self.CS_API_CERT_PATH=['/app/ssl']
        self.CS_API_CERT_PATHKEY=['/app/ssl']
        self.CS_API_STORAGE_TMP=['/app/tmp_storage']
        self.CS_API_ROOTNODE=['False']
#env for api and processing
        self.CS_STORAGE_S3_REGION=['region']
        self.CS_STORAGE_S3_ENDPOINT=['http://localhost/s3']
        self.CS_STORAGE_S3_BUCKET_NAME=['ds-storage']
        self.CS_STORAGE_S3_ACCESS_KEY_ID=['AKID2']
        self.CS_STORAGE_S3_SECRET_ACCESS_KEY=['SECRET']
#env for processing
        self.CS_PROCESSING_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-processing']
        self.CS_PROCESSING_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_PROCESSING_CONTAINER_NAME=['cs-processing']

        self.CS_PROCESSING_HOST=['cs-processing']
        self.CS_PROCESSING_LOGLEVEL=['Trace']
        self.CS_PROCESSING_STORAGE_TMP=['/app/tmp_storage']
        self.CS_PROCESSING_ROOTNODE=['False']
        self.CS_PROCESSING_PUSH_CERT_PATH=['None']
        self.CS_PROCESSING_GCM_AUTHKEY=['None']
        self.CS_PROCESSING_GCM_URL=['None']
        self.CS_PROCESSING_VOIP_CERT=['None']
        self.CS_PROCESSING_VOIP_CERT_PWD=['None']
        self.CS_PROCESSING_SANDBOX_CERT=['None']
        self.CS_PROCESSING_SANDBOX_CERT_PWD=['None']
        self.CS_PROCESSING_PUSH_PRODUCTION_ONLY=['None']
#env for filestorage
        self.CS_FILESTORAGE_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-filestorage']
        self.CS_FILESTORAGE_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_FILESTORAGE_CONTAINER_NAME=['cs-filestorage']

        self.CS_FILESTORAGE_HOST=['cs-filestorage']
        self.CS_FILESTORAGE_PORT_HTTP=['11580']
        self.CS_FILESTORAGE_PORT_TCP=['11581']
        self.CS_FILESTORAGE_HTTP_INTERFACE=['0.0.0.0']
        self.CS_FILESTORAGE_ALLOWHOSTS=['*']
        self.CS_FILESTORAGE_TCP_INTERFACE=['0.0.0.0']
        self.CS_FILESTORAGE_ROOTNODE=['False']
        self.CS_FILESTORAGE_LOGLEVEL=['Trace']
        self.CS_FILESTORAGE_STORAGE=['/var/filestorage']
#env for search
        self.CS_SEARCH_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-searchapi']
        self.CS_SEARCH_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_SEARCH_CONTAINER_NAME=['cs-search']

        self.CS_SEARCH_HOST=['cs-search']
        self.CS_SEARCH_PORT=['2664']
        self.CS_SEARCH_INTERFACE=['+']
        self.CS_SEARCH_ALLOWHOSTS=['*']
        self.CS_SEARCH_INDEXFOLDER=['/app/data']
        self.CS_SEARCH_LOGLEVEL=['Trace']
        self.CS_SEARCH_CLEARMEMORYINTERVAL=['00:01:00']
        self.CS_SEARCH_CLOSEINDEXINTERVAL=['0.23:30:00']
        self.CS_SEARCH_INDEXLIVEINTERVAL=['60']
        self.CS_SEARCH_NEVERCLOSEINDEX=['True']
        self.CS_SEARCH_USELOCALTERMREPOSITORY=['True']
        self.CS_SEARCH_PERCENTMEMORYUSAGE=['80']
        self.CS_SEARCH_SHARDCOUNT=['16']
        self.CS_SEARCH_AVAILABLEPHYSICALMEMORY=['8000']
#env for registry
        self.CS_REGISTRY_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-registry']
        self.CS_REGISTRY_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_REGISTRY_CONTAINER_NAME=['cs-registry']

        self.CS_REGISTRY_HOST=['cs-registry']
        self.CS_REGISTRY_PORT=['7777']
        self.CS_REGISTRY_INTERFACE=['0.0.0.0']
        self.CS_REGISTRY_ALLOWHOSTS=['*']
        self.CS_REGISTRY_LOGLEVEL=['Trace']
#env for sso
        self.CS_SSO_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/cs/cddisk-ssoapi']
        self.CS_SSO_IMAGE_VERSION=[self.CS_VERSION[0]]
        self.CS_SSO_CONTAINER_NAME=['cs-ssoapi']

        self.CS_SSO_HOST=['cs-sso']
        self.CS_SSO_PORT=['38034']
        self.CS_SSO_INTERFACE=['+']
        self.CS_SSO_ALLOWHOSTS=['*']
        self.CS_SSO_LOGLEVEL=['Trace']
        self.CS_LDAP_ENDPOINT=['']
        self.CS_LDAP_USER=['']
        self.CS_LDAP_PWD=['']
        self.CS_LDAP_LOGINPOSTFIX=['']
        self.CS_LDAP_TYPE=['ActiveDirectory']
        self.CS_SSO_IDP_METADATA=['empty']
        self.CS_SSO_SAML_SIGNATUREALGORITM=['http://www.w3.org/2001/04/xmldsig-more#rsa-sha256']
        self.CS_SSO_ISSUER=['empty']
        self.CS_SSO_SIGN_CERT=['domain.pfx']
        self.CS_SSO_SIGN_CERT_PWD=['empty']
        self.CS_SSO_CERT_VALID_MODE=['None']
        self.CS_SSO_REVOCATION_MODE=['NoCheck']


### ENVIRONMENT DS
#env for frontend
        self.DS_FRONTEND_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/ds/ds-frontend']
        self.DS_FRONTEND_IMAGE_VERSION=[self.DS_VERSION[0]]
        self.DS_FRONTEND_CONTAINER_NAME=['ds-frontend']

        self.DS_FRONTEND_HOST=['ds-frontend']
        self.DS_FRONTEND_PREFIX_DOCSERVER=['doc']
        self.DS_FRONTEND_SCHEME=self.CS_FRONTEND_SCHEME
        self.DS_FRONTEND_SCHEME_REDIRECT=self.CS_FRONTEND_SCHEME_REDIRECT
        self.DS_FRONTEND_DOMAIN=self.CS_FRONTEND_DOMAIN
        self.DS_FRONTEND_HTTP_PORT=['80']
        self.DS_FRONTEND_HTTPS_PORT=['443']
#env for docserver
        self.DS_DOCSERVER_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/ds/ds-app']
        self.DS_DOCSERVER_IMAGE_VERSION=[self.DS_VERSION[0]]
        self.DS_DOCSERVER_CONTAINER_NAME=['ds-docserver']

        self.DS_DOCSERVER_HOST=['ds-docserver']
        self.DS_DOCSERVER_PORT=['8000']
        self.DS_DOCSERVER_JWT_KEY=['empty']
        self.DS_DOCSERVER_STORAGE_KEY=self.DS_DOCSERVER_JWT_KEY
#env for docserver over s3
        self.DS_STORAGE_S3_REGION=['region']
        self.DS_STORAGE_S3_ENDPOINT=['http://localhost/s3']
        self.DS_STORAGE_S3_BUCKET_NAME=['ds-storage']
        self.DS_STORAGE_S3_ACCESS_KEY_ID=['AKID2']
        self.DS_STORAGE_S3_SECRET_ACCESS_KEY=['SECRET']
#env for rabbit
        self.DS_RABBIT_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/ds/ds-rabbitmq']
        self.DS_RABBIT_IMAGE_VERSION=[self.DS_VERSION[0]]
        self.DS_RABBIT_CONTAINER_NAME=['ds-rabbitmq']

        self.DS_RABBIT_HOST=['ds-rabbit']
        self.DS_RABBIT_USER=['guest']
        self.DS_RABBIT_PWD=['guest']
        self.DS_RABBIT_PORT=['5672']
#env for psql
        self.DS_PSQL_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/ds/ds-postgres']
        self.DS_PSQL_IMAGE_VERSION=[self.DS_VERSION[0]]
        self.DS_PSQL_CONTAINER_NAME=['ds-postgres']

        self.DS_PSQL_HOST=['ds-psql']
        self.DS_PSQL_DB=['postgres']
        self.DS_PSQL_USER=['postgres']
        self.DS_PSQL_PWD=['pg_pass']
        self.DS_PSQL_PORT=['5432']
#env for redis
        self.DS_REDIS_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/ds/ds-redis']
        self.DS_REDIS_IMAGE_VERSION=[self.DS_VERSION[0]]
        self.DS_REDIS_CONTAINER_NAME=['ds-redis']

        self.DS_REDIS_HOST=['ds-redis']
        self.DS_REDIS_PORT=['6379']

### ENVIRONMENT DS
#env for mailserver
        self.MAIL_MTA_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/mail/mail-server']
        self.MAIL_MTA_IMAGE_VERSION=['1.0.36-swarm']
        self.MAIL_MTA_CONTAINER_NAME=['mail-server']

        self.MAIL_DOMAIN=['domain.ru']
        self.MAIL_MTA_HOST=['mx']
        self.MAIL_MTA_PORT_SMTP=['25']
        self.MAIL_MTA_PORT_SMTPS=['465']
        self.MAIL_MTA_PORT_SMTPS_TLS=['587']
        self.MAIL_MDA_HOST=['mx']
        self.MAIL_MDA_PORT_POP3=['110']
        self.MAIL_MDA_PORT_POP3S=['995']
        self.MAIL_MDA_PORT_IMAP=['143']
        self.MAIL_MDA_PORT_IMAPS=['993']
        self.MAIL_MDA_MAILDIR_STORAGE=['/mail']
        self.MAIL_MTA_CERT_PATH=['/etc/ssl']
        self.MAIL_MTA_CERT_CRT_FILE=['mail_cert.pem']
        self.MAIL_MTA_CERT_KEY_FILE=['mail_key.pem']
#env for mail-api
        self.MAIL_API_PORT=['8084']
#env for psql
        self.MAIL_PSQL_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/mail/mail-psql']
        self.MAIL_PSQL_IMAGE_VERSION=[self.MAIL_VERSION[0]]
        self.MAIL_PSQL_CONTAINER_NAME=['mail-psql']

        self.MAIL_PSQL_HOST=['pgsql-server']
        self.MAIL_PSQL_DB=['postfix']
        self.MAIL_PSQL_USER=['postfix']
        self.MAIL_PSQL_PWD=['pg_pass']
        self.MAIL_PSQL_PORT=['5432']
        self.MAIL_PSQL_DATA=['/var/lib/postgresql/data']

#env for opendkim
        self.MAIL_DKIM_IMAGE_NAME=['downloads.r7-office.ru:9011/r7office/mail/mail-opendkim']
        self.MAIL_DKIM_IMAGE_VERSION=[self.MAIL_VERSION[0]]
        self.MAIL_DKIM_CONTAINER_NAME=['mail-opendkim']

        self.MAIL_DKIM_HOST=['opendkim']
        self.MAIL_DKIM_PORT=['8891']

        self.MAIL_DKIM_KEYS_PATH=['/etc/opendkim/keys']
        self.MAIL_DKIM_KEYTABLE_PATH=['/etc/opendkim/KeyTable']
        self.MAIL_DKIM_SIGNINGTABLE_PATH=['/etc/opendkim/SigningTable']
        self.MAIL_DKIM_TRUSTEDHOSTS_PATH=['/etc/opendkim/TrustedHosts']


### ENVIRONMENT TEAM
#env for rabbit

        self.services = {}
        for service in self.menu:
            getattr(self,"services")[service[0].replace('-','_')] = getattr(globals()[service[0].replace('-','_')], service[0].replace('-','_'))


        self.components={};

        self.compose={
#            'version':'3.3',
#            'name': 'cddisk',
            'services': {},
            'networks': {
                'net-ds': {
                    'name': f'net-{self.PREFIX_DS[0]}',
                    'driver': 'bridge',
                    'attachable': 'true'
                },
            },
            "volumes": {
                'ds-www': {}
            }
        };
        self.select_components=None
        self.dockercli = docker.from_env();

    def postload(self):
        self.get_service();
        if self.BACK_MENU[0]==True:
            return
        self.load_images(['ds-app.tar.gz','ds-frontend.tar.gz','ds-postgres.tar.gz','ds-rabbitmq.tar.gz','ds-redis.tar.gz']);
#        self.get_parameters(exit_target = self.exit_target);
        base_ser = base_service.Base_service()
        test=base_ser.status_dns(f"{self.DS_FRONTEND_PREFIX_DOCSERVER[-1]}.{self.CS_FRONTEND_DOMAIN[-1]}")
        test2=base_ser.status_ram(8)
        test3=base_ser.status_proc(4)
#        test4=base_ser.status_host_port(self)
        test5=base_ser.status_hdd()
        self.build_compose();
        if self.form.yesno(test+test2+test3, default="yes"):
            if self.form.yesno(test5, default="yes"):
                self.build_configs()
                self.deploy()
            else:
                return
        else:
            return
        return self;

        # self.build_compose();
        # self.build_configs();
        # self.deploy();
        # return self;
    def load_images(self, images: list = []):
        outputs=[];
        self.logger.info(f'Начинаю импорт дампа образов: {images}')
        for image in images:
            self.logger.debug(f'Открываю файл дампа: {self.INSTALL_DUMP_PATH}/{image}')
            if os.path.isfile(f'{self.INSTALL_DUMP_PATH}/{image}'):
                with open(f'{self.INSTALL_DUMP_PATH}/{image}', 'rb') as file:
                    print(f'\nЗагружаю dump образов:\n{sys.path[0]}/images/{image}\n');
                    self.logger.info(f'Загружаю dump образов: {self.INSTALL_DUMP_PATH}/{image}')
                    try:
                        outputs = outputs + self.dockercli.images.load(file);
                    except:
                        self.logger.error(f'Произошла ошибка при загрузке docker-образов из dump-файла: {image}')
                        return self.msgbox(f'Произошла ошибка при загрузке docker-образов из dump-файла {image}.');
            else:
                self.logger.error(f'Файл dump образов отсутствует: {self.INSTALL_DUMP_PATH}/{image}')

    def get_service(self, exit_target = None):
        self.response = ([
            'ds-rabbitmq',
            'ds-postgres',
            'ds-redis',
            'ds-docserver',
            'ds-frontend',
            ], 0);
        if not self.response[1]:
            self.select_components = self.response[0];
            self.logger.info(f'Выбраны компоненты: {self.select_components}')
#            print (self.select_components);
            for item in self.select_components:
                print(item)
                self.logger.info(f'Вызываю модуль: {item.replace("-","_")}.py')
                with self.services[item.replace('-','_')](**dict(filter(lambda item: item[0]==item[0].upper(), vars(self).items())), select_components = self.select_components, logger_level = self.logger_level) as run:
                    run.go();
                    if self.BACK_MENU[0]==True:
                        return        
                    for name, value in run.get_constants().items():
                        setattr(self, name, value);
#                    print(run.get_service())
                    self.components.update(run.get_service())
        return self;

    def build_compose(self):
        self.compose['services'] = self.components;
        self.logger.info(f'Открываю compose-файл ds.yaml на запись')
        with open('ds.yaml', 'w') as f:
            self.logger.info(f'Выгружаю compose-файл ds.yaml')
            yaml.dump(self.compose, f);

    def build_configs(self):
        self.logger.info(f'Произвожу поиск файлов-шаблонов конфигураций')
        for root, dirs, files in os.walk(f'{self.INSTALL_CONF_PATH}/ssl'):
            for file in files:
                if file.endswith('.j2'):
                    self.logger.info(f'Вызываю шаблонизатор Jinja2 на файл {root}/{file}')
                    env = jinja.Environment(loader=jinja.FileSystemLoader([root]))
                    template = env.get_template(file);
                    self.logger.info(f'Открываю файл {root}/{file.replace(".j2", "")} на запись.')
                    with open(f'{root}/{file.replace(".j2", "")}', 'w') as f:
                        self.logger.info(f'Произвожу рендеринг шаблона и экспорт в файл')
                        f.write(template.render(self.__dict__));
                        self.logger.info(f'Файл {root}/{file.replace(".j2", "")} создан.')

    def deploy(self):
        print (f'\n\nПроизвожу установку продукта.\n\n############\n#### ВНИМАНИЕ: НЕ ОСТАНАВЛИВАЙТЕ ПРОЦЕСС\n############\n\n');

        command = [f'{sys.path[0]}/runtime/docker-plugins/docker-compose', '-f', f'{sys.path[0]}/ds.yaml', 'up', '--force-recreate', '-d', '-V']#, '--remove-orphans']
        return_code, stdout, stderr = self.subprocess(command, fd_stderr=sys.stdout)
        if return_code != 0:
            self.logger.error(f'При попытке запуска команды ({command}) произошли ошибки')
            for err in stderr: self.logger.error(err) if 'error' in err.lower() else self.logger.info(err)
            self.msgbox(f'Установка не удалась. Обратитесь в техподдержку Р7-Офис')
        else:
            for err in stderr: self.logger.debug(err)
            self.logger.info('Docker Compose Plugin завершился без ошибок.')
            self.msgbox(f'Установка завершена.\nДля проверки работы перейдите по адресу:\nhttps://{self.DS_FRONTEND_PREFIX_DOCSERVER[-1]}.{self.CS_FRONTEND_DOMAIN[-1]}');
