Skip to content

Commit

Permalink
Merge pull request #24 from zeerayne/feature/rac-ras-mode
Browse files Browse the repository at this point in the history
Режим работы через сервер администрирования RAS
  • Loading branch information
zeerayne authored Dec 9, 2024
2 parents 735c5fe + f067dad commit e98ca25
Show file tree
Hide file tree
Showing 55 changed files with 1,756 additions and 581 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.*
24 changes: 0 additions & 24 deletions .flake8

This file was deleted.

4 changes: 2 additions & 2 deletions .github/workflows/pytest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Install Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install Poetry
uses: abatilo/actions-poetry@v2.3.0
uses: abatilo/actions-poetry@v3
- name: Install dependencies
run: make install-dev
- name: Test with coverage
Expand Down
18 changes: 9 additions & 9 deletions .github/workflows/flake8.yaml → .github/workflows/ruff.yaml
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
# This workflow will check modified files with flake8
# This workflow will check modified files with ruff

name: flake8
name: ruff
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
flake8:
ruff:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Poetry
uses: abatilo/actions-poetry@v2.3.0
uses: abatilo/actions-poetry@v3
- name: Install dependencies
run: make install-dev
- name: Get changed python source files
id: changed-files
uses: tj-actions/changed-files@v41
uses: tj-actions/changed-files@v45
with:
files: |
*.py
- name: Check code with flake8
- name: Check code with ruff
if: steps.changed-files.outputs.any_changed == 'true'
run: poetry run flake8 ${{ steps.changed-files.outputs.all_changed_files }}
run: poetry run ruff check ${{ steps.changed-files.outputs.all_changed_files }}
23 changes: 9 additions & 14 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
repos:
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
args: ["--profile", "black", "--filter-files"]
- repo: https://github.com/psf/black-pre-commit-mirror # Using this mirror lets us use mypyc-compiled black, which is about 2x faster
rev: 23.10.1
hooks:
- id: black
# It is recommended to specify the latest version of Python
# supported by your project here, or alternatively use
# pre-commit's default_language_version, see
# https://pre-commit.com/#top_level-default_language_version
language_version: python3.11
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.8.2
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
# Run the formatter.
- id: ruff-format
29 changes: 29 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug: Remote Attach",
"type": "debugpy",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
},
{
"name": "Debug: pytest",
"type": "debugpy",
"request": "launch",
"module": "pytest",
"args": [
"--spec"
]
}
]
}
18 changes: 18 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Run `docker compose up` with debug config",
"type": "docker-compose",
"dockerCompose": {
"up": {
"detached": false,
"build": false
},
"files": [
"${workspaceFolder}/docker-compose.debug.yml"
]
}
}
]
}
47 changes: 47 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
FROM debian:12 AS v8-base
ENV RAGENT_HOST ragent
ENV RAGENT_PORT 1540
ENV RAGENT_REGPORT 1541
ENV RAGENT_PORTRANGE 1560:1591
ENV RAS_PORT 1545
WORKDIR /distr
COPY /docker/1c-enterprise-*-common_*_amd64.deb common_amd64.deb
COPY /docker/1c-enterprise-*-server_*_amd64.deb server_amd64.deb
RUN dpkg -i common_amd64.deb && dpkg -i server_amd64.deb && rm *.deb
WORKDIR /opt/1cv8

FROM v8-base AS ragent
ENV RAGENT_HOME /home/1c/ragent
RUN mkdir -p ${RAGENT_HOME}/reg_${RAGENT_REGPORT}
COPY docker/ragent-entrypoint.sh /opt/docker/entrypoint.sh
RUN chmod +x /opt/docker/entrypoint.sh
ENTRYPOINT ["/opt/docker/entrypoint.sh"]

FROM v8-base AS ras
COPY docker/ras-entrypoint.sh /opt/docker/entrypoint.sh
RUN chmod +x /opt/docker/entrypoint.sh
ENTRYPOINT ["/opt/docker/entrypoint.sh"]

FROM python:3.12 AS python-base
ENV PYTHONUNBUFFERED 1
ENV POETRY_VERSION=1.8.4
ENV POETRY_HOME=/opt/poetry
ENV POETRY_VENV=/opt/poetry-venv
ENV POETRY_CACHE_DIR=/opt/.cache

FROM python-base AS poetry-base
RUN python3 -m venv $POETRY_VENV \
&& $POETRY_VENV/bin/pip install -U pip setuptools \
&& $POETRY_VENV/bin/pip install poetry==${POETRY_VERSION}

FROM python-base AS rac
COPY --from=ras /opt/1cv8 /opt/1cv8
COPY --from=poetry-base ${POETRY_VENV} ${POETRY_VENV}
ENV PATH="${PATH}:${POETRY_VENV}/bin"
WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN poetry check \
&& poetry install --no-interaction --no-cache --no-root --without dev --with debug
COPY docker/rac-entrypoint.sh /opt/docker/entrypoint.sh
RUN chmod +x /opt/docker/entrypoint.sh
ENTRYPOINT ["/opt/docker/entrypoint.sh"]
36 changes: 36 additions & 0 deletions Dockerfile-postgres
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
FROM debian:12

ENV DEBIAN_FRONTEND=noninteractive

ENV PG_APP_HOME="/etc/docker-postgresql"\
PG_VERSION=15 \
PG_USER=postgres \
PG_HOME=/var/lib/postgresql \
PG_RUNDIR=/run/postgresql \
PG_LOGDIR=/var/log/postgresql \
PG_CERTDIR=/etc/postgresql/certs

ENV PG_BINDIR=/opt/pgpro/1c-${PG_VERSION}/bin \
PG_DATADIR=${PG_HOME}/${PG_VERSION}/main

RUN apt-get update \
&& apt-get install -y sudo locales wget gnupg2 \
&& localedef -i ru_RU -c -f UTF-8 -A /usr/share/locale/locale.alias ru_RU.UTF-8 \
&& update-locale LANG=ru_RU.UTF-8

ENV LANG ru_RU.UTF-8

RUN wget --quiet -O - http://repo.postgrespro.ru/keys/GPG-KEY-POSTGRESPRO | apt-key add - \
&& echo 'deb http://repo.postgrespro.ru/1c/1c-'${PG_VERSION}'/debian '$(env -i bash -c '. /etc/os-release; echo $VERSION_CODENAME')' main' > /etc/apt/sources.list.d/postgrespro-1c.list \
&& apt-get update \
&& apt-get install -y postgrespro-1c-${PG_VERSION} \
&& rm -rf /var/lib/apt/lists/*

COPY docker/posgres-runtime/ ${PG_APP_HOME}/
COPY docker/posgres-entrypoint.sh /opt/docker/entrypoint.sh

EXPOSE 5432
VOLUME ${PG_DATADIR}
WORKDIR ${PG_HOME}
RUN chmod +x /opt/docker/entrypoint.sh
ENTRYPOINT ["/opt/docker/entrypoint.sh"]
14 changes: 7 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ test:
test-coverage:
poetry run coverage run -m pytest

.PHONY: code-style
code-style:
poetry run isort .
poetry run black .
.PHONY: ruff
ruff:
poetry run ruff check

.PHONY: flake8
flake8:
poetry run flake8 .
.PHONY: format
format:
poetry run ruff check --fix
poetry run ruff format
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
7. Уведомления на email

В планах:
1. Резервное копирование конфигурации кластера
2. Восстановление конфигурации кластера
3. Уведомления в telegram
4. Возможность работы через утилиту `rac` и сервер администрирования `ras` вместо использования COM-компоненты
1. [ ] Резервное копирование конфигурации кластера
2. [ ] Восстановление конфигурации кластера
3. [ ] Уведомления в telegram
4. [x] Возможность работы через утилиту `rac` и сервер администрирования `ras` вместо использования COM-компоненты

# Установка

Expand Down Expand Up @@ -58,6 +58,9 @@ scoop install python

### Регистрация COM-компоненты 1С Предприятие

> [!TIP]
> Регистрация COM-компоненты не требуется, если предполагается работа с кластером через утилиту `rac`
Регистрировать необходимо COM-компоненту той же версии, что и агент сервера, к которому будет выполняться подключение

Выполнить команду с **правами администратора**
Expand Down Expand Up @@ -117,13 +120,19 @@ TIP: для работы с путями в шаблонном файле нас

Настройки взаимодействия с платформой 1С Предприятие. Эти настройки необходимы для работы любых частей приложения

> [!CAUTION]
> В режиме взаимодействия с кластером 1С Предприятие через клиент администрирования кластера невозможно выполнять обновление информационных баз.
> На текущий момент обновление ИБ поддерживается только при работе через COM-компоненту
|Параметр|Описание|
|-------:|:-------|
|`V8_CLUSTER_ADMIN_CREDENTIALS`|Учетные данные администратора кластера 1С Предприятие|
|`V8_CLUSTER_CONTROL_MODE `|Режим взаимодействия с кластером 1С Предприятие: через COM-компоненту (`'com'`) или через клиент администрирования кластера (`'rac'`)|
|`V8_INFOBASES_CREDENTIALS` |Сопоставление с именами информационных баз, именами пользователей и паролями, которые будут использованы для подключения к информационным базам. Если информационная база не указана в списке в явном виде, для подклчения к ней будут использованы данные от записи `default`|
|`V8_INFOBASES_EXCLUDE` |Список с именами информационных баз, которые будут пропущены. Никакие операции с ними выполняться не будут|
|`V8_INFOBASES_ONLY` |Если список не пустой, все действия будут проводиться только с информационными базами, указанными в нём|
|`V8_LOCK_INFO_BASE_PAUSE` |Пауза в секундах между блокировкой фоновых заданий ИБ и продолжением дальнейших действий. Бывает полезно т.к. некоторые фоновые задания могут долго инициализироваться и создать сеанс уже после установления блокировки|
|`V8_RAS` |Параметры подключения к серверу администрирования кластера 1С Предприятие: address и port|
|`V8_SERVER_AGENT` |Параметры подключения к агенту сервера 1С Предприятие: address и port|
|`V8_PERMISSION_CODE` |Код блокировки начала новых сеансов, который будет устанавливаться при совершении операций с информационной базой|
|`V8_PLATFORM_PATH` |Путь к платформе 1С Предприятие. Последняя версия платформы будет определена автоматически|
Expand Down
33 changes: 21 additions & 12 deletions backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,14 @@ async def _backup_v8(ib_name: str, *args, **kwargs) -> core_models.InfoBaseBacku
# Формирует команду для выгрузки
info_base_user, info_base_pwd = utils.get_info_base_credentials(ib_name)
ib_and_time_str = utils.get_ib_and_time_string(ib_name)
dt_filename = os.path.join(settings.BACKUP_PATH, utils.append_file_extension_to_string(ib_and_time_str, "dt"))
dt_filename = os.path.join(
settings.BACKUP_PATH,
utils.append_file_extension_to_string(ib_and_time_str, "dt"),
)
log_filename = os.path.join(settings.LOG_PATH, utils.append_file_extension_to_string(ib_and_time_str, "log"))
# https://its.1c.ru/db/v838doc#bookmark:adm:TI000000526
v8_command = (
rf'"{utils.get_platform_full_path()}" '
rf'"{utils.get_1cv8_service_full_path()}" '
rf"DESIGNER /S {cluster_utils.get_server_agent_address()}\{ib_name} "
rf'/N"{info_base_user}" /P"{info_base_pwd}" '
rf"/Out {log_filename} -NoTruncate "
Expand Down Expand Up @@ -135,7 +138,8 @@ async def _backup_pgdump(

ib_and_time_str = utils.get_ib_and_time_string(ib_name)
backup_filename = os.path.join(
settings.BACKUP_PATH, utils.append_file_extension_to_string(ib_and_time_str, "pgdump")
settings.BACKUP_PATH,
utils.append_file_extension_to_string(ib_and_time_str, "pgdump"),
)
log_filename = os.path.join(settings.LOG_PATH, utils.append_file_extension_to_string(ib_and_time_str, "log"))
pg_dump_path = os.path.join(settings.PG_BIN_PATH, "pg_dump.exe")
Expand Down Expand Up @@ -168,12 +172,8 @@ async def _backup_pgdump(
async def _backup_info_base(ib_name: str) -> core_models.InfoBaseBackupTaskResult:
cci = cluster_utils.get_cluster_controller_class()()
ib_info = cci.get_info_base(ib_name)
db_server = ib_info.dbServerName
dbms = ib_info.DBMS
db_name = ib_info.dbName
db_user = ib_info.dbUser
if settings.BACKUP_PG and postgres.dbms_is_postgres(dbms):
result = await _backup_pgdump(ib_name, db_server, db_name, db_user)
if settings.BACKUP_PG and postgres.dbms_is_postgres(ib_info.dbms):
result = await _backup_pgdump(ib_name, ib_info.db_server, ib_info.db_name, ib_info.db_user)
else:
result = await cluster_utils.com_func_wrapper(_backup_v8, ib_name)
return result
Expand Down Expand Up @@ -209,7 +209,11 @@ def create_aws_upload_task(
):
if settings.AWS_ENABLED and backup_result.succeeded:
return asyncio.create_task(
aws.upload_infobase_to_s3(backup_result.infobase_name, backup_result.backup_filename, aws_semaphore),
aws.upload_infobase_to_s3(
backup_result.infobase_name,
backup_result.backup_filename,
aws_semaphore,
),
name=f"Task :: Upload {backup_result.infobase_name} to S3",
)

Expand Down Expand Up @@ -240,7 +244,8 @@ def analyze_results(


def send_email_notification(
backup_result: List[core_models.InfoBaseBackupTaskResult], aws_result: List[core_models.InfoBaseAWSUploadTaskResult]
backup_result: List[core_models.InfoBaseBackupTaskResult],
aws_result: List[core_models.InfoBaseAWSUploadTaskResult],
):
if settings.NOTIFY_EMAIL_ENABLED:
log.info(f"<{log_prefix}> Sending email notification")
Expand All @@ -259,7 +264,11 @@ async def main():
initialize_semaphore(settings.AWS_CONCURRENCY, log_prefix, "AWS") if settings.AWS_ENABLED else None
)
backup_replication_semaphore = (
initialize_semaphore(settings.BACKUP_REPLICATION_CONCURRENCY, log_prefix, "backup replication")
initialize_semaphore(
settings.BACKUP_REPLICATION_CONCURRENCY,
log_prefix,
"backup replication",
)
if settings.BACKUP_REPLICATION
else None
)
Expand Down
5 changes: 5 additions & 0 deletions conf/default_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@
## ------------- ##

V8_CLUSTER_ADMIN_CREDENTIALS = ("Администратор", "")
V8_CLUSTER_CONTROL_MODE = "com"
V8_INFOBASES_CREDENTIALS = {
"default": ("Администратор", ""),
}
V8_INFOBASES_EXCLUDE = []
V8_INFOBASES_ONLY = []
V8_LOCK_INFO_BASE_PAUSE = 5
V8_RAS = {
"address": "localhost",
"port": "1545",
}
V8_SERVER_AGENT = {
"address": "localhost",
"port": "1540",
Expand Down
Loading

0 comments on commit e98ca25

Please sign in to comment.