diff --git a/content/documentation/admin/actions/codescoring/createcodescoringproject.md b/content/documentation/admin/actions/codescoring/createcodescoringproject.md index 6031a769..70629ef4 100644 --- a/content/documentation/admin/actions/codescoring/createcodescoringproject.md +++ b/content/documentation/admin/actions/codescoring/createcodescoringproject.md @@ -6,12 +6,14 @@ weight: 10 CreateCodeScoringProject — creates a new project in CodeScoring. The action uses the CodeScoring API to register a project with the specified parameters: -- project name -- repository URL +- Project name +- Repository URL - VCS ID -- option to automatically run SCA analysis after cloning the repository +- Option to automatically run SCA analysis after cloning the repository -### Request example +## Request example + +Example of the action request body: ```yaml name: example-project @@ -20,15 +22,17 @@ vcs_id: 2 run_sca_after_clone: true ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | -------------------- | -------- | ---------------------------------------------------------------------------- | -| name | Yes | Project name in CodeScoring | -| repository | Yes | Repository URL (e.g., ) | -| vcs_id | Yes | VCS ID in CodeScoring (must be greater than 0) | -| run_sca_after_clone | No | Automatically run SCA analysis after cloning the repository | +| `name` | Yes | Project name in CodeScoring | +| `repository` | Yes | Repository URL, for example, `https://gitlab.example.com/group/project.git` | +| `vcs_id` | Yes | VCS ID in CodeScoring (must be greater than 0) | +| `run_sca_after_clone` | No | Automatically run SCA analysis after cloning the repository | -### Response +## Response The response contains the created project object with the following information: project identifier (pk), name, project type, description, repository information, project status, access permissions, license, number of dependencies and vulnerabilities, project languages, scan schedule status, and the dates of the first and last SCA scans. diff --git a/content/documentation/admin/actions/codescoring/createcodescoringproject.ru.md b/content/documentation/admin/actions/codescoring/createcodescoringproject.ru.md index c9f5812b..50e1ccc0 100644 --- a/content/documentation/admin/actions/codescoring/createcodescoringproject.ru.md +++ b/content/documentation/admin/actions/codescoring/createcodescoringproject.ru.md @@ -11,7 +11,9 @@ CreateCodeScoringProject — создаёт новый проект в сист - ID VCS-системы; - опция автоматического запуска SCA-анализа после клонирования репозитория. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: example-project @@ -20,15 +22,17 @@ vcs_id: 2 run_sca_after_clone: true ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | -------------------- | ---------------- | ---------------------------------------------------------------------------- | -| name | Да | Название проекта в CodeScoring | -| repository | Да | URL репозитория (например, ) | -| vcs_id | Да | ID VCS системы в CodeScoring (должен быть больше 0) | -| run_sca_after_clone | Нет | Автоматический запуск SCA-анализа после клонирования репозитория | +| `name` | Да | Название проекта в CodeScoring | +| `repository` | Да | URL репозитория (например, ) | +| `vcs_id` | Да | ID VCS системы в CodeScoring (должен быть больше 0) | +| `run_sca_after_clone` | Нет | Автоматический запуск SCA-анализа после клонирования репозитория | -### Ответ +## Ответ В ответе возвращается объект созданного проекта со следующей информацией: идентификатор проекта (pk), название, тип проекта, описание, информация о репозитории, статус проекта, права доступа, лицензия, количество зависимостей и уязвимостей, языки проекта, статус расписания сканирования и даты первого и последнего SCA-сканирования. diff --git a/content/documentation/admin/actions/codescoring/deletecodescoringproject.md b/content/documentation/admin/actions/codescoring/deletecodescoringproject.md index bfc44dcf..d18106c7 100644 --- a/content/documentation/admin/actions/codescoring/deletecodescoringproject.md +++ b/content/documentation/admin/actions/codescoring/deletecodescoringproject.md @@ -5,14 +5,18 @@ weight: 20 DeleteCodeScoringProject — deletes a project in CodeScoring by its ID. -### Request example +## Request example + +Example of the action request body: ```yaml id: 1 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ---------- | -------- | --------------------------- | -| id | Yes | Project ID in CodeScoring | +| `id` | Yes | Project ID in CodeScoring | diff --git a/content/documentation/admin/actions/codescoring/deletecodescoringproject.ru.md b/content/documentation/admin/actions/codescoring/deletecodescoringproject.ru.md index c0b56384..3ce1da73 100644 --- a/content/documentation/admin/actions/codescoring/deletecodescoringproject.ru.md +++ b/content/documentation/admin/actions/codescoring/deletecodescoringproject.ru.md @@ -5,14 +5,18 @@ weight: 20 DeleteCodeScoringProject — удаляет проект в системе CodeScoring по его ID. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml id: 1 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ---------- | ---------------- | ----------------------------- | -| id | Да | ID проекта в CodeScoring | +| `id` | Да | ID проекта в CodeScoring | diff --git a/content/documentation/admin/actions/debug/debug.md b/content/documentation/admin/actions/debug/debug.md index 1f8741f1..b434e642 100644 --- a/content/documentation/admin/actions/debug/debug.md +++ b/content/documentation/admin/actions/debug/debug.md @@ -3,9 +3,12 @@ title: Debug weight: 10 --- -Debug runs a debugging action. It performs a specified number of wait cycles, writes arbitrary data to the log, and returns the request in the action response. +Debug runs a debugging action. +It performs a specified number of wait cycles, writes arbitrary data to the log, and returns the request in the action response. -### Request example +## Request example + +Example of the action request body: ```yaml sleep_time: 1 @@ -14,17 +17,20 @@ extra: example_key: example_value ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | --------------- | -------- | ---------------------------------------------------------------------------------------------------- | ----------------------- | -| sleep_time | No | Duration of one wait cycle, in seconds | `0` | -| sleep_count | No | Number of wait cycles | `0` | -| extra | No | An arbitrary set of key-value pairs that is written to the log and returned in the action's response | - | +| `sleep_time` | No | Duration of one wait cycle, in seconds | `0` | +| `sleep_count` | No | Number of wait cycles | `0` | +| `extra` | No | An arbitrary set of key-value pairs that is written to the log and returned in the action's response | — | -With `0` values, the action finishes immediately. Negative values are not allowed: `sleep_time and sleep_count must not be negative`. +With `0` values, the action finishes immediately. +Negative values are not allowed: `sleep_time and sleep_count must not be negative`. -### Response +## Response The action returns the whole request: the `sleep_time`, `sleep_count` and `extra` fields with their values. Use them in templates of subsequent actions, for example `{{ .response.extra.example_key }}`. diff --git a/content/documentation/admin/actions/debug/debug.ru.md b/content/documentation/admin/actions/debug/debug.ru.md index 6d0b645c..4e2fbfc2 100644 --- a/content/documentation/admin/actions/debug/debug.ru.md +++ b/content/documentation/admin/actions/debug/debug.ru.md @@ -3,9 +3,12 @@ title: Debug weight: 10 --- -Debug выполняет отладочное действие. Позволяет сделать заданное число циклов ожидания, а также записать произвольные данные в лог и вернуть запрос в ответе действия. +Debug выполняет отладочное действие. +Позволяет сделать заданное число циклов ожидания, а также записать произвольные данные в лог и вернуть запрос в ответе действия. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml sleep_time: 1 @@ -14,17 +17,20 @@ extra: example_key: example_value ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | --------------- | ---------------- | ----------------------------------------------------------------------------------------------------- | ----------------------- | -| sleep_time | Нет | Длительность одного цикла ожидания в секундах | `0` | -| sleep_count | Нет | Число циклов ожидания | `0` | -| extra | Нет | Произвольный набор пар «ключ–значение», который записывается в лог и возвращается в ответе действия | - | +| `sleep_time` | Нет | Длительность одного цикла ожидания в секундах | `0` | +| `sleep_count` | Нет | Число циклов ожидания | `0` | +| `extra` | Нет | Произвольный набор пар «ключ–значение», который записывается в лог и возвращается в ответе действия | — | -При значениях `0` действие завершается сразу. Отрицательные значения не допускаются: `sleep_time and sleep_count must not be negative`. +При значениях `0` действие завершается сразу. +Отрицательные значения не допускаются: `sleep_time and sleep_count must not be negative`. -### Ответ +## Ответ Действие возвращает весь запрос: поля `sleep_time`, `sleep_count` и `extra` с их значениями. Используйте их в шаблонах последующих действий, например `{{ .response.extra.example_key }}`. diff --git a/content/documentation/admin/actions/debug/fail.md b/content/documentation/admin/actions/debug/fail.md index 804ef385..63720bdd 100644 --- a/content/documentation/admin/actions/debug/fail.md +++ b/content/documentation/admin/actions/debug/fail.md @@ -5,14 +5,18 @@ weight: 20 Fail simulates an action execution error. It is intended for use as a debugging step in processes. -### Request example +## Request example + +Example of the action request body: ```yaml fail: true ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | ---------- | -------- | -------------------------------------------------------------------------------------- | ----------------------- | -| fail | No | If `true`, the action completes with an error; if `false`, the action completes successfully | `true` | +| `fail` | No | If `true`, the action completes with an error; if `false`, the action completes successfully | `true` | diff --git a/content/documentation/admin/actions/debug/fail.ru.md b/content/documentation/admin/actions/debug/fail.ru.md index 54569ebd..4ffa777a 100644 --- a/content/documentation/admin/actions/debug/fail.ru.md +++ b/content/documentation/admin/actions/debug/fail.ru.md @@ -5,14 +5,18 @@ weight: 20 Fail эмулирует ошибку исполнения действия. Предназначен для использования в процессах в качестве отладочного элемента. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml fail: true ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | ---------------- | ----------------------------------------------------------------------------------------- | ----------------------- | -| fail | Нет | Если `true`, действие завершается с ошибкой; если `false`, действие завершается успешно | `true` | +| `fail` | Нет | Если `true`, действие завершается с ошибкой; если `false`, действие завершается успешно | `true` | diff --git a/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.md b/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.md index 02bf0820..f141014b 100644 --- a/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.md +++ b/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.md @@ -9,7 +9,9 @@ This action requires an API v2 key for the user on whose behalf it will run. CreateDefectdojoEngagement — creates a new engagement in DefectDojo. The action uses the DefectDojo API v2. -### Request example +## Request example + +Example of the action request body: ```yaml name: example engagement @@ -19,6 +21,7 @@ target_end: '2024-06-30' lead: '1' ``` -### Request specification +## Request specification -The fields correspond to the official DefectDojo API endpoint `/api/v2/engagements`. For details, see the [DefectDojo documentation](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). +The fields correspond to the official DefectDojo API endpoint `/api/v2/engagements`. +For details, see the [DefectDojo documentation](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). diff --git a/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.ru.md b/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.ru.md index cb8ba4bd..61e0c42a 100644 --- a/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.ru.md +++ b/content/documentation/admin/actions/defectdojo/createdefectdojoengagement.ru.md @@ -4,12 +4,14 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — API v2 Key пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия требуется токен API v2 Key пользователя, от имени которого выполняется действие. {{< /alert >}} CreateDefectdojoEngagement — создаёт новый engagement в системе DefectDojo. Действие использует DefectDojo API v2. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: example engagement @@ -19,6 +21,6 @@ target_end: '2024-06-30' lead: '1' ``` -### Спецификация запроса +## Спецификация запроса Список полей соответствует официальному API DefectDojo, `/api/v2/engagements`, подробнее — [в документации DefectDojo](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). diff --git a/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.md b/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.md index 1e225c42..b217b2d6 100644 --- a/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.md +++ b/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.md @@ -9,7 +9,9 @@ This action requires an API v2 key for the user on whose behalf it will run. CreateDefectdojoProduct — creates a new product in DefectDojo. The action uses the DefectDojo API v2. -### Request example +## Request example + +Example of the action request body: ```yaml name: example @@ -17,6 +19,7 @@ description: example description prod_type: 1 ``` -### Request specification +## Request specification -The fields correspond to the official DefectDojo API endpoint `/api/v2/products`. For details, see the [DefectDojo documentation](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). +The fields correspond to the official DefectDojo API endpoint `/api/v2/products`. +For details, see the [DefectDojo documentation](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). diff --git a/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.ru.md b/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.ru.md index 18b50241..2ace9f62 100644 --- a/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.ru.md +++ b/content/documentation/admin/actions/defectdojo/createdefectdojoproduct.ru.md @@ -4,12 +4,14 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — API v2 Key пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия требуется токен API v2 Key пользователя, от имени которого выполняется действие. {{< /alert >}} CreateDefectdojoProduct — создаёт новый продукт в системе DefectDojo. Действие использует DefectDojo API v2. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: example @@ -17,6 +19,6 @@ description: example description prod_type: 1 ``` -### Спецификация запроса +## Спецификация запроса Список полей соответствует официальному API DefectDojo, `/api/v2/products`, подробнее — [в документации DefectDojo](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). diff --git a/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.md b/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.md index c5269d58..5f66afd8 100644 --- a/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.md +++ b/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.md @@ -9,14 +9,18 @@ This action requires an API v2 key for the user on whose behalf it will run. DeleteDefectdojoProduct — deletes a product from DefectDojo. The action uses the DefectDojo API v2. -### Request example +## Request example + +Example of the action request body: ```yaml id: 1 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | ------------- | -------- | ------------------------------------------------ | ------------------------ | -| id | Yes | Identifier of the product to delete | - | +| `id` | Yes | Identifier of the product to delete | — | diff --git a/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.ru.md b/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.ru.md index 35ff4171..4258365f 100644 --- a/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.ru.md +++ b/content/documentation/admin/actions/defectdojo/deletedefectdojoproduct.ru.md @@ -4,19 +4,23 @@ weight: 20 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — API v2 Key пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия требуется токен API v2 Key пользователя, от имени которого выполняется действие. {{< /alert >}} DeleteDefectdojoProduct — удаляет продукт из DefectDojo. Действие использует DefectDojo API v2. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml id: 1 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ------------- | ---------------- | ---------------------------------------------------- | ------------------------ | -| id | Да | Идентификатор продукта, который необходимо удалить | - | +| `id` | Да | Идентификатор продукта, который необходимо удалить | — | diff --git a/content/documentation/admin/actions/gitlab/creategitlabbranches.md b/content/documentation/admin/actions/gitlab/creategitlabbranches.md index 333679b9..fb788fac 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabbranches.md +++ b/content/documentation/admin/actions/gitlab/creategitlabbranches.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabBranches — creates new branches in the target repository. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: '0' @@ -18,16 +20,18 @@ branches: ref: main ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ----------------- | -------- | -------------------------------------------------------------------------------- | -| project_id | Yes | Identifier of the project in which to create the branches | -| branches | Yes | List of branches to create | -| branches.branch | Yes | Name of the new branch | -| branches.ref | Yes | Name of an existing branch or a commit SHA | +| `project_id` | Yes | Identifier of the project in which to create the branches | +| `branches` | Yes | List of branches to create | +| `branches.branch` | Yes | Name of the new branch | +| `branches.ref` | Yes | Name of an existing branch or a commit SHA | -### Note +## GitLab API request The action performs a POST request to the URL `/api/v4/projects/:id/repository/branches` for each branch in the list, in order. If GitLab does not create a branch, the action fails, and the branches created before it remain in the project. diff --git a/content/documentation/admin/actions/gitlab/creategitlabbranches.ru.md b/content/documentation/admin/actions/gitlab/creategitlabbranches.ru.md index 174479f7..b5916b63 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabbranches.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabbranches.ru.md @@ -9,7 +9,9 @@ weight: 40 CreateGitlabBranches — создаёт новые ветки в целевом репозитории. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: '0' @@ -18,16 +20,18 @@ branches: ref: main ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ----------------- | ---------------- | ----------------------------------------------------------------------------- | -| project_id | Да | Идентификатор проекта, в котором необходимо создать ветки | -| branches | Да | Список создаваемых веток | -| branches.branch | Да | Название новой ветки | -| branches.ref | Да | Название существующей ветки или SHA-хеш коммита | +| `project_id` | Да | Идентификатор проекта, в котором необходимо создать ветки | +| `branches` | Да | Список создаваемых веток | +| `branches.branch` | Да | Название новой ветки | +| `branches.ref` | Да | Название существующей ветки или SHA-хеш коммита | -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL `/api/v4/projects/:id/repository/branches` для каждой ветки из списка по порядку. Если GitLab не создал ветку, действие завершается с ошибкой, а ветки, созданные до неё, остаются в проекте. diff --git a/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.md b/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.md index d81e82e0..6259f0f8 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.md +++ b/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabGroupVariables — creates group-level variables in GitLab. -### Request example +## Request example + +Example of the action request body: ```yaml group_id: '0' @@ -18,17 +20,22 @@ variables: value: value ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ----------------- | -------- | ---------------------------------------------------------------------------------- | -| group_id | Yes | Identifier of the group in which to create the variables | -| variables | Yes | List of variables to create | +| `group_id` | Yes | Identifier of the group in which to create the variables | +| `variables` | Yes | List of variables to create | -The fields for each variable correspond to the official GitLab group-level variables API, `/groups/:id/variables`. For details, see the [GitLab documentation](https://docs.gitlab.com/api/group_level_variables/#create-variable). +The fields for each variable correspond to the official GitLab group-level variables API, `/groups/:id/variables`. +For details, see the [GitLab documentation](https://docs.gitlab.com/api/group_level_variables/#create-variable). -The action creates the variables one by one. If GitLab does not create some of the variables, the action creates the remaining ones, and the run ends with the `Warning` status. The GitLab response for each failed variable is written to the run log. +The action creates the variables one by one. +If GitLab does not create some of the variables, the action creates the remaining ones, and the run ends with the `Warning` status. +The GitLab response for each failed variable is written to the run log. -### Note +## GitLab API request The action performs a POST request to the URL: `/api/v4/groups/:id/variables`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.ru.md b/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.ru.md index a9849f8a..d433398b 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabgroupvariables.ru.md @@ -9,7 +9,9 @@ weight: 80 CreateGitlabGroupVariables — создаёт переменные (variables) на уровне группы в GitLab. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml group_id: '0' @@ -18,17 +20,21 @@ variables: value: value ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ----------------- | ---------------- | ------------------------------------------------------------------------------ | -| group_id | Да | Идентификатор группы, в котором необходимо создать переменные | -| variables | Да | Список создаваемых переменных | +| `group_id` | Да | Идентификатор группы, в котором необходимо создать переменные | +| `variables` | Да | Список создаваемых переменных | Список полей для переменных соответствует официальному GitLab Group-level Variables API, `/groups/:id/variables`, подробнее — [в документации GitLab](https://docs.gitlab.com/api/group_level_variables/#create-variable). -Действие создаёт переменные по одной. Если GitLab не создал часть переменных, действие создаёт остальные, а запуск завершается со статусом `Warning`. Ответ GitLab для каждой несозданной переменной записывается в лог запуска. +Действие создаёт переменные по одной. +Если GitLab не создал часть переменных, действие создаёт остальные, а запуск завершается со статусом `Warning`. +Ответ GitLab для каждой несозданной переменной записывается в лог запуска. -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/groups/:id/variables`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabmergerequest.md b/content/documentation/admin/actions/gitlab/creategitlabmergerequest.md index 5440a6bd..9fcd29e8 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabmergerequest.md +++ b/content/documentation/admin/actions/gitlab/creategitlabmergerequest.md @@ -4,15 +4,17 @@ weight: 70 --- {{< alert level="info" >}} -Running this action requires credentials: - -- `password` — the password (token) for the user on whose behalf the action will run. -- `username` — the username of the user on whose behalf the action will run. +Running this action requires credentials: `username` (the username under which the action runs) +and `password` (the password or token for that user). {{< /alert >}} -CreateGitlabMergeRequest — creates a new Merge Request (MR) in the target repository. Files stored in the source repository are added to the Merge Request. Files may contain variables whose values will be substituted at the time the MR is created. +CreateGitlabMergeRequest — creates a new merge request (MR) in the target repository. +Files stored in the source repository are added to the merge request. +Files may contain variables whose values will be substituted at the time the MR is created. + +## Request example -### Request example +Example of the action request body: ```yaml source_project_id: '0' @@ -33,33 +35,43 @@ values: subkey: 123 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -| source_project_id | Yes | Identifier of the template project whose files are added to the Merge Request | - | -| target_project_id | Yes | Identifier of the target project in which the Merge Request will be created | - | -| merge_request_spec | Yes | Specification matching the [GitLab Merge Requests API](https://docs.gitlab.com/ee/api/merge_requests.html#create-mr) | - | -| source_project_tag | No | Tag of the template project to clone. If not specified, the branch `source_project_branch` is used | - | -| source_project_branch | No | Branch of the template project to clone. It is used only to clone the template | main | -| additionalIgnoreFiles | No | List of files containing paths to exclude from the MR. Populated similarly to [.templateignore](createrepositoryfromtemplate/#templateignore) | - | -| values | No | Variables used during templating, in `key: value` format | - | +| `source_project_id` | Yes | Identifier of the template project whose files are added to the merge request | — | +| `target_project_id` | Yes | Identifier of the target project in which the merge request will be created | — | +| `merge_request_spec` | Yes | Specification matching the [GitLab Merge Requests API](https://docs.gitlab.com/ee/api/merge_requests.html#create-mr) | — | +| `source_project_tag` | No | Tag of the template project to clone. If not specified, the branch `source_project_branch` is used | — | +| `source_project_branch` | No | Branch of the template project to clone. It is used only to clone the template | `main` | +| `additionalIgnoreFiles` | No | List of files containing paths to exclude from the MR. Populated similarly to [.templateignore](createrepositoryfromtemplate/#templateignore) | — | +| `values` | No | Variables used during templating, in `key: value` format | — | -### How it works +## How it works The portal: -1. Clones the template project (`source_project_id`) at the tag `source_project_tag` or, if the tag is not specified, at the branch `source_project_branch`. For more information, see [Implementation details](createrepositoryfromtemplate/#implementation-details). +1. Clones the template project (`source_project_id`) at the tag `source_project_tag` or, if the tag is not specified, at the branch `source_project_branch`. + For more information, see [Implementation details](createrepositoryfromtemplate/#implementation-details). 1. Reads the `values.yaml` file stored at the root of the template repository and determines the default templating variables. -1. Reads the variables passed when the action is launched and merges them with the variables from `values.yaml`. Variables passed at launch take priority. +1. Reads the variables passed when the action is launched and merges them with the variables from `values.yaml`. + Variables passed at launch take priority. 1. Reads the `.templateignore` file and determines the directories and files excluded from templating. 1. Renders the files from the templates, taking into account `values.yaml` and the variables passed to the action. 1. Clones the target project (`target_project_id`) at the branch `merge_request_spec.target_branch`. 1. Creates the branch `merge_request_spec.source_branch` from `merge_request_spec.target_branch` in the clone and switches to it. 1. Copies the rendered files to the target project, overwriting files with the same paths. -1. Commits the changes and pushes the commit to the branch `merge_request_spec.source_branch` of the target project. The push is not forced: if this branch already exists in the target project and contains commits that are not in `merge_request_spec.target_branch`, the action fails. +1. Commits the changes and pushes the commit to the branch `merge_request_spec.source_branch` of the target project. + The push is not forced: if this branch already exists in the target project and contains commits that are not in `merge_request_spec.target_branch`, the action fails. 1. Creates an MR in the target project according to `merge_request_spec` by sending a POST request to the GitLab API. -### Note +## Response + +The action returns the created GitLab merge request object with the `iid`, `web_url`, `state`, and other fields. +The fields are available in subsequent process elements, for example, `{{ .response.web_url }}`. + +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/merge_requests`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabmergerequest.ru.md b/content/documentation/admin/actions/gitlab/creategitlabmergerequest.ru.md index 2c45f5f6..b8f3932f 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabmergerequest.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabmergerequest.ru.md @@ -4,15 +4,17 @@ weight: 70 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `password` — пароль (токен) пользователя, от имени которого будет запускаться выполнение действия. -- `username` — имя пользователя, от которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `username` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль или токен этого пользователя). {{< /alert >}} -CreateGitlabMergeRequest — создаёт новый Merge Request (MR) в целевом репозитории. В Merge Request добавляются файлы, хранящиеся в репозитории-источнике. Файлы могут содержать переменные, значение которых будет подставлено в момент создания MR. +CreateGitlabMergeRequest — создаёт новый запрос на слияние (Merge Request, MR) в целевом репозитории. +В запрос на слияние добавляются файлы, хранящиеся в репозитории-источнике. +Файлы могут содержать переменные, значение которых будет подставлено в момент создания MR. + +## Пример запроса -### Пример запроса +Пример тела запроса действия: ```yaml source_project_id: '0' @@ -33,37 +35,44 @@ values: subkey: 123 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -| source_project_id | Да | Идентификатор проекта-шаблона, файлы которого добавляются в Merge Request | - | -| target_project_id | Да | Идентификатор целевого проекта, в котором будет сформирован Merge Request | - | -| merge_request_spec | Да | Спецификация, соответствующая [GitLab Merge Requests API](https://docs.gitlab.com/ee/api/merge_requests.html#create-mr) | - | -| source_project_tag | Нет | Тег проекта-шаблона для клонирования. Если не указан, используется ветка `source_project_branch` | - | -| source_project_branch | Нет | Ветка проекта-шаблона для клонирования. Используется только для клонирования шаблона | main | -| additionalIgnoreFiles | Нет | Список файлов, содержащих пути для исключения из MR. Заполняется по аналогии с [.templateignore](createrepositoryfromtemplate/#templateignore) | - | -| values | Нет | Переменные, используемые при шаблонизации, в формате `ключ: значение` | - | +| `source_project_id` | Да | Идентификатор проекта-шаблона, файлы которого добавляются в запрос на слияние | — | +| `target_project_id` | Да | Идентификатор целевого проекта, в котором будет сформирован запрос на слияние | — | +| `merge_request_spec` | Да | Спецификация, соответствующая [GitLab Merge Requests API](https://docs.gitlab.com/ee/api/merge_requests.html#create-mr) | — | +| `source_project_tag` | Нет | Тег проекта-шаблона для клонирования. Если не указан, используется ветка `source_project_branch` | — | +| `source_project_branch` | Нет | Ветка проекта-шаблона для клонирования. Используется только для клонирования шаблона | `main` | +| `additionalIgnoreFiles` | Нет | Список файлов, содержащих пути для исключения из MR. Заполняется по аналогии с [.templateignore](createrepositoryfromtemplate/#templateignore) | — | +| `values` | Нет | Переменные, используемые при шаблонизации, в формате `ключ: значение` | — | -### Алгоритм работы +## Алгоритм работы Портал: -1. Клонирует проект-шаблон (`source_project_id`) с тегом `source_project_tag` или, если тег не указан, с веткой `source_project_branch`. Подробнее — [в «Деталях работы»](createrepositoryfromtemplate/#детали-работы). +1. Клонирует проект-шаблон (`source_project_id`) с тегом `source_project_tag` или, если тег не указан, с веткой `source_project_branch`. + Подробнее — [в «Деталях работы»](createrepositoryfromtemplate/#детали-работы). 1. Считывает файл `values.yaml`, хранящийся в корне репозитория-шаблона, и определяет переменные по умолчанию для шаблонизации. -1. Считывает переменные, передаваемые при запуске действия, и объединяет (merge) их с переменными из `values.yaml`. Приоритет отдаётся переменным, передаваемым при запуске действия. +1. Считывает переменные, передаваемые при запуске действия, и объединяет (merge) их с переменными из `values.yaml`. + Приоритет отдаётся переменным, передаваемым при запуске действия. 1. Считывает файл `.templateignore` и определяет директории и файлы, исключаемые из шаблонизации. 1. Рендерит файлы из шаблонов с учётом `values.yaml` и переданных в действие переменных. 1. Клонирует целевой проект (`target_project_id`) с веткой `merge_request_spec.target_branch`. 1. Создаёт в клоне ветку `merge_request_spec.source_branch` из `merge_request_spec.target_branch` и переключается на неё. 1. Копирует отрендеренные файлы в целевой проект, перезаписывая файлы с совпадающими путями. -1. Создаёт коммит с изменениями и отправляет его (push) в ветку `merge_request_spec.source_branch` целевого проекта. Отправка выполняется без принудительной перезаписи: если эта ветка уже есть в целевом проекте и содержит коммиты, которых нет в `merge_request_spec.target_branch`, действие завершается с ошибкой. +1. Создаёт коммит с изменениями и отправляет его (push) в ветку `merge_request_spec.source_branch` целевого проекта. + Отправка выполняется без принудительной перезаписи. + Если эта ветка уже есть в целевом проекте и содержит коммиты, которых нет в `merge_request_spec.target_branch`, действие завершается с ошибкой. 1. Создаёт MR в целевом проекте согласно `merge_request_spec`, отправляя POST-запрос в GitLab API. -### Ответ +## Ответ -Ответ действия — объект созданного merge request GitLab с полями `iid`, `web_url`, `state` и другими. Поля доступны в последующих элементах процесса, например `{{ .response.web_url }}`. +Ответ действия — объект созданного запроса на слияние GitLab с полями `iid`, `web_url`, `state` и другими. +Поля доступны в последующих элементах процесса, например `{{ .response.web_url }}`. -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/merge_requests`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.md b/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.md new file mode 100644 index 00000000..661fe684 --- /dev/null +++ b/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.md @@ -0,0 +1,74 @@ +--- +title: CreateGitlabMergeRequestReview +weight: 75 +--- + +{{< alert level="info" >}} +Running this action requires the `password` credentials: the GitLab token of the user under which the action runs. +{{< /alert >}} + +CreateGitlabMergeRequestReview — creates a merge request in GitLab from an existing branch. +In the interface, the action is called "Create Gitlab merge request for an existing branch". + +Unlike [CreateGitlabMergeRequest](creategitlabmergerequest/), the action does not create a branch or write files; instead, it checks the project's open merge requests before creating one. +The action is used by the [microservice template upgrade](../../templates/updates/) process. + +## Request example + +Example of the action request body: + +```yaml +skipReview: false +sourceBranch: ddp/template-upgrade-1.2.0 +targetBranch: main +dedupBranchPrefix: ddp/template-upgrade- +repositoryRef: + gitlabProjectId: "0" +mergeRequestSpec: + title: Upgrade template + description: Apply template upgrade changes +``` + +## Request specification + +The action request body supports the following parameters: + +| Name | Required | Description | Default value | +| ------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `skipReview` | No | If set to `true`, the action completes successfully without creating a merge request | `false` | +| `sourceBranch` | Yes | Existing branch with the changes | — | +| `targetBranch` | No | Branch to which the changes are proposed. If not set and the action runs for a microservice entity, the value of the `microservice_default_branch` mapping role is used | `main` | +| `dedupBranchPrefix` | No | Branch prefix used to search for open merge requests | The "Upgrade branch prefix" value of the template registry, otherwise `ddp/template-upgrade-` | +| `repositoryRef.gitlabProjectId` | Yes | GitLab project ID. If not set and the action runs for a microservice entity, the microservice project ID is used | — | +| `mergeRequestSpec.title` | No | Merge request title | `Upgrade template ()` | +| `mergeRequestSpec.description` | No | Merge request description | — | + +## How it works + +Deckhouse Development Portal (DDP): + +1. Requests the project's open merge requests whose branches start with the `dedupBranchPrefix` prefix. +1. If a merge request from the `sourceBranch` branch is open, completes the action successfully and returns this merge request. +1. If a merge request from another branch with the same prefix is open, fails the action with the `review_already_open: open review for branch blocks ` error. +1. Otherwise, creates a merge request from `sourceBranch` to `targetBranch`. + +One page of 100 open merge requests of the project is checked. + +## Response + +The action response contains the following fields: + +| Name | Description | +| -------------- | --------------------------------------------------------------------------------------- | +| `skipped` | `true` if the action completed without creating a merge request because of `skipReview` | +| `deduplicated` | `true` if an already open merge request was returned | +| `provider` | Version control system provider, `gitlab` | +| `reviewId` | Merge request number (`iid`) in the project | +| `reviewUrl` | Link to the merge request | +| `sourceBranch` | Source branch | +| `targetBranch` | Target branch | + +## GitLab API request + +The action performs GET and POST requests to the URL: `/api/v4/projects/:id/merge_requests`. +A merge request creation error is returned with the `review_create_failed` code. diff --git a/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.ru.md b/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.ru.md index 10e44be5..fb17309c 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabmergerequestreview.ru.md @@ -7,11 +7,15 @@ weight: 75 Для выполнения действия необходимы учётные данные `password` — токен GitLab пользователя, от имени которого будет выполнено действие. {{< /alert >}} -CreateGitlabMergeRequestReview — создаёт merge request в GitLab из уже существующей ветки. В интерфейсе действие называется «Создать MR в Gitlab для существующей ветки». +CreateGitlabMergeRequestReview — создаёт запрос на слияние (Merge Request) в GitLab из уже существующей ветки. +В интерфейсе действие называется «Создать MR в Gitlab для существующей ветки». -В отличие от [CreateGitlabMergeRequest](creategitlabmergerequest/), действие не создаёт ветку и не записывает файлы, а перед созданием проверяет открытые merge request проекта. Действие используется процессом [обновления микросервиса из шаблона](../../templates/updates/). +В отличие от [CreateGitlabMergeRequest](creategitlabmergerequest/), действие не создаёт ветку и не записывает файлы, а перед созданием проверяет открытые запросы на слияние проекта. +Действие используется процессом [обновления микросервиса из шаблона](../../templates/updates/). -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml skipReview: false @@ -25,43 +29,46 @@ mergeRequestSpec: description: Apply template upgrade changes ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ----------------------------- | -------------- | ----------------------------------------------------------------------------------------------------- | --------------------- | -| skipReview | Нет | При значении `true` действие завершается успешно без создания merge request | `false` | -| sourceBranch | Да | Существующая ветка с изменениями | - | -| targetBranch | Нет | Ветка, в которую предлагаются изменения. Если не задана и действие выполняется для сущности микросервиса, используется значение роли маппинга `microservice_default_branch` | `main` | -| dedupBranchPrefix | Нет | Префикс веток для поиска открытых merge request | Значение «Префикс ветки обновления» реестра шаблонов, иначе `ddp/template-upgrade-` | -| repositoryRef.gitlabProjectId | Да | Идентификатор проекта GitLab. Если не задан и действие выполняется для сущности микросервиса, используется ID проекта микросервиса | - | -| mergeRequestSpec.title | Нет | Заголовок merge request | `Upgrade template ()` | -| mergeRequestSpec.description | Нет | Описание merge request | - | +| `skipReview` | Нет | При значении `true` действие завершается успешно без создания запроса на слияние | `false` | +| `sourceBranch` | Да | Существующая ветка с изменениями | — | +| `targetBranch` | Нет | Ветка, в которую предлагаются изменения. Если не задана и действие выполняется для сущности микросервиса, используется значение роли маппинга `microservice_default_branch` | `main` | +| `dedupBranchPrefix` | Нет | Префикс веток для поиска открытых запросов на слияние | Значение «Префикс ветки обновления» реестра шаблонов, иначе `ddp/template-upgrade-` | +| `repositoryRef.gitlabProjectId` | Да | Идентификатор проекта GitLab. Если не задан и действие выполняется для сущности микросервиса, используется ID проекта микросервиса | — | +| `mergeRequestSpec.title` | Нет | Заголовок запроса на слияние | `Upgrade template ()` | +| `mergeRequestSpec.description` | Нет | Описание запроса на слияние | — | -### Алгоритм работы +## Алгоритм работы -DDP: +Deckhouse Development Portal (DDP): -1. Запрашивает открытые merge request проекта, ветки которых начинаются с префикса `dedupBranchPrefix`. -1. Если открыт merge request из ветки `sourceBranch`, завершает действие успешно и возвращает этот merge request. -1. Если открыт merge request из другой ветки с тем же префиксом, завершает действие ошибкой `review_already_open: open review for branch blocks `. -1. Иначе создаёт merge request из `sourceBranch` в `targetBranch`. +1. Запрашивает открытые запросы на слияние проекта, ветки которых начинаются с префикса `dedupBranchPrefix`. +1. Если открыт запрос на слияние из ветки `sourceBranch`, завершает действие успешно и возвращает этот запрос на слияние. +1. Если открыт запрос на слияние из другой ветки с тем же префиксом, завершает действие ошибкой `review_already_open: open review for branch blocks `. +1. Иначе создаёт запрос на слияние из `sourceBranch` в `targetBranch`. -Проверяется одна страница из 100 открытых merge request проекта. +Проверяется одна страница из 100 открытых запросов на слияние проекта. -### Ответ +## Ответ Ответ действия содержит поля: -| Поле | Описание | +| Название | Описание | | -------------- | --------------------------------------------------------------- | -| `skipped` | `true`, если действие завершилось без создания merge request по `skipReview` | -| `deduplicated` | `true`, если возвращён уже открытый merge request | +| `skipped` | `true`, если действие завершилось без создания запроса на слияние по `skipReview` | +| `deduplicated` | `true`, если возвращён уже открытый запрос на слияние | | `provider` | Провайдер системы контроля версий, `gitlab` | -| `reviewId` | Номер merge request (`iid`) в проекте | -| `reviewUrl` | Ссылка на merge request | +| `reviewId` | Номер запроса на слияние (`iid`) в проекте | +| `reviewUrl` | Ссылка на запрос на слияние | | `sourceBranch` | Ветка-источник | | `targetBranch` | Целевая ветка | -### Примечание +## Запрос к API GitLab -Действие осуществляет GET- и POST-запросы по URL: `/api/v4/projects/:id/merge_requests`. Ошибка создания merge request возвращается с кодом `review_create_failed`. +Действие осуществляет GET- и POST-запросы по URL: `/api/v4/projects/:id/merge_requests`. +Ошибка создания запроса на слияние возвращается с кодом `review_create_failed`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabproject.md b/content/documentation/admin/actions/gitlab/creategitlabproject.md index 3005be8a..3ac00b8f 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabproject.md +++ b/content/documentation/admin/actions/gitlab/creategitlabproject.md @@ -7,9 +7,12 @@ weight: 20 This action requires a token for the user on whose behalf it will run. {{< /alert >}} -CreateGitlabProject — creates a new project in GitLab through the GitLab API, using the specified name, project path, description, and other settings. Authentication uses a GitLab token provided in the credentials. +CreateGitlabProject — creates a new project in GitLab through the GitLab API, using the specified name, project path, description, and other settings. +Authentication uses a GitLab token provided in the credentials. -### Request example +## Request example + +Example of the action request body: ```yaml name: example @@ -20,17 +23,20 @@ initialize_with_readme: false namespace_id: '0' ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | ------------------------ | -------- | ---------------------------------------------------------------------------------------- | ----------------------- | -| name | Yes | Name of the project to be created in GitLab | - | -| path | Yes | URL-friendly project path. Usually matches the name, but may differ | - | -| default_branch | Yes | Name of the branch to be used by default, e.g. "main" | - | -| namespace_id | Yes | Identifier of the GitLab namespace in which the project will be created | - | -| initialize_with_readme | No | Flag indicating whether the project should be initialized with a README file | false | -| description | No | Project description visible to users | - | +| `name` | Yes | Name of the project to be created in GitLab | — | +| `path` | Yes | URL-friendly project path. Usually matches the name, but may differ | — | +| `default_branch` | Yes | Name of the branch to be used by default, for example, `main` | — | +| `namespace_id` | Yes | Identifier of the GitLab namespace in which the project will be created | — | +| `initialize_with_readme` | No | Flag indicating whether the project should be initialized with a README file | `false` | +| `description` | No | Project description visible to users | — | -### Note +## GitLab API request -The action performs a POST request to the URL: `/api/v4/projects`, sending the request parameters in JSON format. Upon successful creation, GitLab returns data about the newly created project. +The action performs a POST request to the URL: `/api/v4/projects`, sending the request parameters in JSON format. +Upon successful creation, GitLab returns data about the newly created project. diff --git a/content/documentation/admin/actions/gitlab/creategitlabproject.ru.md b/content/documentation/admin/actions/gitlab/creategitlabproject.ru.md index 94fb1a4a..9080e040 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabproject.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabproject.ru.md @@ -7,9 +7,13 @@ weight: 20 Для выполнения действия требуется токен пользователя, от имени которого оно будет выполнено. {{< /alert >}} -CreateGitlabProject — создаёт новый проект в GitLab. Действие осуществляет вызов GitLab API для создания проекта с указанными параметрами, такими как название, путь проекта, описание и другие настройки. Для аутентификации используется GitLab token, который должен быть предоставлен в учётных данных. +CreateGitlabProject — создаёт новый проект в GitLab. +Действие осуществляет вызов GitLab API для создания проекта с указанными параметрами, такими как название, путь проекта, описание и другие настройки. +Для аутентификации используется GitLab token, который должен быть предоставлен в учётных данных. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: example @@ -20,17 +24,20 @@ initialize_with_readme: false namespace_id: '0' ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ------------------------ | ---------------- | ------------------------------------------------------------------------------------ | ----------------------- | -| name | Да | Название проекта, который будет создан в GitLab | - | -| path | Да | URL-совместимый путь проекта. Обычно совпадает с названием, но может отличаться | - | -| default_branch | Да | Название ветки, которая будет использоваться по умолчанию, например, «main» | - | -| namespace_id | Да | Идентификатор неймспейса (namespace) в GitLab, в котором будет создан проект | - | -| initialize_with_readme | Нет | Флаг, определяющий, нужно ли инициализировать проект с файлом README | false | -| description | Нет | Описание проекта, которое будет видно пользователям | - | +| `name` | Да | Название проекта, который будет создан в GitLab | — | +| `path` | Да | URL-совместимый путь проекта. Обычно совпадает с названием, но может отличаться | — | +| `default_branch` | Да | Название ветки, которая будет использоваться по умолчанию, например, «main» | — | +| `namespace_id` | Да | Идентификатор неймспейса (namespace) в GitLab, в котором будет создан проект | — | +| `initialize_with_readme` | Нет | Флаг, определяющий, нужно ли инициализировать проект с файлом README | `false` | +| `description` | Нет | Описание проекта, которое будет видно пользователям | — | -### Примечание +## Запрос к API GitLab -Действие осуществляет POST-запрос по URL: `/api/v4/projects`, передавая параметры запроса в формате JSON. В случае успешного создания проекта GitLab возвращает данные о вновь созданном проекте. +Действие осуществляет POST-запрос по URL: `/api/v4/projects`, передавая параметры запроса в формате JSON. +В случае успешного создания проекта GitLab возвращает данные о вновь созданном проекте. diff --git a/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.md b/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.md index cb2cd4ab..4075c514 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.md +++ b/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabProjectVariables — creates project-level variables in GitLab. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: '0' @@ -18,17 +20,22 @@ variables: value: value ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ----------------- | -------- | ---------------------------------------------------------------------------------- | -| project_id | Yes | Identifier of the project in which to create the variables | -| variables | Yes | List of variables to create | +| `project_id` | Yes | Identifier of the project in which to create the variables | +| `variables` | Yes | List of variables to create | -The fields for each variable correspond to the official GitLab project-level CI/CD variables API, `/projects/:id/variables`. For details, see the [GitLab documentation](https://docs.gitlab.com/api/project_level_variables/#create-a-variable). +The fields for each variable correspond to the official GitLab project-level CI/CD variables API, `/projects/:id/variables`. +For details, see the [GitLab documentation](https://docs.gitlab.com/api/project_level_variables/#create-a-variable). -The action creates the variables one by one. If GitLab does not create some of the variables, the action creates the remaining ones, and the run ends with the `Warning` status. The GitLab response for each failed variable is written to the run log. +The action creates the variables one by one. +If GitLab does not create some of the variables, the action creates the remaining ones, and the run ends with the `Warning` status. +The GitLab response for each failed variable is written to the run log. -### Note +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/variables`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.ru.md b/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.ru.md index b613b0b9..08fb4b00 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabprojectvariables.ru.md @@ -9,7 +9,9 @@ weight: 90 CreateGitlabProjectVariables — создаёт переменные на уровне проекта в GitLab. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: '0' @@ -18,17 +20,21 @@ variables: value: value ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ----------------- | ---------------- | ------------------------------------------------------------------------------ | -| project_id | Да | Идентификатор проекта, в котором необходимо создать переменные | -| variables | Да | Список создаваемых переменных | +| `project_id` | Да | Идентификатор проекта, в котором необходимо создать переменные | +| `variables` | Да | Список создаваемых переменных | Список полей для переменных соответствует официальному GitLab Project-level CI/CD variables API, `/projects/:id/variables`, подробнее — [в документации GitLab](https://docs.gitlab.com/api/project_level_variables/#create-a-variable). -Действие создаёт переменные по одной. Если GitLab не создал часть переменных, действие создаёт остальные, а запуск завершается со статусом `Warning`. Ответ GitLab для каждой несозданной переменной записывается в лог запуска. +Действие создаёт переменные по одной. +Если GitLab не создал часть переменных, действие создаёт остальные, а запуск завершается со статусом `Warning`. +Ответ GitLab для каждой несозданной переменной записывается в лог запуска. -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/variables`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.md b/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.md index 1f5ba7c8..803a90c6 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.md +++ b/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabProjectWebhook — creates a webhook in a GitLab project. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: '0' @@ -20,17 +22,19 @@ merge_requests_events: true pipeline_events: true ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ----------------------- | ------------------ | ----------------------------------------------------------------- | -| project_id | Yes | Identifier of the project in which to create the webhook | -| url | Yes | Webhook URL | -| push_events | No | Trigger the webhook when changes are pushed to the repository. Defaults to `false` | -| issues_events | No | Trigger the webhook when an issue is created. Defaults to `false` | -| merge_requests_events | No | Trigger the webhook when a merge request is created. Defaults to `false` | -| pipeline_events | No | Trigger the webhook when a pipeline is run. Defaults to `false` | - -### Note +| `project_id` | Yes | Identifier of the project in which to create the webhook | +| `url` | Yes | Webhook URL | +| `push_events` | No | Trigger the webhook when changes are pushed to the repository. Defaults to `false` | +| `issues_events` | No | Trigger the webhook when an issue is created. Defaults to `false` | +| `merge_requests_events` | No | Trigger the webhook when a merge request is created. Defaults to `false` | +| `pipeline_events` | No | Trigger the webhook when a pipeline is run. Defaults to `false` | + +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/hooks`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.ru.md b/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.ru.md index 30da8620..2fcb4c5a 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabprojectwebhook.ru.md @@ -9,7 +9,9 @@ weight: 30 CreateGitlabProjectWebhook — создаёт вебхук в проекте GitLab. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: '0' @@ -20,17 +22,19 @@ merge_requests_events: true pipeline_events: true ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ----------------------- | ------------------ | ------------------------------------------------------------ | -| project_id | Да | Идентификатор проекта, в котором необходимо создать вебхук | -| url | Да | URL-адрес вебхука | -| push_events | Нет | Запускать вебхук при push в репозиторий. По умолчанию `false` | -| issues_events | Нет | Запускать вебхук при создании Issue. По умолчанию `false` | -| merge_requests_events | Нет | Запускать вебхук при создании Merge Request. По умолчанию `false` | -| pipeline_events | Нет | Запускать вебхук при запуске Pipeline. По умолчанию `false` | - -### Примечание +| `project_id` | Да | Идентификатор проекта, в котором необходимо создать вебхук | +| `url` | Да | URL-адрес вебхука | +| `push_events` | Нет | Запускать вебхук при push в репозиторий. По умолчанию `false` | +| `issues_events` | Нет | Запускать вебхук при создании Issue. По умолчанию `false` | +| `merge_requests_events` | Нет | Запускать вебхук при создании запроса на слияние (Merge Request). По умолчанию `false` | +| `pipeline_events` | Нет | Запускать вебхук при запуске Pipeline. По умолчанию `false` | + +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/hooks`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabrelease.md b/content/documentation/admin/actions/gitlab/creategitlabrelease.md index 870b0fe3..046b500f 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabrelease.md +++ b/content/documentation/admin/actions/gitlab/creategitlabrelease.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabRelease — creates a GitLab release based on an existing tag. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: '0' @@ -21,15 +23,17 @@ description: | - Bug fixes. ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | -------------- | -------- | ------------------------------------------------------------------------------------------------ | -| project_id | Yes | Identifier of the project in which to create the release | -| tag_name | Yes | Name of the existing tag on which the release will be based | -| name | Yes | Name of the release as displayed in GitLab | -| description | No | Release description in Markdown format | +| `project_id` | Yes | Identifier of the project in which to create the release | +| `tag_name` | Yes | Name of the existing tag on which the release will be based | +| `name` | Yes | Name of the release as displayed in GitLab | +| `description` | No | Release description in Markdown format | -### Note +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/releases`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabrelease.ru.md b/content/documentation/admin/actions/gitlab/creategitlabrelease.ru.md index 511b106b..25b41ec7 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabrelease.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabrelease.ru.md @@ -9,7 +9,9 @@ weight: 60 CreateGitlabRelease — создаёт релиз GitLab на основе уже существующего тега. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: '0' @@ -21,15 +23,17 @@ description: | - Исправления ошибок. ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | -------------- | ---------------- | -------------------------------------------------------------------------------------------- | -| project_id | Да | Идентификатор проекта, в котором необходимо создать релиз | -| tag_name | Да | Название существующего тега, на основе которого формируется релиз | -| name | Да | Название релиза, отображаемое в GitLab | -| description | Нет | Описание релиза в формате Markdown | +| `project_id` | Да | Идентификатор проекта, в котором необходимо создать релиз | +| `tag_name` | Да | Название существующего тега, на основе которого формируется релиз | +| `name` | Да | Название релиза, отображаемое в GitLab | +| `description` | Нет | Описание релиза в формате Markdown | -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/releases`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabtag.md b/content/documentation/admin/actions/gitlab/creategitlabtag.md index 27f97e45..5bf7837b 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabtag.md +++ b/content/documentation/admin/actions/gitlab/creategitlabtag.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. CreateGitlabTag — creates a new tag in a GitLab project. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: '0' @@ -18,15 +20,17 @@ ref: main message: Tag description ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ---------------------- | -------- | ------------------------------------------------------------------------------------ | -| project_id | Yes | Identifier of the project in which to create the tag | -| tag_name | Yes | Name of the tag | -| ref | Yes | Name of the branch or tag, or the commit SHA, that the new tag will point to | -| message | No | Tag description | +| `project_id` | Yes | Identifier of the project in which to create the tag | +| `tag_name` | Yes | Name of the tag | +| `ref` | Yes | Name of the branch or tag, or the commit SHA, that the new tag will point to | +| `message` | No | Tag description | -### Note +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/repository/tags`. diff --git a/content/documentation/admin/actions/gitlab/creategitlabtag.ru.md b/content/documentation/admin/actions/gitlab/creategitlabtag.ru.md index 042b828b..9d6d3109 100644 --- a/content/documentation/admin/actions/gitlab/creategitlabtag.ru.md +++ b/content/documentation/admin/actions/gitlab/creategitlabtag.ru.md @@ -9,7 +9,9 @@ weight: 50 CreateGitlabTag — создаёт новый тег в проекте GitLab. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: '0' @@ -18,15 +20,17 @@ ref: main message: Tag description ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ---------------------- | ---------------- | ------------------------------------------------------------------------------- | -| project_id | Да | Идентификатор проекта, в котором необходимо создать тег | -| tag_name | Да | Название тега | -| ref | Да | Название ветки, тег или SHA-хеш коммита, на который будет ссылаться новый тег | -| message | Нет | Описание тега | +| `project_id` | Да | Идентификатор проекта, в котором необходимо создать тег | +| `tag_name` | Да | Название тега | +| `ref` | Да | Название ветки, тег или SHA-хеш коммита, на который будет ссылаться новый тег | +| `message` | Нет | Описание тега | -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/repository/tags`. diff --git a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.md b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.md index 0d76ed95..557ca29d 100644 --- a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.md +++ b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.md @@ -4,15 +4,16 @@ weight: 10 --- {{< alert level="info" >}} -Running this action requires credentials: - -- `password` — the password (token) for the user on whose behalf the action will run. -- `username` — the username of the user on whose behalf the action will run. +Running this action requires credentials: `username` (the username under which the action runs) +and `password` (the password or token for that user). {{< /alert >}} -CreateRepositoryFromTemplate — creates a new repository from a template in GitLab. The rendering mechanism is based on [Go template](https://pkg.go.dev/text/template) and supports all built-in methods, as well as extensions added by the portal. +CreateRepositoryFromTemplate — creates a new repository from a template in GitLab. +The rendering mechanism is based on [Go template](https://pkg.go.dev/text/template) and supports all built-in methods, as well as extensions added by the portal. + +## Request example -### Request example +Example of the action request body: ```yaml sourceBranch: main @@ -30,30 +31,33 @@ values: subkey: 123 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | -------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -| templateRepositoryUrl | Yes | URL of the template repository | - | -| targetRepositoryUrl | Yes | URL of the repository to be created as a result of running the action | - | -| values | Yes | Variables used during templating, in `key: value` format | - | -| additionalIgnoreFiles | No | List of files containing paths to exclude from the target repository. Populated similarly to [.templateignore](#templateignore) | - | -| sourceTag | No | Tag of the template repository to use during templating. If not specified, the template repository's branch is used | - | -| sourceBranch | No | Branch of the template repository to use during templating | main | -| targetBranch | No | Branch of the target repository to be created as a result of running the action | main | +| `templateRepositoryUrl` | Yes | URL of the template repository | — | +| `targetRepositoryUrl` | Yes | URL of the repository to be created as a result of running the action | — | +| `values` | Yes | Variables used during templating, in `key: value` format | — | +| `additionalIgnoreFiles` | No | List of files containing paths to exclude from the target repository. Populated similarly to [.templateignore](#templateignore) | — | +| `sourceTag` | No | Tag of the template repository to use during templating. If not specified, the template repository's branch is used | — | +| `sourceBranch` | No | Branch of the template repository to use during templating | `main` | +| `targetBranch` | No | Branch of the target repository to be created as a result of running the action | `main` | -### How it works +## How it works The portal: 1. Clones the template repository from the specified URL (`templateRepositoryUrl`), using `sourceTag`, `sourceBranch`, or the `main` branch as the ref, in that order of preference. 1. Reads the `values.yaml` file stored at the root of the repository and determines the default templating variables. -1. Reads the variables passed when the action is launched and merges them with the variables from `values.yaml`. Variables passed at launch take priority during the merge. +1. Reads the variables passed when the action is launched and merges them with the variables from `values.yaml`. + Variables passed at launch take priority during the merge. 1. Reads the `.templateignore` file and determines the directories and files excluded from templating. 1. Renders the files from the templates, taking into account `values.yaml` and the variables passed to the action. 1. Changes the repository remote to the target repository (`targetRepositoryUrl`) and pushes to the target branch (`targetBranch`) or to the `main` branch. -### Response +## Response The action returns the templating variables in the `values` field: @@ -65,12 +69,14 @@ The action returns the templating variables in the `values` field: For example, `{{ .response.values.merged.module }}` returns the value of the `module` variable used for rendering. -### Implementation details +## Implementation details -The action supports templating of directory and file names. To do this, add an expression in [Go template](https://pkg.go.dev/text/template) format to their name. +The action supports templating of directory and file names. +To do this, add an expression in [Go template](https://pkg.go.dev/text/template) format to their name. For example, the directory `src/{{ .module }}/utils`, given a `module` value of `example`, will be rendered as the directory `src/example/utils` in the target repository. -If, after rendering from the template, a file's content is empty, the file is not created. For example, a file with the following content: +If, after rendering from the template, a file's content is empty, the file is not created. +For example, a file with the following content: ```go-text-template {{- if .createContent }} @@ -78,11 +84,12 @@ If, after rendering from the template, a file's content is empty, the file is no {{- end }} ``` -will not be created if the `createContent` variable is `false`. Similarly, files that are originally empty will not be created either. +will not be created if the `createContent` variable is `false`. +Similarly, files that are originally empty will not be created either. If templating variables are missing from both the `values.yaml` file and the variables passed when the action is launched, rendering fails with an error and the target repository is not created. -### Template repository variables +## Template repository variables To add default variables used during templating, create a `values.yaml` file with the appropriate content at the root of the repository. @@ -97,13 +104,16 @@ The `values.yaml` file is optional. -### Excluding files +## Excluding files -Some files may contain variables in [Go template](https://pkg.go.dev/text/template) format that need to be preserved when rendering the repository from a template, for example Helm charts in the `helm` directory. The `.git` directory is always ignored. +Some files may contain variables in [Go template](https://pkg.go.dev/text/template) format that need to be preserved when rendering the repository from a template, for example Helm charts in the `helm` directory. +The `.git` directory is always ignored. To exclude such files from the rendering mechanism, add a `.templateignore` file with the appropriate content to the root of the repository. -Each line of `.templateignore` defines a single rule — a path or a mask. If the line contains `{{`, the entire line is executed as a single Go template with the same variables and functions used when substituting into file and directory names (for more information, see [How a rule line is processed](#templateignore-templates)). If the line does not contain `{{`, no substitution of variables from `values.yaml` or from the action's request is performed: the line is read as-is and compared with the relative path on disk; literals and the mask characters `*` and `**` are allowed. +Each line of `.templateignore` defines a single rule — a path or a mask. +If the line contains `{{`, the entire line is executed as a single Go template with the same variables and functions used when substituting into file and directory names (for more information, see [How a rule line is processed](#templateignore-templates)). +If the line does not contain `{{`, no substitution of variables from `values.yaml` or from the action's request is performed: the line is read as-is and compared with the relative path on disk; literals and the mask characters `*` and `**` are allowed. Example of a `.templateignore` file containing only path masks, without substitution templates, to ignore the contents of the `helm` and `docs` directories: @@ -112,14 +122,20 @@ helm/** docs/** ``` -#### Adding paths to ignore +### Adding paths to ignore + +To exclude paths from processing, follow these steps: 1. At the root of the template repository, create or edit the `.templateignore` file (one rule per line). -1. Each line is a single rule: a path from the repository root. Regular path characters and masks are allowed: an asterisk `*` within a segment name, and the sequence `**` for arbitrary directory nesting. The portal matches the relative path against the mask according to built-in rules (similar to common conventions used for masks in ignore files in version control systems). -1. To substitute a path fragment from `values.yaml` or from the `values` field of the action's request, use Go template constructs (`{{ ... }}`) in the line. If the line contains `{{`, the portal processes the entire line from start to finish as a single Go template: you cannot leave part of the line as "plain text" and template only the middle of the path. See examples in [Go template examples in .templateignore](#templateignore-go-examples). +1. Each line is a single rule: a path from the repository root. + Regular path characters and masks are allowed: an asterisk `*` within a segment name, and the sequence `**` for arbitrary directory nesting. + The portal matches the relative path against the mask according to built-in rules (similar to common conventions used for masks in ignore files in version control systems). +1. To substitute a path fragment from `values.yaml` or from the `values` field of the action's request, use Go template constructs (`{{ ... }}`) in the line. + If the line contains `{{`, the portal processes the entire line from start to finish as a single Go template: you cannot leave part of the line as "plain text" and template only the middle of the path. + See examples in [Go template examples in .templateignore](#templateignore-go-examples). 1. Empty lines and lines starting with `#` are skipped when parsing the file — you can use them for comments. -#### Examples without substitution (path masks only) +### Examples without substitution (path masks only) Individual files at the root: @@ -156,31 +172,40 @@ Secrets by extension across the entire tree: -#### How a rule line is processed +### How a rule line is processed The variables available for expanding rules are the same ones merged from `values.yaml` at the root of the template repository and from the `values` field in the action's request (the `values` field in the request takes priority). -For each non-empty line from `.templateignore` or from a file listed in `additionalIgnoreFiles`, the portal does the following. +For each non-empty line from `.templateignore` or from a file listed in `additionalIgnoreFiles`, the portal does the following: -1. The line is always added to the rule list exactly as it appears in the file, unchanged. This is the line that is compared with the file path first — this is needed for cases where the on-disk names still contain fragments like `{{ .module }}` before renaming. -1. If the line contains `{{`, the portal runs the entire line once through the [Go template](https://pkg.go.dev/text/template) engine, with the same capabilities used when substituting into file and directory names (built-in portal functions and the Sprig set). If the line does not contain `{{`, this step is skipped. -1. If the substitution step was performed and the resulting text differs from the line in the file (including the case where the result is empty), a second entry is added to the rule list — with this resulting text. As a result, a single line in the file can produce two entries in the list. When checking a file path, both are checked: a match with either one is enough for the file to be covered by the rule. +1. The line is always added to the rule list exactly as it appears in the file, unchanged. + This is the line that is compared with the file path first — this is needed for cases where the on-disk names still contain fragments like `{{ .module }}` before renaming. +1. If the line contains `{{`, the portal runs the entire line once through the [Go template](https://pkg.go.dev/text/template) engine, with the same capabilities used when substituting into file and directory names (built-in portal functions and the Sprig set). + If the line does not contain `{{`, this step is skipped. +1. If the substitution step was performed and the resulting text differs from the line in the file (including the case where the result is empty), a second entry is added to the rule list — with this resulting text. + As a result, a single line in the file can produce two entries in the list. + When checking a file path, both are checked: a match with either one is enough for the file to be covered by the rule. -Then, while traversing the tree, for each file path, the path relative to the root of the cloned copy is calculated (with forward slashes). The path is compared against each rule: first using mask-matching rules (including `*` and `**`), and, if necessary, by an exact match between the rule string and the relative path. +Then, while traversing the tree, for each file path, the path relative to the root of the cloned copy is calculated (with forward slashes). +The path is compared against each rule: first using mask-matching rules (including `*` and `**`), and, if necessary, by an exact match between the rule string and the relative path. -This way, a single line in the file can define two rules: for example, the original `charts/{{ .name }}/**` (so as not to affect the path before directories are renamed), and the expanded `charts/billing/**` (to match the path after variable substitution into on-disk names). This is why the rules work both "before" and "after" the directory-renaming step of the template. +This way, a single line in the file can define two rules: for example, the original `charts/{{ .name }}/**` (so as not to affect the path before directories are renamed), and the expanded `charts/billing/**` (to match the path after variable substitution into on-disk names). +This is why the rules work both "before" and "after" the directory-renaming step of the template. If the template in a line has a syntax error or references a missing field, rule expansion fails with an error, and repository rendering does not continue. -The `additionalIgnoreFiles` field in the action specifies the names of additional files at the root of the repository; each of them contains rule lines just like `.templateignore`, with the same template expansion. However, the meaning is different: matched paths are removed from the working copy (the directory or file is deleted), and this is done twice — at the beginning and at the end of the processing chain — so that these objects do not participate in further steps and do not end up in the resulting repository. +The `additionalIgnoreFiles` field in the action specifies the names of additional files at the root of the repository; each of them contains rule lines just like `.templateignore`, with the same template expansion. +However, the meaning is different: matched paths are removed from the working copy (the directory or file is deleted), and this is done twice — at the beginning and at the end of the processing chain — so that these objects do not participate in further steps and do not end up in the resulting repository. -The `.templateignore` file, on the other hand, means "do not template": for matched paths, the portal does not substitute variables into file contents and does not apply template-based renaming to the corresponding directory paths. The files and directories themselves are not deleted just because of an entry in `.templateignore` — they remain in the copy, but are processed as plain text and plain names, without the templating step. +The `.templateignore` file, on the other hand, means "do not template": for matched paths, the portal does not substitute variables into file contents and does not apply template-based renaming to the corresponding directory paths. +The files and directories themselves are not deleted just because of an entry in `.templateignore` — they remain in the copy, but are processed as plain text and plain names, without the templating step. -#### Go template examples in .templateignore +### Go template examples in .templateignore -Each example below shows fragments of `values.yaml` (or the equivalent fields in the request's `values`) and lines from `.templateignore`. Several independent rules are defined by several lines in the file: the result of one template line is one masked line; line breaks within the template's result do not split the rule into several. +Each example below shows fragments of `values.yaml` (or the equivalent fields in the request's `values`) and lines from `.templateignore`. +Several independent rules are defined by several lines in the file: the result of one template line is one masked line; line breaks within the template's result do not split the rule into several. The directory name in the rule comes from `values.yaml` or from the action's `values`: @@ -212,7 +237,9 @@ lang: ru apps/{{ .lang }}/messages.yaml ``` -A conditional rule on a single line works as follows: when `skipGenerated: false`, the substitution produces an empty string, which is still added as a second rule. The original line with `{{` is used as a path mask and usually does not match any real paths. When `skipGenerated: true`, the second rule becomes `generated/**`: +A conditional rule on a single line works as follows: when `skipGenerated: false`, the substitution produces an empty string, which is still added as a second rule. +The original line with `{{` is used as a path mask and usually does not match any real paths. +When `skipGenerated: true`, the second rule becomes `generated/**`: `values.yaml`: @@ -254,7 +281,8 @@ chartName: wordpress {{ printf "charts/%s/**" .chartName }} ``` -A default value for an "empty" value — the `default` function from the Sprig set. The field must exist in the data (otherwise expansion will fail with `missingkey=error`); for "not set in YAML", add a key with an empty string, or use the `if` / `index` construct: +A default value for an "empty" value — the `default` function from the Sprig set. +The field must exist in the data (otherwise expansion will fail with `missingkey=error`); for "not set in YAML", add a key with an empty string, or use the `if` / `index` construct: `values.yaml`: @@ -330,9 +358,10 @@ variant: canary {{ .base }}/{{ .variant }}/**/*.tmp ``` -#### Examples for additionalIgnoreFiles +### Examples for additionalIgnoreFiles -The action's specification lists the names of files at the root of the repository (for example, `.ship-ignore`, `.ci-remove`). The line format inside such files is the same: `#` comments, empty lines, path masks, and, if needed, Go templates in lines. +The action's specification lists the names of files at the root of the repository (for example, `.ship-ignore`, `.ci-remove`). +The line format inside such files is the same: `#` comments, empty lines, path masks, and, if needed, Go templates in lines. The `.ship-ignore` file in the template: @@ -360,13 +389,13 @@ The `.env-drop` file at the root of the template: With `obsoleteDir: legacy-ui` from `values`, after expansion, the deletion list will contain both `{{ .obsoleteDir }}/**` and `legacy-ui/**` — matching paths will be removed from the copy before the final steps. {{< alert level="info" >}} -Note the difference: - -- `.templateignore` leaves files on disk but disables path renaming and content rendering for them; -- lists from `additionalIgnoreFiles` remove matched paths from the working copy. +Note the difference: `.templateignore` leaves files on disk but disables path renaming and content rendering for them, +while lists from `additionalIgnoreFiles` remove matched paths from the working copy. {{< /alert >}} -### Example directory structure of a template repository +## Example directory structure of a template repository + +Example of the template repository directory structure: ```text ├── example-folder-01 @@ -392,7 +421,7 @@ If the `example` variable is set to `new` when the repository is rendered, the r -### Local debugging +## Local debugging The `ddp-render-dir` utility is available for local debugging of templates. @@ -403,7 +432,7 @@ The utility: Command-line flags for running it: -* `--source-dir` — the source directory to render. -* `--target-dir` — the directory where the rendering result will be placed. +* `--source-dir`: The source directory to render. +* `--target-dir`: The directory where the rendering result will be placed. * `--values` (optional) — path to a `values.yaml` file with variables to use during rendering. * `--ignore-files` (optional) — a list of files containing paths to exclude from the target repository. diff --git a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.ru.md b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.ru.md index 12113854..12060191 100644 --- a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.ru.md +++ b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplate.ru.md @@ -4,15 +4,16 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `password` — пароль (токен) пользователя, от имени которого будет запускаться выполнение действия. -- `username` — имя пользователя, от которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `username` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль или токен этого пользователя). {{< /alert >}} -CreateRepositoryFromTemplate — создаёт новый репозиторий из шаблона в GitLab. Механизм рендеринга основан на [Go template](https://pkg.go.dev/text/template) и поддерживает все встроенные методы, а также расширения, добавленные в портал. +CreateRepositoryFromTemplate — создаёт новый репозиторий из шаблона в GitLab. +Механизм рендеринга основан на [Go template](https://pkg.go.dev/text/template) и поддерживает все встроенные методы, а также расширения, добавленные в портал. + +## Пример запроса -### Пример запроса +Пример тела запроса действия: ```yaml sourceBranch: main @@ -30,30 +31,33 @@ values: subkey: 123 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | -------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -| templateRepositoryUrl | Да | URL шаблонного репозитория | - | -| targetRepositoryUrl | Да | URL репозитория, который будет создан в результате выполнения действия | - | -| values | Да | Переменные, используемые при шаблонизации, в формате `ключ: значение` | - | -| additionalIgnoreFiles | Нет | Список файлов, содержащих пути для исключения из целевого репозитория. Заполняется по аналогии с [.templateignore](#templateignore) | - | -| sourceTag | Нет | Тег шаблонного репозитория, который будет использоваться при шаблонизации. Если не указан, используется ветка шаблонного репозитория | - | -| sourceBranch | Нет | Ветка шаблонного репозитория, которая будет использоваться при шаблонизации | main | -| targetBranch | Нет | Ветка целевого репозитория, которая будет создана в результате выполнения действия | main | +| `templateRepositoryUrl` | Да | URL шаблонного репозитория | — | +| `targetRepositoryUrl` | Да | URL репозитория, который будет создан в результате выполнения действия | — | +| `values` | Да | Переменные, используемые при шаблонизации, в формате `ключ: значение` | — | +| `additionalIgnoreFiles` | Нет | Список файлов, содержащих пути для исключения из целевого репозитория. Заполняется по аналогии с [.templateignore](#templateignore) | — | +| `sourceTag` | Нет | Тег шаблонного репозитория, который будет использоваться при шаблонизации. Если не указан, используется ветка шаблонного репозитория | — | +| `sourceBranch` | Нет | Ветка шаблонного репозитория, которая будет использоваться при шаблонизации | `main` | +| `targetBranch` | Нет | Ветка целевого репозитория, которая будет создана в результате выполнения действия | `main` | -### Алгоритм работы +## Алгоритм работы Портал: 1. Клонирует шаблонный репозиторий по указанному URL (`templateRepositoryUrl`), используя в качестве ref либо `sourceTag`, либо `sourceBranch`, либо ветку `main`. 1. Считывает файл `values.yaml`, хранящийся в корне репозитория, и определяет переменные по умолчанию для шаблонизации. -1. Считывает переменные, передаваемые при запуске действия, и объединяет (merge) их с переменными из `values.yaml`. Приоритет при merge отдаётся переменным, передаваемым при запуске действия. +1. Считывает переменные, передаваемые при запуске действия, и объединяет (merge) их с переменными из `values.yaml`. + Приоритет при merge отдаётся переменным, передаваемым при запуске действия. 1. Считывает файл `.templateignore` и определяет директории и файлы, исключаемые из шаблонизации. 1. Рендерит из шаблонов файлы, учитывая `values.yaml` и переданные в действие переменные. 1. Изменяет удалённый (remote) репозиторий на целевой (`targetRepositoryUrl`) и делает git push в целевую ветку (`targetBranch`), либо в основную ветку `main`. -### Ответ +## Ответ Действие возвращает переменные шаблонизации в поле `values`: @@ -65,9 +69,10 @@ values: Например, `{{ .response.values.merged.module }}` возвращает значение переменной `module`, использованное при рендеринге. -### Детали работы +## Детали работы -Действие поддерживает шаблонизацию имён директорий и файлов. Для этого необходимо в их название добавить выражение в формате [Go template](https://pkg.go.dev/text/template). +Действие поддерживает шаблонизацию имён директорий и файлов. +Для этого добавьте в их название выражение в формате [Go template](https://pkg.go.dev/text/template). Например, директория `src/{{ .module }}/utils` при наличии value `module` со значением `example` будет отрендерена в директорию `src/example/utils` в целевом репозитории. Если после рендеринга из шаблона содержимое файла будет отсутствовать, файл не создаётся. Например, файл с содержимым: @@ -78,13 +83,14 @@ values: {{- end }} ``` -не будет создан, если переменная `createContent` имеет значение `false`. Аналогичным образом, не будут созданы файлы, изначально являющиеся пустыми. +не будет создан, если переменная `createContent` имеет значение `false`. +Аналогичным образом, не будут созданы файлы, изначально являющиеся пустыми. При отсутствии переменных для шаблонизации одновременно в файле `values.yaml` и в переменных, передаваемых при запуске действия, рендеринг завершится с ошибкой и целевой репозиторий создан не будет. -### Переменные шаблонного репозитория +## Переменные шаблонного репозитория -Для добавления переменных по умолчанию, используемых при шаблонизации, необходимо создать в корне репозитория файл values.yaml с соответствующим содержимым. +Для добавления переменных по умолчанию, используемых при шаблонизации, создайте в корне репозитория файл `values.yaml` с соответствующим содержимым. Пример файла `values.yaml`: @@ -97,13 +103,17 @@ createContent: false -### Исключение файлов +## Исключение файлов -Некоторые файлы могут содержать переменные в формате [Go template](https://pkg.go.dev/text/template), которые необходимо сохранять при рендеринге репозитория из шаблона, например, Helm-чарты в директории `helm`. Директория `.git` игнорируется всегда. +Некоторые файлы могут содержать переменные в формате [Go template](https://pkg.go.dev/text/template), которые должны сохраниться при рендеринге репозитория из шаблона, например, Helm-чарты в директории `helm`. +Директория `.git` игнорируется всегда. Для исключения подобных файлов из механизма рендеринга следует добавить в корень репозитория файл `.templateignore` с соответствующим содержимым. -В каждой строке `.templateignore` задаётся одно правило — путь или маска. Если в строке есть `{{`, вся строка выполняется как один шаблон Go с теми же переменными и функциями, что при подстановке в имена файлов и каталогов (подробнее — [«Как обрабатывается строка правила»](#templateignore-templates)). Если `{{` в строке нет, подстановка переменных из `values.yaml` и из запроса действия не делается: строка читается как есть и сравнивается с относительным путём на диске, допускаются литералы и символы маски `*` и `**`. +В каждой строке `.templateignore` задаётся одно правило — путь или маска. +Если в строке есть `{{`, вся строка выполняется как один шаблон Go с теми же переменными и функциями, что при подстановке в имена файлов и каталогов (подробнее — [«Как обрабатывается строка правила»](#templateignore-templates)). +Если `{{` в строке нет, подстановка переменных из `values.yaml` и из запроса действия не делается. +Строка читается как есть и сравнивается с относительным путём на диске, в ней допускаются литералы и символы маски `*` и `**`. Пример файла `.templateignore` только с масками пути, без шаблонов подстановки, для игнорирования содержимого директорий `helm`, `docs`: @@ -112,14 +122,21 @@ helm/** docs/** ``` -#### Добавление путей в игнорирование +### Добавление путей в игнорирование + +Чтобы исключить пути из обработки, выполните следующие действия: 1. В корне шаблонного репозитория создайте или отредактируйте файл `.templateignore` (по одному правилу на строку). -1. Каждая строка — это одно правило: путь от корня репозитория. В нём допускаются обычные символы пути и маски: звёздочка `*` в имени сегмента, последовательность `**` — для произвольной глубины вложенных каталогов. Портал сопоставляет относительный путь с маской по встроенным правилам (аналогично распространённым соглашениям для масок в файлах игнорирования в системах контроля версий). -1. Чтобы подставить фрагмент пути из `values.yaml` или из поля `values` запроса действия, используйте в строке конструкции Go template (`{{ ... }}`). Если в строке есть `{{`, портал обрабатывает всю строку от начала до конца как один шаблон Go: нельзя оставить часть строки «простым текстом» и шаблонизировать только середину пути. Примеры — в разделе [«Примеры Go template в `.templateignore`»](#templateignore-go-examples). +1. Каждая строка — это одно правило: путь от корня репозитория. + В нём допускаются обычные символы пути и маски: звёздочка `*` в имени сегмента, последовательность `**` — для произвольной глубины вложенных каталогов. + Портал сопоставляет относительный путь с маской по встроенным правилам (аналогично распространённым соглашениям для масок в файлах игнорирования в системах контроля версий). +1. Чтобы подставить фрагмент пути из `values.yaml` или из поля `values` запроса действия, используйте в строке конструкции Go template (`{{ ... }}`). + Если в строке есть `{{`, портал обрабатывает всю строку от начала до конца как один шаблон Go. + Нельзя оставить часть строки «простым текстом» и шаблонизировать только середину пути. + Примеры — в разделе [«Примеры Go template в 0»](#templateignore-go-examples). 1. Пустые строки и строки, начинающиеся с `#`, при разборе файла пропускаются — их можно использовать для комментариев. -#### Примеры без подстановки (только маски пути) +### Примеры без подстановки (только маски пути) Отдельные файлы в корне: @@ -156,31 +173,43 @@ charts/*/values.schema.json -#### Обработка строки правила +### Обработка строки правила Переменные для раскрытия правил те же, что объединены из `values.yaml` в корне шаблонного репозитория и из поля `values` в запросе действия (приоритет у `values` в запросе). -Для каждой непустой строки из `.templateignore` или из файла из `additionalIgnoreFiles` портал делает следующее. +Для каждой непустой строки из `.templateignore` или из файла из `additionalIgnoreFiles` портал делает следующее: -1. В список правил всегда попадает строка как в файле, без изменений. Именно её потом сравнивают с путём к файлу в первую очередь — это нужно, когда в именах на диске ещё есть фрагменты вроде `{{ .module }}` до переименования. -1. Если в строке есть `{{`, портал один раз прогоняет всю строку через шаблонизатор [Go template](https://pkg.go.dev/text/template) с теми же возможностями, что при подстановке в имена файлов и каталогов (встроенные функции портала и набор Sprig). Если `{{` в строке нет, этот шаг пропускают. -1. Если шаг подстановки был и полученный текст отличается от строки в файле (включая случай «на выходе пусто»), в список правил добавляют вторую запись — уже с этим полученным текстом. Итого из одной строки файла может получиться две записи в списке. При проверке пути к файлу смотрят обе: достаточно совпадения с любой из них — файл попадает под правило. +1. В список правил всегда попадает строка как в файле, без изменений. + Именно её потом сравнивают с путём к файлу в первую очередь — это важно, если в именах на диске ещё есть фрагменты вроде `{{ .module }}` до переименования. +1. Если в строке есть `{{`, портал один раз обрабатывает всю строку шаблонизатором [Go template](https://pkg.go.dev/text/template) с теми же возможностями, что при подстановке в имена файлов и каталогов (встроенные функции портала и набор Sprig). + Если `{{` в строке нет, этот шаг пропускают. +1. Если шаг подстановки был и полученный текст отличается от строки в файле (включая случай «на выходе пусто»), в список правил добавляют вторую запись — уже с этим полученным текстом. + Итого из одной строки файла может получиться две записи в списке. + При проверке пути к файлу учитываются обе формы. Если путь совпадает с любой из них, файл попадает под правило. -Дальше при обходе дерева для каждого пути к файлу вычисляется путь относительно корня клонированной копии (с прямыми слешами). Путь сравнивается с каждым правилом: сначала по правилам сопоставления с маской (в том числе с использованием `*` и `**`), при необходимости — по точному совпадению строки правила и относительного пути. +Дальше при обходе дерева для каждого пути к файлу вычисляется путь относительно корня клонированной копии (с прямыми слешами). +Путь сравнивается с каждым правилом. +Сначала — по правилам сопоставления с маской (в том числе с использованием `*` и `**`), при необходимости — по точному совпадению строки правила и относительного пути. -Так одна строка в файле может задать два правила: например, исходное `charts/{{ .name }}/**` (чтобы не трогать путь до переименования каталогов), и раскрытое `charts/billing/**` (чтобы совпадало с путём после подстановки переменных в имена на диске). Поэтому правила работают и «до», и «после» этапа переименования каталогов по шаблону. +Так одна строка в файле может задать два правила, например исходное `charts/{{ .name }}/**` (чтобы не трогать путь до переименования каталогов), и раскрытое `charts/billing/**` (чтобы совпадало с путём после подстановки переменных в имена на диске). +Поэтому правила работают и «до», и «после» этапа переименования каталогов по шаблону. Если шаблон в строке синтаксически неверен или обращается к отсутствующему полю, раскрытие правил завершается ошибкой, и рендер репозитория не продолжается. -Поле `additionalIgnoreFiles` в действии задаёт имена дополнительных файлов в корне репозитория; в каждом из них — такие же строки-правила, как в `.templateignore`, с тем же раскрытием шаблонов. Но смысл другой: совпавшие пути убирают из рабочей копии (каталог или файл удаляют), и делают это дважды — в начале и в конце цепочки обработки, чтобы эти объекты не участвовали в дальнейших шагах и не попали в итоговый репозиторий. +Поле `additionalIgnoreFiles` в действии задаёт имена дополнительных файлов в корне репозитория; в каждом из них — такие же строки-правила, как в `.templateignore`, с тем же раскрытием шаблонов. +Но смысл другой. +Совпавшие пути убирают из рабочей копии (каталог или файл удаляют), и делают это дважды — в начале и в конце цепочки обработки, чтобы эти объекты не участвовали в дальнейших шагах и не попали в итоговый репозиторий. -Файл `.templateignore`, наоборот, означает «не шаблонизировать»: для совпавших путей портал не подставляет переменные в содержимое файлов и не применяет к соответствующим каталогам переименование по шаблону в пути. Сами файлы и каталоги при этом не удаляются только из‑за записи в `.templateignore` — они остаются в копии, но обрабатываются как обычный текст и обычные имена, без шага шаблонизации. +Файл `.templateignore`, наоборот, означает «не шаблонизировать»: для совпавших путей портал не подставляет переменные в содержимое файлов и не применяет к соответствующим каталогам переименование по шаблону в пути. +Сами файлы и каталоги при этом не удаляются только из‑за записи в `.templateignore` — они остаются в копии, но обрабатываются как обычный текст и обычные имена, без шага шаблонизации. -#### Примеры Go template в .templateignore +### Примеры Go template в .templateignore -Ниже в каждом примере показаны фрагменты `values.yaml` (или эквивалентные поля в `values` запроса) и строки `.templateignore`. Несколько независимых правил задают несколькими строками файла: результат одной строки-шаблона — одна строка с маской; перевод строк внутри результата шаблона не делит правило на несколько. +Ниже в каждом примере показаны фрагменты `values.yaml` (или эквивалентные поля в `values` запроса) и строки `.templateignore`. +Несколько независимых правил задают несколькими строками файла. +Результат одной строки-шаблона — одна строка с маской, и перевод строк внутри результата шаблона не делит правило на несколько. Имя каталога в правиле берётся из `values.yaml` или из `values` действия: @@ -212,7 +241,9 @@ lang: ru apps/{{ .lang }}/messages.yaml ``` -Условное правило в одной строке работает следующим образом: при `skipGenerated: false` подстановка даёт пустую строку, которая всё равно добавляется вторым правилом. Исходная строка с `{{` используется как маска пути и обычно не совпадает с реальными путями. При `skipGenerated: true` вторым правилом становится `generated/**`): +Условное правило в одной строке работает следующим образом: при `skipGenerated: false` подстановка даёт пустую строку, которая всё равно добавляется вторым правилом. +Исходная строка с `{{` используется как маска пути и обычно не совпадает с реальными путями. +При `skipGenerated: true` вторым правилом становится `generated/**`): `values.yaml`: @@ -254,7 +285,8 @@ chartName: wordpress {{ printf "charts/%s/**" .chartName }} ``` -Значение по умолчанию для «пустого» значения — функция `default` из набора Sprig. Поле в данных должно существовать (иначе при раскрытии сработает `missingkey=error`); для «не задано в YAML» заведите ключ с пустой строкой или используйте условие `if` / `index`: +Значение по умолчанию для «пустого» значения — функция `default` из набора Sprig. +Поле в данных должно существовать (иначе при раскрытии сработает `missingkey=error`); для «не задано в YAML» заведите ключ с пустой строкой или используйте условие `if` / `index`: `values.yaml`: @@ -330,9 +362,10 @@ variant: canary {{ .base }}/{{ .variant }}/**/*.tmp ``` -#### Примеры для additionalIgnoreFiles +### Примеры для additionalIgnoreFiles -В спецификации действия перечисляются имена файлов в корне репозитория (например, `.ship-ignore`, `.ci-remove`). Формат строк внутри таких файлов тот же: комментарии `#`, пустые строки, маски пути, при необходимости — шаблоны Go в строках. +В спецификации действия перечисляются имена файлов в корне репозитория (например, `.ship-ignore`, `.ci-remove`). +Формат строк внутри таких файлов тот же: комментарии `#`, пустые строки, маски пути, при необходимости — шаблоны Go в строках. Файл `.ship-ignore` в шаблоне: @@ -360,13 +393,13 @@ additionalIgnoreFiles: При `obsoleteDir: legacy-ui` из `values` после раскрытия в списке удаления окажутся и `{{ .obsoleteDir }}/**`, и `legacy-ui/**` — совпавшие пути будут удалены из копии перед финальными шагами. {{< alert level="info" >}} -Учитывайте различия: - -- `.templateignore` оставляет файлы на диске, но отключает для них переименование пути и рендер содержимого; -- списки из `additionalIgnoreFiles` удаляют совпавшие пути из рабочей копии. +Учитывайте различия: `.templateignore` оставляет файлы на диске, но отключает для них переименование пути и рендер содержимого, +а списки из `additionalIgnoreFiles` удаляют совпавшие пути из рабочей копии. {{< /alert >}} -### Пример структуры директорий шаблонного репозитория +## Пример структуры директорий шаблонного репозитория + +Пример структуры директорий шаблонного репозитория: ```text ├── example-folder-01 @@ -392,7 +425,7 @@ additionalIgnoreFiles: -### Локальная отладка +## Локальная отладка Для локальной отладки шаблонов доступна утилита `ddp-render-dir`. @@ -403,7 +436,7 @@ additionalIgnoreFiles: Ключи командной строки для запуска: -* `--source-dir` — исходная директория, которую необходимо отрендерить. +* `--source-dir` — исходная директория для рендеринга. * `--target-dir` — директория, в которую будет помещен результат рендеринга. * `--values` (опционально) — путь к файлу `values.yaml` с переменными, которые будут использоваться при рендеринге. * `--ignore-files` (опционально) — список файлов, содержащих пути для исключения из целевого репозитория. diff --git a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.md b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.md new file mode 100644 index 00000000..c98aaf21 --- /dev/null +++ b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.md @@ -0,0 +1,73 @@ +--- +title: CreateRepositoryFromTemplatePack +weight: 12 +--- + +{{< alert level="info" >}} +Running this action requires credentials: `username` (the username under which the action runs) +and `password` (the password or token for that user). +{{< /alert >}} + +CreateRepositoryFromTemplatePack — populates a repository with the files of a [template pack](../../templates/packs/) from the template registry. +In the interface, the action is called "Create repository from a template pack". + +The action downloads a pack version, renders the files with the passed parameter values, writes the `.ddp/template.lock.yaml` lock file to the repository, and pushes a commit to the target branch. +The portal then uses the lock file to [upgrade the repository](../../templates/updates/) to new template versions. + +## Request example + +Example of the action request body: + +```yaml +targetRepositoryUrl: https://gitlab.example.com/group/billing-api.git +targetBranch: main +templateId: go-service +templateVersion: 1.2.0 +templatePackSource: company +values: + port: 8080 +``` + +## Request specification + +The action request body supports the following parameters: + +| Name | Required | Description | Default value | +| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `targetRepositoryUrl` | Yes | HTTPS address of the repository. The host must match the host of the action's external service | — | +| `targetBranch` | No | Branch to which the commit is pushed | The "Default branch" value of the template registry, otherwise `main` | +| `templateId` | Yes | Template ID | — | +| `templatePackSource` | Yes | Name of the connection in the [template registry](../../templates/registry/) from which the template is taken | — | +| `templateVersion` | No | Template version in semver format | Latest template version | +| `values` | No | Template parameter values. The set of parameters is defined by the pack's `values.yaml` file | — | +| `additionalIgnorePatterns` | No | Additional glob patterns of paths that are not rendered or copied to the repository | — | +| `commitMessage` | No | Commit message | `chore(template): scaffold from @` | + +## How it works + +Deckhouse Development Portal (DDP): + +1. Selects the template version in the `templatePackSource` registry. The version must have the "available" status. +1. Downloads the pack and fills in the parameters annotated with `x-ddp-from` from the [process run context](../../home/processes/#creating-a-microservice). +1. Validates the parameter values against the `values.yaml` schema and renders the pack files. +1. Clones the target branch of the repository. An empty repository is initialized. +1. Copies the rendered files and writes the `.ddp/template.lock.yaml` lock file with the template ID, template version, and parameter values. +1. Creates a commit and pushes it to the target branch. + +## Response + +The action response contains the `templateId`, `templateVersion`, `templateSource`, `targetBranch`, and `commitSha` fields, as well as `values.request` (the passed parameter values) and `values.merged` (the resulting values including defaults). + +## Errors + +An error message starts with a code. The main codes are: + +| Code | Cause | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `invalid_request` | `templateId` or `templatePackSource` is not set, or the version is not in semver format | +| `pack_unavailable` | The `templatePackSource` connection is not found, or the version is unavailable | +| `pack_not_found` | The template version is not found | +| `pack_deprecated` | The template version has been withdrawn | +| `values_invalid` | The parameter values do not match the `values.yaml` schema, or the `x-ddp-from` path is not found in the run context | +| `render_failed` | Pack file templating failed | +| `clone_failed`, `push_failed` | Cloning the repository or pushing the commit failed | diff --git a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.ru.md b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.ru.md index 2abad4b3..8dcb23a3 100644 --- a/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.ru.md +++ b/content/documentation/admin/actions/gitlab/createrepositoryfromtemplatepack.ru.md @@ -4,17 +4,19 @@ weight: 12 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `password` — пароль (токен) пользователя, от имени которого будет выполнено действие; -- `username` — имя пользователя, от имени которого будет выполнено действие. +Для выполнения действия необходимы учётные данные: `username` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль или токен этого пользователя). {{< /alert >}} -CreateRepositoryFromTemplatePack — заполняет репозиторий файлами [пакета шаблона](../../templates/packs/) из реестра шаблонов. В интерфейсе действие называется «Создать репозиторий из пакета шаблонов». +CreateRepositoryFromTemplatePack — заполняет репозиторий файлами [пакета шаблона](../../templates/packs/) из реестра шаблонов. +В интерфейсе действие называется «Создать репозиторий из пакета шаблонов». + +Действие загружает версию пакета, отрисовывает файлы с переданными значениями параметров, записывает в репозиторий lock-файл `.ddp/template.lock.yaml` и отправляет коммит в целевую ветку. +По lock-файлу портал затем [обновляет репозиторий](../../templates/updates/) до новых версий шаблона. -Действие загружает версию пакета, отрисовывает файлы с переданными значениями параметров, записывает в репозиторий lock-файл `.ddp/template.lock.yaml` и отправляет коммит в целевую ветку. По lock-файлу портал затем [обновляет репозиторий](../../templates/updates/) до новых версий шаблона. +## Пример запроса -### Пример запроса +Пример тела запроса действия: ```yaml targetRepositoryUrl: https://gitlab.example.com/group/billing-api.git @@ -26,22 +28,24 @@ values: port: 8080 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ------------------------ | -------------- | -------------------------------------------------------------------------------------------------- | --------------------- | -| targetRepositoryUrl | Да | HTTPS-адрес репозитория. Хост должен совпадать с хостом внешнего сервиса действия | - | -| targetBranch | Нет | Ветка, в которую отправляется коммит | Значение «Ветка по умолчанию» реестра шаблонов, иначе `main` | -| templateId | Да | Идентификатор шаблона | - | -| templatePackSource | Да | Название подключения в [реестре шаблонов](../../templates/registry/), из которого берётся шаблон | - | -| templateVersion | Нет | Версия шаблона в формате semver | Последняя версия шаблона | -| values | Нет | Значения параметров шаблона. Состав параметров задаёт файл `values.yaml` пакета | - | -| additionalIgnorePatterns | Нет | Дополнительные glob-шаблоны путей, которые не отрисовываются и не копируются в репозиторий | - | -| commitMessage | Нет | Сообщение коммита | `chore(template): scaffold from @` | +| `targetRepositoryUrl` | Да | HTTPS-адрес репозитория. Хост должен совпадать с хостом внешнего сервиса действия | — | +| `targetBranch` | Нет | Ветка, в которую отправляется коммит | Значение «Ветка по умолчанию» реестра шаблонов, иначе `main` | +| `templateId` | Да | Идентификатор шаблона | — | +| `templatePackSource` | Да | Название подключения в [реестре шаблонов](../../templates/registry/), из которого берётся шаблон | — | +| `templateVersion` | Нет | Версия шаблона в формате semver | Последняя версия шаблона | +| `values` | Нет | Значения параметров шаблона. Состав параметров задаёт файл `values.yaml` пакета | — | +| `additionalIgnorePatterns` | Нет | Дополнительные glob-шаблоны путей, которые не отрисовываются и не копируются в репозиторий | — | +| `commitMessage` | Нет | Сообщение коммита | `chore(template): scaffold from @` | -### Алгоритм работы +## Алгоритм работы -DDP: +Deckhouse Development Portal (DDP): 1. Выбирает версию шаблона в реестре `templatePackSource`. Версия должна иметь статус «доступна». 1. Загружает пакет и заполняет параметры с аннотацией `x-ddp-from` из [контекста запуска процесса](../../home/processes/#создание-микросервиса). @@ -50,11 +54,11 @@ DDP: 1. Копирует отрисованные файлы, записывает lock-файл `.ddp/template.lock.yaml` с идентификатором, версией шаблона и значениями параметров. 1. Создаёт коммит и отправляет его в целевую ветку. -### Ответ +## Ответ Ответ действия содержит поля `templateId`, `templateVersion`, `templateSource`, `targetBranch`, `commitSha`, а также `values.request` — переданные значения параметров и `values.merged` — итоговые значения с учётом значений по умолчанию. -### Ошибки +## Ошибки Сообщение об ошибке начинается с кода. Основные коды: diff --git a/content/documentation/admin/actions/gitlab/deletegitlabproject.md b/content/documentation/admin/actions/gitlab/deletegitlabproject.md index 46aa2fc8..0c6649c9 100644 --- a/content/documentation/admin/actions/gitlab/deletegitlabproject.md +++ b/content/documentation/admin/actions/gitlab/deletegitlabproject.md @@ -7,20 +7,25 @@ weight: 110 This action requires a token for the user on whose behalf it will run. {{< /alert >}} -DeleteGitlabProject — deletes an existing project in GitLab through the GitLab API. Authentication uses a GitLab token provided in the credentials. +DeleteGitlabProject — deletes an existing project in GitLab through the GitLab API. +Authentication uses a GitLab token provided in the credentials. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: 0 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | --------------------------- | -------- | -------------------------------------------------------- | -| project_id | Yes | Identifier of the project to delete | +| `project_id` | Yes | Identifier of the project to delete | -### Note +## GitLab API request The action performs a DELETE request to the URL: `/api/v4/projects/:id`. diff --git a/content/documentation/admin/actions/gitlab/deletegitlabproject.ru.md b/content/documentation/admin/actions/gitlab/deletegitlabproject.ru.md index ffaf7fd4..94a36088 100644 --- a/content/documentation/admin/actions/gitlab/deletegitlabproject.ru.md +++ b/content/documentation/admin/actions/gitlab/deletegitlabproject.ru.md @@ -7,20 +7,26 @@ weight: 110 Для выполнения действия требуется токен пользователя, от имени которого оно будет выполнено. {{< /alert >}} -DeleteGitlabProject — удаляет существующий проект в GitLab. Действие осуществляет вызов GitLab API для удаления проекта. Для аутентификации используется GitLab token, который должен быть предоставлен в учётных данных. +DeleteGitlabProject — удаляет существующий проект в GitLab. +Действие осуществляет вызов GitLab API для удаления проекта. +Для аутентификации используется GitLab token, который должен быть предоставлен в учётных данных. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: 0 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | --------------------------- | ---------------- | ---------------------------------------------------- | -| project_id | Да | Идентификатор проекта, который необходимо удалить | +| `project_id` | Да | Идентификатор проекта, который необходимо удалить | -### Примечание +## Запрос к API GitLab Действие осуществляет DELETE-запрос по URL: `/api/v4/projects/:id`. diff --git a/content/documentation/admin/actions/gitlab/getgitlabpipeline.md b/content/documentation/admin/actions/gitlab/getgitlabpipeline.md new file mode 100644 index 00000000..0da5ab8f --- /dev/null +++ b/content/documentation/admin/actions/gitlab/getgitlabpipeline.md @@ -0,0 +1,39 @@ +--- +title: GetGitlabPipeline +weight: 105 +--- + +{{< alert level="info" >}} +Running this action requires the token of the user under which it runs. +{{< /alert >}} + +GetGitlabPipeline — returns the state of a GitLab pipeline. + +The action is used in processes that start a pipeline with the [StartGitlabPipeline](startgitlabpipeline/) action and wait for it to complete by periodically requesting its state. + +## Request example + +Example of the action request body: + +```yaml +project_id: "0" +pipeline_id: "0" +``` + +## Request specification + +The action request body supports the following parameters: + +| Name | Required | Description | +| ------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `project_id` | Yes | GitLab project ID or project path, for example, `group/project` | +| `pipeline_id` | Yes | Pipeline ID, that is, the `id` field of the GitLab response, for example, `{{ .response.id }}` of the StartGitlabPipeline action | + +## Response + +The action response is the GitLab pipeline object with the `id`, `iid`, `status`, `ref`, `sha`, `web_url`, and other fields. +The pipeline state is available in subsequent process elements as `{{ .response.status }}`. + +## GitLab API request + +The action performs a GET request to the URL: `/api/v4/projects/:id/pipelines/:pipeline_id`. diff --git a/content/documentation/admin/actions/gitlab/getgitlabpipeline.ru.md b/content/documentation/admin/actions/gitlab/getgitlabpipeline.ru.md index 5bef2221..d7d90845 100644 --- a/content/documentation/admin/actions/gitlab/getgitlabpipeline.ru.md +++ b/content/documentation/admin/actions/gitlab/getgitlabpipeline.ru.md @@ -11,24 +11,29 @@ GetGitlabPipeline — возвращает состояние пайплайна Действие используется в процессах, которые запускают пайплайн действием [StartGitlabPipeline](startgitlabpipeline/) и ожидают его завершения, периодически запрашивая состояние. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: "0" pipeline_id: "0" ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ----------- | -------------- | ------------------------------------------------------------------------------------------------- | -| project_id | Да | Идентификатор проекта GitLab или путь проекта, например `group/project` | -| pipeline_id | Да | Идентификатор пайплайна — поле `id` ответа GitLab, например `{{ .response.id }}` действия StartGitlabPipeline | +| `project_id` | Да | Идентификатор проекта GitLab или путь проекта, например `group/project` | +| `pipeline_id` | Да | Идентификатор пайплайна — поле `id` ответа GitLab, например `{{ .response.id }}` действия StartGitlabPipeline | -### Ответ +## Ответ -Ответ действия — объект пайплайна GitLab с полями `id`, `iid`, `status`, `ref`, `sha`, `web_url` и другими. Состояние пайплайна доступно в последующих элементах процесса как `{{ .response.status }}`. +Ответ действия — объект пайплайна GitLab с полями `id`, `iid`, `status`, `ref`, `sha`, `web_url` и другими. +Состояние пайплайна доступно в последующих элементах процесса как `{{ .response.status }}`. -### Примечание +## Запрос к API GitLab Действие осуществляет GET-запрос по URL: `/api/v4/projects/:id/pipelines/:pipeline_id`. diff --git a/content/documentation/admin/actions/gitlab/startgitlabpipeline.md b/content/documentation/admin/actions/gitlab/startgitlabpipeline.md index d3daebed..3ece8fe9 100644 --- a/content/documentation/admin/actions/gitlab/startgitlabpipeline.md +++ b/content/documentation/admin/actions/gitlab/startgitlabpipeline.md @@ -9,7 +9,9 @@ This action requires a token for the user on whose behalf it will run. StartGitlabPipeline — starts a pipeline in GitLab. -### Request example +## Request example + +Example of the action request body: ```yaml project_id: 0 @@ -19,20 +21,23 @@ variables: value: example-value ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | --------------------------- | -------- | ---------------------------------------------------------------------------------- | -| project_id | Yes | Identifier of the project in which to run the pipeline | -| ref | Yes | Name of the branch or tag, or the commit SHA, on which the pipeline will run | -| variables | No | List of variables to pass to the pipeline being run | -| variables.key | Yes | Variable name | -| variables.value | Yes | Variable value | +| `project_id` | Yes | Identifier of the project in which to run the pipeline | +| `ref` | Yes | Name of the branch or tag, or the commit SHA, on which the pipeline will run | +| `variables` | No | List of variables to pass to the pipeline being run | +| `variables.key` | Yes | Variable name | +| `variables.value` | Yes | Variable value | -### Response +## Response -The action response is the object of the created GitLab pipeline with the `id`, `iid`, `status`, `ref`, `web_url` and other fields. Use the identifier `{{ .response.id }}` to track the pipeline status with the GetGitlabPipeline action. +The action response is the object of the created GitLab pipeline with the `id`, `iid`, `status`, `ref`, `web_url` and other fields. +Use the identifier `{{ .response.id }}` to track the pipeline status with the GetGitlabPipeline action. -### Note +## GitLab API request The action performs a POST request to the URL: `/api/v4/projects/:id/pipeline`. diff --git a/content/documentation/admin/actions/gitlab/startgitlabpipeline.ru.md b/content/documentation/admin/actions/gitlab/startgitlabpipeline.ru.md index c1c80677..cd001c24 100644 --- a/content/documentation/admin/actions/gitlab/startgitlabpipeline.ru.md +++ b/content/documentation/admin/actions/gitlab/startgitlabpipeline.ru.md @@ -9,7 +9,9 @@ weight: 100 StartGitlabPipeline — запускает выполнение пайплайна в GitLab. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project_id: 0 @@ -19,20 +21,23 @@ variables: value: example-value ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | --------------------------- | ---------------- | ---------------------------------------------------------------------------- | -| project_id | Да | Идентификатор проекта, в котором необходимо запустить пайплайн | -| ref | Да | Название ветки, тег или SHA-хеш коммита, на котором будет запущен пайплайн | -| variables | Нет | Список переменных, которые необходимо передать в запускаемый пайплайн | -| variables.key | Да | Название переменной | -| variables.value | Да | Значение переменной | +| `project_id` | Да | Идентификатор проекта, в котором необходимо запустить пайплайн | +| `ref` | Да | Название ветки, тег или SHA-хеш коммита, на котором будет запущен пайплайн | +| `variables` | Нет | Список переменных, которые необходимо передать в запускаемый пайплайн | +| `variables.key` | Да | Название переменной | +| `variables.value` | Да | Значение переменной | -### Ответ +## Ответ -Ответ действия — объект созданного пайплайна GitLab с полями `id`, `iid`, `status`, `ref`, `web_url` и другими. Идентификатор `{{ .response.id }}` используется для отслеживания состояния пайплайна действием [GetGitlabPipeline](getgitlabpipeline/). +Ответ действия — объект созданного пайплайна GitLab с полями `id`, `iid`, `status`, `ref`, `web_url` и другими. +Идентификатор `{{ .response.id }}` используется для отслеживания состояния пайплайна действием [GetGitlabPipeline](getgitlabpipeline/). -### Примечание +## Запрос к API GitLab Действие осуществляет POST-запрос по URL: `/api/v4/projects/:id/pipeline`. diff --git a/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.md b/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.md new file mode 100644 index 00000000..539e46c1 --- /dev/null +++ b/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.md @@ -0,0 +1,84 @@ +--- +title: UpgradeRepositoryFromTemplatePack +weight: 14 +--- + +{{< alert level="info" >}} +Running this action requires credentials: `username` (the username under which the action runs) +and `password` (the password or token for that user). +{{< /alert >}} + +UpgradeRepositoryFromTemplatePack — transfers the changes of a new [template pack](../../templates/packs/) version to a microservice repository. +In the interface, the action is called "Upgrade repository from a template pack". + +The action does not change the main branch. +It creates an upgrade branch with the changes, which are then proposed in a merge request created by the [CreateGitlabMergeRequestReview](creategitlabmergerequestreview/) action. +The upgrade mechanism is described in ["Template upgrades"](../../templates/updates/). + +The action runs for a microservice entity. + +## Request example + +Example of the action request body: + +```yaml +templateVersion: 1.3.0 +upgradeStrategy: selective +updateOverwrite: + - .gitlab-ci.yml +updateAddIfMissing: + - docs/CONTRIBUTING.md +``` + +## Request specification + +Unset `templateId`, `templatePackSource`, `targetRepositoryUrl`, and `targetBranch` fields are filled in from the microservice entity properties by the roles of the [mapping rules](../../home/mapping/#microservices). + +| Name | Required | Description | Default value | +| -------------------------- | -------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| `targetRepositoryUrl` | Yes | HTTPS address of the microservice repository | The `microservice_repository` role | +| `targetBranch` | No | Branch from which the upgrade branch is created | The `microservice_default_branch` role, then the "Default branch" of the template registry, then `main` | +| `sourceBranch` | No | Branch to which the changes are written | ``, for example, `ddp/template-upgrade-1.3.0` | +| `templateId` | Yes | Template ID | The `microservice_binding_template_id` role | +| `templatePackSource` | Yes | Name of the connection in the template registry | The `microservice_binding_template_source` role | +| `templateVersion` | No | Target template version in semver format | Latest template version | +| `upgradeStrategy` | No | Upgrade strategy: `selective`, `additive`, `selective_additive`, `full`, or `merge` | The microservice property, then the pack strategy, then `selective` | +| `updateOverwrite` | No | Glob patterns of paths to overwrite | The microservice property, then the pack list | +| `updateAddIfMissing` | No | Glob patterns of paths to add if missing | The microservice property, then the pack list | +| `values` | No | Template parameter values. They are merged with the values from the lock file | — | +| `additionalIgnorePatterns` | No | Additional glob patterns of paths that are not rendered or copied | — | +| `commitMessage` | No | Commit message | `chore(template): upgrade -> ` | + +The strategies and the path lists they require are described in ["Upgrade strategies"](../../templates/updates/#upgrade-strategies). + +## How it works + +Deckhouse Development Portal (DDP): + +1. Clones the `targetBranch` branch and reads the `.ddp/template.lock.yaml` lock file. + If the version in the catalog differs from the version in the lock file, corrects the microservice template version property. +1. If the version in the lock file is not lower than the target version, completes the action successfully without changes. +1. Renders the target pack version with the values from the lock file and the `values` field. +1. Creates the `sourceBranch` branch and applies the changes according to the upgrade strategy. Files are not deleted. +1. Writes the new version and parameter values to the lock file, creates a commit, and pushes the `sourceBranch` branch. + +If a merge conflict occurs with the `merge` strategy, nothing is written to the repository. + +## Response + +The action response contains the following fields: + +| Name | Description | +| ----------------- | ------------------------------------------------------------------- | +| `templateId` | Template ID | +| `templateSource` | Registry connection name | +| `previousVersion` | Template version before the upgrade | +| `targetVersion` | Target version | +| `sourceBranch` | Upgrade branch | +| `targetBranch` | Branch from which the upgrade branch was created | +| `strategy` | Applied strategy | +| `commitSha` | SHA of the upgrade commit | +| `upgradeSkipped` | `true` if the repository is already at the target version | +| `versionDrift` | Details about the catalog version correction based on the lock file | + +Error codes are described in ["Troubleshooting"](../../templates/updates/#troubleshooting). diff --git a/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.ru.md b/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.ru.md index 2563ca9a..f077f054 100644 --- a/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.ru.md +++ b/content/documentation/admin/actions/gitlab/upgraderepositoryfromtemplatepack.ru.md @@ -4,19 +4,22 @@ weight: 14 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `password` — пароль (токен) пользователя, от имени которого будет выполнено действие; -- `username` — имя пользователя, от имени которого будет выполнено действие. +Для выполнения действия необходимы учётные данные: `username` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль или токен этого пользователя). {{< /alert >}} -UpgradeRepositoryFromTemplatePack — переносит в репозиторий микросервиса изменения новой версии [пакета шаблона](../../templates/packs/). В интерфейсе действие называется «Обновить репозиторий из пакета шаблонов». +UpgradeRepositoryFromTemplatePack — переносит в репозиторий микросервиса изменения новой версии [пакета шаблона](../../templates/packs/). +В интерфейсе действие называется «Обновить репозиторий из пакета шаблонов». -Действие не изменяет основную ветку: оно создаёт ветку обновления с изменениями, которые затем предлагаются в merge request действием [CreateGitlabMergeRequestReview](creategitlabmergerequestreview/). Механизм обновления описан в разделе [«Обновление из шаблона»](../../templates/updates/). +Действие не изменяет основную ветку. +Оно создаёт ветку обновления с изменениями, которые затем предлагаются в запросе на слияние (Merge Request), созданном действием [CreateGitlabMergeRequestReview](creategitlabmergerequestreview/). +Механизм обновления описан в разделе [«Обновление из шаблона»](../../templates/updates/). Действие выполняется для сущности микросервиса. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml templateVersion: 1.3.0 @@ -27,32 +30,33 @@ updateAddIfMissing: - docs/CONTRIBUTING.md ``` -### Спецификация запроса +## Спецификация запроса Незаданные поля `templateId`, `templatePackSource`, `targetRepositoryUrl` и `targetBranch` заполняются из параметров сущности микросервиса по ролям [правил маппинга](../../home/mapping/#микросервисы). | Название | Обязательность | Описание | Значение по умолчанию | | ------------------------ | -------------- | ---------------------------------------------------------------------------------------- | --------------------- | -| targetRepositoryUrl | Да | HTTPS-адрес репозитория микросервиса | Роль `microservice_repository` | -| targetBranch | Нет | Ветка, от которой создаётся ветка обновления | Роль `microservice_default_branch`, затем «Ветка по умолчанию» реестра шаблонов, затем `main` | -| sourceBranch | Нет | Ветка, в которую записываются изменения | `<префикс ветки обновления><версия>`, например `ddp/template-upgrade-1.3.0` | -| templateId | Да | Идентификатор шаблона | Роль `microservice_binding_template_id` | -| templatePackSource | Да | Название подключения в реестре шаблонов | Роль `microservice_binding_template_source` | -| templateVersion | Нет | Целевая версия шаблона в формате semver | Последняя версия шаблона | -| upgradeStrategy | Нет | Стратегия обновления: `selective`, `additive`, `selective_additive`, `full` или `merge` | Параметр микросервиса, затем стратегия пакета, затем `selective` | -| updateOverwrite | Нет | Glob-шаблоны перезаписываемых путей | Параметр микросервиса, затем список пакета | -| updateAddIfMissing | Нет | Glob-шаблоны путей, добавляемых при отсутствии | Параметр микросервиса, затем список пакета | -| values | Нет | Значения параметров шаблона. Объединяются со значениями из lock-файла | - | -| additionalIgnorePatterns | Нет | Дополнительные glob-шаблоны путей, которые не отрисовываются и не копируются | - | -| commitMessage | Нет | Сообщение коммита | `chore(template): upgrade -> ` | +| `targetRepositoryUrl` | Да | HTTPS-адрес репозитория микросервиса | Роль `microservice_repository` | +| `targetBranch` | Нет | Ветка, от которой создаётся ветка обновления | Роль `microservice_default_branch`, затем «Ветка по умолчанию» реестра шаблонов, затем `main` | +| `sourceBranch` | Нет | Ветка, в которую записываются изменения | ``, например `ddp/template-upgrade-1.3.0` | +| `templateId` | Да | Идентификатор шаблона | Роль `microservice_binding_template_id` | +| `templatePackSource` | Да | Название подключения в реестре шаблонов | Роль `microservice_binding_template_source` | +| `templateVersion` | Нет | Целевая версия шаблона в формате semver | Последняя версия шаблона | +| `upgradeStrategy` | Нет | Стратегия обновления: `selective`, `additive`, `selective_additive`, `full` или `merge` | Параметр микросервиса, затем стратегия пакета, затем `selective` | +| `updateOverwrite` | Нет | Glob-шаблоны перезаписываемых путей | Параметр микросервиса, затем список пакета | +| `updateAddIfMissing` | Нет | Glob-шаблоны путей, добавляемых при отсутствии | Параметр микросервиса, затем список пакета | +| `values` | Нет | Значения параметров шаблона. Объединяются со значениями из lock-файла | — | +| `additionalIgnorePatterns` | Нет | Дополнительные glob-шаблоны путей, которые не отрисовываются и не копируются | — | +| `commitMessage` | Нет | Сообщение коммита | `chore(template): upgrade -> ` | Стратегии и обязательные для них списки путей описаны в разделе [«Стратегии обновления»](../../templates/updates/#стратегии-обновления). -### Алгоритм работы +## Алгоритм работы -DDP: +Deckhouse Development Portal (DDP): -1. Клонирует ветку `targetBranch` и читает lock-файл `.ddp/template.lock.yaml`. Если версия в каталоге отличается от версии в lock-файле, исправляет параметр версии шаблона микросервиса. +1. Клонирует ветку `targetBranch` и читает lock-файл `.ddp/template.lock.yaml`. + Если версия в каталоге отличается от версии в lock-файле, исправляет параметр версии шаблона микросервиса. 1. Если версия в lock-файле не ниже целевой, завершает действие успешно без изменений. 1. Отрисовывает целевую версию пакета со значениями из lock-файла и из поля `values`. 1. Создаёт ветку `sourceBranch` и применяет изменения по стратегии обновления. Файлы не удаляются. @@ -60,11 +64,11 @@ DDP: При конфликте слияния в стратегии `merge` в репозиторий ничего не записывается. -### Ответ +## Ответ Ответ действия содержит поля: -| Поле | Описание | +| Название | Описание | | ----------------- | ----------------------------------------------------------- | | `templateId` | Идентификатор шаблона | | `templateSource` | Название подключения реестра | diff --git a/content/documentation/admin/actions/kafka/createkafkaacls.md b/content/documentation/admin/actions/kafka/createkafkaacls.md index 129e63d3..b6c1e37c 100644 --- a/content/documentation/admin/actions/kafka/createkafkaacls.md +++ b/content/documentation/admin/actions/kafka/createkafkaacls.md @@ -4,15 +4,15 @@ weight: 50 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} CreateKafkaACLs — creates a set of ACLs in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -50,32 +50,36 @@ acls: pattern: LITERAL ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | Default value | | ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------ | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | - | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | - | -| acls | Yes | Set of ACLs to create | - | - | -| acls.ops | Yes | List of operations to which the rule applies | [List of possible operations](#list-of-possible-operations) | - | -| acls.pattern | Yes | Pattern type | [List of possible patterns](#list-of-possible-patterns) | - | -| acls.topics | No | List of topic names to which the rule applies | - | - | -| acls.groups | No | List of group names to which the rule applies | - | - | -| acls.transactional_ids | No | List of transaction IDs to which the rule applies | - | - | -| acls.tokens | No | List of tokens to which the rule applies | - | - | -| acls.allow | No | List of principals (users or groups) allowed by the rule | - | - | -| acls.deny | No | List of principals (users or groups) denied by the rule | - | - | -| acls.allow_hosts | No | List of hosts for which the operation is allowed | - | - | -| acls.deny_hosts | No | List of hosts for which the operation is denied | - | - | - -### List of possible patterns +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | — | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | — | +| `acls` | Yes | Set of ACLs to create | — | — | +| `acls.ops` | Yes | List of operations to which the rule applies | [List of possible operations](#list-of-possible-operations) | — | +| `acls.pattern` | Yes | Pattern type | [List of possible patterns](#list-of-possible-patterns) | — | +| `acls.topics` | No | List of topic names to which the rule applies | — | — | +| `acls.groups` | No | List of group names to which the rule applies | — | — | +| `acls.transactional_ids` | No | List of transaction IDs to which the rule applies | — | — | +| `acls.tokens` | No | List of tokens to which the rule applies | — | — | +| `acls.allow` | No | List of principals (users or groups) allowed by the rule | — | — | +| `acls.deny` | No | List of principals (users or groups) denied by the rule | — | — | +| `acls.allow_hosts` | No | List of hosts for which the operation is allowed | — | — | +| `acls.deny_hosts` | No | List of hosts for which the operation is denied | — | — | + +## List of possible patterns + +The following pattern types are supported: * ANY. * MATCH. * LITERAL. * PREFIXED. -### List of possible operations +## List of possible operations For more information, see [the Kafka documentation](https://kafka.apache.org). @@ -104,6 +108,4 @@ TransactionalID: * DESCRIBE. * WRITE. -Tokens: - -* DESCRIBE. +Tokens: DESCRIBE. diff --git a/content/documentation/admin/actions/kafka/createkafkaacls.ru.md b/content/documentation/admin/actions/kafka/createkafkaacls.ru.md index 4ff15c15..3178261c 100644 --- a/content/documentation/admin/actions/kafka/createkafkaacls.ru.md +++ b/content/documentation/admin/actions/kafka/createkafkaacls.ru.md @@ -4,15 +4,15 @@ weight: 50 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} CreateKafkaACLs — создаёт набор ACL в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -50,32 +50,36 @@ acls: pattern: LITERAL ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | ------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------ | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | - | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | - | -| acls | Да | Набор ACL, которые необходимо создать | - | - | -| acls.ops | Да | Список операций, для которых будет создано правило | [Список возможных операций](#список-возможных-операций) | - | -| acls.pattern | Да | Тип шаблона | [Список возможных шаблонов](#список-возможных-шаблонов) | - | -| acls.topics | Нет | Список из названий топиков, для которых применяется правило | - | - | -| acls.groups | Нет | Список из названий групп, для которых применяется правило | - | - | -| acls.transactional_ids | Нет | Список из ID транзакций, для которых применяется правило | - | - | -| acls.tokens | Нет | Список токенов, для которых применяется правило | - | - | -| acls.allow | Нет | Список принципалов (user, group), для которых разрешается правило | - | - | -| acls.deny | Нет | Список принципалов (user, group), для которых запрещается правило | - | - | -| acls.allow_hosts | Нет | Список хостов, для которых разрешается операция | - | - | -| acls.deny_hosts | Нет | Список хостов, для которых запрещается операция | - | - | - -### Список возможных шаблонов +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | — | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | — | +| `acls` | Да | Набор ACL, которые необходимо создать | — | — | +| `acls.ops` | Да | Список операций, для которых будет создано правило | [Список возможных операций](#список-возможных-операций) | — | +| `acls.pattern` | Да | Тип шаблона | [Список возможных шаблонов](#список-возможных-шаблонов) | — | +| `acls.topics` | Нет | Список из названий топиков, для которых применяется правило | — | — | +| `acls.groups` | Нет | Список из названий групп, для которых применяется правило | — | — | +| `acls.transactional_ids` | Нет | Список из ID транзакций, для которых применяется правило | — | — | +| `acls.tokens` | Нет | Список токенов, для которых применяется правило | — | — | +| `acls.allow` | Нет | Список принципалов (user, group), для которых разрешается правило | — | — | +| `acls.deny` | Нет | Список принципалов (user, group), для которых запрещается правило | — | — | +| `acls.allow_hosts` | Нет | Список хостов, для которых разрешается операция | — | — | +| `acls.deny_hosts` | Нет | Список хостов, для которых запрещается операция | — | — | + +## Список возможных шаблонов + +Поддерживаются следующие типы шаблонов: * ANY. * MATCH. * LITERAL. * PREFIXED. -### Список возможных операций +## Список возможных операций Подробнее — [в документации Kafka](https://kafka.apache.org). @@ -104,6 +108,4 @@ TransactionalID: * DESCRIBE. * WRITE. -Tokens: - -* DESCRIBE. +Tokens: DESCRIBE. diff --git a/content/documentation/admin/actions/kafka/createkafkatopics.md b/content/documentation/admin/actions/kafka/createkafkatopics.md index 28cb2272..fcbd8e89 100644 --- a/content/documentation/admin/actions/kafka/createkafkatopics.md +++ b/content/documentation/admin/actions/kafka/createkafkatopics.md @@ -4,15 +4,15 @@ weight: 10 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} CreateKafkaTopics — creates new topics in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -25,13 +25,15 @@ topics: - example_2 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | -------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| partitions | Yes | Number of partitions into which each topic will be divided | - | -| replication_factor | Yes | Number of copies (replicas) of each topic partition to place on different brokers | - | -| configs | Yes | Key-value configuration for the topics to create | Values are listed [in the Kafka documentation](https://kafka.apache.org/documentation/#topicconfigs) | -| topics | Yes | List of topic names to create | - | +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `partitions` | Yes | Number of partitions into which each topic will be divided | — | +| `replication_factor` | Yes | Number of copies (replicas) of each topic partition to place on different brokers | — | +| `configs` | Yes | Key-value configuration for the topics to create | Values are listed [in the Kafka documentation](https://kafka.apache.org/documentation/#topicconfigs) | +| `topics` | Yes | List of topic names to create | — | diff --git a/content/documentation/admin/actions/kafka/createkafkatopics.ru.md b/content/documentation/admin/actions/kafka/createkafkatopics.ru.md index 9f7f7a14..63907352 100644 --- a/content/documentation/admin/actions/kafka/createkafkatopics.ru.md +++ b/content/documentation/admin/actions/kafka/createkafkatopics.ru.md @@ -4,15 +4,15 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} CreateKafkaTopics — создаёт новые топики в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -25,13 +25,15 @@ topics: - example_2 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | ------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| partitions | Да | Количество разделов (партиций), на которые будет разделён топик | - | -| replication_factor | Да | Количество копий (реплик) каждой партиции топика, которые необходимо разместить на разных брокерах | - | -| configs | Да | Конфигурация в формате ключ-значение для создаваемых топиков | Значения приведены [в документации Kafka](https://kafka.apache.org/documentation/#topicconfigs) | -| topics | Да | Список названий топиков, которые необходимо создать | - | +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `partitions` | Да | Количество разделов (партиций), на которые будет разделён топик | — | +| `replication_factor` | Да | Количество копий (реплик) каждой партиции топика, которые необходимо разместить на разных брокерах | — | +| `configs` | Да | Конфигурация в формате ключ-значение для создаваемых топиков | Значения приведены [в документации Kafka](https://kafka.apache.org/documentation/#topicconfigs) | +| `topics` | Да | Список названий топиков, которые необходимо создать | — | diff --git a/content/documentation/admin/actions/kafka/createkafkausers.md b/content/documentation/admin/actions/kafka/createkafkausers.md index 4c350fbe..9c5821f6 100644 --- a/content/documentation/admin/actions/kafka/createkafkausers.md +++ b/content/documentation/admin/actions/kafka/createkafkausers.md @@ -4,15 +4,15 @@ weight: 30 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} CreateKafkaUsers — creates new SASL/SCRAM users in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -28,14 +28,16 @@ users: iterations: 4096 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| users | Yes | Set of users to create | - | -| users.user | Yes | Username to create | - | -| users.password | Yes | Password for the user | - | -| users.mechanism | Yes | Authentication mechanism for the user | SCRAM-SHA-256, SCRAM-SHA-512 | -| users.iterations | Yes | Number of iterations used to hash the password | From 4096 to 16384 | +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `users` | Yes | Set of users to create | — | +| `users.user` | Yes | Username to create | — | +| `users.password` | Yes | Password for the user | — | +| `users.mechanism` | Yes | Authentication mechanism for the user | SCRAM-SHA-256, SCRAM-SHA-512 | +| `users.iterations` | Yes | Number of iterations used to hash the password | From 4096 to 16384 | diff --git a/content/documentation/admin/actions/kafka/createkafkausers.ru.md b/content/documentation/admin/actions/kafka/createkafkausers.ru.md index bfa4bc35..d4355e7e 100644 --- a/content/documentation/admin/actions/kafka/createkafkausers.ru.md +++ b/content/documentation/admin/actions/kafka/createkafkausers.ru.md @@ -4,15 +4,15 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} CreateKafkaUsers — создаёт новых пользователей SASL/SCRAM в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -28,14 +28,16 @@ users: iterations: 4096 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | ------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| users | Да | Набор пользователей, которых необходимо создать | - | -| users.user | Да | Имя создаваемого пользователя | - | -| users.password | Да | Пароль создаваемого пользователя | - | -| users.mechanism | Да | Механизм аутентификации создаваемого пользователя | SCRAM-SHA-256, SCRAM-SHA-512 | -| users.iterations | Да | Количество итераций, которые будут применяться для хеширования пароля | От 4096 до 16384 | +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `users` | Да | Набор пользователей, которых необходимо создать | — | +| `users.user` | Да | Имя создаваемого пользователя | — | +| `users.password` | Да | Пароль создаваемого пользователя | — | +| `users.mechanism` | Да | Механизм аутентификации создаваемого пользователя | SCRAM-SHA-256, SCRAM-SHA-512 | +| `users.iterations` | Да | Количество итераций, которые будут применяться для хеширования пароля | От 4096 до 16384 | diff --git a/content/documentation/admin/actions/kafka/deletekafkaacls.md b/content/documentation/admin/actions/kafka/deletekafkaacls.md index 4030fcfe..8e3357b3 100644 --- a/content/documentation/admin/actions/kafka/deletekafkaacls.md +++ b/content/documentation/admin/actions/kafka/deletekafkaacls.md @@ -4,15 +4,15 @@ weight: 60 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} DeleteKafkaACLs — deletes a set of ACLs in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -59,41 +59,45 @@ acls: pattern: ANY ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | Default value | | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------ | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | - | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | - | -| acls | Yes | Set of ACLs to delete | - | - | -| acls.ops | Yes | List of operations to which the rule to delete applies | [List of possible operations](#list-of-possible-operations) | - | -| acls.pattern | Yes | Pattern type | [List of possible patterns](#list-of-possible-patterns) | - | -| acls.any_resource | No | All resources | - | false | -| acls.topics | No | List of topic names to which the rule applies | - | - | -| acls.any_topic | No | All topics | - | false | -| acls.groups | No | List of group names to which the rule applies | - | - | -| acls.any_group | No | All groups | - | false | -| acls.transactional_ids | No | List of transaction IDs to which the rule applies | - | - | -| acls.any_transactional_id | No | Any transaction | - | false | -| acls.tokens | No | List of tokens to which the rule applies | - | - | -| acls.any_token | No | All tokens | - | false | -| acls.allow | No | List of principals (users or groups) allowed by the rule | - | - | -| acls.any_allow | No | Any principal (user or group) | - | false | -| acls.allow_hosts | No | List of hosts for which the operation is allowed | - | - | -| acls.any_allow_hosts | No | Any host from which the operation is allowed | - | false | -| acls.deny | No | List of principals (users or groups) denied by the rule | - | - | -| acls.any_deny | No | Any principal (user or group) | - | false | -| acls.deny_hosts | No | List of hosts from which the operation is denied | - | - | -| acls.any_deny_hosts | No | Any host from which the operation is denied | - | false | - -### List of possible patterns +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | — | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | — | +| `acls` | Yes | Set of ACLs to delete | — | — | +| `acls.ops` | Yes | List of operations to which the rule to delete applies | [List of possible operations](#list-of-possible-operations) | — | +| `acls.pattern` | Yes | Pattern type | [List of possible patterns](#list-of-possible-patterns) | — | +| `acls.any_resource` | No | All resources | — | `false` | +| `acls.topics` | No | List of topic names to which the rule applies | — | — | +| `acls.any_topic` | No | All topics | — | `false` | +| `acls.groups` | No | List of group names to which the rule applies | — | — | +| `acls.any_group` | No | All groups | — | `false` | +| `acls.transactional_ids` | No | List of transaction IDs to which the rule applies | — | — | +| `acls.any_transactional_id` | No | Any transaction | — | `false` | +| `acls.tokens` | No | List of tokens to which the rule applies | — | — | +| `acls.any_token` | No | All tokens | — | `false` | +| `acls.allow` | No | List of principals (users or groups) allowed by the rule | — | — | +| `acls.any_allow` | No | Any principal (user or group) | — | `false` | +| `acls.allow_hosts` | No | List of hosts for which the operation is allowed | — | — | +| `acls.any_allow_hosts` | No | Any host from which the operation is allowed | — | `false` | +| `acls.deny` | No | List of principals (users or groups) denied by the rule | — | — | +| `acls.any_deny` | No | Any principal (user or group) | — | `false` | +| `acls.deny_hosts` | No | List of hosts from which the operation is denied | — | — | +| `acls.any_deny_hosts` | No | Any host from which the operation is denied | — | `false` | + +## List of possible patterns + +The following pattern types are supported: * ANY. * MATCH. * LITERAL. * PREFIXED. -### List of possible operations +## List of possible operations For a detailed description, see [the Kafka documentation](https://kafka.apache.org/39/documentation/#operations_resources_and_protocols). @@ -122,6 +126,4 @@ TransactionalID: * DESCRIBE. * WRITE. -Token: - -* DESCRIBE. +Token: DESCRIBE. diff --git a/content/documentation/admin/actions/kafka/deletekafkaacls.ru.md b/content/documentation/admin/actions/kafka/deletekafkaacls.ru.md index b20adb08..23d2edf6 100644 --- a/content/documentation/admin/actions/kafka/deletekafkaacls.ru.md +++ b/content/documentation/admin/actions/kafka/deletekafkaacls.ru.md @@ -4,15 +4,15 @@ weight: 60 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} DeleteKafkaACLs — удаляет набор ACL в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -59,41 +59,45 @@ acls: pattern: ANY ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | --------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------ | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | - | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | - | -| acls | Да | Набор ACL, которые необходимо удалить | - | - | -| acls.ops | Да | Список операций, для которых будет удалено правило | [Список возможных операций](#список-возможных-операций) | - | -| acls.pattern | Да | Тип шаблона | [Список возможных шаблонов](#список-возможных-шаблонов) | - | -| acls.any_resource | Нет | Все ресурсы | - | false | -| acls.topics | Нет | Список из названий топиков, для которых будет применяться правило | - | - | -| acls.any_topic | Нет | Все топики | - | false | -| acls.groups | Нет | Список из названий групп, для которых будет применяться правило | - | - | -| acls.any_group | Нет | Все топики | - | false | -| acls.transactional_ids | Нет | Список из ID транзакций, для которых будет применяться правило | - | - | -| acls.any_transactional_id | Нет | Любая транзакция | - | false | -| acls.tokens | Нет | Список токенов, для которых будет применяться правило | - | - | -| acls.any_token | Нет | Все токены | - | false | -| acls.allow | Нет | Список принципалов (user, group), для которых разрешить правило | - | - | -| acls.any_allow | Нет | Любой принципал (user, group) | - | false | -| acls.allow_hosts | Нет | Список хостов, для которых разрешить операцию | - | - | -| acls.any_allow_hosts | Нет | Любой хост, с которого разрешено проводить операцию | - | false | -| acls.deny | Нет | Список принципалов (user, group), для которых будет запрещено правило | - | - | -| acls.any_deny | Нет | Любой принципал (user, group) | - | false | -| acls.deny_hosts | Нет | Список хостов, для которых будет запрещено операцию | - | - | -| acls.any_deny_hosts | Нет | Любой хост, с которого запрещено проводить операцию | - | false | - -### Список возможных шаблонов +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | — | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | — | +| `acls` | Да | Набор ACL, которые необходимо удалить | — | — | +| `acls.ops` | Да | Список операций, для которых будет удалено правило | [Список возможных операций](#список-возможных-операций) | — | +| `acls.pattern` | Да | Тип шаблона | [Список возможных шаблонов](#список-возможных-шаблонов) | — | +| `acls.any_resource` | Нет | Все ресурсы | — | `false` | +| `acls.topics` | Нет | Список из названий топиков, для которых будет применяться правило | — | — | +| `acls.any_topic` | Нет | Все топики | — | `false` | +| `acls.groups` | Нет | Список из названий групп, для которых будет применяться правило | — | — | +| `acls.any_group` | Нет | Все топики | — | `false` | +| `acls.transactional_ids` | Нет | Список из ID транзакций, для которых будет применяться правило | — | — | +| `acls.any_transactional_id` | Нет | Любая транзакция | — | `false` | +| `acls.tokens` | Нет | Список токенов, для которых будет применяться правило | — | — | +| `acls.any_token` | Нет | Все токены | — | `false` | +| `acls.allow` | Нет | Список принципалов (user, group), для которых разрешить правило | — | — | +| `acls.any_allow` | Нет | Любой принципал (user, group) | — | `false` | +| `acls.allow_hosts` | Нет | Список хостов, для которых разрешить операцию | — | — | +| `acls.any_allow_hosts` | Нет | Любой хост, с которого разрешено проводить операцию | — | `false` | +| `acls.deny` | Нет | Список принципалов (user, group), для которых будет запрещено правило | — | — | +| `acls.any_deny` | Нет | Любой принципал (user, group) | — | `false` | +| `acls.deny_hosts` | Нет | Список хостов, для которых будет запрещено операцию | — | — | +| `acls.any_deny_hosts` | Нет | Любой хост, с которого запрещено проводить операцию | — | `false` | + +## Список возможных шаблонов + +Поддерживаются следующие типы шаблонов: * ANY. * MATCH. * LITERAL. * PREFIXED. -### Список возможных операций +## Список возможных операций Подробное описание — [в документации Kafka](https://kafka.apache.org/39/documentation/#operations_resources_and_protocols). @@ -122,6 +126,4 @@ TransactionalID: * DESCRIBE. * WRITE. -Token: - -* DESCRIBE. +Token: DESCRIBE. diff --git a/content/documentation/admin/actions/kafka/deletekafkatopics.md b/content/documentation/admin/actions/kafka/deletekafkatopics.md index e077a084..6970cd79 100644 --- a/content/documentation/admin/actions/kafka/deletekafkatopics.md +++ b/content/documentation/admin/actions/kafka/deletekafkatopics.md @@ -4,15 +4,15 @@ weight: 20 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} DeleteKafkaTopics — deletes existing topics in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -22,10 +22,12 @@ topics: - example_2 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| topics | Yes | List of topic names to delete | - | +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `topics` | Yes | List of topic names to delete | — | diff --git a/content/documentation/admin/actions/kafka/deletekafkatopics.ru.md b/content/documentation/admin/actions/kafka/deletekafkatopics.ru.md index aa3f1778..1c3f8972 100644 --- a/content/documentation/admin/actions/kafka/deletekafkatopics.ru.md +++ b/content/documentation/admin/actions/kafka/deletekafkatopics.ru.md @@ -4,15 +4,15 @@ weight: 20 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} DeleteKafkaTopics — удаляет существующие топики в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -22,10 +22,12 @@ topics: - example_2 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| topics | Да | Список названий топиков, которые необходимо удалить | - | +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `topics` | Да | Список названий топиков, которые необходимо удалить | — | diff --git a/content/documentation/admin/actions/kafka/deletekafkausers.md b/content/documentation/admin/actions/kafka/deletekafkausers.md index 9c183c0f..7965485a 100644 --- a/content/documentation/admin/actions/kafka/deletekafkausers.md +++ b/content/documentation/admin/actions/kafka/deletekafkausers.md @@ -4,15 +4,15 @@ weight: 40 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `user` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `user` (the username under which the action runs) +and `password` (the password for that user). {{< /alert >}} DeleteKafkaUsers — deletes existing SASL/SCRAM users in Kafka. -### Request example +## Request example + +Example of the action request body: ```yaml securityProtocol: SASL_PLAINTEXT @@ -24,12 +24,14 @@ users: mechanism: SCRAM-SHA-256 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| users | Yes | Set of users to delete | - | -| users.user | Yes | Username to delete | - | -| users.mechanism | Yes | Authentication mechanism associated with the user to delete | SCRAM-SHA-256, SCRAM-SHA-512 | +| `securityProtocol` | Yes | Protocol for connecting to Kafka. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | No | SASL authentication mechanism. Required when using the SASL_PLAINTEXT or SASL_SSL protocol. For more information, see [the Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `users` | Yes | Set of users to delete | — | +| `users.user` | Yes | Username to delete | — | +| `users.mechanism` | Yes | Authentication mechanism associated with the user to delete | SCRAM-SHA-256, SCRAM-SHA-512 | diff --git a/content/documentation/admin/actions/kafka/deletekafkausers.ru.md b/content/documentation/admin/actions/kafka/deletekafkausers.ru.md index 00844acc..28c3b5d4 100644 --- a/content/documentation/admin/actions/kafka/deletekafkausers.ru.md +++ b/content/documentation/admin/actions/kafka/deletekafkausers.ru.md @@ -4,15 +4,15 @@ weight: 40 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `user` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `user` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). {{< /alert >}} DeleteKafkaUsers — удаляет существующих пользователей SASL/SCRAM в Kafka. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml securityProtocol: SASL_PLAINTEXT @@ -24,12 +24,14 @@ users: mechanism: SCRAM-SHA-256 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | ------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| securityProtocol | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | -| saslMechanism | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -| users | Да | Набор пользователей, которых необходимо удалить | - | -| users.user | Да | Имя удаляемого пользователя | - | -| users.mechanism | Да | Механизм аутентификации удаляемого пользователя | SCRAM-SHA-256, SCRAM-SHA-512 | +| `securityProtocol` | Да | Протокол для подключения к Kafka. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| `saslMechanism` | Нет | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL. Подробнее — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| `users` | Да | Набор пользователей, которых необходимо удалить | — | +| `users.user` | Да | Имя удаляемого пользователя | — | +| `users.mechanism` | Да | Механизм аутентификации удаляемого пользователя | SCRAM-SHA-256, SCRAM-SHA-512 | diff --git a/content/documentation/admin/actions/keycloak/createkeycloakclient.md b/content/documentation/admin/actions/keycloak/createkeycloakclient.md index 6e566fa4..1e008113 100644 --- a/content/documentation/admin/actions/keycloak/createkeycloakclient.md +++ b/content/documentation/admin/actions/keycloak/createkeycloakclient.md @@ -4,10 +4,8 @@ weight: 10 --- {{< alert level="info" >}} -This action requires the following credentials: - -- `username` — the username under which the action runs. -- `password` — the password for that user. +Running this action requires credentials: `username` (the username under which the action runs) +and `password` (the password for that user). The portal obtains a token through the `admin-cli` client in the realm specified in `realm`, the same realm in which the client is created. The user must exist in that realm and have permission to create clients in it. @@ -15,7 +13,9 @@ The user must exist in that realm and have permission to create clients in it. CreateKeycloakClient — creates a new client in Keycloak. -### Request example +## Request example + +Example of the action request body: ```yaml realm: master @@ -35,9 +35,11 @@ config: - offline_access ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| realm | Yes | Keycloak realm in which to create the client | - | -| config | Yes | Parameters for the client to create, as defined in the [Keycloak ClientRepresentation specification](https://www.keycloak.org/docs-api/latest/rest-api/index.html#ClientRepresentation) | - | +| `realm` | Yes | Keycloak realm in which to create the client | — | +| `config` | Yes | Parameters for the client to create, as defined in the [Keycloak ClientRepresentation specification](https://www.keycloak.org/docs-api/latest/rest-api/index.html#ClientRepresentation) | — | diff --git a/content/documentation/admin/actions/keycloak/createkeycloakclient.ru.md b/content/documentation/admin/actions/keycloak/createkeycloakclient.ru.md index 77c0e46b..fe63a3b0 100644 --- a/content/documentation/admin/actions/keycloak/createkeycloakclient.ru.md +++ b/content/documentation/admin/actions/keycloak/createkeycloakclient.ru.md @@ -4,10 +4,8 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действия необходимы учётные данные: - -- `username` — имя пользователя, от которого будет запускаться выполнение действия; -- `password` — пароль пользователя, от имени которого будет запускаться выполнение действия. +Для выполнения действия необходимы учётные данные: `username` (имя пользователя, от имени которого выполняется действие) +и `password` (пароль этого пользователя). Портал получает токен через клиент `admin-cli` в realm, указанном в `realm`, — в том же realm, где создаётся клиент. Пользователь должен существовать в этом realm и иметь права на создание в нём клиентов. @@ -15,7 +13,9 @@ weight: 10 CreateKeycloakClient — создаёт нового клиента в Keycloak. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml realm: master @@ -35,9 +35,11 @@ config: - offline_access ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | ---------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| realm | Да | Realm в Keycloak, где требуется создать клиента | - | -| config | Да | Параметры создаваемого клиента в соответствии со [спецификацией ClientRepresentation Keycloak](https://www.keycloak.org/docs-api/latest/rest-api/index.html#ClientRepresentation) | - | +| `realm` | Да | Realm в Keycloak, где требуется создать клиента | — | +| `config` | Да | Параметры создаваемого клиента в соответствии со [спецификацией ClientRepresentation Keycloak](https://www.keycloak.org/docs-api/latest/rest-api/index.html#ClientRepresentation) | — | diff --git a/content/documentation/admin/actions/kubernetes/createkubernetesresource.md b/content/documentation/admin/actions/kubernetes/createkubernetesresource.md index 93022481..4772dfc7 100644 --- a/content/documentation/admin/actions/kubernetes/createkubernetesresource.md +++ b/content/documentation/admin/actions/kubernetes/createkubernetesresource.md @@ -9,7 +9,9 @@ This action requires a Kubernetes service account token. CreateKubernetesResource — creates one or more resources in a Kubernetes cluster or updates existing resources. -### Request example +## Request example + +Example of the action request body: ```yaml manifests: @@ -23,20 +25,25 @@ manifests: name: example2 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------------- | -| manifests | Yes | Kubernetes manifests to apply | +| `manifests` | Yes | Kubernetes manifests to apply | -### Response +## Response -The action returns an object with one key per applied manifest. The value of each key is the created or updated object as returned by the Kubernetes API. +The action returns an object with one key per applied manifest. +The value of each key is the created or updated object as returned by the Kubernetes API. The key has the form `__` in lowercase, with hyphens (`-`) replaced by underscores (`_`): - ``: Kind of the object, for example `deployment`. -- ``: Namespace of the object. If a namespaced object has no `metadata.namespace`, the action creates it in the `default` namespace. For cluster-wide objects, such as Namespace, this part is empty. +- ``: Namespace of the object. + If a namespaced object has no `metadata.namespace`, the action creates it in the `default` namespace. + For cluster-wide objects, such as Namespace, this part is empty. - ``: Name of the object. For the request example above, the response contains the `namespace__example1` and `namespace__example2` keys. diff --git a/content/documentation/admin/actions/kubernetes/createkubernetesresource.ru.md b/content/documentation/admin/actions/kubernetes/createkubernetesresource.ru.md index 04599f62..5c940ab4 100644 --- a/content/documentation/admin/actions/kubernetes/createkubernetesresource.ru.md +++ b/content/documentation/admin/actions/kubernetes/createkubernetesresource.ru.md @@ -4,12 +4,14 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена сервисного аккаунта Kubernetes. +Для выполнения действий требуется токен сервисного аккаунта Kubernetes. {{< /alert >}} CreateKubernetesResource — создаёт новый ресурс или ресурсы в кластере Kubernetes или обновляет существующие. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml manifests: @@ -23,20 +25,25 @@ manifests: name: example2 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ---------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------- | -| manifests | Да | Манифесты Kubernetes, которые будут применены | +| `manifests` | Да | Манифесты Kubernetes, которые будут применены | -### Ответ +## Ответ -Действие возвращает объект, в котором каждому применённому манифесту соответствует один ключ. Значение ключа — созданный или обновлённый объект в том виде, в котором его вернул API Kubernetes. +Действие возвращает объект, в котором каждому применённому манифесту соответствует один ключ. +Значение ключа — созданный или обновлённый объект в том виде, в котором его вернул API Kubernetes. Ключ имеет вид `__` в нижнем регистре, дефисы (`-`) заменяются на подчёркивания (`_`): - `` — тип (kind) объекта, например `deployment`; -- `` — неймспейс объекта. Если у объекта, относящегося к неймспейсу, не задан `metadata.namespace`, действие создаёт его в неймспейсе `default`. Для объектов уровня кластера, например Namespace, эта часть пустая; +- `` — неймспейс объекта. + Если у объекта, относящегося к неймспейсу, не задан `metadata.namespace`, действие создаёт его в неймспейсе `default`. + Для объектов уровня кластера, например Namespace, эта часть пустая; - `` — имя объекта. Для примера запроса выше ответ содержит ключи `namespace__example1` и `namespace__example2`. diff --git a/content/documentation/admin/actions/kubernetes/deletekubernetesresource.md b/content/documentation/admin/actions/kubernetes/deletekubernetesresource.md index a8126ca5..fff870d9 100644 --- a/content/documentation/admin/actions/kubernetes/deletekubernetesresource.md +++ b/content/documentation/admin/actions/kubernetes/deletekubernetesresource.md @@ -9,7 +9,9 @@ This action requires a Kubernetes service account token. DeleteKubernetesResource — deletes an existing resource in a Kubernetes cluster. -### Request example +## Request example + +Example of the action request body: ```yaml group: apps @@ -20,17 +22,20 @@ namespace: example ignore_not_found: true ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | --------------------------- | ----------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| group | Yes | API group of the resource. Specifies the API group to which the object being deleted belongs | [Determining the required Group and Version](getkubernetesresource/#determining-the-required-group-and-version) | -| version | Yes | API version of the resource | [Determining the required Group and Version](getkubernetesresource/#determining-the-required-group-and-version) | -| resource_type | Yes | Type of resource to delete | pods, services, deployments, statefulsets, daemonsets, replicasets, jobs, cronjobs, nodes, namespaces, configmaps, secrets, persistentvolumes, persistentvolumeclaims, limitranges, resourcequotas, horizontalpodautoscalers, ingresses, networkpolicies, serviceaccounts, roles, clusterroles, rolebindings, clusterrolebindings, podsecuritypolicies, storageclasses, volumeattachments, events, endpoints, customresourcedefinitions | -| resource_name | Yes | Name of the resource to delete | - | -| namespace | Yes | Namespace containing the resource | - | -| ignore_not_found | No | If `true`, deleting an object that does not exist in the cluster succeeds. Defaults to `false`: deleting a missing object fails | `true`, `false` | +| `group` | Yes | API group of the resource. Specifies the API group to which the object being deleted belongs | [Determining the required group and version](getkubernetesresource/#determining-the-required-group-and-version) | +| `version` | Yes | API version of the resource | [Determining the required group and version](getkubernetesresource/#determining-the-required-group-and-version) | +| `resource_type` | Yes | Type of resource to delete | `pods`, `services`, `deployments`, `statefulsets`, `daemonsets`, `replicasets`, `jobs`, `cronjobs`, `nodes`, `namespaces`, `configmaps`, `secrets`, `persistentvolumes`, `persistentvolumeclaims`, `limitranges`, `resourcequotas`, `horizontalpodautoscalers`, `ingresses`, `networkpolicies`, `serviceaccounts`, `roles`, `clusterroles`, `rolebindings`, `clusterrolebindings`, `podsecuritypolicies`, `storageclasses`, `volumeattachments`, `events`, `endpoints`, `customresourcedefinitions` | +| `resource_name` | Yes | Name of the resource to delete | — | +| `namespace` | Yes | Namespace containing the resource | — | +| `ignore_not_found` | No | If `true`, deleting an object that does not exist in the cluster succeeds. Defaults to `false`: deleting a missing object fails | `true`, `false` | -### Note +## Behavior details -The `ignore_not_found` parameter does not suppress other Kubernetes API errors. Use it in deletion processes that can run more than once. +The `ignore_not_found` parameter does not suppress other Kubernetes API errors. +Use it in deletion processes that can run more than once. diff --git a/content/documentation/admin/actions/kubernetes/deletekubernetesresource.ru.md b/content/documentation/admin/actions/kubernetes/deletekubernetesresource.ru.md index facd6619..93fb9895 100644 --- a/content/documentation/admin/actions/kubernetes/deletekubernetesresource.ru.md +++ b/content/documentation/admin/actions/kubernetes/deletekubernetesresource.ru.md @@ -4,12 +4,14 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена сервисного аккаунта Kubernetes. +Для выполнения действий требуется токен сервисного аккаунта Kubernetes. {{< /alert >}} DeleteKubernetesResource — удаляет существующий ресурс в кластере Kubernetes. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml group: apps @@ -20,17 +22,20 @@ namespace: example ignore_not_found: true ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | --------------------------- | ----------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| group | Да | API-группа ресурса. Указывает, к какой группе API относится удаляемый объект | [Определение требуемых Group и Version](getkubernetesresource/#определение-требуемых-group-и-version) | -| version | Да | Версия API ресурса | [Определение требуемых Group и Version](getkubernetesresource/#определение-требуемых-group-и-version) | -| resource_type | Да | Тип удаляемого ресурса | pods, services, deployments, statefulsets, daemonsets, replicasets, jobs, cronjobs, nodes, namespaces, configmaps, secrets, persistentvolumes, persistentvolumeclaims, limitranges, resourcequotas, horizontalpodautoscalers, ingresses, networkpolicies, serviceaccounts, roles, clusterroles, rolebindings, clusterrolebindings, podsecuritypolicies, storageclasses, volumeattachments, events, endpoints, customresourcedefinitions | -| resource_name | Да | Название конкретного ресурса, который необходимо удалить | - | -| namespace | Да | Неймспейс, в котором находится ресурс | - | -| ignore_not_found | Нет | При значении `true` удаление объекта, которого нет в кластере, завершается успешно. По умолчанию `false`: удаление отсутствующего объекта завершается ошибкой | `true`, `false` | +| `group` | Да | API-группа ресурса. Указывает, к какой группе API относится удаляемый объект | [Определение требуемых Group и Version](getkubernetesresource/#определение-требуемых-group-и-version) | +| `version` | Да | Версия API ресурса | [Определение требуемых Group и Version](getkubernetesresource/#определение-требуемых-group-и-version) | +| `resource_type` | Да | Тип удаляемого ресурса | `pods`, `services`, `deployments`, `statefulsets`, `daemonsets`, `replicasets`, `jobs`, `cronjobs`, `nodes`, `namespaces`, `configmaps`, `secrets`, `persistentvolumes`, `persistentvolumeclaims`, `limitranges`, `resourcequotas`, `horizontalpodautoscalers`, `ingresses`, `networkpolicies`, `serviceaccounts`, `roles`, `clusterroles`, `rolebindings`, `clusterrolebindings`, `podsecuritypolicies`, `storageclasses`, `volumeattachments`, `events`, `endpoints`, `customresourcedefinitions` | +| `resource_name` | Да | Название конкретного ресурса, который необходимо удалить | — | +| `namespace` | Да | Неймспейс, в котором находится ресурс | — | +| `ignore_not_found` | Нет | При значении `true` удаление объекта, которого нет в кластере, завершается успешно. По умолчанию `false`: удаление отсутствующего объекта завершается ошибкой | `true`, `false` | -### Примечание +## Особенности работы -Параметр `ignore_not_found` не подавляет другие ошибки API Kubernetes. Используйте его в процессах удаления, которые могут запускаться повторно. +Параметр `ignore_not_found` не подавляет другие ошибки API Kubernetes. +Используйте его в процессах удаления, которые могут запускаться повторно. diff --git a/content/documentation/admin/actions/kubernetes/getkubernetesresource.md b/content/documentation/admin/actions/kubernetes/getkubernetesresource.md index ccb5429f..7aad7749 100644 --- a/content/documentation/admin/actions/kubernetes/getkubernetesresource.md +++ b/content/documentation/admin/actions/kubernetes/getkubernetesresource.md @@ -9,7 +9,9 @@ This action requires a Kubernetes service account token. GetKubernetesResource — retrieves a resource from a Kubernetes cluster. -### Request example +## Request example + +Example of the action request body: ```yaml group: managed-services.deckhouse.io @@ -20,27 +22,31 @@ namespace: default ignore_not_found: true ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | | --------------------------- | -------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | -| group | Yes | API group of the resource. Specifies the API group to which the requested object belongs | [Determining the required Group and Version](#determining-the-required-group-and-version) | -| version | Yes | API version of the resource | [Determining the required Group and Version](#determining-the-required-group-and-version) | -| resource_type | Yes | Type of resource to retrieve | - | -| resource_name | Yes | Name of the resource to retrieve | - | -| namespace | Yes | Namespace containing the resource | - | -| ignore_not_found | No | If `true`, a missing object is not treated as an error. Defaults to `false` | `true`, `false` | +| `group` | Yes | API group of the resource. Specifies the API group to which the requested object belongs | [Determining the required group and version](#determining-the-required-group-and-version) | +| `version` | Yes | API version of the resource | [Determining the required group and version](#determining-the-required-group-and-version) | +| `resource_type` | Yes | Type of resource to retrieve | — | +| `resource_name` | Yes | Name of the resource to retrieve | — | +| `namespace` | Yes | Namespace containing the resource | — | +| `ignore_not_found` | No | If `true`, a missing object is not treated as an error. Defaults to `false` | `true`, `false` | -### Response +## Response -On success, the action returns the `found` flag and the object in the `resource` field. If the object is not found and `ignore_not_found` is not enabled, the action fails with an error. With `ignore_not_found: true`, the action succeeds with `found: false` and without the `resource` field. +On success, the action returns the `found` flag and the object in the `resource` field. +If the object is not found and `ignore_not_found` is not enabled, the action fails with an error. +With `ignore_not_found: true`, the action succeeds with `found: false` and without the `resource` field. | Name | Description | | ------------ | --------------------------------------------------- | | `found` | `true` if the object is found | | `resource` | Resource object in Kubernetes format | -### Determining the required Group and Version +## Determining the required group and version Each resource type has its own API group (Group) and version (Version). A complete list of API resources, groups, and versions is available [in the Kubernetes documentation](https://kubernetes.io/docs/reference/kubernetes-api/). @@ -48,7 +54,7 @@ A complete list of API resources, groups, and versions is available [in the Kube If you do not know which API groups and versions are required, you can look up the current values. There are several ways to determine them: -#### Using the `d8 k` utility +### Using the d8 k utility The `d8 k explain` command shows the `apiVersion` for a resource. @@ -72,7 +78,9 @@ FIELDS: ... ``` -#### Using the documentation +### Using the documentation + +To find the API group and version in the Kubernetes documentation, follow these steps: 1. Find the resource you need (for example, Deployment). 1. Find the API group and version in the header. For example, for Deployment: @@ -82,5 +90,5 @@ FIELDS: ``` Here: - * `API Group` is `apps`; - * `Version` is `v1`. + * `API Group` is `apps` + * `Version` is `v1` diff --git a/content/documentation/admin/actions/kubernetes/getkubernetesresource.ru.md b/content/documentation/admin/actions/kubernetes/getkubernetesresource.ru.md index 6fa7ce4b..0db7893c 100644 --- a/content/documentation/admin/actions/kubernetes/getkubernetesresource.ru.md +++ b/content/documentation/admin/actions/kubernetes/getkubernetesresource.ru.md @@ -4,12 +4,14 @@ weight: 20 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена сервисного аккаунта Kubernetes. +Для выполнения действий требуется токен сервисного аккаунта Kubernetes. {{< /alert >}} GetKubernetesResource — получает ресурс из кластера Kubernetes. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml group: managed-services.deckhouse.io @@ -20,27 +22,30 @@ namespace: default ignore_not_found: true ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | | --------------------------- | ---------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -| group | Да | API-группа ресурса. Указывает, к какой группе API относится запрашиваемый объект | [Определение требуемых Group и Version](#определение-требуемых-group-и-version) | -| version | Да | Версия API ресурса | [Определение требуемых Group и Version](#определение-требуемых-group-и-version) | -| resource_type | Да | Тип получаемого ресурса | - | -| resource_name | Да | Название конкретного ресурса, который необходимо получить | - | -| namespace | Да | Неймспейс, в котором находится ресурс | - | -| ignore_not_found | Нет | При значении `true` отсутствие объекта не считается ошибкой. По умолчанию `false` | `true`, `false` | +| `group` | Да | API-группа ресурса. Указывает, к какой группе API относится запрашиваемый объект | [Определение требуемых Group и Version](#определение-требуемых-group-и-version) | +| `version` | Да | Версия API ресурса | [Определение требуемых Group и Version](#определение-требуемых-group-и-version) | +| `resource_type` | Да | Тип получаемого ресурса | — | +| `resource_name` | Да | Название конкретного ресурса, который необходимо получить | — | +| `namespace` | Да | Неймспейс, в котором находится ресурс | — | +| `ignore_not_found` | Нет | При значении `true` отсутствие объекта не считается ошибкой. По умолчанию `false` | `true`, `false` | -### Ответ +## Ответ -При успешном выполнении действие возвращает признак `found` и объект в поле `resource`. Если объект не найден и `ignore_not_found` не включён, действие завершается с ошибкой; при `ignore_not_found: true` действие завершается успешно с `found: false` и без поля `resource`. +При успешном выполнении действие возвращает признак `found` и объект в поле `resource`. +Если объект не найден и `ignore_not_found` не включён, действие завершается с ошибкой; при `ignore_not_found: true` действие завершается успешно с `found: false` и без поля `resource`. | Название | Описание | | ------------ | ----------------------------------------------- | | `found` | `true`, если объект найден | | `resource` | Объект ресурса в формате Kubernetes | -### Определение требуемых Group и Version +## Определение требуемых Group и Version Каждому типу ресурса соответствует своя группа API (Group) и версия (Version). Полный список API-ресурсов с их группами и версиями приведён [в документации Kubernetes](https://kubernetes.io/docs/reference/kubernetes-api/). @@ -48,7 +53,7 @@ ignore_not_found: true Если неизвестно, какие требуются группы API и версии, можно использовать актуальные значения. Существует несколько способов их определить: -#### С помощью утилиты `d8 k` +### С помощью утилиты d8 k Команда `d8 k explain` показывает `apiVersion` для ресурса. @@ -72,7 +77,9 @@ FIELDS: ... ``` -#### С помощью документации +### С помощью документации + +Чтобы найти API Group и версию в документации Kubernetes, выполните следующие действия: 1. Найдите нужный ресурс (например, Deployment). 1. В заголовке указана API Group и версия. Пример для Deployment: diff --git a/content/documentation/admin/actions/nexus/assignnexusprivilege.md b/content/documentation/admin/actions/nexus/assignnexusprivilege.md index c1888d01..bd56f30d 100644 --- a/content/documentation/admin/actions/nexus/assignnexusprivilege.md +++ b/content/documentation/admin/actions/nexus/assignnexusprivilege.md @@ -4,12 +4,16 @@ weight: 40 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} -AssignNexusPrivilege — assigns privileges to an existing role in Nexus Repository Manager 3. The action retrieves the role's current configuration and merges its existing privileges with the new ones. +AssignNexusPrivilege — assigns privileges to an existing role in Nexus Repository Manager 3. +The action retrieves the role's current configuration and merges its existing privileges with the new ones. -### Request example +## Request example + +Example of the action request body: ```yaml roleId: example-role @@ -18,19 +22,25 @@ privileges: - another-privilege ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------------ | ----------------- | ------------------------------------------------------------------------------ | -| roleId | Yes | Identifier of the role to which privileges are assigned | -| privileges | Yes | List of privilege names to assign to the role | +| `roleId` | Yes | Identifier of the role to which privileges are assigned | +| `privileges` | Yes | List of privilege names to assign to the role | + +## How it works -### How it works +The action runs in the following order: 1. Retrieves the role's current configuration from Nexus. 1. Merges the role's existing privileges with the new privileges from the request. 1. Updates the role with the merged list of privileges. -### Note +## Requirements -The role must exist in Nexus before privileges can be assigned. If the role is not found, the action fails with an error. All specified privileges must also exist in Nexus. +The role must exist in Nexus before privileges can be assigned. +If the role is not found, the action fails with an error. +All specified privileges must also exist in Nexus. diff --git a/content/documentation/admin/actions/nexus/assignnexusprivilege.ru.md b/content/documentation/admin/actions/nexus/assignnexusprivilege.ru.md index 943e1fcb..7a2b5bbc 100644 --- a/content/documentation/admin/actions/nexus/assignnexusprivilege.ru.md +++ b/content/documentation/admin/actions/nexus/assignnexusprivilege.ru.md @@ -4,12 +4,16 @@ weight: 40 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} -AssignNexusPrivilege — назначает привилегии существующей роли в Nexus Repository Manager 3. Действие получает текущую конфигурацию роли и объединяет существующие привилегии с новыми. +AssignNexusPrivilege — назначает привилегии существующей роли в Nexus Repository Manager 3. +Действие получает текущую конфигурацию роли и объединяет существующие привилегии с новыми. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml roleId: example-role @@ -18,19 +22,25 @@ privileges: - another-privilege ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------------ | ----------------- | ------------------------------------------------------------------------------ | -| roleId | Да | Идентификатор роли, которой назначаются привилегии | -| privileges | Да | Список названий привилегий, которые необходимо назначить роли | +| `roleId` | Да | Идентификатор роли, которой назначаются привилегии | +| `privileges` | Да | Список названий привилегий, которые необходимо назначить роли | + +## Алгоритм работы -### Алгоритм работы +Действие выполняется в следующем порядке: 1. Получает текущую конфигурацию роли из Nexus. 1. Объединяет существующие привилегии роли с новыми привилегиями из запроса. 1. Обновляет роль с объединённым списком привилегий. -### Примечание +## Требования -Роль должна существовать в Nexus до назначения привилегий. Если роль не найдена, действие завершится с ошибкой. Все указанные привилегии также должны существовать в Nexus. +Роль должна существовать в Nexus до назначения привилегий. +Если роль не найдена, действие завершится с ошибкой. +Все указанные привилегии также должны существовать в Nexus. diff --git a/content/documentation/admin/actions/nexus/assignnexusrole.md b/content/documentation/admin/actions/nexus/assignnexusrole.md index 2426ffb3..ff8e491f 100644 --- a/content/documentation/admin/actions/nexus/assignnexusrole.md +++ b/content/documentation/admin/actions/nexus/assignnexusrole.md @@ -4,12 +4,16 @@ weight: 70 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} -AssignNexusRole — assigns roles to an existing user in Nexus Repository Manager 3. The action retrieves the user's current configuration and merges the user's existing roles with the new ones. +AssignNexusRole — assigns roles to an existing user in Nexus Repository Manager 3. +The action retrieves the user's current configuration and merges the user's existing roles with the new ones. -### Request example +## Request example + +Example of the action request body: ```yaml userId: example-user @@ -18,19 +22,25 @@ roles: - another-role ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | -------- | ----------------- | ----------------------------------------------------------------------- | -| userId | Yes | Identifier of the user to which roles are assigned | -| roles | Yes | List of role identifiers to assign to the user | +| `userId` | Yes | Identifier of the user to which roles are assigned | +| `roles` | Yes | List of role identifiers to assign to the user | + +## How it works -### How it works +The action runs in the following order: 1. Retrieves the user's current configuration from Nexus. 1. Merges the user's existing roles with the new roles from the request. 1. Updates the user with the merged list of roles. -### Note +## Requirements -The user must exist in Nexus before roles can be assigned. If the user is not found, the action fails with an error. All specified roles must also exist in Nexus. +The user must exist in Nexus before roles can be assigned. +If the user is not found, the action fails with an error. +All specified roles must also exist in Nexus. diff --git a/content/documentation/admin/actions/nexus/assignnexusrole.ru.md b/content/documentation/admin/actions/nexus/assignnexusrole.ru.md index 752da61f..96cfeade 100644 --- a/content/documentation/admin/actions/nexus/assignnexusrole.ru.md +++ b/content/documentation/admin/actions/nexus/assignnexusrole.ru.md @@ -4,12 +4,16 @@ weight: 70 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} -AssignNexusRole — назначает роли существующему пользователю в Nexus Repository Manager 3. Действие получает текущую конфигурацию пользователя и объединяет существующие роли с новыми. +AssignNexusRole — назначает роли существующему пользователю в Nexus Repository Manager 3. +Действие получает текущую конфигурацию пользователя и объединяет существующие роли с новыми. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml userId: example-user @@ -18,19 +22,25 @@ roles: - another-role ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | -------- | ----------------- | ----------------------------------------------------------------------- | -| userId | Да | Идентификатор пользователя, которому назначаются роли | -| roles | Да | Список идентификаторов ролей, которые необходимо назначить пользователю | +| `userId` | Да | Идентификатор пользователя, которому назначаются роли | +| `roles` | Да | Список идентификаторов ролей, которые необходимо назначить пользователю | + +## Алгоритм работы -### Алгоритм работы +Действие выполняется в следующем порядке: 1. Получает текущую конфигурацию пользователя из Nexus. 1. Объединяет существующие роли пользователя с новыми ролями из запроса. 1. Обновляет пользователя с объединённым списком ролей. -### Примечание +## Требования -Пользователь должен существовать в Nexus до назначения ролей. Если пользователь не найден, действие завершится с ошибкой. Все указанные роли также должны существовать в Nexus. +Пользователь должен существовать в Nexus до назначения ролей. +Если пользователь не найден, действие завершится с ошибкой. +Все указанные роли также должны существовать в Nexus. diff --git a/content/documentation/admin/actions/nexus/createnexusprivilege.md b/content/documentation/admin/actions/nexus/createnexusprivilege.md index d190dd0c..cf9e4a4a 100644 --- a/content/documentation/admin/actions/nexus/createnexusprivilege.md +++ b/content/documentation/admin/actions/nexus/createnexusprivilege.md @@ -4,12 +4,16 @@ weight: 30 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} -CreateNexusPrivilege — creates a new privilege in Nexus Repository Manager 3. Privileges define access rights to repositories and other Nexus resources. +CreateNexusPrivilege — creates a new privilege in Nexus Repository Manager 3. +Privileges define access rights to repositories and other Nexus resources. -### Request example (repository-view) +## Request example (repository-view) + +Example of the action request body: ```yaml name: example-privilege @@ -22,7 +26,9 @@ format: maven2 repository: maven-releases ``` -### Request example (repository-content-selector) +## Request example (repository-content-selector) + +Example of the action request body: ```yaml name: content-selector-privilege @@ -35,7 +41,9 @@ repository: maven-releases contentSelector: my-content-selector ``` -### Request example (wildcard) +## Request example (wildcard) + +Example of the action request body: ```yaml name: wildcard-privilege @@ -46,21 +54,24 @@ actions: - READ ``` -### Request specification +## Request specification -| Field | Required | Description | +The action request body supports the following parameters: + +| Name | Required | Description | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| name | Yes | Name of the privilege to create. Must be unique within Nexus | -| description | No | Privilege description | -| type | Yes | Privilege type: `repository-view`, `repository-content-selector`, `repository-admin`, `application`, `wildcard` | -| actions | No | List of actions allowed by the privilege (e.g., `READ`, `BROWSE`, `CREATE`, `UPDATE`, `DELETE`) | -| format | No | Repository format (e.g., `maven2`, `docker`, `npm`). Used for the `repository-view`, `repository-content-selector`, `repository-admin` types | -| repository | No | Repository name. Used for the `repository-view`, `repository-content-selector`, `repository-admin` types | -| contentSelector | No | Content selector name. Required for the `repository-content-selector` type. If not specified or invalid, the type is automatically converted to `repository-view` | -| pattern | No | Pattern for the `wildcard` type | -| domain | No | Domain for the `application` type | -| attributes | No | Additional key-value parameters | - -### Note - -For the `repository-content-selector` type, the content selector must exist in Nexus before the privilege is created. If the content selector is not specified or is invalid, the action automatically converts the privilege type to `repository-view`. +| `name` | Yes | Name of the privilege to create. Must be unique within Nexus | +| `description` | No | Privilege description | +| `type` | Yes | Privilege type: `repository-view`, `repository-content-selector`, `repository-admin`, `application`, `wildcard` | +| `actions` | No | List of actions allowed by the privilege (for example, `READ`, `BROWSE`, `CREATE`, `UPDATE`, `DELETE`) | +| `format` | No | Repository format (for example, `maven2`, `docker`, `npm`). Used for the `repository-view`, `repository-content-selector`, `repository-admin` types | +| `repository` | No | Repository name. Used for the `repository-view`, `repository-content-selector`, `repository-admin` types | +| `contentSelector` | No | Content selector name. Required for the `repository-content-selector` type. If not specified or invalid, the type is automatically converted to `repository-view` | +| `pattern` | No | Pattern for the `wildcard` type | +| `domain` | No | Domain for the `application` type | +| `attributes` | No | Additional key-value parameters | + +## Behavior details + +For the `repository-content-selector` type, the content selector must exist in Nexus before the privilege is created. +If the content selector is not specified or is invalid, the action automatically converts the privilege type to `repository-view`. diff --git a/content/documentation/admin/actions/nexus/createnexusprivilege.ru.md b/content/documentation/admin/actions/nexus/createnexusprivilege.ru.md index fd4141b1..3f32323a 100644 --- a/content/documentation/admin/actions/nexus/createnexusprivilege.ru.md +++ b/content/documentation/admin/actions/nexus/createnexusprivilege.ru.md @@ -4,12 +4,16 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} -CreateNexusPrivilege — создаёт новую привилегию в Nexus Repository Manager 3. Привилегии определяют права доступа к репозиториям и другим ресурсам Nexus. +CreateNexusPrivilege — создаёт новую привилегию в Nexus Repository Manager 3. +Привилегии определяют права доступа к репозиториям и другим ресурсам Nexus. -### Пример запроса (repository-view) +## Пример запроса (repository-view) + +Пример тела запроса действия: ```yaml name: example-privilege @@ -22,7 +26,9 @@ format: maven2 repository: maven-releases ``` -### Пример запроса (repository-content-selector) +## Пример запроса (repository-content-selector) + +Пример тела запроса действия: ```yaml name: content-selector-privilege @@ -35,7 +41,9 @@ repository: maven-releases contentSelector: my-content-selector ``` -### Пример запроса (wildcard) +## Пример запроса (wildcard) + +Пример тела запроса действия: ```yaml name: wildcard-privilege @@ -46,21 +54,24 @@ actions: - READ ``` -### Спецификация запроса +## Спецификация запроса -| Поле | Обязательность | Описание | +Тело запроса действия поддерживает следующие параметры: + +| Название | Обязательность | Описание | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| name | Да | Название создаваемой привилегии. Должно быть уникальным в рамках Nexus | -| description | Нет | Описание привилегии | -| type | Да | Тип привилегии: `repository-view`, `repository-content-selector`, `repository-admin`, `application`, `wildcard` | -| actions | Нет | Список действий, разрешённых привилегией (например, `READ`, `BROWSE`, `CREATE`, `UPDATE`, `DELETE`) | -| format | Нет | Формат репозитория (например, `maven2`, `docker`, `npm`). Используется для типов `repository-view`, `repository-content-selector`, `repository-admin` | -| repository | Нет | Название репозитория. Используется для типов `repository-view`, `repository-content-selector`, `repository-admin` | -| contentSelector | Нет | Название селектора контента. Обязателен для типа `repository-content-selector`. Если не указан или невалиден, тип автоматически преобразуется в `repository-view` | -| pattern | Нет | Шаблон для типа `wildcard` | -| domain | Нет | Домен для типа `application` | -| attributes | Нет | Дополнительные параметры в формате ключ-значение | - -### Примечание - -Для типа `repository-content-selector` селектор контента должен существовать в Nexus до создания привилегии. Если селектор контента не указан или невалиден, действие автоматически преобразует тип привилегии в `repository-view`. +| `name` | Да | Название создаваемой привилегии. Должно быть уникальным в рамках Nexus | +| `description` | Нет | Описание привилегии | +| `type` | Да | Тип привилегии: `repository-view`, `repository-content-selector`, `repository-admin`, `application`, `wildcard` | +| `actions` | Нет | Список действий, разрешённых привилегией (например, `READ`, `BROWSE`, `CREATE`, `UPDATE`, `DELETE`) | +| `format` | Нет | Формат репозитория (например, `maven2`, `docker`, `npm`). Используется для типов `repository-view`, `repository-content-selector`, `repository-admin` | +| `repository` | Нет | Название репозитория. Используется для типов `repository-view`, `repository-content-selector`, `repository-admin` | +| `contentSelector` | Нет | Название селектора контента. Обязателен для типа `repository-content-selector`. Если не указан или невалиден, тип автоматически преобразуется в `repository-view` | +| `pattern` | Нет | Шаблон для типа `wildcard` | +| `domain` | Нет | Домен для типа `application` | +| `attributes` | Нет | Дополнительные параметры в формате ключ-значение | + +## Особенности работы + +Для типа `repository-content-selector` селектор контента должен существовать в Nexus до создания привилегии. +Если селектор контента не указан или невалиден, действие автоматически преобразует тип привилегии в `repository-view`. diff --git a/content/documentation/admin/actions/nexus/createnexusrepository.md b/content/documentation/admin/actions/nexus/createnexusrepository.md index 8d308ebb..7f7f2e97 100644 --- a/content/documentation/admin/actions/nexus/createnexusrepository.md +++ b/content/documentation/admin/actions/nexus/createnexusrepository.md @@ -4,13 +4,16 @@ weight: 10 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} -`CreateNexusRepository` — creates a new repository of any supported type (maven, docker, npm, etc.) in Nexus Repository Manager 3 using the REST API. +`CreateNexusRepository` — creates a new repository of any supported type, for example, `maven`, `docker`, or `npm`, in Nexus Repository Manager 3 using the REST API. The format, type, and other key settings are fully configurable and correspond to the Nexus API. -### Request example (Maven hosted) +## Request example (Maven hosted) + +Example of the action request body: ```yaml description: | @@ -31,7 +34,9 @@ maven: layoutPolicy: PERMISSIVE ``` -### Request example (Docker group) +## Request example (Docker group) + +Example of the action request body: ```yaml description: | @@ -53,27 +58,31 @@ docker: httpPort: 5001 ``` -### Request specification +## Request specification -| Field | Required | Description | Example | +The action request body supports the following parameters: + +| Name | Required | Description | Example | | ------------- | ------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| description | No | Description of the action or repository's purpose. Used only in the UI, not by Nexus itself | - | -| name | Yes | Name of the repository to create. Must be unique within Nexus | my-maven-repo | -| format | Yes | Format (`maven`, `docker`, `npm`, `raw`, etc.) | maven | -| type | Yes | Type: `hosted`, `proxy`, or `group` | hosted | -| online | Yes | Whether the repository is available (`true`/`false`) | true | -| storage | Yes | Storage object: `blobStoreName`, `strictContentTypeValidation`, `writePolicy` | [Maven hosted example](#request-example-maven-hosted) | -| cleanup | No | Linked cleanup policies (`policyNames`) | policyNames: [maven-cleanup] | -| maven | For maven | Maven-only: `versionPolicy`, `layoutPolicy` | [Maven hosted example](#request-example-maven-hosted) | -| proxy | For proxy | Proxy repository: `remoteUrl`, `contentMaxAge`, `metadataMaxAge` | - | -| group | For group | List of `memberNames` values | [Docker group example](#request-example-docker-group) | -| docker | For docker | Docker-specific parameters: `httpPort`, `v1Enabled`, `forceBasicAuth` | [Docker group example](#request-example-docker-group) | -| component | No | Component settings passed to the Nexus API as is. Specify them only if the Nexus API requires them for the repository format | - | -| attributes | No | Any custom fields | - | +| `description` | No | Description of the action or repository's purpose. Used only in the UI, not by Nexus itself | — | +| `name` | Yes | Name of the repository to create. Must be unique within Nexus | `my-maven-repo` | +| `format` | Yes | Format, for example, `maven`, `docker`, `npm`, or `raw` | `maven` | +| `type` | Yes | Type: `hosted`, `proxy`, or `group` | `hosted` | +| `online` | Yes | Whether the repository is available (`true`/`false`) | `true` | +| `storage` | Yes | Storage object: `blobStoreName`, `strictContentTypeValidation`, `writePolicy` | [Maven hosted example](#request-example-maven-hosted) | +| `cleanup` | No | Linked cleanup policies (`policyNames`) | `policyNames: [maven-cleanup]` | +| `maven` | For maven | Maven-only: `versionPolicy`, `layoutPolicy` | [Maven hosted example](#request-example-maven-hosted) | +| `proxy` | For proxy | Proxy repository: `remoteUrl`, `contentMaxAge`, `metadataMaxAge` | — | +| `group` | For group | List of `memberNames` values | [Docker group example](#request-example-docker-group) | +| `docker` | For docker | Docker-specific parameters: `httpPort`, `v1Enabled`, `forceBasicAuth` | [Docker group example](#request-example-docker-group) | +| `component` | No | Component settings passed to the Nexus API as is. Specify them only if the Nexus API requires them for the repository format | — | +| `attributes` | No | Any custom fields | — | + +## Requirements -### Requirements +When preparing the request, follow these requirements: -- Use only the blocks (`maven`, `group`, `proxy`, `docker`, etc.) supported by the selected type and format. +- Use only the blocks supported by the selected type and format, for example, `maven`, `group`, `proxy`, or `docker`. - For Maven hosted repositories, `maven: {versionPolicy, layoutPolicy}` is required. - For group repositories, `group.memberNames` is required. - For proxy repositories, `proxy.remoteUrl` is required. diff --git a/content/documentation/admin/actions/nexus/createnexusrepository.ru.md b/content/documentation/admin/actions/nexus/createnexusrepository.ru.md index a22ddb80..50cbe37b 100644 --- a/content/documentation/admin/actions/nexus/createnexusrepository.ru.md +++ b/content/documentation/admin/actions/nexus/createnexusrepository.ru.md @@ -4,13 +4,16 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} `CreateNexusRepository` — создаёт новый репозиторий любого поддерживаемого типа (maven, docker, npm и др.) в Nexus Repository Manager 3 с помощью REST API. Параметры формата, типа и другие ключевые настройки полностью настраиваются и соответствуют Nexus API. -### Пример запроса (Maven hosted) +## Пример запроса (Maven hosted) + +Пример тела запроса действия: ```yaml description: | @@ -31,7 +34,9 @@ maven: layoutPolicy: PERMISSIVE ``` -### Пример запроса (Docker group) +## Пример запроса (Docker group) + +Пример тела запроса действия: ```yaml description: | @@ -53,27 +58,31 @@ docker: httpPort: 5001 ``` -### Спецификация запроса +## Спецификация запроса -| Поле | Обязательность | Описание | Пример | +Тело запроса действия поддерживает следующие параметры: + +| Название | Обязательность | Описание | Пример | | ------------- | ---------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------- | -| description | Нет | Документация по назначению этого действия/репозитория. Не используется самим Nexus, только для UI | - | -| name | Да | Название создаваемого репозитория. Должно быть уникальным в рамках Nexus | my-maven-repo | -| format | Да | Формат (`maven`, `docker`, `npm`, `raw` и т. д.) | maven | -| type | Да | Тип: `hosted`, `proxy` или `group` | hosted | -| online | Да | Доступен ли репозиторий (`true`/`false`) | true | -| storage | Да | Объект storage: `blobStoreName`, `strictContentTypeValidation`, `writePolicy` | [Пример Maven hosted](#пример-запроса-maven-hosted) | -| cleanup | Нет | Привязанные политики очистки (`policyNames`) | policyNames: [maven-cleanup] | -| maven | Для maven | Только для maven: `versionPolicy`, `layoutPolicy` | [Пример Maven hosted](#пример-запроса-maven-hosted) | -| proxy | Для proxy | Прокси-репозиторий: `remoteUrl`, `contentMaxAge`, `metadataMaxAge` | - | -| group | Для group | Список значений `memberNames` | [Пример Docker group](#пример-запроса-docker-group) | -| docker | Для docker | Специфичные для Docker параметры: `httpPort`, `v1Enabled`, `forceBasicAuth` | [Пример Docker group](#пример-запроса-docker-group) | -| component | Нет | Параметры компонентов, которые передаются в API Nexus без изменений. Указывайте их, только если API Nexus требует их для формата репозитория | - | -| attributes | Нет | Любые кастомные поля | - | +| `description` | Нет | Документация по назначению этого действия/репозитория. Не используется самим Nexus, только для UI | — | +| `name` | Да | Название создаваемого репозитория. Должно быть уникальным в рамках Nexus | `my-maven-repo` | +| `format` | Да | Формат (`maven`, `docker`, `npm`, `raw` и т. д.) | `maven` | +| `type` | Да | Тип: `hosted`, `proxy` или `group` | `hosted` | +| `online` | Да | Доступен ли репозиторий (`true`/`false`) | `true` | +| `storage` | Да | Объект storage: `blobStoreName`, `strictContentTypeValidation`, `writePolicy` | [Пример Maven hosted](#пример-запроса-maven-hosted) | +| `cleanup` | Нет | Привязанные политики очистки (`policyNames`) | `policyNames: [maven-cleanup]` | +| `maven` | Для maven | Только для maven: `versionPolicy`, `layoutPolicy` | [Пример Maven hosted](#пример-запроса-maven-hosted) | +| `proxy` | Для proxy | Прокси-репозиторий: `remoteUrl`, `contentMaxAge`, `metadataMaxAge` | — | +| `group` | Для group | Список значений `memberNames` | [Пример Docker group](#пример-запроса-docker-group) | +| `docker` | Для docker | Специфичные для Docker параметры: `httpPort`, `v1Enabled`, `forceBasicAuth` | [Пример Docker group](#пример-запроса-docker-group) | +| `component` | Нет | Параметры компонентов, которые передаются в API Nexus без изменений. Указывайте их, только если API Nexus требует их для формата репозитория | — | +| `attributes` | Нет | Любые кастомные поля | — | + +## Требования -### Требования +При подготовке запроса учитывайте следующие требования: -- Используйте только те блоки (`maven`, `group`, `proxy`, `docker` и пр.), которые поддерживаются для вашего типа/формата. +- Используйте только блоки, которые поддерживаются выбранным типом и форматом, например `maven`, `group`, `proxy` или `docker`. - Для maven hosted обязательно `maven: {versionPolicy, layoutPolicy}`. - Для group — обязательно `group.memberNames`. - Для proxy — обязательно `proxy.remoteUrl`. diff --git a/content/documentation/admin/actions/nexus/createnexusrole.md b/content/documentation/admin/actions/nexus/createnexusrole.md index 2878d894..b13f31a4 100644 --- a/content/documentation/admin/actions/nexus/createnexusrole.md +++ b/content/documentation/admin/actions/nexus/createnexusrole.md @@ -4,12 +4,16 @@ weight: 60 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} -CreateNexusRole — creates a new role in Nexus Repository Manager 3. Roles combine privileges and can include other roles. +CreateNexusRole — creates a new role in Nexus Repository Manager 3. +Roles combine privileges and can include other roles. -### Request example +## Request example + +Example of the action request body: ```yaml id: example-role @@ -21,12 +25,14 @@ privileges: roles: [] ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------------- | ----------------- | ------------------------------------------------------------------------------ | -| id | Yes | Unique role identifier | -| name | Yes | Role name | -| description | No | Role description | -| privileges | No | List of privilege names assigned to the role | -| roles | No | List of other role identifiers included in this role | +| `id` | Yes | Unique role identifier | +| `name` | Yes | Role name | +| `description` | No | Role description | +| `privileges` | No | List of privilege names assigned to the role | +| `roles` | No | List of other role identifiers included in this role | diff --git a/content/documentation/admin/actions/nexus/createnexusrole.ru.md b/content/documentation/admin/actions/nexus/createnexusrole.ru.md index 238deb22..122ab4a1 100644 --- a/content/documentation/admin/actions/nexus/createnexusrole.ru.md +++ b/content/documentation/admin/actions/nexus/createnexusrole.ru.md @@ -4,12 +4,16 @@ weight: 60 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} -CreateNexusRole — создаёт новую роль в Nexus Repository Manager 3. Роли объединяют привилегии и могут включать другие роли. +CreateNexusRole — создаёт новую роль в Nexus Repository Manager 3. +Роли объединяют привилегии и могут включать другие роли. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml id: example-role @@ -21,12 +25,14 @@ privileges: roles: [] ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------------- | ----------------- | ------------------------------------------------------------------------------ | -| id | Да | Уникальный идентификатор роли | -| name | Да | Название роли | -| description | Нет | Описание роли | -| privileges | Нет | Список названий привилегий, которые назначаются роли | -| roles | Нет | Список идентификаторов других ролей, которые включаются в данную роль | +| `id` | Да | Уникальный идентификатор роли | +| `name` | Да | Название роли | +| `description` | Нет | Описание роли | +| `privileges` | Нет | Список названий привилегий, которые назначаются роли | +| `roles` | Нет | Список идентификаторов других ролей, которые включаются в данную роль | diff --git a/content/documentation/admin/actions/nexus/createnexususer.md b/content/documentation/admin/actions/nexus/createnexususer.md index 2c06e487..783ea1ef 100644 --- a/content/documentation/admin/actions/nexus/createnexususer.md +++ b/content/documentation/admin/actions/nexus/createnexususer.md @@ -4,12 +4,15 @@ weight: 90 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} CreateNexusUser — creates a new user in Nexus Repository Manager 3. -### Request example +## Request example + +Example of the action request body: ```yaml userId: example-user @@ -22,14 +25,16 @@ roles: - nx-admin ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------------- | ----------------- | ------------------------------------------------------------------------------ | -| userId | Yes | Unique user identifier | -| firstName | Yes | User's first name | -| lastName | Yes | User's last name | -| emailAddress | Yes | User's email address | -| password | Yes | User's password | -| status | Yes | User status: `active` or `disabled` | -| roles | No | List of role identifiers assigned to the user at creation | +| `userId` | Yes | Unique user identifier | +| `firstName` | Yes | User's first name | +| `lastName` | Yes | User's last name | +| `emailAddress` | Yes | User's email address | +| `password` | Yes | User's password | +| `status` | Yes | User status: `active` or `disabled` | +| `roles` | No | List of role identifiers assigned to the user at creation | diff --git a/content/documentation/admin/actions/nexus/createnexususer.ru.md b/content/documentation/admin/actions/nexus/createnexususer.ru.md index aa686a5c..48f42f2f 100644 --- a/content/documentation/admin/actions/nexus/createnexususer.ru.md +++ b/content/documentation/admin/actions/nexus/createnexususer.ru.md @@ -4,12 +4,15 @@ weight: 90 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} CreateNexusUser — создаёт нового пользователя в Nexus Repository Manager 3. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml userId: example-user @@ -22,14 +25,16 @@ roles: - nx-admin ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------------- | ----------------- | ------------------------------------------------------------------------------ | -| userId | Да | Уникальный идентификатор пользователя | -| firstName | Да | Имя пользователя | -| lastName | Да | Фамилия пользователя | -| emailAddress | Да | Email-адрес пользователя | -| password | Да | Пароль пользователя | -| status | Да | Статус пользователя: `active` или `disabled` | -| roles | Нет | Список идентификаторов ролей, которые назначаются пользователю при создании | +| `userId` | Да | Уникальный идентификатор пользователя | +| `firstName` | Да | Имя пользователя | +| `lastName` | Да | Фамилия пользователя | +| `emailAddress` | Да | Email-адрес пользователя | +| `password` | Да | Пароль пользователя | +| `status` | Да | Статус пользователя: `active` или `disabled` | +| `roles` | Нет | Список идентификаторов ролей, которые назначаются пользователю при создании | diff --git a/content/documentation/admin/actions/nexus/deletenexusprivilege.md b/content/documentation/admin/actions/nexus/deletenexusprivilege.md index 98f338f2..c3475330 100644 --- a/content/documentation/admin/actions/nexus/deletenexusprivilege.md +++ b/content/documentation/admin/actions/nexus/deletenexusprivilege.md @@ -4,19 +4,24 @@ weight: 50 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} DeleteNexusPrivilege — deletes a privilege from Nexus Repository Manager 3. -### Request example +## Request example + +Example of the action request body: ```yaml name: example-privilege ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------ | ----------------- | ---------------------------------------------- | -| name | Yes | Name of the privilege to delete | +| `name` | Yes | Name of the privilege to delete | diff --git a/content/documentation/admin/actions/nexus/deletenexusprivilege.ru.md b/content/documentation/admin/actions/nexus/deletenexusprivilege.ru.md index 5e432f55..ee3361de 100644 --- a/content/documentation/admin/actions/nexus/deletenexusprivilege.ru.md +++ b/content/documentation/admin/actions/nexus/deletenexusprivilege.ru.md @@ -4,19 +4,24 @@ weight: 50 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} DeleteNexusPrivilege — удаляет привилегию из Nexus Repository Manager 3. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: example-privilege ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------ | ----------------- | ---------------------------------------------- | -| name | Да | Название привилегии, которую требуется удалить | +| `name` | Да | Название привилегии, которую требуется удалить | diff --git a/content/documentation/admin/actions/nexus/deletenexusrepository.md b/content/documentation/admin/actions/nexus/deletenexusrepository.md index 9ed8a2a0..5f735f07 100644 --- a/content/documentation/admin/actions/nexus/deletenexusrepository.md +++ b/content/documentation/admin/actions/nexus/deletenexusrepository.md @@ -4,24 +4,31 @@ weight: 20 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} DeleteNexusRepository — deletes an existing repository from Nexus Repository Manager 3. -### Request example +## Request example + +Example of the action request body: ```yaml name: my-repo-to-delete ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------ | ----------------- | ------------------------------------------------ | | `name` | Yes | Name of the repository to delete | -### Algorithm +## How it works + +The action runs in the following order: - Sends a `DELETE` request to `/service/rest/v1/repositories/{name}`, where `{name}` is the value of the `name` field. - If the repository is found and deleted, the request returns status code 204. diff --git a/content/documentation/admin/actions/nexus/deletenexusrepository.ru.md b/content/documentation/admin/actions/nexus/deletenexusrepository.ru.md index 17ca6e97..36d5a5b7 100644 --- a/content/documentation/admin/actions/nexus/deletenexusrepository.ru.md +++ b/content/documentation/admin/actions/nexus/deletenexusrepository.ru.md @@ -4,24 +4,31 @@ weight: 20 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} DeleteNexusRepository — удаляет существующий репозиторий из Nexus Repository Manager 3. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml name: my-repo-to-delete ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------ | ----------------- | ----------------------------------------------- | | `name` | Да | Название репозитория, который требуется удалить | -### Алгоритм +## Алгоритм работы + +Действие выполняется в следующем порядке: - Выполняется `DELETE` по адресу `/service/rest/v1/repositories/{name}`, где `{name}` — это значение поля `name`. - Если репозиторий найден и удалён — возвращается 204. diff --git a/content/documentation/admin/actions/nexus/deletenexusrole.md b/content/documentation/admin/actions/nexus/deletenexusrole.md index d61fad48..677475cb 100644 --- a/content/documentation/admin/actions/nexus/deletenexusrole.md +++ b/content/documentation/admin/actions/nexus/deletenexusrole.md @@ -4,19 +4,24 @@ weight: 80 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} DeleteNexusRole — deletes a role from Nexus Repository Manager 3. -### Request example +## Request example + +Example of the action request body: ```yaml id: example-role ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | ------ | ----------------- | --------------------------------------------- | -| id | Yes | Identifier of the role to delete | +| `id` | Yes | Identifier of the role to delete | diff --git a/content/documentation/admin/actions/nexus/deletenexusrole.ru.md b/content/documentation/admin/actions/nexus/deletenexusrole.ru.md index dfa072a4..8f702bb4 100644 --- a/content/documentation/admin/actions/nexus/deletenexusrole.ru.md +++ b/content/documentation/admin/actions/nexus/deletenexusrole.ru.md @@ -4,19 +4,24 @@ weight: 80 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} DeleteNexusRole — удаляет роль из Nexus Repository Manager 3. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml id: example-role ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------ | ----------------- | --------------------------------------------- | -| id | Да | Идентификатор роли, которую требуется удалить | +| `id` | Да | Идентификатор роли, которую требуется удалить | diff --git a/content/documentation/admin/actions/nexus/deletenexususer.md b/content/documentation/admin/actions/nexus/deletenexususer.md index 110e369f..dc898908 100644 --- a/content/documentation/admin/actions/nexus/deletenexususer.md +++ b/content/documentation/admin/actions/nexus/deletenexususer.md @@ -4,19 +4,24 @@ weight: 100 --- {{< alert level="info" >}} -Running this action requires a token — a base64(`admin:password`) string used for HTTP Basic authentication in requests to Nexus. +Running this action requires a token: the `admin:password` string encoded in Base64. +The token is used for HTTP Basic authentication in requests to Nexus. {{< /alert >}} DeleteNexusUser — deletes a user from Nexus Repository Manager 3. -### Request example +## Request example + +Example of the action request body: ```yaml userId: example-user ``` -### Request specification +## Request specification + +The action request body supports the following parameters: -| Field | Required | Description | +| Name | Required | Description | | -------- | ----------------- | ------------------------------------------------------ | -| userId | Yes | Identifier of the user to delete | +| `userId` | Yes | Identifier of the user to delete | diff --git a/content/documentation/admin/actions/nexus/deletenexususer.ru.md b/content/documentation/admin/actions/nexus/deletenexususer.ru.md index 7a08dd38..4aeaa429 100644 --- a/content/documentation/admin/actions/nexus/deletenexususer.ru.md +++ b/content/documentation/admin/actions/nexus/deletenexususer.ru.md @@ -4,19 +4,24 @@ weight: 100 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие токена — строки base64(`admin:password`), используемой как Basic Auth при запросах к Nexus. +Для выполнения действия требуется токен — строка `admin:password` в кодировке Base64. +Токен используется для Basic-аутентификации в запросах к Nexus. {{< /alert >}} DeleteNexusUser — удаляет пользователя из Nexus Repository Manager 3. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml userId: example-user ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | -------- | ----------------- | ------------------------------------------------------ | -| userId | Да | Идентификатор пользователя, которого требуется удалить | +| `userId` | Да | Идентификатор пользователя, которого требуется удалить | diff --git a/content/documentation/admin/actions/overview.md b/content/documentation/admin/actions/overview.md index 27145d02..d75e2ba9 100644 --- a/content/documentation/admin/actions/overview.md +++ b/content/documentation/admin/actions/overview.md @@ -4,24 +4,27 @@ description: Action configuration in Deckhouse Development Portal (DDP) — requ weight: 10 --- -Actions are a Deckhouse Development Portal mechanism for running operations in external infrastructure systems and services. For example, actions can: +Actions are a Deckhouse Development Portal mechanism for running operations in external infrastructure systems and services. +For example, actions can: -- create projects, variables, branches, tags, releases, and merge requests in [GitLab](../gitlab/); -- create resources in [Kubernetes](../kubernetes/) and retrieve them; -- create secrets in [Deckhouse Stronghold and HashiCorp Vault](../vault/), as well as clients in [Keycloak](../keycloak/); -- create projects in [SonarQube](../sonarqube/), products and engagements in [DefectDojo](../defectdojo/), projects in [CodeScoring](../codescoring/), and repositories, roles, users, and privileges in [Nexus Repository](../nexus/); -- create topics and ACLs in [Apache Kafka](../kafka/); -- perform helper actions for debugging and controlling process execution (for example, [Debug](../debug/) and [Wait](../wait/)). +- Create projects, variables, branches, tags, releases, and merge requests in [GitLab](../gitlab/). +- Create resources in [Kubernetes](../kubernetes/) and retrieve them. +- Create secrets in [Deckhouse Stronghold and HashiCorp Vault](../vault/), as well as clients in [Keycloak](../keycloak/). +- Create projects in [SonarQube](../sonarqube/), products and engagements in [DefectDojo](../defectdojo/), projects in [CodeScoring](../codescoring/), and repositories, roles, users, and privileges in [Nexus Repository](../nexus/). +- Create topics and ACLs in [Apache Kafka](../kafka/). +- Perform helper actions for debugging and controlling process execution (for example, [Debug](../debug/) and [Wait](../wait/)). An action can be linked to one or more resources. Once linked, it can be run for any entity of those resources. ## Action configuration +An action is configured on several tabs described below. + ### Basic information When creating or editing an action, specify the basic information: -| Field | Required | Description | +| Name | Required | Description | | ----------------- | -------- | -------------------------------------------------------------------------------------------- | | Name | Yes | Arbitrary name of the action | | Identifier | Yes | Action identifier. Generated automatically from the name | @@ -34,36 +37,40 @@ When creating or editing an action, specify the basic information: ### Request configuration -#### Action type +The request configuration defines how the action is executed and what it sends. -An action can be of the following types: +#### Action type -- "Built-in (BuiltIn)" — the action's execution logic is defined within the portal. For built-in actions, you must select one of the preconfigured backends. -- "Webhook" — the action's execution logic is fully configured by the user. +An action can be built-in or a webhook. +For a "Built-in (BuiltIn)" action, the execution logic is defined within the portal. +For built-in actions, you must select one of the preconfigured backends. +For a "Webhook" action, the execution logic is fully configured by the user. #### Restart parameters If an action fails, the portal can automatically retry it. Configure retries in the "Restart parameters" section: -| Field | Description | +| Name | Description | | -------------- | ----------------------------------------------------------------------------------------------------------------- | | Max retries | How many times to retry execution after a failure. `0` means a single attempt with no retries | | Base delay (s) | Delay in seconds before the first retry. The pause doubles before each subsequent attempt (exponential backoff) | #### Request body format -For webhook actions, you can choose the format used to send the request body: - -- JSON (default) — the request body is sent in JSON format with the `Content-Type: application/json` header. -- "Form URL Encoded" — the request body is sent in `application/x-www-form-urlencoded` format. +For webhook actions, you can choose the format used to send the request body. +By default, the request body is sent in JSON format with the `Content-Type: application/json` header. +With "Form URL Encoded", the request body is sent in `application/x-www-form-urlencoded` format. {{< alert level="info" >}} -When "Form URL Encoded" is selected, the request body must contain only flat key-value pairs. Nested structures and arrays are not supported in this format. +When "Form URL Encoded" is selected, the request body must contain only flat key-value pairs. +Nested structures and arrays are not supported in this format. {{< /alert >}} -If the request body is empty, the webhook sends the request without a body and without the `Content-Type` header. Use this for `GET` and `DELETE` requests. +If the request body is empty, the webhook sends the request without a body and without the `Content-Type` header. +Use this for `GET` and `DELETE` requests. -If the external system returns an error response code, the response body is saved in the action response: JSON as an object, anything else in the `raw_body` field. The action error text has the form `unexpected status code: , response: `; the response body is truncated to 8192 bytes. +If the external system returns an error response code, the response body is saved in the action response: JSON as an object, anything else in the `raw_body` field. +The action error text has the form `unexpected status code: , response: `; the response body is truncated to 8192 bytes. Example: @@ -75,23 +82,27 @@ token: {{ .credentials.token }} For webhook actions, you can enable the "Verbose logging" option that logs all HTTP request and response details: -- request URL; -- HTTP method; -- HTTP headers (including tokens); -- request body; -- response status code; -- response HTTP headers; -- response body. +- Request URL +- HTTP method +- HTTP headers (including tokens) +- Request body +- Response status code +- Response HTTP headers +- Response body -When this option is enabled, all this data is written to the action run log. When it is disabled, logging works in standard mode. +When this option is enabled, all this data is written to the action run log. +When it is disabled, logging works in standard mode. {{< alert level="warning" >}} -Enabling verbose logging may result in sensitive information (tokens, passwords, etc.) being written to the logs. Use this option with caution and only when needed for debugging. +Enabling verbose logging may result in sensitive information, such as tokens and passwords, being written to the logs. +Use this option with caution and only when needed for debugging. {{< /alert >}} #### Request body -Each action sends an HTTP request to a built-in backend or to a webhook backend URL. The request usually includes a request body (`body`) that describes what exactly will be sent. The request body is defined in YAML. +Each action sends an HTTP request to a built-in backend or to a webhook backend URL. +The request usually includes a request body (`body`) that describes what exactly will be sent. +The request body is defined in YAML. Parameter values from the user form can be substituted into the request body using [Go template](https://pkg.go.dev/text/template) templates. @@ -107,15 +118,19 @@ For built-in actions, the "Request body" parameter is part of the action configu ### User form +The user form defines the parameters that the user fills in when running the action. + #### Parameters -The "User form" section specifies the parameters that the user can fill in when launching the action. Property types are described in the [Properties](../../user/properties/) section. +The "User form" section specifies the parameters that the user can fill in when launching the action. +Property types are described in the [Properties](../../user/properties/) section. The following options are available for each parameter: -- "Editable" — allows the parameter value to be changed when launching the action. If this option is disabled, the value cannot be changed. -- "Required" — requires a value to be specified when launching the action. -- "Hidden" — the parameter is not displayed in the user form when launching the action. +- "Editable": Allows the parameter value to be changed when launching the action. + If this option is disabled, the value cannot be changed. +- "Required": Requires a value to be specified when launching the action. +- "Hidden": The parameter is not displayed in the user form when launching the action. Each parameter can have a default value that is pre-filled in the form when the action is launched. @@ -123,40 +138,47 @@ Each parameter can have a default value that is pre-filled in the form when the Set a default value for non-editable and hidden parameters: the user cannot change them when launching the action. {{< /alert >}} -The parameter description is shown when launching the action by clicking the "info" icon. Providing a description makes the parameter's purpose easier to understand and reduces the risk of errors when launching the action. +The parameter description is shown when launching the action by clicking the "info" icon. +Providing a description makes the parameter's purpose easier to understand and reduces the risk of errors when launching the action. -Parameter values can use [Go template](https://pkg.go.dev/text/template) template functions. For example, the expression `{{ .entity.name }}` in a parameter value means that when the action is launched, the name of the entity it is running for will be substituted. +Parameter values can use [Go template](https://pkg.go.dev/text/template) template functions. +For example, the expression `{{ .entity.name }}` in a parameter value means that when the action is launched, the name of the entity it is running for will be substituted. #### Property conditions -Parameters can be automatically hidden or shown in the user form depending on the value of a `Boolean`-type parameter. This is configured in the "Property conditions" section, where you define rules for showing or hiding selected parameters. +Parameters can be automatically hidden or shown in the user form depending on the value of a `Boolean`-type parameter. +This is configured in the "Property conditions" section, where you define rules for showing or hiding selected parameters. ### Update +After a successful run, the action can update entities, relations, credentials, and the process store. + #### Templating contexts -All updates are performed only after the action completes successfully. The following templating contexts are available in Go templates: +All updates are performed only after the action completes successfully. +The following templating contexts are available in Go templates: | Context | Description | Example | | ----------- | --------------------------------------------------------------------------- | ------------------------------------- | | `.property` | Values from the user form | `{{ .property.repo }}` | | `.response` | Parsed action response (JSON) | `{{ .response.id }}` | -| `.entity` | Parameters of the catalog entity for which the action is run | `{{ .entity.slug }}` | +| `.entity` | Properties of the catalog entity for which the action is run | `{{ .entity.slug }}` | | `.workflow` | Workflow parameters | `{{ .workflow.branch }}` | | `.process` | Process parameters | `{{ .process.releaseId }}` | | `.global` | Global variables (variable set identifier, then key) | `{{ .global.myGroup.apiUrl }}` | | `.team` | Variables of the team selected at launch | `{{ .team.token }}` | | `.store` | Variables from the process store | `{{ .store.myKey }}` | -| `.context` | [Process launch context](../processes/overview/#launch-context), for example data of the environment selected on the home page | `{{ .context.environment.slug }}` | +| `.context` | [Process launch context](../processes/overview/#launch-context), for example data of the environment selected on the Home page | `{{ .context.environment.slug }}` | -#### Entity parameter update +#### Entity property update -To enable property update, turn on the switch in the "Entity property updates" section header. The portal then applies the update rules and writes the values to the entity's parameters. +To enable property update, turn on the switch in the "Entity property updates" section header. +The portal then applies the update rules and writes the values to the entity's properties. -| Field | Description | +| Name | Description | | ------------------- | ------------------------------------------------------------------------- | | Source | Go template for the value | -| Entity parameter | Identifier of the entity parameter in the catalog | +| Entity property | Identifier of the entity property in the catalog | For example, when the "Create GitLab project" action is run, the response (`response`) will contain the specification of the created project: @@ -167,16 +189,18 @@ For example, when the "Create GitLab project" action is run, the response (`resp } ``` -If you need to immediately populate the entity's `repository_id` parameter after creating a project in GitLab, specify the following update rule: +If you need to immediately populate the entity's `repository_id` property after creating a project in GitLab, specify the following update rule: 1. Source: `{{ .response.id }}`. -1. Entity parameter: `repository_id`. +1. Entity property: `repository_id`. #### Entity creation -To enable entity creation, turn on the switch in the "Creating entities" section header. The portal then automatically creates new entities in the selected resources according to the specified rules. Rules are defined separately for each resource. +To enable entity creation, turn on the switch in the "Creating entities" section header. +The portal then automatically creates new entities in the selected resources according to the specified rules. +Rules are defined separately for each resource. -| Field | Description | +| Name | Description | | ------------------------------------- | ---------------------------------------------------------------------------------------------- | | Owner is the run initiator | The user who launched the action becomes the owner of created entities. If the initiator is unknown (a run by an automation or a webhook), the owner from the "Owner of created entities" field is used | | Owner of created entities | Assigned as the owner of all entities the action creates in the catalog | @@ -184,9 +208,10 @@ To enable entity creation, turn on the switch in the "Creating entities" section | Resource | Catalog resource in which the entity will be created | | Source (identifier) | Go template for the identifier of the entity being created | | Source (name) | Go template for the name of the entity being created | -| Additional rules | Mapping of a Go template value to an entity parameter | +| Additional rules | Mapping of a Go template value to an entity property | -The identifier and name are required for each rule group. If a resource already has an entity with the same identifier, creation is skipped. +The identifier and name are required for each rule group. +If a resource already has an entity with the same identifier, creation is skipped. For example, when the "Create GitLab project" action is run, the response may contain: @@ -204,13 +229,15 @@ To create an entity in the "GitLab projects" resource after the action completes 1. Source (identifier): `{{ .response.id }}`. 1. Source (name): `{{ .response.name }}`. -If needed, add additional rules to populate entity parameters, for example map `{{ .response.path }}` to the `path` parameter. +If needed, add additional rules to populate entity properties, for example map `{{ .response.path }}` to the `path` property. #### Entity deletion -To enable entity deletion, turn on the switch in the "Deleting entities" section header. The portal then automatically deletes entities in the selected resources according to the specified rules. Rules are defined separately for each resource. +To enable entity deletion, turn on the switch in the "Deleting entities" section header. +The portal then automatically deletes entities in the selected resources according to the specified rules. +Rules are defined separately for each resource. -| Field | Description | +| Name | Description | | -------- | --------------------------------------------------------------------------- | | Resource | Catalog resource that contains the entity to delete | | Source | Go template for the entity identifier (for example, `{{ .response.id }}`) | @@ -233,9 +260,11 @@ To delete the entity in the "GitLab projects" resource after the action complete #### Entity relation creation -To enable relation creation, turn on the switch in the "Creating relations for the entity" section header. The portal then automatically creates new relations for the selected entity according to the specified rules. The set of rules is defined separately for each resource. +To enable relation creation, turn on the switch in the "Creating relations for the entity" section header. +The portal then automatically creates new relations for the selected entity according to the specified rules. +The set of rules is defined separately for each resource. -| Field | Description | +| Name | Description | | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Resource | Either of the two resources involved in the required resource relation: the list of relations in which the selected resource is specified as the parent or the child is loaded based on the selected resource. You can choose the resource of the entity for which the action is running, or the resource on the other side of the relation — the list will contain the same relation if both resources are part of it | | Relation | The catalog resource relation: it defines the parent and child resources and entity roles when creating the relation. The selected relation determines which side the launch entity is on and which of the fields below specifies the identifier of the second entity from the action's response | @@ -244,9 +273,11 @@ To enable relation creation, turn on the switch in the "Creating relations for t #### Entity relation deletion -To enable relation deletion, turn on the switch in the "Deleting relations for the entity" section header. The portal then automatically deletes relations for the selected entity according to the specified rules. The set of rules is defined separately for each resource. +To enable relation deletion, turn on the switch in the "Deleting relations for the entity" section header. +The portal then automatically deletes relations for the selected entity according to the specified rules. +The set of rules is defined separately for each resource. -| Field | Description | +| Name | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Resource | Either of the two resources involved in the required resource relation: the list of relations in which the selected resource is specified as the parent or the child is loaded based on the selected resource. You can choose the resource of the entity for which the action is running, or the resource on the other side of the relation — the list will contain the same relation if both resources are part of it | | Relation | The catalog resource relation: it defines the parent and child resources and entity roles when deleting the relation. The selected relation determines which side the launch entity is on and which of the fields below specifies the identifier of the second entity from the action's response | @@ -257,9 +288,10 @@ If no matching relation exists, deletion is skipped. #### User credentials update -To enable user credentials update, turn on the switch in the "Updating user credentials" section header. The action then automatically updates the user's credentials according to the specified rules. +To enable user credentials update, turn on the switch in the "Updating user credentials" section header. +The action then automatically updates the user's credentials according to the specified rules. -| Field | Description | +| Name | Description | | ------------------- | --------------------------------------- | | Source | Go template for the value | | Credentials type | Type of credentials to be updated | @@ -285,14 +317,15 @@ To update the credentials of a different user, enable the "Update credentials fo Rules from the "Updating process store" section only apply when the action is run as part of a process: after the action completes successfully, values are written to the run's store according to the specified rules, in list order. -| Field | Description | +| Name | Description | | ----------- | -------------------------------------------------------------------------------------------------------------------- | | Condition | An optional Go template; if empty, the rule always applies. Rendering result: `true`, `false`, `1`, or `0` | | Operation | Write string, Write JSON, Append string, Append JSON, Merge JSON (shallow), Delete | -| Target | Dot-path in the store without a leading dot, e.g. `deploy.job_id` or `notification.items` | +| Target | Dot-path in the store without a leading dot, for example, `deploy.job_id` or `notification.items` | | Source | Go template for the value | -Other actions and process elements read this data via `{{ .store. }}`. Inside a loop, the `{{ .store._loop.* }}` context is available in templates. +Other actions and process elements read this data via `{{ .store. }}`. +Inside a loop, the `{{ .store._loop.* }}` context is available in templates. If there are no rules (the list is empty), nothing is written to the store when the action runs as part of a process. @@ -302,15 +335,22 @@ For a detailed description of operations, rule examples, iterating over a collec Datasource synchronization after an action brings the object that the action created or deleted in the external system into the catalog without waiting for the scheduled synchronization. -To enable synchronization, turn on the switch in the "Datasource synchronization" section header and select datasources in the "Datasources" field. Select the datasources that load the object created or deleted by the action into the catalog. If the switch is on, select at least one datasource. +To enable synchronization, turn on the switch in the "Datasource synchronization" section header and select datasources in the "Datasources" field. +Select the datasources that load the object created or deleted by the action into the catalog. +If the switch is on, select at least one datasource. -Synchronization starts after the action completes successfully and the update rules are applied. Synchronization runs in the background: the action does not wait for it to finish and does not fail if synchronization fails. Deleted datasources are skipped. +Synchronization starts after the action completes successfully and the update rules are applied. +Synchronization runs in the background: the action does not wait for it to finish and does not fail if synchronization fails. +Deleted datasources are skipped. ### Security +Security settings restrict when and by whom the action can be run. + #### Execution conditions -The action will only run if the entity's status matches one of the selected values in the status field. If no restrictions are set, this condition does not apply. +The action will only run if the entity's status matches one of the selected values in the status field. +If no restrictions are set, this condition does not apply. #### Masking action fields @@ -318,30 +358,31 @@ For each action, you can enable masking of fields that may contain sensitive inf If this option is enabled, the following will be hidden in the action's run records: -- values of all filled-in parameters; -- request body (`body`); -- response (`response`) generated as a result of execution. +- Values of all filled-in parameters. +- Request body (`body`). +- Response (`response`) generated as a result of execution. #### Temporary response -For each action, you can enable the "Temporary response" option. It restricts access to the action's execution result and hides it from other users. - -If this option is enabled, after the action completes successfully, the response: +For each action, you can enable the "Temporary response" option. +It restricts access to the action's execution result and hides it from other users. -- is stored as temporary and displayed only to the user who launched the action; -- is removed from the regular response field so that it is not accessible to other users. +If this option is enabled, after the action completes successfully, the response is stored as temporary and displayed only to the user who launched the action. +It is removed from the regular response field so that it is not accessible to other users. Other users will see only an encrypted placeholder instead of the response content. The action's initiator can delete the temporary response manually. {{< alert level="info" >}} -The temporary response is available only to the action's initiator. Other users cannot view its contents and cannot delete it. +The temporary response is available only to the action's initiator. +Other users cannot view its contents and cannot delete it. {{< /alert >}} #### Approval -You can enable mandatory approval for an action and specify the number of approvers required. In this case, the action will not run until the specified number of approvals has been received from the designated users. +You can enable mandatory approval for an action and specify the number of approvers required. +In this case, the action will not run until the specified number of approvals has been received from the designated users. The current number of approvals and the list of users whose approval is expected are displayed in the action run table for the corresponding entity. @@ -349,31 +390,38 @@ If approval is required from a specific user, they will receive a notification i #### Approval notifications -When approval is enabled, you can enable notifications and specify how they are sent. If sending to a URL is selected, specify the webhook address, optionally disable the server's TLS certificate verification, and add additional HTTP request headers. +When approval is enabled, you can enable notifications and specify how they are sent. +If sending to a URL is selected, specify the webhook address, optionally disable the server's TLS certificate verification, and add additional HTTP request headers. ### Authorization +Authorization settings define which external services and credentials the action uses. + #### Use external service -Select the external services for which the action can be run. If multiple external services are added, a specific service can be selected when launching the action. +Select the external services for which the action can be run. +If multiple external services are added, a specific service can be selected when launching the action. #### URL and HTTP headers Specify the address to which the request will be sent and the HTTP headers. -Headers support Go templates in the form `{{ .credentials. }}` for substituting user credentials. +Headers support Go templates in the form `{{ .credentials. }}` for substituting user credentials. #### Select account for execution -By default, external infrastructure services are accessed using the credentials of the user who launched the action. To run the action on behalf of a specific account, enable the "Select account for execution" option and select the account in the "Account for execution" field. +By default, external infrastructure services are accessed using the credentials of the user who launched the action. +To run the action on behalf of a specific account, enable the "Select account for execution" option and select the account in the "Account for execution" field. For actions launched as automation events, specifying the account to run as is mandatory. #### Credentials -For built-in actions, the portal predefines the set of required credentials. Their identifiers are loaded when the built-in backend is selected. For each identifier, you must select the type of credentials to be used. +For built-in actions, the portal predefines the set of required credentials. +Their identifiers are loaded when the built-in backend is selected. +For each identifier, you must select the type of credentials to be used. -For webhook actions, credentials can be accessed in the request body using the `{{ .credentials. }}` construct. +For webhook actions, credentials can be accessed in the request body using the `{{ .credentials. }}` construct. #### HTTP method @@ -381,9 +429,13 @@ For webhook actions, the HTTP method of the outgoing request is specified. ## Action runs +The portal records each action run and its log. + ### Action run records -Each time an action is run, a record is created containing the initiator, execution status, and a detailed log. Run records for each entity are available on the entity's card, on the "Action runs" tab. If the action requires approval, it is handled on the same tab. +Each time an action is run, a record is created containing the initiator, execution status, and a detailed log. +Run records for each entity are available on the entity's card, on the "Actions" tab in the "Execution history" table. +If the action requires approval, it is handled on the same tab. A run record can be deleted, or the action can be re-run. Re-running creates a new record. @@ -402,14 +454,15 @@ Records with the full run log are created in the database regardless of the valu For each action run, a record with a status is created. Possible statuses: -- `Created` — the record has been created, but the action has not been run yet. -- `Unapproved` — the action is awaiting approval. -- `Running` — the action is running. -- `Failed` — the action finished with an error. -- `Update failed` — the action completed, but updating the entity's parameters failed. -- `Success` — the action completed successfully. -- `Retrying` — the action finished with an error and is being retried. -- `Warning` — the action completed, but part of the operations failed. For example, the CreateGitlabProjectVariables action could not create some of the variables. -- `Declined` — the action was not run because the entity status does not match the [execution conditions](#execution-conditions). -- `Skipped` — the action was not run because it was disabled in the process launch configuration. -- `Canceled` — the run was canceled by a user or because the process was stopped. +- `Created`: The record has been created, but the action has not been run yet. +- `Unapproved`: The action is awaiting approval. +- `Running`: The action is running. +- `Failed`: The action finished with an error. +- `Update failed`: The action completed, but updating the entity's properties failed. +- `Success`: The action completed successfully. +- `Retrying`: The action finished with an error and is being retried. +- `Warning`: The action completed, but part of the operations failed. + For example, the CreateGitlabProjectVariables action could not create some of the variables. +- `Declined`: The action was not run because the entity status does not match the [execution conditions](#execution-conditions). +- `Skipped`: The action was not run because it was disabled in the process launch configuration. +- `Canceled`: The run was canceled by a user or because the process was stopped. diff --git a/content/documentation/admin/actions/overview.ru.md b/content/documentation/admin/actions/overview.ru.md index c725eaa4..af1e618b 100644 --- a/content/documentation/admin/actions/overview.ru.md +++ b/content/documentation/admin/actions/overview.ru.md @@ -4,26 +4,32 @@ description: Конфигурация действий в Deckhouse Development weight: 10 --- -Действия — это механизм Deckhouse Development Portal для запуска операций во внешних инфраструктурных системах и сервисах. С их помощью можно, например: +Действия — это механизм Deckhouse Development Portal для запуска операций во внешних инфраструктурных системах и сервисах. +С их помощью можно, например: -- создавать проекты, переменные, ветки, теги, релизы и запросы на слияние в [GitLab](../gitlab/); +- создавать проекты, переменные, ветки, теги, релизы и запросы на слияние (Merge Request) в [GitLab](../gitlab/); - создавать ресурсы в [Kubernetes](../kubernetes/) и получать их; - создавать секреты в [Deckhouse Stronghold и HashiCorp Vault](../vault/), а также клиентов в [Keycloak](../keycloak/); - создавать проекты в [SonarQube](../sonarqube/), продукты и проверки (engagement) в [DefectDojo](../defectdojo/), проекты в [CodeScoring](../codescoring/) и репозитории, роли, пользователей и привилегии в [Nexus Repository](../nexus/); - создавать топики и ACL в [Apache Kafka](../kafka/); - выполнять вспомогательные действия для отладки и управления выполнением процессов (например, [Debug](../debug/) и [Wait](../wait/)). -Действие можно привязать к одному или нескольким ресурсам. После этого его можно запускать для любой сущности этих ресурсов. +Действие можно привязать к одному или нескольким ресурсам. +После этого его можно запускать для любой сущности этих ресурсов. -Действие, которое используется в задачах процессов, удалить нельзя: портал отвечает ошибкой `409` со списком таких процессов. Чтобы удалить действие, сначала уберите его из задач этих процессов. +Действие, которое используется в задачах процессов, удалить нельзя. +Портал отвечает ошибкой `409` со списком таких процессов. +Чтобы удалить действие, сначала уберите его из задач этих процессов. ## Конфигурация действия +Действие настраивается на нескольких вкладках, которые описаны ниже. + ### Основная информация При создании или редактировании действия укажите основную информацию: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | ------------------- | -------------- | ------------------------------------------------------------------------------------------- | | Название | Да | Произвольное название действия | | Идентификатор | Да | Идентификатор действия. Генерируется автоматически из названия | @@ -36,38 +42,45 @@ weight: 10 ### Конфигурация запроса -#### Тип действия +Конфигурация запроса определяет, как выполняется действие и какие данные оно отправляет. -Действие может быть следующих типов: +#### Тип действия -- «Встроенное (BuiltIn)» — логика выполнения действия описана внутри портала. Для встроенных действий необходимо выбрать один из преднастроенных бэкендов. -- «Вебхук (Webhook)» — логика выполнения действия полностью настраивается пользователем. +Действие может быть встроенным или вебхуком. +У встроенного действия («Встроенное (BuiltIn)») логика выполнения описана внутри портала. +Для встроенного действия выберите один из преднастроенных бэкендов. +У вебхук-действия («Вебхук (Webhook)») логика выполнения полностью настраивается пользователем. #### Параметры перезапуска -Если выполнение действия завершается с ошибкой, портал может автоматически выполнить повторные попытки. Настройте их в разделе «Параметры перезапуска»: +Если выполнение действия завершается с ошибкой, портал может автоматически выполнить повторные попытки. +Настройте их в разделе «Параметры перезапуска»: -| Поле | Описание | +| Название | Описание | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | | Количество перезапусков | Сколько раз повторять выполнение после ошибки. `0` — одна попытка без перезапусков | | Базовая задержка (сек.) | Задержка в секундах перед первым перезапуском. Перед каждой следующей попыткой пауза удваивается (экспоненциальная задержка) | #### Формат тела запроса -Для вебхук-действий доступен выбор формата отправки тела запроса: - -- JSON (по умолчанию) — тело запроса отправляется в формате JSON с заголовком `Content-Type: application/json`. -- «Form URL Encoded» — тело запроса отправляется в формате `application/x-www-form-urlencoded`. +Для вебхук-действий доступен выбор формата отправки тела запроса. +По умолчанию тело запроса отправляется в формате JSON с заголовком `Content-Type: application/json`. +В формате «Form URL Encoded» тело запроса отправляется в формате `application/x-www-form-urlencoded`. {{< alert level="info" >}} -При выборе формата «Form URL Encoded» тело запроса должно содержать только плоские пары «ключ — значение». Вложенные структуры и массивы в этом формате не поддерживаются. +При выборе формата «Form URL Encoded» тело запроса должно содержать только плоские пары «ключ — значение». +Вложенные структуры и массивы в этом формате не поддерживаются. {{< /alert >}} -Если тело запроса пустое, вебхук отправляет запрос без тела и без заголовка `Content-Type`. Так настраиваются запросы `GET` и `DELETE`. +Если тело запроса пустое, вебхук отправляет запрос без тела и без заголовка `Content-Type`. +Так настраиваются запросы `GET` и `DELETE`. -Вебхук-действие выполняется успешно, только если внешняя система вернула код ответа `2xx`. Перенаправление с заголовком `Location` портал выполняет сам и проверяет код итогового ответа. Ответ `3xx` без перенаправления, `4xx` и `5xx` завершают действие ошибкой. +Вебхук-действие выполняется успешно, только если внешняя система вернула код ответа `2xx`. +Перенаправление с заголовком `Location` портал выполняет сам и проверяет код итогового ответа. +Ответ `3xx` без перенаправления, `4xx` и `5xx` завершают действие ошибкой. -Если внешняя система вернула код ответа с ошибкой, тело ответа сохраняется в ответе действия: JSON — как объект, остальное — в поле `raw_body`. Текст ошибки действия имеет вид `unexpected status code: <код>, response: <тело ответа>`, тело ответа обрезается до 8192 байт. +Если внешняя система вернула код ответа с ошибкой, тело ответа сохраняется в ответе действия: JSON — как объект, остальное — в поле `raw_body`. +Текст ошибки действия имеет вид `unexpected status code: <код>, response: <тело ответа>`, тело ответа обрезается до 8192 байт. Пример: @@ -87,15 +100,19 @@ token: {{ .credentials.token }} - HTTP-заголовки ответа; - тело ответа. -При включённой опции все эти данные записываются в лог выполнения действия. При выключённой опции логирование выполняется в стандартном режиме. +При включённой опции все эти данные записываются в лог выполнения действия. +При выключённой опции логирование выполняется в стандартном режиме. {{< alert level="warning" >}} -Включение расширенного логирования может привести к записи конфиденциальной информации (токены, пароли и т. д.) в логи. Используйте эту опцию с осторожностью и только при необходимости отладки. +Включение расширенного логирования может привести к записи конфиденциальной информации (токены, пароли и т. д.) в логи. +Используйте эту опцию с осторожностью и только при необходимости отладки. {{< /alert >}} #### Тело запроса -Каждое действие отправляет HTTP-запрос на встроенный бэкенд или на URL вебхука бэкенда. Обычно запрос включает тело запроса (`body`), в котором описывается, что именно будет отправлено. Тело запроса задаётся в YAML. +Каждое действие отправляет HTTP-запрос на встроенный бэкенд или на URL вебхука бэкенда. +Обычно запрос включает тело запроса (`body`), в котором описывается, что именно будет отправлено. +Тело запроса задаётся в YAML. В тело запроса можно подставлять значения параметров из пользовательской формы с помощью шаблонов [Go template](https://pkg.go.dev/text/template). @@ -111,37 +128,48 @@ project_id: {{ .property.project_id }} ### Пользовательская форма +Пользовательская форма определяет параметры, которые пользователь заполняет при запуске действия. + #### Параметры -В разделе «Пользовательская форма» указываются параметры, доступные пользователю для заполнения при запуске действия. Типы параметров описаны в разделе [«Параметры»](../../user/properties/). +В разделе «Пользовательская форма» указываются параметры, доступные пользователю для заполнения при запуске действия. +Типы параметров описаны в разделе [«Параметры»](../../user/properties/). Для каждого параметра доступны опции: -- «Редактируемый» — позволяет изменить значение параметра при запуске действия. Если опция выключена, значение изменить нельзя. +- «Редактируемый» — позволяет изменить значение параметра при запуске действия. + Если опция выключена, значение изменить нельзя. - «Обязательный» — требует указания значения при запуске действия. - «Скрытый» — параметр не отображается в пользовательской форме при запуске действия. Для каждого параметра можно задать значение по умолчанию, которое будет подставляться в форму при запуске. -Действие принимает только параметры, объявленные в пользовательской форме. Если при запуске, например из процесса или через API, передан параметр, которого нет в форме, запуск завершается ошибкой `action "" does not declare property `. +Действие принимает только параметры, объявленные в пользовательской форме. +Если при запуске, например из процесса или через API, передан параметр, которого нет в форме, запуск завершается ошибкой `action "" does not declare property `. {{< alert level="info" >}} -Задайте значение по умолчанию для нередактируемых и скрытых параметров: при запуске действия пользователь не сможет их изменить. +Задайте значение по умолчанию для нередактируемых и скрытых параметров, поскольку при запуске действия пользователь не сможет их изменить. {{< /alert >}} -Описание параметра отображается при запуске действия по кнопке со значком «info». Заполните описание: оно помогает понять назначение параметра и снижает риск ошибок при запуске. +Описание параметра отображается при запуске действия по кнопке со значком «info». +Заполните описание. Оно помогает понять назначение параметра и снижает риск ошибок при запуске. -В значениях параметров можно использовать шаблонные функции [Go template](https://pkg.go.dev/text/template). Например, выражение `{{ .entity.name }}` в значении параметра означает, что при запуске действия будет подставлено название сущности, для которой оно запускается. +В значениях параметров можно использовать шаблонные функции [Go template](https://pkg.go.dev/text/template). +Например, выражение `{{ .entity.name }}` в значении параметра означает, что при запуске действия будет подставлено название сущности, для которой оно запускается. #### Условия параметров -Параметры могут автоматически скрываться или отображаться в пользовательской форме в зависимости от значения параметра типа `Boolean`. Настройка выполняется в разделе «Условия параметров», где задаются правила показа или скрытия для выбранных параметров. +Параметры могут автоматически скрываться или отображаться в пользовательской форме в зависимости от значения параметра типа `Boolean`. +Настройка выполняется в разделе «Условия параметров», где задаются правила показа или скрытия для выбранных параметров. ### Обновление +После успешного выполнения действие может обновлять сущности, связи, учётные данные и хранилище процесса. + #### Контексты шаблонизации -Все обновления выполняются только после успешного завершения действия. В Go-шаблонах доступны следующие контексты шаблонизации: +Все обновления выполняются только после успешного завершения действия. +В Go-шаблонах доступны следующие контексты шаблонизации: | Контекст | Описание | Пример | | ----------- | ------------------------------------------------------------------------ | ------------------------------------ | @@ -153,13 +181,14 @@ project_id: {{ .property.project_id }} | `.global` | Глобальные переменные (идентификатор набора, затем ключ) | `{{ .global.myGroup.apiUrl }}` | | `.team` | Переменные команды, выбранной при запуске | `{{ .team.token }}` | | `.store` | Переменные из хранилища процесса | `{{ .store.myKey }}` | -| `.context` | [Контекст запуска процесса](../processes/overview/#контекст-запуска), например данные окружения, выбранного на главной | `{{ .context.environment.slug }}` | +| `.context` | [Контекст запуска процесса](../processes/overview/#контекст-запуска), например данные окружения, выбранного на главной странице | `{{ .context.environment.slug }}` | #### Обновление параметров сущности -Чтобы включить обновление параметров, включите переключатель в заголовке раздела «Обновление параметров сущности». После этого портал применяет правила обновления и записывает значения в параметры сущности. +Чтобы включить обновление параметров, включите переключатель в заголовке раздела «Обновление параметров сущности». +После этого портал применяет правила обновления и записывает значения в параметры сущности. -| Поле | Описание | +| Название | Описание | | ------------------- | ------------------------------------------------------------------------ | | Источник | Go-шаблон значения | | Параметр сущности | Идентификатор параметра сущности в каталоге | @@ -175,16 +204,18 @@ project_id: {{ .property.project_id }} } ``` -Если после создания проекта в GitLab нужно сразу заполнить параметр сущности `repository_id`, укажите в правилах обновления: +Чтобы сразу после создания проекта в GitLab заполнить параметр сущности `repository_id`, укажите в правилах обновления: 1. Источник: `{{ .response.id }}`. 1. Параметр сущности: `repository_id`. #### Создание сущностей -Чтобы включить создание сущностей, включите переключатель в заголовке раздела «Создание сущностей». После этого портал автоматически создаёт новые сущности в выбранных ресурсах по заданным правилам. Правила задаются отдельно для каждого ресурса. +Чтобы включить создание сущностей, включите переключатель в заголовке раздела «Создание сущностей». +После этого портал автоматически создаёт новые сущности в выбранных ресурсах по заданным правилам. +Правила задаются отдельно для каждого ресурса. -| Поле | Описание | +| Название | Описание | | -------------------------------------- | --------------------------------------------------------------------------------------------- | | Владелец — инициатор запуска | Владельцем создаваемых сущностей становится пользователь, запустивший действие. Если инициатор неизвестен (запуск автоматизацией или вебхуком), владельцем становится пользователь из поля «Владелец создаваемых сущностей» | | Владелец создаваемых сущностей | Назначается владельцем всем сущностям, которые действие создаёт в каталоге | @@ -194,7 +225,8 @@ project_id: {{ .property.project_id }} | Источник (название) | Go-шаблон для названия создаваемой сущности | | Дополнительные правила | Сопоставление Go-шаблона значения с параметром сущности | -Идентификатор и название обязательны для каждой группы правил. Если в ресурсе уже есть сущность с таким идентификатором, создание пропускается. +Идентификатор и название обязательны для каждой группы правил. +Если в ресурсе уже есть сущность с таким идентификатором, создание пропускается. Например, при выполнении действия «Создание проекта в GitLab» в ответе может быть: @@ -216,9 +248,11 @@ project_id: {{ .property.project_id }} #### Удаление сущностей -Чтобы включить удаление сущностей, включите переключатель в заголовке раздела «Удаление сущностей». После этого портал автоматически удаляет сущности в выбранных ресурсах по заданным правилам. Правила задаются отдельно для каждого ресурса. +Чтобы включить удаление сущностей, включите переключатель в заголовке раздела «Удаление сущностей». +После этого портал автоматически удаляет сущности в выбранных ресурсах по заданным правилам. +Правила задаются отдельно для каждого ресурса. -| Поле | Описание | +| Название | Описание | | -------- | ----------------------------------------------------------------------------- | | Ресурс | Ресурс каталога, в котором находится удаляемая сущность | | Источник | Go-шаблон идентификатора сущности (например, `{{ .response.id }}`) | @@ -241,9 +275,11 @@ project_id: {{ .property.project_id }} #### Создание связей сущности -Чтобы включить создание связей, включите переключатель в заголовке раздела «Создание связей сущности». После этого портал автоматически создаёт новые связи для выбранной сущности по заданным правилам. Набор правил задаётся отдельно для каждого ресурса. +Чтобы включить создание связей, включите переключатель в заголовке раздела «Создание связей сущности». +После этого портал автоматически создаёт новые связи для выбранной сущности по заданным правилам. +Набор правил задаётся отдельно для каждого ресурса. -| Поле | Описание | +| Название | Описание | | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Ресурс | Любой из двух ресурсов, участвующих в нужной связи ресурсов: по выбранному ресурсу загружается список связей, в которых он указан как родительский или как дочерний. Можно выбрать ресурс сущности, для которой запускается действие, или ресурс другой стороны связи — в списке будет одна и та же связь, если оба ресурса входят в неё | | Связь | Связь ресурсов в каталоге: в ней заданы родительский и дочерний ресурсы и роли сущностей при создании связи. По выбранной связи определяется, на какой стороне находится сущность запуска и какое из полей ниже задаёт идентификатор второй сущности из ответа действия | @@ -252,9 +288,11 @@ project_id: {{ .property.project_id }} #### Удаление связей сущности -Чтобы включить удаление связей, включите переключатель в заголовке раздела «Удаление связей сущности». После этого портал автоматически удаляет связи для выбранной сущности по заданным правилам. Набор правил задаётся отдельно для каждого ресурса. +Чтобы включить удаление связей, включите переключатель в заголовке раздела «Удаление связей сущности». +После этого портал автоматически удаляет связи для выбранной сущности по заданным правилам. +Набор правил задаётся отдельно для каждого ресурса. -| Поле | Описание | +| Название | Описание | | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Ресурс | Любой из двух ресурсов, участвующих в нужной связи ресурсов: по выбранному ресурсу загружается список связей, в которых он указан как родительский или как дочерний. Можно выбрать ресурс сущности, для которой запускается действие, или ресурс другой стороны связи — в списке будет одна и та же связь, если оба ресурса входят в неё | | Связь | Связь ресурсов в каталоге: в ней заданы родительский и дочерний ресурсы и роли сущностей при удалении связи. По выбранной связи определяется, на какой стороне находится сущность запуска и какое из полей ниже задаёт идентификатор второй сущности из ответа действия | @@ -265,9 +303,10 @@ project_id: {{ .property.project_id }} #### Обновление учётных данных пользователя -Чтобы включить обновление учётных данных, включите переключатель в заголовке раздела «Обновление учётных данных пользователя». После этого действие автоматически обновляет учётные данные пользователя в соответствии с правилами обновления. +Чтобы включить обновление учётных данных, включите переключатель в заголовке раздела «Обновление учётных данных пользователя». +После этого действие автоматически обновляет учётные данные пользователя в соответствии с правилами обновления. -| Поле | Описание | +| Название | Описание | | ------------------- | ---------------------------------- | | Источник | Go-шаблон значения | | Тип учётных данных | Тип обновляемых учётных данных | @@ -291,16 +330,18 @@ project_id: {{ .property.project_id }} #### Обновление хранилища процесса -Правила из раздела «Обновление хранилища процесса» применяются только при выполнении действия в рамках процесса: после успешного завершения действия значения записываются в хранилище запуска по заданным правилам, в порядке списка. +Правила из раздела «Обновление хранилища процесса» применяются только при выполнении действия в рамках процесса. +После успешного завершения действия значения записываются в хранилище запуска по заданным правилам, в порядке списка. -| Поле | Описание | +| Название | Описание | | -------- | ----------------------------------------------------------------------------------------------------------------- | | Условие | Необязательный Go-шаблон; пустое — правило всегда выполняется. Результат рендеринга: `true`, `false`, `1` или `0` | | Операция | Записать строку, Записать JSON, Добавить строку, Добавить JSON, Слить JSON (поверхностно), Удалить | | Цель | Dot-path в хранилище без ведущей точки, например `deploy.job_id` или `notification.items` | | Источник | Go-шаблон значения | -Другие действия и элементы процесса читают данные через `{{ .store.<путь> }}`. Внутри цикла в шаблонах доступен контекст `{{ .store._loop.* }}`. +Другие действия и элементы процесса читают данные через `{{ .store. }}`. +Внутри цикла в шаблонах доступен контекст `{{ .store._loop.* }}`. Если правил нет (список пустой), при выполнении действия в процессе в хранилище ничего не записывается. @@ -310,15 +351,23 @@ project_id: {{ .property.project_id }} Синхронизация источников данных после действия переносит в каталог объект, который действие создало или удалило во внешней системе, без ожидания синхронизации по расписанию. -Чтобы включить синхронизацию, включите переключатель в заголовке раздела «Синхронизация источников данных» и выберите источники в поле «Источники данных». Выберите источники, которые загружают в каталог объект, созданный или удалённый действием. Если переключатель включён, выберите хотя бы один источник данных. +Чтобы включить синхронизацию, включите переключатель в заголовке раздела «Синхронизация источников данных» и выберите источники в поле «Источники данных». +Выберите источники, которые загружают в каталог объект, созданный или удалённый действием. +Если переключатель включён, выберите хотя бы один источник данных. -Синхронизация запускается после успешного выполнения действия и применения правил обновления. Синхронизация выполняется в фоне: действие не ожидает её завершения и не завершается ошибкой, если синхронизация не удалась. Удалённые источники данных пропускаются. +Синхронизация запускается после успешного выполнения действия и применения правил обновления. +Синхронизация выполняется в фоне. +Действие не ожидает её завершения и не завершается ошибкой, если синхронизация не удалась. +Удалённые источники данных пропускаются. ### Безопасность +Настройки безопасности ограничивают, когда и кем может быть запущено действие. + #### Условия выполнения -Действие будет выполнено, только если статус сущности соответствует одному из выбранных значений в поле статусов. Если ограничения не заданы, это условие не применяется. +Действие будет выполнено, только если статус сущности соответствует одному из выбранных значений в поле статусов. +Если ограничения не заданы, это условие не применяется. #### Маскирование полей действия @@ -332,24 +381,25 @@ project_id: {{ .property.project_id }} #### Временный ответ -Для каждого действия можно включить опцию «Временный ответ». Она позволяет ограничить доступ к результату выполнения действия и скрыть его от других пользователей. - -Если опция включена, то после успешного выполнения действия ответ: +Для каждого действия можно включить опцию «Временный ответ». +Она позволяет ограничить доступ к результату выполнения действия и скрыть его от других пользователей. -- сохраняется как временный и отображается только пользователю, который запустил действие; -- удаляется из обычного поля ответа, чтобы он не был доступен другим пользователям. +Если опция включена, то после успешного выполнения действия ответ сохраняется как временный и отображается только пользователю, который запустил действие. +Из обычного поля ответа он удаляется, чтобы не был доступен другим пользователям. Другие пользователи вместо содержимого ответа будут видеть только зашифрованный временный ответ. Инициатор действия может удалить временный ответ вручную. {{< alert level="info" >}} -Временный ответ доступен только инициатору действия. Остальные пользователи не могут просмотреть его содержимое и не могут удалить его. +Временный ответ доступен только инициатору действия. +Остальные пользователи не могут просмотреть его содержимое и не могут удалить его. {{< /alert >}} #### Подтверждение -Для действия можно включить обязательное подтверждение и задать количество подтверждающих. В этом случае действие не будет запущено, пока не будет получено указанное число подтверждений от заданных пользователей. +Для действия можно включить обязательное подтверждение и задать количество подтверждающих. +В этом случае действие не будет запущено, пока не будет получено указанное число подтверждений от заданных пользователей. Текущее число подтверждений и список пользователей, от которых ожидается подтверждение, отображаются в таблице запусков действий для соответствующей сущности. @@ -357,13 +407,17 @@ project_id: {{ .property.project_id }} #### Уведомления о подтверждении -При включённом подтверждении можно включить уведомления и указать способ отправки. Если выбрана отправка на URL, указывается адрес вебхука, при необходимости отключается проверка TLS-сертификата сервера и добавляются дополнительные HTTP-заголовки запроса. +При включённом подтверждении можно включить уведомления и указать способ отправки. +Если выбрана отправка на URL, указывается адрес вебхука, при необходимости отключается проверка TLS-сертификата сервера и добавляются дополнительные HTTP-заголовки запроса. ### Авторизация +Настройки авторизации определяют, какие внешние сервисы и учётные данные использует действие. + #### Использовать внешний сервис -Выбор внешних сервисов, для которых может выполняться действие. В случае добавления нескольких внешних сервисов конкретный можно будет выбрать непосредственно при запуске. +Выбор внешних сервисов, для которых может выполняться действие. +В случае добавления нескольких внешних сервисов конкретный можно будет выбрать непосредственно при запуске. #### URL и HTTP-заголовки @@ -371,19 +425,22 @@ project_id: {{ .property.project_id }} В URL вебхук-действия поддерживаются Go-шаблоны, в том числе условия `{{ if }}`. -В заголовках поддерживаются Go-шаблоны вида `{{ .credentials.<идентификатор типа учётных данных> }}` для подстановки учётных данных пользователя. +В заголовках поддерживаются Go-шаблоны вида `{{ .credentials. }}` для подстановки учётных данных пользователя. #### Выбрать учётную запись для запуска -По умолчанию доступ к внешним инфраструктурным сервисам выполняется с использованием учётных данных пользователя, который запустил действие. Чтобы действие выполнялось от имени конкретной учётной записи, включите опцию «Выбрать учётную запись для запуска» и выберите учётную запись в поле «Учётная запись для запуска». +По умолчанию доступ к внешним инфраструктурным сервисам выполняется с использованием учётных данных пользователя, который запустил действие. +Чтобы действие выполнялось от имени конкретной учётной записи, включите опцию «Выбрать учётную запись для запуска» и выберите учётную запись в поле «Учётная запись для запуска». Для действий, запускаемых как события автоматизации, указание учётной записи для запуска является обязательным. #### Учётные данные -Для встроенных действий портал заранее определяет набор требуемых учётных данных. Их идентификаторы подгружаются при выборе встроенного бэкенда. Для каждого идентификатора необходимо выбрать тип учётных данных, который будет использоваться. +Для встроенных действий портал заранее определяет набор требуемых учётных данных. +Их идентификаторы подгружаются при выборе встроенного бэкенда. +Для каждого идентификатора выберите тип учётных данных. -Для вебхук-действий обращение к учётным данным возможно в теле запроса с использованием конструкции `{{ .credentials.<идентификатор типа учётных данных> }}`. +Для вебхук-действий обращение к учётным данным возможно в теле запроса с использованием конструкции `{{ .credentials. }}`. #### HTTP-метод @@ -391,27 +448,37 @@ project_id: {{ .property.project_id }} ## Запуски действий +Портал сохраняет сведения о каждом запуске действия и его лог. + ### Записи запусков действий -При каждом запуске действия создаётся запись, содержащая инициатора, статус выполнения и подробный лог. Записи запусков для каждой сущности доступны на странице сущности на вкладке «Действия» в таблице «История выполнения». Если для действия требуется подтверждение, оно выполняется на этой же вкладке. +При каждом запуске действия создаётся запись, содержащая инициатора, статус выполнения и подробный лог. +Записи запусков для каждой сущности доступны на странице сущности на вкладке «Действия» в таблице «История выполнения». +Если для действия требуется подтверждение, оно выполняется на этой же вкладке. -Над таблицей отображается блок «Что можно запустить» со списком действий, доступных для сущности, и поиском по действиям. Недавно запускавшиеся действия и статус их последнего запуска также отображаются в [блоке «Запуск»](../../user/catalog/#блок-запуск) на вкладке «Обзор». -Записи в таблице группируются по статусам: «Все», «Активные», «Ожидающие подтверждения», «Созданные», «Успешные», «С проблемами», «Отменённые» и «Пропущенные». В раскрытой строке записи отображаются последние строки лога. +Над таблицей отображается блок «Что можно запустить» со списком действий, доступных для сущности, и поиском по действиям. +Недавно запускавшиеся действия и статус их последнего запуска также отображаются в [блоке «Запуск»](../../user/catalog/#блок-запуск) на вкладке «Обзор». +Записи в таблице группируются по статусам: «Все», «Активные», «Ожидающие подтверждения», «Созданные», «Успешные», «С проблемами», «Отменённые» и «Пропущенные». +В раскрытой строке записи отображаются последние строки лога. -Запись о запуске можно удалить или перезапустить действие. При перезапуске создаётся новая запись. Разрешения, которые нужны для просмотра записей, их отмены, перезапуска и удаления, описаны в разделе [«Записи запусков действий»](../../security/rbac/#записи-запусков-действий) ролевой модели. +Запись о запуске можно удалить или перезапустить действие. +При перезапуске создаётся новая запись. +Разрешения, которые нужны для просмотра записей, их отмены, перезапуска и удаления, описаны в разделе [«Записи запусков действий»](../../security/rbac/#записи-запусков-действий) ролевой модели. ### Логирование запусков Для каждого запуска действия в базе данных создаётся запись, содержащая полный лог выполнения. -Параметр модуля `actions.logging.enabled` управляет выводом логов запуска в `stdout`: при значении `true` логи выводятся, при `false` (по умолчанию) не выводятся. +Параметр модуля `actions.logging.enabled` управляет выводом логов запуска в `stdout`. +При значении `true` логи выводятся, при `false` (по умолчанию) не выводятся. Задайте параметр в секции `settings` ModuleConfig `development-platform` или в веб-интерфейсе Deckhouse Platform. {{< alert level="info" >}} Записи с полным логом запуска в базе данных создаются независимо от значения `actions.logging.enabled`. {{< /alert >}} -Минимальный уровень сообщений в логе запуска, который отображается в веб-интерфейсе, задаёт параметр модуля `logger.executionLevel`. По умолчанию — `info`: сообщения уровня `debug` не отображаются. +Минимальный уровень сообщений в логе запуска, который отображается в веб-интерфейсе, задаёт параметр модуля `logger.executionLevel`. +По умолчанию используется уровень `info`, и сообщения уровня `debug` не отображаются. ### Статусы запуска действий @@ -424,7 +491,8 @@ project_id: {{ .property.project_id }} - `Update failed` — действие выполнено, но обновить параметры сущности не удалось. - `Success` — действие выполнено успешно. - `Retrying` — действие завершилось с ошибкой, выполняется повторная попытка запуска. -- `Warning` — действие выполнено, но часть операций завершилась с ошибкой. Например, действие CreateGitlabProjectVariables не смогло создать часть переменных. +- `Warning` — действие выполнено, но часть операций завершилась с ошибкой. + Например, действие CreateGitlabProjectVariables не смогло создать часть переменных. - `Declined` — действие не запущено, так как статус сущности не соответствует [условиям выполнения](#условия-выполнения). - `Skipped` — действие не запущено, так как оно выключено в конфигурации запуска процесса или процесс завершился успешно, не дойдя до задачи, например по другой ветке эксклюзивного шлюза. - `Canceled` — запуск отменён пользователем или из-за остановки процесса. diff --git a/content/documentation/admin/actions/sonarqube/createsonarqubeproject.md b/content/documentation/admin/actions/sonarqube/createsonarqubeproject.md index 7ab790ca..85053563 100644 --- a/content/documentation/admin/actions/sonarqube/createsonarqubeproject.md +++ b/content/documentation/admin/actions/sonarqube/createsonarqubeproject.md @@ -8,9 +8,12 @@ Running this action requires a SonarQube User Token generated by the user on who {{< /alert >}} CreateSonarqubeProject — creates a new project in SonarQube. -The action uses the SonarQube Web API to create a project with the specified parameters, such as the project key, project name, main branch, new code definition parameters, and project visibility. Authentication is performed using a SonarQube token, which must be provided in the credentials. +The action uses the SonarQube Web API to create a project with the specified parameters, such as the project key, project name, main branch, new code definition parameters, and project visibility. +Authentication is performed using a SonarQube token, which must be provided in the credentials. -### Request example +## Request example + +Example of the action request body: ```yaml project: example-project @@ -21,13 +24,15 @@ newCodeDefinitionValue: '30' visibility: public ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | Default value | | ------------------------- | -------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------- | -| project | Yes | Unique project identifier (Project Key) in SonarQube | - | - | -| name | Yes | Project name displayed in the SonarQube interface | - | - | -| mainBranch | No | Name of the project's main branch | - | master | -| newCodeDefinitionType | No | Method for defining "new code" | PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH | - | -| newCodeDefinitionValue | No | Value for the "new code" definition (e.g., number of days, if the type is NUMBER_OF_DAYS) | - | - | -| visibility | No | Project visibility | private, public | private | +| `project` | Yes | Unique project identifier (Project Key) in SonarQube | — | — | +| `name` | Yes | Project name displayed in the SonarQube interface | — | — | +| `mainBranch` | No | Name of the project's main branch | — | `master` | +| `newCodeDefinitionType` | No | Method for defining "new code" | PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH | — | +| `newCodeDefinitionValue` | No | Value for the "new code" definition (for example, the number of days if the type is `NUMBER_OF_DAYS`) | — | — | +| `visibility` | No | Project visibility | `private`, `public` | `private` | diff --git a/content/documentation/admin/actions/sonarqube/createsonarqubeproject.ru.md b/content/documentation/admin/actions/sonarqube/createsonarqubeproject.ru.md index f7c2b928..0d08c50d 100644 --- a/content/documentation/admin/actions/sonarqube/createsonarqubeproject.ru.md +++ b/content/documentation/admin/actions/sonarqube/createsonarqubeproject.ru.md @@ -4,13 +4,16 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена SonarQube с типом User Token, сгенерированного пользователем, от имени которого будет запускаться выполнение действия. +Для выполнения действий требуется токен SonarQube с типом User Token, сгенерированный пользователем, от имени которого выполняется действие. {{< /alert >}} CreateSonarqubeProject — создаёт новый проект в SonarQube. -Действие использует SonarQube Web API для создания проекта с указанными параметрами, такими как ключ (project key), название проекта, главная ветка, параметры определения нового кода (new code definition) и видимость проекта. Аутентификация осуществляется с использованием токена SonarQube, который должен быть передан в учётных данных. +Действие использует SonarQube Web API для создания проекта с указанными параметрами, такими как ключ (project key), название проекта, главная страница ветка, параметры определения нового кода (new code definition) и видимость проекта. +Аутентификация осуществляется с использованием токена SonarQube, который должен быть передан в учётных данных. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project: example-project @@ -21,13 +24,15 @@ newCodeDefinitionValue: '30' visibility: public ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | ------------------------- | ---------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------- | -| project | Да | Уникальный идентификатор проекта (Project Key) в SonarQube | - | - | -| name | Да | Название проекта, отображаемое в интерфейсе SonarQube | - | - | -| mainBranch | Нет | Название главной ветки проекта | - | master | -| newCodeDefinitionType | Нет | Метод определения «нового кода» | PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH | - | -| newCodeDefinitionValue | Нет | Значение для определения «нового кода» (например, количество дней, если тип - NUMBER_OF_DAYS) | - | - | -| visibility | Нет | Видимость проекта | private, public | private | +| `project` | Да | Уникальный идентификатор проекта (Project Key) в SonarQube | — | — | +| `name` | Да | Название проекта, отображаемое в интерфейсе SonarQube | — | — | +| `mainBranch` | Нет | Название главной страницы ветки проекта | — | `master` | +| `newCodeDefinitionType` | Нет | Метод определения «нового кода» | PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH | — | +| `newCodeDefinitionValue` | Нет | Значение для определения «нового кода» (например, количество дней, если тип - NUMBER_OF_DAYS) | — | — | +| `visibility` | Нет | Видимость проекта | `private`, `public` | `private` | diff --git a/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.md b/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.md index 0e7f8033..08722e95 100644 --- a/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.md +++ b/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.md @@ -9,14 +9,18 @@ Running this action requires a SonarQube User Token generated by the user on who DeleteSonarqubeProject — deletes a project from SonarQube. -### Request example +## Request example + +Example of the action request body: ```yaml project: example-project ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | ------------------ | -------- | -------------------------------------------------------------------------------- | ------------------------ | -| project | Yes | Unique identifier (Project Key) of the project to delete | - | +| `project` | Yes | Unique identifier (Project Key) of the project to delete | — | diff --git a/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.ru.md b/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.ru.md index 7818aa03..b4908409 100644 --- a/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.ru.md +++ b/content/documentation/admin/actions/sonarqube/deletesonarqubeproject.ru.md @@ -4,19 +4,23 @@ weight: 20 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена SonarQube с типом User Token, сгенерированного пользователем, от имени которого будет запускаться выполнение действия. +Для выполнения действий требуется токен SonarQube с типом User Token, сгенерированный пользователем, от имени которого выполняется действие. {{< /alert >}} DeleteSonarqubeProject — удаляет проект из SonarQube. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml project: example-project ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | ------------------ | ---------------- | ---------------------------------------------------------------------------- | ------------------------ | -| project | Да | Уникальный идентификатор (Project Key) проекта, который необходимо удалить | - | +| `project` | Да | Уникальный идентификатор (Project Key) проекта, который необходимо удалить | — | diff --git a/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.md b/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.md index 32e35b62..dd19cdeb 100644 --- a/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.md +++ b/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.md @@ -9,7 +9,9 @@ Running this action requires a SonarQube User Token generated by the user on who DeleteSonarqubeProjects — deletes one or more projects from SonarQube. -### Request example +## Request example + +Example of the action request body: ```yaml analyzedBefore: 2017-10-19T13:00:00+0200 @@ -19,12 +21,14 @@ q: example qualifiers: TRK ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | Example values | | -------------------- | -------- | ------------------------------------------------------------------------------------- | -------------------------------- | --------------------------------------- | -| analyzedBefore | No | Delete all projects whose last analysis is older than a specific date | - | 2017-10-19, 2017-10-19T13:00:00+0200 | -| onProvisionedOnly | No | Filter projects by the `onProvisionedOnly` value | true, false, yes, no | - | -| projects | No | List of project keys to delete | - | my_project, another_project | -| q | No | Delete all projects whose name or key contains the specified substring | - | example | -| qualifiers | No | Filter projects by the specified qualifiers | TRK, VW, APP | | +| `analyzedBefore` | No | Delete all projects whose last analysis is older than a specific date | — | 2017-10-19, 2017-10-19T13:00:00+0200 | +| `onProvisionedOnly` | No | Filter projects by the `onProvisionedOnly` value | `true`, `false`, `yes`, `no` | — | +| `projects` | No | List of project keys to delete | — | `my_project`, `another_project` | +| `q` | No | Delete all projects whose name or key contains the specified substring | — | `example` | +| `qualifiers` | No | Filter projects by the specified qualifiers | TRK, VW, APP | — | diff --git a/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.ru.md b/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.ru.md index 10da2ebd..cc50575a 100644 --- a/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.ru.md +++ b/content/documentation/admin/actions/sonarqube/deletesonarqubeprojects.ru.md @@ -4,12 +4,14 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие токена SonarQube с типом User Token, сгенерированного пользователем, от имени которого будет запускаться выполнение действия. +Для выполнения действий требуется токен SonarQube с типом User Token, сгенерированный пользователем, от имени которого выполняется действие. {{< /alert >}} DeleteSonarqubeProjects — удаляет один или несколько проектов из SonarQube. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml analyzedBefore: 2017-10-19T13:00:00+0200 @@ -19,12 +21,14 @@ q: example qualifiers: TRK ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | Примеры значений | | -------------------- | ---------------- | --------------------------------------------------------------------------------- | ------------------------------- | --------------------------------------- | -| analyzedBefore | Нет | Удалить все проекты, в которых последний анализ старше определённой даты | - | 2017-10-19, 2017-10-19T13:00:00+0200 | -| onProvisionedOnly | Нет | Фильтровать проекты по значению `onProvisionedOnly` | true, false, yes, no | - | -| projects | Нет | Список ключей проектов, которые необходимо удалить | - | my_project, another_project | -| q | Нет | Удалить все проекты, в названии или ключе которых содержится заданная подстрока | - | example | -| qualifiers | Нет | Фильтровать проекты по указанным квалификаторам | TRK, VW, APP | | +| `analyzedBefore` | Нет | Удалить все проекты, в которых последний анализ старше определённой даты | — | 2017-10-19, 2017-10-19T13:00:00+0200 | +| `onProvisionedOnly` | Нет | Фильтровать проекты по значению `onProvisionedOnly` | `true`, `false`, `yes`, `no` | — | +| `projects` | Нет | Список ключей проектов, которые необходимо удалить | — | `my_project`, `another_project` | +| `q` | Нет | Удалить все проекты, в названии или ключе которых содержится заданная подстрока | — | `example` | +| `qualifiers` | Нет | Фильтровать проекты по указанным квалификаторам | TRK, VW, APP | — | diff --git a/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.md b/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.md index 1f44ded4..573904ce 100644 --- a/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.md +++ b/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.md @@ -9,7 +9,9 @@ Running this action requires a Vault token with permission to create or update K CreateVaultKubernetesAuthRole — creates or updates a Kubernetes authentication role in HashiCorp Vault. -### Request example +## Request example + +Example of the action request body: ```yaml mountPath: kubernetes @@ -26,30 +28,32 @@ optional: - default ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | -------------------------------------- | -------- | ------------------------------------------------------------------------------------- | -| mountPath | Yes | Mount path of the Kubernetes auth backend in Vault (e.g., kubernetes) | -| name | Yes | Name of the role to create in Vault | -| bound_service_account_names | Yes | List of service account names allowed to access via this role | -| bound_service_account_namespaces | Yes | List of namespaces allowed to access via this role | -| optional | No | Additional role parameters (listed in the table below) | +| `mountPath` | Yes | Mount path of the Kubernetes auth backend in Vault (for example, `kubernetes`) | +| `name` | Yes | Name of the role to create in Vault | +| `bound_service_account_names` | Yes | List of service account names allowed to access via this role | +| `bound_service_account_namespaces` | Yes | List of namespaces allowed to access via this role | +| `optional` | No | Additional role parameters (listed in the table below) | Supported values for `optional`: -| Field | Type | Description | +| Name | Type | Description | | ------------------------- | --------------- | ----------------------------------------------------------------------- | -| token_ttl | string | Time-to-live (TTL) of the token issued at login | -| token_max_ttl | string | Maximum TTL of the token | -| token_policies | []string | Additional policies assigned at login | -| audience | string | Value of the JWT audience (aud) that Vault expects from the token | -| token_period | string | Token renewal period | -| token_explicit_max_ttl | string | Explicit upper bound on the token's TTL | -| token_num_uses | int | Limit on the number of times the token can be used | -| token_type | string | Type of token issued (e.g., service, batch) | -| alias_name_source | string | Source of the alias name for identity | -| token_no_default_policy | bool | Exclude the default policy from the token | -| token_bound_cidrs | []string | Restriction on the CIDR ranges from which the issued token can be used | +| `token_ttl` | `string` | Time-to-live (TTL) of the token issued at login | +| `token_max_ttl` | `string` | Maximum TTL of the token | +| `token_policies` | []string | Additional policies assigned at login | +| `audience` | `string` | Value of the JWT audience (aud) that Vault expects from the token | +| `token_period` | `string` | Token renewal period | +| `token_explicit_max_ttl` | `string` | Explicit upper bound on the token's TTL | +| `token_num_uses` | `int` | Limit on the number of times the token can be used | +| `token_type` | `string` | Type of token issued (for example, `service` or `batch`) | +| `alias_name_source` | `string` | Source of the alias name for identity | +| `token_no_default_policy` | `bool` | Exclude the default policy from the token | +| `token_bound_cidrs` | []string | Restriction on the CIDR ranges from which the issued token can be used | The full list of supported parameters is provided in the official [HashiCorp Vault documentation](https://developer.hashicorp.com/vault/docs/auth/kubernetes#parameters). diff --git a/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.ru.md b/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.ru.md index be802a67..c3ff99b6 100644 --- a/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.ru.md +++ b/content/documentation/admin/actions/vault/createvaultkubernetesauthrole.ru.md @@ -4,12 +4,14 @@ weight: 30 --- {{< alert level="info" >}} -Для выполнения действия необходимо наличие Vault-токена, обладающего правами на создание/обновление ролей Kubernetes auth backend. +Для выполнения действия требуется Vault-токен с правами на создание и обновление ролей Kubernetes auth backend. {{< /alert >}} CreateVaultKubernetesAuthRole — создаёт или обновляет роль аутентификации Kubernetes в HashiCorp Vault. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml mountPath: kubernetes @@ -26,30 +28,32 @@ optional: - default ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | ------------------------------------- | ---------------- | ----------------------------------------------------------------------------------- | -| mountPath | Да | Путь монтирования Kubernetes auth backend в Vault (например, kubernetes) | -| name | Да | Название роли, которая создаётся в Vault | -| bound_service_account_names | Да | Список имён service account'ов, которым разрешён доступ через данную роль | -| bound_service_account_namespaces | Да | Список неймспейсов (namespaces), в которых разрешён доступ через данную роль | -| optional | Нет | Дополнительные параметры роли (приведены в следующей таблице) | +| `mountPath` | Да | Путь монтирования Kubernetes auth backend в Vault (например, kubernetes) | +| `name` | Да | Название роли, которая создаётся в Vault | +| `bound_service_account_names` | Да | Список имён service account'ов, которым разрешён доступ через данную роль | +| `bound_service_account_namespaces` | Да | Список неймспейсов (namespaces), в которых разрешён доступ через данную роль | +| `optional` | Нет | Дополнительные параметры роли (приведены в следующей таблице) | Поддерживаемые значения в optional: -| Поле | Тип | Описание | +| Название | Тип | Описание | | ------------------------- | --------------- | ----------------------------------------------------------------------- | -| token_ttl | string | Время жизни (TTL) токена, выданного при логине | -| token_max_ttl | string | Максимальное TTL токена | -| token_policies | []string | Дополнительные политики, назначаемые при логине | -| audience | string | Значение JWT audience (aud), которое Vault ожидает от токена | -| token_period | string | Периодичность выдачи токена | -| token_explicit_max_ttl | string | Явный верхний предел TTL токена | -| token_num_uses | int | Ограничение на количество использований токена | -| token_type | string | Тип выдаваемого токена (например, service, batch) | -| alias_name_source | string | Источник alias name для identity | -| token_no_default_policy | bool | Исключение default policy из состава токена | -| token_bound_cidrs | []string | Ограничение CIDR-диапазонов, откуда можно использовать выданный токен | +| `token_ttl` | `string` | Время жизни (TTL) токена, выданного при логине | +| `token_max_ttl` | `string` | Максимальное TTL токена | +| `token_policies` | []string | Дополнительные политики, назначаемые при логине | +| `audience` | `string` | Значение JWT audience (aud), которое Vault ожидает от токена | +| `token_period` | `string` | Периодичность выдачи токена | +| `token_explicit_max_ttl` | `string` | Явный верхний предел TTL токена | +| `token_num_uses` | `int` | Ограничение на количество использований токена | +| `token_type` | `string` | Тип выдаваемого токена (например, service, batch) | +| `alias_name_source` | `string` | Источник alias name для identity | +| `token_no_default_policy` | `bool` | Исключение default policy из состава токена | +| `token_bound_cidrs` | []string | Ограничение CIDR-диапазонов, откуда можно использовать выданный токен | Полный список поддерживаемых параметров приведён в официальной документации [HashiCorp Vault](https://developer.hashicorp.com/vault/docs/auth/kubernetes#parameters). diff --git a/content/documentation/admin/actions/vault/createvaultsecret.md b/content/documentation/admin/actions/vault/createvaultsecret.md index 01e1c583..f10bc003 100644 --- a/content/documentation/admin/actions/vault/createvaultsecret.md +++ b/content/documentation/admin/actions/vault/createvaultsecret.md @@ -9,7 +9,9 @@ Running this action requires a Vault token with permission to create secrets. CreateVaultSecret — creates a secret with one or more values in HashiCorp Vault. -### Request example +## Request example + +Example of the action request body: ```yaml path: example/data/path @@ -20,21 +22,25 @@ secrets: value: value2 ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Possible values | Default value | | --------------------------- | -------- | ------------------------------------------------------------------- | ------------------------------------- | ----------------------- | -| path | Yes | Path at which the secret will be stored in Vault | | - | -| allow_update | No | Determines the action's behavior when creating or updating a secret | true, false, merge, merge_or_create | false | -| secrets | Yes | Set of secrets to create in Vault | | - | -| secrets.key | Yes | Name (identifier) of the secret | | - | -| secrets.value | Yes | Value of the secret | | - | +| `path` | Yes | Path at which the secret will be stored in Vault | — | — | +| `allow_update` | No | Determines the action's behavior when creating or updating a secret | `true`, `false`, `merge`, `merge_or_create` | `false` | +| `secrets` | Yes | Set of secrets to create in Vault | — | — | +| `secrets.key` | Yes | Name (identifier) of the secret | — | — | +| `secrets.value` | Yes | Value of the secret | — | — | -### Note +## Secret update modes `allow_update` determines the action's behavior when creating or updating a secret: -- `false` (default) — the action fails with an error if the secret already exists; -- `true` — a new version of the secret is created with the values passed to the action; -- `merge` — only the secret keys specified in the action are updated or created. Existing keys not mentioned in the action are preserved unchanged. If the secret does not yet exist at the path, the action fails with an error; -- `merge_or_create` — behaves like `merge` if the secret already exists; if the secret does not exist at the path, it is created (a full write of the values from the action). +- `false` (default) — the action fails with an error if the secret already exists. +- `true`: A new version of the secret is created with the values passed to the action. +- `merge`: Only the secret keys specified in the action are updated or created. + Existing keys not mentioned in the action are preserved unchanged. + If the secret does not yet exist at the path, the action fails with an error. +- `merge_or_create`: Behaves like `merge` if the secret already exists; if the secret does not exist at the path, it is created (a full write of the values from the action). diff --git a/content/documentation/admin/actions/vault/createvaultsecret.ru.md b/content/documentation/admin/actions/vault/createvaultsecret.ru.md index c4a01b7c..27540ec7 100644 --- a/content/documentation/admin/actions/vault/createvaultsecret.ru.md +++ b/content/documentation/admin/actions/vault/createvaultsecret.ru.md @@ -4,12 +4,14 @@ weight: 10 --- {{< alert level="info" >}} -Для выполнения действий необходимо наличие Vault-токена, который имеет необходимые права для создания секретов. +Для выполнения действий требуется Vault-токен с правами на создание секретов. {{< /alert >}} CreateVaultSecret — создаёт секрет с одним или несколькими значениями в HashiCorp Vault. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml path: example/data/path @@ -20,23 +22,27 @@ secrets: value: value2 ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | --------------------------- | ---------------- | ------------------------------------------------------------------- | ------------------------------------- | ----------------------- | -| path | Да | Путь, по которому будет сохранён секрет в Vault | | - | -| allow_update | Нет | Определяет поведение действия при создании или обновлении секрета | true, false, merge, merge_or_create | false | -| secrets | Да | Набор секретов, которые необходимо создать в Vault | | - | -| secrets.key | Да | Название (идентификатор) секрета | | - | -| secrets.value | Да | Значение секрета | | - | +| `path` | Да | Путь, по которому будет сохранён секрет в Vault | — | — | +| `allow_update` | Нет | Определяет поведение действия при создании или обновлении секрета | `true`, `false`, `merge`, `merge_or_create` | `false` | +| `secrets` | Да | Набор секретов, которые необходимо создать в Vault | — | — | +| `secrets.key` | Да | Название (идентификатор) секрета | — | — | +| `secrets.value` | Да | Значение секрета | — | — | -### Примечание +## Режимы обновления секрета `allow_update` — определяет поведение действия при создании или обновлении секрета: - `false` (по умолчанию) — действие завершается с ошибкой, если секрет уже существует; - `true` — создаётся новая версия секрета со значениями, переданными в действии; -- `merge` — обновляются или создаются только те ключи секрета, которые указаны в действии. Существующие ключи, не упомянутые в действии, сохраняются без изменений. Если секрета по пути ещё нет, действие завершается с ошибкой; +- `merge` — обновляются или создаются только те ключи секрета, которые указаны в действии. + Существующие ключи, не упомянутые в действии, сохраняются без изменений. + Если секрета по пути ещё нет, действие завершается с ошибкой; - `merge_or_create` — как `merge`, если секрет уже существует; если секрета по пути нет, он создаётся (полная запись значений из действия). После успешного выполнения действия значения секретов заменяются на `MASKED` в сохранённом теле запроса записи запуска и в параметрах процесса, если значение секрета передано через них. diff --git a/content/documentation/admin/actions/vault/deletevaultsecret.md b/content/documentation/admin/actions/vault/deletevaultsecret.md index 6a33b86e..c5ab8be6 100644 --- a/content/documentation/admin/actions/vault/deletevaultsecret.md +++ b/content/documentation/admin/actions/vault/deletevaultsecret.md @@ -10,14 +10,18 @@ For a KV v2 path (contains `/data/`), the token also needs permission to delete DeleteVaultSecret — deletes a secret from HashiCorp Vault. -### Request example +## Request example + +Example of the action request body: ```yaml path: example/data/path ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | | --------------------------- | -------- | ---------------------------------------------------------------------------------------------------- | -| path | Yes | Path at which the secret to be deleted is located in Vault | +| `path` | Yes | Path at which the secret to be deleted is located in Vault | diff --git a/content/documentation/admin/actions/vault/deletevaultsecret.ru.md b/content/documentation/admin/actions/vault/deletevaultsecret.ru.md index f24f41c0..42e6945d 100644 --- a/content/documentation/admin/actions/vault/deletevaultsecret.ru.md +++ b/content/documentation/admin/actions/vault/deletevaultsecret.ru.md @@ -10,14 +10,18 @@ weight: 20 DeleteVaultSecret — удаляет секрет из HashiCorp Vault. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml path: example/data/path ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | | --------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------- | -| path | Да | Путь, по которому находится секрет в Vault, который необходимо удалить | +| `path` | Да | Путь, по которому находится секрет в Vault, который необходимо удалить | diff --git a/content/documentation/admin/actions/wait/wait.md b/content/documentation/admin/actions/wait/wait.md index 884d266a..b5a9157d 100644 --- a/content/documentation/admin/actions/wait/wait.md +++ b/content/documentation/admin/actions/wait/wait.md @@ -3,9 +3,12 @@ title: Wait weight: 10 --- -Wait pauses execution for a specified number of seconds and can optionally add a random duration (jitter). It is intended for use in processes as a delay element, including while waiting for the results of a previous action to be applied. +Wait pauses execution for a specified number of seconds and can optionally add a random duration (jitter). +It is intended for use in processes as a delay element, including while waiting for the results of a previous action to be applied. -### Request example +## Request example + +Example of the action request body: ```yaml duration_seconds: 10 @@ -13,17 +16,19 @@ max_jitter_seconds: 0 description: "Waiting for release" ``` -### Request specification +## Request specification + +The action request body supports the following parameters: | Name | Required | Description | Default value | | --------------------- | -------- | ------------------------------------------------------------------------------------- | ---------------------- | -| duration_seconds | No | Base wait duration in seconds, from `0` to `86400` (24 hours) | `0` | -| max_jitter_seconds | No | Maximum random addition to the wait time in seconds (0–N). 0 disables jitter | `0` | -| description | No | Description shown in the logs and the action's response | - | +| `duration_seconds` | No | Base wait duration in seconds, from `0` to `86400` (24 hours) | `0` | +| `max_jitter_seconds` | No | Maximum random addition to the wait time in seconds (0–N). 0 disables jitter | `0` | +| `description` | No | Description shown in the logs and the action's response | — | The total wait time, including jitter, does not exceed 86400 seconds. -### Response +## Response The action returns the following fields: diff --git a/content/documentation/admin/actions/wait/wait.ru.md b/content/documentation/admin/actions/wait/wait.ru.md index e09be330..a8eb2306 100644 --- a/content/documentation/admin/actions/wait/wait.ru.md +++ b/content/documentation/admin/actions/wait/wait.ru.md @@ -3,9 +3,12 @@ title: Wait weight: 10 --- -Wait ожидает заданное число секунд; дополнительно может применяться случайная добавка к длительности (джиттер). Предназначено для использования в процессах в качестве элемента задержки, в том числе для ожидания применения результатов предыдущего действия. +Wait ожидает заданное число секунд; дополнительно может применяться случайная добавка к длительности (джиттер). +Предназначено для использования в процессах в качестве элемента задержки, в том числе для ожидания применения результатов предыдущего действия. -### Пример запроса +## Пример запроса + +Пример тела запроса действия: ```yaml duration_seconds: 10 @@ -13,17 +16,19 @@ max_jitter_seconds: 0 description: "Waiting for release" ``` -### Спецификация запроса +## Спецификация запроса + +Тело запроса действия поддерживает следующие параметры: | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | ---------------- | ---------------------------------------------------------------------------------- | ---------------------- | -| duration_seconds | Нет | Базовая длительность ожидания в секундах, от `0` до `86400` (24 часа) | `0` | -| max_jitter_seconds | Нет | Максимальная случайная добавка к ожиданию в секундах (0–N). 0 — джиттер отключён | `0` | -| description | Нет | Описание для отображения в логах и ответе действия | - | +| `duration_seconds` | Нет | Базовая длительность ожидания в секундах, от `0` до `86400` (24 часа) | `0` | +| `max_jitter_seconds` | Нет | Максимальная случайная добавка к ожиданию в секундах (0–N). 0 — джиттер отключён | `0` | +| `description` | Нет | Описание для отображения в логах и ответе действия | — | Общая длительность ожидания с учётом джиттера не превышает 86400 секунд. -### Ответ +## Ответ Действие возвращает следующие поля: diff --git a/content/documentation/admin/ai-agents/_index.md b/content/documentation/admin/ai-agents/_index.md new file mode 100644 index 00000000..a3796d9a --- /dev/null +++ b/content/documentation/admin/ai-agents/_index.md @@ -0,0 +1,4 @@ +--- +title: AI agents +weight: 37 +--- diff --git a/content/documentation/admin/ai-agents/agent-sources.md b/content/documentation/admin/ai-agents/agent-sources.md new file mode 100644 index 00000000..6bdb4bf5 --- /dev/null +++ b/content/documentation/admin/ai-agents/agent-sources.md @@ -0,0 +1,169 @@ +--- +title: Agent sources +weight: 40 +description: Connecting external AI agents automatically from catalog entities — resource bindings, filter rules, synchronization, and its results. +--- + +{{< alert level="warning" >}} +AI agents are a Preview feature. +Agent types, available settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +An agent source creates external agent connections from catalog entities. +Each entity of a bound resource becomes an external agent. +The agent ID is taken from the entity ID, and the card URL is taken from an entity property. + +The source does not access external systems itself; it reads entities that already exist in the catalog. +Agent entities can be created manually, through the API, or by a [datasource](../datasources/overview/), for example, by synchronizing kagent agent objects from Kubernetes. + +## How the source works + +The portal synchronizes each enabled source when the backend starts and then once a minute. +You can start synchronization manually with the "Sync now" button. + +For each resource binding, the portal performs the following steps: + +1. Gets all entities of the resource. +1. Applies the [filter rules](#filter-rules) to the entities. +1. Skips entities whose [enablement property](#enablement-property) is turned off. +1. Creates or updates an agent connection for each remaining entity. + +The portal takes the agent name and description from its card, and until the card has been read, from the entity name and description. +The portal re-reads the agent card if the agent is new, if the card URL has changed, or if more than 15 minutes have passed since the last read. + +The owner and owner team of the entity become the owner and owner team of the agent. +If they are not set for the entity, the owner and owner team of the source are used. + +Synchronization reflects the current state of the catalog as a whole: + +- An agent whose entity has dropped out of the selection is disabled but not deleted. +- If the selection is empty, all agents of the source are disabled, and this is not considered an error. +- If the entity gets back into the selection, the agent is enabled. + +## Quick start + +To connect agents from the catalog, follow these steps: + +1. Create a resource whose entities will describe agents. + Add a `String` property for the agent card URL to the resource, for example, `agent_card_url`. +1. Create entities of the resource and fill in the card URL in them. The entity ID becomes the agent ID. +1. Go to "AI" → "Agents" → "Agent sources" and click "Create agent source". + The button is available with the `edit:ai-agents` permission. +1. On the "Main information" tab, turn on "Enable" and fill in "Name" and "Identifier". +1. On the "Catalog resources" tab, click "Add resource", select the resource, and in the "Agent Card URL property" field, select the property with the card URL. +1. On the "Connection" tab, specify the "API key" shared by all agents of the source. +1. Click "Save", then select "Sync now" in the source card menu. + +After synchronization, the portal shows the notification "Synced: {created} created, {updated} updated, {skipped} skipped", and the agents appear in the "Catalog" section with the "External" and "From source" marks. + +## Source parameters + +The source form contains the "Main information", "Catalog resources", and "Connection" tabs. +Collections are set in the source settings and applied to its agents. + +### Basic information + +The "Main information" tab contains the following fields: + +| Name | Required | Description | +| --- | --- | --- | +| "Enable" | — | A disabled source is not synchronized and does not disable agents it has already created | +| "Name" | Yes | Source name | +| "Identifier" | Yes | Unique source ID | +| "Description" | No | Source description | +| "Owner" | No | Owner of agents whose entities have no owner set | +| "Owning team" | No | Owner team of agents whose entities have no team set | + +### Catalog resources + +On the "Catalog resources" tab, at least one resource binding is set. +A resource can be bound to a source only once. + +Each binding has the following fields: + +| Name | Required | Description | +| --- | --- | --- | +| "Resource" | Yes | Catalog resource whose entities become agents | +| "Agent Card URL property" | Yes | Resource property containing the link to the agent card | +| "Enabled property" | No | Property that determines whether to register the entity as an agent | +| "Filter rules" | No | Rules that limit the selection of entities | + +On save, the portal checks that the resource exists and the specified properties are declared in the resource. + +#### Enablement property + +If the enablement property is set, the entity is skipped when the property is empty or its value is `false`, `0`, `no`, or `off` in any case. +Any other value is treated as enabled. + +#### Filter rules + +Filter rules limit which entities of the resource are synchronized as agents. +The rules are applied in order, and each subsequent rule works with the result of the previous one. +If there are no rules, all entities of the resource are synchronized. + +Each rule consists of the following fields: + +- "Action": "Keep only matches" or "Remove matches". +- "Source": Path to the entity field in Go template format. +- "Condition": Regular expression against which the field value is checked. + +In the "Source" field, the entity is available through the `.entity` root: + +```go +{{ .entity.slug }} +{{ .entity.name }} +{{ .entity.description }} +{{ .entity.properties.environment }} +``` + +For example, to synchronize only production environment agents, add a rule with the "Keep only matches" action, the `{{ .entity.properties.environment }}` source, and the `^production$` condition. + +An entity excluded by a rule does not get into the selection, and the agent previously created from it is disabled at the next synchronization. + +### Connection + +The parameters on the "Connection" tab apply to all agents of the source: + +| Name | Required | Description | +| --- | --- | --- | +| "API key" | Yes | Key that the portal passes to each agent of the source in the `X-A2A-Api-Key` and `Authorization: Bearer` headers | +| "Call the address from the agent card" | — | If disabled, the portal calls the base URL of the card. Disable it for in-cluster sources, for example, kagent, that publish addresses reachable only from inside the cluster | +| "MCP collections" | No | Collections of each agent of the source. The run receives their tools that the running user is allowed to use; without collections, the agents work without MCP tools | + +The API key is stored encrypted and is not displayed after saving. +When editing the source, leave the field empty to keep the current key. + +## Agents from a source + +For an agent from a source, the portal sets the card URL, the API key, "Call the address from the agent card", and the MCP collections from the source settings at every synchronization. +Change the collections of such an agent in the source. +In the agent connection, you can change the enabled state and the permission to use the Deckhouse Development Portal (DDP) model proxy; skills are assigned to the agent itself. + +If the agent needs the DDP model proxy, enable "Allow the DDP model proxy" in the agent connection after the first synchronization, because the source does not change this switch. + +If you disable an agent manually, synchronization does not re-enable it; in the synchronization results, it is shown as skipped with the `manually_disabled` reason. +You can delete an agent from a source only when it is disabled, because the next synchronization would recreate an enabled agent. + +## Synchronization results + +The "Sync now" button returns a result for each agent. +The notification shows the number of created, updated, and skipped agents; all results other than creation and update are counted as skipped. + +Reasons why an agent is skipped or requires attention: + +| Reason | Meaning | +| --- | --- | +| `card_url_missing` | The card URL property is not filled in for the entity | +| `card_unreachable` | The card of a new agent cannot be read. The agent is created disabled. An agent that is already working is not disabled when its card is unavailable | +| `invalid_slug` | The entity ID is not valid as an agent ID | +| `duplicate_in_payload` | The selection contains several entities with the same ID | +| `manually_disabled` | The agent was disabled manually | +| `ai_agent_remote_link_slug_conflict` | The ID is already taken by an external agent connected manually or by another source | +| `ai_agent_remote_link_slug_reserved` | The `ddp-agent` ID is reserved for the platform agent | + +## Disabling and deleting a source + +A disabled source is not synchronized. Agents it created remain in their current state. + +When a source is deleted, the agents it created are neither deleted nor disabled. +They become regular external agents, all fields of which can be changed manually. diff --git a/content/documentation/admin/ai-agents/agent-sources.ru.md b/content/documentation/admin/ai-agents/agent-sources.ru.md index 6c7889f8..972b39f1 100644 --- a/content/documentation/admin/ai-agents/agent-sources.ru.md +++ b/content/documentation/admin/ai-agents/agent-sources.ru.md @@ -5,18 +5,21 @@ description: Автоматическое подключение внешних --- {{< alert level="warning" >}} -AI-агенты — функциональность на стадии Preview. Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +AI-агенты — функциональность на стадии Preview. +Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} Источник агентов создаёт подключения внешних агентов по сущностям каталога. -Каждая сущность привязанного ресурса становится внешним агентом: идентификатор агента берётся из идентификатора сущности, а URL карточки — из параметра сущности. +Каждая сущность привязанного ресурса становится внешним агентом. +Идентификатор агента берётся из идентификатора сущности, а URL карточки — из параметра сущности. -Источник не обращается к внешним системам сам: он читает сущности, которые уже есть в каталоге. +Источник не обращается к внешним системам сам, а читает сущности, которые уже есть в каталоге. Сущности агентов можно создать вручную, через API или [источником данных](../datasources/overview/), например синхронизацией объектов агентов kagent из Kubernetes. -## Как работает источник +## Принцип работы источника -Портал синхронизирует каждый включённый источник при запуске backend и затем раз в минуту. Синхронизацию можно запустить вручную кнопкой «Синхронизировать сейчас». +Портал синхронизирует каждый включённый источник при запуске backend и затем раз в минуту. +Синхронизацию можно запустить вручную кнопкой «Синхронизировать сейчас». Для каждой привязки ресурса портал выполняет шаги: @@ -28,7 +31,8 @@ AI-агенты — функциональность на стадии Preview. Название и описание агента портал берёт из его карточки, а пока карточка не прочитана — из названия и описания сущности. Карточку агента портал перечитывает, если агент новый, если изменился URL карточки или если с последнего чтения прошло больше 15 минут. -Владельцем агента и его командой-владельцем становятся владелец и команда-владелец сущности. Если у сущности они не заданы, используются владелец и команда-владелец источника. +Владельцем агента и его командой-владельцем становятся владелец и команда-владелец сущности. +Если у сущности они не заданы, используются владелец и команда-владелец источника. Синхронизация отражает текущее состояние каталога целиком: @@ -40,9 +44,11 @@ AI-агенты — функциональность на стадии Preview. Чтобы подключать агентов из каталога: -1. Создайте ресурс, сущности которого будут описывать агентов. Добавьте в ресурс параметр типа `String` для URL карточки агента, например `agent_card_url`. +1. Создайте ресурс, сущности которого будут описывать агентов. + Добавьте в ресурс параметр типа `String` для URL карточки агента, например `agent_card_url`. 1. Создайте сущности ресурса и заполните в них URL карточки. Идентификатор сущности станет идентификатором агента. -1. Перейдите в раздел «AI» → «Агенты» → «Источники агентов» и нажмите «Создать источник агентов». Кнопка доступна с разрешением `edit:ai-agents`. +1. Перейдите в раздел «AI» → «Агенты» → «Источники агентов» и нажмите «Создать источник агентов». + Кнопка доступна с разрешением `edit:ai-agents`. 1. На вкладке «Основная информация» включите «Включить», заполните «Название» и «Идентификатор». 1. На вкладке «Ресурсы каталога» нажмите «Добавить ресурс», выберите ресурс и в поле «Параметр с URL Agent Card» выберите параметр с URL карточки. 1. На вкладке «Подключение» укажите «API-ключ», общий для всех агентов источника. @@ -52,13 +58,14 @@ AI-агенты — функциональность на стадии Preview. ## Параметры источника -Форма источника содержит вкладки «Основная информация», «Ресурсы каталога» и «Подключение». Коллекции задаются в настройках источника и применяются к его агентам. +Форма источника содержит вкладки «Основная информация», «Ресурсы каталога» и «Подключение». +Коллекции задаются в настройках источника и применяются к его агентам. ### Основная информация На вкладке «Основная информация» задаются поля: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Включить» | — | Выключенный источник не синхронизируется и не выключает уже созданных им агентов | | «Название» | Да | Название источника | @@ -69,11 +76,12 @@ AI-агенты — функциональность на стадии Preview. ### Ресурсы каталога -На вкладке «Ресурсы каталога» задаётся хотя бы одна привязка ресурса. Один ресурс можно привязать к источнику только один раз. +На вкладке «Ресурсы каталога» задаётся хотя бы одна привязка ресурса. +Один ресурс можно привязать к источнику только один раз. Для каждой привязки задаются поля: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Ресурс» | Да | Ресурс каталога, сущности которого становятся агентами | | «Параметр с URL Agent Card» | Да | Параметр ресурса со ссылкой на карточку агента | @@ -90,7 +98,8 @@ AI-агенты — функциональность на стадии Preview. #### Правила фильтрации Правила фильтрации ограничивают, какие сущности ресурса синхронизируются как агенты. -Правила применяются по порядку: каждое следующее правило работает с результатом предыдущего. Если правил нет, синхронизируются все сущности ресурса. +Правила применяются по порядку, и каждое следующее правило работает с результатом предыдущего. +Если правил нет, синхронизируются все сущности ресурса. Каждое правило состоит из полей: @@ -109,33 +118,36 @@ AI-агенты — функциональность на стадии Preview. Например, чтобы синхронизировать только агентов production-окружения, добавьте правило с действием «Оставить только совпадения», источником `{{ .entity.properties.environment }}` и условием `^production$`. -Сущность, исключённая правилом, не попадает в выборку: созданный по ней ранее агент выключается при следующей синхронизации. +Сущность, исключённая правилом, не попадает в выборку, а созданный по ней ранее агент выключается при следующей синхронизации. ### Подключение Параметры вкладки «Подключение» применяются ко всем агентам источника: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «API-ключ» | Да | Ключ, который портал передаёт каждому агенту источника в заголовках `X-A2A-Api-Key` и `Authorization: Bearer` | | «Вызывать адрес из карточки агента» | — | Если выключено, портал вызывает базовый URL карточки. Выключите для источников внутри кластера, например kagent, которые публикуют адреса, доступные только изнутри кластера | | «MCP-коллекции» | Нет | Коллекции каждого агента источника. В запуск попадают их инструменты, которыми может пользоваться запускающий пользователь; без коллекций агенты работают без MCP-инструментов | -API-ключ хранится в зашифрованном виде и после сохранения не отображается. При редактировании источника оставьте поле пустым, чтобы сохранить текущий ключ. +API-ключ хранится в зашифрованном виде и после сохранения не отображается. +При редактировании источника оставьте поле пустым, чтобы сохранить текущий ключ. ## Агенты из источника У агента из источника портал при каждой синхронизации задаёт адрес карточки, API-ключ, «Вызывать адрес из карточки агента» и MCP-коллекции по настройкам источника. -Коллекции такого агента меняйте в источнике. В подключении агента можно менять включение и разрешение прокси моделей DDP; навыки назначаются самому агенту. +Коллекции такого агента меняйте в источнике. +В подключении агента можно менять включение и разрешение прокси моделей Deckhouse Development Portal (DDP); навыки назначаются самому агенту. -Если агенту нужен прокси моделей DDP, включите «Разрешить прокси моделей DDP» в подключении агента после первой синхронизации: источник этот переключатель не меняет. +Если агенту нужен прокси моделей DDP, включите «Разрешить прокси моделей DDP» в подключении агента после первой синхронизации, поскольку источник этот переключатель не меняет. Если выключить агента вручную, синхронизация не включает его обратно; в результатах синхронизации он отображается как пропущенный с причиной `manually_disabled`. -Удалить агента из источника можно только выключенным: включённого агента следующая синхронизация создала бы заново. +Удалить агента из источника можно только выключенным, поскольку включённого агента следующая синхронизация создала бы заново. ## Результаты синхронизации -Кнопка «Синхронизировать сейчас» возвращает результат по каждому агенту. Уведомление показывает число созданных, обновлённых и пропущенных агентов; к пропущенным относятся все результаты, кроме создания и обновления. +Кнопка «Синхронизировать сейчас» возвращает результат по каждому агенту. +Уведомление показывает число созданных, обновлённых и пропущенных агентов; к пропущенным относятся все результаты, кроме создания и обновления. Причины, по которым агент пропущен или требует проверки: @@ -153,4 +165,5 @@ API-ключ хранится в зашифрованном виде и посл Выключенный источник не синхронизируется. Созданные им агенты остаются в текущем состоянии. -При удалении источника созданные им агенты не удаляются и не выключаются: они становятся обычными внешними агентами, все поля которых можно изменять вручную. +При удалении источника созданные им агенты не удаляются и не выключаются. +Они становятся обычными внешними агентами, все поля которых можно изменять вручную. diff --git a/content/documentation/admin/ai-agents/external-agents.md b/content/documentation/admin/ai-agents/external-agents.md new file mode 100644 index 00000000..47a09480 --- /dev/null +++ b/content/documentation/admin/ai-agents/external-agents.md @@ -0,0 +1,170 @@ +--- +title: External agents +weight: 30 +description: Connecting an external AI agent over the A2A protocol — connection parameters, agent requirements, and connecting kagent agents. +--- + +{{< alert level="warning" >}} +AI agents are a Preview feature. +Agent types, available settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +An external agent is an AI agent that runs outside the portal and accepts tasks over the A2A protocol version 1.0. +The portal connects to the agent using its card URL and an API key, after which the agent can be selected in the AI assistant, the "AI chat" widget, and the "AI agent" process element. + +If there are many agents and they are already described in the catalog, connect them through an [agent source](agent-sources/): the source creates and updates the connections itself. + +## Quick start + +To connect an external agent, follow these steps: + +1. Go to "AI" → "Agents" → "Catalog" and click "Connect agent". + The button is available with the `edit:ai-agents` permission. +1. On the "Main information" tab, fill in "Name" and "Identifier". +1. On the "Connection" tab, turn on the "Enable" switch. +1. Specify the "Agent Card URL", that is, the agent card address, for example, `https://agents.example.com/.well-known/agent-card.json`. +1. Specify the "API key" that the agent expects. +1. Click "Save". + +The agent appears in the catalog with the "External" mark. +To let a user run it, grant the user `use:ai-agents` or `use:ai-agent` on this connection. +Ownership grants permissions when `owner-is-admin` is enabled. + +## Connection parameters + +The connection form contains the "Main information", "Connection", and "Tools and skills" tabs. + +### Basic information + +The "Main information" tab contains the following fields: + +| Name | Required | Description | +| --- | --- | --- | +| "Name" | Yes | Agent name in the catalog and in agent selection lists | +| "Identifier" | Yes | From 3 to 64 characters: lowercase Latin letters, digits, and hyphens. The `ddp-agent` ID is reserved for the platform agent | +| "Description" | No | Agent description | + +The ID is used to specify the agent in the "AI agent" process element and in the "AI chat" widget settings. + +### Connection + +The fields of the "Connection" tab are shown when the "Enable" switch is on: + +| Name | Required | Description | +| --- | --- | --- | +| "Enable" | — | A disabled agent is not shown in the AI assistant, widgets, and process steps | +| "Agent Card URL" | Yes | Agent card address. The portal reads the name, description, and the addresses at which the agent accepts calls from the card | +| "Call the address from the agent card" | — | If enabled, the portal calls the address declared in the card. If disabled, the portal calls the base URL of the card, that is, the address from the "Agent Card URL" field without `/.well-known/agent-card.json` or `/.well-known/agent.json` | +| "Allow the DDP model proxy" | — | The agent accesses the language model through the portal and uses the AI provider of the user who started the task. For details, see ["Agent language model"](overview/#agent-language-model) | +| "API key" | Yes | Key that the portal passes to the agent in the `X-A2A-Api-Key` and `Authorization: Bearer` headers on every call and when reading the card | + +On the "Tools and skills" tab, select "MCP collections" and, if needed, [skills](skills/). +The agent receives the tools of these collections that the running user is allowed to use. +Without collections, the agent works without MCP tools. +Access to tools is defined by [collections and roles](../../user/mcp-management/#integration-with-the-ai-assistant-and-mcp-server). + +The API key is stored encrypted in the database and is not displayed after saving. +When editing the connection, leave the "API key" field empty to keep the current key. +During [encryption key rotation](../security/encryption-key-rotation/), agent API keys are re-encrypted. + +## Agent requirements + +The portal works with an agent that meets the following requirements: + +- It supports the A2A protocol version 1.0 with the HTTP+JSON or JSON-RPC binding. +- It publishes an agent card reachable from the portal cluster. +- It accepts the API key from the `X-A2A-Api-Key` or `Authorization: Bearer` header. + +The portal sends an A2A message to the agent and waits for the task to complete, polling its state every 2 seconds. +The agent response is the text of its final message. + +### Message metadata + +In the metadata of each A2A message, the portal passes the access that the agent is allowed: + +| Key | When passed | Value | +| --- | --- | --- | +| `ddp.mcp.endpoint` | The collections contain permitted tools | Portal MCP endpoint address, for example, `https:///api/v2/agent-mcp` | +| `ddp.mcp.runToken` | The collections contain permitted tools | Run token | +| `ddp.mcp.toolAllowlist` | The collections contain permitted tools | Tools permitted in this run | +| `ddp.llm.baseUrl` | The "Allow the DDP model proxy" switch is on | Model proxy address, for example, `https:///api/v2/agent-llm/v1` | +| `ddp.llm.apiKey` | The "Allow the DDP model proxy" switch is on | Run token | +| `ddp.llm.model` | The "Allow the DDP model proxy" switch is on | Model of the user's AI provider | +| `ddp.provider` | The "Allow the DDP model proxy" switch is on | Name of the user's AI provider | + +The addresses in the metadata are built from the public portal address, so the agent must have network access to the portal. + +### Calling portal tools + +To call portal tools, the agent sends requests to the MCP endpoint from the metadata with the run token in the `X-Agent-Run-Token` header. +The `POST /tools/list` request returns the list of available tools with the JSON schema of their arguments. +The `POST /tools/call` request calls a tool; the request body is `{"tool": "", "arguments": {...}}`. + +Example of a tool call: + +```shell +curl -s -X POST "https:///api/v2/agent-mcp/tools/call" -H "X-Agent-Run-Token: " -H "Content-Type: application/json" -d '{"tool": "ddp_get_resources", "arguments": {}}' +``` + +Where: + +- ``: Portal domain. +- ``: Value of `ddp.mcp.runToken` from the message metadata. + +A tool that is not in `ddp.mcp.toolAllowlist` returns a `403` error. +An invalid or revoked token returns a `401` error. + +### Accessing the model through the portal + +If the agent is allowed to use the Deckhouse Development Portal (DDP) model proxy, it sends requests to `/chat/completions` as to the OpenAI Chat Completions API and passes `ddp.llm.apiKey` as the API key. +Proxy limitations are described in ["Agent language model"](overview/#agent-language-model). + +### Run result + +The agent can report the result type in the metadata of the final message, task, or artifact. +The `ddp.deliverableType` field contains the result type: `message`, `merge_request`, `branch`, or `patch`. +The `ddp.deliverableRef` field contains a reference to the result, for example, the merge request URL. + +The type and reference are shown in the run details in the [run history](runs/). +If the type is not passed, the result is considered a message. + +## Connecting a kagent agent + +Agents deployed in the cluster with kagent are connected through the kagent A2A endpoint. +The card of such an agent contains in-cluster service addresses, so the portal calls the base URL of the card. + +To connect a kagent agent, follow these steps: + +1. In the "Agent Card URL" field, specify the address of the agent's A2A endpoint in kagent, for example, `https:///api/a2a///`. +1. Turn off the "Call the address from the agent card" switch. +1. In the "API key" field, specify the key that the kagent A2A endpoint expects. +1. If the agent has no model access of its own, enable "Allow the DDP model proxy". + +Where: + +- ``: Address of the kagent A2A endpoint. +- ``: Agent namespace. +- ``: Agent name. + +If there are several kagent agents, create an [agent source](agent-sources/) with the "Call the address from the agent card" switch turned off. + +## Editing and deleting + +You can edit and delete a connection with the global `edit:ai-agents` permission or the object-level `edit:ai-agent` permission. +When `owner-is-admin` is enabled, the owner and members of the owner team also get these permissions; a super administrator has access to all connections. +To edit or delete a connection, select "Edit" or "Delete" in the agent card menu in the catalog. + +If you disable an agent manually, it is not re-enabled automatically, even if it is managed by an agent source. + +## Troubleshooting + +Agent call errors are shown in the AI assistant and in the run details: + +| Message | Cause and solution | +| --- | --- | +| "Failed to get the external agent's Agent Card. Check the card URL and agent availability." | The card cannot be read at the address from the "Agent Card URL" field. Check the address and network access from the portal cluster to the agent | +| "The external agent's Agent Card is unusable (no supported interfaces or invalid address). Check the agent settings." | The card contains no addresses with a supported A2A binding. If the agent publishes addresses inside its own cluster, turn off "Call the address from the agent card" | +| "The external agent rejected the credentials. Check the API key of its link." | The agent did not accept the API key. Specify the key that the agent expects in the connection | +| "The external agent is unavailable (network error or timeout). Try again later." | The agent did not respond in time or is unreachable over the network | +| "The external agent returned no answer." | The agent task completed without a final message | +| "You do not have permission to run this AI agent" | Check the global `use:ai-agents` permission or the object-level `use:ai-agent` permission on the connection | diff --git a/content/documentation/admin/ai-agents/external-agents.ru.md b/content/documentation/admin/ai-agents/external-agents.ru.md index da56ae6c..b7275e5b 100644 --- a/content/documentation/admin/ai-agents/external-agents.ru.md +++ b/content/documentation/admin/ai-agents/external-agents.ru.md @@ -5,7 +5,8 @@ description: Подключение внешнего AI-агента по про --- {{< alert level="warning" >}} -AI-агенты — функциональность на стадии Preview. Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +AI-агенты — функциональность на стадии Preview. +Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} Внешний агент — AI-агент, который работает вне портала и принимает задачи по протоколу A2A версии 1.0. @@ -17,14 +18,17 @@ AI-агенты — функциональность на стадии Preview. Чтобы подключить внешнего агента: -1. Перейдите в раздел «AI» → «Агенты» → «Каталог» и нажмите «Подключить агента». Кнопка доступна с разрешением `edit:ai-agents`. +1. Перейдите в раздел «AI» → «Агенты» → «Каталог» и нажмите «Подключить агента». + Кнопка доступна с разрешением `edit:ai-agents`. 1. На вкладке «Основная информация» заполните «Название» и «Идентификатор». 1. На вкладке «Подключение» включите переключатель «Включить». 1. Укажите «URL Agent Card» — адрес карточки агента, например `https://agents.example.com/.well-known/agent-card.json`. 1. Укажите «API-ключ», который ожидает агент. 1. Нажмите «Сохранить». -Агент появится в каталоге с отметкой «Внешний». Для запуска предоставьте пользователю `use:ai-agents` или `use:ai-agent` на это подключение. Владение даёт права при включённом `owner-is-admin`. +Агент появится в каталоге с отметкой «Внешний». +Для запуска предоставьте пользователю `use:ai-agents` или `use:ai-agent` на это подключение. +Владение даёт права при включённом `owner-is-admin`. ## Параметры подключения @@ -34,7 +38,7 @@ AI-агенты — функциональность на стадии Preview. На вкладке «Основная информация» задаются поля: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Название» | Да | Название агента в каталоге и в списках выбора агента | | «Идентификатор» | Да | От 3 до 64 символов: строчные латинские буквы, цифры и дефис. Идентификатор `ddp-agent` зарезервирован за платформенным агентом | @@ -46,7 +50,7 @@ AI-агенты — функциональность на стадии Preview. Поля вкладки «Подключение» отображаются, когда включён переключатель «Включить»: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Включить» | — | Выключенный агент не отображается в AI-ассистенте, виджетах и шагах процессов | | «URL Agent Card» | Да | Адрес карточки агента. Портал читает из карточки название, описание и адреса, по которым принимает вызовы агент | @@ -54,7 +58,10 @@ AI-агенты — функциональность на стадии Preview. | «Разрешить прокси моделей DDP» | — | Агент обращается к языковой модели через портал и использует AI-провайдера пользователя, который запустил задачу. Подробнее — в разделе [«Языковая модель агента»](overview/#языковая-модель-агента) | | «API-ключ» | Да | Ключ, который портал передаёт агенту в заголовках `X-A2A-Api-Key` и `Authorization: Bearer` при каждом вызове и при чтении карточки | -На вкладке «Инструменты и навыки» выберите «MCP-коллекции» и при необходимости [навыки](skills/). Агент получает инструменты этих коллекций, которыми может пользоваться запускающий пользователь. Без коллекций агент работает без MCP-инструментов. Доступ к инструментам задаётся [коллекциями и ролями](../../user/mcp-management/#связь-с-ai-ассистентом-и-mcp-сервером). +На вкладке «Инструменты и навыки» выберите «MCP-коллекции» и при необходимости [навыки](skills/). +Агент получает инструменты этих коллекций, которыми может пользоваться запускающий пользователь. +Без коллекций агент работает без MCP-инструментов. +Доступ к инструментам задаётся [коллекциями и ролями](../../user/mcp-management/#связь-с-ai-ассистентом-и-mcp-сервером). API-ключ хранится в базе данных в зашифрованном виде и после сохранения не отображается. При редактировании подключения оставьте поле «API-ключ» пустым, чтобы сохранить текущий ключ. @@ -89,10 +96,9 @@ API-ключ хранится в базе данных в зашифрованн ### Вызов инструментов портала -Чтобы вызвать инструменты портала, агент обращается к MCP-эндпоинту из метаданных с токеном запуска в заголовке `X-Agent-Run-Token`: - -- `POST /tools/list` — возвращает список доступных инструментов с JSON-схемой аргументов; -- `POST /tools/call` — вызывает инструмент. Тело запроса — `{"tool": "", "arguments": {...}}`. +Чтобы вызвать инструменты портала, агент обращается к MCP-эндпоинту из метаданных с токеном запуска в заголовке `X-Agent-Run-Token`. +Запрос `POST /tools/list` возвращает список доступных инструментов с JSON-схемой аргументов. +Запрос `POST /tools/call` вызывает инструмент, тело запроса — `{"tool": "", "arguments": {...}}`. Пример вызова инструмента: @@ -105,21 +111,22 @@ curl -s -X POST "https:///api/v2/agent-mcp/tools/call" -H "X-Agent-Run-T - `` — домен портала; - `` — значение `ddp.mcp.runToken` из метаданных сообщения. -Инструмент, которого нет в `ddp.mcp.toolAllowlist`, возвращает ошибку `403`. Недействительный или отозванный токен — ошибку `401`. +Инструмент, которого нет в `ddp.mcp.toolAllowlist`, возвращает ошибку `403`. +Недействительный или отозванный токен — ошибку `401`. ### Обращение к модели через портал -Если агенту разрешён прокси моделей DDP, он обращается к `/chat/completions` как к API OpenAI Chat Completions и передаёт `ddp.llm.apiKey` как API-ключ. +Если агенту разрешён прокси моделей Deckhouse Development Portal (DDP), он обращается к `/chat/completions` как к API OpenAI Chat Completions и передаёт `ddp.llm.apiKey` как API-ключ. Ограничения прокси описаны в разделе [«Языковая модель агента»](overview/#языковая-модель-агента). ### Результат запуска -Агент может сообщить тип результата в метаданных итогового сообщения, задачи или артефакта: - -- `ddp.deliverableType` — тип результата: `message`, `merge_request`, `branch` или `patch`; -- `ddp.deliverableRef` — ссылка на результат, например URL merge request. +Агент может сообщить тип результата в метаданных итогового сообщения, задачи или артефакта. +В поле `ddp.deliverableType` передаётся тип результата: `message`, `merge_request`, `branch` или `patch`. +В поле `ddp.deliverableRef` передаётся ссылка на результат, например URL запроса на слияние (Merge Request). -Тип и ссылка отображаются в деталях запуска в [истории запусков](runs/). Если тип не передан, результатом считается сообщение. +Тип и ссылка отображаются в деталях запуска в [истории запусков](runs/). +Если тип не передан, результатом считается сообщение. ## Подключение агента kagent @@ -143,7 +150,8 @@ curl -s -X POST "https:///api/v2/agent-mcp/tools/call" -H "X-Agent-Run-T ## Изменение и удаление -Изменять и удалять подключение можно с глобальным `edit:ai-agents` или объектным `edit:ai-agent`. При включённом `owner-is-admin` эти права также получают владелец и участники команды-владельца; супер-администратор имеет доступ ко всем подключениям. +Изменять и удалять подключение можно с глобальным `edit:ai-agents` или объектным `edit:ai-agent`. +При включённом `owner-is-admin` эти права также получают владелец и участники команды-владельца; супер-администратор имеет доступ ко всем подключениям. Чтобы изменить или удалить подключение, выберите «Редактировать» или «Удалить» в меню карточки агента в каталоге. Если выключить агента вручную, он не включится автоматически, даже если им управляет источник агентов. diff --git a/content/documentation/admin/ai-agents/overview.md b/content/documentation/admin/ai-agents/overview.md new file mode 100644 index 00000000..b7405be0 --- /dev/null +++ b/content/documentation/admin/ai-agents/overview.md @@ -0,0 +1,107 @@ +--- +title: Overview +weight: 10 +description: DDP AI agent types, access model, MCP collections, skills, and running agents in the chat, widgets, and processes. +--- + +{{< alert level="warning" >}} +AI agents are a Preview feature. +Agent types, available settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +An AI agent receives a task in natural language, calls a language model, and invokes tools to prepare an answer or perform the work. +Deckhouse Development Portal (DDP) connects agents over the A2A (Agent2Agent) protocol version 1.0. + +Agents from the catalog are used in the [AI assistant](../../user/ai-assistant/), the ["AI chat" widget](../widgets/ai/chat/), and the ["AI agent" process element](../processes/overview/#ai-agent). +A separate workspace agent is also available for working with project files. + +## Agent types + +An agent connection is defined by its Agent Card, which the agent publishes as JSON, usually at `/.well-known/agent-card.json`: + +| Type | Connection | +| --- | --- | +| [Platform agent](platform-agent/) | Deployed with the portal and connected automatically, ID `ddp-agent` | +| [External agent](external-agents/) | Connected by an administrator using the card URL and an API key | +| [Agent from a source](agent-sources/) | Created by a source from a catalog entity | + +The portal sends a message to the agent over A2A and receives a response. The agent itself runs outside the portal backend. + +## Agent language model + +An agent uses its own model access or the DDP model proxy. +When working through the proxy, the portal uses the AI provider of the user who started the task and consumes that user's quota. + +In the catalog, the model source is shown as "DDP model" or "Agent model". + +The platform agent always uses the proxy. +For an external agent, enable "Allow the DDP model proxy" in the connection settings if the portal must provide the model. + +The proxy works with an API compatible with OpenAI Chat Completions. +`/chat/completions` is appended to the provider URL unless the URL already ends with it. +A model and a token are required; the provider fields "Request body template" and "Response field" are not used for agent requests. + +The proxy does not support `stream: true` and substitutes the AI provider's model for the model specified in the agent request. + +## Agent tools + +On the "Tools and skills" tab, set "MCP collections". +The agent receives the tools of the enabled collections that the running user is allowed to use through their own collections. +Permissions on portal objects are checked separately on every call. + +Without collections, the agent works without MCP tools. +This rule is the same for the platform agent, external agents, the chat, widgets, and processes. +A collection can include portal tools, tools of connected MCP servers, and custom HTTP tools. + +For example, to let the agent read the catalog, add `ddp_get_resources` and `ddp_get_resource_entities` to a collection, attach the collection to the agent, and grant the user permission to use it. +To run processes, add `get_processes`, `run_process`, and `get_process_instance`. + +For step-by-step setup, see the [MCP collections guide](../../user/mcp-management/#mcp-collections). + +## Agent skills + +On the same tab, assign [skills](skills/) with a specific version or the "Latest" binding. +At run time, the agent receives their names and descriptions and reads the full text through `get_skill` when needed. +This tool must be available through both the agent's and the user's collections. + +For instructions and materials stored in GitLab, configure a [skill source](skill-sources/). + +## Access to agents + +Usage is controlled by the global `use:ai-agents` permission or the object-level `use:ai-agent` permission for a specific connection. +The permission applies to the chat, widgets, and process steps. +It does not grant access to catalog data or provide MCP tools. + +Viewing and editing are controlled by separate permissions: + +| Object | Global permissions | Object-level permissions | +| --- | --- | --- | +| Agent | `read:ai-agents`, `edit:ai-agents` | `read:ai-agent`, `edit:ai-agent`, `use:ai-agent` | +| Agent source | `read:ai-agents`, `edit:ai-agents` | `read:ai-agent-source`, `edit:ai-agent-source` | +| AI provider template | `read:ai-provider-templates`, `edit:ai-provider-templates`, `use:ai-provider-templates` | `read:ai-provider-template`, `edit:ai-provider-template`, `use:ai-provider-template` | + +Ownership and membership in the owner team grant permissions when `owner-is-admin` is enabled. +You can grant access to other users and teams using "Edit role bindings". +A super administrator has access to all connections. + +Viewing your own run history requires `read:ai-agent-runs`, and stopping runs requires `cancel:ai-agent-runs`. +The "AI" section requires `view:ai-page`; this permission alone does not grant access to the section's objects. + +## Run token and limits + +For permitted calls to MCP and the model proxy, the portal passes a short-lived run token. +The token is revoked after the run completes or is stopped. + +The following limits apply to A2A agent runs: + +| Limit | Value | +| --- | --- | +| Maximum run duration | 70 minutes | +| Maximum token lifetime | 75 minutes | +| MCP calls | 120 per minute per run | +| Model proxy requests | 60 per minute per run | +| Proxy request size | 1 MiB | +| Model response size through the proxy | 4 MiB | +| Model request timeout | 90 seconds | + +Check errors and results in the [run history](runs/), and aggregated metrics in the AI statistics. diff --git a/content/documentation/admin/ai-agents/overview.ru.md b/content/documentation/admin/ai-agents/overview.ru.md index 79dab5c7..3b63b1ed 100644 --- a/content/documentation/admin/ai-agents/overview.ru.md +++ b/content/documentation/admin/ai-agents/overview.ru.md @@ -5,12 +5,15 @@ description: Виды AI-агентов DDP, модель доступа, MCP-к --- {{< alert level="warning" >}} -AI-агенты — функциональность на стадии Preview. Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +AI-агенты — функциональность на стадии Preview. +Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} -AI-агент получает задачу на естественном языке, обращается к языковой модели и вызывает инструменты для подготовки ответа или выполнения работы. Deckhouse Development Portal (DDP) подключает агентов по протоколу A2A (Agent2Agent) версии 1.0. +AI-агент получает задачу на естественном языке, обращается к языковой модели и вызывает инструменты для подготовки ответа или выполнения работы. +Deckhouse Development Portal (DDP) подключает агентов по протоколу A2A (Agent2Agent) версии 1.0. -Агенты из каталога используются в [AI-ассистенте](../../user/ai-assistant/), виджете [«AI-чат»](../widgets/ai/chat/) и элементе процесса [«AI-агент»](../processes/overview/#ai-агент). Для работы с файлами проекта доступен также отдельный [агент рабочего пространства](../../user/workspaces/). +Агенты из каталога используются в [AI-ассистенте](../../user/ai-assistant/), виджете [«AI-чат»](../widgets/ai/chat/) и элементе процесса [«AI-агент»](../processes/overview/#ai-агент). +Для работы с файлами проекта доступен также отдельный [агент рабочего пространства](../../user/workspaces/). ## Виды агентов @@ -26,35 +29,48 @@ AI-агент получает задачу на естественном язы ## Языковая модель агента -Агент использует собственные доступы к модели или прокси моделей DDP. При работе через прокси портал использует AI-провайдера пользователя, запустившего задачу, и расходует его квоту. +Агент использует собственные доступы к модели или прокси моделей DDP. +При работе через прокси портал использует AI-провайдера пользователя, запустившего задачу, и расходует его квоту. В каталоге источник модели отображается как «Модель DDP» или «Модель агента». -Платформенный агент всегда использует прокси. Для внешнего агента включите «Разрешить прокси моделей DDP» в настройках подключения, если модель должен предоставлять портал. +Платформенный агент всегда использует прокси. +Для внешнего агента включите «Разрешить прокси моделей DDP» в настройках подключения, если модель должен предоставлять портал. -Прокси работает с API, совместимым с OpenAI Chat Completions: к URL провайдера добавляется `/chat/completions`, если суффикса ещё нет. Требуются модель и токен; поля провайдера «Шаблон тела запроса» и «Поле ответа» для агентского запроса не используются. +Прокси работает с API, совместимым с OpenAI Chat Completions. +К URL провайдера добавляется `/chat/completions`, если суффикса ещё нет. +Требуются модель и токен; поля провайдера «Шаблон тела запроса» и «Поле ответа» для агентского запроса не используются. Прокси не поддерживает `stream: true` и подставляет модель AI-провайдера вместо модели из запроса агента. ## Инструменты агента -На вкладке «Инструменты и навыки» задайте «MCP-коллекции». Агент получает инструменты включённых коллекций, которыми может пользоваться запускающий пользователь через свои коллекции. Проверка прав на объекты портала выполняется отдельно при каждом вызове. +На вкладке «Инструменты и навыки» задайте «MCP-коллекции». +Агент получает инструменты включённых коллекций, которыми может пользоваться запускающий пользователь через свои коллекции. +Проверка прав на объекты портала выполняется отдельно при каждом вызове. -Без коллекций агент работает без MCP-инструментов. Это правило одинаково для платформенного агента, внешних агентов, чата, виджетов и процессов. Состав коллекции может включать инструменты портала, подключённых MCP-серверов и пользовательские HTTP-инструменты. +Без коллекций агент работает без MCP-инструментов. +Это правило одинаково для платформенного агента, внешних агентов, чата, виджетов и процессов. +Состав коллекции может включать инструменты портала, подключённых MCP-серверов и пользовательские HTTP-инструменты. -Например, чтобы агент читал каталог, включите `ddp_get_resources` и `ddp_get_resource_entities` в коллекцию, подключите её к агенту и предоставьте пользователю право использовать её. Для запуска процессов добавьте `get_processes`, `run_process` и `get_process_instance`. +Например, чтобы агент читал каталог, включите `ddp_get_resources` и `ddp_get_resource_entities` в коллекцию, подключите её к агенту и предоставьте пользователю право использовать её. +Для запуска процессов добавьте `get_processes`, `run_process` и `get_process_instance`. Пошаговая настройка — [в руководстве по MCP-коллекциям](../../user/mcp-management/#mcp-коллекции). ## Навыки агента -На той же вкладке назначьте [навыки](skills/) с конкретной версией или привязкой «Последняя». При запуске агент получает их названия и описания, полный текст читает через `get_skill` при необходимости. Этот инструмент должен быть доступен через коллекции агента и пользователя. +На той же вкладке назначьте [навыки](skills/) с конкретной версией или привязкой «Последняя». +При запуске агент получает их названия и описания, полный текст читает через `get_skill` при необходимости. +Этот инструмент должен быть доступен через коллекции агента и пользователя. Для инструкций и материалов в GitLab настройте [источник навыков](skill-sources/). ## Доступ к агентам -Использование регулируется глобальным `use:ai-agents` или объектным `use:ai-agent` для конкретного подключения. Право действует для чата, виджета и шага процесса. Оно не предоставляет доступ к данным каталога и не выдаёт инструменты MCP. +Использование регулируется глобальным `use:ai-agents` или объектным `use:ai-agent` для конкретного подключения. +Право действует для чата, виджета и шага процесса. +Оно не предоставляет доступ к данным каталога и не выдаёт инструменты MCP. Просмотр и изменение регулируются отдельными правами: @@ -64,13 +80,17 @@ AI-агент получает задачу на естественном язы | Источник агентов | `read:ai-agents`, `edit:ai-agents` | `read:ai-agent-source`, `edit:ai-agent-source` | | Шаблон AI-провайдера | `read:ai-provider-templates`, `edit:ai-provider-templates`, `use:ai-provider-templates` | `read:ai-provider-template`, `edit:ai-provider-template`, `use:ai-provider-template` | -Владение и участие в команде-владельце предоставляют права при включённом `owner-is-admin`. Доступ можно выдать другим пользователям и командам через «Настроить доступ». Супер-администратор имеет доступ ко всем подключениям. +Владение и участие в команде-владельце предоставляют права при включённом `owner-is-admin`. +Доступ можно выдать другим пользователям и командам через «Настроить доступ». +Супер-администратор имеет доступ ко всем подключениям. -История своих запусков требует `read:ai-agent-runs`, остановка — `cancel:ai-agent-runs`. Для раздела «AI» требуется `view:ai-page`; само по себе это разрешение не выдаёт доступ к его объектам. +История своих запусков требует `read:ai-agent-runs`, остановка — `cancel:ai-agent-runs`. +Для раздела «AI» требуется `view:ai-page`; само по себе это разрешение не выдаёт доступ к его объектам. ## Токен запуска и ограничения -Для разрешённых обращений к MCP и прокси моделей портал передаёт короткоживущий токен запуска. После завершения или остановки запуска токен отзывается. +Для разрешённых обращений к MCP и прокси моделей портал передаёт короткоживущий токен запуска. +После завершения или остановки запуска токен отзывается. Для запусков A2A-агентов действуют ограничения: diff --git a/content/documentation/admin/ai-agents/platform-agent.md b/content/documentation/admin/ai-agents/platform-agent.md new file mode 100644 index 00000000..480736bf --- /dev/null +++ b/content/documentation/admin/ai-agents/platform-agent.md @@ -0,0 +1,81 @@ +--- +title: Platform agent +weight: 20 +description: Preparing the ddp-agent platform agent for use, user access, MCP collections, skills, and troubleshooting. +--- + +The platform agent with the `ddp-agent` ID is deployed together with Deckhouse Development Portal (DDP). +It is available in the AI assistant, the "AI chat" widget, and process steps. + +The agent uses a language model through the AI provider of the running user. +In the catalog, it is marked as "DDP model"; the "Allow the DDP model proxy" switch in its connection is enabled and cannot be changed. +To work with project files, use a workspace. + +## Quick start + +To let users work with the agent and catalog data, follow these steps: + +1. Grant access to the agent with the global `use:ai-agents` permission or the object-level `use:ai-agent` permission. + For the "AI" section, add `view:ai-page`. +1. Prepare an [AI provider](../../user/ai-assistant/#connecting-an-ai-provider) or a [template with a shared token](provider-templates/). +1. Create an enabled MCP collection with the `ddp_get_resources` and `ddp_get_resource_entities` tools. +1. Grant the user permission to use this collection and read permissions on the required catalog objects. +1. In the agent catalog, open the platform agent for editing. + On the "Tools and skills" tab, select the collection in "MCP collections" and save. +1. In the AI assistant, select the agent and the provider, then ask it to show the available catalog resources. + +An empty set of collections means the agent works without MCP tools. +The portal does not automatically restore the previous set of read tools. + +## Changing tools and skills + +To extend the agent's capabilities, edit the collection or attach another one. +For example, for processes, add `get_processes`, `run_process`, and `get_process_instance`. +The user also needs access to these tools through collections and permissions for operations on entities. + +On the "Tools and skills" tab, you can assign [skills](skills/). +To read them, `get_skill` must be available in the run. + +When you add an entire portal group, new tools of that group are automatically included in the collection. +If the collection contents must stay fixed, select individual tools. + +## Deployment and settings + +The `development-platform` module creates the `agent` Deployment in `d8-development-platform`. +The agent is available inside the cluster at `http://agent:8080`; it does not need a separate Ingress. + +The module sets the API key and the card URL. +The portal creates the connection automatically and checks it when the backend starts and once a minute. +The name, description, enabled state, collections, and skills are set in the connection. +The `ddp-agent` ID, the card URL, and the key are managed by the installation. + +Disabling the agent removes it from selection in the chat, widgets, and processes. +The connection check does not re-enable it. +You cannot delete the platform agent connection. + +## Troubleshooting + +Check the agent status using the portal endpoint: + +```shell +curl -s https://ddp.example.com/healthz +``` + +The `agents` field shows the status: + +| Value | Meaning for the user | +| --- | --- | +| `ok` | The card can be read, the agent is ready | +| `unavailable` | The connection exists, but the card is unavailable | +| `not_configured` | The connection has not been created | + +If the agent is unavailable, check the pod and its logs: + +```shell +d8 k -n d8-development-platform get pods -l app=agent +d8 k -n d8-development-platform logs deploy/agent +``` + +If access is denied, check `use:ai-agents` or `use:ai-agent`. +If the agent responds without catalog data, check the agent's collections, the user's access to the tools, and the user's permissions on entities. +Check model errors in the AI provider and the [run history](runs/). diff --git a/content/documentation/admin/ai-agents/platform-agent.ru.md b/content/documentation/admin/ai-agents/platform-agent.ru.md index 089d843a..dfcea389 100644 --- a/content/documentation/admin/ai-agents/platform-agent.ru.md +++ b/content/documentation/admin/ai-agents/platform-agent.ru.md @@ -4,38 +4,54 @@ weight: 20 description: Подготовка платформенного агента ddp-agent к работе, доступ пользователей, MCP-коллекции, навыки и диагностика. --- -Платформенный агент с идентификатором `ddp-agent` разворачивается вместе с Deckhouse Development Portal (DDP). Он доступен в AI-ассистенте, виджете «AI-чат» и шагах процессов. +Платформенный агент с идентификатором `ddp-agent` разворачивается вместе с Deckhouse Development Portal (DDP). +Он доступен в AI-ассистенте, виджете «AI-чат» и шагах процессов. -Агент использует языковую модель через AI-провайдера запускающего пользователя. В каталоге он отмечен как «Модель DDP»; переключатель «Разрешить прокси моделей DDP» в его подключении включён и недоступен для изменения. Для работы с файлами проекта используйте [рабочее пространство](../../user/workspaces/). +Агент использует языковую модель через AI-провайдера запускающего пользователя. +В каталоге он отмечен как «Модель DDP»; переключатель «Разрешить прокси моделей DDP» в его подключении включён и недоступен для изменения. +Для работы с файлами проекта используйте [рабочее пространство](../../user/workspaces/). ## Быстрый старт Чтобы пользователи работали с агентом и данными каталога: -1. Выдайте доступ к агенту через глобальное `use:ai-agents` или объектное `use:ai-agent`. Для раздела «AI» добавьте `view:ai-page`. +1. Выдайте доступ к агенту через глобальное `use:ai-agents` или объектное `use:ai-agent`. + Для раздела «AI» добавьте `view:ai-page`. 1. Подготовьте [AI-провайдера](../../user/ai-assistant/#подключение-ai-провайдера) или [шаблон с общим токеном](provider-templates/). 1. Создайте включённую MCP-коллекцию с инструментами `ddp_get_resources` и `ddp_get_resource_entities`. 1. Предоставьте пользователю право использовать эту коллекцию и права чтения нужных объектов каталога. -1. В каталоге агентов откройте редактирование платформенного агента. На вкладке «Инструменты и навыки» выберите коллекцию в «MCP-коллекции» и сохраните. +1. В каталоге агентов откройте редактирование платформенного агента. + На вкладке «Инструменты и навыки» выберите коллекцию в «MCP-коллекции» и сохраните. 1. В AI-ассистенте выберите агента и провайдера, затем попросите показать доступные ресурсы каталога. -Пустой набор коллекций означает работу без MCP-инструментов. Портал не восстанавливает автоматически прежний набор инструментов чтения. +Пустой набор коллекций означает работу без MCP-инструментов. +Портал не восстанавливает автоматически прежний набор инструментов чтения. ## Изменение инструментов и навыков -Для расширения возможностей отредактируйте коллекцию или подключите другую. Например, для процессов добавьте `get_processes`, `run_process` и `get_process_instance`. Пользователю также необходимы доступ к этим инструментам через коллекции и разрешения на операции с сущностями. +Для расширения возможностей отредактируйте коллекцию или подключите другую. +Например, для процессов добавьте `get_processes`, `run_process` и `get_process_instance`. +Пользователю также необходимы доступ к этим инструментам через коллекции и разрешения на операции с сущностями. -На вкладке «Инструменты и навыки» можно назначить [навыки](skills/). Для их чтения в запуске должен быть доступен `get_skill`. +На вкладке «Инструменты и навыки» можно назначить [навыки](skills/). +Для их чтения в запуске должен быть доступен `get_skill`. -При добавлении группы портала целиком новые инструменты этой группы автоматически входят в коллекцию. Если состав должен быть фиксированным, выбирайте отдельные инструменты. +При добавлении группы портала целиком новые инструменты этой группы автоматически входят в коллекцию. +Если состав должен быть фиксированным, выбирайте отдельные инструменты. ## Развёртывание и настройки -Модуль `development-platform` создаёт Deployment `agent` в `d8-development-platform`. Агент доступен внутри кластера по `http://agent:8080`; отдельный Ingress ему не нужен. +Модуль `development-platform` создаёт Deployment `agent` в `d8-development-platform`. +Агент доступен внутри кластера по `http://agent:8080`; отдельный Ingress ему не нужен. -Модуль задаёт API-ключ и адрес карточки. Портал создаёт подключение автоматически и проверяет его при запуске backend и раз в минуту. Название, описание, включение, коллекции и навыки задаются в подключении. Идентификатор `ddp-agent`, адрес карточки и ключ управляются установкой. +Модуль задаёт API-ключ и адрес карточки. +Портал создаёт подключение автоматически и проверяет его при запуске backend и раз в минуту. +Название, описание, включение, коллекции и навыки задаются в подключении. +Идентификатор `ddp-agent`, адрес карточки и ключ управляются установкой. -Выключение агента убирает его из выбора в чате, виджетах и процессах. Проверка подключения не включает его обратно. Удаление подключения платформенного агента недоступно. +Выключение агента убирает его из выбора в чате, виджетах и процессах. +Проверка подключения не включает его обратно. +Удаление подключения платформенного агента недоступно. ## Диагностика @@ -60,4 +76,6 @@ d8 k -n d8-development-platform get pods -l app=agent d8 k -n d8-development-platform logs deploy/agent ``` -При отказе в доступе проверьте `use:ai-agents` или `use:ai-agent`. Если агент отвечает без данных каталога, проверьте коллекции агента, доступ пользователя к инструментам и его права на сущности. Ошибки модели проверяйте в AI-провайдере и [истории запусков](runs/). +При отказе в доступе проверьте `use:ai-agents` или `use:ai-agent`. +Если агент отвечает без данных каталога, проверьте коллекции агента, доступ пользователя к инструментам и его права на сущности. +Ошибки модели проверяйте в AI-провайдере и [истории запусков](runs/). diff --git a/content/documentation/admin/ai-agents/provider-templates.md b/content/documentation/admin/ai-agents/provider-templates.md new file mode 100644 index 00000000..6cb49a87 --- /dev/null +++ b/content/documentation/admin/ai-agents/provider-templates.md @@ -0,0 +1,109 @@ +--- +title: AI provider templates +weight: 60 +description: AI provider templates — preparing a language model connection for portal users, shared and personal tokens, and AI providers of service accounts. +--- + +{{< alert level="warning" >}} +AI agents are a Preview feature. +Agent types, available settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +An AI provider template is a language model connection that an administrator prepares for portal users. +The template defines the URL, method, headers, and models, and when connecting a provider from the template, the user selects a model and, depending on the template, enters their own token. + +A user needs an AI provider to work with the [platform agent](platform-agent/) and with external agents that are allowed to use the Deckhouse Development Portal (DDP) model proxy. + +## Token source + +A template works in one of the modes set by the "Token source" field: + +| Mode | How it works | +| --- | --- | +| "Personal token of each user" | The user connects a provider from the template in their profile and enters their own token | +| "One shared token for everyone" | The token is set in the template. The provider appears for every user allowed to use the template without connecting it. Such a provider cannot be deleted or changed in the profile | + +The token is stored encrypted and is substituted into the request headers in place of `{{ .token }}`. + +## Creating a template + +To create a template, follow these steps: + +1. Go to "AI" → "Agents" → "Provider templates". + Creating templates is available with the global `edit:ai-provider-templates` permission; viewing and editing existing templates can also be allowed by object-level roles. +1. Click "Create". +1. Fill in the template fields as described in ["Template parameters"](#template-parameters). +1. Click "Save". + +To prepare a template in advance, save it disabled. +The disabled state is preserved on creation; enable the template when it is ready for use. + +## Template parameters + +The template form contains the following fields: + +| Name | Required | Description | +| --- | --- | --- | +| "Name" | Yes | Template name that users see when connecting a provider | +| "Description" | No | Short description shown to users when connecting | +| "Default model" | Yes | Model used if the user has not selected another one | +| "Allowed models" | No | Models that the user can select. An empty list means any model | +| "Enabled" | — | A disabled template cannot be used for new connections | +| "URL" | Yes | Provider API URL, for example, `https://api.openai.com/v1/chat/completions` | +| "Method" | Yes | HTTP method of the request to the provider | +| "Token source" | Yes | Template mode. For details, see ["Token source"](#token-source) | +| "Token" | For a shared token | Token used to authorize all users of the template. When editing, an empty value keeps the current token | +| "Headers" | No | HTTP request headers. The token is substituted in place of `{{ .token }}`, for example, `Authorization: Bearer {{ .token }}` | +| "Response field" | No | Path to the model response text in the provider's JSON response, for example, `choices.0.message.content` | +| "Request body template" | No | JSON template of the request body with the `{{.prompt}}` and `{{.model}}` variables | + +For the template to work with agents, specify an API compatible with OpenAI Chat Completions: the URL must end with `/v1` or `/v1/chat/completions`. + +If you switch a template from a shared token to a personal one, the shared token is deleted. +You cannot delete a template from which users have connected providers. + +### OpenAI template example + +Example of a template with a shared token for the OpenAI API: + +| Field | Value | +| --- | --- | +| "Name" | `OpenAI` | +| "Default model" | `gpt-4o` | +| "URL" | `https://api.openai.com/v1/chat/completions` | +| "Method" | `POST` | +| "Token source" | "One shared token for everyone" | +| "Token" | OpenAI API key | +| "Headers" | `Authorization: Bearer {{ .token }}` | + +## Access to a template + +Using a template requires the global `use:ai-provider-templates` permission or the object-level `use:ai-provider-template` permission. +Ownership grants permissions when `owner-is-admin` is enabled. +This applies to templates with both personal and shared tokens. + +For a template with a shared token, access automatically creates a provider for the user. +For a specific template, grant the object-level `use:ai-provider-template` permission; the global `use:ai-provider-templates` permission grants access to all templates. +To grant access, select "Edit role bindings" in the template card menu and create a role binding for users or teams. + +Disabled templates are visible to users with read or edit permissions on the template, granted globally or on the object. +Other users see the template headers only with placeholder values. + +## User provider from a template + +For a provider connected from a template, the user can change only the name, the model within the "Allowed models" list, and the token. +The portal takes the URL, method, headers, and other connection parameters from the template, so template changes apply immediately to all connected providers. + +In the profile, such a provider is marked as "from template", and a provider from a template with a shared token is marked as "shared token". +For details on how a user connects a provider, see ["Connecting an AI provider"](../../user/ai-assistant/#connecting-an-ai-provider). + +## AI providers of service accounts + +A service account cannot sign in to a profile, so its AI providers are managed by an administrator with the `edit:users` permission. +An AI provider for a service account is needed, for example, when a process with the "AI agent" element runs on behalf of a service account. + +To configure an AI provider for a service account, follow these steps: + +1. Go to "Administration" → "Users". +1. In the service account row, click the button with the "Manage AI provider for this service account" tooltip. +1. Connect a provider from a template or set your own configuration, as in a user profile. diff --git a/content/documentation/admin/ai-agents/provider-templates.ru.md b/content/documentation/admin/ai-agents/provider-templates.ru.md index 225fa0f0..daa0677b 100644 --- a/content/documentation/admin/ai-agents/provider-templates.ru.md +++ b/content/documentation/admin/ai-agents/provider-templates.ru.md @@ -5,13 +5,14 @@ description: Шаблоны AI-провайдеров — подготовка --- {{< alert level="warning" >}} -AI-агенты — функциональность на стадии Preview. Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +AI-агенты — функциональность на стадии Preview. +Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} Шаблон AI-провайдера — подключение к языковой модели, которое администратор готовит для пользователей портала. В шаблоне задаются URL, метод, заголовки и модели, а пользователь при подключении провайдера из шаблона выбирает модель и, в зависимости от шаблона, вводит свой токен. -AI-провайдер нужен пользователю для работы с [платформенным агентом](platform-agent/) и с внешними агентами, которым разрешён прокси моделей DDP. +AI-провайдер нужен пользователю для работы с [платформенным агентом](platform-agent/) и с внешними агентами, которым разрешён прокси моделей Deckhouse Development Portal (DDP). ## Источник токена @@ -28,18 +29,20 @@ AI-провайдер нужен пользователю для работы с Чтобы создать шаблон: -1. Перейдите в раздел «AI» → «Агенты» → «Шаблоны провайдеров». Создание доступно с глобальным `edit:ai-provider-templates`; просмотр и изменение существующих шаблонов также могут быть разрешены объектными ролями. +1. Перейдите в раздел «AI» → «Агенты» → «Шаблоны провайдеров». + Создание доступно с глобальным `edit:ai-provider-templates`; просмотр и изменение существующих шаблонов также могут быть разрешены объектными ролями. 1. Нажмите «Создать». 1. Заполните поля шаблона, как описано в разделе [«Параметры шаблона»](#параметры-шаблона). 1. Нажмите «Сохранить». -Для предварительной подготовки сохраните шаблон выключенным. Выключенное состояние сохраняется при создании; включите шаблон, когда он будет готов к использованию. +Для предварительной подготовки сохраните шаблон выключенным. +Выключенное состояние сохраняется при создании; включите шаблон, когда он будет готов к использованию. ## Параметры шаблона Форма шаблона содержит поля: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Название» | Да | Название шаблона, которое видят пользователи при подключении провайдера | | «Описание» | Нет | Краткое описание для пользователей при подключении | @@ -75,9 +78,12 @@ AI-провайдер нужен пользователю для работы с ## Доступ к шаблону -Использование шаблона требует глобального `use:ai-provider-templates` или объектного `use:ai-provider-template`. Владение предоставляет права при включённом `owner-is-admin`. Это относится к шаблонам с личным и общим токеном. +Использование шаблона требует глобального `use:ai-provider-templates` или объектного `use:ai-provider-template`. +Владение предоставляет права при включённом `owner-is-admin`. +Это относится к шаблонам с личным и общим токеном. -Для шаблона с общим токеном доступ автоматически создаёт провайдера у пользователя. На конкретный шаблон выдавайте объектное `use:ai-provider-template`; глобальное `use:ai-provider-templates` даёт доступ ко всем шаблонам. +Для шаблона с общим токеном доступ автоматически создаёт провайдера у пользователя. +На конкретный шаблон выдавайте объектное `use:ai-provider-template`; глобальное `use:ai-provider-templates` даёт доступ ко всем шаблонам. Чтобы выдать доступ, в меню карточки шаблона выберите «Настроить доступ» и создайте привязку роли для пользователей или команд. Отключённые шаблоны видны пользователям с правами чтения или изменения шаблона, выданными глобально или на объект. diff --git a/content/documentation/admin/ai-agents/runs.md b/content/documentation/admin/ai-agents/runs.md new file mode 100644 index 00000000..265604db --- /dev/null +++ b/content/documentation/admin/ai-agents/runs.md @@ -0,0 +1,80 @@ +--- +title: Agent runs +weight: 50 +description: AI agent run history — statuses, run triggers, results, and stopping a run. +--- + +{{< alert level="warning" >}} +AI agents are a Preview feature. +Agent types, available settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +Every call to an AI agent creates a run: an answer to a question in the AI assistant, a response of the "AI chat" widget, or the execution of the "AI agent" process element. +A run stores the message sent to the agent, the response, tool calls, the error, and the result. + +## Run history + +The history is available in "AI" → "Usage" → "Audit", on the "Agent runs" tab, with the `read:ai-agent-runs` permission. +A user sees only their own runs; a super administrator sees runs of all users. + +You can filter the run table by the following fields: + +| Filter | Description | +| --- | --- | +| "Status" | Run status | +| "Trigger" | Where the agent was started from | +| "Agent" | Agent ID | +| "Period start", "Period end" | Time interval of the run start. The period start must not be later than the period end | +| "Search by agent, provider, or error" | Substring of up to 64 characters in the agent ID or name, the AI provider name, or the error text | + +## Run statuses + +A run has one of the following statuses: + +| Status | Meaning | +| --- | --- | +| "Running" (`running`) | The agent is performing the task | +| "Succeeded" (`succeeded`) | The agent returned a response | +| "Failed" (`failed`) | The run ended with an error, exceeded the maximum duration, or was interrupted | +| "Cancelled" (`cancelled`) | The run was stopped by a user or together with the process | + +## Triggers + +The "Trigger" field shows where the agent was started from: + +| Trigger | Where the agent is started from | +| --- | --- | +| "Chat" | A question in the AI assistant | +| "Widget" | A question in the "AI chat" widget | +| "Process" | The "AI agent" element in a process run | + +## Run details + +To open the details, click "Open" in the run row. +The "Agent run details" window shows the agent, status, trigger, AI provider, start and end time, the error and the provider response, and the run result. + +The result type is shown in the "Deliverable type" field: + +| Type | When used | Reference | +| --- | --- | --- | +| "Message" | The agent returned a text response | Run UUID | +| "Process store" | The agent was run by a process element, and the result was written to the process store | Store key | +| "Merge request", "Branch", "Patch" | The external agent reported the result in the response metadata | Link to the merge request, branch, or patch | + +For details on how an external agent reports the result type, see ["Run result"](external-agents/#run-result). + +## Stopping a run + +To stop a run in the "Running" status, click "Stop" in the run row or in the details window and confirm the action. +The button is available with the `cancel:ai-agent-runs` permission. + +After the run is stopped: + +- The run gets the "Cancelled" status. +- The portal revokes the run token, and the agent can no longer call portal tools or access the model through the portal. +- If the agent was started by a process element, the process continues according to the element's error handling rules. + +The portal does not send a task cancellation command to the external agent. +The agent keeps working until its next call to the portal, which fails with a `401` error. + +Runs created by process elements are also stopped when the process is stopped or force-restarted. diff --git a/content/documentation/admin/ai-agents/runs.ru.md b/content/documentation/admin/ai-agents/runs.ru.md index ca6fcca4..f20d64d5 100644 --- a/content/documentation/admin/ai-agents/runs.ru.md +++ b/content/documentation/admin/ai-agents/runs.ru.md @@ -5,7 +5,8 @@ description: История запусков AI-агентов — статус --- {{< alert level="warning" >}} -AI-агенты — функциональность на стадии Preview. Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +AI-агенты — функциональность на стадии Preview. +Виды агентов, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} Каждое обращение к AI-агенту создаёт запуск: ответ на вопрос в AI-ассистенте, ответ виджета «AI-чат», выполнение элемента процесса «AI-агент». @@ -49,7 +50,8 @@ AI-агенты — функциональность на стадии Preview. ## Детали запуска -Чтобы открыть детали, нажмите «Открыть» в строке запуска. В окне «Детали запуска агента» отображаются агент, статус, триггер, AI-провайдер, время начала и окончания, ошибка и ответ провайдера, а также результат запуска. +Чтобы открыть детали, нажмите «Открыть» в строке запуска. +В окне «Детали запуска агента» отображаются агент, статус, триггер, AI-провайдер, время начала и окончания, ошибка и ответ провайдера, а также результат запуска. Тип результата отображается в поле «Тип deliverable»: @@ -57,13 +59,14 @@ AI-агенты — функциональность на стадии Preview. | --- | --- | --- | | «Сообщение» | Агент вернул текстовый ответ | UUID запуска | | «Store процесса» | Агент выполнен элементом процесса, результат записан в хранилище процесса | Ключ хранилища | -| «Merge request», «Ветка», «Patch» | Внешний агент сообщил о результате в метаданных ответа | Ссылка на merge request, ветку или patch | +| «Merge request», «Ветка», «Patch» | Внешний агент сообщил о результате в метаданных ответа | Ссылка на запрос на слияние (Merge Request), ветку или patch | Как внешний агент сообщает тип результата — в разделе [«Результат запуска»](external-agents/#результат-запуска). ## Остановка запуска -Чтобы остановить запуск в статусе «Выполняется», нажмите «Остановить» в строке запуска или в окне деталей и подтвердите действие. Кнопка доступна с разрешением `cancel:ai-agent-runs`. +Чтобы остановить запуск в статусе «Выполняется», нажмите «Остановить» в строке запуска или в окне деталей и подтвердите действие. +Кнопка доступна с разрешением `cancel:ai-agent-runs`. После остановки: @@ -71,6 +74,7 @@ AI-агенты — функциональность на стадии Preview. - портал отзывает токен запуска, и агент больше не может вызывать инструменты портала и обращаться к модели через портал; - если агент запущен элементом процесса, процесс продолжает работу по правилам обработки ошибок элемента. -Портал не отправляет внешнему агенту команду отмены задачи. Агент продолжает работу до следующего обращения к порталу, которое завершается ошибкой `401`. +Портал не отправляет внешнему агенту команду отмены задачи. +Агент продолжает работу до следующего обращения к порталу, которое завершается ошибкой `401`. Запуски, созданные элементами процесса, также останавливаются при остановке и принудительном перезапуске процесса. diff --git a/content/documentation/admin/ai-agents/skill-sources.md b/content/documentation/admin/ai-agents/skill-sources.md new file mode 100644 index 00000000..89bfad45 --- /dev/null +++ b/content/documentation/admin/ai-agents/skill-sources.md @@ -0,0 +1,62 @@ +--- +title: Skills from GitLab +description: Preparing a skill repository, configuring a GitLab source, synchronizing versions, and archiving skills. +weight: 66 +--- + +A skill source synchronizes directories from GitLab with the Deckhouse Development Portal (DDP) skill catalog. +Edits are made in GitLab; the portal publishes immutable versions. + +## Repository structure + +Place skills in the immediate subdirectories of the selected path, each with its own `SKILL.md`: + +```text +skills/ + project-check/ + SKILL.md + references/ + checklist.md + release-prepare/ + SKILL.md + scripts/ + check.sh +``` + +The skill directory name must match the `name` in its `SKILL.md`. +The file format and limits are described in the [skills guide](skills/). + +## Connecting a source + +For synchronization, prepare a GitLab connection and the credentials of a user with access to the project. Then follow these steps: + +1. Open "AI" → "Skills" → "Skill sources" and click "Create source". +1. Set the source name, ID, owner, and team. +1. On the "Repository" tab, select "GitLab external service" and "Credentials user". +1. Specify "Project" as `group/project` or a numeric ID, "Branch or tag", and "Skills folder", for example, `skills`. + For the repository root, use `.`. +1. On the "Synchronization" tab, set "Schedule (cron)" and turn on "Synchronize on schedule" if you need automatic synchronization. +1. Save the source and click "Sync". +1. Check "Sync history" and the created skills. + +A disabled source can be synchronized with the button. +The source team manages the source itself when `owner-is-admin` is enabled; this team is not automatically assigned to the source's skills. + +## Publishing changes + +When the directory contents change, synchronization creates a new version labeled with the first 12 characters of the commit SHA. +If the files have not changed, no new version appears. + +Agents and templates with the "Latest" binding receive the new active version at the next run. +Pinned bindings continue to use the selected version. + +The sync history shows created, updated, unchanged, restored, archived, and skipped skills. +For a skipped skill, check the reason, the `SKILL.md` format, the directory name, file sizes, and the GitLab credentials. + +## Removing skills from a source + +If a directory disappears from the repository, the skill is archived. +Restoring the directory restores a skill archived by the source. + +To delete a source, all its skills must be archived. +After deletion, they remain archived manual skills with their versions. diff --git a/content/documentation/admin/ai-agents/skill-sources.ru.md b/content/documentation/admin/ai-agents/skill-sources.ru.md index 2353c5ae..f1220ff5 100644 --- a/content/documentation/admin/ai-agents/skill-sources.ru.md +++ b/content/documentation/admin/ai-agents/skill-sources.ru.md @@ -4,7 +4,8 @@ description: Подготовка репозитория навыков, нас weight: 66 --- -Источник навыков синхронизирует директории из GitLab с каталогом навыков DDP. Правки выполняются в GitLab; портал публикует неизменяемые версии. +Источник навыков синхронизирует директории из GitLab с каталогом навыков Deckhouse Development Portal (DDP). +Правки выполняются в GitLab; портал публикует неизменяемые версии. ## Структура репозитория @@ -22,7 +23,8 @@ skills/ check.sh ``` -Название директории навыка должно совпадать с `name` его `SKILL.md`. Формат файла и ограничения описаны [в руководстве по навыкам](skills/). +Название директории навыка должно совпадать с `name` его `SKILL.md`. +Формат файла и ограничения описаны [в руководстве по навыкам](skills/). ## Подключение источника @@ -31,23 +33,30 @@ skills/ 1. Откройте «AI» → «Навыки» → «Источники навыков» и нажмите «Создать источник». 1. Задайте название, идентификатор, владельца и команду источника. 1. На вкладке «Репозиторий» выберите «Внешний сервис GitLab» и «Пользователь для реквизитов». -1. Укажите «Проект» как `group/project` или числовой идентификатор, «Ветка или тег» и «Директория с навыками», например `skills`. Для корня репозитория используйте `.`. +1. Укажите «Проект» как `group/project` или числовой идентификатор, «Ветка или тег» и «Директория с навыками», например `skills`. + Для корня репозитория используйте `.`. 1. На вкладке «Синхронизация» задайте «Расписание (cron)» и включите «Синхронизировать по расписанию», если нужна автоматическая синхронизация. 1. Сохраните источник и нажмите «Синхронизировать». 1. Проверьте «История синхронизаций» и созданные навыки. -Выключенный источник можно синхронизировать кнопкой. Команда источника управляет самим источником при включённом `owner-is-admin`; навыкам источника эта команда автоматически не передаётся. +Выключенный источник можно синхронизировать кнопкой. +Команда источника управляет самим источником при включённом `owner-is-admin`; навыкам источника эта команда автоматически не передаётся. ## Публикация изменений -При изменении содержимого директории синхронизация создаёт новую версию с меткой из первых 12 символов SHA коммита. Без изменения файлов новая версия не появляется. +При изменении содержимого директории синхронизация создаёт новую версию с меткой из первых 12 символов SHA коммита. +Без изменения файлов новая версия не появляется. -Агенты и шаблоны с привязкой «Последняя» получают новую активную версию при следующем запуске. Закреплённые привязки продолжают использовать выбранную версию. +Агенты и шаблоны с привязкой «Последняя» получают новую активную версию при следующем запуске. +Закреплённые привязки продолжают использовать выбранную версию. -История синхронизаций показывает созданные, обновлённые, неизменившиеся, восстановленные, архивированные и пропущенные навыки. Для пропущенного навыка проверьте причину, формат `SKILL.md`, название директории, размеры файлов и реквизиты GitLab. +История синхронизаций показывает созданные, обновлённые, неизменившиеся, восстановленные, архивированные и пропущенные навыки. +Для пропущенного навыка проверьте причину, формат `SKILL.md`, название директории, размеры файлов и реквизиты GitLab. ## Удаление навыков из источника -Если директория исчезла из репозитория, навык архивируется. Возвращение директории восстанавливает навык, архивированный источником. +Если директория исчезла из репозитория, навык архивируется. +Возвращение директории восстанавливает навык, архивированный источником. -Для удаления источника его навыки должны быть в архиве. После удаления они остаются архивными ручными навыками со своими версиями. +Для удаления источника его навыки должны быть в архиве. +После удаления они остаются архивными ручными навыками со своими версиями. diff --git a/content/documentation/admin/ai-agents/skills.md b/content/documentation/admin/ai-agents/skills.md new file mode 100644 index 00000000..9f4d98e2 --- /dev/null +++ b/content/documentation/admin/ai-agents/skills.md @@ -0,0 +1,132 @@ +--- +title: Agent skills +description: Creating a skill with SKILL.md, publishing versions, binding skills to agents and workspaces, and installing them in an IDE. +weight: 65 +--- + +A skill is a directory with instructions in `SKILL.md` and additional scripts, reference files, and materials. +The portal stores skill versions and passes them to agents and workspaces. + +A skill defines how to perform a task. +Access to tools and objects is still defined by MCP collections and user roles. + +## Creating and publishing + +To create a skill for preparing project changes, follow these steps: + +1. Open "AI" → "Skills" → "Skills" and click "Create skill". +1. Set the name `project-check`, a description, the owner, and the team. +1. Open the draft on the "Files" tab and fill in `SKILL.md`: + + ```markdown + --- + name: project-check + description: Checks project changes before submitting them for review. Use after changing project files. + metadata: + version: "1.0" + --- + + # Checking changes + + 1. Read README.md and the project instructions. + 2. Identify the tests related to the changed files. + 3. Run these tests and check the result. + 4. Show the list of changes, the checks performed, and the remaining limitations. + ``` + +1. If needed, add files with the "Add file" button: scripts to `scripts/`, reference materials to `references/`, and other materials to `assets/`. +1. Save the draft and check the errors and warnings panel. +1. Click "Publish version", set a unique label, for example, `v1`, and publish. + +The skill name and description are defined by the `name` and `description` fields in `SKILL.md`. +To change them after creation, publish a new version. +Published files are immutable. + +## Importing an archive + +For import, prepare a `tar.gz` or `zip` archive with a single root directory whose name matches the `name` in `SKILL.md`: + +```text +project-check/ + SKILL.md + references/ + checklist.md + scripts/ + check.sh +``` + +In the skills section, select "Upload from archive", upload the file, and check the skill contents and versions. +Allowed sizes are listed in [Limits](#limits). + +## Binding to an agent + +To let an agent receive a published skill, follow these steps: + +1. Open the agent in "AI" → "Agents" → "Catalog" and select editing. +1. On the "Tools and skills" tab, add the skill and select a specific version or "Latest". +1. In "MCP collections", attach a collection with the `get_skill` tool; to read additional files, also add `get_skill_file`. +1. Grant the running user access to these tools through the MCP collections available to them. +1. Save the agent and start a new run. + +At run time, the agent receives the names and descriptions of the assigned skills and loads the full text when needed. +Without an available `get_skill`, the skill set is not passed; the bindings form shows a warning. +`list_skills` is intended for a regular MCP client; the agent receives its own prepared set. + +The "Latest" binding selects the active version with the highest number at the next run. +A pinned binding keeps the selected version. + +## Binding to a workspace + +Open a [workspace template](../workspaces/templates/), go to the "Skills" tab, and add the required skills. +For each binding, select a version or "Latest". + +The set is fixed when the workspace is created and every time it starts. +A new skill version does not immediately replace the set in a running workspace; stop and start it again. +The workspace card shows the fixed skills and available updates. + +For a template with Git, configure "Allow repository skills". +When the switch is off, the "Hidden skill folders" field sets the paths excluded from the working copy. +For example, `.agents/skills` or `**/skills`. + +Hiding uses Git sparse-checkout and does not delete files from the repository. +Local changes, untracked files, and conflicts may remain on disk; the list of such files appears as a warning in the startup log. +The repository contents remain accessible through `git show`. + +## Installing in a local IDE + +To use a skill outside a Deckhouse Development Portal (DDP) workspace, open its card and go to the "Install in IDE" block: + +1. Select "Latest" or "Specific version". +1. Create a portal API key in your profile and set it in the `DDP_API_KEY` environment variable of the terminal. +1. Copy the command from the card and run it in the root of the local project. +1. Check that `.agents/skills/project-check/SKILL.md` has appeared. + +The command downloads the archive of the selected version and extracts it to `.agents/skills`. +Running it again may replace files of an already installed copy of the skill. + +## Deprecated versions and archive + +On the "Versions" tab, you can mark a version as deprecated and specify the reason. +Such a version is not selected as "Latest"; pinned bindings to it are preserved. +If no active versions remain, "Latest" bindings skip the skill. + +An archived skill is skipped in new runs with a warning. +The "Usage" tab shows the agents and templates available to the user to which the skill is bound. +Check this list before archiving. + +## Limits + +When preparing a skill, take the following limits into account: + +| Limit | Value | +| --- | --- | +| Name | Up to 64 characters: lowercase Latin letters, digits, and single hyphens between them | +| Description | Up to 1,024 characters | +| Number of files | Up to 1,000 | +| File size | Up to 10 MiB | +| Total size of the skill and the imported archive | Up to 25 MiB | +| Number of assigned skills | Up to 20 per agent or template | +| Text file in the editor and when read through MCP | Up to 1 MiB | + +Scripts, `allowed-tools`, a long `SKILL.md`, and a missing `metadata.version` may produce warnings. +Check them before publishing. diff --git a/content/documentation/admin/ai-agents/skills.ru.md b/content/documentation/admin/ai-agents/skills.ru.md index ea136dae..f3e56937 100644 --- a/content/documentation/admin/ai-agents/skills.ru.md +++ b/content/documentation/admin/ai-agents/skills.ru.md @@ -4,9 +4,11 @@ description: Создание навыка с SKILL.md, публикация в weight: 65 --- -Навык — директория с инструкциями в `SKILL.md` и дополнительными скриптами, справочными файлами и материалами. Портал хранит версии навыков и передаёт их агентам и рабочим пространствам. +Навык — директория с инструкциями в `SKILL.md` и дополнительными скриптами, справочными файлами и материалами. +Портал хранит версии навыков и передаёт их агентам и рабочим пространствам. -Навык определяет, как выполнить задачу. Доступ к инструментам и объектам по-прежнему задаётся MCP-коллекциями и ролями пользователя. +Навык определяет, как выполнить задачу. +Доступ к инструментам и объектам по-прежнему задаётся MCP-коллекциями и ролями пользователя. ## Создание и публикация @@ -36,7 +38,9 @@ weight: 65 1. Сохраните черновик и проверьте панель ошибок и предупреждений. 1. Нажмите «Опубликовать версию», задайте уникальную метку, например `v1`, и опубликуйте. -Название и описание навыка определяются полями `name` и `description` в `SKILL.md`. Чтобы изменить их после создания, опубликуйте новую версию. Опубликованные файлы неизменяемы. +Название и описание навыка определяются полями `name` и `description` в `SKILL.md`. +Чтобы изменить их после создания, опубликуйте новую версию. +Опубликованные файлы неизменяемы. ## Импорт архива @@ -51,7 +55,8 @@ project-check/ check.sh ``` -В разделе навыков выберите «Загрузить из архива», загрузите файл и проверьте содержимое и версии навыка. Допустимые размеры приведены [в ограничениях](#ограничения). +В разделе навыков выберите «Загрузить из архива», загрузите файл и проверьте содержимое и версии навыка. +Допустимые размеры приведены [в ограничениях](#ограничения). ## Подключение к агенту @@ -63,36 +68,51 @@ project-check/ 1. Предоставьте запускающему пользователю доступ к этим инструментам через доступные ему MCP-коллекции. 1. Сохраните агента и начните новый запуск. -При запуске агент получает названия и описания назначенных навыков и загружает полный текст при необходимости. Без доступного `get_skill` набор навыков не передаётся; форма привязок показывает предупреждение. `list_skills` предназначен для обычного MCP-клиента; агент получает свой подготовленный набор. +При запуске агент получает названия и описания назначенных навыков и загружает полный текст при необходимости. +Без доступного `get_skill` набор навыков не передаётся; форма привязок показывает предупреждение. +`list_skills` предназначен для обычного MCP-клиента; агент получает свой подготовленный набор. -Привязка «Последняя» выбирает активную версию с наибольшим номером при следующем запуске. Закреплённая привязка сохраняет выбранную версию. +Привязка «Последняя» выбирает активную версию с наибольшим номером при следующем запуске. +Закреплённая привязка сохраняет выбранную версию. ## Подключение к рабочему пространству -Откройте [шаблон рабочего пространства](../workspaces/templates/), вкладку «Навыки», и добавьте нужные навыки. Для каждой привязки выберите версию или «Последняя». +Откройте [шаблон рабочего пространства](../workspaces/templates/), вкладку «Навыки», и добавьте нужные навыки. +Для каждой привязки выберите версию или «Последняя». -Набор фиксируется при создании и каждом запуске пространства. Новая версия навыка не заменяет набор в работающем пространстве немедленно; остановите и снова запустите его. На карточке пространства видны зафиксированные навыки и доступные обновления. +Набор фиксируется при создании и каждом запуске пространства. +Новая версия навыка не заменяет набор в работающем пространстве немедленно; остановите и снова запустите его. +На карточке пространства видны зафиксированные навыки и доступные обновления. -Для шаблона с Git настройте «Разрешить навыки из репозитория». При выключенном переключателе поле «Скрытые директории навыков» задаёт пути, исключаемые из рабочей копии. Например, `.agents/skills` или `**/skills`. +Для шаблона с Git настройте «Разрешить навыки из репозитория». +При выключенном переключателе поле «Скрытые директории навыков» задаёт пути, исключаемые из рабочей копии. +Например, `.agents/skills` или `**/skills`. -Скрытие использует Git sparse-checkout и не удаляет файлы из репозитория. Локальные изменения, неотслеживаемые файлы и конфликты могут остаться на диске; список таких файлов появляется предупреждением в логе запуска. Через `git show` содержимое репозитория остаётся доступным. +Скрытие использует Git sparse-checkout и не удаляет файлы из репозитория. +Локальные изменения, неотслеживаемые файлы и конфликты могут остаться на диске; список таких файлов появляется предупреждением в логе запуска. +Через `git show` содержимое репозитория остаётся доступным. ## Установка в локальную IDE -Для использования навыка вне рабочего пространства DDP откройте его карточку, блок «Установка в IDE»: +Для использования навыка вне рабочего пространства Deckhouse Development Portal (DDP) откройте его карточку, блок «Установка в IDE»: 1. Выберите «Последняя» или «Конкретная версия». 1. Создайте API-ключ портала в профиле и задайте его в переменной окружения `DDP_API_KEY` терминала. 1. Скопируйте команду из карточки и выполните её в корне локального проекта. 1. Проверьте появление `.agents/skills/project-check/SKILL.md`. -Команда скачивает архив выбранной версии и распаковывает его в `.agents/skills`. При повторном выполнении могут замениться файлы уже установленной копии навыка. +Команда скачивает архив выбранной версии и распаковывает его в `.agents/skills`. +При повторном выполнении могут замениться файлы уже установленной копии навыка. ## Устаревшие версии и архив -На вкладке «Версии» можно пометить версию устаревшей и указать причину. Такая версия не выбирается как «Последняя»; закреплённые привязки к ней сохраняются. Если активных версий не осталось, привязки «Последняя» пропускают навык. +На вкладке «Версии» можно пометить версию устаревшей и указать причину. +Такая версия не выбирается как «Последняя»; закреплённые привязки к ней сохраняются. +Если активных версий не осталось, привязки «Последняя» пропускают навык. -Архивный навык пропускается при новых запусках с предупреждением. Вкладка «Использование» показывает доступные пользователю агенты и шаблоны, к которым он привязан. Перед архивированием проверьте этот список. +Архивный навык пропускается при новых запусках с предупреждением. +Вкладка «Использование» показывает доступные пользователю агенты и шаблоны, к которым он привязан. +Перед архивированием проверьте этот список. ## Ограничения @@ -108,4 +128,5 @@ project-check/ | Число назначенных навыков | До 20 на агента или шаблон | | Текстовый файл в редакторе и чтении через MCP | До 1 МиБ | -Наличие скриптов, `allowed-tools`, длинного `SKILL.md` и отсутствие `metadata.version` могут давать предупреждения. Проверяйте их перед публикацией. +Наличие скриптов, `allowed-tools`, длинного `SKILL.md` и отсутствие `metadata.version` могут давать предупреждения. +Проверяйте их перед публикацией. diff --git a/content/documentation/admin/architecture/functional-architecture.md b/content/documentation/admin/architecture/functional-architecture.md new file mode 100644 index 00000000..8f23f886 --- /dev/null +++ b/content/documentation/admin/architecture/functional-architecture.md @@ -0,0 +1,228 @@ +--- +title: Functional architecture +description: Deckhouse Development Portal components, their functions, and network interactions. +weight: 10 +--- + +{{< alert level="info" >}} +The diagram uses the following simplifications. +It shows containers of different pods interacting with each other directly. +In fact, they interact through the corresponding Kubernetes Services (internal load balancers). +Service names are omitted when they are obvious from the context. +In other cases, the Service name is shown above the arrow. +Pods can run in multiple replicas, but the diagram shows each pod as a single replica. +{{< /alert >}} + +The following diagram shows the Deckhouse Development Portal (DDP, portal) architecture at level 2 of the C4 model and its interaction with other components: + +![DDP architecture](../images/functional-architecture/c4-l2-ddp.svg) + +## Components + +DDP consists of the following components: + +1. **Frontend** is the portal web interface built with Vue.js 3 and TypeScript. + The component consists of a single **frontend** container and provides users with a graphical interface for working with the portal in a web browser. + + Main functions: + + * Rendering the user interface for managing services, environments, and resources + * Handling user actions in the browser and sending requests to the backend through the REST API + + Technical details: + + * It serves the web interface files to the browser through the Ingress controller or Gateway + * It does not access the backend itself: the user's browser sends REST API requests through the same Ingress controller or Gateway + +1. **Backend** is the server side of the portal, written in Go. + The component provides a REST API for managing all portal mechanisms. + + Main functions: + + * Providing the REST API for programmatic interaction with the portal + * Processing the portal business logic + * Implementing access control (RBAC) and user permission management + * Integrating with external infrastructure services to perform various operations + * Managing data through PostgreSQL and Redis + + Technical details: + + * Accepts API requests from the web interface in the user's browser and from external REST API clients + * Signs users in through Dex and validates access tokens locally using cached signing keys + * Assigns tasks to the agent and forwards its requests to external language models + * Connects to Redis to coordinate the task queue + * Connects to PostgreSQL to store and manage data + * Connects to ClickHouse, if configured, to read the data stored there + + It consists of the following containers: + + * **wait-for-postgres**: Init container that waits until PostgreSQL starts accepting connections. For managed PostgreSQL instance, it also runs initial SQL scripts, for example, to create the required PostgreSQL extensions. + * **wait-for-redis**: Init container that waits until Redis starts accepting connections. + * **wait-for-clickhouse**: Init container that waits until ClickHouse (if configured) starts accepting connections. For managed ClickHouse instance, it also runs initial SQL scripts. + * **migrations**: Init container that updates the database schema when the component starts. + * **backend**: Main container. + +1. **Worker** is a component written in Go for running background tasks and asynchronous operations. + Worker processes tasks from Redis Streams queues: it runs actions and processes and synchronizes datasources. + For details, see ["Workers"](workers/) section. + + Main functions: + + * Synchronizing data from external sources + * Running actions and processes asynchronously + * Running entity status checks + * Running AI agents from "AI agent" process elements + + Technical details: + + * Can be deployed in multiple instances for scalability + * Uses Redis Streams to receive tasks from queues + * Connects to PostgreSQL to read and update data + * Integrates with external infrastructure services to perform operations + * Assigns tasks to the agent when running "AI agent" process elements + * Moves data from PostgreSQL to ClickHouse, if configured + + It consists of the following containers: + + * **wait-for-postgres**: Init container that waits until PostgreSQL starts accepting connections. For managed PostgreSQL instance, it also runs initial SQL scripts, for example, to create the required PostgreSQL extensions. + * **wait-for-redis**: Init container that waits until Redis starts accepting connections. + * **wait-for-clickhouse**: Init container that waits until ClickHouse (if configured) starts accepting connections. For managed ClickHouse instance, it also runs initial SQL scripts. + * **worker**: Main container. + +1. **Agent** is the component that implements the [platform agent](../ai-agents/platform-agent/). + The component consists of a single **agent** container. + By default, the agent handles requests in the [AI assistant](../../user/ai-assistant/) and in the ["AI chat"](../widgets/ai/chat/) widget; you can also select it in the ["AI agent"](../processes/overview/#ai-agent) process element. + + Technical details: + + * Accepts tasks from the backend and worker over the A2A protocol + * Accesses external language models and portal tools through the backend + * Available only inside the cluster, without an Ingress controller or Gateway + + DDP also supports connecting an [external AI agent](../ai-agents/external-agents/). + +Short-term and long-term data storage is provided by Redis, PostgreSQL, and ClickHouse. + +{{< alert level="info" >}} +For each of these components, you select a mode during installation: `internal` (an instance that is part of DDP), `managed` (an instance created by the corresponding Deckhouse managed module), or `external` (an existing external instance). +For production, use external database instances. +For details, see [Installation](../install/). +{{< /alert >}} + +The data storage components perform the following functions: + +1. **Redis** is an in-memory data store that the portal uses for task queues. + In `managed` mode, the Redis-compatible Valkey is used instead of Redis. + + Main functions: + + * Implementing task queues through Redis Streams for asynchronous processing + * Supporting distributed locks to coordinate multiple worker instances + * Delivering events generated by entity changes to automation handlers. + The events themselves are stored in PostgreSQL. + + Technical details: + + * Used to store task queues that are processed by the worker + +1. **PostgreSQL** is the main relational database of the portal, used to store all persistent information. + +1. **ClickHouse** is a store for large volumes of data, for example, the history of entity property changes. + + {{< alert level="info" >}} + You can install ClickHouse as part of DDP, create it using the `managed-clickhouse` module, or connect an external instance. + The portal works without ClickHouse, but features that depend on it are unavailable. + For example, the history of entity property changes is not saved. + For details, see [ClickHouse](../install/#clickhouse). + {{< /alert >}} + + Main functions: + + * Storing large volumes of records + * Serving queries that select from this data + + Technical details: + + * Populated by the worker, which moves data to it from PostgreSQL + * Accepts backend and worker connections over the native ClickHouse protocol + +The following component is not part of DDP: + +1. **Dex**: An authentication and authorization component that acts as an identity provider. + Dex provides a single sign-in point for users and integrates with various external authentication providers. + + {{< alert level="info" >}} + The Dex component is part of the [`user-authn`](/modules/user-authn/) module in Deckhouse Platform (DP). + {{< /alert >}} + + Main functions: + + * Managing the user authentication process + * Issuing access tokens + * Integrating with external authentication providers (Keycloak, LDAP, and others) + * Providing signing keys for token verification + + Technical details: + + * Shows the sign-in page to the user + * Issues and refreshes tokens on backend requests + * Periodically provides token signing keys for verification + * Integrates with external authentication providers through standard protocols (OIDC, LDAP, and others) + +## Workspaces + +[Workspaces](../workspaces/overview/) are created in the cluster and namespace of the template. +When installed by the module, OpenTofu operation Jobs run in the module namespace. +Persistent workspace data is stored on separate volumes; the OpenTofu state is passed to the portal HTTP backend. + +The starter template creates a pod with the following containers: + +| Container | Purpose | +| --- | --- | +| `bootstrap` | Init container: It clones the repository, delivers files and skills, and runs scripts | +| `runtime` | OpenCode agent that runs tasks from the chat and processes | +| `ide` | Code-server IDE with files from the same persistent volume | +| `gate` | Checks IDE access through the portal | + +The browser opens the IDE on a separate HTTPS domain through the Ingress of the target cluster. +The `gate` container checks access in DDP. +The agent accesses the model and MCP through the portal, so the pods require access to the DDP HTTPS address. +The setup is described in the [network and storage examples](../workspaces/network-storage/). + +## Network interactions + +![DDP components network interactions](../images/functional-architecture/ddp-network-flows.ru.svg) + +### Incoming connections + +Incoming connections are accepted by the cluster Ingress controller or Gateway over HTTPS (TCP/443) and forwarded to the portal components on port TCP/8080: + +* Users → DDP Frontend: The browser loads the web interface files. +* Users → DDP Backend: The browser sends REST API requests from the web interface; external clients access the REST API directly. + Requests to portal webhooks also go to the backend. +* Users → Dex (TCP/443): The browser opens the Dex sign-in page. + +### Interaction between portal components + +The portal components interact with each other as follows: + +* DDP Backend → Dex (TCP/443): Backend obtains user tokens at sign-in and on refresh, as well as signing keys for token verification. +* DDP Backend ↔ Redis (TCP/6379): Backend uses Redis to coordinate task queues and store events. +* DDP Backend ↔ PostgreSQL (TCP/5432): Backend reads and writes persistent data. +* DDP Worker ↔ Redis (TCP/6379): Worker receives tasks from Redis Streams queues and uses distributed locks. +* DDP Worker ↔ PostgreSQL (TCP/5432): Worker updates data in the database after running tasks. +* DDP Backend ↔ ClickHouse (TCP/9000, optional): Backend reads the data stored in ClickHouse. +* DDP Worker ↔ ClickHouse (TCP/9000, optional): Worker moves data from PostgreSQL to ClickHouse and deletes from it the data of objects that have already been deleted in the portal. +* DDP Backend → DDP Agent (TCP/8080): Backend assigns tasks from the AI assistant and the "AI chat" widget to the agent. +* DDP Worker → DDP Agent (TCP/8080): Worker assigns tasks from "AI agent" process elements to the agent. +* DDP Agent → DDP Backend (TCP/8080): Agent sends requests to the language model and calls portal tools. + +### Integration with external services + +The portal components interact with external services as follows: + +* Dex ↔ Authentication providers (Keycloak, LDAP, and others): Dex integrates with external user management systems. +* DDP Backend ↔ Infrastructure services (TCP/443): Backend interacts with external services to get information. +* DDP Worker ↔ Infrastructure services (TCP/443): Worker performs operations with external services when synchronizing data and running actions. +* DDP Backend → External language models (TCP/443): Backend forwards agent requests to the language model provider. +* DDP Backend and DDP Worker → External AI agents (TCP/443): The portal assigns tasks to connected external agents over the A2A protocol. diff --git a/content/documentation/admin/architecture/functional-architecture.ru.md b/content/documentation/admin/architecture/functional-architecture.ru.md index 55ead638..4be31266 100644 --- a/content/documentation/admin/architecture/functional-architecture.ru.md +++ b/content/documentation/admin/architecture/functional-architecture.ru.md @@ -5,10 +5,12 @@ weight: 10 --- {{< alert level="info" >}} -Для упрощения схемы приняты следующие допущения: - -* На схеме показано, что контейнеры разных подов взаимодействуют друг с другом напрямую. Фактически они взаимодействуют через соответствующие сервисы Kubernetes (внутренние балансировщики). Названия сервисов не указываются, если они очевидны из контекста. В остальных случаях название сервиса указано над стрелкой. -* Поды могут быть запущены в нескольких репликах, однако на схеме все поды изображены в одной реплике. +Для упрощения схемы приняты следующие допущения. +На схеме показано, что контейнеры разных подов взаимодействуют друг с другом напрямую. +Фактически они взаимодействуют через соответствующие сервисы Kubernetes (внутренние балансировщики). +Названия сервисов не указываются, если они очевидны из контекста. +В остальных случаях название сервиса указано над стрелкой. +Поды могут быть запущены в нескольких репликах, однако на схеме все поды изображены в одной реплике. {{< /alert >}} Архитектура Deckhouse Development Portal (DDP, портал) на уровне 2 модели C4 и его взаимодействие с другими компонентами изображены на следующей диаграмме: @@ -19,7 +21,8 @@ weight: 10 В состав DDP входят следующие компоненты: -1. **Frontend** — это веб-интерфейс портала, построенный на Vue.js 3 с TypeScript. Компонент состоит из одного контейнера **frontend** и предоставляет пользователям графический интерфейс для работы с порталом через веб-браузер. +1. **Frontend** — это веб-интерфейс портала, построенный на Vue.js 3 с TypeScript. + Компонент состоит из одного контейнера **frontend** и предоставляет пользователям графический интерфейс для работы с порталом через веб-браузер. Основные функции: @@ -31,7 +34,8 @@ weight: 10 * отдаёт браузеру файлы веб-интерфейса через Ingress-контроллер или Gateway; * не обращается к backend сам: запросы к REST API отправляет браузер пользователя через тот же Ingress-контроллер или Gateway. -1. **Backend** — это серверная часть портала, реализованная на языке Go. Компонент предоставляет REST API для управления всеми механизмами портала. +1. **Backend** — это серверная часть портала, реализованная на языке Go. + Компонент предоставляет REST API для управления всеми механизмами портала. Основные функции: @@ -52,11 +56,15 @@ weight: 10 Состоит из следующих контейнеров: - * **wait-for-storage** — init-контейнер, ожидающий, пока PostgreSQL, Redis и ClickHouse (если он настроен) начнут принимать подключения; для managed-экземпляров PostgreSQL и ClickHouse он также выполняет начальные SQL-скрипты, например создаёт нужные расширения PostgreSQL; + * **wait-for-postgres** — init-контейнер, ожидающий, пока PostgreSQL начнёт принимать подключения; для managed-экземпляра PostgreSQL он также выполняет начальные SQL-скрипты, например создаёт нужные расширения PostgreSQL; + * **wait-for-redis** — init-контейнер, ожидающий, пока Redis (в режиме `managed` вместо Redis используется совместимый с ним Valkey) начнёт принимать подключения; + * **wait-for-clickhouse** — опциональный init-контейнер, ожидающий, пока ClickHouse (если он настроен) начнёт принимать подключения; для managed-экземпляра ClickHouse он также выполняет начальные SQL-скрипты; * **migrations** — init-контейнер, выполняющий обновление структуры базы данных при старте компонента; * **backend** — основной контейнер. -1. **Worker** — это компонент для выполнения фоновых задач и асинхронных операций, реализованный на языке Go. Worker обрабатывает задачи из очередей Redis Streams: запускает действия и процессы, синхронизирует источники данных. Подробнее — в разделе [«Воркеры»](workers/). +1. **Worker** — это компонент для выполнения фоновых задач и асинхронных операций, реализованный на языке Go. + Worker обрабатывает задачи из очередей Redis Streams: запускает действия и процессы, синхронизирует источники данных. + Подробнее — в разделе [«Воркеры»](workers/). Основные функции: @@ -76,10 +84,14 @@ weight: 10 Состоит из следующих контейнеров: - * **wait-for-storage** — init-контейнер, ожидающий, пока PostgreSQL, Redis и ClickHouse (если он настроен) начнут принимать подключения; + * **wait-for-postgres** — init-контейнер, ожидающий, пока PostgreSQL начнёт принимать подключения; для managed-экземпляра PostgreSQL он также выполняет начальные SQL-скрипты, например создаёт нужные расширения PostgreSQL; + * **wait-for-redis** — init-контейнер, ожидающий, пока Redis (в режиме `managed` вместо Redis используется совместимый с ним Valkey) начнёт принимать подключения; + * **wait-for-clickhouse** — опциональный init-контейнер, ожидающий, пока ClickHouse (если он настроен) начнёт принимать подключения; для managed-экземпляра ClickHouse он также выполняет начальные SQL-скрипты; * **worker** — основной контейнер. -1. **Agent** — это компонент, реализующий [платформенный агент](../ai-agents/platform-agent/). Компонент состоит из одного контейнера **agent**. По умолчанию агент обрабатывает запросы в [AI-ассистенте](../../user/ai-assistant/) и в виджете [«AI-чат»](../widgets/ai/chat/); его также можно выбрать в элементе процесса [«AI-агент»](../processes/overview/#ai-агент). +1. **Agent** — это компонент, реализующий [платформенный агент](../ai-agents/platform-agent/). + Компонент состоит из одного контейнера **agent**. + По умолчанию агент обрабатывает запросы в [AI-ассистенте](../../user/ai-assistant/) и в виджете [«AI-чат»](../widgets/ai/chat/); его также можно выбрать в элементе процесса [«AI-агент»](../processes/overview/#ai-агент). Технические характеристики: @@ -89,19 +101,25 @@ weight: 10 DDP также поддерживает подключение [внешнего AI-агента](../ai-agents/external-agents/). -Следующие компоненты реализуют оперативное и долгосрочное хранение данных: +Оперативное и долгосрочное хранение данных реализуют компоненты Redis, PostgreSQL и ClickHouse. {{< alert level="info" >}} -Для каждого из этих компонентов при установке выбирается режим: `internal` — экземпляр в составе DDP, `managed` — экземпляр, который создаёт соответствующий managed-модуль Deckhouse, или `external` — существующий внешний экземпляр. Для промышленной эксплуатации используйте внешние экземпляры баз данных (БД). Подробнее — в разделе [«Установка»](../install/). +Для каждого из этих компонентов при установке выбирается режим: `internal` — экземпляр в составе DDP, `managed` — экземпляр, который создаёт соответствующий managed-модуль Deckhouse, или `external` — существующий внешний экземпляр. +Для промышленной эксплуатации используйте внешние экземпляры баз данных (БД). +Подробнее — в разделе [«Установка»](../install/). {{< /alert >}} -1. **Redis** — это хранилище данных в памяти, используемое порталом для работы с очередями задач. В режиме `managed` вместо Redis используется совместимый с ним Valkey. +Компоненты хранения данных выполняют следующие функции: + +1. **Redis** — это хранилище данных в памяти, используемое порталом для работы с очередями задач. + В режиме `managed` вместо Redis используется совместимый с ним Valkey. Основные функции: * реализация очередей задач через Redis Streams для асинхронной обработки; * поддержка распределённых блокировок для координации работы нескольких экземпляров worker; - * передача событий, генерируемых при изменениях сущностей, в обработчики автоматизаций. Сами события хранятся в PostgreSQL. + * передача событий, генерируемых при изменениях сущностей, в обработчики автоматизаций. + Сами события хранятся в PostgreSQL. Технические характеристики: @@ -112,7 +130,10 @@ weight: 10 1. **ClickHouse** — это хранилище для больших объёмов данных, например истории изменений параметров сущностей. {{< alert level="info" >}} - ClickHouse можно установить в составе DDP, создать с помощью модуля `managed-clickhouse` или подключить внешний экземпляр. Без ClickHouse портал работает, но зависящие от него возможности недоступны: например, не сохраняется история изменений параметров сущностей. Подробнее — в разделе [«ClickHouse»](../install/#clickhouse). + ClickHouse можно установить в составе DDP, создать с помощью модуля `managed-clickhouse` или подключить внешний экземпляр. + Без ClickHouse портал работает, но зависящие от него возможности недоступны. + Например, не сохраняется история изменений параметров сущностей. + Подробнее — в разделе [«ClickHouse»](../install/#clickhouse). {{< /alert >}} Основные функции: @@ -127,7 +148,8 @@ weight: 10 Следующий компонент не входит в состав DDP: -1. **Dex** — это компонент системы аутентификации и авторизации, выполняющий роль identity provider. Dex обеспечивает единую точку входа для пользователей и интегрируется с различными внешними провайдерами аутентификации. +1. **Dex** — это компонент системы аутентификации и авторизации, выполняющий роль identity provider. + Dex обеспечивает единую точку входа для пользователей и интегрируется с различными внешними провайдерами аутентификации. {{< alert level="info" >}} Компонент Dex является частью модуля [`user-authn`](/modules/user-authn/) в Deckhouse Platform (DP). @@ -149,7 +171,9 @@ weight: 10 ## Рабочие пространства -[Рабочие пространства](../workspaces/overview/) создаются в кластере и неймспейсе шаблона. При установке модулем Jobs операций OpenTofu запускаются в неймспейсе модуля. Постоянные данные рабочих пространств хранятся на отдельных томах; состояние OpenTofu передаётся в HTTP backend портала. +[Рабочие пространства](../workspaces/overview/) создаются в кластере и неймспейсе шаблона. +При установке модулем Jobs операций OpenTofu запускаются в неймспейсе модуля. +Постоянные данные рабочих пространств хранятся на отдельных томах; состояние OpenTofu передаётся в HTTP backend портала. Стартовый шаблон создаёт под с контейнерами: @@ -160,7 +184,10 @@ weight: 10 | `ide` | IDE code-server с файлами того же постоянного тома | | `gate` | Проверка доступа к IDE через портал | -Браузер открывает IDE по отдельному HTTPS-домену через Ingress целевого кластера. Контейнер `gate` проверяет доступ в DDP. Агент обращается к модели и MCP через портал, поэтому подам нужен доступ к HTTPS-адресу DDP. Настройка описана [в примерах сети и хранения](../workspaces/network-storage/). +Браузер открывает IDE по отдельному HTTPS-домену через Ingress целевого кластера. +Контейнер `gate` проверяет доступ в DDP. +Агент обращается к модели и MCP через портал, поэтому подам нужен доступ к HTTPS-адресу DDP. +Настройка описана [в примерах сети и хранения](../workspaces/network-storage/). ## Описание сетевых взаимодействий @@ -171,11 +198,14 @@ weight: 10 Входящие соединения принимает Ingress-контроллер или Gateway кластера по протоколу HTTPS (TCP/443) и пересылает их в компоненты портала на порт TCP/8080: * Пользователи → DDP Frontend: браузер загружает файлы веб-интерфейса. -* Пользователи → DDP Backend: браузер отправляет запросы к REST API с веб-интерфейса; внешние клиенты обращаются к REST API напрямую. На backend также поступают запросы к вебхукам портала. +* Пользователи → DDP Backend: браузер отправляет запросы к REST API с веб-интерфейса; внешние клиенты обращаются к REST API напрямую. + На backend также поступают запросы к вебхукам портала. * Пользователи → Dex (TCP/443): браузер открывает страницу входа Dex. ### Взаимодействие между компонентами портала +Компоненты портала взаимодействуют друг с другом следующим образом: + * DDP Backend → Dex (TCP/443): Backend получает токены пользователей при входе и при их обновлении, а также ключи подписи для проверки токенов. * DDP Backend ↔ Redis (TCP/6379): Backend использует Redis для координации очередей задач и хранения событий. * DDP Backend ↔ PostgreSQL (TCP/5432): Backend выполняет операции чтения и записи постоянных данных. @@ -189,6 +219,8 @@ weight: 10 ### Интеграция с внешними сервисами +Компоненты портала взаимодействуют с внешними сервисами следующим образом: + * Dex ↔ Провайдеры аутентификации (Keycloak, LDAP и др.): Dex интегрируется с внешними системами управления пользователями. * DDP Backend ↔ Инфраструктурные сервисы (TCP/443): Backend взаимодействует с внешними сервисами для получения информации. * DDP Worker ↔ Инфраструктурные сервисы (TCP/443): Worker выполняет операции с внешними сервисами при синхронизации данных и выполнении действий. diff --git a/content/documentation/admin/architecture/high-level-architecture.md b/content/documentation/admin/architecture/high-level-architecture.md new file mode 100644 index 00000000..ec7a2689 --- /dev/null +++ b/content/documentation/admin/architecture/high-level-architecture.md @@ -0,0 +1,108 @@ +--- +title: High-level architecture +description: Purpose of Deckhouse Development Portal, user groups, and ways to access the portal. +weight: 5 +--- + +## System goal and purpose + +Deckhouse Development Portal (DDP, portal) is an IDP (Internal Developer Platform), an internal developer portal that brings together tools, infrastructure services, and development processes. + +The portal provides a single layer for interacting with infrastructure and engineering services and is used to automate operations related to the product lifecycle. +DDP provides unified access to tools and resources, formalizes and automates development processes, and simplifies onboarding of new users and teams. + +The main tasks of the portal are as follows: + +- Enforcing common development standards across teams through templates and standard configurations +- Managing dynamic environments with automatic creation, update, and deletion of environments +- Integrating with external infrastructure services through APIs +- Simplifying developer and team onboarding with templates and documentation +- Digitizing development processes and workflows through a BPMN-like process description mechanism +- Providing a built-in CMDB that automatically collects data from infrastructure services and visualizes dependencies +- Controlling entity properties through status checks + +## System users + +Several groups of users work with the portal. + +### Development teams + +Development teams use DDP to work with portal entities and resources. +These teams create and manage entities, run actions, view data from datasources, use widgets, and work with processes. + +### Management + +Management receives statistics and data for decision-making. +Management-level users can view dashboards with metrics, analyze development efficiency, track key indicators, and get reports on team performance. + +### Infrastructure teams + +These teams provide services and resources through DDP. +They configure integrations with external services, set up resources, create templates and automations, manage environments, and keep the portal running. + +### Security teams + +Security teams use DDP to provide and manage security tools, perform audits, and monitor compliance. +In the portal, they configure security policies and access permissions, view audit logs, and manage protection mechanisms. + +### Administrators + +Administrators are users with full permissions to configure and maintain the portal. +They manage user accounts, configure roles and access permissions through RBAC, configure integrations with external services, manage credentials, resources, automations, and portal settings, and view audit logs. + +Access permissions for all user groups are configured through role-based access control (RBAC), which provides flexible permission management at the level of global roles, resource roles, and entity roles. + +## System access + +Users and external systems access the portal through the web interface and the REST API. + +### Web interface + +All user groups access the portal through the DDP Frontend web interface, which is designed for working with the portal in a web browser. + +Access protocol: HTTPS (TCP/443) + +Authentication: Users authenticate through the Dex component, which integrates with external authentication providers (Keycloak, LDAP, and others) through standard protocols (OIDC, LDAP). +After successful authentication, the user receives a JWT access token, which is used to authorize requests to the portal. + +### REST API + +Administrators and developers can access DDP Backend directly through the REST API to interact with the portal programmatically. + +Access protocol: HTTPS (TCP/443) + +The browser authenticates with a session stored in a cookie file with the `HttpOnly` flag (JWT from Dex). +For programmatic access, use an API token from the "Profile" section, passed in the `Authorization: Bearer ` header. + +The REST API provides a full set of functions for managing all portal objects: entities, resources, actions, datasources, widgets, processes, and other components. + +## Access from outside and inside the company perimeter + +DDP is deployed in a Kubernetes cluster and can be accessible both inside the corporate perimeter and from outside, depending on the network infrastructure configuration. + +### Access inside the perimeter + +In a typical scenario, users access the portal through the company's internal network. This type of access has the following characteristics: + +- The web interface and REST API are available through an internal Ingress controller. +- Access is provided through internal domain names (for example, `ddp.internal.company.com`). +- Authentication can be integrated with corporate LDAP or Active Directory through Dex. +- Additional protection can be provided by Kubernetes network policies. + +### Access outside the perimeter + +In a typical scenario, users access the portal from outside the corporate network. This type of access has the following characteristics: + +- The web interface and REST API are available through a public Ingress controller. +- Access is provided through public domain names (for example, `ddp.company.com`). +- Authentication can be integrated with external authentication providers through Dex. + +### Hybrid access + +The portal can be configured to support both scenarios at the same time: + +- Internal users access the portal through an internal Ingress. +- External users (for example, remote employees) access the portal through a public Ingress or VPN. +- Different user groups can use different authentication providers through Dex. + +The administrator configures access when deploying the portal, using Ingress controller parameters and Kubernetes network policies. diff --git a/content/documentation/admin/architecture/high-level-architecture.ru.md b/content/documentation/admin/architecture/high-level-architecture.ru.md index ccb9545f..bea13394 100644 --- a/content/documentation/admin/architecture/high-level-architecture.ru.md +++ b/content/documentation/admin/architecture/high-level-architecture.ru.md @@ -23,6 +23,8 @@ DDP обеспечивает единый доступ к инструмента ## Пользователи системы +С порталом работают несколько групп пользователей. + ### Команды разработки Команды разработки используют DDP для работы с сущностями и ресурсами портала. @@ -30,7 +32,8 @@ DDP обеспечивает единый доступ к инструмента ### Менеджмент -Менеджмент получает статистику и данные для принятия решений. Пользователи управленческого уровня могут просматривать дашборды с метриками, анализировать эффективность разработки, отслеживать ключевые показатели и получать отчёты о работе команд. +Менеджмент получает статистику и данные для принятия решений. +Пользователи управленческого уровня могут просматривать дашборды с метриками, анализировать эффективность разработки, отслеживать ключевые показатели и получать отчёты о работе команд. ### Команды инфраструктуры @@ -51,13 +54,16 @@ DDP обеспечивает единый доступ к инструмента ## Доступ к системе +Пользователи и внешние системы получают доступ к порталу через веб-интерфейс и REST API. + ### Веб-интерфейс Все группы пользователей получают доступ к порталу через веб-интерфейс DDP Frontend, предназначенный для работы с порталом в веб-браузере. Протокол доступа: HTTPS (TCP/443) -Аутентификация: Пользователи проходят аутентификацию через компонент Dex, который интегрируется с внешними провайдерами аутентификации (Keycloak, LDAP и др.) через стандартные протоколы (OIDC, LDAP). После успешной аутентификации пользователь получает JWT-токен доступа, который используется для авторизации запросов к порталу. +Аутентификация: Пользователи проходят аутентификацию через компонент Dex, который интегрируется с внешними провайдерами аутентификации (Keycloak, LDAP и др.) через стандартные протоколы (OIDC, LDAP). +После успешной аутентификации пользователь получает JWT-токен доступа, который используется для авторизации запросов к порталу. ### REST API @@ -65,10 +71,8 @@ DDP обеспечивает единый доступ к инструмента Протокол доступа: HTTPS (TCP/443) -Аутентификация: - -- Браузер: сессия по файлу cookie с флагом `HttpOnly` (JWT от Dex). -- Программный доступ: API-токен из раздела «Профиль», заголовок `Authorization: Bearer `. +Браузер аутентифицируется сессией по файлу cookie с флагом `HttpOnly` (JWT от Dex). +Для программного доступа используется API-токен из раздела «Профиль», который передаётся в заголовке `Authorization: Bearer `. REST API предоставляет полный набор функций для управления всеми объектами портала: сущностями, ресурсами, действиями, источниками данных, виджетами, процессами и другими компонентами. @@ -78,7 +82,7 @@ DDP развёртывается в кластере Kubernetes и может б ### Доступ внутри периметра -Типичный сценарий: Пользователи получают доступ к порталу через внутреннюю сеть компании. +В типичном сценарии пользователи получают доступ к порталу через внутреннюю сеть компании. Особенности такого доступа: - Веб-интерфейс и REST API доступны через внутренний Ingress-контроллер. - Доступ осуществляется по внутренним доменным именам (например, `ddp.internal.company.com`). @@ -87,7 +91,7 @@ DDP развёртывается в кластере Kubernetes и может б ### Доступ снаружи периметра -Типичный сценарий: Пользователи получают доступ к порталу извне корпоративной сети. +В типичном сценарии пользователи получают доступ к порталу извне корпоративной сети. Особенности такого доступа: - Веб-интерфейс и REST API доступны через публичный Ingress-контроллер. - Доступ осуществляется по публичным доменным именам (например, `ddp.company.com`). diff --git a/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.ru.svg b/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.ru.svg index b443eb1a..22719f21 100644 --- a/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.ru.svg +++ b/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.ru.svg @@ -1 +1 @@ -Пользователь [Person]а также разработчик,администратор и инженербезопасностиИнфраструктурныесервисы,предоставляющие APIGitLab/GitHub/Bitbucket,Sonarqube/DefectDojo/CodeScoring,Jira/Kaiten, Nexus/Docker RegistryВнешние провайдерыаутентификацииOIDC, LDAP, GitLab, GitHubDexGateway/Ingress-контроллерИнстанс PostgreSQLPostgreSQLИнстанс RedisRedis / ValkeyИнстанс ClickHouseClickHouseВнешние языковыемоделиOpenAI, Gemini,OpenAI-compatibleDeckhouse Development Portal[Software System]Подсистема DDPbackend [pod]frontend [pod]agent [pod]workers [pod]wait-for-storage (init)[Container: init]migrations (init)[Container: init]backend[Container]frontend[Container]agent[Container]wait-for-storage (init)[Container: init]worker[Container]Получает токены и ключиподписи для их проверки[443 TCP]Управляет задачами вочереди[6379 TCP]Обрабатывает данныепостоянного хранения[5432 TCP]Получает и выполняетзадачи из очереди[6379 TCP]Обновляет данные вбазе после выполнениязадач[5432 TCP]Читает историюизменений параметровсущностей[9000 TCP]Переносит данные изPostgreSQL, удаляетстарые записи[9000 TCP]Выполняетаутентификациюпользователей[HTTPS]Управляетпорталом черезвеб-интерфейсПересылаетзапросыпользователя[8080 TCP]Пересылаетзапросы к API[8080 TCP]Получаетинформацию[HTTPS]Синхронизирует данныеи выполняет заданныеоперации[HTTPS]Ставит задачуагенту[8080 TCP]Вызывает внешнююязыковую модель,вызывает инструментыпортала, возвращаетрезультат запроса[8080 TCP]Пересылаетзапросы отагентаСтавит задачуагенту[8080 TCP]Пересылает запросына страницу входа[443 TCP] \ No newline at end of file +Пользователь [Person]а также разрабочик,администратор и инженербезопасностиИнфраструктурныесервисы,предоставляющие APIGitLab/GitHub/Bitbucket,Sonarqube/DefectDojo/CodeScoring,Jira/Kaiten, Nexus/Docker RegistryВнешние провайдерыаутентификацииOIDC, LDAP, GitLab, GitHubDexGateway/Ingress-контроллерИнстанс PostgreSQLPostgreSQLИнстанс RedisRedisИнстанс ClickHouseClickHouseВнешние языковыемоделиOpenAI, Gemini,OpenAI-compatibleDeckhouse Development Portal[Software System]Подсистема DDPbackend [pod]frontend [pod]agent [pod]workers [pod]wait-for-postgres (init,optional, backend)[Container: init]wait-for-redis (init,optional, backend)[Container: init]wait-for-clickhouse (init,optional, backend)[Container: init]migrations (init)[Container: init]backend[Container]frontend[Container]agent[Container]wait-for-postgres (init,optional, worker)[Container: init]wait-for-redis (init,optional, worker)[Container: init]wait-for-clickhouse (init,optional, worker)[Container: init]worker[Container]Передаёт запросыпользователя[8080 TCP]Получает ключи подписидля проверки токенов[443 TCP]Управляет задачами вочереди[6379 TCP]Обрабатывает данныепостоянного хранения[5432 TCP]Получает и выполняетзадачи из очереди[6379 TCP]Обновляет данные в базепосле выполнения задач[5432 TCP]Читает историюизменений параметровсущностей[9000 TCP]Переносит данные изPostgreSQL, удаляетстарые записи[9000 TCP]Выполняетаутентификациюпользователей[HTTPS]Управляетпорталом черезвеб-интерфейсПересылаетзапросыпользователя[8080 TCP]Пересылаетзапросы к API[8080 TCP]Получаетинформацию[HTTPS]Синхронизирует данные ивыполняет заданныеоперации[HTTPS]Ставит задачуагенту[8080 TCP]Вызывает внешнююязыковую модель,вызывает инструментыпортала, возвращаетрезультат запроса[8080 TCP]Пересылаетзапросы отагента \ No newline at end of file diff --git a/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.svg b/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.svg new file mode 100644 index 00000000..c6a1d306 --- /dev/null +++ b/content/documentation/admin/architecture/images/functional-architecture/c4-l2-ddp.svg @@ -0,0 +1 @@ +User [Person]as well as a developer,administrator and securityengineerInfrastructure servicesproviding APIGitLab/GitHub/Bitbucket,Sonarqube/DefectDojo/CodeScoring,Jira/Kaiten, Nexus/Docker RegistryExternal authenticationprovidersOIDC, LDAP, GitLab, GitHubDexGateway/IngresscontrollerPostgreSQL instancePostgreSQLRedis instanceRedisClickHouse instanceClickHouseExternal languagemodelsOpenAI, Gemini,OpenAI-compatibleDeckhouse Development Portal[Software System]DDP subsystembackend [pod]frontend [pod]agent [pod]workers [pod]wait-for-postgres (init,optional, backend)[Container: init]wait-for-redis (init,optional, backend)[Container: init]wait-for-clickhouse (init,optional, backend)[Container: init]migrations (init)[Container: init]backend[Container]frontend[Container]agent[Container]wait-for-postgres (init,optional, worker)[Container: init]wait-for-redis (init,optional, worker)[Container: init]wait-for-clickhouse (init,optional, worker)[Container: init]worker[Container]Transmits user requests[8080 TCP]Obtains signing keys fortoken verification[443 TCP]Manages tasks in thequeue[6379 TCP]Processes persistentstorage data[5432 TCP]Receives and executestasks from the queue[6379 TCP]Updates data in thedatabase after taskexecution[5432 TCP]Reads the history of entityparameter changes[9000 TCP]Migrates data fromPostgreSQL, deletes oldrecords[9000 TCP]Performs userauthentication[HTTPS]Manages theportal via theweb interfaceForwards userrequests[8080 TCP]Forwardsrequests to theAPI[8080 TCP]Retrievesinformation[HTTPS]Synchronizes data andperforms specifiedoperations[HTTPS]Assigns a task tothe agent[8080 TCP]Calls an external languagemodel, invokes portaltools, returns the requestresult[8080 TCP]Forwardsrequests fromthe agent \ No newline at end of file diff --git a/content/documentation/admin/architecture/overview.md b/content/documentation/admin/architecture/overview.md new file mode 100644 index 00000000..d04cc207 --- /dev/null +++ b/content/documentation/admin/architecture/overview.md @@ -0,0 +1,18 @@ +--- +title: Overview +description: Contents of the Deckhouse Development Portal architecture section. +weight: 1 +--- + +This section describes how Deckhouse Development Portal (DDP, portal) is built: its purpose, components, network interactions, and background task processing. +Use this information to plan the installation, configure network access, and troubleshoot the portal. + +The section consists of the following pages: + +| Page | Contents | +| --- | --- | +| [High-level architecture](high-level-architecture/) | Purpose of the portal, user groups, and ways to access the portal | +| [Functional architecture](functional-architecture/) | Portal components, their functions, and network interactions | +| [Workers](workers/) | Configuring, monitoring, and scaling the workers that run background tasks | + +For compute resource requirements for different load profiles, see [Resource requirements](../resource-requirements/). diff --git a/content/documentation/admin/architecture/overview.ru.md b/content/documentation/admin/architecture/overview.ru.md new file mode 100644 index 00000000..5fa55933 --- /dev/null +++ b/content/documentation/admin/architecture/overview.ru.md @@ -0,0 +1,18 @@ +--- +title: Обзор +description: Состав раздела об архитектуре Deckhouse Development Portal. +weight: 1 +--- + +Раздел описывает устройство Deckhouse Development Portal (DDP, портал): его назначение, компоненты, сетевые взаимодействия и фоновую обработку задач. +Сведения помогут спланировать установку, настроить сетевой доступ и диагностировать работу портала. + +Раздел состоит из следующих страниц: + +| Страница | Содержание | +| --- | --- | +| [Верхнеуровневая архитектура](high-level-architecture/) | Назначение портала, группы пользователей и способы доступа к порталу | +| [Функциональная архитектура](functional-architecture/) | Компоненты портала, их функции и сетевые взаимодействия | +| [Воркеры](workers/) | Настройка, мониторинг и масштабирование воркеров, которые выполняют фоновые задачи | + +Требования к вычислительным ресурсам для разных профилей нагрузки приведены в разделе [«Требования к вычислительным ресурсам»](../resource-requirements/). diff --git a/content/documentation/admin/architecture/workers.md b/content/documentation/admin/architecture/workers.md new file mode 100644 index 00000000..61bc1530 --- /dev/null +++ b/content/documentation/admin/architecture/workers.md @@ -0,0 +1,138 @@ +--- +title: Workers +description: Configuring, monitoring, and scaling the workers that run Deckhouse Development Portal background tasks. +weight: 20 +--- + +Workers are Deckhouse Development Portal (DDP, portal) components that process tasks from a queue in the background. +They run various operations asynchronously, such as: + +- Synchronizing data from datasources +- Running actions and processes +- Running entity status checks +- Running AI agents from "AI agent" process elements +- Periodically synchronizing catalogs of external MCP servers + +Workers run independently of the main application and let you scale the system load by moving resource-intensive operations to dedicated replicas. + +## Configuration + +Worker parameters are set in the `spec.settings.workers` section of the `development-platform` ModuleConfig or in the module settings in the Deckhouse web UI. +The following parameters are available. + +### Number of replicas + +The `workers.replicas` parameter sets the number of workers running at the same time. +Default value: `2`. +Each worker processes tasks independently of the others. + +### Maximum number of parallel tasks + +The `workers.maxTasks` parameter sets how many tasks each worker processes in parallel. Default value: `10`. + +{{< alert level="info" >}} +The total number of tasks processed simultaneously by the whole system is calculated as `workers.replicas × workers.maxTasks`. +For example, with 2 workers and 10 tasks per worker, the system can process up to 20 tasks at the same time. +{{< /alert >}} + +## Monitoring + +To monitor workers and the task queue, use the ["Task queue"](../../widgets/generic/task-queue/) widget, which shows: + +- Queue size (total number of tasks) +- Number of pending tasks +- Number of active workers (consumers) +- Detailed information about tasks in the queue +- Status of each task (new, in progress) + +## Types of processed tasks + +Workers process the following types of tasks: + +### Entity status check tasks + +Status check tasks are run by workers, which determine the state of entities based on the configured rules. +This approach lets you: + +- Reduce the load on the main server +- Keep the system stable with a large number of entities +- Guarantee that checks run even when the main application is under high load + +### Datasource synchronization tasks + +Workers process tasks that synchronize data from external sources, which lets you: + +- Run synchronization in the background +- Avoid blocking the user interface +- Process large amounts of data + +### Action execution tasks + +Long-running actions are processed by workers, which provides: + +- Asynchronous execution of actions +- The ability to track execution progress +- A stable user interface + +### AI agent run tasks + +Workers run [AI agents](../ai-agents/overview/) from "AI agent" process elements: they send the task to the agent over the A2A protocol and wait for it to complete. +A single run is limited to 70 minutes. +While a run is in progress, it occupies one of the worker's `workers.maxTasks` parallel tasks. + +### MCP server synchronization + +Periodic synchronization of MCP server catalogs is performed by workers. +Enable it in the server settings and specify a system account. +If an attempt fails, the previous catalog is kept; the results and update time are shown on the server card. +For setup instructions, see the [MCP guide](../../user/mcp-management/#mcp-servers). + +## Background ClickHouse data operations + +If [ClickHouse](../../install/#clickhouse) is connected, workers also move data to it from PostgreSQL and clean up obsolete data. +For example, this is how the history of entity property changes is maintained: + +- Moving new change records from PostgreSQL to ClickHouse +- Rebuilding queue indexes in PostgreSQL after a large volume of changes is moved +- Deleting the history of entities and properties that no longer exist +- Deleting history that is past its retention period + +These operations are not taken from the task queue. +Each worker starts them on its own, and a distributed lock prevents them from running in several replicas at the same time. +If no worker is running, property changes are still written to PostgreSQL and remain visible in the interface, but the transfer queue is not processed and keeps growing. + +Transfer parameters are set in the `clickhouse.replication` section of the module settings: the transfer batch size and interval, and index rebuilding. +The history retention period and cleanup interval are set in the `clickhouse.propertyHistory` section. + +## Scaling + +To increase system performance, you can: + +1. Increase the number of worker replicas to process more tasks at the same time. +1. Increase the number of parallel tasks per worker to improve the utilization of each worker. + +{{< alert level="info" >}} +When increasing the load on workers, make sure the cluster has enough resources (CPU, memory) to process all tasks. +{{< /alert >}} + +## Troubleshooting + +This section describes common problems with workers and how to resolve them. + +### Workers do not process tasks + +If tasks accumulate in the queue and are not processed: + +1. Check that the workers are deployed and running (using the "Task queue" widget). +1. Make sure the number of worker replicas is greater than 0. +1. Check the worker logs for errors. +1. Make sure the workers have enough resources (CPU, memory). + +### Slow task processing + +If tasks are processed slowly: + +1. Increase the number of worker replicas. +1. Increase the number of parallel tasks per worker (if resources allow). +1. Check the performance of the external systems the workers interact with. +1. Make sure there are no bottlenecks in the network or database. diff --git a/content/documentation/admin/architecture/workers.ru.md b/content/documentation/admin/architecture/workers.ru.md index c1287a11..83a41f74 100644 --- a/content/documentation/admin/architecture/workers.ru.md +++ b/content/documentation/admin/architecture/workers.ru.md @@ -4,7 +4,8 @@ description: Настройка, мониторинг и масштабиров weight: 20 --- -Воркеры — это компоненты DDP (портала), которые обрабатывают задачи из очереди в фоновом режиме. Они обеспечивают асинхронное выполнение различных операций, таких как: +Воркеры — это компоненты Deckhouse Development Portal (DDP, портала), которые обрабатывают задачи из очереди в фоновом режиме. +Они обеспечивают асинхронное выполнение различных операций, таких как: - Синхронизация данных из источников данных. - Запуск действий и процессов. @@ -16,18 +17,22 @@ weight: 20 ## Конфигурация -Параметры воркеров задаются в секции `spec.settings.workers` ModuleConfig `development-platform` или в настройках модуля в веб-интерфейсе Deckhouse Platform. Доступны следующие параметры. +Параметры воркеров задаются в секции `spec.settings.workers` ModuleConfig `development-platform` или в настройках модуля в веб-интерфейсе Deckhouse Platform. +Доступны следующие параметры. ### Количество реплик -Параметр `workers.replicas` определяет количество одновременно работающих воркеров. По умолчанию — `2`. Каждый воркер обрабатывает задачи независимо от других. +Параметр `workers.replicas` определяет количество одновременно работающих воркеров. +По умолчанию — `2`. +Каждый воркер обрабатывает задачи независимо от других. ### Максимальное количество параллельных задач Параметр `workers.maxTasks` определяет, сколько задач каждый воркер обрабатывает параллельно. По умолчанию — `10`. {{< alert level="info" >}} -Общее количество задач, обрабатываемых одновременно всей системой, рассчитывается как `workers.replicas × workers.maxTasks`. Например, при 2 воркерах и 10 задачах на каждый воркер, система может обрабатывать до 20 задач одновременно. +Общее количество задач, обрабатываемых одновременно всей системой, рассчитывается как `workers.replicas × workers.maxTasks`. +Например, при 2 воркерах и 10 задачах на каждый воркер, система может обрабатывать до 20 задач одновременно. {{< /alert >}} ## Мониторинг @@ -46,7 +51,8 @@ weight: 20 ### Задачи проверки статуса сущностей -Задачи проверки статуса выполняются воркерами, которые определяют состояние сущностей на основе настроенных правил. Такой подход позволяет: +Задачи проверки статуса выполняются воркерами, которые определяют состояние сущностей на основе настроенных правил. +Такой подход позволяет: - Снизить нагрузку на основной сервер. - Обеспечить стабильность работы при большом количестве сущностей. @@ -71,24 +77,32 @@ weight: 20 ### Задачи запуска AI-агентов Воркеры выполняют запуски [AI-агентов](../ai-agents/overview/) из элементов процессов «AI-агент»: отправляют задачу агенту по протоколу A2A и ждут её завершения. -Длительность одного запуска ограничена 70 минутами. Пока запуск выполняется, он занимает одну из `workers.maxTasks` параллельных задач воркера. +Длительность одного запуска ограничена 70 минутами. +Пока запуск выполняется, он занимает одну из `workers.maxTasks` параллельных задач воркера. ### Синхронизация MCP-серверов -Периодическая синхронизация каталогов MCP-серверов выполняется воркерами. Включите её в настройках сервера и задайте системную учётную запись. При неудачной попытке сохраняется предыдущий каталог; результаты и время обновления доступны в карточке сервера. Настройка — [в руководстве по MCP](../../user/mcp-management/#автоматическая-синхронизация). +Периодическая синхронизация каталогов MCP-серверов выполняется воркерами. +Включите её в настройках сервера и задайте системную учётную запись. +При неудачной попытке сохраняется предыдущий каталог; результаты и время обновления доступны в карточке сервера. +Настройка — [в руководстве по MCP](../../user/mcp-management/#автоматическая-синхронизация). ## Фоновые операции с данными в ClickHouse -Если подключён [ClickHouse](../../install/#clickhouse), воркеры дополнительно переносят в него данные из PostgreSQL и убирают лишнее. Так, например, обслуживается [история изменений параметров сущностей](../../../user/catalog/#история-параметров): +Если подключён [ClickHouse](../../install/#clickhouse), воркеры дополнительно переносят в него данные из PostgreSQL и убирают лишнее. +Так, например, обслуживается [история изменений параметров сущностей](../../../user/catalog/#история-параметров): - перенос новых записей об изменениях из PostgreSQL в ClickHouse; - перестроение индексов очереди в PostgreSQL после переноса большого объёма изменений; - удаление истории сущностей и параметров, которых больше нет; - удаление истории, вышедшей за срок хранения. -Эти операции не берутся из очереди задач: каждый воркер запускает их сам, а от одновременного выполнения в нескольких репликах они защищены распределённой блокировкой. Если ни один воркер не запущен, изменения параметров продолжают записываться в PostgreSQL и остаются видимыми в интерфейсе, но очередь на перенос не разбирается и растёт. +Эти операции не берутся из очереди задач. +Каждый воркер запускает их сам, а от одновременного выполнения в нескольких репликах они защищены распределённой блокировкой. +Если ни один воркер не запущен, изменения параметров продолжают записываться в PostgreSQL и остаются видимыми в интерфейсе, но очередь на перенос не разбирается и растёт. -Параметры переноса задаются в секции `clickhouse.replication` настроек модуля: размер и периодичность переноса, перестроение индексов. [Срок хранения истории](../../../user/catalog/#хранение-истории) и периодичность очистки — в секции `clickhouse.propertyHistory`. +Параметры переноса задаются в секции `clickhouse.replication` настроек модуля: размер и периодичность переноса, перестроение индексов. +[Срок хранения истории](../../../user/catalog/#хранение-истории) и периодичность очистки — в секции `clickhouse.propertyHistory`. ## Масштабирование @@ -98,11 +112,13 @@ weight: 20 1. Увеличить количество параллельных задач на воркер — это повысит утилизацию каждого воркера. {{< alert level="info" >}} -При увеличении нагрузки на воркеры необходимо убедиться, что у кластера достаточно ресурсов (CPU, память) для обработки всех задач. +При увеличении нагрузки на воркеры убедитесь, что у кластера достаточно ресурсов (CPU, память) для обработки всех задач. {{< /alert >}} ## Устранение неполадок +В этом разделе описаны типовые проблемы с воркерами и способы их устранения. + ### Воркеры не обрабатывают задачи Если задачи накапливаются в очереди и не обрабатываются: diff --git a/content/documentation/admin/automations.md b/content/documentation/admin/automations.md new file mode 100644 index 00000000..52a8b4fa --- /dev/null +++ b/content/documentation/admin/automations.md @@ -0,0 +1,70 @@ +--- +title: Automations +menuTitle: Automations +description: Automatically running actions, processes, and datasource syncs when entities change. +weight: 70 +--- + +Automations are the Deckhouse Development Portal (DDP) mechanism for responding to changes in entity specifications. + +Each automation can subscribe to updates of entities of a particular resource according to specific rules. +When an update event occurs, the automation runs an action, a process, or a datasource sync. + +According to its settings, an automation can run for the entity that fired the trigger as well as for entities related to it. + +## Automation settings interface + +The form for creating and editing an automation is divided into logical sections. + +### Triggers + +This section configures the conditions under which the automation runs. +Each automation can contain any number of triggers. + +For each trigger, you specify a "Resource": the resource whose entity events trigger the automation. +You also specify a "Condition" in [Go template](https://developer.hashicorp.com/nomad/docs/reference/go-template-syntax) format. +It describes which property change triggers the automation and which value the changed property must take. + +For example, with the `{{ ne .entity.properties.id 0 }}` condition, the automation runs if the value of the `id` property has changed and is no longer zero. +With the `{{ eq .entity.properties.status "Failed" }}` condition, the automation runs if the value of the `status` property has changed to `Failed` from any other value. + +### Execution + +This section configures what runs when the automation trigger fires. + +In the "Execution type" field, select the type of object to run: an action, a process, or a datasource sync. +In the "Execution object" field, select the specific object (action, process, or datasource). + +A process runs only for entities of the resources it is bound to in the "Resource" field of the [process](../processes/overview/#basic-information). +Therefore, an automation process must be bound to all resources for whose entities the automation runs it: to the trigger resources if execution runs for the entity that fired the trigger or on a schedule, and to the resource at the other end of each selected relation if running for related resources is enabled. + +If execution runs for the entity that fired the trigger or on a schedule, processes not bound to the trigger resources are inactive in the "Execution object" list and labeled "not bound to the trigger resources". The portal checks the binding to related resources when saving. +An automation with a process that is not bound to the required resources is not saved. +The portal responds with a `422` error with the text "A process runs only for entities of its resources: bind it to the resources for whose entities the automation runs it (trigger resources or related resources), or select another process". + +Actions and processes have the additional "Run execution for related resources" setting. +When it is enabled, execution automatically runs for all entities that have the corresponding relation to the changed entity. +In this case, execution does not run for the entity that fired the event. + +### Sync + +This section configures periodic sync, that is, running the automation automatically on a schedule. + +The "Periodic synchronization" parameter enables and disables periodic sync. +The "Launch frequency" parameter takes a cron expression that sets how often the automation runs, for example, `0 0 * * *` to run daily at midnight. + +## Triggers + +Automation triggers are based on events that are generated every time any entity of any resource is created, changed, or deleted. + +Automations do the following: + +1. Listen to events of the resources specified in the trigger configuration. +1. Check whether the value of the property specified in the trigger conditions has changed. +1. If it has changed, compare the current property value with the condition. +1. If the condition is met, start execution. + +{{< alert level="warning" >}} +New automations process only events that occurred after they were created. +Events that occurred before the automation was created are not processed. +{{< /alert >}} diff --git a/content/documentation/admin/automations.ru.md b/content/documentation/admin/automations.ru.md index d6d3b1c7..4ba5bba8 100644 --- a/content/documentation/admin/automations.ru.md +++ b/content/documentation/admin/automations.ru.md @@ -5,9 +5,10 @@ description: Автоматический запуск действий, про weight: 70 --- -Автоматизации — механизм реагирования DDP на изменения спецификации сущностей. +Автоматизации — механизм реагирования Deckhouse Development Portal (DDP) на изменения спецификации сущностей. -Каждая автоматизация может подписываться на обновления сущностей какого-либо ресурса по определённым правилам. При возникновении события обновления автоматизация запускает выполнение действия, процесса или синхронизации источника данных. +Каждая автоматизация может подписываться на обновления сущностей какого-либо ресурса по определённым правилам. +При возникновении события обновления автоматизация запускает выполнение действия, процесса или синхронизации источника данных. Автоматизация может запускать выполнение как для сущности, которая вызвала триггер, так и для связанных с ней сущностей в соответствии с настройками. @@ -17,43 +18,40 @@ weight: 70 ### Триггеры -Секция для настройки условий, при которых автоматизация будет запускаться. Каждая автоматизация может содержать произвольное количество триггеров. +Секция для настройки условий, при которых автоматизация будет запускаться. +Каждая автоматизация может содержать произвольное количество триггеров. -При настройке каждого триггера указываются: +При настройке каждого триггера указывается «Ресурс» — ресурс, события с сущностями которого будут являться триггером для запуска автоматизации. +Также указывается «Условие» в формате [Go template](https://developer.hashicorp.com/nomad/docs/reference/go-template-syntax). +Оно описывает, изменение какого параметра считается триггером для запуска автоматизации и какое значение должен принять изменённый параметр. -* «Ресурс» — ресурс, события с сущностями которого будут являться триггером для запуска автоматизации; -* «Условие» — условие в формате [Go template](https://developer.hashicorp.com/nomad/docs/reference/go-template-syntax), описывающее, изменения какого параметра будет считаться триггером для запуска автоматизации и какое именно значение должен принять изменённый параметр. - -Примеры условий триггера: - -* `{{ ne .entity.properties.id 0 }}` — автоматизация будет запускаться, если значение параметра `id` изменилось и после изменения стало не равным нулю; -* `{{ eq .entity.properties.status "Failed" }}` — автоматизация будет запускаться, если значение параметра `status` изменилось на `Failed` с любого другого. +Например, с условием `{{ ne .entity.properties.id 0 }}` автоматизация запускается, если значение параметра `id` изменилось и стало не равным нулю. +С условием `{{ eq .entity.properties.status "Failed" }}` автоматизация запускается, если значение параметра `status` изменилось на `Failed` с любого другого. ### Выполнение Секция для настройки того, что будет выполняться при срабатывании триггера автоматизации. -Настраиваются: - -* «Тип выполнения» — тип объекта, который будет выполняться: действие, процесс или синхронизация источника данных; -* «Объект выполнения» — конкретный объект (действие, процесс или источник данных), который будет выполняться. +В поле «Тип выполнения» выбирается тип объекта, который будет выполняться: действие, процесс или синхронизация источника данных. +В поле «Объект выполнения» выбирается конкретный объект (действие, процесс или источник данных). -Процесс запускается только для сущностей ресурсов, к которым он привязан в поле «Ресурс» [процесса](../processes/overview/#основная-информация). Поэтому процесс автоматизации должен быть привязан ко всем ресурсам, для сущностей которых автоматизация его запускает: к ресурсам триггеров — если выполнение запускается для сущности, вызвавшей триггер, или по расписанию; к ресурсу на другом конце каждой выбранной связи — если включён запуск для связанных ресурсов. +Процесс запускается только для сущностей ресурсов, к которым он привязан в поле «Ресурс» [процесса](../processes/overview/#основная-информация). +Поэтому процесс автоматизации должен быть привязан ко всем ресурсам, для сущностей которых автоматизация его запускает: к ресурсам триггеров — если выполнение запускается для сущности, вызвавшей триггер, или по расписанию; к ресурсу на другом конце каждой выбранной связи — если включён запуск для связанных ресурсов. -Если выполнение запускается для сущности, вызвавшей триггер, или по расписанию, в списке «Объект выполнения» процессы, не привязанные к ресурсам триггеров, неактивны с подписью «не привязан к ресурсам триггеров»; привязку к связанным ресурсам портал проверяет при сохранении. Автоматизация с процессом, не привязанным к нужным ресурсам, не сохраняется: портал отвечает ошибкой `422` с текстом «Процесс запускается только для сущностей своих ресурсов: привяжите его к ресурсам, для сущностей которых автоматизация его запускает (ресурсы триггеров или связанные ресурсы), или выберите другой процесс». +Если выполнение запускается для сущности, вызвавшей триггер, или по расписанию, в списке «Объект выполнения» процессы, не привязанные к ресурсам триггеров, неактивны с подписью «не привязан к ресурсам триггеров»; привязку к связанным ресурсам портал проверяет при сохранении. +Автоматизация с процессом, не привязанным к нужным ресурсам, не сохраняется. +Портал отвечает ошибкой `422` с текстом «Процесс запускается только для сущностей своих ресурсов: привяжите его к ресурсам, для сущностей которых автоматизация его запускает (ресурсы триггеров или связанные ресурсы), или выберите другой процесс». -Для действий и процессов доступна дополнительная настройка: - -* «Запускать выполнение для связанных ресурсов» — при включении этой опции выполнение будет автоматически запускаться для всех сущностей, имеющих соответствующую связь с изменённой сущностью. При этом выполнение не будет запущено на сущность, вызвавшую событие. +Для действий и процессов доступна дополнительная настройка «Запускать выполнение для связанных ресурсов». +При её включении выполнение автоматически запускается для всех сущностей, имеющих соответствующую связь с изменённой сущностью. +При этом выполнение не запускается для сущности, вызвавшей событие. ### Синхронизация Секция для настройки периодической синхронизации — автоматического запуска автоматизации по расписанию. -Настраиваются: - -* «Периодическая синхронизация» — включение/выключение периодической синхронизации; -* «Периодичность запуска» — cron-выражение для настройки частоты запуска автоматизации (например, `0 0 * * *` для ежедневного запуска в полночь). +Параметр «Периодическая синхронизация» включает и выключает периодическую синхронизацию. +В параметре «Периодичность запуска» задаётся cron-выражение для настройки частоты запуска автоматизации, например `0 0 * * *` для ежедневного запуска в полночь. ## Триггеры @@ -67,5 +65,6 @@ weight: 70 1. При соответствии условию запускают выполнение. {{< alert level="warning" >}} -Новые автоматизации обрабатывают только события, которые произошли после их создания. События, произошедшие до создания автоматизации, не будут обработаны. +Новые автоматизации обрабатывают только события, которые произошли после их создания. +События, произошедшие до создания автоматизации, не будут обработаны. {{< /alert >}} diff --git a/content/documentation/admin/datasets.md b/content/documentation/admin/datasets.md new file mode 100644 index 00000000..e4b10cf1 --- /dev/null +++ b/content/documentation/admin/datasets.md @@ -0,0 +1,223 @@ +--- +title: Datasets +menuTitle: Datasets +description: Ready-made configuration sets for integrating the portal with external systems. +weight: 74 +--- + +Datasets are preconfigured configurations for quickly deploying ready-made integrations with external systems and setting up the required components of Deckhouse Development Portal (DDP, portal). + +Each dataset contains: + +- Dashboards for data visualization +- Widgets for displaying information +- Datasources for synchronization +- External services for connecting to APIs +- Credential types for authentication +- Roles and access permissions +- Other required portal components + +## Managing datasets + +You can view, apply, and delete datasets in the web interface. + +### Viewing available datasets + +The "Administration" → "Datasets" section shows a list of all available datasets. +Each card contains: + +- "Name": The dataset name. +- "Short description": A general description of the functionality. +- The "Description" button: Opens detailed information about the dataset, including: + - A detailed description with full information about the components + - A list of objects that will be created when the dataset is applied +- The "Apply" button: Starts the dataset installation. +- The "Delete" button: Deletes a previously applied dataset. + +### Applying a dataset + +To apply a dataset, follow these steps: + +1. Click "Apply" on the card of the required dataset. +1. If the dataset requires parameter configuration, a configuration form opens. +1. Fill in the required parameters and click "Apply". +1. If no parameters are required, a confirmation window appears. +1. After the dataset is applied successfully, all its components are created in the system. + +A dataset that depends on another dataset can be applied only after it. Otherwise, applying fails with the "Failed to apply dataset" error. +If a required parameter is not filled in, the "Fill in all required dataset parameters" error is shown. + +### Deleting a dataset + +To delete a dataset, follow these steps: + +1. Click "Delete" on the card of the applied dataset. +1. Confirm the deletion in the dialog. +1. All dataset components are deleted from the system. + +### Configuring after applying + +Some datasets may require additional configuration after they are applied: + +1. Go to "Profile" → "Credentials". +1. Fill in the required credentials, such as tokens and passwords. +1. Save the changes. + +### Initial setup + +The "Initial setup" button opens a wizard that applies the "Canonical architecture" datasets for the Home page in a single run: the catalog model, mapping rules, connections to Kubernetes, Vault, and GitLab, datasources, processes, and widgets. +The wizard and the datasets it applies are described in ["Initial setup"](../home/setup/). + +The "Show the initial setup banner" toggle returns the "The platform is ready for setup" banner to the Home page after it was hidden with the "Hide" button. + +## Available datasets + +The following datasets are available in the portal. + +### GitLab + +This dataset is designed for connecting to the GitLab API. + +Created objects: + +- The "GitLab" external service +- The "GitLab token" credential type: A personal access token for accessing the GitLab API. +- The "GitLab username" credential type: The GitLab username. + +Configuration parameters: + +| Name | Description | Default value | +|--------------|--------------------------------------------------------|-----------------------| +| "GitLab URL" | Base GitLab URL, for example, `https://gitlab.example.com`. Required parameter | — | + +After applying the dataset, fill in the "GitLab token" and "GitLab username" credentials in the user profile. + +GitLab groups, repositories, and widgets for the Home page are created by the "GitLab: groups", "GitLab: repository activity", and "GitLab: widgets" datasets. +They are described in ["Initial setup"](../home/setup/#wizard-datasets). + +### Kubernetes + +This dataset is designed for connecting to the Kubernetes API. + +The dataset creates the "Kubernetes" external service and the "Kubernetes token" credential type, a service account token for accessing the Kubernetes API. + +Configuration parameters: + +| Name | Description | Default value | +|----------------------|---------------------------------------------------------------------------|-----------------------| +| "Kubernetes API URL" | Base URL of the Kubernetes API server, for example, `https://api.cluster.example.com`. Required parameter | — | + +After applying the dataset, fill in the "Kubernetes token" credentials in the user profile. + +### Vault + +This dataset is designed for connecting to the HashiCorp Vault API. + +The dataset creates the "Vault" external service and the "Vault token" credential type, a token for API requests. + +Configuration: + +The dataset configures a connection to the Vault API through an external service with authorization by the `X-Vault-Token` header. +For details on the authorization format, refer to ["External services"](../external-services/#vault). + +{{< alert level="info" >}} +After applying the dataset, specify the Vault token in the "Vault token" credentials in the super administrator profile. +{{< /alert >}} + +Configuration parameters: + +| Name | Description | Default value | +|-------------|---------------------------------|-------------------------------| +| "Vault URL" | Base URL of the HashiCorp Vault API, for example, `https://vault.example.com`. Required parameter | — | + +Applying: + +1. Apply the Vault dataset. +1. Specify the URL of the Vault server. +1. Go to the super administrator profile. +1. Fill in the "Vault token" credentials. +1. Connect the "Vault" external service to the actions, widgets, or datasources that access the Vault API. + +After that, requests through the external service use the token from the user's credentials. +For example, you can connect the external service to the ["Vault secrets"](../widgets/generic/vault/) widget to view secrets in KV v2. + +### Deckhouse managed PostgreSQL + +A dataset for deploying managed PostgreSQL in Deckhouse Platform. + +The dataset prepares a resource, actions, and processes for managing the managed PostgreSQL lifecycle: creating an instance in the cluster through the Kubernetes external service and saving the connection details in Vault or Stronghold. + +Configuration: + +Before applying the dataset, configure the [Kubernetes](../external-services/#kubernetes) and [Vault](../external-services/#vault) (or Stronghold) external services. + +{{< alert level="info" >}} +A detailed description of the dataset components is available with the "Description" button on the card in the "Datasets" section. +{{< /alert >}} + +Configuration parameters: + +| Name | Description | Default value | +|----------|----------|-----------------------| +| "Kubernetes external service" | Kubernetes cluster where managed PostgreSQL will be deployed. Required parameter | — | +| "Vault or Stronghold external service" | External service for writing connection details to KV v2. Required parameter | — | +| "Vault path prefix" | KV v2 path prefix for saving connection details (with `/data/`) | `services/data/` | +| "Create catalog resource" | Create the dataset's own parent resource. Disable it if processes are bound to the canonical shared resources | Enabled | +| "Create actions" | Create actions for creating and deleting the managed service | Enabled | +| "Create processes" | Create processes for creating and deleting the managed service | Enabled | +| "Create datasource" | Collect managed service instances from the cluster into the catalog: status, environment, class, and allocated resources. Only objects with DDP labels are synced | Enabled | +| "Catalog resource for processes" | If set, processes are bound to this resource instead of the dataset's own parent resource. For the canonical Home page model, specify the UUID of the "Shared resources" resource | — | + +### Deckhouse managed Valkey + +A dataset for deploying managed Valkey in Deckhouse Platform. + +The dataset prepares a resource, actions, and processes for managing the managed Valkey lifecycle: creating an instance in the cluster through the Kubernetes external service and saving the connection details in Vault or Stronghold. + +Configuration: + +Before applying the dataset, configure the [Kubernetes](../external-services/#kubernetes) and [Vault](../external-services/#vault) (or Stronghold) external services. + +{{< alert level="info" >}} +A detailed description of the dataset components is available with the "Description" button on the card in the "Datasets" section. +{{< /alert >}} + +Configuration parameters: + +| Name | Description | Default value | +|----------|----------|-----------------------| +| "Kubernetes external service" | Kubernetes cluster where managed Valkey will be deployed. Required parameter | — | +| "Vault or Stronghold external service" | External service for writing connection details to KV v2. Required parameter | — | +| "Vault path prefix" | KV v2 path prefix for saving connection details (with `/data/`) | `services/data/` | +| "Create catalog resource" | Create the dataset's own parent resource. Disable it if processes are bound to the canonical shared resources | Enabled | +| "Create actions" | Create actions for creating and deleting the managed service | Enabled | +| "Create processes" | Create processes for creating and deleting the managed service | Enabled | +| "Create datasource" | Collect managed service instances from the cluster into the catalog: status, environment, class, and allocated resources. Only objects with DDP labels are synced | Enabled | +| "Catalog resource for processes" | If set, processes are bound to this resource instead of the dataset's own parent resource. For the canonical Home page model, specify the UUID of the "Shared resources" resource | — | + +### Deckhouse managed Kafka + +A dataset for deploying managed Kafka in Deckhouse Platform. + +The dataset prepares a resource, actions, and processes for managing the managed Kafka lifecycle: creating an instance in the cluster through the Kubernetes external service and saving the connection details in Vault or Stronghold. + +Configuration: + +Before applying the dataset, configure the [Kubernetes](../external-services/#kubernetes) and [Vault](../external-services/#vault) (or Stronghold) external services. + +{{< alert level="info" >}} +A detailed description of the dataset components is available with the "Description" button on the card in the "Datasets" section. +{{< /alert >}} + +Configuration parameters: + +| Name | Description | Default value | +|----------|----------|-----------------------| +| "Kubernetes external service" | Kubernetes cluster where managed Kafka will be deployed. Required parameter | — | +| "Vault or Stronghold external service" | External service for writing connection details to KV v2. Required parameter | — | +| "Vault path prefix" | KV v2 path prefix for saving connection details (with `/data/`) | `services/data/` | +| "Create catalog resource" | Create the dataset's own parent resource. Disable it if processes are bound to the canonical shared resources | Enabled | +| "Create actions" | Create actions for creating and deleting the managed service | Enabled | +| "Create processes" | Create processes for creating and deleting the managed service | Enabled | +| "Create datasource" | Collect managed service instances from the cluster into the catalog: status, environment, class, and allocated resources. Only objects with DDP labels are synced | Enabled | +| "Catalog resource for processes" | If set, processes are bound to this resource instead of the dataset's own parent resource. For the canonical Home page model, specify the UUID of the "Shared resources" resource | — | diff --git a/content/documentation/admin/datasets.ru.md b/content/documentation/admin/datasets.ru.md index 34e8e00d..1fc9a0da 100644 --- a/content/documentation/admin/datasets.ru.md +++ b/content/documentation/admin/datasets.ru.md @@ -5,7 +5,7 @@ description: Готовые наборы конфигураций для инт weight: 74 --- -Наборы данных — это предварительно настроенные конфигурации, предназначенные для быстрого развёртывания готовых интеграций с внешними системами и настройки необходимых компонентов DDP (портала). +Наборы данных — это предварительно настроенные конфигурации, предназначенные для быстрого развёртывания готовых интеграций с внешними системами и настройки необходимых компонентов Deckhouse Development Portal (DDP, портала). Каждый набор данных содержит: @@ -19,9 +19,12 @@ weight: 74 ## Управление наборами данных +Наборы данных можно просматривать, применять и удалять в веб-интерфейсе. + ### Просмотр доступных наборов -В разделе «Администрирование» → «Наборы данных» отображается список всех доступных наборов данных. Каждая карточка содержит: +В разделе «Администрирование» → «Наборы данных» отображается список всех доступных наборов данных. +Каждая карточка содержит: - «Название» — название набора данных. - «Краткое описание» — общее описание функциональности. @@ -33,16 +36,21 @@ weight: 74 ### Применение набора данных +Чтобы применить набор данных, выполните следующие действия: + 1. Нажмите кнопку «Применить» на карточке нужного набора данных. 1. Если набор данных требует настройки параметров, откроется форма конфигурации. 1. Заполните необходимые параметры и нажмите «Применить». 1. Если параметры не требуются, появится окно подтверждения. 1. После успешного применения все компоненты набора данных будут созданы в системе. -Набор данных, который зависит от другого набора, применяется только после него: иначе применение завершается ошибкой «Ошибка записи набора данных». Если не заполнен обязательный параметр, отображается ошибка «Заполните обязательные параметры набора данных». +Набор данных, который зависит от другого набора, применяется только после него, иначе применение завершается ошибкой «Ошибка записи набора данных». +Если не заполнен обязательный параметр, отображается ошибка «Заполните обязательные параметры набора данных». ### Удаление набора данных +Чтобы удалить набор данных, выполните следующие действия: + 1. Нажмите кнопку «Удалить» на карточке применённого набора данных. 1. Подтвердите удаление в диалоговом окне. 1. Все компоненты набора данных будут удалены из системы. @@ -57,13 +65,15 @@ weight: 74 ### Первоначальная настройка -Кнопка «Первоначальная настройка» открывает мастер, который применяет наборы данных «Каноничной архитектуры» для главной одним запуском: модель каталога, правила маппинга, подключения к Kubernetes, Vault и GitLab, источники данных, процессы и виджеты. +Кнопка «Первоначальная настройка» открывает мастер, который применяет наборы данных «Каноничной архитектуры» для главной страницы одним запуском: модель каталога, правила маппинга, подключения к Kubernetes, Vault и GitLab, источники данных, процессы и виджеты. Мастер и наборы данных, которые он применяет, описаны в разделе [«Первоначальная настройка»](../home/setup/). -Переключатель «Показывать баннер первоначальной настройки» возвращает на главную баннер «Платформа готова к настройке», скрытый кнопкой «Скрыть». +Переключатель «Показывать баннер первоначальной настройки» возвращает на главную страницу баннер «Платформа готова к настройке», скрытый кнопкой «Скрыть». ## Доступные наборы данных +В портале доступны следующие наборы данных. + ### GitLab Набор данных предназначен для подключения к API GitLab. @@ -82,16 +92,14 @@ weight: 74 После применения заполните в профиле пользователя учётные данные «GitLab токен» и «GitLab username». -Группы, репозитории и виджеты GitLab для главной создают наборы данных «GitLab: группы», «GitLab: активность репозиториев» и «GitLab: виджеты». Они описаны в разделе [«Первоначальная настройка»](../home/setup/#наборы-данных-мастера). +Группы, репозитории и виджеты GitLab для главной страницы создают наборы данных «GitLab: группы», «GitLab: активность репозиториев» и «GitLab: виджеты». +Они описаны в разделе [«Первоначальная настройка»](../home/setup/#наборы-данных-мастера). ### Kubernetes Набор данных предназначен для подключения к API Kubernetes. -Создаваемые объекты: - -- внешний сервис «Kubernetes»; -- тип учётных данных «Kubernetes токен» — токен сервисного аккаунта для доступа к API Kubernetes. +Набор создаёт внешний сервис «Kubernetes» и тип учётных данных «Kubernetes токен» — токен сервисного аккаунта для доступа к API Kubernetes. Параметры настройки: @@ -105,14 +113,12 @@ weight: 74 Набор данных предназначен для подключения к API HashiCorp Vault. -Создаваемые объекты: - -- внешний сервис «Vault»; -- тип учётных данных «Vault токен» — токен для запросов к API. +Набор создаёт внешний сервис «Vault» и тип учётных данных «Vault токен» — токен для запросов к API. Настройка: -Набор данных настраивает подключение к API Vault через внешний сервис с авторизацией по заголовку `X-Vault-Token`. Подробнее о формате авторизации — в разделе [«Внешние сервисы»](../external-services/#vault). +Набор данных настраивает подключение к API Vault через внешний сервис с авторизацией по заголовку `X-Vault-Token`. +Подробнее о формате авторизации — в разделе [«Внешние сервисы»](../external-services/#vault). {{< alert level="info" >}} После применения укажите в профиле суперадминистратора токен Vault в учётных данных «Vault токен». @@ -132,7 +138,8 @@ weight: 74 1. Заполните учётные данные «Vault токен». 1. Подключите внешний сервис «Vault» к действиям, виджетам или источникам данных, которые обращаются к API Vault. -После этого запросы через внешний сервис будут использовать токен из учётных данных пользователя. Например, внешний сервис можно подключить к виджету [«Секреты Vault»](../widgets/generic/vault/) для просмотра секретов в KV v2. +После этого запросы через внешний сервис будут использовать токен из учётных данных пользователя. +Например, внешний сервис можно подключить к виджету [«Секреты Vault»](../widgets/generic/vault/) для просмотра секретов в KV v2. ### Deckhouse managed PostgreSQL @@ -159,7 +166,7 @@ weight: 74 | «Создать действия» | Создать действия создания и удаления managed-сервиса | Включено | | «Создать процессы» | Создать процессы создания и удаления managed-сервиса | Включено | | «Создать источник данных» | Собирать экземпляры managed-сервиса из кластера в каталог: статус, окружение, класс и выделенные ресурсы. Синхронизируются только объекты с метками DDP | Включено | -| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной укажите UUID ресурса «Общие ресурсы» | — | +| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной страницы укажите UUID ресурса «Общие ресурсы» | — | ### Deckhouse managed Valkey @@ -186,7 +193,7 @@ weight: 74 | «Создать действия» | Создать действия создания и удаления managed-сервиса | Включено | | «Создать процессы» | Создать процессы создания и удаления managed-сервиса | Включено | | «Создать источник данных» | Собирать экземпляры managed-сервиса из кластера в каталог: статус, окружение, класс и выделенные ресурсы. Синхронизируются только объекты с метками DDP | Включено | -| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной укажите UUID ресурса «Общие ресурсы» | — | +| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной страницы укажите UUID ресурса «Общие ресурсы» | — | ### Deckhouse managed Kafka @@ -213,4 +220,4 @@ weight: 74 | «Создать действия» | Создать действия создания и удаления managed-сервиса | Включено | | «Создать процессы» | Создать процессы создания и удаления managed-сервиса | Включено | | «Создать источник данных» | Собирать экземпляры managed-сервиса из кластера в каталог: статус, окружение, класс и выделенные ресурсы. Синхронизируются только объекты с метками DDP | Включено | -| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной укажите UUID ресурса «Общие ресурсы» | — | +| «Ресурс каталога для процессов» | Если задан, процессы привязываются к этому ресурсу вместо собственного родительского. Для каноничной модели главной страницы укажите UUID ресурса «Общие ресурсы» | — | diff --git a/content/documentation/admin/datasources/_index.md b/content/documentation/admin/datasources/_index.md new file mode 100644 index 00000000..3bae6461 --- /dev/null +++ b/content/documentation/admin/datasources/_index.md @@ -0,0 +1,4 @@ +--- +title: Datasources +weight: 40 +--- diff --git a/content/documentation/admin/datasources/overview.md b/content/documentation/admin/datasources/overview.md new file mode 100644 index 00000000..f87fbcb2 --- /dev/null +++ b/content/documentation/admin/datasources/overview.md @@ -0,0 +1,258 @@ +--- +title: Overview +description: Datasources in Deckhouse Development Portal (DDP) — synchronization with external systems, rules, types, entity deletion, and logging. +weight: 10 +--- + +Datasources are a Deckhouse Development Portal (DDP) mechanism that synchronizes information from external infrastructure systems (for example, GitLab or Kubernetes) and converts it into properties of entities. + +Datasources also let you: + +- Create new entities. +- Delete entities that were deleted from external infrastructure systems. +- Create relations between entities. + +Each datasource is bound to a specific resource and, accordingly, can operate only on entities of that resource. +Relations, however, can be created between entities of the bound resource and any other entities. + +## Datasource types + +DDP supports two types of datasources. +Built-in (BuiltIn) datasources are datasources whose logic for polling infrastructure systems is shipped with DDP. +Webhooks (Webhooks) are a mechanism for receiving data in incoming POST requests from external systems. For details, see the ["Webhooks"](../webhooks/) section. + +## Datasource parameters + +Some datasource types support configurable parameters that let you further configure their behavior. +Details on the parameters of each datasource type are provided in the ["Datasource types"](./types/) section. + +## Datasource rules + +For each datasource, the system administrator configures rules that define how: + +- New entities are created. +- New relations are created. +- Matching entities are found to update their properties. +- Entities to delete are found. + +Rules are described in the `"source": "target"` format. +Rules use the [Go template](https://pkg.go.dev/text/template) syntax. + +DDP supports 5 types of rules: + +- Filter rules +- Creation rules (create rules) +- Matching rules (match rules) +- Update rules +- Relation creation rules (create relation rules) + +### Filter rules + +After data is received from an external system, filter rules are applied, and each subsequent rule processes the already filtered set of items. + +In the datasource editing dialog, open the "Rules" tab. +In the "Filter rules" block, each rule has three fields: + +1. Action: Keep only the items whose value of the selected field matches a regular expression (the "Keep only matches" option), or remove such items from the set (the "Remove matches" option). +1. Source: The path to a field in the data structure in the [Go template](https://pkg.go.dev/text/template) format. +1. Condition: A regular expression used to check the field value. + +If there are no rules, all received items are passed further down the chain. +If no action is selected, the "Keep only matches" option is used. + +To keep only records with a specific field value (for example, records whose `name` field value starts with `first`), select "Keep only matches". +In the source, specify an expression for this field, for example, `{{ .name }}`, and in the condition, specify a regular expression for matching values. +To skip records that match a pattern, select "Remove matches" and set the pattern in the condition. + +{{< alert level="info" >}} +If the condition contains an invalid regular expression, the rule is not applied; the error is written to the synchronization log, and the datasource processing continues. +{{< /alert >}} + +### Creation rules + +Creation rules define how the information received from the datasource backend is used to create new entities. + +For example, given the following specification of an external infrastructure system resource received through a datasource: + +```yaml +# ... +metadata: + name: example + namespace: default +# ... +``` + +and the following creation rules: + +```json +"create": [ + { + "source": "{{ .metadata.name }}", + "target": "Name" + }, + { + "source": "{{ .metadata.namespace }}-{{ .metadata.name }}", + "target": "Slug" + } +] +``` + +after the datasource is synchronized, an entity is created with the name (`Name`) set to `example` and the identifier (`Slug`) set to `default-example`. + +### Matching rules + +Matching rules define how to find existing entities, or entities just created by the datasource, to update their properties. + +### Update rules + +Update rules define which entity properties are populated automatically based on the specification of the corresponding resource from the external system. +The entity whose properties are populated is determined by the matching rules. + +### Importing from a specification + +Using the import mechanism, you can generate update rules and parameters of the updated resource automatically from a JSON, YAML, or OpenAPI data specification. + +#### Configuring in the interface + +To open the import from a specification, follow these steps: + +1. On the "Main information" tab, select the resource the datasource will be bound to. +1. In the datasource editing dialog, open the "Rules" tab. +1. In the "Update rules" block, click "Import from specification". + +#### Configuration steps + +The import wizard consists of the following steps: + +1. "Load data": Select the format (auto-detect, JSON, YAML, OpenAPI 3.x, Swagger 2.0) and paste the specification contents into the "Data" field. + If the specification contains several schemas, you can select the schema for mapping in the "Select schema to import" field at the next step. +1. "Mapping configuration": The table shows the "Path in data", "Type in source", "Parameter slug", "Parameter name", and "Parameter type" columns. + You can edit the parameter slug, name, and type, and select the rows to apply using checkboxes. + Rows for which the resource already has a parameter with the same slug or name are marked as "Exists". +1. "Apply": Click "Apply" to add the generated rules to the "Update rules" block of the datasource. + New resource parameters are created when the datasource is saved. + +#### System behavior during import + +You can enable the following options during import: + +1. "Auto-create resource parameters": For specification fields that have no corresponding parameter in the resource yet, new parameters are suggested; they are added to the resource when the datasource is saved. +1. "Auto-fill update rules": A rule is created for each selected field: the source is set to a [Go template](https://pkg.go.dev/text/template) expression for the data path (for example, `{{ .metadata.name }}`), and the parameter is set to the resource parameter slug. + After you click "Apply", these rules appear in the "Update rules" block on the "Rules" tab of the datasource. + +#### Supported formats + +Auto-detect, JSON, YAML, OpenAPI 3.x, Swagger 2.0. +Types from the specification (`string`, `integer`, `array`, `object`, and others) are mapped to DDP parameter types; if needed, you can change the type at the "Mapping configuration" step. + +### Relation creation rules + +Relation creation rules define which relations are created for the entity that matches the matching rules. +When you define relation creation rules, you specify a resource relation and a field from the specification of the external infrastructure system resource, +which is used to find the entity to create a relation with. + +For example, given the following specification of an external infrastructure system resource received through a datasource: + +```yaml +# ... +metadata: + name: example + namespace: default +# ... +``` + +and the following relation creation rule: + +```json +"createRelations": [ + { + "resourceRelationUuid": "<12345678-1234-5678-1234-567812345678>", + "parentEntitySlug": "{{ .metadata.namespace }}", + "childEntitySlug": "" + } +] +``` + +the following applies: + +- If the parent entity identifier (`parentEntitySlug`) is specified, the search is performed only among entities of the parent resource. +- If the child entity identifier (`childEntitySlug`) is specified, the search is performed only among entities of the child resource. +- Specify either the parent or the child identifier within a single rule. +- If both identifiers are set, the search is performed only in the parent resource. + +If the parent resource has an entity with the `default` identifier, a relation is created between that entity and the entity of the resource the datasource is bound to that matches the matching rules. + +## Synchronization + +To configure synchronization, each datasource has the "Periodic synchronization" parameter, which enables or disables periodic synchronization, +and the "Launch frequency" parameter, a cron expression that defines the periodic synchronization interval. + +When "Periodic synchronization" is enabled, the datasource automatically updates information from external infrastructure systems at the interval defined in the "Launch frequency" parameter. + +You can also synchronize any datasource manually at any time in the web interface (the "Sync" item in the datasource menu) or through the API. + +## Deleting entities + +Entity deletion is configured with the "Delete non-existing entities" and "Delete only entities created by this data source" parameters. + +When "Delete non-existing entities" is enabled, the datasource compares the list of resources received from the external infrastructure system with the list of existing entities of the resource. +Entities found in DDP that are missing from the received list are deleted from DDP. + +When "Delete only entities created by this data source" is enabled, the datasource additionally checks how the entity to be deleted was created. +If the entity was created by this datasource, it is deleted; otherwise, the datasource moves on to the next entity in the list without deleting the current one. + +The entity creator (origin) is determined by two fields in the entity specification: + +```json +{ + "origin": { + "type": "", + "uuid": "<12345678-1234-5678-1234-567812345678>" + } +} +``` + +## Run logging + +For each datasource run, a record containing the full execution log is created in the database (DB). +The maximum number of such records is controlled by the "Maximum number of records" parameter in the datasource configuration. +When the maximum is reached, old records are deleted. + +The `datasources.logging.enabled` module parameter lets you output datasource synchronization logs to stdout or hide them. +If set to `true`, logs are written to stdout; if set to `false` (default), they are not. +The parameter is set in the `development-platform` ModuleConfig (`spec.settings.datasources.logging.enabled`) or in the module settings in the Deckhouse web UI. + +Example of a ModuleConfig fragment: + +```yaml +apiVersion: deckhouse.io/v1alpha1 +kind: ModuleConfig +metadata: + name: development-platform +spec: + settings: + datasources: + logging: + enabled: true +``` + +{{< alert level="info" >}} +DB records with the full datasource run log are created regardless of the `datasources.logging.enabled` parameter value. +{{< /alert >}} + +## System account + +When configuring a datasource, select the system account used to run synchronization. + +The datasource uses the details of this account to access the polled infrastructure system. + +In addition to the system account, specify which of its details are used when running the datasource. +To do this, add new credentials with a specific identifier in the "Security / Credentials" section. + +The value of this identifier can be substituted into the datasource configuration using the [Go template](https://pkg.go.dev/text/template) syntax. + +For example, if a secret value with the `token` identifier is passed in a header for the datasource, you can specify it as follows: + +```go-text-template +{{ .credentials.token }} +``` diff --git a/content/documentation/admin/datasources/overview.ru.md b/content/documentation/admin/datasources/overview.ru.md index 9b279f0b..1fad205d 100644 --- a/content/documentation/admin/datasources/overview.ru.md +++ b/content/documentation/admin/datasources/overview.ru.md @@ -12,16 +12,19 @@ weight: 10 - Удалять сущности, которые были удалены из внешних инфраструктурных систем. - Создавать связи между сущностями. -Каждый источник данных привязан к определённому ресурсу, и, соответственно, может оперировать сущностями только данного ресурса. При этом, связи могут создаваться между сущностями привязанного ресурса и любыми другими сущностями. +Каждый источник данных привязан к определённому ресурсу, и, соответственно, может оперировать сущностями только данного ресурса. +При этом, связи могут создаваться между сущностями привязанного ресурса и любыми другими сущностями. ## Типы источников данных -- Встроенные (BuiltIn) — источники данных, для которых логика опроса инфраструктурных систем поставляется в рамках DDP. -- Вебхуки (Webhooks) — механизм приёма данных во входящих POST-запросах от внешних систем, подробнее в разделе [«Вебхуки»](../webhooks/). +DDP поддерживает два типа источников данных. +Встроенные (BuiltIn) — источники данных, для которых логика опроса инфраструктурных систем поставляется в рамках DDP. +Вебхуки (Webhooks) — механизм приёма данных во входящих POST-запросах от внешних систем, подробнее — в разделе [«Вебхуки»](../webhooks/). ## Параметры источников данных -Некоторые типы источников данных поддерживают настраиваемые параметры, позволяющие дополнительно конфигурировать их поведение. Подробная информация о параметрах для каждого типа источника данных приведена в разделе [«Типы источников данных»](./types/). +Некоторые типы источников данных поддерживают настраиваемые параметры, позволяющие дополнительно конфигурировать их поведение. +Подробная информация о параметрах для каждого типа источника данных приведена в разделе [«Типы источников данных»](./types/). ## Правила источников данных @@ -32,7 +35,8 @@ weight: 10 - Производиться поиск соответствующих сущностей для обновления их параметров. - Производиться поиск сущностей для удаления. -Правила описываются в формате `"source": "target"`. Для описания правил используется синтаксис [Go template](https://pkg.go.dev/text/template). +Правила описываются в формате `"source": "target"`. +Для описания правил используется синтаксис [Go template](https://pkg.go.dev/text/template). В DDP реализованы 5 типов правил: @@ -44,17 +48,21 @@ weight: 10 ### Правила фильтрации -После получения данных из внешней системы применяются правила фильтрации: каждое следующее правило обрабатывает уже отфильтрованный набор элементов. +После получения данных из внешней системы применяются правила фильтрации, и каждое следующее правило обрабатывает уже отфильтрованный набор элементов. -В диалоге редактирования источника данных откройте вкладку «Правила». В блоке «Правила фильтрации» для каждого правила задаются три поля: +В диалоге редактирования источника данных откройте вкладку «Правила». +В блоке «Правила фильтрации» для каждого правила задаются три поля: 1. Действие — оставить только элементы, у которых значение выбранного поля совпало с регулярным выражением (вариант «Оставить только совпадения»), или убрать из набора такие элементы (вариант «Убрать совпадения»). 1. Источник — путь к полю в структуре данных в формате [Go template](https://pkg.go.dev/text/template). 1. Условие — регулярное выражение для проверки значения этого поля. -Если правил нет, дальше по цепочке проходят все полученные элементы. Если действие не выбрано, подставляется вариант «Оставить только совпадения». +Если правил нет, дальше по цепочке проходят все полученные элементы. +Если действие не выбрано, подставляется вариант «Оставить только совпадения». -Чтобы оставить только записи с нужным значением поля (например, чтобы в поле `name` значение начиналось с `first`), выберите «Оставить только совпадения». В источнике укажите выражение для этого поля, например `{{ .name }}`, в условии — регулярное выражение для подходящих значений. Чтобы не обрабатывать записи, которые совпадают с шаблоном, выберите «Убрать совпадения» и задайте шаблон в условии. +Чтобы оставить только записи с нужным значением поля (например, чтобы в поле `name` значение начиналось с `first`), выберите «Оставить только совпадения». +В источнике укажите выражение для этого поля, например `{{ .name }}`, в условии — регулярное выражение для подходящих значений. +Чтобы не обрабатывать записи, которые совпадают с шаблоном, выберите «Убрать совпадения» и задайте шаблон в условии. {{< alert level="info" >}} Если в условии указано невалидное регулярное выражение, правило не выполняется; ошибка попадает в лог синхронизации и обработка источника данных продолжается. @@ -97,39 +105,51 @@ metadata: ### Правила обновления -Правила обновления определяют, какие параметры сущности автоматически заполняются на основе спецификации соответствующего ресурса из внешней системы. Сущность, параметры которой необходимо заполнить, определяется на основе правил сопоставления. +Правила обновления определяют, какие параметры сущности автоматически заполняются на основе спецификации соответствующего ресурса из внешней системы. +Сущность, параметры которой заполняются, определяется на основе правил сопоставления. -#### Импорт из спецификации +### Импорт из спецификации С использованием механизма импорта, правила обновления и параметры обновляемого ресурса можно сформировать автоматически по JSON, YAML или OpenAPI-спецификации данных. -##### Настройка в интерфейсе +#### Настройка в интерфейсе + +Чтобы открыть импорт из спецификации, выполните следующие действия: 1. На вкладке «Основная информация» выберите ресурс, к которому будет привязан источник данных. 1. В диалоге редактирования источника данных откройте вкладку «Правила». 1. В блоке «Правила обновления» нажмите кнопку «Импортировать из спецификации». -##### Шаги по настройке +#### Шаги по настройке + +Мастер импорта состоит из следующих шагов: + +1. «Загрузка данных» — выберите формат (автоопределение, JSON, YAML, OpenAPI 3.x, Swagger 2.0) и вставьте содержимое спецификации в поле «Данные». + Если в спецификации несколько схем, на следующем шаге в поле «Выберите схему для импорта» можно выбрать схему для маппинга. +1. «Настройка маппинга» — в таблице отображаются столбцы «Путь в данных», «Тип в источнике», «Идентификатор параметра», «Название параметра», «Тип параметра». + Можно редактировать идентификатор, название и тип параметра, отметить галочками строки для применения. + Строки, для которых в ресурсе уже есть параметр с таким идентификатором или названием, помечаются как «Существует». +1. «Применение» — нажмите «Применить»: в блок «Правила обновления» источника данных добавятся сформированные правила. + Новые параметры ресурса будут созданы при сохранении источника данных. -1. «Загрузка данных» — выберите формат (автоопределение, JSON, YAML, OpenAPI 3.x, Swagger 2.0) и вставьте содержимое спецификации в поле «Данные». Если в спецификации несколько схем, на следующем шаге в поле «Выберите схему для импорта» можно выбрать схему для маппинга. -1. «Настройка маппинга» — в таблице отображаются столбцы «Путь в данных», «Тип в источнике», «Идентификатор параметра», «Название параметра», «Тип параметра». Можно редактировать идентификатор, название и тип параметра, отметить галочками строки для применения. Строки, для которых в ресурсе уже есть параметр с таким идентификатором или названием, помечаются как «Существует». -1. «Применение» — нажмите «Применить»: в блок «Правила обновления» источника данных добавятся сформированные правила. Новые параметры ресурса будут созданы при сохранении источника данных. +#### Поведение системы при импорте -##### Поведение системы при импорте +При импорте можно включить следующие опции: 1. «Автосоздание параметров ресурса» — для полей спецификации, по которым в ресурсе ещё нет параметра, предлагаются новые параметры; они добавляются в ресурс при сохранении источника данных. -1. «Автозаполнение правил обновления» — по каждому выбранному полю создаётся правило: источник задаётся выражением [Go template](https://pkg.go.dev/text/template) по пути в данных (например, `{{ .metadata.name }}`), параметр — идентификатор параметра ресурса. После нажатия «Применить» эти правила появляются в блоке «Правила обновления» на вкладке «Правила» источника данных. +1. «Автозаполнение правил обновления» — по каждому выбранному полю создаётся правило: источник задаётся выражением [Go template](https://pkg.go.dev/text/template) по пути в данных (например, `{{ .metadata.name }}`), параметр — идентификатор параметра ресурса. + После нажатия «Применить» эти правила появляются в блоке «Правила обновления» на вкладке «Правила» источника данных. -##### Поддерживаемые форматы +#### Поддерживаемые форматы -Автоопределение, JSON, YAML, OpenAPI 3.x, Swagger 2.0. Типы из спецификации (string, integer, array, object и т.д.) сопоставляются с типами параметров DDP; при необходимости тип можно изменить на шаге «Настройка маппинга». +Автоопределение, JSON, YAML, OpenAPI 3.x, Swagger 2.0. +Типы из спецификации (`string`, `integer`, `array`, `object` и другие) сопоставляются с типами параметров DDP; при необходимости тип можно изменить на шаге «Настройка маппинга». ### Правила создания связей -Правила создания связей определяют, какие связи создаются для сущности, соответствующей правилам сопоставления. При задании правил создания связей заполняется: - -- Связь ресурса. -- Поле из спецификации ресурса внешней инфраструктурной системы, на основании которого выполняется поиск сущности для установления связи. +Правила создания связей определяют, какие связи создаются для сущности, соответствующей правилам сопоставления. +При задании правил создания связей указываются связь ресурса и поле из спецификации ресурса внешней инфраструктурной системы, +на основании которого выполняется поиск сущности для установления связи. Например, при следующей спецификации одного из ресурсов внешней инфраструктурной системы, полученного через источник данных: @@ -157,17 +177,15 @@ metadata: - Если указан идентификатор родительской сущности (`parentEntitySlug`), поиск выполняется только среди сущностей родительского ресурса. - Если указан идентификатор дочерней сущности (`childEntitySlug`), поиск выполняется только среди сущностей дочернего ресурса. -- В рамках одного правила необходимо указывать либо родительский, либо дочерний идентификатор. +- В рамках одного правила указывайте либо родительский, либо дочерний идентификатор. - Если заданы оба идентификатора, поиск выполняется только по родительскому ресурсу. Если в родительском ресурсе существует сущность с идентификатором `default`, создаётся связь между этой сущностью и сущностью ресурса, к которому привязан источник данных и которая соответствует правилам сопоставления. ## Синхронизация -Каждый источник данных имеет несколько параметров настройки синхронизации: - -- Периодическая синхронизация — включение или выключение периодической синхронизации. -- Периодичность запуска — cron-выражение, определяющее интервал запуска периодической синхронизации. +Для настройки синхронизации у каждого источника данных есть параметр «Периодическая синхронизация», который включает или выключает периодическую синхронизацию, +и параметр «Периодичность запуска» — cron-выражение, определяющее интервал запуска периодической синхронизации. При включённом параметре «Периодическая синхронизация» источник данных будет автоматически обновлять информацию из внешних инфраструктурных систем с интервалом, определённым в параметре «Периодичность запуска». @@ -175,14 +193,13 @@ metadata: ## Удаление сущностей -Каждый источник данных имеет несколько параметров удаления сущностей: - -- Удаление несуществующих сущностей. -- Удаление только сущностей, созданных этим источником данных. +Удаление сущностей настраивается параметрами «Удаление несуществующих сущностей» и «Удаление только сущностей, созданных этим источником данных». -При включении параметра «Удаление несуществующих сущностей» источник данных будет сравнивать список ресурсов, полученных из внешней инфраструктурной системы и список существующих сущностей ресурса. При обнаружении в DDP сущностей, которые отсутствуют в списке полученных, они будут удалены из DDP. +При включении параметра «Удаление несуществующих сущностей» источник данных будет сравнивать список ресурсов, полученных из внешней инфраструктурной системы и список существующих сущностей ресурса. +При обнаружении в DDP сущностей, которые отсутствуют в списке полученных, они будут удалены из DDP. -При включении параметра «Удаление только сущностей, созданных этим источником данных» источник данных будет дополнительно сравнивать, каким образом была создана сущность, которую необходимо удалить. Если сущность была создана этим источником данных, то она будет удалена, если нет, то источник данных перейдёт к обработке следующей сущности в списке без удаления текущей. +При включении параметра «Удаление только сущностей, созданных этим источником данных» источник данных будет дополнительно сравнивать, каким образом была создана удаляемая сущность. +Если сущность была создана этим источником данных, то она будет удалена, если нет, то источник данных перейдёт к обработке следующей сущности в списке без удаления текущей. Поиск создателя (origin) сущности производится по двум полям в спецификации сущности: @@ -197,9 +214,13 @@ metadata: ## Логирование запусков -Для каждого запуска источника данных создаётся запись в базе данных (БД), содержащая полный лог выполнения. Максимальное количество подобных записей регулируется параметром «максимальное количество записей» в конфигурации источника данных. При достижении максимального количества старые записи будут удаляться. +Для каждого запуска источника данных создаётся запись в базе данных (БД), содержащая полный лог выполнения. +Максимальное количество подобных записей регулируется параметром «максимальное количество записей» в конфигурации источника данных. +При достижении максимального количества старые записи будут удаляться. -Параметр модуля `datasources.logging.enabled` позволяет выводить в stdout или скрывать логи синхронизации источников данных. При значении `true` логи выводятся в stdout, при значении `false` (по умолчанию) — не выводятся. Параметр задаётся в ModuleConfig `development-platform` (`spec.settings.datasources.logging.enabled`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. +Параметр модуля `datasources.logging.enabled` позволяет выводить в stdout или скрывать логи синхронизации источников данных. +При значении `true` логи выводятся в stdout, при значении `false` (по умолчанию) — не выводятся. +Параметр задаётся в ModuleConfig `development-platform` (`spec.settings.datasources.logging.enabled`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. Пример фрагмента ModuleConfig: @@ -221,15 +242,16 @@ spec: ## Системная учётная запись -При настройке источника данных необходимо выбрать системную учётную запись для запуска синхронизации. +При настройке источника данных выберите системную учётную запись для запуска синхронизации. Реквизиты данной учётной записи будут использоваться источником данных для доступа к опрашиваемой инфраструктурной системе. -Помимо системной учётной записи необходимо указание того, какие её реквизиты будут использованы при запуске источника данных. Для этого в секции «Безопасность / Учётные данные» добавляются новые учётные данные с определённым идентификатором. +Помимо системной учётной записи укажите, какие её реквизиты будут использованы при запуске источника данных. +Для этого в секции «Безопасность / Учётные данные» добавляются новые учётные данные с определённым идентификатором. Значение данного идентификатора может быть подставлено в конфигурацию источника данных с использованием синтаксиса [Go template](https://pkg.go.dev/text/template). -Например, если в заголовке для источника данных необходимо передать секретное значение с идентификатором `token`, то оно может быть указано в следующем виде: +Например, если в заголовке для источника данных передаётся секретное значение с идентификатором `token`, то оно может быть указано в следующем виде: ```go-text-template {{ .credentials.token }} diff --git a/content/documentation/admin/datasources/types.md b/content/documentation/admin/datasources/types.md new file mode 100644 index 00000000..fc15db53 --- /dev/null +++ b/content/documentation/admin/datasources/types.md @@ -0,0 +1,972 @@ +--- +title: Datasource types +description: Built-in DDP datasource types — authorization, response specification, configuration, and parameters. +weight: 20 +--- + +## DefectdojoProducts + +A datasource of the `DefectdojoProducts` type returns a list of products in Defectdojo. + +### Authorization + +Authorization configuration is described in the ["DefectDojo external service"](../external-services/#defectdojo) section. + +### Response specification + +Deckhouse Development Portal (DDP) sends a GET request to the following URL: `/api/v2/products`. +All available values are returned. +[Response specification](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). + +### Configuration + +In the `URL` parameter, specify the DefectDojo URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## GitlabGroups + +A datasource of the `GitlabGroups` type returns a list of groups in GitLab. + +### Authorization + +Authorization configuration is described in the ["GitLab external service"](../external-services/#gitlab) section. + +### Response specification + +The portal sends a GET request to the GitLab API at the following URL: `/api/v4/groups`. +The portal returns all available values. +[Response specification](https://docs.gitlab.com/api/groups/#list-groups). + +### Configuration + +In the `URL` parameter, specify the GitLab URL in the `https://gitlab.com` format, without the `/api/v4` part. + +### Parameters + +There are no configurable parameters. + +## GitlabProjects + +A datasource of the `GitlabProjects` type returns a list of projects in GitLab. + +### Authorization + +Authorization configuration is described in the ["GitLab external service"](../external-services/#gitlab) section. + +### Response specification + +Depending on the [parameter configuration](#gitlabprojectsparameters), the portal sends a GET request to the GitLab API and returns the corresponding specification. + +If the `all` parameter is set to `true`, a GET request is sent to the following URL: `/api/v4/projects`. +The portal returns all available values. +[Response specification](https://docs.gitlab.com/api/projects/#list-all-projects). + +If the `all` parameter is set to `false`, a GET request is sent to the following URL: `/api/v4/groups/:id/projects`. +The portal returns all available values. +[Response specification](https://docs.gitlab.com/api/projects/#list-all-projects). + +If the `tags` parameter is set to `true`, the portal also retrieves git tags. +To retrieve git tags, a GET request is sent to the following URL: `/api/v4/projects/:id/repository/tags`. +The portal retrieves the list of all git tags and extends the [response specification](https://docs.gitlab.com/api/projects/#list-all-projects) with the `ddp_repository_tags` field, which matches the [list-project-repository-tags response specification](https://docs.gitlab.com/api/tags/#list-project-repository-tags). + +### Configuration + +In the `URL` parameter, specify the GitLab URL in the `https://gitlab.com` format, without the `/api/v4` part. + + + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | Default value | +| --- | --- | --- | --- | --- | +| `all` | No | Explicitly specifies that repositories of all groups you have access to must be collected | `true`, `false` | `false` | +| `group_ids` | Yes, if `all` is `false` | The datasource collects projects of the groups with the specified IDs. Group IDs are comma-separated | Example: 1001,1002 | — | +| `tags` | No | The portal also retrieves the list of all git tags and extends the [response specification](https://docs.gitlab.com/api/projects/#list-all-projects) with the `ddp_repository_tags` field, which matches the [list-project-repository-tags response specification](https://docs.gitlab.com/api/tags/#list-project-repository-tags) | `true`, `false` | `false` | +| `include_subgroups` | No | If the `group_ids` parameter is set, the `include_subgroups` parameter defines whether to collect projects of subgroups of the specified groups | `true`, `false` | `false` | +| `tags_order_by` | No | Field used to sort tags. For the parameter description, see the [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) | `updated`, `name`, `version` | `updated` | +| `tags_sort` | No | Tag sort direction. For the parameter description, see the [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) | `asc`, `desc` | `desc` | +| `tags_search` | No | String used to search tags by name. For the parameter description, see the [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) | String | — | + +## GitlabRepositoryActivity + +A datasource of the `GitlabRepositoryActivity` type returns GitLab project activity: the number of open merge requests, the latest commit, and the latest pipeline of the default branch. + +The datasource populates the metrics of the microservice card on the Home page and is used by the "GitLab: repository activity" dataset. + +### Authorization + +Authorization configuration is described in the ["GitLab external service"](../external-services/#gitlab) section. + +### Response specification + +The portal sends POST requests to the GitLab GraphQL API at the `/api/graphql` URL, 50 projects per request. +For each group specified by a numeric ID, a GET request is also sent to the `/api/v4/groups/:id` URL. + +For each project, the datasource returns the following fields: + +| Name | Description | +| --- | --- | +| `path` | Project path without the group path | +| `gitlab_repository_id` | Numeric project ID | +| `default_branch` | Default branch | +| `open_mr_count` | Number of open merge requests | +| `last_commit_sha` | Short SHA of the latest commit in the default branch | +| `last_commit_message` | Title of the latest commit | +| `last_commit_author` | Author of the latest commit | +| `last_pipeline_id` | Number (`iid`) of the latest pipeline of the default branch | +| `last_pipeline_status` | Status of the latest pipeline in lowercase | +| `last_pipeline_web_url` | Link to the latest pipeline | + +If a project has no commits or pipelines, the commit and pipeline fields are omitted. + +### Configuration + +In the `URL` parameter, specify the GitLab URL in the `https://gitlab.com` format, without the `/api/graphql` part. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | Default value | +| --- | --- | --- | --- | --- | +| `all` | No | Collect activity of all projects the token user is a member of. The `group_ids` parameter is ignored in this case | `true`, `false` | `false` | +| `group_ids` | Yes, if `all` is `false` | Comma-separated group IDs or full group paths | Example: `1001,platform/backend` | — | +| `include_subgroups` | No | Collect projects of subgroups of the specified groups | `true`, `false` | `false` | + +If a group is not found or is not accessible, synchronization fails with the `gitlab group "" not found or not accessible` error. + +## GitlabRepositoryFiles + +A datasource of the `GitlabRepositoryFiles` type reads structured files (YAML or JSON) from GitLab project repositories and returns one record for each document in a file or for each list item in a document. + +### Authorization + +Authorization configuration is described in the ["GitLab external service"](../external-services/#gitlab) section. + +### Response specification + +The portal gets the list of projects with a GET request to the GitLab API at the `/api/v4/projects` URL if the `all` parameter is set to `true`, or at the `/api/v4/groups/:id/projects` URL for each group from the `group_ids` parameter. +[Response specification](https://docs.gitlab.com/api/projects/#list-projects). + +Then, for each project, the portal determines which files to read. +If the `file_path` parameter is set, only the specified file is read. +If the `file_pattern` parameter is set, the portal gets the repository tree with a GET request to the `/api/v4/projects/:id/repository/tree` URL and selects the files that match the pattern. + +The portal gets the contents of each file with a GET request to the `/api/v4/projects/:id/repository/files/:file_path` URL. +A file can contain several YAML documents separated by `---`. +Each document must be an object. + +Each record contains the document fields (with `document_mode: file`) or the list item fields (with `document_mode: list`), as well as the following service fields: + +| Name | Description | +| --- | --- | +| `_file_path` | File path in the repository | +| `_file_name` | File name | +| `_dir` | File directory in the repository | +| `_ref` | Branch or tag the file was read from | +| `_project_id` | Numeric project ID | +| `_project_path` | Full project path (`path_with_namespace`) | +| `_project_name` | Project name | +| `_default_branch` | Default branch of the project | +| `_project_url` | Link to the project. Omitted if GitLab did not return a link to the project | +| `_web_url` | Link to the file in the GitLab web interface. Omitted together with `_project_url` | +| `_document` | The entire document the record was obtained from | +| `_index` | Index of the item in the list, starting from `0`. Only with `document_mode: list` | + +Projects whose files could not be read are skipped. +A file with a syntax error is skipped entirely. +Information about skipped projects and files is written to the synchronization log. + +### Configuration + +In the `URL` parameter, specify the GitLab URL in the `https://gitlab.com` format, without the `/api/v4` part. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | Default value | +| --- | --- | --- | --- | --- | +| `all` | No | Read files from projects of all groups you have access to. The `group_ids` parameter is ignored in this case | `true`, `false` | `false` | +| `group_ids` | Yes, if `all` is `false` | Comma-separated group IDs | Example: `1001,1002` | — | +| `include_subgroups` | No | If the `group_ids` parameter is set, defines whether to read files from projects of subgroups of the specified groups | `true`, `false` | `false` | +| `topic` | No | Read files only from projects with the specified GitLab topic. Filtering is performed on the GitLab side | String | — | +| `project_pattern` | No | Regular expression for the full project path (`path_with_namespace`). Projects whose path does not match the expression are skipped | Regular expression | — | +| `max_projects` | No | Maximum number of projects to read files from. The remaining projects are not processed, and a warning is written to the synchronization log. `0` means no limit | Non-negative integer | `0` | +| `ref` | No | Branch or tag to read files from. If not set, the default branch of each project is used | String | — | +| `file_path` | Yes, if `file_pattern` is not set | Exact file path in the repository. The repository tree is not requested in this case | Example: `catalog/service.yaml` | — | +| `path` | No | Repository directory where the search for files matching the `file_pattern` pattern starts. An empty value means the repository root | Example: `catalog` | `""` | +| `file_pattern` | Yes, if `file_path` is not set | File name pattern in the [path.Match](https://pkg.go.dev/path#Match) format. If the pattern contains `/`, it is matched against the full file path in the repository | Example: `*.yaml` | — | +| `recursive` | No | Search for files matching the `file_pattern` pattern in nested directories | `true`, `false` | `true` | +| `document_mode` | No | How a document is converted into records: `file` — the document becomes a single record; `list` — each list item under the `list_path` key becomes a record | `file`, `list` | `file` | +| `list_path` | Yes, if `document_mode` is `list` | Top-level document key that holds the list of items | Example: `items` | — | + +Exactly one of the `file_path` and `file_pattern` parameters must be set. +If the parameters are set incorrectly, synchronization fails. + +### Example + +Get records from the `services` list in the `catalog/services.yaml` file of projects in the `1001` group with the `ddp` topic: + +```yaml +group_ids: "1001" +topic: ddp +file_path: catalog/services.yaml +document_mode: list +list_path: services +``` + +## HarborArtifacts + +A datasource of the `HarborArtifacts` type collects information about all artifacts in Harbor. + +### Authorization + +Authorization configuration is described in the ["Harbor external service"](../external-services/#harbor) section. + +### Response specification + +The portal gets the list of all projects and the repositories they contain, then sends a GET request to the Harbor API for each available project: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. +The response specification is available [in the Harbor interface](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). + +### Configuration + +In the `URL` parameter, specify the Harbor URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## HarborProjects + +A datasource of the `HarborProjects` type collects information about all projects in Harbor. + +### Authorization + +Authorization configuration is described in the ["Harbor external service"](../external-services/#harbor) section. + +### Response specification + +The portal gets the list of all available projects by sending GET requests to the Harbor API: `/api/v2.0/projects`. +The response specification is available [in the Harbor interface](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). + +### Configuration + +In the `URL` parameter, specify the Harbor URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## HarborRepositories + +A datasource of the `HarborRepositories` type collects information about all repositories in Harbor. + +### Authorization + +Authorization configuration is described in the ["Harbor external service"](../external-services/#harbor) section. + +### Response specification + +The portal gets the list of all projects, then gets the list of all repositories in each project by sending GET requests to the Harbor API: `/api/v2.0/projects/{project_name}/repositories`. +The response specification is available [in the Harbor interface](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). + +### Configuration + +In the `URL` parameter, specify the Harbor URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## HarborTags + +A datasource of the `HarborTags` type collects information about all artifact tags in Harbor. + +### Authorization + +Authorization configuration is described in the ["Harbor external service"](../external-services/#harbor) section. + +### Response specification + +The portal gets the list of all projects and the repositories they contain, then sends a GET request to the Harbor API for each available project: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. +Then all tags of all artifacts (the `tags` field) are collected, and the result is returned as an array. +The response specification is available [in the Harbor interface](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). + +### Configuration + +In the `URL` parameter, specify the Harbor URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## HelmReleases + +A datasource of the `HelmReleases` type returns a list of all HelmReleases in a Kubernetes cluster. + +### Authorization + +Authorization configuration is described in the ["Kubernetes external service"](../external-services/#kubernetes) section. + +Authentication in Kubernetes is described [in the official documentation](https://kubernetes.io/docs/reference/access-authn-authz/authentication/). + +### Response specification + +The portal returns all HelmReleases in the Kubernetes cluster. Specification: + +```json +[ + { + "name": "string", // Name. + "info": { + "first_deployed": "string", // Date and time of the first deployment. + "last_deployed": "string", // Date and time of the last deployment. + "deleted": "string", // Date and time of deletion (can be an empty string). + "description": "string", // Description. + "status": "string", // Status. + "notes": "string" // Notes. + }, + "chart": { + "metadata": { + "name": "string", // Chart name. + "home": "string", // Home page. + "sources": "array", // Array of strings with source URLs. + "version": "string", // Chart version. + "description": "string", // Chart description. + "keywords": "array", // Array of strings with keywords. + "maintainers": "array", // Array of objects with maintainer information. + "icon": "string", // Icon URL. + "apiVersion": "string", // API version. + "appVersion": "string" // Application version. + }, + "templates": [ // Array of template objects. + { + "name": "templates/NOTES.txt", + "data": "..." + }, + { + "name": "templates/_helpers.tpl", + "data": "..." + } + // ... other templates. + ], + "values": "object", // Object with the available Helm chart settings. + "schema": "null", // Schema (can be null). + "files": [ // Array of file objects. + { + "name": ".helmignore", + "data": "..." + }, + { + "name": "LICENSE", + "data": "..." + } + // ... other files. + ] + }, + "config": { // Current configuration. + "caSecretName": "string", + "cache": { + "enabled": "boolean", + "expireHours": "integer" + } + // ... other settings. + }, + "manifest": "string", // Rendered manifests. + "version": "integer", // HelmRelease version. + "namespace": "string" // Namespace where the release is deployed. + }, + // ... other HelmRelease resources. +] + +``` + +### Configuration + +In the `URL` parameter, specify the Kubernetes API URL in the `https://api.example.com` format. + +### Parameters + +There are no configurable parameters. + +## KafkaAcls + +A datasource of the `KafkaAcls` type collects information about the available ACLs. + +### Authorization + +The portal supports authentication in Kafka using [SASL/PLAIN](https://kafka.apache.org/documentation/#security_sasl_plain), [SASL/SCRAM](https://kafka.apache.org/documentation/#security_sasl_scram). + +### Response specification + +The portal requests information about the ACLs configured in Kafka. The retrieved data is provided in the following format: + +```json +[ + { + "Cluster": "string", // Kafka cluster name. + "ResourceType": "string", // Resource type (TOPIC, GROUP, and others). + "ResourceName": "string", // Resource name. + "PatternType": "string", // Pattern type (LITERAL, PREFIXED, and others). + "Principal": "string", // User principal (for example, "User:Alice"). + "Host": "string", // Host (usually "*" for any host). + "Operation": "string", // Operation (READ, WRITE, DESCRIBE, and others). + "PermissionType": "string" // Permission type (ALLOW, DENY). + }, + // ... other ACL entries. +] +``` + +### Configuration + +In the `URL` parameter, specify the Kafka URL in the `example.com` format. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | +| --- | --- | --- | --- | +| SecurityProtocol | Yes | Protocol used to connect to Kafka. See the [Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| SaslMechanism | No | Authentication mechanism used by SASL. Required with the SASL_PLAINTEXT or SASL_SSL protocol. See the [Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| User | Yes | Username for connecting to Kafka | — | +| Pass | Yes | User password for connecting to Kafka | — | + +## KafkaBrokers + +A datasource of the `KafkaBrokers` type collects information about the available brokers. + +### Authorization + +The portal supports authentication in Kafka using [SASL/PLAIN](https://kafka.apache.org/documentation/#security_sasl_plain), [SASL/SCRAM](https://kafka.apache.org/documentation/#security_sasl_scram). + +### Response specification + +The portal sends several requests to Kafka to retrieve information about the available brokers. +The retrieved data is provided in the following format: + +```json +{ + "Cluster": "string", // Kafka cluster name (from kafkaBrokerMetadata.Cluster). + "Leader": "boolean", // Whether the broker is the controller leader (true/false). + "NodeID": "number", // Unique broker ID (from broker.NodeID). + "Port": "number", // Broker port (from broker.Port). + "Host": "string", // Broker host (from broker.Host). + "Rack": "string|null", // Broker rack (availability zone) (from broker.Rack). + "Configs": { // Broker configurations. + { + "Name": "number", // Unique broker ID. + "Configs": [ // Array of individual configurations. + { + "Key": "listeners", // Configuration key. + "Value": "CLIENT://:9092,INTERNAL://:9094", // Configuration value. + "Source": "STATIC_BROKER_CONFIG" // Configuration source. + }, + { + "Key": "log.retention.hours", // Configuration key. + "Value": 168, // Configuration value. + "Source": "DEFAULT_CONFIG" // Configuration source. + }, + { + "...": "..." // Other parameters. + // For the full list of parameters, see the official documentation: + // https://kafka.apache.org/documentation/#brokerconfigs. + } + ] + } + } +} +``` + +### Configuration + +In the `URL` parameter, specify the Kafka URL in the `example.com` format. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | +| --- | --- | --- | --- | +| SecurityProtocol | Yes | Protocol used to connect to Kafka. See the [Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| SaslMechanism | No | Authentication mechanism used by SASL. Required with the SASL_PLAINTEXT or SASL_SSL protocol. See the [Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| User | Yes | Username for connecting to Kafka | — | +| Pass | Yes | User password for connecting to Kafka | — | + +## KafkaTopics + +A datasource of the `KafkaTopics` type collects information about the available topics in Kafka. + +### Authorization + +The portal supports authentication in Kafka using [SASL/PLAIN](https://kafka.apache.org/documentation/#security_sasl_plain), [SASL/SCRAM](https://kafka.apache.org/documentation/#security_sasl_scram). + +### Response specification + +The portal sends several requests to Kafka to retrieve information about the available topics. +The retrieved data is provided in the following format: + +```json +{ + "Cluster": "string", // Kafka cluster name. + "Topic": "string", // Topic name. + "ID": "string", // Unique topic identifier. + "IsInternal": "boolean", // Whether the topic is internal (example of an internal topic: __consumer_offsets). + "Partitions": "number", // Number of partitions in the topic. + "Configs": { // Topic configurations (dynamic parameters). + "retention.ms": 604800000, // Example parameter: message retention time. + "cleanup.policy": "delete", // Example parameter: cleanup policy. + "...": "..." // Other parameters. + // For the full list of parameters, see the official documentation: + // https://kafka.apache.org/documentation/#topicconfigs. + } +} +``` + +### Configuration + +In the `URL` parameter, specify the Kafka URL in the `example.com` format. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | +| --- | --- | --- | --- | +| SecurityProtocol | Yes | Protocol used to connect to Kafka. See the [Kafka documentation](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | +| SaslMechanism | No | Authentication mechanism used by SASL. Required with the SASL_PLAINTEXT or SASL_SSL protocol. See the [Kafka documentation](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | +| User | Yes | Username for connecting to Kafka | — | +| Pass | Yes | User password for connecting to Kafka | — | + +## KubernetesResources + +A datasource of the `KubernetesResources` type returns a list of Kubernetes resources. +The type of returned resources is set in the datasource parameters. +Both built-in Kubernetes resource types and any custom resources are supported. + +### Authorization + +Authorization configuration is described in the ["Kubernetes external service"](../external-services/#kubernetes) section. + +### Response specification + +The response specification depends on the type of resource you want to retrieve. +For exact information, refer to the documentation. +For built-in Kubernetes resources, the [official documentation](https://kubernetes.io/docs/reference/kubernetes-api/) is available. + +If you cannot access the documentation, you can get the specification description using the `d8 k explain` command. + +Example for a Deployment: + +`d8 k explain deployment --recursive` + +Sample output: + +```console +GROUP: apps +KIND: Deployment +VERSION: v1 + +DESCRIPTION: + Deployment enables declarative updates for Pods and ReplicaSets. + +FIELDS: + apiVersion + kind + metadata + annotations + creationTimestamp +... +``` + +The specification description is located under `FIELDS:`. + +### Configuration + +In the `URL` parameter, specify the Kubernetes API URL in the `https://api.example.com` format. + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | +| --- | --- | --- | --- | +| `apiGroup` | No | API group of the resource. Leave the field empty for resources in the core API group | [See how to determine the required group and version](#determining-the-required-group-and-version) | +| `version` | Yes | API version of the resource | [See how to determine the required group and version](#determining-the-required-group-and-version) | +| `isNamespaced` | Yes | Whether the resource is namespaced. You can check this using the `d8 k api-resources` command | `true`, `false` | +| `namespace` | No | Namespace to collect resources from. If not specified, resources are collected from all namespaces. The value is taken into account only if `isNamespaced` is `true` | — | +| `resource` | Yes | Resource name. Specified in lowercase plural form, as in the NAME field of the `d8 k api-resources` command output | — | + +### Examples + +Collect all Ingress resources of a Kubernetes cluster: + +```yaml +apiGroup: networking.k8s.io +version: v1 +isNamespaced: true +resource: ingresses +``` + +Collect all pods of a Kubernetes cluster: + +```yaml +version: v1 +isNamespaced: true +resource: pods +``` + +Collect all pods of a Kubernetes cluster in the `d8-development-platform` namespace: + +```yaml +version: v1 +isNamespaced: true +resource: pods +namespace: d8-development-platform +``` + +Collect all namespaces of a Kubernetes cluster: + +```yaml +version: v1 +isNamespaced: false +resource: namespaces +``` + +Collect all ModuleRelease custom resources of a Kubernetes cluster: + +```yaml +apiGroup: deckhouse.io +version: v1alpha1 +isNamespaced: false +resource: modulereleases +``` + +### Determining the required group and version + +Each resource type has its own version and group. +For the full list of API resources with their groups and versions, see the [Kubernetes documentation](https://kubernetes.io/docs/reference/kubernetes-api/). + +If you do not know which group and version are required, you can look up the current values. +There are several ways to do this, for example, using the `d8 k` utility. +The `d8 k explain` command shows the `version` and `apiGroup` of a resource. + +Example: + +```bash +d8 k explain deployment +``` + +Output: + +```console +GROUP: apps +KIND: Deployment +VERSION: v1 + +DESCRIPTION: + Deployment enables declarative updates for Pods and ReplicaSets. + +FIELDS: +... +``` + +## NexusArtifacts + +A datasource of the `NexusArtifacts` type returns a list of artifacts in Nexus. + +### Authorization + +Authorization configuration is described in the ["Nexus external service"](../external-services/#nexus) section. + +### Response specification + +The portal builds a list of available repositories, then sends a GET request to the Nexus API for each repository: `/service/rest/v1/components`. +[Response specification](https://help.sonatype.com/en/components-api.html). + +### Configuration + +In the `URL` parameter, specify the Nexus URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## NexusRepositories + +A datasource of the `NexusRepositories` type returns a list of repositories in Nexus. + +### Authorization + +Authorization configuration is described in the ["Nexus external service"](../external-services/#nexus) section. + +### Response specification + +The portal sends a GET request to the Nexus API: `/service/rest/v1/repositories`. +[Response specification](https://help.sonatype.com/en/repositories-api.html). + +### Configuration + +In the `URL` parameter, specify the Nexus URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## PrometheusMetrics + +A datasource of the `PrometheusMetrics` type returns the result of a PromQL query in Prometheus. + +### Authorization + +Authorization configuration is described in the ["Prometheus external service"](../external-services/#prometheus) section. + +### Response specification + +The portal sends a GET request to the Prometheus API: `/api/v1/query`. +[Response specification](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries). + +### Configuration + +In the `URL` parameter, specify the Prometheus API URL in the `https://example.com/api/v1/query` format. +In the "Query" parameter, specify a [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) query used to build the response. + +### Parameters + +There are no configurable parameters. + +## SonarqubeProjects + +A datasource of the `SonarqubeProjects` type returns a list of projects in SonarQube. + +### Authorization + +Authorization configuration is described in the ["SonarQube external service"](../external-services/#sonarqube) section. + +### Response specification + +The portal sends a GET request to the SonarQube API: `/api/projects/search`. +The system collects all available `components` and returns them as an array. +[`components` specification](https://next.sonarqube.com/sonarqube/web_api/api/projects/search). + +### Configuration + +In the `URL` parameter, specify the SonarQube URL in the `https://example.com` format. + +### Parameters + +There are no configurable parameters. + +## GenericAPI + +A datasource of the `GenericAPI` type lets you connect to any REST API and retrieve data in JSON format. +Various pagination types and configurable request parameters are supported. + +### Authorization + +GenericAPI supports any authentication type through HTTP header configuration. The most common methods are: + +Bearer Token: + +```text +Authorization: Bearer +``` + +Basic Authentication: + +```text +Authorization: Basic +``` + +API Key: + +```text +X-API-Key: +``` + +### Configuration + +When configuring the datasource, set the following parameters: + +- `URL`: Base API URL in the `https://api.example.com` format. +- `Method`: HTTP method (GET, POST, PUT, PATCH, DELETE). +- `Query`: Additional query parameters (for example, for filtering or searching). + +### Parameters + +The datasource supports the following parameters: + +| Name | Required | Description | Possible values | Example | Default value | +| --- | --- | --- | --- | --- | --- | +| `paginationType` | No | Pagination type for processing large amounts of data | `none`, `offset`, `cursor`, `page`, `link_header` | `none` | `none` | +| `path` | No | API endpoint path appended to the base URL | Any string starting with `/` | `/api/v1/users`, `/projects` | `""` | +| `dataPath` | No | Path to the data in the response (a chain of dot-separated keys) | Any string | `data`, `results.items`, `.` | `.` | +| `responseFormat` | No | Response format | `array`, `map` | `array`, `map` | `array` | +| `mapKeyField` | No | With `responseFormat` set to `map`: name of the field to write the JSON object key to | Any string | `slug`, `externalId` | `""` | +| `pageParam` | No | Name of the page number parameter (for page pagination) | Any string | `page`, `_page`, `pageNumber` | `page` | +| `offsetParam` | No | Name of the offset parameter (for offset pagination) | Any string | `offset`, `skip` | `offset` | +| `limitParam` | No | Name of the parameter for the number of items per page (for offset pagination) | Any string | `limit`, `_limit` | `limit` | +| `sizeParam` | No | Name of the page size parameter (for page pagination) | Any string | `size`, `pageSize`, `_size` | `size` | +| `cursorParam` | No | Name of the cursor parameter (for cursor pagination) | Any string | `cursor`, `after`, `next` | `cursor` | +| `pageSize` | No | Number of items per page for pagination | Positive integer | `10`, `20`, `50`, `100` | `100` | +| `maxPages` | No | Maximum number of pages to load for all pagination types. `0` means no limit | Non-negative integer | `10`, `50` | `0` | +| `nextCursorPath` | Yes, with `paginationType: cursor` | Name of the field in the last item of the received data that contains the next page cursor | Any string | `next_cursor`, `cursor` | `""` | +| `requestBody` | No | Request body for the POST/PUT/PATCH methods | Any string | `{"query": "example"}` | `""` | + +### Response specification + +The expected response format is set by the `responseFormat` parameter (`array` by default). + +Example response for `responseFormat: array`: + +```json +[ + { + "id": 1, + "name": "Example Item", + "description": "Description of the item", + "created_at": "2023-01-01T00:00:00Z" + }, + { + "id": 2, + "name": "Another Item", + "description": "Another description", + "created_at": "2023-01-02T00:00:00Z" + } +] +``` + +Example response for `responseFormat: map`: + +```json +{ + "billing": { "title": "Billing", "owner": "team-a" }, + "shipping": { "title": "Shipping", "owner": "team-b" } +} +``` + +Before processing, a response with `responseFormat: map` is converted into an array based on the `mapKeyField` parameter value. + +With `mapKeyField: example`, an array is passed for processing with an added `example` field whose value is taken from the object key: + +```json +[ + { "example": "billing", "title": "Billing", "owner": "team-a" }, + { "example": "shipping", "title": "Shipping", "owner": "team-b" } +] +``` + +If `mapKeyField` is not set (an empty string), an array is passed for processing without adding a new field: + +```json +[ + { "title": "Billing", "owner": "team-a" }, + { "title": "Shipping", "owner": "team-b" } +] +``` + +### Pagination types + +The following pagination types are supported: + +- `none`: No pagination; all data is retrieved in a single request. + +- `offset`: Pagination by offset and limit: + - Uses the `offsetParam` and `limitParam` parameters. + - The offset starts at `0` and increases by the number of received records. + - Example: `?offset=0&limit=100`, then `?offset=100&limit=100`. + +- `page`: Pagination by page number and size: + - Uses the `pageParam` and `sizeParam` parameters. + - Example: `?page=1&size=20`. + +- `cursor`: Cursor-based pagination: + - Uses the `cursorParam` and `nextCursorPath` parameters. + The `nextCursorPath` parameter is required. If it is not set, only the first page is loaded. + - The next page cursor is taken from the `nextCursorPath` field of the last item of the received data and passed in the `cursorParam` query parameter. + Loading stops when the cursor field is missing, empty, or not a string. + - Example: `?cursor=eyJpZCI6MTIzfQ==`. + +- `link_header`: Pagination using the Link header: + - Uses the `Link` header in the response to determine the next page. + - RFC 5988 standard. + +### Configuration examples + +JSONPlaceholder API (no pagination): + +```yaml +url: https://jsonplaceholder.typicode.com +path: /users +paginationType: none +dataPath: . +``` + +GitLab API (page pagination): + +```yaml +url: https://gitlab.example.com +path: /api/v4/projects +paginationType: page +pageParam: page +sizeParam: per_page +pageSize: 20 +headers: + Authorization: Bearer +``` + +DefectDojo API (offset pagination): + +```yaml +url: https://defectdojo.example.com +path: /api/v2/engagements +paginationType: offset +limitParam: limit +pageSize: 100 +dataPath: results +query: "product=42" +headers: + Authorization: Token +``` + +GitHub API (Link header pagination): + +```yaml +url: https://api.github.com +path: /repos/owner/repo/issues +paginationType: link_header +headers: + Authorization: Bearer + Accept: application/vnd.github.v3+json +``` + +API with nested data: + +```yaml +url: https://api.example.com +path: /data +dataPath: response.data.items +paginationType: page +pageParam: page +sizeParam: limit +query: "filter=active&sort=name" +``` + +POST request with a body: + +```yaml +url: https://api.example.com +path: /search +method: POST +requestBody: '{"query": "example", "filters": {"status": "active"}}' +query: "include=metadata&format=json" +headers: + Content-Type: application/json + Authorization: Bearer +``` diff --git a/content/documentation/admin/datasources/types.ru.md b/content/documentation/admin/datasources/types.ru.md index 990e6bcf..85bc5257 100644 --- a/content/documentation/admin/datasources/types.ru.md +++ b/content/documentation/admin/datasources/types.ru.md @@ -14,11 +14,13 @@ weight: 20 ### Спецификация ответа -DDP (портал) выполняет GET-запрос по URL: `/api/v2/products`. Возвращаются все доступные значения. [Спецификация ответа](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). +Deckhouse Development Portal (DDP, портал) выполняет GET-запрос по URL: `/api/v2/products`. +Возвращаются все доступные значения. +[Спецификация ответа](https://demo.defectdojo.org/api/v2/oa3/swagger-ui/). ### Конфигурация -- `URL` — URL DefectDojo в формате `https://example.com`. +В параметре `URL` укажите URL DefectDojo в формате `https://example.com`. ### Параметры @@ -34,11 +36,13 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc ### Спецификация ответа -Портал выполняет GET-запрос к API GitLab по URL: `/api/v4/groups`. Портал возвращает все доступные значения. [Спецификация ответа](https://docs.gitlab.com/api/groups/#list-groups). +Портал выполняет GET-запрос к API GitLab по URL: `/api/v4/groups`. +Портал возвращает все доступные значения. +[Спецификация ответа](https://docs.gitlab.com/api/groups/#list-groups). ### Конфигурация -- `URL` — URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. +В параметре `URL` укажите URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. ### Параметры @@ -56,35 +60,43 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc В зависимости от [конфигурации параметров](#gitlabprojectsparameters), портал выполняет GET-запрос к API GitLab и возвращает соответствующую спецификацию. -Если значение параметра `all` равно `true`, выполняется GET-запрос по URL: `/api/v4/projects`. Портал возвращает все доступные значения. [Спецификация ответа](https://docs.gitlab.com/api/projects/#list-all-projects). +Если значение параметра `all` равно `true`, выполняется GET-запрос по URL: `/api/v4/projects`. +Портал возвращает все доступные значения. +[Спецификация ответа](https://docs.gitlab.com/api/projects/#list-all-projects). -Если значение параметра `all` равно `false`, выполняется GET-запрос по URL: `/api/v4/groups/:id/projects`. Портал возвращает все доступные значения. [Спецификация ответа](https://docs.gitlab.com/api/projects/#list-all-projects). +Если значение параметра `all` равно `false`, выполняется GET-запрос по URL: `/api/v4/groups/:id/projects`. +Портал возвращает все доступные значения. +[Спецификация ответа](https://docs.gitlab.com/api/projects/#list-all-projects). -Если значение параметра `tags` равно `true`, портал дополнительно получает git-теги. Для получения git-тегов выполняется GET-запрос по URL: `/api/v4/projects/:id/repository/tags`. Портал получает список всех git-тегов и расширяет [спецификацию ответа](https://docs.gitlab.com/api/projects/#list-all-projects) полем `ddp_repository_tags`, которое соответствует [спецификации ответа list-project-repository-tags](https://docs.gitlab.com/api/tags/#list-project-repository-tags). +Если значение параметра `tags` равно `true`, портал дополнительно получает git-теги. +Для получения git-тегов выполняется GET-запрос по URL: `/api/v4/projects/:id/repository/tags`. +Портал получает список всех git-тегов и расширяет [спецификацию ответа](https://docs.gitlab.com/api/projects/#list-all-projects) полем `ddp_repository_tags`, которое соответствует [спецификации ответа list-project-repository-tags](https://docs.gitlab.com/api/tags/#list-project-repository-tags). ### Конфигурация -- `URL` — URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. +В параметре `URL` укажите URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. ### Параметры -|Название |Обязательность |Описание |Возможные значения |По умолчанию | +Источник данных поддерживает следующие параметры: + +|Название |Обязательность |Описание |Возможные значения | Значение по умолчанию | |-----------------|--------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|------------------------------------------------------------------------------| -|all |Опционально |В явном виде указывает, что необходимо собирать репозитории всех групп, к которым есть доступ |true, false |false | -|group_ids |Обязательно, если `all` в значении `false`|Источник данных будет собирать проекты групп с указанным ID. ID групп указываются через запятую |Пример: 1001,1002 |\- | -|tags |Опционально |Портал дополнительно получает список всех git тегов и расширяет [спецификацию ответа](https://docs.gitlab.com/api/projects/#list-all-projects) полем `ddp_repository_tags`, которое соответствует [спецификации ответа list-project-repository-tags](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |true, false |false | -|include_subgroups|Опционально |Если указан параметр `group_ids`, то параметр `include_subgroups` определяет, собирать ли проекты подгрупп указанных групп |true, false |false | -|tags_order_by |Опционально |Поле для сортировки тегов. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |`updated`, `name`, `version` |`updated` | -|tags_sort |Опционально |Направление сортировки тегов. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |`asc`, `desc` |`desc` | -|tags_search |Опционально |Строка для поиска тегов по имени. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |Строка |\- | +| `all` |Опционально |В явном виде указывает, что необходимо собирать репозитории всех групп, к которым есть доступ | `true`, `false` | `false` | +| `group_ids` |Обязательно, если `all` в значении `false`|Источник данных будет собирать проекты групп с указанным ID. ID групп указываются через запятую |Пример: 1001,1002 |\- | +| `tags` |Опционально |Портал дополнительно получает список всех git тегов и расширяет [спецификацию ответа](https://docs.gitlab.com/api/projects/#list-all-projects) полем `ddp_repository_tags`, которое соответствует [спецификации ответа list-project-repository-tags](https://docs.gitlab.com/api/tags/#list-project-repository-tags) | `true`, `false` | `false` | +| `include_subgroups` |Опционально |Если указан параметр `group_ids`, то параметр `include_subgroups` определяет, собирать ли проекты подгрупп указанных групп | `true`, `false` | `false` | +| `tags_order_by` |Опционально |Поле для сортировки тегов. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |`updated`, `name`, `version` |`updated` | +| `tags_sort` |Опционально |Направление сортировки тегов. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |`asc`, `desc` |`desc` | +| `tags_search` |Опционально |Строка для поиска тегов по имени. Описание параметра — в [GitLab Tags API](https://docs.gitlab.com/api/tags/#list-project-repository-tags) |Строка |\- | ## GitlabRepositoryActivity -Источник данных типа `GitlabRepositoryActivity` возвращает активность проектов GitLab: число открытых merge request, последний коммит и последний пайплайн ветки по умолчанию. +Источник данных типа `GitlabRepositoryActivity` возвращает активность проектов GitLab: число открытых запросов на слияние (Merge Request), последний коммит и последний пайплайн ветки по умолчанию. -Источник заполняет показатели карточки микросервиса на главной и используется набором данных «GitLab: активность репозиториев». +Источник заполняет показатели карточки микросервиса на главной странице и используется набором данных «GitLab: активность репозиториев». ### Авторизация @@ -92,16 +104,17 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc ### Спецификация ответа -Портал выполняет POST-запросы к GraphQL API GitLab по URL `/api/graphql`, по 50 проектов на запрос. Для каждой группы, заданной числовым ID, дополнительно выполняется GET-запрос по URL `/api/v4/groups/:id`. +Портал выполняет POST-запросы к GraphQL API GitLab по URL `/api/graphql`, по 50 проектов на запрос. +Для каждой группы, заданной числовым ID, дополнительно выполняется GET-запрос по URL `/api/v4/groups/:id`. Для каждого проекта источник возвращает поля: -| Поле | Описание | +| Название | Описание | | ----------------------- | ----------------------------------------------------------------- | | `path` | Путь проекта без пути группы | | `gitlab_repository_id` | Числовой ID проекта | | `default_branch` | Ветка по умолчанию | -| `open_mr_count` | Число открытых merge request | +| `open_mr_count` | Число открытых запросов на слияние | | `last_commit_sha` | Короткий SHA последнего коммита ветки по умолчанию | | `last_commit_message` | Заголовок последнего коммита | | `last_commit_author` | Автор последнего коммита | @@ -113,15 +126,17 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc ### Конфигурация -- `URL` — URL GitLab в формате `https://gitlab.com`, без части `/api/graphql`. +В параметре `URL` укажите URL GitLab в формате `https://gitlab.com`, без части `/api/graphql`. ### Параметры -| Название | Обязательность | Описание | Возможные значения | По умолчанию | +Источник данных поддерживает следующие параметры: + +| Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | ----------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------- | --------------------------- | ------------ | -| all | Опционально | Собирать активность всех проектов, участником которых является пользователь токена. Параметр `group_ids` при этом не используется | true, false | false | -| group_ids | Обязательно, если `all` в значении `false` | ID или полные пути групп через запятую | Пример: `1001,platform/backend` | \- | -| include_subgroups | Опционально | Собирать проекты подгрупп указанных групп | true, false | false | +| `all` | Опционально | Собирать активность всех проектов, участником которых является пользователь токена. Параметр `group_ids` при этом не используется | `true`, `false` | `false` | +| `group_ids` | Обязательно, если `all` в значении `false` | ID или полные пути групп через запятую | Пример: `1001,platform/backend` | \- | +| `include_subgroups` | Опционально | Собирать проекты подгрупп указанных групп | `true`, `false` | `false` | Если группа не найдена или недоступна, синхронизация завершается ошибкой `gitlab group "" not found or not accessible`. @@ -135,18 +150,20 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc ### Спецификация ответа -Портал получает список проектов GET-запросом к API GitLab по URL `/api/v4/projects`, если значение параметра `all` равно `true`, или по URL `/api/v4/groups/:id/projects` для каждой группы из параметра `group_ids`. [Спецификация ответа](https://docs.gitlab.com/api/projects/#list-projects). - -Затем для каждого проекта портал определяет файлы для чтения: +Портал получает список проектов GET-запросом к API GitLab по URL `/api/v4/projects`, если значение параметра `all` равно `true`, или по URL `/api/v4/groups/:id/projects` для каждой группы из параметра `group_ids`. +[Спецификация ответа](https://docs.gitlab.com/api/projects/#list-projects). -- если задан параметр `file_path`, читается только указанный файл; -- если задан параметр `file_pattern`, портал получает дерево репозитория GET-запросом по URL `/api/v4/projects/:id/repository/tree` и выбирает файлы, подходящие под маску. +Затем для каждого проекта портал определяет файлы для чтения. +Если задан параметр `file_path`, читается только указанный файл. +Если задан параметр `file_pattern`, портал получает дерево репозитория GET-запросом по URL `/api/v4/projects/:id/repository/tree` и выбирает файлы, подходящие под маску. -Содержимое каждого файла портал получает GET-запросом по URL `/api/v4/projects/:id/repository/files/:file_path`. Файл может содержать несколько YAML-документов, разделённых `---`. Каждый документ должен быть объектом. +Содержимое каждого файла портал получает GET-запросом по URL `/api/v4/projects/:id/repository/files/:file_path`. +Файл может содержать несколько YAML-документов, разделённых `---`. +Каждый документ должен быть объектом. Каждая запись содержит поля документа (при `document_mode: file`) или поля элемента списка (при `document_mode: list`), а также служебные поля: -| Поле | Описание | +| Название | Описание | | ----------------- | ------------------------------------------------------------------------ | | `_file_path` | Путь файла в репозитории | | `_file_name` | Имя файла | @@ -161,31 +178,36 @@ DDP (портал) выполняет GET-запрос по URL: `/api/v2/produc | `_document` | Весь документ, из которого получена запись | | `_index` | Номер элемента в списке, начиная с `0`. Только при `document_mode: list` | -Проекты, файлы которых не удалось прочитать, пропускаются. Файл с синтаксической ошибкой пропускается целиком. Сведения о пропущенных проектах и файлах записываются в лог синхронизации. +Проекты, файлы которых не удалось прочитать, пропускаются. +Файл с синтаксической ошибкой пропускается целиком. +Сведения о пропущенных проектах и файлах записываются в лог синхронизации. ### Конфигурация -- `URL` — URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. +В параметре `URL` укажите URL GitLab в формате `https://gitlab.com`, без части `/api/v4`. ### Параметры -| Название | Обязательность | Описание | Возможные значения | По умолчанию | +Источник данных поддерживает следующие параметры: + +| Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | ----------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------ | -| all | Опционально | Читать файлы из проектов всех групп, к которым есть доступ. Параметр `group_ids` при этом не используется | true, false | false | -| group_ids | Обязательно, если `all` в значении `false` | ID групп через запятую | Пример: `1001,1002` | \- | -| include_subgroups | Опционально | Если указан параметр `group_ids`, определяет, читать ли файлы из проектов подгрупп указанных групп | true, false | false | -| topic | Опционально | Читать файлы только из проектов с указанной темой (topic) GitLab. Фильтрация выполняется на стороне GitLab | Строка | \- | -| project_pattern | Опционально | Регулярное выражение для полного пути проекта (`path_with_namespace`). Проекты, путь которых не совпадает с выражением, пропускаются | Регулярное выражение | \- | -| max_projects | Опционально | Максимальное число проектов, из которых читаются файлы. Остальные проекты не обрабатываются, в лог синхронизации записывается предупреждение. `0` — без ограничения | Целое неотрицательное число | `0` | -| ref | Опционально | Ветка или тег, из которых читаются файлы. Если не задан, используется ветка по умолчанию каждого проекта | Строка | \- | -| file_path | Обязательно, если не задан `file_pattern` | Точный путь файла в репозитории. Дерево репозитория при этом не запрашивается | Пример: `catalog/service.yaml` | \- | -| path | Опционально | Директория в репозитории, с которой начинается поиск файлов по маске `file_pattern`. Пустое значение — корень репозитория | Пример: `catalog` | `""` | -| file_pattern | Обязательно, если не задан `file_path` | Маска имени файла в формате [path.Match](https://pkg.go.dev/path#Match). Если маска содержит `/`, она сопоставляется с полным путём файла в репозитории | Пример: `*.yaml` | \- | -| recursive | Опционально | Искать файлы по маске `file_pattern` во вложенных директориях | true, false | true | -| document_mode | Опционально | Способ преобразования документа в записи: `file` — документ становится одной записью, `list` — записью становится каждый элемент списка по ключу `list_path` | `file`, `list` | `file` | -| list_path | Обязательно, если `document_mode` равен `list` | Ключ верхнего уровня документа, по которому находится список элементов | Пример: `items` | \- | - -Должен быть задан ровно один из параметров `file_path` и `file_pattern`. Если параметры заданы некорректно, синхронизация завершается ошибкой. +| `all` | Опционально | Читать файлы из проектов всех групп, к которым есть доступ. Параметр `group_ids` при этом не используется | `true`, `false` | `false` | +| `group_ids` | Обязательно, если `all` в значении `false` | ID групп через запятую | Пример: `1001,1002` | \- | +| `include_subgroups` | Опционально | Если указан параметр `group_ids`, определяет, читать ли файлы из проектов подгрупп указанных групп | `true`, `false` | `false` | +| `topic` | Опционально | Читать файлы только из проектов с указанной темой (topic) GitLab. Фильтрация выполняется на стороне GitLab | Строка | \- | +| `project_pattern` | Опционально | Регулярное выражение для полного пути проекта (`path_with_namespace`). Проекты, путь которых не совпадает с выражением, пропускаются | Регулярное выражение | \- | +| `max_projects` | Опционально | Максимальное число проектов, из которых читаются файлы. Остальные проекты не обрабатываются, в лог синхронизации записывается предупреждение. `0` — без ограничения | Целое неотрицательное число | `0` | +| `ref` | Опционально | Ветка или тег, из которых читаются файлы. Если не задан, используется ветка по умолчанию каждого проекта | Строка | \- | +| `file_path` | Обязательно, если не задан `file_pattern` | Точный путь файла в репозитории. Дерево репозитория при этом не запрашивается | Пример: `catalog/service.yaml` | \- | +| `path` | Опционально | Директория в репозитории, с которой начинается поиск файлов по маске `file_pattern`. Пустое значение — корень репозитория | Пример: `catalog` | `""` | +| `file_pattern` | Обязательно, если не задан `file_path` | Маска имени файла в формате [path.Match](https://pkg.go.dev/path#Match). Если маска содержит `/`, она сопоставляется с полным путём файла в репозитории | Пример: `*.yaml` | \- | +| `recursive` | Опционально | Искать файлы по маске `file_pattern` во вложенных директориях | `true`, `false` | `true` | +| `document_mode` | Опционально | Способ преобразования документа в записи: `file` — документ становится одной записью, `list` — записью становится каждый элемент списка по ключу `list_path` | `file`, `list` | `file` | +| `list_path` | Обязательно, если `document_mode` равен `list` | Ключ верхнего уровня документа, по которому находится список элементов | Пример: `items` | \- | + +Должен быть задан ровно один из параметров `file_path` и `file_pattern`. +Если параметры заданы некорректно, синхронизация завершается ошибкой. ### Пример @@ -209,11 +231,12 @@ list_path: services ### Спецификация ответа -Портал получает список всех проектов и репозиториев, которые содержатся в этих проектах, затем по каждому из доступных проектов выполняется GET-запрос к API Harbor: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). +Портал получает список всех проектов и репозиториев, которые содержатся в этих проектах, затем по каждому из доступных проектов выполняется GET-запрос к API Harbor: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. +Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). ### Конфигурация -- `URL` — URL Harbor в формате `https://example.com`. +В параметре `URL` укажите URL Harbor в формате `https://example.com`. ### Параметры @@ -229,11 +252,12 @@ list_path: services ### Спецификация ответа -Портал получает список всех доступных проектов, выполняя GET-запросы к API Harbor: `/api/v2.0/projects`. Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). +Портал получает список всех доступных проектов, выполняя GET-запросы к API Harbor: `/api/v2.0/projects`. +Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). ### Конфигурация -- `URL` — URL Harbor в формате `https://example.com`. +В параметре `URL` укажите URL Harbor в формате `https://example.com`. ### Параметры @@ -249,11 +273,12 @@ list_path: services ### Спецификация ответа -Портал получает список всех проектов, затем получает список всех репозиториев в каждом из проектов, выполняя GET-запросы к API Harbor: `/api/v2.0/projects/{project_name}/repositories`. Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). +Портал получает список всех проектов, затем получает список всех репозиториев в каждом из проектов, выполняя GET-запросы к API Harbor: `/api/v2.0/projects/{project_name}/repositories`. +Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). ### Конфигурация -- `URL` — URL Harbor в формате `https://example.com`. +В параметре `URL` укажите URL Harbor в формате `https://example.com`. ### Параметры @@ -269,11 +294,13 @@ list_path: services ### Спецификация ответа -Портал получает список всех проектов и репозиториев, которые содержатся в этих проектах, затем по каждому из доступных проектов выполняется GET-запрос к API Harbor: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. Затем происходит сбор всех тегов по всем артефактам (поле `tags`) и результат возвращается в виде массива. Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). +Портал получает список всех проектов и репозиториев, которые содержатся в этих проектах, затем по каждому из доступных проектов выполняется GET-запрос к API Harbor: `/api/v2.0/projects/{project_name}/repositories/{repository_name}/artifacts`. +Затем происходит сбор всех тегов по всем артефактам (поле `tags`) и результат возвращается в виде массива. +Спецификация ответа доступна [в интерфейсе Harbor](https://goharbor.io/docs/main/working-with-projects/using-api-explorer/). ### Конфигурация -- `URL` — URL Harbor в формате `https://example.com`. +В параметре `URL` укажите URL Harbor в формате `https://example.com`. ### Параметры @@ -362,7 +389,7 @@ list_path: services ### Конфигурация -- `URL` — URL Kubernetes API в формате `https://api.example.com`. +В параметре `URL` укажите URL Kubernetes API в формате `https://api.example.com`. ### Параметры @@ -398,16 +425,18 @@ list_path: services ### Конфигурация -- `URL` — URL Kafka в формате `example.com`. +В параметре `URL` укажите URL Kafka в формате `example.com`. ### Параметры +Источник данных поддерживает следующие параметры: + |Название |Обязательность | Описание |Возможные значения | |-----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| |SecurityProtocol | Обязательно | Протокол для подключения к Kafka — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | |SaslMechanism | Опционально | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -|User | Обязательно | Имя пользователя для подключения к Kafka | - | -|Pass | Обязательно | Пароль пользователя для подключения к Kafka | - | +|User | Обязательно | Имя пользователя для подключения к Kafka | — | +|Pass | Обязательно | Пароль пользователя для подключения к Kafka | — | ## KafkaBrokers @@ -419,7 +448,8 @@ list_path: services ### Спецификация ответа -Портал выполняет несколько запросов к Kafka с целью получения сведений о доступных брокерах. Полученные данные предоставляются в следующем формате: +Портал выполняет несколько запросов к Kafka с целью получения сведений о доступных брокерах. +Полученные данные предоставляются в следующем формате: ```json { @@ -456,16 +486,18 @@ list_path: services ### Конфигурация -- `URL` — URL Kafka в формате `example.com`. +В параметре `URL` укажите URL Kafka в формате `example.com`. ### Параметры +Источник данных поддерживает следующие параметры: + |Название |Обязательность | Описание |Возможные значения | |-----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| |SecurityProtocol | Обязательно | Протокол для подключения к Kafka — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | |SaslMechanism | Опционально | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -|User | Обязательно | Имя пользователя для подключения к Kafka | - | -|Pass | Обязательно | Пароль пользователя для подключения к Kafka | - | +|User | Обязательно | Имя пользователя для подключения к Kafka | — | +|Pass | Обязательно | Пароль пользователя для подключения к Kafka | — | ## KafkaTopics @@ -477,7 +509,8 @@ list_path: services ### Спецификация ответа -Портал осуществляет несколько запросов к Kafka с целью получения сведений о доступных топиках. Полученные данные предоставляются в следующем формате: +Портал осуществляет несколько запросов к Kafka с целью получения сведений о доступных топиках. +Полученные данные предоставляются в следующем формате: ```json { @@ -498,20 +531,24 @@ list_path: services ### Конфигурация -- `URL` — URL Kafka в формате `example.com`. +В параметре `URL` укажите URL Kafka в формате `example.com`. ### Параметры +Источник данных поддерживает следующие параметры: + |Название |Обязательность | Описание |Возможные значения | |-----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| |SecurityProtocol | Обязательно | Протокол для подключения к Kafka — [в документации Kafka](https://kafka.apache.org/documentation/#adminclientconfigs_security.protocol) | PLAINTEXT, SASL_PLAINTEXT, SASL_SSL | |SaslMechanism | Опционально | Механизм аутентификации, который будет использовать SASL. Обязателен при использовании протокола SASL_PLAINTEXT или SASL_SSL — [в документации Kafka](https://kafka.apache.org/documentation/#security_sasl_mechanism) | PLAIN, SCRAM-SHA-256, SCRAM-SHA-512 | -|User | Обязательно | Имя пользователя для подключения к Kafka | - | -|Pass | Обязательно | Пароль пользователя для подключения к Kafka | - | +|User | Обязательно | Имя пользователя для подключения к Kafka | — | +|Pass | Обязательно | Пароль пользователя для подключения к Kafka | — | ## KubernetesResources -Источник данных типа `KubernetesResources` возвращает список ресурсов Kubernetes. Тип возвращаемых ресурсов задаётся через параметры источника данных. Поддерживаются как встроенные в Kubernetes типы ресурсов, так и любые кастомные ресурсы. +Источник данных типа `KubernetesResources` возвращает список ресурсов Kubernetes. +Тип возвращаемых ресурсов задаётся через параметры источника данных. +Поддерживаются как встроенные в Kubernetes типы ресурсов, так и любые кастомные ресурсы. ### Авторизация @@ -519,7 +556,9 @@ list_path: services ### Спецификация ответа -Спецификация ответа зависит от типа ресурса, который планируется получить. Для получения точной информации необходимо обратиться к документации. Для встроенных в Kubernetes ресурсов доступна [официальная документация](https://kubernetes.io/docs/reference/kubernetes-api/). +Спецификация ответа зависит от типа ресурса, который планируется получить. +Точная информация приведена в документации. +Для встроенных в Kubernetes ресурсов доступна [официальная документация](https://kubernetes.io/docs/reference/kubernetes-api/). При отсутствии возможности обратиться к документации можно получить описание спецификации с помощью команды `d8 k explain`. @@ -550,17 +589,19 @@ FIELDS: ### Конфигурация -- `URL` — URL Kubernetes API в формате `https://api.example.com`. +В параметре `URL` укажите URL Kubernetes API в формате `https://api.example.com`. ### Параметры +Источник данных поддерживает следующие параметры: + |Название |Обязательность | Описание |Возможные значения | |------------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------| -|apiGroup |Опционально | API-группа ресурса. Для ресурсов в core API-группе поле не задаётся |[См. определение требуемых Group и Version](#определение-требуемых-group-и-version)| -|version |Обязательно| Версия API ресурса |[См. определение требуемых Group и Version](#определение-требуемых-group-и-version)| -|isNamespaced|Обязательно| Принадлежность ресурса неймспейсам. Проверить принадлежность можно с помощью команды `d8 k api-resources` |true, false | -|namespace |Опционально | Неймспейс, из которого будут собираться ресурсы. Если не указан, ресурсы будут собираться из всех неймспейсов. Значение параметра учитывается, только если значение `isNamespaced` равно `true` | | -|resource |Обязательно| Название ресурса. Указывается маленькими буквами во множественном числе, как в поле NAME вывода команды `d8 k api-resources` | | +| `apiGroup` |Опционально | API-группа ресурса. Для ресурсов в core API-группе поле не задаётся |[См. определение требуемых Group и Version](#определение-требуемых-group-и-version)| +| `version` |Обязательно| Версия API ресурса |[См. определение требуемых Group и Version](#определение-требуемых-group-и-version)| +| `isNamespaced` |Обязательно| Принадлежность ресурса неймспейсам. Проверить принадлежность можно с помощью команды `d8 k api-resources` | `true`, `false` | +| `namespace` |Опционально | Неймспейс, из которого будут собираться ресурсы. Если не указан, ресурсы будут собираться из всех неймспейсов. Значение параметра учитывается, только если значение `isNamespaced` равно `true` | — | +| `resource` |Обязательно| Название ресурса. Указывается маленькими буквами во множественном числе, как в поле NAME вывода команды `d8 k api-resources` | — | ### Примеры @@ -609,9 +650,12 @@ resource: modulereleases ### Определение требуемых Group и Version -Каждому типу ресурса соответствует своя версия и группа. Полный список API-ресурсов с их группами и версиями — в [документации Kubernetes](https://kubernetes.io/docs/reference/kubernetes-api/). +Каждому типу ресурса соответствует своя версия и группа. +Полный список API-ресурсов с их группами и версиями — в [документации Kubernetes](https://kubernetes.io/docs/reference/kubernetes-api/). -Если неизвестно, какие требуются группы и версии, можно попробовать подставить актуальные значения. Есть несколько вариантов, как их посмотреть, например с помощью утилиты `d8 k`: команда `d8 k explain` показывает `version` и `apiGroup` для ресурса. +Если неизвестно, какие требуются группы и версии, можно попробовать подставить актуальные значения. +Есть несколько вариантов, как их посмотреть, например с помощью утилиты `d8 k`. +Команда `d8 k explain` показывает `version` и `apiGroup` для ресурса. Пример: @@ -643,11 +687,12 @@ FIELDS: ### Спецификация ответа -Портал формирует список доступных репозиториев, затем по каждому репозиторию выполняется GET-запрос к API Nexus: `/service/rest/v1/components`. [Спецификация ответа](https://help.sonatype.com/en/components-api.html). +Портал формирует список доступных репозиториев, затем по каждому репозиторию выполняется GET-запрос к API Nexus: `/service/rest/v1/components`. +[Спецификация ответа](https://help.sonatype.com/en/components-api.html). ### Конфигурация -- `URL` — URL Nexus в формате `https://example.com`. +В параметре `URL` укажите URL Nexus в формате `https://example.com`. ### Параметры @@ -663,11 +708,12 @@ FIELDS: ### Спецификация ответа -Портал выполняет GET-запрос к API Nexus: `/service/rest/v1/repositories`. [Спецификация ответа](https://help.sonatype.com/en/repositories-api.html). +Портал выполняет GET-запрос к API Nexus: `/service/rest/v1/repositories`. +[Спецификация ответа](https://help.sonatype.com/en/repositories-api.html). ### Конфигурация -- `URL` — URL Nexus в формате `https://example.com`. +В параметре `URL` укажите URL Nexus в формате `https://example.com`. ### Параметры @@ -683,12 +729,13 @@ FIELDS: ### Спецификация ответа -Портал выполняет GET-запрос к API Prometheus: `/api/v1/query`. [Спецификация ответа](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries). +Портал выполняет GET-запрос к API Prometheus: `/api/v1/query`. +[Спецификация ответа](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries). ### Конфигурация -- `URL` — URL Prometheus API в формате `https://example.com/api/v1/query`. -- «Query» — запрос [в формате PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/), на основе которого будет сформирован ответ. +В параметре `URL` укажите URL Prometheus API в формате `https://example.com/api/v1/query`. +В параметре «Query» задайте запрос [в формате PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/), на основе которого будет сформирован ответ. ### Параметры @@ -704,11 +751,13 @@ FIELDS: ### Спецификация ответа -Портал выполняет GET-запрос к API SonarQube: `/api/projects/search`. Система собирает все доступные `components` и возвращает их в виде массива. [Спецификация `components`](https://next.sonarqube.com/sonarqube/web_api/api/projects/search). +Портал выполняет GET-запрос к API SonarQube: `/api/projects/search`. +Система собирает все доступные `components` и возвращает их в виде массива. +[Спецификация `components`](https://next.sonarqube.com/sonarqube/web_api/api/projects/search). ### Конфигурация -- `URL` — URL SonarQube в формате `https://example.com`. +В параметре `URL` укажите URL SonarQube в формате `https://example.com`. ### Параметры @@ -716,7 +765,8 @@ FIELDS: ## GenericAPI -Источник данных типа `GenericAPI` позволяет подключаться к любому REST API и получать данные в формате JSON. Поддерживаются различные типы пагинации и настраиваемые параметры запроса. +Источник данных типа `GenericAPI` позволяет подключаться к любому REST API и получать данные в формате JSON. +Поддерживаются различные типы пагинации и настраиваемые параметры запроса. ### Авторизация @@ -725,30 +775,34 @@ GenericAPI поддерживает любые типы аутентификац Bearer Token: ```text -Authorization: Bearer <токен> +Authorization: Bearer ``` Basic Authentication: ```text -Authorization: Basic +Authorization: Basic ``` API Key: ```text -X-API-Key: <ключ> +X-API-Key: ``` ### Конфигурация +При настройке источника данных задайте следующие параметры: + - `URL` — базовый URL API в формате `https://api.example.com`. - `Method` — HTTP-метод (GET, POST, PUT, PATCH, DELETE). - `Query` — дополнительные query-параметры (например, для фильтрации или поиска). ### Параметры -| Название | Обязательность | Описание | Возможные значения | Примеры | По умолчанию | +Источник данных поддерживает следующие параметры: + +| Название | Обязательность | Описание | Возможные значения | Пример | Значение по умолчанию | |---------------------|----------------|-------------------------------------------------------------------------------------------|---------------------------------------------------|---------------------------------------|--------------| | `paginationType` | Опционально | Тип пагинации для обработки больших объёмов данных | `none`, `offset`, `cursor`, `page`, `link_header` | `none` | `none` | | `path` | Опционально | Путь к эндпоинту API, который будет добавлен к базовому URL | Любая строка, начинающаяся с `/` | `/api/v1/users`, `/projects` | `""` | @@ -819,6 +873,8 @@ X-API-Key: <ключ> ### Типы пагинации +Поддерживаются следующие типы пагинации: + - `none` — без пагинации, получает все данные одним запросом. - `offset` — пагинация по смещению и лимиту: @@ -831,8 +887,10 @@ X-API-Key: <ключ> - Пример: `?page=1&size=20`. - `cursor` — пагинация по курсору: - - Использует параметры `cursorParam` и `nextCursorPath`. Параметр `nextCursorPath` обязателен: если он не задан, загружается только первая страница. - - Курсор следующей страницы берётся из поля `nextCursorPath` последнего элемента полученных данных и передаётся в query-параметре `cursorParam`. Загрузка завершается, когда поле с курсором отсутствует, пустое или не является строкой. + - Использует параметры `cursorParam` и `nextCursorPath`. + Параметр `nextCursorPath` обязателен. Если он не задан, загружается только первая страница. + - Курсор следующей страницы берётся из поля `nextCursorPath` последнего элемента полученных данных и передаётся в query-параметре `cursorParam`. + Загрузка завершается, когда поле с курсором отсутствует, пустое или не является строкой. - Пример: `?cursor=eyJpZCI6MTIzfQ==`. - `link_header` — пагинация через заголовок Link: @@ -860,7 +918,7 @@ pageParam: page sizeParam: per_page pageSize: 20 headers: - Authorization: Bearer + Authorization: Bearer ``` DefectDojo API (offset-пагинация): @@ -874,7 +932,7 @@ pageSize: 100 dataPath: results query: "product=42" headers: - Authorization: Token + Authorization: Token ``` GitHub API (link header пагинация): @@ -884,7 +942,7 @@ url: https://api.github.com path: /repos/owner/repo/issues paginationType: link_header headers: - Authorization: Bearer + Authorization: Bearer Accept: application/vnd.github.v3+json ``` @@ -910,5 +968,5 @@ requestBody: '{"query": "example", "filters": {"status": "active"}}' query: "include=metadata&format=json" headers: Content-Type: application/json - Authorization: Bearer + Authorization: Bearer ``` diff --git a/content/documentation/admin/examples/_index.md b/content/documentation/admin/examples/_index.md new file mode 100644 index 00000000..29e5f047 --- /dev/null +++ b/content/documentation/admin/examples/_index.md @@ -0,0 +1,4 @@ +--- +title: Configuration examples +weight: 20 +--- diff --git a/content/documentation/admin/examples/home-custom-catalog.md b/content/documentation/admin/examples/home-custom-catalog.md new file mode 100644 index 00000000..983118e8 --- /dev/null +++ b/content/documentation/admin/examples/home-custom-catalog.md @@ -0,0 +1,107 @@ +--- +title: Home page for a custom catalog model +weight: 31 +description: Configuring DDP Home page mapping rules for an existing catalog model — matching resources, relations, and properties to Home page roles without the "Canonical architecture" dataset. +--- + +This guide describes connecting the Home page to a catalog that already has its own resources for systems, microservices, and environments. +The "Canonical architecture" dataset is not applied in this scenario because the Home page uses the existing resources through mapping rules. + +The example uses a catalog with the following resources: + +- "Products": Systems with the "Domain" (`domain`) and "Status" (`status`) properties. +- "Services": Microservices with the "Language" (`lang`) and "Repository" (`repo_url`) properties. +- "Stands": Environments with the "Stand type" (`stand_type`) and "Domain" (`base_domain`) properties. +- "Workloads": Deployments with the `replicas` and `image` properties. + +The resources are linked by the "Product — service", "Service — workload", and "Workload — stand" relations. + +## Before you begin + +To follow this guide, you need the `create:home-mapping-sets` and `update:home-mapping-sets` permissions, as well as permissions to view resources, resource relations, processes, and widgets so that the selection lists in the form are populated. + +## Matching resources to roles + +Create a table that matches the catalog's resources, relations, and properties to Home page roles. For example: + +| Role | Catalog object | +| --- | --- | +| `system` | "Products" resource | +| `system_domain` | `domain` property of the "Products" resource | +| `system_lifecycle` | `status` property of the "Products" resource | +| `microservice` | "Services" resource | +| `microservice_language` | `lang` property of the "Services" resource | +| `microservice_repository` | `repo_url` property of the "Services" resource | +| `contains_service` | "Product — service" relation | +| `deployment` | "Workloads" resource | +| `deployment_replicas` | `replicas` property of the "Workloads" resource | +| `deployment_image_tag` | `image` property of the "Workloads" resource | +| `has_deployment` | "Service — workload" relation | +| `deployment_in_environment` | "Workload — stand" relation | +| `environment` | "Stands" resource | +| `environment_type` | `stand_type` property of the "Stands" resource | +| `environment_domain` | `base_domain` property of the "Stands" resource | + +Leave roles that have no match in the catalog empty. +Sections whose main role is not mapped show the message "Configure mapping rules or apply the 'Canonical architecture' dataset". +For the full list of roles, see [Mapping rules](../home/mapping/#resource-roles). + +## Creating a mapping set + +Create a mapping set and make it the default set: + +1. Go to "Administration" → "Directories" → "Mapping rules" and click "Create". +1. On the "Main information" tab, fill in the fields: + - "Name": For example, `Home for products`. + - "Identifier": For example, `home-products`. + - Enable "Default for Home". +1. Go to the "Catalog mapping" tab. + +## Filling in the areas + +The areas are filled in one by one. +A role's relations and properties are selected from the resource of its parent role, so map the resources first. + +Fill in the "Systems" area: + +1. In the "Catalog resource" block, select "Products". +1. In the "Properties" block, select `domain` for "System domain" and `status` for "System lifecycle". + +Fill in the "Microservices" area: + +1. In the "Catalog resources" block, click "Add resource" and select "Services". +1. On the resource card, select the `lang` property for "Microservice language" and `repo_url` for "Microservice repository". +1. Select the "Product — service" relation for "Contains microservice" and the "Service — workload" relation for "Has deployment". + +Fill in the "Environments" and "Deployments" areas: + +1. In the "Environments" area, select the "Stands" resource and the `stand_type` property for "Environment type" and `base_domain` for "Environment domain". +1. In the "Deployments" area, select the "Workloads" resource, the "Workload — stand" relation for "Deployment in environment", and the `replicas` and `image` properties. + +Click "Save". + +If you change a role's resource after saving, the form clears the dependent relations and properties. +Check them before saving again. + +## Verifying the result + +Open the Home page and check the sections: + +- "Systems": The "Domains" tree shows products grouped by the `domain` property. + Products without a `domain` value are not shown in the tree. +- "Microservices": The table shows the services, their languages, and their products in the "System" column. +- "Environments": The table shows the stands with their types and domains. +- "Resource consumption": The table shows entities of the "Workloads" resource with the number of replicas. + +If a section shows "Configure mapping rules or apply the 'Canonical architecture' dataset", check that the section's main role is mapped to a resource and that the user has permission to view that resource's entities. + +## Processes + +To run processes from the Home page, add processes to the action slots. +For example, to create stands with the "Create environment" button, follow these steps: + +1. Open the mapping set, the "Environments" area, the "Actions" block. +1. In the "Create environment" slot, click "Add process" and select the stand creation process. +1. Save the set. + +The requirements for Home page processes and the context they receive are described in [Home page processes](../home/processes/). diff --git a/content/documentation/admin/examples/home-custom-catalog.ru.md b/content/documentation/admin/examples/home-custom-catalog.ru.md index ab5c5cb5..003a0dfa 100644 --- a/content/documentation/admin/examples/home-custom-catalog.ru.md +++ b/content/documentation/admin/examples/home-custom-catalog.ru.md @@ -1,10 +1,11 @@ --- -title: Главная для собственной модели каталога +title: Главная страница для собственной модели каталога weight: 31 -description: Настройка правил маппинга главной DDP для существующей модели каталога — сопоставление ресурсов, связей и параметров ролям главной без набора данных «Каноничная архитектура». +description: Настройка правил маппинга главной страницы DDP для существующей модели каталога — сопоставление ресурсов, связей и параметров ролям главной страницы без набора данных «Каноничная архитектура». --- -Инструкция описывает подключение главной к каталогу, в котором уже есть собственные ресурсы систем, микросервисов и окружений. Набор данных «Каноничная архитектура» в этом сценарии не применяется: главная использует существующие ресурсы через правила маппинга. +Инструкция описывает подключение главной страницы к каталогу, в котором уже есть собственные ресурсы систем, микросервисов и окружений. +Набор данных «Каноничная архитектура» в этом сценарии не применяется, поскольку главная страница использует существующие ресурсы через правила маппинга. В примере используется каталог со следующими ресурсами: @@ -21,7 +22,7 @@ description: Настройка правил маппинга главной DDP ## Соответствие ресурсов ролям -Составьте таблицу соответствия ресурсов, связей и параметров каталога ролям главной. Для примера: +Составьте таблицу соответствия ресурсов, связей и параметров каталога ролям главной страницы. Для примера: | Роль | Объект каталога | | --- | --- | @@ -41,7 +42,8 @@ description: Настройка правил маппинга главной DDP | `environment_type` | Параметр `stand_type` ресурса «Стенды» | | `environment_domain` | Параметр `base_domain` ресурса «Стенды» | -Роли, которым нет соответствия в каталоге, оставьте пустыми. Разделы, основная роль которых не сопоставлена, покажут сообщение «Настройте правила маппинга или примените набор данных «Каноничная архитектура»». +Роли, которым нет соответствия в каталоге, оставьте пустыми. +Разделы, основная роль которых не сопоставлена, покажут сообщение «Настройте правила маппинга или примените набор данных «Каноничная архитектура»». Перечень всех ролей — в разделе [«Правила маппинга»](../home/mapping/#роли-ресурсов). ## Создание набора маппинга @@ -57,7 +59,8 @@ description: Настройка правил маппинга главной DDP ## Заполнение областей -Области заполняются по очереди: связи и параметры роли выбираются из ресурса её родительской роли, поэтому сначала сопоставьте ресурсы. +Области заполняются по очереди. +Связи и параметры роли выбираются из ресурса её родительской роли, поэтому сначала сопоставьте ресурсы. Заполните область «Системы»: @@ -77,13 +80,15 @@ description: Настройка правил маппинга главной DDP Нажмите «Сохранить». -Если после сохранения изменить ресурс роли, форма очистит зависимые связи и параметры. Проверьте их перед повторным сохранением. +Если после сохранения изменить ресурс роли, форма очистит зависимые связи и параметры. +Проверьте их перед повторным сохранением. ## Проверка результата -Откройте главную и проверьте разделы: +Откройте главную страницу и проверьте разделы: -- «Системы» — в дереве «Домены» отображаются продукты, сгруппированные по параметру `domain`. Продукты без значения `domain` в дереве не отображаются; +- «Системы» — в дереве «Домены» отображаются продукты, сгруппированные по параметру `domain`. + Продукты без значения `domain` в дереве не отображаются; - «Микросервисы» — в таблице отображаются сервисы, их языки и продукты в колонке «Система»; - «Окружения» — в таблице отображаются стенды с типами и доменами; - «Потребление ресурсов» — в таблице отображаются сущности ресурса «Workloads» с числом реплик. @@ -92,10 +97,11 @@ description: Настройка правил маппинга главной DDP ## Процессы -Чтобы запускать процессы с главной, добавьте процессы в слоты действий. Например, чтобы создавать стенды кнопкой «Создать окружение»: +Чтобы запускать процессы с главной страницы, добавьте процессы в слоты действий. +Например, чтобы создавать стенды кнопкой «Создать окружение»: 1. Откройте набор маппинга, область «Окружения», блок «Действия». 1. В слоте «Создать окружение» нажмите «Добавить процесс» и выберите процесс создания стенда. 1. Сохраните набор. -Требования к процессам главной и контекст, который они получают, описаны в разделе [«Процессы главной»](../home/processes/). +Требования к процессам главной страницы и контекст, который они получают, описаны в разделе [«Процессы главной страницы»](../home/processes/). diff --git a/content/documentation/admin/examples/home-custom-process.md b/content/documentation/admin/examples/home-custom-process.md new file mode 100644 index 00000000..49544e48 --- /dev/null +++ b/content/documentation/admin/examples/home-custom-process.md @@ -0,0 +1,106 @@ +--- +title: Custom resource ordering process +weight: 32 +description: Adding a custom process for ordering and deleting a shared resource to the DDP Home page — parameters from the run context, registering the resource in the catalog, and the order_resource and delete_shared_resource slot categories. +--- + +This guide describes adding ordering of a custom resource type to the Home page — a Redis cache provided by an internal resource ordering system through an HTTP API. +As a result, Redis is shown in the "Resource ordering" section as a separate resource type, is ordered for the selected system and environment, and is deleted from the "Recent resources" list. + +## Before you begin + +To follow this guide, prepare the following: + +- Permissions to create actions and processes, and the `update:home-mapping-sets` permission. +- An [external service](../external-services/) for the resource ordering system API. +- A mapping set in which the `system`, `environment`, and `shared_resource` roles are mapped, for example, the set created by the [initial setup wizard](../home/setup/). + +The example uses property identifiers of the canonical catalog model: the "Shared resources" resource with the `kind`, `provider`, and `environment` properties. +For a custom catalog model, use the properties mapped to the `shared_kind`, `shared_provider`, and `shared_environment` roles. + +## Ordering action + +Create an action that calls the ordering system API and registers the resource in the catalog: + +1. Create an HTTP request action with the ordering system's external service. + Creating an action is described in [Actions](../actions/overview/). +1. Set the request body with the process parameters: + + ```json + { + "name": "{{ .process.instance_name }}", + "namespace": "{{ .process.environment }}", + "owner": "{{ .process.system }}", + "type": "redis" + } + ``` + +1. Configure [entity creation](../actions/overview/#entity-creation) in the "Shared resources" resource after the action completes successfully: + - Name and identifier: `{{ .process.instance_name }}` + - `kind` property: `Redis` + - `provider` property: `Internal` + - `environment` property: `{{ .process.environment }}` +1. Configure [relation creation](../actions/overview/#entity-relation-creation) between the created resource and the run's system, using the relation mapped to the `contains_shared` role. + +The `kind` and `provider` values determine the category in which the Home page looks for the resource deletion process. + +## Ordering process + +The process gets the system and environment from the run context: the system selected in the "Resource ordering" section header and the environment selected in the "Order resource" dialog. + +Create the process: + +1. Create a process named "Order Redis" and add a task with the ordering action to it. + Creating a process is described in [Processes](../processes/overview/). +1. In the "Resource" field, bind the ordering process to the resource mapped to the `system` role ("Systems" in the canonical model). + The Home page runs the order on the selected system's entity. +1. Add the process parameters: + + | Identifier | Default value | Settings | + | --- | --- | --- | + | `environment` | `{{ .context.environment.slug }}` | Required | + | `system` | `{{ .context.system.slug }}` | Required | + | `instance_name` | `{{ .context.system.slug }}-{{ .context.environment.slug }}` | Required, show in simplified form | + +1. Fill in the process description: it is shown on the process card in the "Resource ordering" section. + +The default resource name `-` matches the name of the temporary row that the Home page shows while the order is in progress. +If the user changes the name, the temporary row disappears when the process completes, and the created resource appears in the list after the data is reloaded. + +## Deletion process + +The deletion process runs for a shared resource entity, so the process gets the resource data from the `.entity` root. + +Create the "Delete Redis" process: + +1. Add a task with an action that calls the resource deletion API and deletes the entity from the catalog after it completes successfully. + Entity deletion is configured in the [Deleting entities](../actions/overview/#entity-deletion) section of the action. +1. Bind the deletion process to the "Shared resources" resource or to the resource mapped to the `shared_resource` role in your model. +1. Add the required `instance_name` parameter with the default value `{{ .entity.slug }}` and use it in the request body. + +## Adding processes to the Home page + +Add the processes to the mapping set's action slots: + +1. Go to "Administration" → "Directories" → "Mapping rules" and open the default set. +1. On the "Catalog mapping" tab, expand the "Shared resources" area and find the "Actions" block. +1. In the "Order resource" slot, click "Add category", specify the `Redis` category, and add the "Order Redis" process. +1. In the "Delete shared resource" slot, click "Add category", specify the `Internal Redis` category, and add the "Delete Redis" process. +1. Click "Save". + +The `Internal Redis` category consists of the resource's `provider` and `kind` property values. +The Home page uses it to select the deletion process for Redis resources and does not offer this process for resources of other types. + +## Verifying the result + +Check ordering and deleting the resource: + +1. Open the Home page → "Resource ordering" and select a system. +1. Make sure the "Resource types" indicator contains `Redis` and the process catalog contains the "Order Redis" card. +1. Click "Run" on the card, select an environment, and click "Next". +1. In the "Run process" dialog, check that the `instance_name` parameter is filled in with `-`, and click "Run". +1. Wait until the row labeled "creating" in the "Recent resources" list is replaced by the created resource. +1. Click "Delete" in the resource row and run the deletion process. + +If the `environment` parameter is not filled in, check that the default value template starts with `.context` and that an environment is selected in the "Order resource" dialog. +The context of each Home page scenario is described in [Home page processes](../home/processes/#entity-and-context-by-scenario). diff --git a/content/documentation/admin/examples/home-custom-process.ru.md b/content/documentation/admin/examples/home-custom-process.ru.md index e22c3c3a..ff783a6b 100644 --- a/content/documentation/admin/examples/home-custom-process.ru.md +++ b/content/documentation/admin/examples/home-custom-process.ru.md @@ -1,10 +1,10 @@ --- title: Собственный процесс заказа ресурса weight: 32 -description: Добавление собственного процесса заказа и удаления общего ресурса на главную DDP — параметры из контекста запуска, регистрация ресурса в каталоге, категории слотов order_resource и delete_shared_resource. +description: Добавление собственного процесса заказа и удаления общего ресурса на главную страницу DDP — параметры из контекста запуска, регистрация ресурса в каталоге, категории слотов order_resource и delete_shared_resource. --- -Инструкция описывает добавление на главную заказа собственного типа ресурса — кеша Redis, который выдаёт внутренняя система заказа ресурсов через HTTP API. +Инструкция описывает добавление на главную страницу заказа собственного типа ресурса — кеша Redis, который выдаёт внутренняя система заказа ресурсов через HTTP API. В результате Redis отображается в разделе «Заказ ресурсов» как отдельный тип ресурса, заказывается для выбранных системы и окружения и удаляется из списка «Недавние ресурсы». ## Перед началом работы @@ -15,13 +15,15 @@ description: Добавление собственного процесса за - [внешний сервис](../external-services/) для API системы заказа ресурсов; - набор маппинга, в котором сопоставлены роли `system`, `environment` и `shared_resource`, например набор, созданный [мастером первоначальной настройки](../home/setup/). -В примере используются идентификаторы параметров каноничной модели каталога: ресурс «Общие ресурсы» с параметрами `kind`, `provider` и `environment`. Для собственной модели каталога используйте параметры, сопоставленные ролям `shared_kind`, `shared_provider` и `shared_environment`. +В примере используются идентификаторы параметров каноничной модели каталога: ресурс «Общие ресурсы» с параметрами `kind`, `provider` и `environment`. +Для собственной модели каталога используйте параметры, сопоставленные ролям `shared_kind`, `shared_provider` и `shared_environment`. ## Действие заказа Создайте действие, которое вызывает API системы заказа и регистрирует ресурс в каталоге: -1. Создайте действие типа HTTP-запроса с внешним сервисом системы заказа. Порядок создания действия описан в разделе [«Действия»](../actions/overview/). +1. Создайте действие типа HTTP-запроса с внешним сервисом системы заказа. + Порядок создания действия описан в разделе [«Действия»](../actions/overview/). 1. Задайте тело запроса с параметрами процесса: ```json @@ -40,7 +42,7 @@ description: Добавление собственного процесса за - параметр `environment` — `{{ .process.environment }}`. 1. Настройте [создание связи](../actions/overview/#создание-связей-сущности) созданного ресурса с системой запуска — связью, сопоставленной роли `contains_shared`. -Значения `kind` и `provider` определяют, в какой категории главная ищет процесс удаления ресурса. +Значения `kind` и `provider` определяют, в какой категории главная страница ищет процесс удаления ресурса. ## Процесс заказа @@ -48,8 +50,10 @@ description: Добавление собственного процесса за Создайте процесс: -1. Создайте процесс с названием «Заказать Redis» и добавьте в него задачу с действием заказа. Порядок создания процесса описан в разделе [«Процессы»](../processes/overview/). -1. В поле «Ресурс» привяжите процесс заказа к ресурсу, сопоставленному роли `system` (в каноничной модели — «Системы»). Главная запускает заказ на сущности выбранной системы. +1. Создайте процесс с названием «Заказать Redis» и добавьте в него задачу с действием заказа. + Порядок создания процесса описан в разделе [«Процессы»](../processes/overview/). +1. В поле «Ресурс» привяжите процесс заказа к ресурсу, сопоставленному роли `system` (в каноничной модели — «Системы»). + Главная страница запускает заказ на сущности выбранной системы. 1. Добавьте параметры процесса: | Идентификатор | Значение по умолчанию | Настройки | @@ -60,7 +64,8 @@ description: Добавление собственного процесса за 1. Заполните описание процесса: оно отображается на карточке процесса в разделе «Заказ ресурсов». -Название ресурса по умолчанию `<идентификатор системы>-<идентификатор окружения>` совпадает с названием временной строки, которую главная показывает во время заказа. Если пользователь изменит название, временная строка исчезнет по завершении процесса, а созданный ресурс появится в списке после перезагрузки данных. +Название ресурса по умолчанию `-` совпадает с названием временной строки, которую главная страница показывает во время заказа. +Если пользователь изменит название, временная строка исчезнет по завершении процесса, а созданный ресурс появится в списке после перезагрузки данных. ## Процесс удаления @@ -68,11 +73,12 @@ description: Добавление собственного процесса за Создайте процесс «Удалить Redis»: -1. Добавьте задачу с действием, которое вызывает API удаления ресурса и удаляет сущность из каталога после успешного выполнения. Удаление сущности настраивается в разделе действия [«Удаление сущностей»](../actions/overview/#удаление-сущностей). +1. Добавьте задачу с действием, которое вызывает API удаления ресурса и удаляет сущность из каталога после успешного выполнения. + Удаление сущности настраивается в разделе действия [«Удаление сущностей»](../actions/overview/#удаление-сущностей). 1. Привяжите процесс удаления к ресурсу «Общие ресурсы» или к ресурсу, сопоставленному роли `shared_resource` в своей модели. 1. Добавьте обязательный параметр `instance_name` со значением по умолчанию `{{ .entity.slug }}` и используйте его в теле запроса. -## Добавление процессов на главную +## Добавление процессов на главную страницу Добавьте процессы в слоты действий набора маппинга: @@ -82,17 +88,19 @@ description: Добавление собственного процесса за 1. В слоте «Удалить общий ресурс» нажмите «Добавить категорию», укажите категорию `Internal Redis` и добавьте процесс «Удалить Redis». 1. Нажмите «Сохранить». -Категория `Internal Redis` состоит из значений параметров `provider` и `kind` ресурса. По ней главная выбирает процесс удаления для ресурсов Redis и не предлагает его для ресурсов других типов. +Категория `Internal Redis` состоит из значений параметров `provider` и `kind` ресурса. +По ней главная страница выбирает процесс удаления для ресурсов Redis и не предлагает его для ресурсов других типов. ## Проверка результата Проверьте заказ и удаление ресурса: -1. Откройте главную → «Заказ ресурсов» и выберите систему. +1. Откройте главную страницу → «Заказ ресурсов» и выберите систему. 1. Убедитесь, что в показателе «Типы ресурсов» есть `Redis`, а в каталоге процессов — карточка «Заказать Redis». 1. Нажмите «Запустить» на карточке, выберите окружение и нажмите «Далее». -1. В окне «Запустить процесс» проверьте, что параметр `instance_name` заполнен значением `<система>-<окружение>`, и нажмите «Запустить». +1. В окне «Запустить процесс» проверьте, что параметр `instance_name` заполнен значением `-`, и нажмите «Запустить». 1. Дождитесь, пока в списке «Недавние ресурсы» строка с подписью «создаётся» заменится созданным ресурсом. 1. Нажмите «Удалить» в строке ресурса и запустите процесс удаления. -Если параметр `environment` не заполнился, проверьте, что шаблон значения по умолчанию начинается с `.context`, и что окружение выбрано в окне «Заказать ресурс». Контекст каждого сценария главной описан в разделе [«Процессы главной»](../home/processes/#сущность-и-контекст-по-сценариям). +Если параметр `environment` не заполнился, проверьте, что шаблон значения по умолчанию начинается с `.context`, и что окружение выбрано в окне «Заказать ресурс». +Контекст каждого сценария главной страницы описан в разделе [«Процессы главной страницы»](../home/processes/#сущность-и-контекст-по-сценариям). diff --git a/content/documentation/admin/examples/home-quick-start.md b/content/documentation/admin/examples/home-quick-start.md new file mode 100644 index 00000000..21ad4a17 --- /dev/null +++ b/content/documentation/admin/examples/home-quick-start.md @@ -0,0 +1,135 @@ +--- +title: Quick Home page setup +weight: 30 +description: Step-by-step setup of the DDP Home page on a new installation — the initial setup wizard, enabling the Home page, credentials, the template registry, binding processes to templates, and verifying the result. +--- + +This guide describes setting up the Home page on a new Deckhouse Development Portal (DDP) installation with the canonical catalog model. +As a result, the Home page shows the cluster's environments and deployments, and developers create microservices from templates and deploy them to environments. + +## Before you begin + +To follow this guide, prepare the following: + +- A portal user with the `apply:seeds`, `update:home-mapping-sets`, `edit:template-registries`, and `read:template-packs` permissions, for example, with the "Admin" role preset. +- The Kubernetes API server URL and a service account token with permissions to create namespaces and deployments. +- The Vault or Deckhouse Stronghold URL and an access token. +- The GitLab URL, a GitLab personal access token with permissions to create projects, and a GitLab username. +- A container registry with published template packs. + Publishing a pack is described in the [Creating and publishing a microservice template](template-first-pack/) example. + +## Applying datasets + +Datasets create the catalog model, mapping rules, connections to external systems, datasources, and Home page processes. + +To apply the datasets: + +1. Go to "Administration" → "Directories" → "Datasets" and click "Initial setup". +1. At the "Preset" step, select "Platform setup". + To populate the catalog with examples, select "Platform setup with demo data". +1. At the "Select" step, keep all datasets selected and click "Next". +1. At the "Parameters" step, fill in the required parameters: + - "Kubernetes API URL" in the "Kubernetes" dataset, for example, `https://api.cluster.example.com` + - "Vault URL" in the "Vault" dataset, for example, `https://vault.example.com` + - "GitLab URL" in the "GitLab" dataset, for example, `https://gitlab.example.com` + + The wizard fills in the remaining parameters automatically. +1. At the "Review" step, enable "Confirm Application" and click "Apply". +1. Wait for the "All selected datasets were applied successfully" message. + +If applying a dataset fails, fix the cause and click "Retry from current". + +## Enabling the Home page + +The Home page is disabled after the portal is installed. To enable it, follow these steps: + +1. Go to "Administration" → "Directories" → "Mapping rules". +1. Make sure the table contains the "Home (default)" set with the "Default for Home" switch enabled. +1. Enable the "Show Home" switch. + +The "Home" tab appears in the portal's top bar. + +## Configuring credentials + +Home page processes perform actions in Kubernetes, Vault, and GitLab using the credentials of the user who runs them. + +Fill in the credentials in the user profile: the Kubernetes token, the Vault token, and the GitLab token and username. +The procedure is described in the "Credentials" section of the user guide. + +Every user who runs processes from the Home page fills in the credentials in their own profile. + +## Environments from the cluster + +Kubernetes datasources load into the catalog only namespaces, Deployments, and Ingresses with the `ddp.deckhouse.io/environment` label. +Namespaces created with the "Create environment" button on the Home page get the label automatically. + +To show an existing namespace on the Home page as an environment, add the label to it with a value equal to the namespace name: + +```shell +d8 k label namespace ddp.deckhouse.io/environment= +``` + +Where `` is the namespace name. + +The `d8-*` and `kube-*` namespaces are not loaded. + +The environment appears in the "Environments" section after the namespace datasource from the "Kubernetes: deployments, ingresses, and namespaces" dataset is synchronized. +In the catalog, fill in the environment properties that do not come from the cluster: the type, the domain, and the relation to the cluster. + +## Connecting the template registry + +The template registry connects a container registry that stores template packs. To connect the registry, follow these steps: + +1. Go to "Administration" → "Integrations" → "Templates". +1. On the "Registries" tab, click "Connect registry" and fill in the fields: + - "Name": For example, `company`. + - "Registry": The registry host, for example, `registry.example.com`. + - "Repository prefix": For example, `ddp-templates`. + - "Username" and "Password": The registry credentials. +1. Save the connection. +1. On the "Settings" tab, enable "Enable sync" and save the settings. +1. On the "Sync runs" tab, click "Sync" and wait for the "Success" status. +1. On the "Templates" tab, check that the template versions have the "available" status. + +If the sync fails, the error text is shown in the "Error" column. +The causes of errors are described in the [Template registry](../templates/registry/#sync-errors) section. + +## Binding processes to templates + +Actions on a microservice are performed by processes bound to the microservice template. +The "Microservice template registry" dataset has created processes that work with any template. + +Bind the processes to each template: + +1. Go to "Administration" → "Directories" → "Mapping rules" and open the "Home (default)" set. +1. On the "Catalog mapping" tab, expand the "Microservices" area and find the "Template actions" block. +1. Click "Add template" and select the template in the "Template" field. +1. Select the action processes: + - "Create microservice": "Create microservice from template" + - "Deploy microservice to an environment": "Deploy microservice to an environment" + - "Delete microservice from an environment": "Delete microservice from an environment" + - "Upgrade microservice from template": "Upgrade microservice from template" +1. Repeat steps 3–4 for the remaining templates and click "Save". + +## Verifying the result + +Check that the Home page works by creating a microservice: + +1. Open the "Home" tab → "Create microservice". +1. Select a template, fill in the "Service" and "Parameters" steps, and click "Create microservice". +1. In the "Run process" dialog, click "Run". +1. Wait for the process to complete in the "My activities" panel. + +The Home page is set up if the following conditions are met: + +- A microservice project with the `.ddp/template.lock.yaml` file is created in GitLab. +- The microservice is shown in the "Microservices" section, and the "Template" and "Version" fields are filled in on its card. +- The cluster's environments are shown in the "Environments" section. + +## Next steps + +After the basic setup, do the following if needed: + +- Configure automatic microservice upgrades: [template version release example](template-release-update/). +- Add custom processes to the Home page: the [Custom resource ordering process](home-custom-process/) example. +- Grant developers access to catalog entities: the [Access permissions](../home/overview/#access-permissions) section. diff --git a/content/documentation/admin/examples/home-quick-start.ru.md b/content/documentation/admin/examples/home-quick-start.ru.md index 569274e8..764ce4e9 100644 --- a/content/documentation/admin/examples/home-quick-start.ru.md +++ b/content/documentation/admin/examples/home-quick-start.ru.md @@ -1,10 +1,11 @@ --- -title: Быстрая настройка главной +title: Быстрая настройка главной страницы weight: 30 -description: Пошаговая настройка главной DDP на новой установке — мастер первоначальной настройки, включение главной, учётные данные, реестр шаблонов, привязка процессов к шаблонам и проверка результата. +description: Пошаговая настройка главной страницы DDP на новой установке — мастер первоначальной настройки, включение главной страницы, учётные данные, реестр шаблонов, привязка процессов к шаблонам и проверка результата. --- -Инструкция описывает настройку главной на новой установке Deckhouse Development Portal (DDP, портал) с каноничной моделью каталога. В результате на главной отображаются окружения и развёртывания кластера, а разработчики создают микросервисы из шаблонов и разворачивают их на окружения. +Инструкция описывает настройку главной страницы на новой установке Deckhouse Development Portal (DDP, портал) с каноничной моделью каталога. +В результате на главной странице отображаются окружения и развёртывания кластера, а разработчики создают микросервисы из шаблонов и разворачивают их на окружения. ## Перед началом работы @@ -14,16 +15,18 @@ description: Пошаговая настройка главной DDP на но - URL API-сервера Kubernetes и токен сервисного аккаунта с правами на создание неймспейсов и развёртываний; - URL Vault или Deckhouse Stronghold и токен доступа; - URL GitLab, персональный токен GitLab с правами на создание проектов и имя пользователя GitLab; -- хранилище образов контейнеров с опубликованными пакетами шаблонов. Как опубликовать пакет, описано в примере [«Создание и публикация шаблона микросервиса»](template-first-pack/). +- хранилище образов контейнеров с опубликованными пакетами шаблонов. + Как опубликовать пакет, описано в примере [«Создание и публикация шаблона микросервиса»](template-first-pack/). ## Применение наборов данных -Наборы данных создают модель каталога, правила маппинга, подключения к внешним системам, источники данных и процессы главной. +Наборы данных создают модель каталога, правила маппинга, подключения к внешним системам, источники данных и процессы главной страницы. Чтобы применить наборы данных: 1. Перейдите в раздел «Администрирование» → «Справочники» → «Наборы данных» и нажмите «Первоначальная настройка». -1. На шаге «Пресет» выберите «Настройка платформы». Чтобы наполнить каталог примерами, выберите «Настройка платформы с демоданными». +1. На шаге «Пресет» выберите «Настройка платформы». + Чтобы наполнить каталог примерами, выберите «Настройка платформы с демоданными». 1. На шаге «Выбор» оставьте все наборы отмеченными и нажмите «Далее». 1. На шаге «Параметры» заполните обязательные параметры: - «URL Kubernetes API» в наборе «Kubernetes», например `https://api.cluster.example.com`; @@ -36,9 +39,9 @@ description: Пошаговая настройка главной DDP на но Если применение набора завершилось ошибкой, исправьте причину и нажмите «Повторить с текущего». -## Включение главной +## Включение главной страницы -Главная выключена после установки портала. Включите её: +Главная страница выключена после установки портала. Включите её: 1. Перейдите в раздел «Администрирование» → «Справочники» → «Правила маппинга». 1. Убедитесь, что в таблице есть набор «Главная (по умолчанию)» с включённым переключателем «По умолчанию для главной». @@ -48,17 +51,19 @@ description: Пошаговая настройка главной DDP на но ## Учётные данные -Процессы главной выполняют действия в Kubernetes, Vault и GitLab с учётными данными пользователя, который их запускает. +Процессы главной страницы выполняют действия в Kubernetes, Vault и GitLab с учётными данными пользователя, который их запускает. -Заполните учётные данные в профиле пользователя: токен Kubernetes, токен Vault, токен и имя пользователя GitLab. Порядок описан в разделе [«Учётные данные»](../../user/credentials/). +Заполните учётные данные в профиле пользователя: токен Kubernetes, токен Vault, токен и имя пользователя GitLab. +Порядок описан в разделе [«Учётные данные»](../../user/credentials/). -Каждый пользователь, который запускает процессы с главной, заполняет учётные данные в своём профиле. +Каждый пользователь, который запускает процессы с главной страницы, заполняет учётные данные в своём профиле. ## Окружения из кластера -Источники данных Kubernetes загружают в каталог только неймспейсы, Deployment и Ingress с лейблом `ddp.deckhouse.io/environment`. Неймспейсы, созданные кнопкой «Создать окружение» на главной, получают лейбл автоматически. +Источники данных Kubernetes загружают в каталог только неймспейсы, Deployment и Ingress с лейблом `ddp.deckhouse.io/environment`. +Неймспейсы, созданные кнопкой «Создать окружение» на главной странице, получают лейбл автоматически. -Чтобы существующий неймспейс отображался на главной как окружение, добавьте ему лейбл со значением, равным имени неймспейса: +Чтобы существующий неймспейс отображался на главной странице как окружение, добавьте ему лейбл со значением, равным имени неймспейса: ```shell d8 k label namespace ddp.deckhouse.io/environment= @@ -68,7 +73,8 @@ d8 k label namespace ddp.deckhouse.io/environment= Неймспейсы `d8-*` и `kube-*` не загружаются. -Окружение появится в разделе «Окружения» после синхронизации источника данных неймспейсов из набора «Kubernetes: deployments, ingresses и namespaces». Заполните в каталоге параметры окружения, которые не приходят из кластера: тип, домен и связь с кластером. +Окружение появится в разделе «Окружения» после синхронизации источника данных неймспейсов из набора «Kubernetes: deployments, ingresses и namespaces». +Заполните в каталоге параметры окружения, которые не приходят из кластера: тип, домен и связь с кластером. ## Подключение реестра шаблонов @@ -83,13 +89,15 @@ d8 k label namespace ddp.deckhouse.io/environment= 1. Сохраните подключение. 1. На вкладке «Настройки» включите «Включить синхронизацию» и сохраните настройки. 1. На вкладке «Запуски синхронизации» нажмите «Синхронизировать» и дождитесь статуса «Успех». -1. На вкладке «Шаблоны» проверьте, что у версий шаблонов статус «доступна». +1. На вкладке «Шаблоны» проверьте, что у версий шаблонов статус «Доступна». -Если синхронизация завершилась ошибкой, текст ошибки отображается в колонке «Ошибка». Причины ошибок описаны в разделе [«Реестр шаблонов»](../templates/registry/#ошибки-синхронизации). +Если синхронизация завершилась ошибкой, текст ошибки отображается в колонке «Ошибка». +Причины ошибок описаны в разделе [«Реестр шаблонов»](../templates/registry/#ошибки-синхронизации). ## Привязка процессов к шаблонам -Действия над микросервисом выполняют процессы, привязанные к шаблону микросервиса. Набор данных «Реестр шаблонов микросервисов» создал процессы, которые подходят для любого шаблона. +Действия над микросервисом выполняют процессы, привязанные к шаблону микросервиса. +Набор данных «Реестр шаблонов микросервисов» создал процессы, которые подходят для любого шаблона. Привяжите процессы к каждому шаблону: @@ -105,14 +113,14 @@ d8 k label namespace ddp.deckhouse.io/environment= ## Проверка результата -Проверьте работу главной на создании микросервиса: +Проверьте работу главной страницы на создании микросервиса: 1. Откройте вкладку «Главная» → «Создать микросервис». 1. Выберите шаблон, заполните шаги «Сервис» и «Параметры» и нажмите «Создать микросервис». 1. В окне «Запустить процесс» нажмите «Запустить». 1. Дождитесь завершения процесса в панели «Мои активности». -Главная настроена, если выполнены условия: +Главная страница настроена, если выполнены условия: - в GitLab создан проект микросервиса с файлом `.ddp/template.lock.yaml`; - микросервис отображается в разделе «Микросервисы», а в его карточке заполнены поля «Шаблон» и «Версия»; @@ -122,6 +130,6 @@ d8 k label namespace ddp.deckhouse.io/environment= После базовой настройки выполните при необходимости: -- настройку автоматического обновления микросервисов — пример [«Выпуск новой версии шаблона и обновление микросервисов»](template-release-update/); -- добавление собственных процессов на главную — пример [«Собственный процесс заказа ресурса»](home-custom-process/); +- настройку автоматического обновления микросервисов — [пример выпуска версии шаблона](template-release-update/); +- добавление собственных процессов на главную страницу — пример [«Собственный процесс заказа ресурса»](home-custom-process/); - выдачу разработчикам доступа к сущностям каталога — раздел [«Права доступа»](../home/overview/#права-доступа). diff --git a/content/documentation/admin/examples/home-widget-slot.md b/content/documentation/admin/examples/home-widget-slot.md new file mode 100644 index 00000000..afe08ebc --- /dev/null +++ b/content/documentation/admin/examples/home-widget-slot.md @@ -0,0 +1,67 @@ +--- +title: Widget on a microservice tab +weight: 33 +description: Showing a GitLab widget on the "Pipelines" and "MRs" tabs of a microservice card on the DDP Home page — widget configuration with the microservice context and filling in widget slots in mapping rules. +--- + +This guide describes showing the "GitLab. Pipelines" widget on the "Pipelines" tab of a microservice card. +The widget shows the pipelines of the repository of the microservice whose card is open. + +A single widget serves all microservices because the widget gets the GitLab project ID from the card context, not from its own configuration. + +## Before you begin + +To follow this guide, prepare the following: + +- Permissions to create widgets and the `update:home-mapping-sets` permission. +- A GitLab external service. +- A property with the numeric GitLab project ID on microservice entities, mapped to the `microservice_gitlab_project_id` role. + In the canonical catalog model, this is the `gitlab_repository_id` property, which is filled in by the process that creates a microservice from a template or by the "GitLab: repository activity" datasource. + +The "GitLab: widgets" dataset creates ready-made widgets for both tabs. +This guide shows how to configure the widget yourself, for example, for a different version control system or with different properties. + +## Creating a widget + +Create a widget with the project ID from the context: + +1. Create a widget of the ["GitLab. Pipelines"](../widgets/gitlab/pipelines/) type with the GitLab external service. +1. In the "Project ID" field, specify `{{ .context.repository.id }}`. +1. Save the widget. + +On a microservice card tab, the Home page passes the following values to the widget: + +| Path | Value | +| --- | --- | +| `.context.microservice.uuid` | UUID of the microservice entity | +| `.context.microservice.slug` | Microservice identifier | +| `.context.microservice.name` | Microservice name | +| `.context.repository.id` | Value of the `microservice_gitlab_project_id` role | +| `.context.repository.url` | Value of the `microservice_repository` role | + +The context is passed only on microservice card tabs. +For dashboards, create a separate widget with a specific project ID. + +## Filling in the widget slot + +Add the widget to the "Pipelines" tab slot: + +1. Go to "Administration" → "Directories" → "Mapping rules" and open the default set. +1. On the "Catalog mapping" tab, expand the "Microservices" area and find the "Widgets" block. +1. In the "'Pipelines' tab widget" field, select the created widget. +1. Click "Save". + +The "MRs" tab is filled in with the "'MRs' tab widget" field, for example, with the ["GitLab. Merge requests"](../widgets/gitlab/merge-requests/) widget with the same "Project ID" field value. + +## Verifying the result + +Check the widget on the Home page: + +1. Open the Home page → "Microservices" and select a microservice in the table. +1. Open the "Pipelines" tab on the microservice card. + +The tab shows the pipelines of the selected microservice's repository. +When you select another microservice, the widget shows the pipelines of its repository. + +If the tab shows "This section is not available yet", the widget slot is not filled in. +If the widget shows no data, check that the microservice has the property mapped to the `microservice_gitlab_project_id` role filled in. diff --git a/content/documentation/admin/examples/home-widget-slot.ru.md b/content/documentation/admin/examples/home-widget-slot.ru.md index cd359976..10303943 100644 --- a/content/documentation/admin/examples/home-widget-slot.ru.md +++ b/content/documentation/admin/examples/home-widget-slot.ru.md @@ -1,12 +1,13 @@ --- title: Виджет на вкладке микросервиса weight: 33 -description: Вывод виджета GitLab на вкладках «Пайплайны» и «MRs» карточки микросервиса на главной DDP — конфигурация виджета с контекстом микросервиса и заполнение слотов виджетов в правилах маппинга. +description: Вывод виджета GitLab на вкладках «Пайплайны» и «MRs» карточки микросервиса на главной странице DDP — конфигурация виджета с контекстом микросервиса и заполнение слотов виджетов в правилах маппинга. --- -Инструкция описывает вывод виджета «GitLab. Пайплайны» на вкладке «Пайплайны» карточки микросервиса. Виджет показывает пайплайны репозитория того микросервиса, карточка которого открыта. +Инструкция описывает вывод виджета «GitLab. Пайплайны» на вкладке «Пайплайны» карточки микросервиса. +Виджет показывает пайплайны репозитория того микросервиса, карточка которого открыта. -Один виджет обслуживает все микросервисы: идентификатор проекта GitLab виджет получает из контекста карточки, а не из собственной конфигурации. +Один виджет обслуживает все микросервисы, поскольку идентификатор проекта GitLab виджет получает из контекста карточки, а не из собственной конфигурации. ## Перед началом работы @@ -14,9 +15,11 @@ description: Вывод виджета GitLab на вкладках «Пайпл - разрешения на создание виджетов и разрешение `update:home-mapping-sets`; - внешний сервис GitLab; -- у сущностей микросервисов — параметр с числовым ID проекта GitLab, сопоставленный роли `microservice_gitlab_project_id`. В каноничной модели каталога это параметр `gitlab_repository_id`, который заполняет процесс создания микросервиса из шаблона или источник данных «GitLab: активность репозиториев». +- у сущностей микросервисов — параметр с числовым ID проекта GitLab, сопоставленный роли `microservice_gitlab_project_id`. + В каноничной модели каталога это параметр `gitlab_repository_id`, который заполняет процесс создания микросервиса из шаблона или источник данных «GitLab: активность репозиториев». -Набор данных «GitLab: виджеты» создаёт готовые виджеты для обеих вкладок. Инструкция показывает, как настроить виджет самостоятельно, например для другой системы контроля версий или с другими параметрами. +Набор данных «GitLab: виджеты» создаёт готовые виджеты для обеих вкладок. +Инструкция показывает, как настроить виджет самостоятельно, например для другой системы контроля версий или с другими параметрами. ## Создание виджета @@ -26,7 +29,7 @@ description: Вывод виджета GitLab на вкладках «Пайпл 1. В поле «ID проекта» укажите `{{ .context.repository.id }}`. 1. Сохраните виджет. -Главная передаёт виджету на вкладке карточки микросервиса следующие значения: +Главная страница передаёт виджету на вкладке карточки микросервиса следующие значения: | Путь | Значение | | --- | --- | @@ -36,7 +39,8 @@ description: Вывод виджета GitLab на вкладках «Пайпл | `.context.repository.id` | Значение роли `microservice_gitlab_project_id` | | `.context.repository.url` | Значение роли `microservice_repository` | -Контекст передаётся только на вкладках карточки микросервиса. Для дашбордов создайте отдельный виджет с конкретным ID проекта. +Контекст передаётся только на вкладках карточки микросервиса. +Для дашбордов создайте отдельный виджет с конкретным ID проекта. ## Заполнение слота виджета @@ -51,11 +55,13 @@ description: Вывод виджета GitLab на вкладках «Пайпл ## Проверка результата -Проверьте виджет на главной: +Проверьте виджет на главной странице: -1. Откройте главную → «Микросервисы» и выберите микросервис в таблице. +1. Откройте главную страницу → «Микросервисы» и выберите микросервис в таблице. 1. Откройте вкладку «Пайплайны» в карточке микросервиса. -На вкладке отображаются пайплайны репозитория выбранного микросервиса. При выборе другого микросервиса виджет показывает пайплайны его репозитория. +На вкладке отображаются пайплайны репозитория выбранного микросервиса. +При выборе другого микросервиса виджет показывает пайплайны его репозитория. -Если на вкладке отображается «Раздел пока недоступен», слот виджета не заполнен. Если виджет не показывает данные, проверьте, что у микросервиса заполнен параметр, сопоставленный роли `microservice_gitlab_project_id`. +Если на вкладке отображается «Раздел пока недоступен», слот виджета не заполнен. +Если виджет не показывает данные, проверьте, что у микросервиса заполнен параметр, сопоставленный роли `microservice_gitlab_project_id`. diff --git a/content/documentation/admin/examples/microservice-lifecycle.md b/content/documentation/admin/examples/microservice-lifecycle.md new file mode 100644 index 00000000..02ac406d --- /dev/null +++ b/content/documentation/admin/examples/microservice-lifecycle.md @@ -0,0 +1,96 @@ +--- +title: Microservice from creation to deployment +weight: 42 +description: End-to-end developer workflow on the DDP Home page — creating a microservice from a template, creating an environment, deploying, ordering and connecting a database, and upgrading from a template. +--- + +This guide describes the path of a new microservice on the Home page: creating it from a template, deploying it to a temporary environment, ordering a PostgreSQL database, and connecting the database to the microservice. +A developer performs the scenario on the Home page without using the catalog or administration. + +## Before you begin + +To follow this guide, you need the following: + +- A Home page configured by the portal administrator, for example, following the [Quick Home page setup](home-quick-start/) guide. +- Access to catalog entities and permission to run processes. +- Kubernetes, Vault, and GitLab credentials in the user profile. + +## Creating a microservice + +Create a microservice from a template: + +1. Open the Home page → "Create microservice". +1. At the "Template" step, select a template, for example, "Go service", and click "Next". +1. At the "Service" step, fill in the fields: + - "Microservice name": `Billing API`. + - "Microservice identifier": Filled in as `billing-api`. + - "System": The system that the microservice will belong to. + - "Version control namespace": The GitLab group for the repository. +1. Click "Next", fill in the template parameters, and click "Create microservice". +1. In the "Run process" dialog, click "Run". + +The creation progress is shown in the "Processes running" bar. +After the process completes, the microservice appears in the "Microservices" section, and the `billing-api` repository appears in GitLab. + +## Creating an environment + +Create a temporary environment to test the microservice: + +1. Open the Home page → "Environments" and click "Create environment". +1. Fill in "Identifier", for example, `billing-review`, and select "7 days" for "TTL". +1. Click "Run". + +While the environment is being created, the table shows the `billing-review` row labeled "creating". +The environment appears in the table after the catalog is synchronized with the cluster. + +To give the microservice an address in the environment, set the environment domain. +To do this, open the environment card, click the pencil icon in the "Domain" row, and enter a domain, for example, `review.example.com`. + +## Deploying the microservice + +Deploy the microservice to the created environment: + +1. Open the Home page → "System deployment", select the microservice's system and the `billing-review` environment. +1. Click "Deploy microservice". +1. Select the `Billing API` microservice and the `billing-review` environment, and click "Next". +1. In the "Run process" dialog, click "Run". + +The "Deployments" column shows the `Billing API` card labeled "creating", and after the process completes, a deployment card with replica and resource properties. +If the environment domain is set, the process from the dataset creates an Ingress with the `billing-api.review.example.com` host, which is shown in the "Infrastructure" column. + +## Ordering a database + +Order a PostgreSQL database for the microservice: + +1. In the "System deployment" section, click "Order resource" under the "Data resources" column. +1. In the "Order resource" dialog, select the PostgreSQL ordering process in "Service". The `billing-review` environment is already selected. +1. Click "Next", and in the "Run process" dialog, click "Run". + +A resource card appears in the "Data resources" column. The database connection details are written to Vault. + +## Connecting the database + +Connect the database to the microservice deployment: + +1. Click the dot on the left side of the database card and drag a line to the `Billing API` deployment card. +1. In the "Run process" dialog, click "Run". + +After the process completes, the diagram shows the connection line, and the database secrets are delivered to the application. + +## Upgrading from a template + +When the template author releases a new version, the "Version {version} is available" block appears on the microservice card. + +Upgrade the microservice: + +1. Open the Home page → "Microservices" and select `Billing API`. +1. Click "Upgrade", and in the "Run process" dialog, click "Run". +1. Open the `Upgrade to ` merge request in GitLab, review the changes, and merge it. + +## Deleting + +Deckhouse Development Portal (DDP) writes the TTL to the namespace's `ddp.deckhouse.io/deletion-ttl` label. +The environment is deleted when the TTL expires if namespace cleanup by this label is configured in the cluster. +To delete the environment immediately, open its card in the "Environments" section and click "Delete environment" in the "Danger zone" block. + +Deleting an environment deletes all deployments in it. diff --git a/content/documentation/admin/examples/microservice-lifecycle.ru.md b/content/documentation/admin/examples/microservice-lifecycle.ru.md index e6ef3011..d051c84f 100644 --- a/content/documentation/admin/examples/microservice-lifecycle.ru.md +++ b/content/documentation/admin/examples/microservice-lifecycle.ru.md @@ -1,17 +1,17 @@ --- title: Микросервис от создания до развёртывания weight: 42 -description: Сквозной сценарий работы разработчика на главной DDP — создание микросервиса из шаблона, создание окружения, развёртывание, заказ и подключение базы данных, обновление из шаблона. +description: Сквозной сценарий работы разработчика на главной странице DDP — создание микросервиса из шаблона, создание окружения, развёртывание, заказ и подключение базы данных, обновление из шаблона. --- -Инструкция описывает путь нового микросервиса на главной: создание из шаблона, развёртывание на временное окружение, заказ базы данных PostgreSQL и её подключение к микросервису. -Сценарий выполняется разработчиком на главной без обращения к каталогу и администрированию. +Инструкция описывает путь нового микросервиса на главной странице: создание из шаблона, развёртывание на временное окружение, заказ базы данных PostgreSQL и её подключение к микросервису. +Сценарий выполняется разработчиком на главной странице без обращения к каталогу и администрированию. ## Перед началом работы Для выполнения инструкции требуется: -- главная, настроенная администратором портала, например по инструкции [«Быстрая настройка главной»](home-quick-start/); +- главная страница, настроенная администратором портала, например по инструкции [«Быстрая настройка главной страницы»](home-quick-start/); - доступ к сущностям каталога и право на запуск процессов; - учётные данные Kubernetes, Vault и GitLab в [профиле пользователя](../../user/credentials/). @@ -19,7 +19,7 @@ description: Сквозной сценарий работы разработчи Создайте микросервис из шаблона: -1. Откройте главную → «Создать микросервис». +1. Откройте главную страницу → «Создать микросервис». 1. На шаге «Шаблон» выберите шаблон, например «Go service», и нажмите «Далее». 1. На шаге «Сервис» заполните поля: - «Название микросервиса» — `Billing API`; @@ -29,25 +29,28 @@ description: Сквозной сценарий работы разработчи 1. Нажмите «Далее», заполните параметры шаблона и нажмите «Создать микросервис». 1. В окне «Запустить процесс» нажмите «Запустить». -Ход создания отображается в строке «Выполняются процессы». После завершения процесса микросервис появится в разделе «Микросервисы», а в GitLab — репозиторий `billing-api`. +Ход создания отображается в строке «Выполняются процессы». +После завершения процесса микросервис появится в разделе «Микросервисы», а в GitLab — репозиторий `billing-api`. ## Создание окружения Создайте временное окружение для проверки микросервиса: -1. Откройте главную → «Окружения» и нажмите «Создать окружение». +1. Откройте главную страницу → «Окружения» и нажмите «Создать окружение». 1. Заполните «Идентификатор», например `billing-review`, и выберите «TTL» — «7 дней». 1. Нажмите «Запустить». -Пока окружение создаётся, в таблице отображается строка `billing-review` с подписью «создаётся». Окружение появится в таблице после синхронизации каталога с кластером. +Пока окружение создаётся, в таблице отображается строка `billing-review` с подписью «создаётся». +Окружение появится в таблице после синхронизации каталога с кластером. -Чтобы у микросервиса был адрес на окружении, задайте домен окружения: откройте карточку окружения, нажмите значок карандаша в строке «Домен» и введите домен, например `review.example.com`. +Чтобы у микросервиса был адрес на окружении, задайте домен окружения. +Для этого откройте карточку окружения, нажмите значок карандаша в строке «Домен» и введите домен, например `review.example.com`. ## Развёртывание микросервиса Разверните микросервис на созданное окружение: -1. Откройте главную → «Развертывание систем», выберите систему микросервиса и окружение `billing-review`. +1. Откройте главную страницу → «Развертывание систем», выберите систему микросервиса и окружение `billing-review`. 1. Нажмите «Развернуть микросервис». 1. Выберите микросервис `Billing API` и окружение `billing-review`, нажмите «Далее». 1. В окне «Запустить процесс» нажмите «Запустить». @@ -80,12 +83,14 @@ description: Сквозной сценарий работы разработчи Обновите микросервис: -1. Откройте главную → «Микросервисы» и выберите `Billing API`. +1. Откройте главную страницу → «Микросервисы» и выберите `Billing API`. 1. Нажмите «Обновить» и в окне «Запустить процесс» нажмите «Запустить». -1. Откройте запрос на слияние `Upgrade <шаблон> to <версия>` в GitLab, проверьте изменения и примите его. +1. Откройте запрос на слияние (Merge Request) `Upgrade to ` в GitLab, проверьте изменения и примите его. ## Удаление -DDP записывает TTL в лейбл `ddp.deckhouse.io/deletion-ttl` неймспейса. Окружение удаляется по истечении TTL, если в кластере настроена очистка неймспейсов по этому лейблу. Чтобы удалить окружение сразу, откройте его карточку в разделе «Окружения» и нажмите «Удалить окружение» в блоке «Опасная зона». +Deckhouse Development Portal (DDP) записывает TTL в лейбл `ddp.deckhouse.io/deletion-ttl` неймспейса. +Окружение удаляется по истечении TTL, если в кластере настроена очистка неймспейсов по этому лейблу. +Чтобы удалить окружение сразу, откройте его карточку в разделе «Окружения» и нажмите «Удалить окружение» в блоке «Опасная зона». Удаление окружения удаляет все развёртывания в нём. diff --git a/content/documentation/admin/examples/overview.md b/content/documentation/admin/examples/overview.md new file mode 100644 index 00000000..27090e80 --- /dev/null +++ b/content/documentation/admin/examples/overview.md @@ -0,0 +1,34 @@ +--- +title: Overview +description: Step-by-step examples of configuring Deckhouse Development Portal — the Home page, microservice templates, and automatic service upgrades. +weight: 10 +--- + +This section contains step-by-step examples of configuring Deckhouse Development Portal (DDP) for common administrator tasks. +Each example covers the full scenario, from preparation to verifying the result. + +## Configuring the Home page + +These examples show how to prepare the Home page to work with the catalog and processes: + +| Example | Description | +| --- | --- | +| [Quick Home page setup](home-quick-start/) | The initial setup wizard, credentials, template registry, and process binding on a new installation | +| [Home page for a custom catalog model](home-custom-catalog/) | Mapping existing resources, relations, and properties to Home page roles without the "Canonical architecture" dataset | +| [Custom resource ordering process](home-custom-process/) | Processes for ordering and deleting a shared resource, parameters from the run context, and slot categories | +| [Widget on a microservice tab](home-widget-slot/) | Displaying a GitLab widget on microservice card tabs using widget slots | + +## Microservice templates + +These examples describe the lifecycle of a template and the microservices created from it: + +| Example | Description | +| --- | --- | +| [Creating and publishing a microservice template](template-first-pack/) | A template pack for a Go service, validation with the `ddp-template` utility, publishing, and creating a microservice | +| [Releasing a new template version](template-release-update/) | Releasing a new version, manual and automatic microservice upgrades, and resolving conflicts | +| [Microservice from creation to deployment](microservice-lifecycle/) | An end-to-end developer scenario: creation, environment, deployment, database, and upgrade | + +## Automation based on actions and processes + +The [Automatic service upgrades](service-autoupdates/) example shows how to configure resources, a datasource, actions, a process, and an automation without microservice templates. +As a result, when a new version of a template repository is released, merge requests are created in the services. diff --git a/content/documentation/admin/examples/overview.ru.md b/content/documentation/admin/examples/overview.ru.md new file mode 100644 index 00000000..56ed755b --- /dev/null +++ b/content/documentation/admin/examples/overview.ru.md @@ -0,0 +1,34 @@ +--- +title: Обзор +description: Пошаговые примеры настройки Deckhouse Development Portal — главная страница, шаблоны микросервисов и автоматическое обновление сервисов. +weight: 10 +--- + +Раздел содержит пошаговые примеры настройки Deckhouse Development Portal (DDP) для типовых задач администратора. +Каждый пример описывает сценарий целиком: от подготовки до проверки результата. + +## Настройка главной страницы + +Примеры показывают, как подготовить главную страницу к работе с каталогом и процессами: + +| Пример | Содержание | +| --- | --- | +| [Быстрая настройка главной страницы](home-quick-start/) | Мастер первоначальной настройки, учётные данные, реестр шаблонов и привязка процессов на новой установке | +| [Главная страница для собственной модели каталога](home-custom-catalog/) | Сопоставление существующих ресурсов, связей и параметров ролям главной страницы без набора данных «Каноничная архитектура» | +| [Собственный процесс заказа ресурса](home-custom-process/) | Процессы заказа и удаления общего ресурса, параметры из контекста запуска и категории слотов | +| [Виджет на вкладке микросервиса](home-widget-slot/) | Вывод виджета GitLab на вкладках карточки микросервиса через слоты виджетов | + +## Шаблоны микросервисов + +Примеры описывают жизненный цикл шаблона и созданных из него микросервисов: + +| Пример | Содержание | +| --- | --- | +| [Создание и публикация шаблона микросервиса](template-first-pack/) | Пакет шаблона Go-сервиса, проверка утилитой `ddp-template`, публикация и создание микросервиса | +| [Выпуск новой версии шаблона](template-release-update/) | Выпуск новой версии, ручное и автоматическое обновление микросервисов и разбор конфликтов | +| [Микросервис от создания до развёртывания](microservice-lifecycle/) | Сквозной сценарий разработчика: создание, окружение, развёртывание, база данных и обновление | + +## Автоматизация на основе действий и процессов + +Пример [«Автоматическое обновление сервисов»](service-autoupdates/) показывает, как без шаблонов микросервисов настроить ресурсы, источник данных, действия, процесс и автоматизацию. +В результате при выпуске новой версии шаблонного репозитория в сервисах создаются запросы на слияние (Merge Request). diff --git a/content/documentation/admin/examples/service-autoupdates.md b/content/documentation/admin/examples/service-autoupdates.md new file mode 100644 index 00000000..bbb8a228 --- /dev/null +++ b/content/documentation/admin/examples/service-autoupdates.md @@ -0,0 +1,805 @@ +--- +title: Automatic service upgrades +weight: 50 +description: Configuring DDP resources, a relation, a datasource, actions, a process, and an automation that create merge requests in services when a new template version is released. +--- + +This guide describes how to configure an automatic mechanism that upgrades all services created from a template when a new version of that template is released. +A new template version is detected by a new tag added to the template's Git repository. + +{{< alert level="info" >}} +The names of resources, properties, actions, and processes in this guide are examples and may differ depending on your settings. +{{< /alert >}} + +## System components and their purpose + +Automatic service upgrades use the following components of Deckhouse Development Portal (DDP): + +- Resources: Elements of the DDP catalog data model that define how information is stored. + Each resource can contain properties for storing entity metadata, as well as relations to other resources for displaying dependencies. + + This guide uses two resources: + + - "Templates": Stores information about template repositories (repository URL and ID, latest version tag). + - "Services": Stores information about created services (repository URL and ID, templating variables, default branch). + +- Relation: Defines a dependency between resources and makes it possible to automatically find all services related to a specific template. + +- [Datasource](../datasources/overview/): A DDP mechanism that synchronizes information from external infrastructure systems (for example, GitLab) to the portal catalog. + Datasources periodically poll external systems, retrieve up-to-date information, and update the corresponding entities in the catalog. + In this guide, the datasource: + + - Synchronizes information about template repositories from GitLab. + - Updates the list of tags for each template. + - Automatically updates the "Latest tag" property in entities of the "Templates" resource. + +- Action: A DDP mechanism that lets portal users interact with external infrastructure services via an API. + Actions can create projects in GitLab, create secrets in secret management systems, deploy applications, and perform other operations. + + This guide uses three actions: + + - Creating a new project in GitLab to host the service. + - Cloning code from the template repository to the new service repository, applying templating variables. + - Creating a merge request in the service repository with changes from the new template version. + +- Process: An automation mechanism for complex business processes that lets you build visual execution diagrams for actions, with support for sequential or parallel execution. + Processes combine multiple actions into a single execution chain. + In this guide, the process: + + - Runs the creation of a project in GitLab and then the creation of a repository from the template, in sequence. + - Provides the user interface for creating a service from a template. + +- Automation: A mechanism by which the portal responds to changes in entity specifications. + Automations subscribe to update events of resource entities based on specific rules (triggers) and run actions, processes, or datasource synchronization. + In this guide, the automation: + + - Tracks changes to the "Latest tag" property in entities of the "Templates" resource. + - When a new tag is detected, runs the "Upgrade service from template" action for all related services. + - Creates a merge request in each service repository with changes from the new template version. + +Automatic upgrade diagram: + +![Automatic update diagram](../images/service-autoupdates/workflow.png) + +How it works: + +1. The "Datasource" periodically synchronizes information about templates from GitLab and updates the property with the `repository_last_tag` identifier in entities of the "Templates" resource. +1. The "Automation" tracks changes to the property with the `repository_last_tag` identifier using triggers. +1. When a new tag is detected, the automation runs the "Upgrade service from template" action for all services related to the updated template. +1. The "Action" creates a merge request in each service repository that includes changes from the new template version. + +As a result, when a new tag is added to a template repository, all related services automatically receive an upgrade proposal as a merge request. + +## Configuring components + +The following sections describe the configuration of each system component. +If you use different names and property identifiers in your resources, use them in all actions, automations, and datasources that reference these properties. + +This guide covers: + +1. Required resources in DDP and their properties. +1. Required relations between resources. +1. Required [datasources](../datasources/overview/) for retrieving information about new template versions. +1. Required [actions](../actions/overview/) for creating a service from a template. +1. A required process for running a chain of [actions](../actions/overview/) in sequence. +1. A required [automation](../automations) that implements the following functionality: + - DDP automatically checks for a new template version. + - DDP automatically creates a merge request with changes from the new version in services created from the template. + +## Creating resources and a relation + +"Resources" are elements of the DDP catalog data model that define how information is stored. +Each resource can contain properties for storing entity metadata, as well as relations to other resources for displaying dependencies. + +{{< alert level="warning" >}} +Make sure the property identifiers are specified correctly in all actions, automations, and datasources that reference these properties. +{{< /alert >}} + +### "Templates" resource + +You must have a resource for storing information about template repositories. +In this guide, it is named "Templates", but you can use any name you prefer. +If the resource does not exist yet, [create it](#creating-a-resource). + +The resource must contain the following properties for storing data about template repositories: + +- The "URL" property of the URL type: Stores the URL of the template repository in GitLab. + This parameter is required for actions that work with the template repository. + +- The "Repository ID" property of the Number type: Stores the internal repository ID in GitLab. + It is used by actions that require a GitLab project ID. + +- The "Latest tag" property of the String type: Contains the name of the latest tag (version) of the template. + The automation uses this parameter to track new template versions. + Each time the datasource updates this property, the automation checks for a change and starts upgrading the related services. + +If the properties are missing, open the resource for editing and add them on the resource's "Properties" tab by clicking "Add property". + +### "Services" resource + +You must have a second resource for storing information about created services. +In this guide, it is named "Services", but you can choose any name you prefer. +If the resource does not exist yet, [create it](#creating-a-resource). + +The resource must contain the following properties for storing metadata about created services: + +- The "URL" property of the URL type: A link to the service repository in GitLab. + Actions use it to work with the service repository. + +- The "Repository ID" property of the Number type: The internal repository ID in GitLab. + It is required for actions that require a GitLab project ID. + +- The "Variables used for templating" property of the YAML type: Contains the variables that were applied when cloning code from the template to the service. + These variables are required when upgrading the service from the template because they must be applied again to correctly render new changes from the template. + +- The "Default branch" property of the String type: The name of the repository's main branch (for example, `main` or `master`). + The service upgrade action uses it to determine the target branch of the merge request. + +If the properties are missing, open the resource for editing and add them on the resource's "Properties" tab by clicking "Add property". + +### Creating a resource + +To create resources, go to the "Catalog" section. +Create a new resource. +To do this, click "Create resource" at the bottom of the catalog sidebar. + +A window for creating a new resource opens, with several tabs. + +#### "Main information" tab + +Fill in the following fields on the "Main information" tab: + +- "Name": [Specify the resource name]. + +- "Owner": [Specify the owner]. + +- "Owning team": [Specify the owner team]. + +#### "Properties" tab + +Go to the "Properties" tab and add the required resource properties. +To add a new parameter, click "Add property". + +Example of the "Templates" resource properties: + +| Name | Identifier | Description | Type | +|---------------|---------------------|-------------------------------------------|--------| +| URL | `web_url` | Link to the service repository | URL | +| Repository ID | `project_id` | Internal repository ID in GitLab | Number | +| Latest tag | `repository_last_tag` | Latest tag created in the Git repository | String | + +Example of the "Services" resource properties: + +| Name | Identifier | Description | Type | +|-------------------------------|---------------------|--------------------------------------------------------------|--------| +| URL | `web_url` | Link to the service repository | URL | +| Repository ID | `project_id` | Internal repository ID in GitLab | Number | +| Variables used for templating | `template_values` | Variables that were applied when cloning from the template | YAML | +| Default branch | `default_branch` | Name of the repository's main branch | String | + +### Relation + +You must have a relation that reflects the dependency between templates and the services created from them. +If the relation does not exist yet, [create it](#creating-a-relation). + +In the relation, the resource that stores information about templates must be selected as the parent resource ("Parent resource"), +and the resource that stores information about services must be selected as the child resource ("Child resource"). + +### Creating a relation + +To create a relation, click "Create relation" at the bottom of the "Catalog" section sidebar. + +A window for creating a new relation opens. +Fill in the data according to the table below: + +| Parameter | Value | +|-----------------|--------------------------------------------------------| +| Name | [Enter the relation name, for example, `Templates-Services`] | +| Parent resource | [Select the name of the resource with templates] | +| Child resource | [Select the name of the resource with services] | + +## Datasource + +You must have a datasource that automatically retrieves information about the current state of templates from GitLab. +If the datasource does not exist yet, [create it](#creating-a-datasource). + +### Checking the datasource + +On the "Main information" tab, the "Templates" resource must be selected in the "Resource" field. + +On the "Backend" tab, check that automatic synchronization is enabled. +The "Periodic synchronization" parameter must be enabled so that information about templates is updated automatically when templates change in GitLab. +The "Launch frequency" parameter must contain a schedule in CRON format, for example, `1 * * * *` to run every hour. +The schedule determines how often the datasource checks template repositories for new tags. + +The following keys must be set in the backend parameters: + +| Key | Value | Description | +|-------------|---------------------------|-----------------------------------------------------------------| +| `group_ids` | [ID of the template group] | ID of the GitLab group that contains the template repositories | +| `tags` | `true` | Retrieval of tag information for each repository is enabled | + +For details on the available parameters, see [GitlabProjects](../datasources/types/#gitlabprojects). + +On the "Rules" tab, rules must be configured to update the "Templates" resource properties with data retrieved from GitLab: + +- The "URL" property stores the URL of the template repository in GitLab. + `{{ .web_url }}` must be used as the source. + +- The "Repository ID" property stores the internal repository ID in GitLab. + `{{ .id }}` must be used as the source. + +- The "Latest tag" property stores the latest tag of the Git repository (in this guide, it is used as the template version). + For example, you can use the `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` source: this expression gets the latest tag created in the Git repository by taking the first element of the tag array. + If needed, you can configure a different way of getting the tag. + This property is critical for the automation because a change in its value triggers service upgrades. + +The source identifiers are taken from the [GitLab Projects API](https://docs.gitlab.com/api/projects/#get-a-single-project) specification. + +### Creating a datasource + +To create [datasources](../datasources/overview/), go to "Self-service" → "Datasources". +Click "Create" in the upper right corner. + +A window for creating a new [datasource](../datasources/overview/) opens, with several tabs. + +#### "Main information" tab + +Fill in the following fields: + +- "Name": Specify the datasource name (for example, `Service templates`). + +- "Resource": Select the resource that contains information about templates. + +- "Owner": Assign an owner of the datasource. + +- "Owning team": Specify the team responsible for the datasource. + +#### "Backend" tab + +On the "Backend" tab, configure the connection to GitLab: + +- "Backend": Select the built-in `GitlabProjects` datasource type for working with GitLab projects. + +- "Periodic synchronization": Enable automatic synchronization so that information about templates is updated automatically when templates change in GitLab. + +- "Launch frequency": Specify a schedule in CRON format (for example, `1 * * * *` to run every hour). + The schedule determines how often the datasource checks template repositories for new tags. + +- "URL": Specify the URL of your GitLab instance (for example, `https://gitlab.example.com`). + +In the backend parameters, configure the GitLab API request parameters: + +| Key | Value | Description | +|-------------|---------------------------|----------------------------------------------------------------------| +| `group_ids` | [ID of the template group] | Specify the ID of the GitLab group that contains the template repositories | +| `tags` | `true` | Enables retrieval of tag information for each repository | + +For details on the available parameters, see [GitlabProjects](../datasources/types/#gitlabprojects). + +#### "Rules" tab + +On the "Rules" tab, configure the logic for creating and updating entities: + +- "Create new entities": Enable the creation of new entities. + DDP will automatically create records for new templates if a template repository is found in GitLab but does not exist in the catalog yet. + +- "Owner of created entities": Assign an owner for new entities. + +- "Owning team of created entities": Specify the owner team for new entities. + +In the creation rules, configure the identifier and name of the new entity in the portal. +In the "Identifier" field, set the identifier of the entity being created. +For example, the `{{ replaceChar .path_with_namespace "/" "-" }}` expression transforms the path with the namespace, replacing slashes with hyphens to get a unique ID. +In the "Name" field, set the name of the entity being created. +For example, the `{{ .name }}` expression uses the project name from GitLab. + +If needed, you can define your own rules based on Go templates. + +In the matching rules, configure how existing entities are found during synchronization. +In the "Identifier" and "Name" fields, set the identifier and name of the entity being updated. +For example, you can use the same `{{ replaceChar .path_with_namespace "/" "-" }}` and `{{ .name }}` expressions as in the creation rules. + +If needed, you can define your own rules based on Go templates. +If you do not plan to create resource entities manually, use the same rules for matching and creation. + +In the update rules, configure updating the "Templates" resource properties with data retrieved from GitLab: + +- The "URL" property: The URL of the template repository in GitLab is used as the value. + Use `{{ .web_url }}` as the source. + +- The "Repository ID" property: The internal repository ID in GitLab is used as the value. + Use `{{ .id }}` as the source. + +- The "Latest tag" property: The Git repository tag is used as the value. + For example, you can use the `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` source: this expression gets the latest tag created in the Git repository by taking the first element of the tag array. + If needed, you can configure a different way of getting the tag. + This property is critical for the automation because a change in its value triggers service upgrades. + +The source identifiers are taken from the [GitLab Projects API](https://docs.gitlab.com/api/projects/#get-a-single-project) specification. + +#### "Authorization" tab + +On the "Authorization" tab, configure the credentials and headers required to connect to GitLab. + +Configure the credentials. +In the "Identifier" field, specify `token`, and in the "Credentials" field, select the credential that contains a GitLab token with access to the repositories. +The token must have permissions to read projects and tag information in the specified GitLab group. + +Configure the header. In the "Key" field, specify `Private-Token`, and in the "Value" field, specify `{{ .credentials.token }}`. +In this case, the value configured for the credentials is used. +If you use an identifier other than `token` for the credentials, replace `token` with your identifier. + +For details on the available headers, see [GitlabProjects](../datasources/types/#gitlabprojects) and [System account](../datasources/overview/#system-account). + +## Creating actions + +Configure three actions that are responsible for creating a service from a template and upgrading services when new template versions are released. + +{{< alert level="info" >}} +In the entity update rules, in the `entity parameter` field, specify the identifier of the corresponding property of the resource that stores information about services. +The request bodies use the user form field identifiers given in this guide. +If you set different identifiers, change them in the request body as well. +{{< /alert >}} + +### "Create GitLab project" action + +You must have an action that initializes a new project in GitLab. +It runs first when a new service is created and creates the GitLab project that will host the service created from the template. +If the action does not exist yet, [create it](#creating-an-action). + +Check that on the "Main information" tab, the resource that contains information about services is selected in the "Resource" field. +On the "Update" tab, the "Entity property updates" option must be enabled and update rules must be configured +that write the ID, URL, and default branch of the newly created project to the entity for which the action was run. + +Example of entity update rules: + +- The "Repository ID" property: The `{{ .response.id }}` source is used. It saves the ID of the created project from the GitLab API response to the entity property. + +- The "URL" property: The `{{ .response.web_url }}` source is used. It saves the GitLab URL of the created project to the entity property. + +- The "Default branch" property: The `{{ .response.default_branch }}` source is used. It saves the default branch name to the entity property. + +The source identifiers (`id`, `web_url`, `default_branch`) are taken from the [GitLab Projects API](https://docs.gitlab.com/api/projects/#get-a-single-project) specification. + +### "Create repository from template" action + +You must have an action that clones code from the template repository to the new service repository, applying templating variables. +This action runs after the project is created in GitLab and populates it with code from the template. +If the action does not exist yet, [create it](#creating-an-action). + +Check that the action has the following settings: + +- On the "Main information" tab, the resource that contains information about services is selected in the "Resource" field (the action runs for the entity of the service being upgraded). + +- On the "User form" tab, there is a "Template repository ID" parameter with the `template_ddp_slug` identifier (or another one) of the Entities type. It is automatically populated with the DDP identifier of the template entity from which the code will be cloned. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Identifier". + This lets you select the required template from the related entities. + You can make this parameter hidden. + +- On the "Update" tab, the "Entity property updates" option is enabled and saving the variables used for templating back to the entity for which the action was run is configured. + +For example, in the entity update rule for the "Variables used for templating" property, use the `{{ toYAML .response.values.merged }}` source. +This expression saves the variables in YAML format. +These variables are critical for future service upgrades from the template because they must be applied again. +The data is received as a response to a successful action run. + +On the "Update" tab, the "Creating relations for the entity" option is also enabled so that the action automatically creates a relation between the created service and its template: + +- "Resource": The "Services" resource is selected. + +- "Relation": The "Templates-Services" relation is selected. + +- "Parent entity slug": Use `{{ .property.template_ddp_slug }}`, the template identifier from the action parameter. + + {{< alert level="warning" >}} + If the parameter identifier is not `template_ddp_slug`, replace it with the correct one. + {{< /alert >}} + +- "Child entity slug": Leave it empty. The current entity for which the action runs will be used. + +### "Upgrade service from template" action + +You must have an action that the automation uses to create a new merge request in the service repository. +This merge request will contain changes from the new version (new tag) of the related template. +If the action does not exist yet, [create it](#creating-an-action). + +Check that on the "Main information" tab, the resource that contains information about services is selected in the "Resource" field. + +Check that the following fields exist on the "User form" tab: + +- The "Variables used in templating" parameter with the `template_values` identifier (or another one) of the String type: Stores the variables that were used during the initial templating (they are stored in the entity property). + Default value: `{{ .entity.properties.template_values }}`. It uses the saved variables from the entity property. + If the parameter has a different name (for example, `template_vars`), use the corresponding identifier. + +- The "Version" parameter with the `version` identifier (or another one) of the Entities type: Gets the value of the new tag (version) from the template entity. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Property", Property: "Latest tag". + +- The "Target repository" parameter with the `target_project_id` identifier (or another one) of the String type: The ID of the service repository in GitLab in which the merge request is created. + Default value: `{{ .entity.properties.project_id }}`. It uses the project ID from the entity property. + If the property that stores the internal GitLab project ID has a different identifier, use it instead of `project_id`. + +- The "Template repository" parameter with the `source_project_id` identifier (or another one) of the Entities type: The ID of the template repository in GitLab. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Property", Property: "Repository ID". + +- The "Target repository branch" parameter with the `target_repo_branch` identifier (or another one) of the String type: The main branch of the service repository (for example, `master` or `main`) that the merge request targets. + If needed, you can specify any other branch. + Default value: `{{ .entity.properties.default_branch }}`. It uses the default branch from the entity property. + If the property has a different identifier, use it instead of `default_branch`. + +On the "Request configuration" tab, the request body must be configured approximately as follows: + +```yaml +merge_request_spec: + source_branch: update-to-{{ .version }} + target_branch: {{ .target_repo_branch }} + title: update-to-{{ .version }} +source_project_tag: {{ .version }} +source_project_id: "{{ .source_project_id }}" +target_project_id: "{{ .target_project_id }}" +values: {{ .template_values | nindent 4 }} +``` + +In the request body: + +- `source_branch`: The name of the branch that contains the changes. + The example uses a branch whose name includes the tag version. +- `target_branch`: The target branch of the service that the merge request targets. +- `title`: The merge request title, including the version. +- `source_project_tag`: The template version tag from which the changes are taken. +- `source_project_id` and `target_project_id`: The IDs of the template and service repositories. +- `values`: The templating variables, applied again to render the changes correctly. + +For details on the built-in backend settings, see [CreateGitlabMergeRequest](../actions/gitlab/creategitlabmergerequest/). + +### Creating an action + +To create an [action](../actions/overview/), go to "Self-service" → "Actions". +Create a new action. +To do this, click "Create" in the upper right corner. +A window for creating a new [action](../actions/overview/) opens, with several tabs. + +#### "Main information" tab + +Fill in the following fields on the "Main information" tab: + +- "Name": [Specify the action name]. + +- "Resource": Select the "Services" resource. + +- "Owner": [Specify the owner]. + +- "Owning team": [Specify the owner team]. + +#### "User form" tab + +On the "User form" tab, configure the fields to fill in when running the action. +The set of parameters depends on the action being created. + +For the "Create GitLab project" action, add the following parameters: + +- The "Name" parameter with the `name` identifier (or another one if needed) of the String type: The name of the new project. + Default value: `{{ .entity.name }}`. It uses the entity name in DDP. + +- The "Path" parameter with the `path` identifier (or another one if needed) of the String type: The URL path to the repository in GitLab. + Default value: `{{ .entity.slug }}`. It uses the entity identifier in DDP. + +- The "Repository group" parameter with the `group` identifier (or another one if needed) of the String type: The ID of the GitLab group in which the service will be created. + In the "Default value" field, specify the ID of the GitLab group in which the project will be created. + +For the "Create repository from template" action, add the following parameters: + +- The "Template repository ID" parameter with the `template_ddp_slug` identifier (or another one if needed) of the Entities type: The DDP identifier of the template entity from which the code will be cloned. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Identifier". + This lets you select the required template from the related entities. + +- The "Service repository URL" parameter with the `service_git_url` identifier (or another one if needed) of the URL type: The URL of the repository to which the rendered template will be pushed. + Default value: `{{ .entity.properties.web_url }}`. It uses the URL of the service entity from the catalog. + If the URL property in the resource has a different name, use the corresponding identifier (for example, `{{ .entity.properties.service_url }}`). + +- The "Template repository URL" parameter with the `template_git_url` identifier (or another one if needed) of the Entities type: The URL of the template repository that the backend uses for cloning. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Property", Property: "URL". + +Additional parameters depend on your template and must be configured according to the variables used in the template. + +For the "Upgrade service from template" action, configure fields that collect the data the backend needs to create a merge request. +This data will be populated automatically from entities of the "Services" resource or from the related entity of the "Templates" resource: + +- The "Variables used in templating" parameter with the `template_values` identifier (or another one if needed) of the String type: The variables that were used during the initial templating (they are stored in the entity property). + Default value: `{{ .entity.properties.template_values }}`. It uses the saved variables from the entity property. + If the parameter has a different name (for example, `template_vars`), use the corresponding identifier. + +- The "Version" parameter with the `version` identifier (or another one if needed) of the Entities type: Gets the value of the new tag (version) from the template entity. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Property", Property: "Latest tag". + +- The "Target repository" parameter with the `target_project_id` identifier (or another one if needed) of the String type: The internal ID of the service repository in GitLab in which the merge request is created. + Default value: `{{ .entity.properties.project_id }}`. It uses the project ID from the entity property. + If the ID property in the resource has a different name, use the corresponding identifier. + +- The "Template repository" parameter with the `source_project_id` identifier (or another one if needed) of the Entities type: The internal ID of the template repository in GitLab. + In the additional settings, specify: Resource: "Templates", Relation: "Templates-Services", Field: "Property", Property: "Repository ID". + +- The "Target repository branch" parameter with the `target_repo_branch` identifier (or another one if needed) of the String type: The main branch of the service repository (for example, `master` or `main`) that the merge request targets. + Default value: `{{ .entity.properties.default_branch }}`. It uses the default branch from the entity property. + If the property identifier is different, use your own. + +#### "Request configuration" tab + +On the "Request configuration" tab, configure the action execution logic. The logic depends on the action being configured. + +For the "Create GitLab project" action, fill in the following fields: + +- "Action type": Select the built-in action type (the `BuiltIn` value). +- "Built-in action type": Select `CreateGitlabProject` to create a project in GitLab. +- "URL": Specify the URL of your GitLab instance (for example, `https://gitlab.example.com`). + +Request body of the "Create GitLab project" action: + +```yaml +initialize_with_readme: false +name: '{{ .name }}' +namespace_id: '{{ .group }}' +path: '{{ .path }}' +``` + +This request body passes the project name, group ID, and repository path to the GitLab API. +For details on the settings, see [CreateGitlabProject](../actions/gitlab/creategitlabproject/). + +For the "Create repository from template" action, fill in the following fields: + +- "Action type": Select the built-in action type (the `BuiltIn` value). + +- "Built-in action type": Select `CreateRepositoryFromTemplate` to create a repository from a template. + +- "URL": Specify the URL of your GitLab instance (for example, `https://gitlab.example.com`). + +Request body of the "Create repository from template" action: + +```yaml +sourceBranch: "master" +templateRepositoryUrl: "{{ .template_git_url }}" +targetRepositoryUrl: "{{ .service_git_url }}" +values: + : +``` + +Replace `` and `` with the names and values of your template variables. +Add a separate line for each variable. + +In the request body: + +- `sourceBranch`: The branch in the template repository from which the code will be cloned (usually `master` or `main`). + +- `templateRepositoryUrl`: The template repository URL from the action parameter. + +- `targetRepositoryUrl`: The URL of the target service repository. + +- `values`: Key-value pairs used to replace variables in the template files. + The format and set of these variables depend entirely on how your template is configured. + +For details on the settings, see [CreateRepositoryFromTemplate](../actions/gitlab/createrepositoryfromtemplate/). + +For the "Upgrade service from template" action, fill in the following fields: + +- "Action type": Select the built-in action type (the `BuiltIn` value). + +- "Built-in action type": Select `CreateGitlabMergeRequest` to create a merge request in GitLab. + +- "URL": Specify the URL of your GitLab instance (for example, `https://gitlab.example.com`). + +Request body of the "Upgrade service from template" action: + +```yaml +merge_request_spec: + source_branch: update-to-{{ .version }} + target_branch: {{ .target_repo_branch }} + title: update-to-{{ .version }} +source_project_tag: {{ .version }} +source_project_id: "{{ .source_project_id }}" +target_project_id: "{{ .target_project_id }}" +values: {{ .template_values | nindent 4 }} +``` + +In the request body: + +- `source_branch`: A new branch is created with a name that includes the tag version. + +- `target_branch`: The target branch of the service that the merge request targets. + +- `title`: The merge request title, including the version. + +- `source_project_tag`: The template version tag from which the changes are taken. + +- `source_project_id` and `target_project_id`: The IDs of the template and service repositories. + +- `values`: The templating variables, applied again to render the changes correctly. + +For details on the settings, see [CreateGitlabMergeRequest](../actions/gitlab/creategitlabmergerequest/). + +#### "Update" tab + +For the "Create GitLab project" and "Create repository from template" actions, enable the "Entity property updates" option and configure update rules that write information to the entity for which the action was run. +The entity update rules depend on the action being configured. + +For the "Create GitLab project" action, use the identifiers of the corresponding resource properties: + +- The "Repository ID" property: Use the `{{ .response.id }}` source. It saves the ID of the created project from the GitLab API response. + +- The "URL" property: Use the `{{ .response.web_url }}` source. It saves the URL of the created project. + +- The "Default branch" property: Use the `{{ .response.default_branch }}` source. It saves the default branch name. + +The source identifiers (`id`, `web_url`, `default_branch`) are taken from the [GitLab Projects API](https://docs.gitlab.com/api/projects/#get-a-single-project) specification. + +For the "Create repository from template" action, use the identifier of the corresponding resource property. +For the "Variables used for templating" property, use the `{{ toYAML .response.values.merged }}` source. +This expression saves the variables in YAML format. +These variables are critical for future service upgrades from the template because they must be applied again. +The data is received as a response to a successful action run. + +For the "Create repository from template" action, also enable the "Creating relations for the entity" option so that the action automatically creates a relation between the created service and its template: + +- "Resource": Select "Services". + +- "Relation": Select the "Templates-Services" relation. + +- "Parent entity slug": Use `{{ .property.template_ddp_slug }}`, the template identifier from the action parameter. + + {{< alert level="warning" >}} + If the parameter identifier is not `template_ddp_slug`, replace it with the correct one. + {{< /alert >}} + +- "Child entity slug": Leave it empty. The current entity for which the action runs will be used. + +#### "Authorization" tab + +On the "Authorization" tab, configure the credentials for running the action. The settings depend on the action. + +For the "Create GitLab project" action, configure the credentials. +In the "Identifier" field, specify `token`, and in the "Credentials" field, select the credential that contains a GitLab token with the permissions required to create projects in the specified group. + +For the "Create repository from template" action, configure credentials with the `password` and `username` identifiers. +For `password`, select the credential that contains a GitLab password (token) with the required repository access permissions; for `username`, select the credential that contains the GitLab username. + +For the "Update service from template" action, configure credentials with the `password` and `username` identifiers. +For `password`, select the credential that contains a GitLab password (token) with the required repository access permissions; for `username`, select the credential that contains the GitLab username. + +## Process + +You must have a process that combines the actions for creating a project in GitLab and creating a service from a template into a single sequential automated chain. +The process must run the creation of a project in GitLab and then the creation of a repository from the template, in sequence. +If the process does not exist yet, [create it](#creating-a-process). + +Check that on the "Main information" tab, the "Services" resource is selected in the "Resource" field. + +On the "Configuration" tab, the actions must be in the following order: + +1. Start. +1. Create GitLab project. +1. Create repository from template. +1. End. + +### Creating a process + +To create a process, go to "Self-service" → "Processes". +Create a new process. +To do this, click "Create" in the upper right corner. + +A window for creating a new process opens, with several tabs. + +#### "Main information" tab + +Fill in the following fields: + +- "Name": `Create service from template`. + +- "Resource": Select the "Services" resource. + +- "Owner": [Specify the owner]. + +- "Owning team": [Specify the owner team]. + +#### "Configuration" tab + +On the "Configuration" tab, configure the process steps and their execution order. +The task and action names are examples. +Add the following elements: + +1. Add a "Task" element named "Create GitLab project" and select the "Create GitLab project" action to run. +1. Add a "Task" element named "Create repository from template" and select the "Create repository from template" action to run. +1. Add an "End" element to complete the process. + +After adding all elements, configure the execution order: + +1. Start. +1. Create GitLab project. +1. Create repository from template. +1. End. + +## Automation + +You must have an automation that runs the action for creating a merge request to upgrade services when a new template version appears. +The automation tracks changes to the "Latest tag" property in entities of the "Templates" resource and, when a new tag is detected, automatically runs the "Upgrade service from template" action for all related services. +If the automation does not exist yet, [create it](#creating-an-automation). + +### Checking the automation + +On the "Configuration" tab, check the trigger settings. +The "Resource" field must be set to "Templates", and the "Condition" field must contain `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}` or a similar condition if your check is configured differently. + +This condition fires every time the property with the `repository_last_tag` identifier in an entity of the "Templates" resource is not equal to the specified value (`v1.0.0`). +The condition is checked only once when the `repository_last_tag` parameter changes. +If the "Latest tag" property has a different identifier (for example, `last_tag`), use it in the condition: `{{ ne .entity.properties.last_tag "v1.0.0" }}`. + +Check the execution settings. +The "Execution type" field must be set to "Actions", and the "Execution object" field must be set to the "Upgrade service from template" action. + +Check that the "Run execution for related resources" parameter is enabled and the resource relations are configured. +The "Resource" field must be set to "Templates", and the "Relation" field must be set to the "Templates-Services" relation. + +### Creating an automation + +To create an [automation](../automations), go to "Self-service" → "Automations". +Create an automation. +To do this, click "Create" in the upper right corner. + +A window for creating a new automation opens, with several tabs. + +#### "Main information" tab + +Fill in the following fields: + +- "Name": [Specify the automation name]. + +- "Owner": [Specify the owner]. + +- "Owning team": [Specify the owner team]. + +#### "Configuration" tab + +On the "Configuration" tab, configure the automation run logic. + +A trigger determines when the automation runs. +Add a new trigger. +In the "Resource" field, select "Templates", and in the "Condition" field, specify `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}`. + +{{< alert level="warning" >}} +The condition uses the identifier of the "Templates" resource property that stores the latest tag of the Git repository. +If your identifier is different, use the correct one. +{{< /alert >}} + +This condition fires every time the `repository_last_tag` property in an entity of the "Templates" resource is not equal to the specified value (`v1.0.0`). +The condition is checked only once when the `repository_last_tag` parameter changes. + +{{< alert level="info" >}} +If you plan to create several automations, each of which must respond to property changes in entities of the same resource, specify the condition in the `{{ and (ne .entity.properties.repository_last_tag "v1.0.0") (eq .entity.slug "example") }}` format to additionally filter which automation runs in each specific case. +Without the `(eq .entity.slug "example")` condition, each automation will respond to changes in every entity. +{{< /alert >}} + +Configure the action execution. +In the "Execution type" field, select "Actions", and in the "Execution object" field, select the "Upgrade service from template" action. + +The automation watches for changes in entities of the "Templates" resource, but the action upgrades entities of the "Services" resource that are related to the template in which the `repository_last_tag` property was updated. +Enable the "Run execution for related resources" parameter and configure the resource relations. +In the "Resource" field, select "Templates", and in the "Relation" field, select the "Templates-Services" relation. + +When the tag is updated in the "Templates" resource, the system finds all entities of the "Services" resource related to this template and runs the "Upgrade service from template" action for each of them, creating a merge request with changes from the new template version. + +## Creating a service + +The portal is now configured to create services from a template and automatically upgrade them when a new template version is released. + +To create a service: + +1. Go to the "Catalog" tab and open the "Services" resource. +1. Click "Create" in the upper right corner. +1. In the window that opens, fill in the required fields on the "Main information" tab. + If you configured everything according to this guide, you do not need to fill in data on the other tabs. + The data will be filled in automatically later. +1. To the right of the new service record, click the blue button with three vertical dots and select "Run process". +1. In the drop-down list, select the `Create service from template` process. +1. If needed, fill in the template variables and run the process. +1. If everything is configured correctly, the service is created. + When template upgrades are available, merge requests with the changes will be created for the service. + To verify that the service was created correctly, open it and go to the "Actions" tab and check the "Execution history" table. + All [actions](../actions/overview/) must have the `Success` status. diff --git a/content/documentation/admin/examples/service-autoupdates.ru.md b/content/documentation/admin/examples/service-autoupdates.ru.md index ccb2d334..2519a541 100644 --- a/content/documentation/admin/examples/service-autoupdates.ru.md +++ b/content/documentation/admin/examples/service-autoupdates.ru.md @@ -4,7 +4,8 @@ weight: 50 description: Настройка ресурсов, связи, источника данных, действий, процесса и автоматизации DDP, которые создают запросы на слияние в сервисах при выпуске новой версии шаблона. --- -Инструкция описывает настройку автоматического механизма обновления всех сервисов, созданных из шаблона, при выпуске новой версии этого шаблона. Новая версия шаблона определяется по новому тегу, добавленному в Git-репозиторий шаблона. +Инструкция описывает настройку автоматического механизма обновления всех сервисов, созданных из шаблона, при выпуске новой версии этого шаблона. +Новая версия шаблона определяется по новому тегу, добавленному в Git-репозиторий шаблона. {{< alert level="info" >}} Названия ресурсов, параметров, действий и процессов в инструкции приведены в качестве примера и могут отличаться в зависимости от ваших настроек. @@ -14,7 +15,8 @@ description: Настройка ресурсов, связи, источника Для реализации автоматического обновления сервисов используются следующие компоненты Deckhouse Development Portal (DDP, портал): -- Ресурсы — это элементы модели данных каталога DDP, которые определяют структуру хранения информации. Каждый ресурс может содержать параметры для хранения метаданных сущностей, а также связи с другими ресурсами для отображения зависимостей. +- Ресурсы — это элементы модели данных каталога DDP, которые определяют структуру хранения информации. + Каждый ресурс может содержать параметры для хранения метаданных сущностей, а также связи с другими ресурсами для отображения зависимостей. В рамках инструкции используются два ресурса: @@ -23,26 +25,33 @@ description: Настройка ресурсов, связи, источника - Связь — устанавливает зависимость между ресурсами и обеспечивает возможность автоматического нахождения всех сервисов, связанных с конкретным шаблоном. -- [Источник данных](../datasources/overview/) — механизм DDP, который позволяет синхронизировать информацию из внешних инфраструктурных систем (например, GitLab) в каталог портала. Источники данных периодически опрашивают внешние системы, получают актуальную информацию и обновляют соответствующие сущности в каталоге. В рамках инструкции источник данных: +- [Источник данных](../datasources/overview/) — механизм DDP, который позволяет синхронизировать информацию из внешних инфраструктурных систем (например, GitLab) в каталог портала. + Источники данных периодически опрашивают внешние системы, получают актуальную информацию и обновляют соответствующие сущности в каталоге. + В рамках инструкции источник данных: - синхронизирует информацию о шаблонных репозиториях из GitLab; - обновляет список тегов для каждого шаблона; - автоматически обновляет параметр «Последний тег» в сущностях ресурса «Шаблоны». -- Действие — механизм DDP, который позволяет пользователям портала взаимодействовать с внешними инфраструктурными сервисами через API. Действия могут создавать проекты в GitLab, создавать секреты в системах управления секретами, развёртывать приложения и выполнять другие операции. +- Действие — механизм DDP, который позволяет пользователям портала взаимодействовать с внешними инфраструктурными сервисами через API. + Действия могут создавать проекты в GitLab, создавать секреты в системах управления секретами, развёртывать приложения и выполнять другие операции. В рамках инструкции используются три действия: - создание нового проекта в GitLab для размещения сервиса; - клонирование кода из шаблонного репозитория в новый репозиторий сервиса с применением переменных шаблонизации; - - создание запроса на слияние в репозитории сервиса с изменениями из новой версии шаблона. + - создание запроса на слияние (Merge Request) в репозитории сервиса с изменениями из новой версии шаблона. -- Процесс — механизм автоматизации сложных бизнес-процессов, который позволяет создавать визуальные схемы выполнения действий с поддержкой последовательного или параллельного выполнения. Процессы объединяют несколько действий в единую цепочку выполнения. В рамках инструкции процесс: +- Процесс — механизм автоматизации сложных бизнес-процессов, который позволяет создавать визуальные схемы выполнения действий с поддержкой последовательного или параллельного выполнения. + Процессы объединяют несколько действий в единую цепочку выполнения. + В рамках инструкции процесс: - последовательно запускает создание проекта в GitLab, а затем создание репозитория из шаблона; - обеспечивает интерфейс для пользователя при создании сервиса из шаблона. -- Автоматизация — механизм реагирования портала на изменения спецификации сущностей. Автоматизации подписываются на события обновления сущностей ресурсов по определённым правилам (триггерам) и запускают выполнение действий, процессов или синхронизацию источников данных. В рамках инструкции автоматизация: +- Автоматизация — механизм реагирования портала на изменения спецификации сущностей. + Автоматизации подписываются на события обновления сущностей ресурсов по определённым правилам (триггерам) и запускают выполнение действий, процессов или синхронизацию источников данных. + В рамках инструкции автоматизация: - отслеживает изменения параметра «Последний тег» в сущностях ресурса «Шаблоны»; - при обнаружении нового тега запускает действие «Обновление сервиса из шаблона» для всех связанных сервисов; @@ -63,7 +72,8 @@ description: Настройка ресурсов, связи, источника ## Настройка компонентов -В следующих разделах описывается конфигурация каждого компонента системы. Если вы используете другие названия и идентификаторы параметров в ресурсах, используйте их во всех действиях, автоматизациях и источниках данных, которые ссылаются на эти параметры. +В следующих разделах описывается конфигурация каждого компонента системы. +Если вы используете другие названия и идентификаторы параметров в ресурсах, используйте их во всех действиях, автоматизациях и источниках данных, которые ссылаются на эти параметры. Будет описано: @@ -78,7 +88,8 @@ description: Настройка ресурсов, связи, источника ## Создание ресурсов и связи -«Ресурсы» — это элементы модели данных каталога DDP, которые определяют структуру хранения информации. Каждый ресурс может содержать параметры для хранения метаданных сущностей, а также связи с другими ресурсами для отображения зависимостей. +«Ресурсы» — это элементы модели данных каталога DDP, которые определяют структуру хранения информации. +Каждый ресурс может содержать параметры для хранения метаданных сущностей, а также связи с другими ресурсами для отображения зависимостей. {{< alert level="warning" >}} Убедитесь, что идентификаторы параметров корректно указаны во всех действиях, автоматизациях и источниках данных, которые ссылаются на эти параметры. @@ -86,37 +97,51 @@ description: Настройка ресурсов, связи, источника ### Ресурс «Шаблоны» -У вас должен быть создан ресурс для хранения информации о шаблонных репозиториях. В рамках данной инструкции он назван «Шаблоны», однако вы можете использовать любое удобное для вас название. Если ресурса ещё нет, [создайте его](#создание-ресурса). +У вас должен быть создан ресурс для хранения информации о шаблонных репозиториях. +В рамках данной инструкции он назван «Шаблоны», однако вы можете использовать любое удобное для вас название. +Если ресурса ещё нет, [создайте его](#создание-ресурса). Ресурс должен содержать следующие параметры для хранения данных о шаблонных репозиториях: -- Параметр «URL» типа URL — используется для хранения URL-адреса репозитория шаблона в GitLab. Этот параметр необходим для действий, которые работают с репозиторием шаблона. +- Параметр «URL» типа URL — используется для хранения URL-адреса репозитория шаблона в GitLab. + Этот параметр необходим для действий, которые работают с репозиторием шаблона. -- Параметр «ID репозитория» типа Number — хранит внутренний ID репозитория в GitLab. Используется для действий, которые требуют указания ID проекта GitLab. +- Параметр «ID репозитория» типа Number — хранит внутренний ID репозитория в GitLab. + Используется для действий, которые требуют указания ID проекта GitLab. -- Параметр «Последний тег» типа String — содержит название последнего тега (версии) шаблона. Этот параметр используется автоматизацией для отслеживания появления новых версий шаблона. При каждом обновлении этого параметра источником данных автоматизация проверяет изменение и запускает обновление связанных сервисов. +- Параметр «Последний тег» типа String — содержит название последнего тега (версии) шаблона. + Этот параметр используется автоматизацией для отслеживания появления новых версий шаблона. + При каждом обновлении этого параметра источником данных автоматизация проверяет изменение и запускает обновление связанных сервисов. Если параметры отсутствуют, откройте ресурс на редактирование и добавьте их на вкладке «Параметры» ресурса, нажав кнопку «Добавить параметр». ### Ресурс «Сервисы» -У вас должен быть создан второй ресурс для хранения информации о созданных сервисах. В рамках инструкции он называется «Сервисы», но вы можете выбрать любое удобное для вас название. Если ресурса ещё нет, [создайте его](#создание-ресурса). +У вас должен быть создан второй ресурс для хранения информации о созданных сервисах. +В рамках инструкции он называется «Сервисы», но вы можете выбрать любое удобное для вас название. +Если ресурса ещё нет, [создайте его](#создание-ресурса). Ресурс должен содержать следующие параметры для хранения метаданных о созданных сервисах: -- Параметр «URL» типа URL — ссылка на репозиторий сервиса в GitLab. Используется действиями для работы с репозиторием сервиса. +- Параметр «URL» типа URL — ссылка на репозиторий сервиса в GitLab. + Используется действиями для работы с репозиторием сервиса. -- Параметр «ID репозитория» типа Number — внутренний ID репозитория в GitLab. Необходим для действий, которые требуют указания ID проекта GitLab. +- Параметр «ID репозитория» типа Number — внутренний ID репозитория в GitLab. + Необходим для действий, которые требуют указания ID проекта GitLab. -- Параметр «Переменные использованные при шаблонизации» типа YAML — содержит переменные, которые были применены при клонировании кода из шаблона в сервис. Эти переменные необходимы при обновлении сервиса из шаблона, так как они должны быть применены повторно для корректного рендеринга новых изменений из шаблона. +- Параметр «Переменные использованные при шаблонизации» типа YAML — содержит переменные, которые были применены при клонировании кода из шаблона в сервис. + Эти переменные необходимы при обновлении сервиса из шаблона, так как они должны быть применены повторно для корректного рендеринга новых изменений из шаблона. -- Параметр «Ветка по умолчанию» типа String — название основной ветки репозитория (например, `main` или `master`). Используется действием обновления сервиса для определения целевой ветки запроса на слияние. +- Параметр «Ветка по умолчанию» типа String — название основной ветки репозитория (например, `main` или `master`). + Используется действием обновления сервиса для определения целевой ветки запроса на слияние. Если параметры отсутствуют, откройте ресурс на редактирование и добавьте их на вкладке «Параметры» ресурса, нажав кнопку «Добавить параметр». ### Создание ресурса -Для создания ресурсов перейдите в раздел «Каталог». Создайте новый ресурс. Для этого в нижней части боковой панели каталога нажмите кнопку «Создать ресурс». +Для создания ресурсов перейдите в раздел «Каталог». +Создайте новый ресурс. +Для этого в нижней части боковой панели каталога нажмите кнопку «Создать ресурс». Откроется окно по созданию нового ресурса с различными вкладками. @@ -132,40 +157,40 @@ description: Настройка ресурсов, связи, источника #### Вкладка «Параметры» -Перейдите на вкладку «Параметры» и добавьте требуемые параметры ресурса. Для добавления нового параметра нажмите кнопку «Добавить параметр». +Перейдите на вкладку «Параметры» и добавьте требуемые параметры ресурса. +Для добавления нового параметра нажмите кнопку «Добавить параметр». Пример параметров ресурса «Шаблоны»: | Название | Идентификатор | Описание | Тип | |----------------|---------------------|-------------------------------------------|--------| -| URL | web_url | Ссылка на репозиторий сервиса | URL | -| ID репозитория | project_id | Внутренний ID репозитория в GitLab | Number | -| Последний тег | repository_last_tag | Последний созданный тег в git репозитории | String | +| URL | `web_url` | Ссылка на репозиторий сервиса | URL | +| ID репозитория | `project_id` | Внутренний ID репозитория в GitLab | Number | +| Последний тег | `repository_last_tag` | Последний созданный тег в git репозитории | String | Пример параметров ресурса «Сервисы»: | Название | Идентификатор | Описание | Тип | |--------------------------------------------|---------------------|----------------------------------------------------------------|--------| -| URL | web_url | Ссылка на репозиторий сервиса | URL | -| ID репозитория | project_id | Внутренний ID репозитория в GitLab | Number | -| Переменные использованные при шаблонизации | template_values | Переменные, которые были применены при клонировании из шаблона | YAML | -| Ветка по умолчанию | default_branch | Название основной ветки репозитория | String | +| URL | `web_url` | Ссылка на репозиторий сервиса | URL | +| ID репозитория | `project_id` | Внутренний ID репозитория в GitLab | Number | +| Переменные использованные при шаблонизации | `template_values` | Переменные, которые были применены при клонировании из шаблона | YAML | +| Ветка по умолчанию | `default_branch` | Название основной ветки репозитория | String | ### Связь -У вас должна быть настроена связь, которая отражает зависимость между шаблонами и созданными из них сервисами. Если связи ещё нет, [создайте её](#создание-связи). +У вас должна быть настроена связь, которая отражает зависимость между шаблонами и созданными из них сервисами. +Если связи ещё нет, [создайте её](#создание-связи). -Связь должна быть настроена следующим образом: - -- «Родительский ресурс»: выбран ресурс, хранящий информацию о шаблонах. - -- «Дочерний ресурс»: выбран ресурс, хранящий информацию о сервисах. +В связи в качестве родительского ресурса («Родительский ресурс») должен быть выбран ресурс, хранящий информацию о шаблонах, +а в качестве дочернего («Дочерний ресурс») — ресурс, хранящий информацию о сервисах. ### Создание связи Для создания связи нажмите кнопку «Создать связь» в нижней части боковой панели раздела «Каталог». -Откроется окно по созданию новой [связи](../../user/catalog/#связи-между-ресурсами). Заполните данные согласно таблице ниже: +Откроется окно по созданию новой [связи](../../user/catalog/#связи-между-ресурсами). +Заполните данные согласно таблице ниже: | Параметр | Значение | |---------------------|------------------------------------------------------| @@ -175,40 +200,46 @@ description: Настройка ресурсов, связи, источника ## Источник данных -У вас должен быть настроен источник данных, который автоматически получает информацию об актуальном состоянии шаблонов из GitLab. Если источника данных ещё нет, [создайте его](#создание-источника-данных). +У вас должен быть настроен источник данных, который автоматически получает информацию об актуальном состоянии шаблонов из GitLab. +Если источника данных ещё нет, [создайте его](#создание-источника-данных). ### Проверка источника данных На вкладке «Основная информация» в поле «Ресурс» должен быть выбран ресурс «Шаблоны». -На вкладке «Бэкенд» проверьте, что включена автоматическая синхронизация: - -- «Периодическая синхронизация»: должна быть включена, для автоматического обновления информации о шаблонах при их изменении в GitLab. - -- «Периодичность запуска»: должно быть указано расписание в формате CRON (например, `1 * * * *` для запуска каждый час). Расписание определяет, как часто источник данных будет проверять наличие новых тегов в репозиториях шаблонов. +На вкладке «Бэкенд» проверьте, что включена автоматическая синхронизация. +Параметр «Периодическая синхронизация» должен быть включён, чтобы информация о шаблонах автоматически обновлялась при их изменении в GitLab. +В параметре «Периодичность запуска» должно быть указано расписание в формате CRON, например `1 * * * *` для запуска каждый час. +Расписание определяет, как часто источник данных будет проверять наличие новых тегов в репозиториях шаблонов. В параметрах бэкенда должны быть заданы следующие ключи: | Ключ | Значение | Описание | |-----------|-------------------------|---------------------------------------------------------------------| -| group_ids | [ID группы с шаблонами] | Указано ID группы GitLab, в которой находятся шаблонные репозитории | -| tags | true | Включено получение информации о тегах для каждого репозитория | +| `group_ids` | [ID группы с шаблонами] | Указано ID группы GitLab, в которой находятся шаблонные репозитории | +| `tags` | `true` | Включено получение информации о тегах для каждого репозитория | Подробнее о доступных параметрах — в разделе [«GitlabProjects»](../datasources/types/#gitlabprojects). На вкладке «Правила» должны быть настроены правила обновления параметров ресурса «Шаблоны» данными, полученными из GitLab: -- Параметр «URL»: необходимо хранить URL репозитория шаблона в GitLab. В качестве источника должен использоваться `{{ .web_url }}`. +- Параметр «URL» хранит URL репозитория шаблона в GitLab. + В качестве источника должен использоваться `{{ .web_url }}`. -- Параметр «ID репозитория»: необходимо хранить внутренний ID репозитория в GitLab. В качестве источника должен использоваться `{{ .id }}`. +- Параметр «ID репозитория» хранит внутренний ID репозитория в GitLab. + В качестве источника должен использоваться `{{ .id }}`. -- Параметр «Последний тег»: необходимо хранить последний тег git-репозитория (в рамках данной инструкции используется как версия шаблона). Например, можно использовать источник `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` — данное выражение получает последний тег, созданный в git-репозитории, беря первый элемент из массива тегов. При необходимости способ получения тега можно настроить иначе. Этот параметр критически важен для работы автоматизации, так как изменение его значения является триггером для обновления сервисов. +- Параметр «Последний тег» хранит последний тег git-репозитория (в рамках данной инструкции используется как версия шаблона). + Например, можно использовать источник `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` — данное выражение получает последний тег, созданный в git-репозитории, беря первый элемент из массива тегов. + При необходимости способ получения тега можно настроить иначе. + Этот параметр критически важен для работы автоматизации, так как изменение его значения является триггером для обновления сервисов. Идентификаторы источников берутся из спецификации [Projects API GitLab](https://docs.gitlab.com/api/projects/#get-a-single-project). ### Создание источника данных -Для создания [источников данных](../datasources/overview/) перейдите в раздел «Самообслуживание» в пункт «Источники данных». В правом верхнем углу нажмите кнопку «Создать». +Для создания [источников данных](../datasources/overview/) перейдите в раздел «Самообслуживание» в пункт «Источники данных». +В правом верхнем углу нажмите кнопку «Создать». Откроется окно по созданию нового [источника данных](../datasources/overview/) с различными вкладками. @@ -232,7 +263,8 @@ description: Настройка ресурсов, связи, источника - «Периодическая синхронизация»: включите автоматический запуск синхронизации, для автоматического обновления информации о шаблонах при их изменении в GitLab. -- «Периодичность запуска»: укажите расписание в формате CRON (например, `1 * * * *` для запуска каждый час). Расписание определяет, как часто источник данных будет проверять наличие новых тегов в репозиториях шаблонов. +- «Периодичность запуска»: укажите расписание в формате CRON (например, `1 * * * *` для запуска каждый час). + Расписание определяет, как часто источник данных будет проверять наличие новых тегов в репозиториях шаблонов. - «URL»: укажите URL вашего экземпляра GitLab (например, `https://gitlab.example.com`). @@ -240,8 +272,8 @@ description: Настройка ресурсов, связи, источника | Ключ | Значение | Описание | |-----------|-------------------------|---------------------------------------------------------------------| -| group_ids | [ID группы с шаблонами] | Укажите ID группы GitLab, в которой находятся шаблонные репозитории | -| tags | true | Включает получение информации о тегах для каждого репозитория | +| `group_ids` | [ID группы с шаблонами] | Укажите ID группы GitLab, в которой находятся шаблонные репозитории | +| `tags` | `true` | Включает получение информации о тегах для каждого репозитория | Подробнее о доступных параметрах — в разделе [«GitlabProjects»](../datasources/types/#gitlabprojects). @@ -249,33 +281,40 @@ description: Настройка ресурсов, связи, источника На вкладке «Правила» настройте логику создания и обновления сущностей: -- «Создание новых сущностей»: включите создание новых сущностей. DDP автоматически будет создавать записи о новых шаблонах, если шаблонный репозиторий обнаружен в GitLab, но ещё не существует в каталоге. +- «Создание новых сущностей»: включите создание новых сущностей. + DDP автоматически будет создавать записи о новых шаблонах, если шаблонный репозиторий обнаружен в GitLab, но ещё не существует в каталоге. - «Владелец создаваемых сущностей»: назначьте владельца для новых сущностей. - «Команда владелец создаваемых сущностей»: укажите команду-владельца для новых сущностей. -В правилах создания настройте идентификатор и название новой сущности в портале: - -- «Идентификатор»: идентификатор создаваемой сущности. Например, можно использовать выражение `{{ replaceChar .path_with_namespace "/" "-" }}` — оно преобразует путь с неймспейсом, заменяя слеши на дефисы для получения уникального ID. -- «Название»: название создаваемой сущности. Например, можно использовать выражение `{{ .name }}` — оно использует название проекта из GitLab. +В правилах создания настройте идентификатор и название новой сущности в портале. +В поле «Идентификатор» задайте идентификатор создаваемой сущности. +Например, выражение `{{ replaceChar .path_with_namespace "/" "-" }}` преобразует путь с неймспейсом, заменяя слеши на дефисы для получения уникального ID. +В поле «Название» задайте название создаваемой сущности. +Например, выражение `{{ .name }}` использует название проекта из GitLab. При необходимости вы можете задать свои собственные правила на основе Go template. -В правилах сопоставления настройте поиск уже существующих сущностей при синхронизации: - -- «Идентификатор»: идентификатор сущности, которую необходимо обновить. Например, можно использовать то же выражение `{{ replaceChar .path_with_namespace "/" "-" }}`, что и в правилах создания. -- «Название»: название сущности, которую необходимо обновить. Например, можно использовать то же выражение `{{ .name }}`, что и в правилах создания. +В правилах сопоставления настройте поиск уже существующих сущностей при синхронизации. +В полях «Идентификатор» и «Название» задайте идентификатор и название обновляемой сущности. +Например, можно использовать те же выражения `{{ replaceChar .path_with_namespace "/" "-" }}` и `{{ .name }}`, что и в правилах создания. -При необходимости вы можете задать свои собственные правила на основе Go template. Если не планируется вручную создавать сущности ресурса, рекомендуется использовать одинаковые правила для сопоставления и создания. +При необходимости вы можете задать свои собственные правила на основе Go template. +Если не планируется вручную создавать сущности ресурса, рекомендуется использовать одинаковые правила для сопоставления и создания. В правилах обновления настройте обновление параметров ресурса «Шаблоны» данными, полученными из GitLab: -- Параметр «URL»: в качестве значения используется URL репозитория шаблона в GitLab. В качестве источника используйте `{{ .web_url }}`. +- Параметр «URL»: в качестве значения используется URL репозитория шаблона в GitLab. + В качестве источника используйте `{{ .web_url }}`. -- Параметр «ID репозитория»: в качестве значения используется внутренний ID репозитория в GitLab. В качестве источника используйте `{{ .id }}`. +- Параметр «ID репозитория»: в качестве значения используется внутренний ID репозитория в GitLab. + В качестве источника используйте `{{ .id }}`. -- Параметр «Последний тег»: в качестве значения используется тег git-репозитория. Например, можно использовать источник `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` — данное выражение получает последний тег, созданный в git-репозитории, беря первый элемент из массива тегов. При необходимости способ получения тега можно настроить иначе. Этот параметр критически важен для работы автоматизации, так как изменение его значения является триггером для обновления сервисов. +- Параметр «Последний тег»: в качестве значения используется тег git-репозитория. + Например, можно использовать источник `{{ ( index ( .ddp_repository_tags ) 0 ).name }}` — данное выражение получает последний тег, созданный в git-репозитории, беря первый элемент из массива тегов. + При необходимости способ получения тега можно настроить иначе. + Этот параметр критически важен для работы автоматизации, так как изменение его значения является триггером для обновления сервисов. Идентификаторы источников берутся из спецификации [Projects API GitLab](https://docs.gitlab.com/api/projects/#get-a-single-project). @@ -283,38 +322,35 @@ description: Настройка ресурсов, связи, источника На вкладке «Авторизация» настройте учётные данные и заголовки, необходимые для подключения к GitLab. -Настройте учётные данные: - -- «Идентификатор»: `token`. - -- «Реквизиты»: укажите реквизиты, которые содержат токен GitLab с необходимыми правами доступа к репозиториям. Токен должен иметь права на чтение проектов и информации о тегах в указанной группе GitLab. - -Настройте заголовок: - -- «Ключ»: `Private-Token`. +Настройте учётные данные. +В поле «Идентификатор» укажите `token`, а в поле «Реквизиты» — реквизиты, которые содержат токен GitLab с правами доступа к репозиториям. +Токен должен иметь права на чтение проектов и информации о тегах в указанной группе GitLab. -- «Значение»: `{{ .credentials.token }}` — используется значение, которое было настроено для учётных данных. Если в качестве идентификатора учётных данных используется не `token`, необходимо заменить `token` на заданное вами. +Настройте заголовок. В поле «Ключ» укажите `Private-Token`, а в поле «Значение» — `{{ .credentials.token }}`. +В этом случае используется значение, которое было настроено для учётных данных. +Если в качестве идентификатора учётных данных используется не `token`, замените `token` на заданный вами идентификатор. Подробнее о доступных заголовках — в разделах [«GitlabProjects»](../datasources/types/#gitlabprojects) и [«Системная учётная запись»](../datasources/overview/#системная-учётная-запись). ## Создание действий -Необходимо настроить три действия, которые будут отвечать за создание сервиса из шаблона и их обновление в случае выпуска новых версий шаблона. +Настройте три действия, которые будут отвечать за создание сервиса из шаблона и их обновление в случае выпуска новых версий шаблона. {{< alert level="info" >}} В правилах обновления сущности в поле `параметр сущности` указывайте идентификатор соответствующего параметра ресурса, который хранит информацию о сервисах. -В телах запросов используются идентификаторы полей пользовательской формы, приведённые в инструкции. Если вы задали другие идентификаторы, измените их и в теле запроса. +В телах запросов используются идентификаторы полей пользовательской формы, приведённые в инструкции. +Если вы задали другие идентификаторы, измените их и в теле запроса. {{< /alert >}} ### Действие «Создать проект в GitLab» -У вас должно быть создано действие, которое отвечает за инициализацию нового проекта в GitLab. Оно запускается первым при создании нового сервиса и создаёт проект в GitLab, в который будет помещён сервис, созданный из шаблона. Если действия ещё нет, [создайте его](#создание-действия). +У вас должно быть создано действие, которое отвечает за инициализацию нового проекта в GitLab. +Оно запускается первым при создании нового сервиса и создаёт проект в GitLab, в который будет помещён сервис, созданный из шаблона. +Если действия ещё нет, [создайте его](#создание-действия). -Проверьте, что действие содержит следующие настройки: - -- На вкладке «Основная информация» в поле «Ресурс» выбран ресурс, который содержит информацию о сервисах. - -- На вкладке «Обновление» активирована опция «Обновление параметров сущности» и настроены правила обновления, которые записывают ID, URL и ветку по умолчанию только что созданного проекта в сущность, для которой запускалось действие. +Проверьте, что на вкладке «Основная информация» в поле «Ресурс» выбран ресурс, который содержит информацию о сервисах. +На вкладке «Обновление» должна быть активирована опция «Обновление параметров сущности» и настроены правила обновления, +которые записывают ID, URL и ветку по умолчанию только что созданного проекта в сущность, для которой запускалось действие. Пример правил обновления сущности: @@ -328,19 +364,25 @@ description: Настройка ресурсов, связи, источника ### Действие «Создать репозиторий из шаблона» -У вас должно быть создано действие для клонирования кода из шаблонного репозитория в новый репозиторий сервиса с применением переменных шаблонизации. Это действие будет запускаться после создания проекта в GitLab и заполнять его кодом из шаблона. Если действия ещё нет, [создайте его](#создание-действия). +У вас должно быть создано действие для клонирования кода из шаблонного репозитория в новый репозиторий сервиса с применением переменных шаблонизации. +Это действие будет запускаться после создания проекта в GitLab и заполнять его кодом из шаблона. +Если действия ещё нет, [создайте его](#создание-действия). Проверьте, что действие содержит следующие настройки: -- На вкладке «Основная информация» в поле «Ресурс» выбран ресурс, который содержит информацию о сервисах (действие запускается для сущности сервиса, который нужно обновить). +- На вкладке «Основная информация» в поле «Ресурс» выбран ресурс, который содержит информацию о сервисах (действие запускается для сущности обновляемого сервиса). -- На вкладке «Пользовательская форма» есть параметр «Идентификатор шаблонного репозитория» с идентификатором `template_ddp_slug` (или другим, если это необходимо) типа Entities — будет автоматически подставляться идентификатор сущности шаблона внутри DDP, из которого будет клонироваться код. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Идентификатор». Это позволяет выбрать нужный шаблон из связанных сущностей. Данный параметр можно сделать скрытым. +- На вкладке «Пользовательская форма» есть параметр «Идентификатор шаблонного репозитория» с идентификатором `template_ddp_slug` (или другим) типа Entities — будет автоматически подставляться идентификатор сущности шаблона внутри DDP, из которого будет клонироваться код. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Идентификатор». + Это позволяет выбрать нужный шаблон из связанных сущностей. + Данный параметр можно сделать скрытым. - На вкладке «Обновление» активирована опция «Обновление параметров сущности» и настроено сохранение переменных, использованных при шаблонизации, обратно в сущность, для которой запускалось действие. -Пример правила обновления сущности: - -- Параметр «Переменные использованные при шаблонизации»: используйте источник `{{ toYAML .response.values.merged }}` — данное выражение сохраняет переменные в формате YAML. Эти переменные критически важны для будущего обновления сервиса из шаблона, так как они должны быть применены повторно. Данные получены в качестве ответа на успешное выполнение действия. +Например, в правиле обновления сущности для параметра «Переменные использованные при шаблонизации» используйте источник `{{ toYAML .response.values.merged }}`. +Это выражение сохраняет переменные в формате YAML. +Эти переменные критически важны для будущего обновления сервиса из шаблона, так как они должны быть применены повторно. +Данные получены в качестве ответа на успешное выполнение действия. На вкладке «Обновление» также активирована опция «Создание связей сущности», чтобы действие автоматически устанавливало связь между созданным сервисом и его шаблоном: @@ -358,21 +400,32 @@ description: Настройка ресурсов, связи, источника ### Действие «Обновление сервиса из шаблона» -У вас должно быть создано действие, которое будет использоваться в автоматизации для создания нового запроса на слияние в репозиторий сервиса. Этот запрос на слияние будет содержать изменения из новой версии (нового тега) связанного шаблона. Если действия ещё нет, [создайте его](#создание-действия). +У вас должно быть создано действие, которое будет использоваться в автоматизации для создания нового запроса на слияние в репозиторий сервиса. +Этот запрос на слияние будет содержать изменения из новой версии (нового тега) связанного шаблона. +Если действия ещё нет, [создайте его](#создание-действия). Проверьте, что на вкладке «Основная информация» в поле «Ресурс» выбран ресурс, который содержит информацию о сервисах. Проверьте наличие следующих полей на вкладке «Пользовательская форма»: -- Параметр «Переменные используемые при шаблонизации» с идентификатором `template_values` (или другим, если это необходимо) типа String — он хранит переменные, которые были использованы при изначальной шаблонизации (хранятся в параметре сущности). Значение по умолчанию: `{{ .entity.properties.template_values }}` — использует сохранённые переменные из параметра сущности. Если параметр называется иначе (например, `template_vars`), используйте соответствующий идентификатор. +- Параметр «Переменные используемые при шаблонизации» с идентификатором `template_values` (или другим) типа String — он хранит переменные, которые были использованы при изначальной шаблонизации (хранятся в параметре сущности). + Значение по умолчанию: `{{ .entity.properties.template_values }}` — использует сохранённые переменные из параметра сущности. + Если параметр называется иначе (например, `template_vars`), используйте соответствующий идентификатор. -- Параметр «Версия» с идентификатором `version` (или другим, если это необходимо) типа Entities — получает значение нового тега (версии) из сущности шаблона. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «Последний тег». +- Параметр «Версия» с идентификатором `version` (или другим) типа Entities — получает значение нового тега (версии) из сущности шаблона. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «Последний тег». -- Параметр «Обновляемый репозиторий» с идентификатором `target_project_id` (или другим, если это необходимо) типа String — это ID репозитория сервиса в GitLab, в который создаётся запрос на слияние. Значение по умолчанию: `{{ .entity.properties.project_id }}` — использует ID проекта из параметра сущности. Если параметр, который хранит внутренний ID проекта в GitLab, имеет другой идентификатор, используйте его вместо `project_id`. +- Параметр «Обновляемый репозиторий» с идентификатором `target_project_id` (или другим) типа String — это ID репозитория сервиса в GitLab, в который создаётся запрос на слияние. + Значение по умолчанию: `{{ .entity.properties.project_id }}` — использует ID проекта из параметра сущности. + Если параметр, который хранит внутренний ID проекта в GitLab, имеет другой идентификатор, используйте его вместо `project_id`. -- Параметр «Шаблонный репозиторий» с идентификатором `source_project_id` (или другим, если это необходимо) типа Entities — это ID репозитория шаблона в GitLab. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «ID репозитория». +- Параметр «Шаблонный репозиторий» с идентификатором `source_project_id` (или другим) типа Entities — это ID репозитория шаблона в GitLab. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «ID репозитория». -- Параметр «Ветка обновляемого репозитория» с идентификатором `target_repo_branch` (или другим, если это необходимо) типа String — это основная ветка репозитория сервиса (например, `master` или `main`), куда будет направлен запрос на слияние. При необходимости можете указать любую другую. Значение по умолчанию: `{{ .entity.properties.default_branch }}` — использует ветку по умолчанию из параметра сущности. Если параметр имеет другой идентификатор, используйте его вместо `default_branch`. +- Параметр «Ветка обновляемого репозитория» с идентификатором `target_repo_branch` (или другим) типа String — это основная ветка репозитория сервиса (например, `master` или `main`), куда будет направлен запрос на слияние. + При необходимости можете указать любую другую. + Значение по умолчанию: `{{ .entity.properties.default_branch }}` — использует ветку по умолчанию из параметра сущности. + Если параметр имеет другой идентификатор, используйте его вместо `default_branch`. На вкладке «Конфигурация запроса» тело запроса должно быть настроено примерно таким образом: @@ -389,7 +442,8 @@ values: {{ .template_values | nindent 4 }} В теле запроса: -- `source_branch` — название ветки, содержащей изменения. В качестве примера используется ветка с названием, включающим версию тега. +- `source_branch` — название ветки, содержащей изменения. + В качестве примера используется ветка с названием, включающим версию тега. - `target_branch` — целевая ветка сервиса, куда будет направлен запрос на слияние. - `title` — заголовок запроса на слияние с указанием версии. - `source_project_tag` — тег версии шаблона, из которого берутся изменения. @@ -400,7 +454,10 @@ values: {{ .template_values | nindent 4 }} ### Создание действия -Для создания [действия](../actions/overview/) перейдите в раздел «Самообслуживание», пункт «Действия». Создайте новое действие. Для этого нажмите справа вверху кнопку «Создать». Откроется окно по созданию нового [действия](../actions/overview/) с различными вкладками. +Для создания [действия](../actions/overview/) перейдите в раздел «Самообслуживание», пункт «Действия». +Создайте новое действие. +Для этого нажмите справа вверху кнопку «Создать». +Откроется окно по созданию нового [действия](../actions/overview/) с различными вкладками. #### Вкладка «Основная информация» @@ -416,37 +473,55 @@ values: {{ .template_values | nindent 4 }} #### Вкладка «Пользовательская форма» -На вкладке «Пользовательская форма» настройте поля для заполнения при запуске действия. Параметры, которые необходимо настроить, зависят от действия, которое вы создаёте. +На вкладке «Пользовательская форма» настройте поля для заполнения при запуске действия. +Набор параметров зависит от создаваемого действия. Для действия «Создать проект в GitLab» добавьте параметры: -- Параметр «Название» с идентификатором `name` (или иным при необходимости) типа String — это название нового проекта. Значение по умолчанию: `{{ .entity.name }}` — использует название сущности в DDP. +- Параметр «Название» с идентификатором `name` (или иным при необходимости) типа String — это название нового проекта. + Значение по умолчанию: `{{ .entity.name }}` — использует название сущности в DDP. -- Параметр «Путь» с идентификатором `path` (или иным при необходимости) типа String — это URL-путь до репозитория в GitLab. Значение по умолчанию: `{{ .entity.slug }}` — использует идентификатор сущности в DDP. +- Параметр «Путь» с идентификатором `path` (или иным при необходимости) типа String — это URL-путь до репозитория в GitLab. + Значение по умолчанию: `{{ .entity.slug }}` — использует идентификатор сущности в DDP. -- Параметр «Группа репозиториев» с идентификатором `group` (или иным при необходимости) типа String — ID группы GitLab, где будет создан сервис. Значение по умолчанию: укажите ID группы в GitLab, в которой необходимо создать проект. +- Параметр «Группа репозиториев» с идентификатором `group` (или иным при необходимости) типа String — ID группы GitLab, где будет создан сервис. + В поле «Значение по умолчанию» укажите ID группы в GitLab, в которой будет создан проект. Для действия «Создать репозиторий из шаблона» добавьте параметры: -- Параметр «Идентификатор шаблонного репозитория» с идентификатором `template_ddp_slug` (или иным при необходимости) типа Entities — это идентификатор сущности шаблона внутри DDP, из которого будет клонироваться код. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Идентификатор». Это позволяет выбрать нужный шаблон из связанных сущностей. +- Параметр «Идентификатор шаблонного репозитория» с идентификатором `template_ddp_slug` (или иным при необходимости) типа Entities — это идентификатор сущности шаблона внутри DDP, из которого будет клонироваться код. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Идентификатор». + Это позволяет выбрать нужный шаблон из связанных сущностей. -- Параметр «URL сервисного репозитория» с идентификатором `service_git_url` (или иным при необходимости) типа URL — это URL репозитория, в который будет помещён отрендеренный шаблон. Значение по умолчанию: `{{ .entity.properties.web_url }}` — использует URL сущности сервиса из каталога. Если параметр URL в ресурсе называется иначе, используйте соответствующий идентификатор (например, `{{ .entity.properties.service_url }}`). +- Параметр «URL сервисного репозитория» с идентификатором `service_git_url` (или иным при необходимости) типа URL — это URL репозитория, в который будет помещён отрендеренный шаблон. + Значение по умолчанию: `{{ .entity.properties.web_url }}` — использует URL сущности сервиса из каталога. + Если параметр URL в ресурсе называется иначе, используйте соответствующий идентификатор (например, `{{ .entity.properties.service_url }}`). -- Параметр «URL шаблонного репозитория» с идентификатором `template_git_url` (или иным при необходимости) типа Entities — это URL репозитория шаблона, который используется бэкендом для клонирования. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «URL». +- Параметр «URL шаблонного репозитория» с идентификатором `template_git_url` (или иным при необходимости) типа Entities — это URL репозитория шаблона, который используется бэкендом для клонирования. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «URL». Дополнительные параметры зависят от вашего шаблона и должны быть настроены в соответствии с переменными, используемыми в шаблоне. -Для действия «Обновление сервиса из шаблона» настройте поля для сбора данных, которые нужны бэкенду для создания запроса на слияние. Эти данные будут автоматически заполняться из сущностей ресурса «Сервисы» или связанной с ним сущности из ресурса «Шаблоны»: +Для действия «Обновление сервиса из шаблона» настройте поля для сбора данных, которые нужны бэкенду для создания запроса на слияние. +Эти данные будут автоматически заполняться из сущностей ресурса «Сервисы» или связанной с ним сущности из ресурса «Шаблоны»: -- Параметр «Переменные используемые при шаблонизации» с идентификатором `template_values` (или иным при необходимости) типа String — это переменные, которые были использованы при изначальной шаблонизации (хранятся в параметре сущности). Значение по умолчанию: `{{ .entity.properties.template_values }}` — использует сохранённые переменные из параметра сущности. Если параметр называется иначе (например, `template_vars`), используйте соответствующий идентификатор. +- Параметр «Переменные используемые при шаблонизации» с идентификатором `template_values` (или иным при необходимости) типа String — это переменные, которые были использованы при изначальной шаблонизации (хранятся в параметре сущности). + Значение по умолчанию: `{{ .entity.properties.template_values }}` — использует сохранённые переменные из параметра сущности. + Если параметр называется иначе (например, `template_vars`), используйте соответствующий идентификатор. -- Параметр «Версия» с идентификатором `version` (или иным при необходимости) типа Entities — получает значение нового тега (версии) из сущности шаблона. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «Последний тег». +- Параметр «Версия» с идентификатором `version` (или иным при необходимости) типа Entities — получает значение нового тега (версии) из сущности шаблона. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «Последний тег». -- Параметр «Обновляемый репозиторий» с идентификатором `target_project_id` (или иным при необходимости) типа String — это внутренний ID репозитория сервиса в GitLab, в который создаётся запрос на слияние. Значение по умолчанию: `{{ .entity.properties.project_id }}` — использует ID проекта из параметра сущности. Если параметр ID в ресурсе называется иначе, используйте соответствующий идентификатор. +- Параметр «Обновляемый репозиторий» с идентификатором `target_project_id` (или иным при необходимости) типа String — это внутренний ID репозитория сервиса в GitLab, в который создаётся запрос на слияние. + Значение по умолчанию: `{{ .entity.properties.project_id }}` — использует ID проекта из параметра сущности. + Если параметр ID в ресурсе называется иначе, используйте соответствующий идентификатор. -- Параметр «Шаблонный репозиторий» с идентификатором `source_project_id` (или иным при необходимости) типа Entities — это внутренний ID репозитория шаблона в GitLab. В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «ID репозитория». +- Параметр «Шаблонный репозиторий» с идентификатором `source_project_id` (или иным при необходимости) типа Entities — это внутренний ID репозитория шаблона в GitLab. + В дополнительных настройках укажите: Ресурс: «Шаблоны», Связь: «Шаблоны-Сервисы», Поле: «Параметр», Параметр: «ID репозитория». -- Параметр «Ветка обновляемого репозитория» с идентификатором `target_repo_branch` (или иным при необходимости) типа String — основная ветка репозитория сервиса (например, `master` или `main`), куда будет направлен запрос на слияние. Значение по умолчанию: `{{ .entity.properties.default_branch }}` — использует ветку по умолчанию из параметра сущности. Если идентификатор параметра называется иначе, используйте свой. +- Параметр «Ветка обновляемого репозитория» с идентификатором `target_repo_branch` (или иным при необходимости) типа String — основная ветка репозитория сервиса (например, `master` или `main`), куда будет направлен запрос на слияние. + Значение по умолчанию: `{{ .entity.properties.default_branch }}` — использует ветку по умолчанию из параметра сущности. + Если идентификатор параметра называется иначе, используйте свой. #### Вкладка «Конфигурация запроса» @@ -467,7 +542,8 @@ namespace_id: '{{ .group }}' path: '{{ .path }}' ``` -Это тело запроса передаёт в GitLab API название проекта, ID группы и путь репозитория. Подробнее о настройках — в разделе [«CreateGitlabProject»](../actions/gitlab/creategitlabproject/). +Это тело запроса передаёт в GitLab API название проекта, ID группы и путь репозитория. +Подробнее о настройках — в разделе [«CreateGitlabProject»](../actions/gitlab/creategitlabproject/). Для действия «Создать репозиторий из шаблона» заполните поля: @@ -487,7 +563,8 @@ values: : ``` -Замените `` и `` на имена и значения переменных вашего шаблона. Добавьте отдельную строку для каждой переменной. +Замените `` и `` на имена и значения переменных вашего шаблона. +Добавьте отдельную строку для каждой переменной. В теле запроса: @@ -497,7 +574,8 @@ values: - `targetRepositoryUrl` — URL целевого репозитория сервиса. -- `values` — пары ключ-значение, которые будут использованы для замены переменных в файлах шаблона. Формат и состав этих переменных полностью зависит от того, как настроен ваш шаблон. +- `values` — пары ключ-значение, которые будут использованы для замены переменных в файлах шаблона. + Формат и состав этих переменных полностью зависит от того, как настроен ваш шаблон. Подробнее о настройках — в разделе [«CreateRepositoryFromTemplate»](../actions/gitlab/createrepositoryfromtemplate/). @@ -540,7 +618,8 @@ values: {{ .template_values | nindent 4 }} #### Вкладка «Обновление» -Для действий «Создать проект в GitLab» и «Создать репозиторий из шаблона» активируйте опцию «Обновление параметров сущности» и настройте правила обновления, которые запишут информацию в сущность, для которой запускалось действие. Правила обновления сущности зависят от настраиваемого действия. +Для действий «Создать проект в GitLab» и «Создать репозиторий из шаблона» активируйте опцию «Обновление параметров сущности» и настройте правила обновления, которые запишут информацию в сущность, для которой запускалось действие. +Правила обновления сущности зависят от настраиваемого действия. Для действия «Создать проект в GitLab» используйте идентификаторы соответствующих параметров ресурса: @@ -552,9 +631,11 @@ values: {{ .template_values | nindent 4 }} Идентификаторы источников (`id`, `web_url`, `default_branch`) берутся из спецификации [Projects API GitLab](https://docs.gitlab.com/api/projects/#get-a-single-project). -Для действия «Создать репозиторий из шаблона» используйте идентификатор соответствующего параметра ресурса: - -- Параметр «Переменные использованные при шаблонизации»: используйте источник `{{ toYAML .response.values.merged }}` — данное выражение сохраняет переменные в формате YAML. Эти переменные критически важны для будущего обновления сервиса из шаблона, так как они должны быть применены повторно. Данные получены в качестве ответа на успешное выполнение действия. +Для действия «Создать репозиторий из шаблона» используйте идентификатор соответствующего параметра ресурса. +Для параметра «Переменные использованные при шаблонизации» используйте источник `{{ toYAML .response.values.merged }}`. +Это выражение сохраняет переменные в формате YAML. +Эти переменные критически важны для будущего обновления сервиса из шаблона, так как они должны быть применены повторно. +Данные получены в качестве ответа на успешное выполнение действия. Для действия «Создать репозиторий из шаблона» также активируйте опцию «Создание связей сущности», чтобы действие автоматически устанавливало связь между созданным сервисом и его шаблоном: @@ -574,27 +655,20 @@ values: {{ .template_values | nindent 4 }} На вкладке «Авторизация» настройте учётные данные для выполнения действия. Настройки зависят от действия. -Для действия «Создать проект в GitLab» настройте учётные данные: - -- «Идентификатор»: `token`. - -- «Реквизиты»: укажите реквизиты, которые содержат токен GitLab с необходимыми правами доступа для создания проектов в указанной группе. - -Для действия «Создать репозиторий из шаблона» настройте учётные данные: - -- «Идентификатор»: `password` — реквизиты, которые содержат пароль (токен) GitLab с необходимыми правами доступа к репозиториям. +Для действия «Создать проект в GitLab» настройте учётные данные. +В поле «Идентификатор» укажите `token`, а в поле «Реквизиты» — реквизиты, которые содержат токен GitLab с необходимыми правами доступа для создания проектов в указанной группе. -- «Идентификатор»: `username` — реквизиты, которые содержат GitLab username. +Для действия «Создать репозиторий из шаблона» настройте учётные данные с идентификаторами `password` и `username`. +Для `password` укажите реквизиты, которые содержат пароль (токен) GitLab с необходимыми правами доступа к репозиториям, для `username` — реквизиты, которые содержат имя пользователя GitLab. -Для действия «Обновление сервиса из шаблона» настройте учётные данные: - -- «Идентификатор»: `password` — реквизиты, которые содержат пароль (токен) GitLab с необходимыми правами доступа к репозиториям. - -- «Идентификатор»: `username` — реквизиты, которые содержат GitLab username. +Для действия «Обновление сервиса из шаблона» настройте учётные данные с идентификаторами `password` и `username`. +Для `password` укажите реквизиты, которые содержат пароль (токен) GitLab с необходимыми правами доступа к репозиториям, для `username` — реквизиты, которые содержат имя пользователя GitLab. ## Процесс -У вас должен быть создан процесс, который объединяет действия по созданию проекта в GitLab и созданию сервиса из шаблона в единую последовательную автоматизированную цепочку. Процесс должен последовательно запускать создание проекта в GitLab, а затем создание репозитория из шаблона. Если процесса ещё нет, [создайте его](#создание-процесса). +У вас должен быть создан процесс, который объединяет действия по созданию проекта в GitLab и созданию сервиса из шаблона в единую последовательную автоматизированную цепочку. +Процесс должен последовательно запускать создание проекта в GitLab, а затем создание репозитория из шаблона. +Если процесса ещё нет, [создайте его](#создание-процесса). Проверьте, что на вкладке «Основная информация» в поле «Ресурс» выбран ресурс «Сервисы». @@ -607,7 +681,9 @@ values: {{ .template_values | nindent 4 }} ### Создание процесса -Для создания процесса перейдите в раздел «Самообслуживание», пункт «Процессы». Создайте новый процесс. Для этого справа вверху нажмите кнопку «Создать». +Для создания процесса перейдите в раздел «Самообслуживание», пункт «Процессы». +Создайте новый процесс. +Для этого справа вверху нажмите кнопку «Создать». Откроется окно по созданию нового процесса с различными вкладками. @@ -625,7 +701,9 @@ values: {{ .template_values | nindent 4 }} #### Вкладка «Конфигурация» -На вкладке «Конфигурация» настройте шаги процесса и их порядок выполнения. Названия задач и действий приведены в качестве примера. +На вкладке «Конфигурация» настройте шаги процесса и их порядок выполнения. +Названия задач и действий приведены в качестве примера. +Добавьте следующие элементы: 1. Добавьте элемент типа «Задача» с названием «Создать проект в GitLab» и выберите действие «Создать проект в GitLab» для запуска. 1. Добавьте элемент типа «Задача» с названием «Создать репозиторий из шаблона» и выберите действие «Создать репозиторий из шаблона» для запуска. @@ -640,33 +718,30 @@ values: {{ .template_values | nindent 4 }} ## Автоматизация -У вас должна быть настроена автоматизация, которая запускает действие по созданию запроса на слияние для обновления сервисов при появлении новой версии шаблона. Автоматизация отслеживает изменения параметра «Последний тег» в сущностях ресурса «Шаблоны» и при обнаружении нового тега автоматически запускает действие «Обновление сервиса из шаблона» для всех связанных сервисов. Если автоматизации ещё нет, [создайте её](#создание-автоматизации). +У вас должна быть настроена автоматизация, которая запускает действие по созданию запроса на слияние для обновления сервисов при появлении новой версии шаблона. +Автоматизация отслеживает изменения параметра «Последний тег» в сущностях ресурса «Шаблоны» и при обнаружении нового тега автоматически запускает действие «Обновление сервиса из шаблона» для всех связанных сервисов. +Если автоматизации ещё нет, [создайте её](#создание-автоматизации). ### Проверка автоматизации -На вкладке «Конфигурация» проверьте настройки триггера: - -- «Ресурс»: выбран «Шаблоны». - -- «Условие»: указано `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}` (или аналогичное, если проверка у вас настроена иначе). - -Данное условие срабатывает каждый раз, когда параметр с идентификатором `repository_last_tag` в сущности ресурса «Шаблоны» не равен указанному значению (`v1.0.0`). Условие будет проверяться только один раз при изменении параметра `repository_last_tag`. Если параметр «Последний тег» имеет другой идентификатор (например, `last_tag`), используйте его в условии: `{{ ne .entity.properties.last_tag "v1.0.0" }}`. +На вкладке «Конфигурация» проверьте настройки триггера. +В поле «Ресурс» должно быть выбрано «Шаблоны», а в поле «Условие» — указано `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}` или аналогичное условие, если проверка у вас настроена иначе. -Проверьте настройки выполнения: +Данное условие срабатывает каждый раз, когда параметр с идентификатором `repository_last_tag` в сущности ресурса «Шаблоны» не равен указанному значению (`v1.0.0`). +Условие будет проверяться только один раз при изменении параметра `repository_last_tag`. +Если параметр «Последний тег» имеет другой идентификатор (например, `last_tag`), используйте его в условии: `{{ ne .entity.properties.last_tag "v1.0.0" }}`. -- «Тип выполнения»: выбрано «Действия». +Проверьте настройки выполнения. +В поле «Тип выполнения» должно быть выбрано «Действия», а в поле «Объект выполнения» — действие «Обновление сервиса из шаблона». -- «Объект выполнения»: выбрано действие «Обновление сервиса из шаблона». - -Проверьте, что параметр «Запускать выполнение для связанных ресурсов» включён и настроены связи ресурса: - -- «Ресурс»: выбрано «Шаблоны». - -- «Связь»: выбрана связь «Шаблоны-Сервисы». +Проверьте, что параметр «Запускать выполнение для связанных ресурсов» включён и настроены связи ресурса. +В поле «Ресурс» должно быть выбрано «Шаблоны», а в поле «Связь» — связь «Шаблоны-Сервисы». ### Создание автоматизации -Для создания [автоматизации](../automations) перейдите в раздел «Самообслуживание», пункт «Автоматизации». Создайте автоматизацию. Для этого нажмите справа вверху кнопку «Создать». +Для создания [автоматизации](../automations) перейдите в раздел «Самообслуживание», пункт «Автоматизации». +Создайте автоматизацию. +Для этого нажмите справа вверху кнопку «Создать». Откроется окно по созданию новой автоматизации с различными вкладками. @@ -684,33 +759,29 @@ values: {{ .template_values | nindent 4 }} На вкладке «Конфигурация» настройте логику запуска автоматизации. -Триггер определяет, когда автоматизация должна запускаться. Добавьте новый триггер: - -- «Ресурс»: выберите «Шаблоны». +Триггер определяет, когда автоматизация должна запускаться. +Добавьте новый триггер. +В поле «Ресурс» выберите «Шаблоны», а в поле «Условие» укажите `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}`. -- «Условие»: укажите `{{ ne .entity.properties.repository_last_tag "v1.0.0" }}`. - - {{< alert level="warning" >}} - Используется идентификатор параметра ресурса «Шаблоны», который хранит информацию о последнем теге git-репозитория. Если идентификатор отличается, используйте корректный. - {{< /alert >}} +{{< alert level="warning" >}} +Используется идентификатор параметра ресурса «Шаблоны», который хранит информацию о последнем теге git-репозитория. +Если идентификатор отличается, используйте корректный. +{{< /alert >}} -Данное условие срабатывает каждый раз, когда параметр `repository_last_tag` в сущности ресурса «Шаблоны» не равен указанному значению (`v1.0.0`). Условие будет проверяться только один раз при изменении параметра `repository_last_tag`. +Данное условие срабатывает каждый раз, когда параметр `repository_last_tag` в сущности ресурса «Шаблоны» не равен указанному значению (`v1.0.0`). +Условие будет проверяться только один раз при изменении параметра `repository_last_tag`. {{< alert level="info" >}} -Если планируется создание нескольких автоматизаций, каждая из которых должна реагировать на изменения параметров сущностей одного и того же ресурса, рекомендуется указывать условие в формате `{{ and (ne .entity.properties.repository_last_tag "v1.0.0") (eq .entity.slug "example") }}` для того, чтобы дополнительно фильтровать, какая из автоматизаций будет запускаться в каждом конкретном случае. Без добавления условия `(eq .entity.slug "example")` каждая из автоматизаций будет реагировать на изменения каждой сущности. +Если планируется создание нескольких автоматизаций, каждая из которых должна реагировать на изменения параметров сущностей одного и того же ресурса, рекомендуется указывать условие в формате `{{ and (ne .entity.properties.repository_last_tag "v1.0.0") (eq .entity.slug "example") }}` для того, чтобы дополнительно фильтровать, какая из автоматизаций будет запускаться в каждом конкретном случае. +Без добавления условия `(eq .entity.slug "example")` каждая из автоматизаций будет реагировать на изменения каждой сущности. {{< /alert >}} -Настройте выполнение действия: +Настройте выполнение действия. +В поле «Тип выполнения» выберите «Действия», а в поле «Объект выполнения» — действие «Обновление сервиса из шаблона». -- «Тип выполнения»: выберите «Действия». - -- «Объект выполнения»: выберите действие «Обновление сервиса из шаблона». - -Автоматизация просматривает изменения в сущности ресурса «Шаблоны», но действие будет обновлять сущности ресурса «Сервисы», которые связаны с шаблоном, в котором произошло обновление параметра `repository_last_tag`. Включите параметр «Запускать выполнение для связанных ресурсов» и настройте связи ресурса: - -- «Ресурс»: выберите «Шаблоны». - -- «Связь»: выберите связь «Шаблоны-Сервисы». +Автоматизация просматривает изменения в сущности ресурса «Шаблоны», но действие будет обновлять сущности ресурса «Сервисы», которые связаны с шаблоном, в котором произошло обновление параметра `repository_last_tag`. +Включите параметр «Запускать выполнение для связанных ресурсов» и настройте связи ресурса. +В поле «Ресурс» выберите «Шаблоны», а в поле «Связь» — связь «Шаблоны-Сервисы». При обновлении тега в ресурсе «Шаблоны» система найдёт все связанные с этим шаблоном сущности ресурса «Сервисы» и запустит для каждой из них действие «Обновление сервиса из шаблона», создавая запрос на слияние с изменениями из новой версии шаблона. @@ -722,8 +793,13 @@ values: {{ .template_values | nindent 4 }} 1. Перейдите во вкладку «Каталог» в ресурс «Сервисы». 1. В правом верхнем углу нажмите кнопку «Создать». -1. В открывшемся окне во вкладке «Основная информация» заполните требуемые поля. Если настройки были произведены в соответствии с данной инструкцией, заполнение данных в других вкладках не требуется. Данные будут заполнены автоматически в дальнейшем. +1. В открывшемся окне во вкладке «Основная информация» заполните требуемые поля. + Если настройки были произведены в соответствии с данной инструкцией, заполнение данных в других вкладках не требуется. + Данные будут заполнены автоматически в дальнейшем. 1. Справа от появившейся записи о новом сервисе нажмите на синюю кнопку с тремя вертикальными точками и выберите пункт «Запустить процесс». 1. В выпадающем списке выберите процесс `Создание сервиса из шаблона`. 1. При необходимости заполните переменные шаблона и запустите процесс. -1. При корректных настройках сервис будет создан. При наличии обновлений шаблона для сервиса будут создаваться запросы на слияние с изменениями. Проверить корректность создания можно, перейдя в него и открыв вкладку «Запуски действий». Все [действия](../actions/overview/) должны быть в статусе `Success`. +1. При корректных настройках сервис будет создан. + При наличии обновлений шаблона для сервиса будут создаваться запросы на слияние с изменениями. + Проверить корректность создания можно, перейдя в него и открыв вкладку «Действия» и таблицу «История выполнения». + Все [действия](../actions/overview/) должны быть в статусе `Success`. diff --git a/content/documentation/admin/examples/template-first-pack.md b/content/documentation/admin/examples/template-first-pack.md new file mode 100644 index 00000000..3ab1aa3e --- /dev/null +++ b/content/documentation/admin/examples/template-first-pack.md @@ -0,0 +1,220 @@ +--- +title: Creating and publishing a microservice template +weight: 40 +description: Step-by-step creation of a Go service template pack for DDP — the manifest, parameters, files, validation with the ddp-template utility, publishing to a container registry, synchronization, and creating a microservice from the template. +--- + +This guide describes creating an HTTP service template in Go and publishing it to the portal's template registry. +As a result, the template is shown in the gallery of the "Create microservice" Home page section, and the repository created from it contains code, CI, and a Helm chart. + +## Before you begin + +To follow this guide, prepare the following: + +- A container registry with OCI Distribution Spec v2, for example, `registry.example.com`, and a token with write permissions for the `ddp-templates/go-service` repository. +- The `ddp-template` utility. +- A connection to this registry in the portal's template registry with the `ddp-templates` repository prefix. + Connecting a registry is described in the [Template registry](../templates/registry/#connecting-a-registry) section. + +## Pack structure + +Create a pack directory with the following files: + +```text +go-service/ + template.yaml + values.yaml + .templateignore + .editorconfig + .gitlab-ci.yml + go.mod + cmd/{{ .slug }}/main.go + deploy/helm/Chart.yaml + deploy/helm/values.yaml + deploy/helm/templates/deployment.yaml +``` + +The `cmd/{{ .slug }}` directory is named after the microservice identifier. + +### Manifest + +The `template.yaml` manifest sets the template identifier and the upgrade rules. +CI and the Helm chart belong to the template and are overwritten on upgrade, while `.editorconfig` is added only if it is missing from the repository: + +```yaml +id: go-service +name: Go service +description: HTTP service on Go with GitLab CI and Helm chart +language: Go +tags: + - http + - helm +update: + strategy: selective_additive + overwrite: + - .gitlab-ci.yml + - deploy/** + addIfMissing: + - .editorconfig +``` + +The `id` value matches the name of the pack repository in the registry: `ddp-templates/go-service`. + +### Parameters + +The `values.yaml` file describes the template parameters. +The identifier, microservice name, and system are filled in from the run context and are not shown in the form; the user enters the port at the "Parameters" step: + +```yaml +type: object +required: + - slug + - name + - system + - port +properties: + slug: + type: string + title: Service identifier + x-ddp-from: context.microservice.slug + name: + type: string + title: Service name + x-ddp-from: context.microservice.name + system: + type: string + title: System + x-ddp-from: context.system.slug + port: + type: integer + title: HTTP port + description: Port the service listens on + default: 8080 +``` + +### Repository files + +The repository files use the template parameters. The `go.mod` file: + +```go-html-template +module {{ .slug }} + +go 1.23 +``` + +The `cmd/{{ .slug }}/main.go` file: + +```go-html-template +package main + +import ( + "log" + "net/http" +) + +func main() { + // Service {{ .name }} of system {{ .system }}. + log.Fatal(http.ListenAndServe(":{{ .port }}", nil)) +} +``` + +The `deploy/helm/values.yaml` file: + +```go-html-template +name: {{ .slug }} +system: {{ .system }} +port: {{ .port }} +``` + +The `deploy/helm/templates/deployment.yaml` file uses the Helm `{{ .Values }}` syntax. +To prevent the portal from processing it as a template, add the path to `.templateignore`: + +```text +# Helm templates are copied as is. +deploy/helm/templates/** +``` + +## Validating the pack + +Validate the pack with the `ddp-template` utility: + +```shell +ddp-template lint ./go-service +``` + +The command checks the manifest, the parameter schema, `.templateignore`, and the upgrade path lists, and performs a trial render. +Exit code `0` means there are no errors. + +To see the render result, create a `test-values.yaml` file with test values and render the pack: + +```yaml +slug: billing-api +name: Billing API +system: billing +port: 8080 +``` + +```shell +ddp-template render ./go-service --values ./test-values.yaml --output ./render-out +``` + +The `./render-out` directory will contain the repository files: `cmd/billing-api/main.go`, `go.mod` with `module billing-api`, and the unchanged Helm templates. + +## Publishing + +Publish version `1.0.0` to the container registry: + +```shell +export DDP_TEMPLATE_REGISTRY_TOKEN= +ddp-template publish ./go-service --version 1.0.0 \ + --registry registry.example.com \ + --repository-prefix ddp-templates +``` + +Where `` is a container registry token with write permissions. + +The command outputs JSON with the `templateId`, `version`, `ociRef`, and `sha256` fields. +A published version cannot be overwritten. To make changes, publish a new version. + +## Synchronizing + +The portal loads the version during the next template registry sync. To load the version immediately, follow these steps: + +1. Go to "Administration" → "Integrations" → "Templates" → "Sync runs". +1. Click "Sync" and wait for the "Success" status. +1. On the "Templates" tab, find `go-service` version `1.0.0` and make sure it has the "available" status and the "Latest" tag. + +If the "Repository IDs" field of the connection is filled in, add `go-service` to it before syncing. + +If the version has the "invalid" status, the reason is shown in the "Status reason" column. +Fix the pack and publish version `1.0.1`. + +## Binding processes + +Bind processes to the template in the Home page mapping rules: + +1. Go to "Administration" → "Directories" → "Mapping rules" and open the default set. +1. On the "Catalog mapping" tab, expand "Microservices" → "Template actions" and click "Add template". +1. Select the `go-service` template and the action processes: + - "Create microservice": "Create microservice from template" + - "Deploy microservice to an environment": "Deploy microservice to an environment" + - "Delete microservice from an environment": "Delete microservice from an environment" + - "Upgrade microservice from template": "Upgrade microservice from template" +1. Click "Save". + +## Verifying the result + +Create a microservice from the template: + +1. Open the Home page → "Create microservice" and select the "Go service" card. +1. At the "Service" step, enter the name `Billing API`, select a system and a GitLab namespace, and click "Next". +1. At the "Parameters" step, check that only the "HTTP port" field is shown, and click "Create microservice". +1. In the "Run process" dialog, click "Run" and wait for the process to complete. + +The template works if the following conditions are met: + +- The `billing-api` project with the `cmd/billing-api/main.go` and `.ddp/template.lock.yaml` files is created in GitLab. +- The lock file contains `templateId: go-service` and `templateVersion: 1.0.0`. +- On the microservice card on the Home page, the "Template" and "Version" fields contain `go-service` and `1.0.0`. + +Releasing the next template version and upgrading microservices are described in the [template version release example](template-release-update/). diff --git a/content/documentation/admin/examples/template-first-pack.ru.md b/content/documentation/admin/examples/template-first-pack.ru.md index aed47373..711ff1a6 100644 --- a/content/documentation/admin/examples/template-first-pack.ru.md +++ b/content/documentation/admin/examples/template-first-pack.ru.md @@ -4,7 +4,8 @@ weight: 40 description: Пошаговое создание пакета шаблона Go-сервиса для DDP — манифест, параметры, файлы, проверка утилитой ddp-template, публикация в хранилище образов, синхронизация и создание микросервиса из шаблона. --- -Инструкция описывает создание шаблона HTTP-сервиса на Go и его публикацию в реестр шаблонов портала. В результате шаблон отображается в галерее раздела главной «Создать микросервис», а созданный из него репозиторий содержит код, CI и Helm-чарт. +Инструкция описывает создание шаблона HTTP-сервиса на Go и его публикацию в реестр шаблонов портала. +В результате шаблон отображается в галерее раздела главной страницы «Создать микросервис», а созданный из него репозиторий содержит код, CI и Helm-чарт. ## Перед началом работы @@ -12,7 +13,8 @@ description: Пошаговое создание пакета шаблона Go- - хранилище образов контейнеров с OCI Distribution Spec v2, например `registry.example.com`, и токен с правами на запись в репозиторий `ddp-templates/go-service`; - утилиту `ddp-template`; -- подключение этого хранилища в реестре шаблонов портала с префиксом репозиториев `ddp-templates`. Порядок подключения описан в разделе [«Реестр шаблонов»](../templates/registry/#подключение-хранилища). +- подключение этого хранилища в реестре шаблонов портала с префиксом репозиториев `ddp-templates`. + Порядок подключения описан в разделе [«Реестр шаблонов»](../templates/registry/#подключение-хранилища). ## Структура пакета @@ -36,7 +38,8 @@ go-service/ ### Манифест -Манифест `template.yaml` задаёт идентификатор шаблона и правила обновления. CI и Helm-чарт принадлежат шаблону и перезаписываются при обновлении, а `.editorconfig` добавляется, только если его нет в репозитории: +Манифест `template.yaml` задаёт идентификатор шаблона и правила обновления. +CI и Helm-чарт принадлежат шаблону и перезаписываются при обновлении, а `.editorconfig` добавляется, только если его нет в репозитории: ```yaml id: go-service @@ -59,7 +62,8 @@ update: ### Параметры -Файл `values.yaml` описывает параметры шаблона. Идентификатор, название микросервиса и система заполняются из контекста запуска и не отображаются в форме; порт пользователь вводит на шаге «Параметры»: +Файл `values.yaml` описывает параметры шаблона. +Идентификатор, название микросервиса и система заполняются из контекста запуска и не отображаются в форме; порт пользователь вводит на шаге «Параметры»: ```yaml type: object @@ -122,7 +126,8 @@ system: {{ .system }} port: {{ .port }} ``` -Файл `deploy/helm/templates/deployment.yaml` использует синтаксис Helm `{{ .Values }}`. Чтобы портал не обрабатывал его как шаблон, добавьте путь в `.templateignore`: +Файл `deploy/helm/templates/deployment.yaml` использует синтаксис Helm `{{ .Values }}`. +Чтобы портал не обрабатывал его как шаблон, добавьте путь в `.templateignore`: ```text # Helm templates are copied as is. @@ -137,7 +142,8 @@ deploy/helm/templates/** ddp-template lint ./go-service ``` -Команда проверяет манифест, схему параметров, `.templateignore`, списки путей обновления и выполняет пробную отрисовку. Код завершения `0` означает, что ошибок нет. +Команда проверяет манифест, схему параметров, `.templateignore`, списки путей обновления и выполняет пробную отрисовку. +Код завершения `0` означает, что ошибок нет. Чтобы посмотреть результат отрисовки, создайте файл `test-values.yaml` с тестовыми значениями и отрисуйте пакет: @@ -167,7 +173,8 @@ ddp-template publish ./go-service --version 1.0.0 \ Где `` — токен хранилища образов с правами на запись. -Команда выводит JSON с полями `templateId`, `version`, `ociRef` и `sha256`. Опубликованную версию перезаписать нельзя: для изменений публикуйте новую версию. +Команда выводит JSON с полями `templateId`, `version`, `ociRef` и `sha256`. +Опубликованную версию перезаписать нельзя. Для изменений публикуйте новую версию. ## Синхронизация @@ -179,11 +186,12 @@ ddp-template publish ./go-service --version 1.0.0 \ Если поле «Идентификаторы репозиториев» подключения заполнено, добавьте в него `go-service` перед синхронизацией. -Если у версии статус «некорректна», причина указана в колонке «Причина статуса». Исправьте пакет и опубликуйте версию `1.0.1`. +Если у версии статус «некорректна», причина указана в колонке «Причина статуса». +Исправьте пакет и опубликуйте версию `1.0.1`. ## Привязка процессов -Привяжите к шаблону процессы в правилах маппинга главной: +Привяжите к шаблону процессы в правилах маппинга главной страницы: 1. Перейдите в раздел «Администрирование» → «Справочники» → «Правила маппинга» и откройте набор по умолчанию. 1. На вкладке «Маппинг каталога» раскройте «Микросервисы» → «Действия по шаблонам» и нажмите «Добавить шаблон». @@ -198,7 +206,7 @@ ddp-template publish ./go-service --version 1.0.0 \ Создайте микросервис из шаблона: -1. Откройте главную → «Создать микросервис» и выберите карточку «Go service». +1. Откройте главную страницу → «Создать микросервис» и выберите карточку «Go service». 1. На шаге «Сервис» заполните название `Billing API`, выберите систему и пространство GitLab и нажмите «Далее». 1. На шаге «Параметры» проверьте, что отображается только поле «HTTP port», и нажмите «Создать микросервис». 1. В окне «Запустить процесс» нажмите «Запустить» и дождитесь завершения процесса. @@ -207,6 +215,6 @@ ddp-template publish ./go-service --version 1.0.0 \ - в GitLab создан проект `billing-api` с файлами `cmd/billing-api/main.go` и `.ddp/template.lock.yaml`; - в lock-файле указаны `templateId: go-service` и `templateVersion: 1.0.0`; -- в карточке микросервиса на главной поля «Шаблон» и «Версия» содержат `go-service` и `1.0.0`. +- в карточке микросервиса на главной странице поля «Шаблон» и «Версия» содержат `go-service` и `1.0.0`. -Выпуск следующей версии шаблона и обновление микросервисов описаны в примере [«Выпуск новой версии шаблона и обновление микросервисов»](template-release-update/). +Выпуск следующей версии шаблона и обновление микросервисов описаны [в примере выпуска версии шаблона](template-release-update/). diff --git a/content/documentation/admin/examples/template-release-update.md b/content/documentation/admin/examples/template-release-update.md new file mode 100644 index 00000000..c9eb24d2 --- /dev/null +++ b/content/documentation/admin/examples/template-release-update.md @@ -0,0 +1,130 @@ +--- +title: Releasing a new template version and upgrading microservices +weight: 41 +description: Releasing a new DDP microservice template version and carrying the changes over to microservice repositories — local upgrade check, manual upgrade with a button, automatic upgrade, and resolving conflicts. +--- + +This guide describes releasing version `1.1.0` of the `go-service` template and upgrading the microservices created from version `1.0.0`. +In the new version, CI changes and a `.dockerignore` file is added. +As a result, merge requests with the template changes are opened in the microservice repositories, and after they are merged, the microservices' template version in the catalog becomes `1.1.0`. + +This guide continues the [Creating and publishing a microservice template](template-first-pack/) example. + +## Before you begin + +To follow this guide, prepare the following: + +- The `go-service` template version `1.0.0` in the template registry and microservices created from it. +- The "Upgrade microservice from template" process bound to the template in the "Template actions" block of the mapping rules. +- The `edit:template-registries` permission to change the template registry settings. + +## Preparing a new version + +Make changes to the pack: + +1. Change `.gitlab-ci.yml`, for example, add a test job. +1. Create a `.dockerignore` file. +1. Add `.dockerignore` to the `update.addIfMissing` list of the manifest: + + ```yaml + update: + strategy: selective_additive + overwrite: + - .gitlab-ci.yml + - deploy/** + addIfMissing: + - .editorconfig + - .dockerignore + ``` + +1. Validate the pack with the `ddp-template lint ./go-service` command. + +Files that are not included in `update.overwrite` and `update.addIfMissing`, for example, `cmd/{{ .slug }}/main.go`, are not changed on upgrade, so developers' changes to these files are preserved. + +## Checking the upgrade on a copy of a microservice + +Before publishing, check which files the upgrade will change in an existing microservice. +Copy the `values` section of the microservice's `.ddp/template.lock.yaml` lock file to a `service-values.yaml` file and render the new version, simulating the upgrade strategy: + +```shell +ddp-template render ./go-service \ + --values ./service-values.yaml \ + --use-overwrite \ + --output ./render-out +``` + +The values of parameters with the `x-ddp-from` annotation are already written to the lock file, so the command renders the files with the microservice's data. + +## Publishing and synchronizing + +Publish version `1.1.0` and load it into the portal: + +1. Publish the version: + + ```shell + ddp-template publish ./go-service --version 1.1.0 \ + --registry registry.example.com \ + --repository-prefix ddp-templates + ``` + +1. Go to "Administration" → "Integrations" → "Templates" → "Sync runs", click "Sync", and wait for the "Success" status. +1. On the "Templates" tab, make sure the "Latest" tag marks version `1.1.0`. + +## Upgrading manually + +Upgrade a single microservice with the button on its card: + +1. Open the Home page → "Microservices" and select a microservice created from `go-service`. +1. On the "Overview" tab, in the "Version 1.1.0 available" block, click "Upgrade". +1. In the "Run process" dialog, click "Run" and wait for the process to complete in the "My activities" panel. +1. Open the microservice project in GitLab and find the `Upgrade go-service to 1.1.0` merge request from the `ddp/template-upgrade-1.1.0` branch. + +The merge request contains the changed `.gitlab-ci.yml`, the new `.dockerignore`, and the lock file with version `1.1.0`. +If `.dockerignore` already existed in the repository, it is not changed. + +Merge the merge request. +After the version reconciliation interval, the "Version" field on the microservice card changes to `1.1.0`, and the "Version available" block disappears. +Version reconciliation runs if an automation user is set in the registry settings; without it, the version in the catalog is updated the next time the upgrade process runs. + +## Upgrading automatically + +Automatic upgrade opens merge requests in all of the template's microservices without clicking a button. +Configure it before publishing the next version. + +Configure the automation user: + +1. Create a service user, for example, `template-bot`, and fill in the GitLab token and username in its profile. +1. Go to "Administration" → "Integrations" → "Templates" → "Settings". +1. Select the user in the "Automation user" field. +1. Set "Upgrade queue rate limit" to at least the number of the template's microservices, for example, `20`, and save the settings. + +Enable automatic upgrade for the microservices. +To do this, open the microservice entity in the catalog and set the "Microservice template update policy" property to "Auto review". + +After the next version, for example, `1.2.0`, is published and synchronized, the portal runs the upgrade process for each microservice with the "Auto review" policy on behalf of the automation user. +Merge requests are created the same way as with a manual upgrade. + +Automatic upgrade does not run for a microservice if its repository has an open merge request with an upgrade to the previous version. +Merge or close that merge request and upgrade the microservice with the "Upgrade" button. + +## Conflicts and manual changes + +The `selective_additive` strategy overwrites `.gitlab-ci.yml` and the `deploy/**` files entirely. +If developers changed these files in the repository, their changes are replaced with the template version in the merge request; review the changes before merging. + +To preserve developers' changes in template files, set the `merge` strategy for the microservice: + +1. Open the microservice entity in the catalog. +1. Set the "Microservice template upgrade strategy" property to `merge`. +1. Run the upgrade with the "Upgrade" button. + +With the `merge` strategy, the portal merges the template changes with the changes in the repository. +If the changes overlap, the upgrade fails with the `merge_conflict` error listing the files, and the repository is not changed. +In this case, switch back to the `selective_additive` strategy, run the upgrade, and move the developers' changes to the merge request branch manually. + +## Deleting files from a template + +The upgrade does not delete files. +If a file is deleted or renamed in a new template version, the old file remains in the microservice repositories. + +List the files that are no longer used in the template version description, and delete them in the upgrade merge request branch before merging it. diff --git a/content/documentation/admin/examples/template-release-update.ru.md b/content/documentation/admin/examples/template-release-update.ru.md index 9a3efbca..885ddf1a 100644 --- a/content/documentation/admin/examples/template-release-update.ru.md +++ b/content/documentation/admin/examples/template-release-update.ru.md @@ -4,8 +4,9 @@ weight: 41 description: Выпуск новой версии шаблона микросервиса DDP и перенос изменений в репозитории микросервисов — локальная проверка обновления, ручное обновление кнопкой, автоматическое обновление и разбор конфликтов. --- -Инструкция описывает выпуск версии `1.1.0` шаблона `go-service` и обновление микросервисов, созданных из версии `1.0.0`. В новой версии меняется CI и добавляется файл `.dockerignore`. -В результате в репозиториях микросервисов открываются запросы на слияние с изменениями шаблона, а после их принятия версия шаблона микросервисов в каталоге становится `1.1.0`. +Инструкция описывает выпуск версии `1.1.0` шаблона `go-service` и обновление микросервисов, созданных из версии `1.0.0`. +В новой версии меняется CI и добавляется файл `.dockerignore`. +В результате в репозиториях микросервисов открываются запросы на слияние (Merge Request) с изменениями шаблона, а после их принятия версия шаблона микросервисов в каталоге становится `1.1.0`. Инструкция продолжает пример [«Создание и публикация шаблона микросервиса»](template-first-pack/). @@ -38,11 +39,12 @@ description: Выпуск новой версии шаблона микросе 1. Проверьте пакет командой `ddp-template lint ./go-service`. -Файлы, которые не входят в `update.overwrite` и `update.addIfMissing`, например `cmd/{{ .slug }}/main.go`, при обновлении не изменяются: изменения разработчиков в этих файлах сохраняются. +Файлы, которые не входят в `update.overwrite` и `update.addIfMissing`, например `cmd/{{ .slug }}/main.go`, при обновлении не изменяются, поэтому изменения разработчиков в этих файлах сохраняются. ## Проверка обновления на копии микросервиса -Перед публикацией проверьте, какие файлы изменит обновление в существующем микросервисе. Скопируйте раздел `values` lock-файла `.ddp/template.lock.yaml` микросервиса в файл `service-values.yaml` и отрисуйте новую версию с имитацией стратегии обновления: +Перед публикацией проверьте, какие файлы изменит обновление в существующем микросервисе. +Скопируйте раздел `values` lock-файла `.ddp/template.lock.yaml` микросервиса в файл `service-values.yaml` и отрисуйте новую версию с имитацией стратегии обновления: ```shell ddp-template render ./go-service \ @@ -72,19 +74,22 @@ ddp-template render ./go-service \ Обновите один микросервис кнопкой в карточке: -1. Откройте главную → «Микросервисы» и выберите микросервис, созданный из `go-service`. +1. Откройте главную страницу → «Микросервисы» и выберите микросервис, созданный из `go-service`. 1. На вкладке «Справка» в блоке «Доступна версия 1.1.0» нажмите «Обновить». 1. В окне «Запустить процесс» нажмите «Запустить» и дождитесь завершения процесса в панели «Мои активности». 1. Откройте проект микросервиса в GitLab и найдите запрос на слияние `Upgrade go-service to 1.1.0` из ветки `ddp/template-upgrade-1.1.0`. -Запрос на слияние содержит изменённый `.gitlab-ci.yml`, новый `.dockerignore` и lock-файл с версией `1.1.0`. Если `.dockerignore` уже был в репозитории, он не изменяется. +Запрос на слияние содержит изменённый `.gitlab-ci.yml`, новый `.dockerignore` и lock-файл с версией `1.1.0`. +Если `.dockerignore` уже был в репозитории, он не изменяется. -Примите запрос на слияние. Через интервал сверки версии поле «Версия» в карточке микросервиса примет значение `1.1.0`, а блок «Доступна версия» исчезнет. +Примите запрос на слияние. +Через интервал сверки версии поле «Версия» в карточке микросервиса примет значение `1.1.0`, а блок «Доступна версия» исчезнет. Сверка версии выполняется, если в настройках реестра задан пользователь автоматизации; без него версия в каталоге обновится при следующем запуске процесса обновления. ## Автоматическое обновление -Автоматическое обновление открывает запросы на слияние во всех микросервисах шаблона без нажатия кнопки. Настройте его до публикации следующей версии. +Автоматическое обновление открывает запросы на слияние во всех микросервисах шаблона без нажатия кнопки. +Настройте его до публикации следующей версии. Настройте пользователя автоматизации: @@ -93,15 +98,19 @@ ddp-template render ./go-service \ 1. Выберите пользователя в поле «Пользователь автоматизации». 1. Задайте «Лимит очереди обновлений» не меньше числа микросервисов шаблона, например `20`, и сохраните настройки. -Включите автоматическое обновление для микросервисов: откройте сущность микросервиса в каталоге и установите параметр «Политика обновления шаблона» в значение «Ревью автоматически». +Включите автоматическое обновление для микросервисов. +Для этого откройте сущность микросервиса в каталоге и установите параметр «Политика обновления шаблона» в значение «Ревью автоматически». -После публикации и синхронизации следующей версии, например `1.2.0`, портал запустит процесс обновления для каждого микросервиса с политикой «Ревью автоматически» от имени пользователя автоматизации. Запросы на слияние создаются так же, как при ручном обновлении. +После публикации и синхронизации следующей версии, например `1.2.0`, портал запустит процесс обновления для каждого микросервиса с политикой «Ревью автоматически» от имени пользователя автоматизации. +Запросы на слияние создаются так же, как при ручном обновлении. -Автоматическое обновление не запускается для микросервиса, если в его репозитории открыт запрос на слияние с обновлением до предыдущей версии. Примите или закройте такой запрос на слияние и обновите микросервис кнопкой «Обновить». +Автоматическое обновление не запускается для микросервиса, если в его репозитории открыт запрос на слияние с обновлением до предыдущей версии. +Примите или закройте такой запрос на слияние и обновите микросервис кнопкой «Обновить». ## Конфликты и ручные изменения -Стратегия `selective_additive` перезаписывает `.gitlab-ci.yml` и файлы `deploy/**` целиком. Если разработчики изменили эти файлы в репозитории, их изменения будут заменены версией шаблона в запросе на слияние; проверьте изменения перед принятием. +Стратегия `selective_additive` перезаписывает `.gitlab-ci.yml` и файлы `deploy/**` целиком. +Если разработчики изменили эти файлы в репозитории, их изменения будут заменены версией шаблона в запросе на слияние; проверьте изменения перед принятием. Чтобы сохранить изменения разработчиков в файлах шаблона, задайте для микросервиса стратегию `merge`: @@ -109,11 +118,13 @@ ddp-template render ./go-service \ 1. Установите параметр «Стратегия обновления шаблона» в значение `merge`. 1. Запустите обновление кнопкой «Обновить». -При стратегии `merge` портал сливает изменения шаблона с изменениями в репозитории. Если изменения пересекаются, обновление завершается ошибкой `merge_conflict` со списком файлов, и репозиторий не изменяется. +При стратегии `merge` портал сливает изменения шаблона с изменениями в репозитории. +Если изменения пересекаются, обновление завершается ошибкой `merge_conflict` со списком файлов, и репозиторий не изменяется. В этом случае верните стратегию `selective_additive`, запустите обновление и перенесите изменения разработчиков в ветку запроса на слияние вручную. ## Удаление файлов из шаблона -Обновление не удаляет файлы. Если в новой версии шаблона файл удалён или переименован, старый файл остаётся в репозиториях микросервисов. +Обновление не удаляет файлы. +Если в новой версии шаблона файл удалён или переименован, старый файл остаётся в репозиториях микросервисов. -Опишите в описании версии шаблона, какие файлы нужно удалить, и удалите их в ветке запроса на слияние с обновлением до его принятия. +Перечислите в описании версии шаблона файлы, которые больше не используются, и удалите их в ветке запроса на слияние с обновлением до его принятия. diff --git a/content/documentation/admin/external-services.md b/content/documentation/admin/external-services.md index 00ceccb5..66a528ef 100644 --- a/content/documentation/admin/external-services.md +++ b/content/documentation/admin/external-services.md @@ -13,7 +13,7 @@ Configure external services under "Administration" → "External services". An external service has the following parameters: -| Parameter | Description | +| Name | Description | |-----------|-------------| | "Name" | External service name displayed in the interface | | "Identifier" | Unique human-readable identifier (slug) | @@ -23,52 +23,65 @@ An external service has the following parameters: | "Credentials" | Available credentials, such as tokens, that can be included in requests | | "Headers" | HTTP headers automatically added to requests | | "Disable SSL verification" | Disables verification of the external service's SSL certificate, for example when using self-signed certificates. Instead, add the required certificates to [trusted certificates](../trusted-certificates/) | -| "System Account" | Account used for scheduled jobs such as data source synchronization and status checks | +| "System Account" | Account used for scheduled jobs such as datasource synchronization and status checks | ## Using external services -External services can be connected to the following DDP (portal) objects: +External services can be connected to the following Deckhouse Development Portal (DDP, portal) objects: -- actions; -- widgets; -- data sources; -- entity status checks. +- Actions +- Widgets +- Datasources +- Entity status checks Connect a service on the "Authorization" tab in the settings of the corresponding object. -Each object can explicitly override parameters configured for the external service. For example, if an external service contains an authentication token but an action requires different credentials, specify alternative values. Only the specified parameter is overridden; all other values come from the external service configuration. +Each object can explicitly override parameters configured for the external service. +For example, if an external service contains an authentication token but an action requires different credentials, specify alternative values. +Only the specified parameter is overridden; all other values come from the external service configuration. ## Object-specific behavior +The behavior of external services depends on the object they are connected to. + ### Actions +External services are connected to actions as follows: + - Multiple external services can be connected to one action. - One service can be selected as the default. - The "System Account" parameter is not used for actions. -- When running an action, you can select the external service to use. If you do not select a service, the default service is used. If no default is configured, the first external service in the list is used. +- When running an action, you can select the external service to use. + If you do not select a service, the default service is used. + If no default is configured, the first external service in the list is used. ### Widgets +External services are connected to widgets as follows: + - Multiple external services can be connected to one widget. - One service can be selected as the default. - The "System Account" parameter is not used for widgets. -### Data sources +### Datasources -- Only one external service can be connected. -- If the service has a system account, it is used by default during synchronization. +Only one external service can be connected to a datasource. +If the service has a system account, it is used by default during synchronization. ### Status checks -- One external service can be assigned to a status check. -- If the service has a system account, it is used for automatic checks. +One external service can be assigned to a status check. +If the service has a system account, it is used for automatic checks. ## Authorization headers for external services -When configuring an external service, specify the HTTP headers required for authentication. The following sections list supported external services, authentication methods, and required headers. +When configuring an external service, specify the HTTP headers required for authentication. +The following sections list supported external services, authentication methods, and required headers. {{< alert level="info" >}} -The examples below show possible authentication methods for each service. Some services may support other methods. The portal supports any method that can be passed through HTTP headers. +The examples below show possible authentication methods for each service. +Some services may support other methods. +The portal supports any method that can be passed through HTTP headers. {{< /alert >}} ### CodeScoring diff --git a/content/documentation/admin/external-services.ru.md b/content/documentation/admin/external-services.ru.md index bb22e158..3ef0d461 100644 --- a/content/documentation/admin/external-services.ru.md +++ b/content/documentation/admin/external-services.ru.md @@ -27,7 +27,7 @@ weight: 72 ## Использование внешних сервисов -Внешние сервисы могут быть подключены к различным объектам DDP (портала): +Внешние сервисы могут быть подключены к различным объектам Deckhouse Development Portal (DDP, портала): - действиям; - виджетам; @@ -36,39 +36,52 @@ weight: 72 Подключение сервиса выполняется на вкладке «Авторизация» в настройках соответствующего объекта. -Для каждого объекта можно в явном виде переопределить параметры, заданные во внешнем сервисе. Например, если внешний сервис содержит токен авторизации, но в конкретном действии используются другие учётные данные, можно указать альтернативные значения. В этом случае будет переопределён только указанный параметр, остальные значения будут взяты из конфигурации внешнего сервиса. +Для каждого объекта можно в явном виде переопределить параметры, заданные во внешнем сервисе. +Например, если внешний сервис содержит токен авторизации, но в конкретном действии используются другие учётные данные, можно указать альтернативные значения. +В этом случае будет переопределён только указанный параметр, остальные значения будут взяты из конфигурации внешнего сервиса. ## Особенности подключения к объектам +Поведение внешних сервисов зависит от объекта, к которому они подключены. + ### Действия +Для действий подключение внешних сервисов работает так: + - К одному действию можно подключить несколько внешних сервисов. - Можно выбрать сервис по умолчанию. - Параметр «Системная учётная запись» не используется в действиях. -- При запуске действия можно выбрать, для какого внешнего сервиса оно будет запускаться. Если ни один сервис не выбран, будет использоваться сервис по умолчанию. Если сервис по умолчанию не задан, то будет использоваться первый внешний сервис в списке. +- При запуске действия можно выбрать, для какого внешнего сервиса оно будет запускаться. + Если ни один сервис не выбран, будет использоваться сервис по умолчанию. + Если сервис по умолчанию не задан, то будет использоваться первый внешний сервис в списке. ### Виджеты +Для виджетов подключение внешних сервисов работает так: + - Для одного виджета также поддерживается подключение нескольких внешних сервисов. - Один из них может быть выбран как используемый по умолчанию. - Параметр «Системная учётная запись» не используется в виджетах. ### Источники данных -- Поддерживается подключение только одного внешнего сервиса. -- Если в сервисе задана системная учётная запись, она используется по умолчанию при синхронизации. +К источнику данных можно подключить только один внешний сервис. +Если в сервисе задана системная учётная запись, она используется по умолчанию при синхронизации. ### Проверки статуса -- Проверке может быть назначен один внешний сервис. -- Если у него указана системная учётная запись — она используется при запуске автоматических проверок. +Проверке статуса можно назначить один внешний сервис. +Если у него указана системная учётная запись, она используется при запуске автоматических проверок. ## Заголовки авторизации для внешних сервисов -При настройке внешних сервисов необходимо указать соответствующие HTTP-заголовки для авторизации. Ниже приведён список внешних сервисов, поддерживаемых порталом, с указанием типа авторизации и необходимых заголовков. +При настройке внешних сервисов укажите соответствующие HTTP-заголовки для авторизации. +Ниже приведён список внешних сервисов, поддерживаемых порталом, с указанием типа авторизации и необходимых заголовков. {{< alert level="info" >}} -Приведённые ниже примеры демонстрируют возможные способы авторизации для каждого сервиса. В некоторых сервисах могут использоваться другие механизмы. Портал поддерживает все варианты, которые можно передать через HTTP-заголовки. +Приведённые ниже примеры демонстрируют возможные способы авторизации для каждого сервиса. +В некоторых сервисах могут использоваться другие механизмы. +Портал поддерживает все варианты, которые можно передать через HTTP-заголовки. {{< /alert >}} ### CodeScoring diff --git a/content/documentation/admin/healthchecks/overview.md b/content/documentation/admin/healthchecks/overview.md index 8398886e..37a4b4c7 100644 --- a/content/documentation/admin/healthchecks/overview.md +++ b/content/documentation/admin/healthchecks/overview.md @@ -3,10 +3,8 @@ title: Overview weight: 10 --- -For each resource, you can configure any number of rules that determine the status of its entities. The `Condition` field determines whether: - -- all rules must pass (`AllOf`); -- at least one rule must pass (`AnyOf`). +For each resource, you can configure any number of rules that determine the status of its entities. +The `Condition` field determines whether all rules must pass (`AllOf`) or at least one rule must pass (`AnyOf`). {{< alert level="info" >}} If at least one check returns an error, the entity status is set to `error`, regardless of the other check results and the condition. @@ -14,7 +12,11 @@ If at least one check returns an error, the entity status is set to `error`, reg ## Schedule -The check scheduler runs every minute. For each rule, you can specify a five-field cron expression in the "Schedule" field. The rule then runs only at the specified times. The schedule is evaluated in UTC. If the field is empty, the rule runs every time the scheduler starts (once a minute). +The check scheduler runs every minute. +For each rule, you can specify a five-field cron expression in the "Schedule" field. +The rule then runs only at the specified times. +The schedule is evaluated in UTC. +If the field is empty, the rule runs every time the scheduler starts (once a minute). Example: `0 * * * *` runs the check at the beginning of every hour. @@ -26,12 +28,13 @@ Logs for the latest checks are available under "Health checks" in the resource m An entity can have one of four statuses: -- `healthy` — rules are configured, and the entity parameters satisfy them; -- `unhealthy` — rules are configured, but the entity parameters do not satisfy them; -- `unknown` — no rules are configured, or the check cannot run; -- `error` — an error occurred while at least one rule was running. +- `healthy`: Rules are configured, and the entity properties satisfy them. +- `unhealthy`: Rules are configured, but the entity properties do not satisfy them. +- `unknown`: No rules are configured, or the check cannot run. +- `error`: An error occurred while at least one rule was running. -Click an entity status badge to open a table with rule results and additional information. The table shows only rules that have run at least once. +Click an entity status badge to open a table with rule results and additional information. +The table shows only rules that have run at least once. {{< alert level="info" >}} The `ENTITY_UPDATED` event is generated only when the entity status changes. diff --git a/content/documentation/admin/healthchecks/overview.ru.md b/content/documentation/admin/healthchecks/overview.ru.md index 7f3265e9..d34ca219 100644 --- a/content/documentation/admin/healthchecks/overview.ru.md +++ b/content/documentation/admin/healthchecks/overview.ru.md @@ -3,10 +3,9 @@ title: Обзор weight: 10 --- -Для каждого ресурса можно настроить набор правил, по которым будет определяться статус его сущностей. Возможно добавление произвольного количества правил. Поле `Условие` определяет, должны ли выполняться: - -- все правила (`AllOf`); -- хотя бы одно из них (`AnyOf`). +Для каждого ресурса можно настроить набор правил, по которым будет определяться статус его сущностей. +Возможно добавление произвольного количества правил. +Поле `Условие` определяет, должны ли выполняться все правила (`AllOf`) или хотя бы одно из них (`AnyOf`). {{< alert level="info" >}} Если хотя бы одна из проверок завершилась с ошибкой, то статус сущности будет выставлен в `error` независимо от результата остальных проверок и условия. @@ -14,7 +13,10 @@ weight: 10 ## Расписание -Планировщик проверок запускается каждую минуту. Для каждого правила в поле «Расписание» можно задать cron-выражение из пяти полей — тогда проверка по этому правилу выполняется только в указанные моменты времени. Расписание вычисляется по времени UTC. Если поле пустое, правило выполняется при каждом запуске планировщика (каждую минуту). +Планировщик проверок запускается каждую минуту. +Для каждого правила в поле «Расписание» можно задать cron-выражение из пяти полей — тогда проверка по этому правилу выполняется только в указанные моменты времени. +Расписание вычисляется по времени UTC. +Если поле пустое, правило выполняется при каждом запуске планировщика (каждую минуту). Пример: `0 * * * *` — проверка в начале каждого часа. @@ -31,7 +33,8 @@ weight: 10 - `unknown` — правила не заданы либо проверка не может быть выполнена по каким-либо причинам; - `error` — во время выполнения хотя бы одного из правил произошла ошибка. -Для каждой сущности при клике на плашку со статусом открывается таблица с результатами выполнения правил и дополнительной информацией. В таблице отображаются только правила, для которых уже выполнялась хотя бы одна проверка. +Для каждой сущности при клике на плашку со статусом открывается таблица с результатами выполнения правил и дополнительной информацией. +В таблице отображаются только правила, для которых уже выполнялась хотя бы одна проверка. {{< alert level="info" >}} Событие `ENTITY_UPDATED` генерируется только при изменении статуса сущности. diff --git a/content/documentation/admin/healthchecks/types.md b/content/documentation/admin/healthchecks/types.md index 762b477c..73117eb6 100644 --- a/content/documentation/admin/healthchecks/types.md +++ b/content/documentation/admin/healthchecks/types.md @@ -6,18 +6,17 @@ weight: 20 ## Property -A `Property` rule checks whether a specific entity parameter matches a template expression. +A `Property` rule checks whether a specific entity property matches a template expression. The rule configuration contains one parameter: an expression written in [Go template syntax](https://pkg.go.dev/text/template). -Expression examples: - -- `{{ eq .entity.properties.lifecycle "deployed" }}` — the `lifecycle` property must equal `"deployed"`; -- `{{ lt .entity.properties.vulnerabilities 10 }}` — the `vulnerabilities` property must be less than `10`. +For example, the `{{ eq .entity.properties.lifecycle "deployed" }}` expression requires the `lifecycle` property to equal `"deployed"`, +and the `{{ lt .entity.properties.vulnerabilities 10 }}` expression requires the `vulnerabilities` property to be less than `10`. ## Prometheus -A Prometheus rule checks whether a specified metric meets a configured threshold. The configuration contains a PromQL query that must return a Scalar or a single-value Vector. +A Prometheus rule checks whether a specified metric meets a configured threshold. +The configuration contains a PromQL query that must return a Scalar or a single-value Vector. Templating is supported. For example: @@ -29,11 +28,13 @@ In this example, the entity identifier replaces `{{ .entity.slug }}`. ### Configuration parameters -| Name | Description | Allowed values | +The rule supports the following parameters: + +| Name | Description | Possible values | |-----------|------------------------------------------------------------|-----------------------------------------| -| Query | PromQL query for a Prometheus metric | | +| Query | PromQL query for a Prometheus metric | — | | Operator | Comparison operator applied to the query result and threshold | Equal, NotEqual, LessThan, GreaterThan | -| Threshold | Threshold compared with the query result | | +| Threshold | Threshold compared with the query result | — | {{< alert level="info" >}} Each entity check sends a separate request to Prometheus. Account for this when planning system load. @@ -53,15 +54,17 @@ All text fields support templating. For example, specify the following expressio {{ .entity.properties.mainBranch }} ``` -During the check, the value of the checked entity's `mainBranch` parameter replaces the expression. +During the check, the value of the checked entity's `mainBranch` property replaces the expression. ### Configuration parameters -| Name | Description | Allowed values | +The rule supports the following parameters: + +| Name | Description | Possible values | |------------|--------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| -| Project ID | GitLab project ID | | -| Ref | Branch or tag whose latest pipeline is checked | | -| Status | Pipeline status considered successful | created, waiting_for_resource, preparing, pending, running, success, failed, canceled, skipped, manual, scheduled | +| Project ID | GitLab project ID | — | +| Ref | Branch or tag whose latest pipeline is checked | — | +| Status | Pipeline status considered successful | `created`, `waiting_for_resource`, `preparing`, `pending`, `running`, `success`, `failed`, `canceled`, `skipped`, `manual`, `scheduled` | {{< alert level="info" >}} Each entity check sends a separate request to GitLab. Account for this when planning system load. @@ -75,9 +78,10 @@ Authorization is configured in the [GitLab external service](../external-service A `DefectDojoFindings` rule checks the number of active vulnerabilities at each severity level for a specified DefectDojo product. -The check uses the conditions in the `conditions` block. For each severity, you can specify the expected number of vulnerabilities and a comparison operator, for example, Critical < 5. +The check uses the conditions in the `conditions` block. +For each severity, you can specify the expected number of vulnerabilities and a comparison operator, for example, Critical < 5. -All text fields support templating. For example, you can insert the product name from the entity parameters: +All text fields support templating. For example, you can insert the product name from the entity properties: ```go-text-template {{ .entity.properties.defectdojo_product_key }} @@ -85,10 +89,12 @@ All text fields support templating. For example, you can insert the product name ### Configuration parameters -| Name | Description | Allowed values | +The rule supports the following parameters: + +| Name | Description | Possible values | |--------------|---------------------------------------------------------------|----------------| -| Product name | Product identifier in DefectDojo | | -| Conditions | Conditions for comparing vulnerability counts by severity | | +| Product name | Product identifier in DefectDojo | — | +| Conditions | Conditions for comparing vulnerability counts by severity | — | #### Conditions @@ -104,11 +110,11 @@ conditions: value: "10" ``` -| Field | Description | Allowed values | +| Name | Description | Possible values | |----------|-----------------------------------|-------------------------------------------| | Severity | Severity level | Total, Critical, High, Medium, Low, Info | | Operator | Comparison operator | ==, !=, <, <=, >, >= | -| Value | Target value for the comparison | | +| Value | Target value for the comparison | — | ### Authorization @@ -118,9 +124,11 @@ Authorization is configured in the [DefectDojo external service](../external-ser A `CodeScoringVulnerabilities` rule checks the number of vulnerabilities at each severity level for a specified CodeScoring project. -The check uses the conditions in the `conditions` block. For each severity, you can specify the expected number of vulnerabilities and a comparison operator. Both CVSS2 and CVSS3 metrics are supported. +The check uses the conditions in the `conditions` block. +For each severity, you can specify the expected number of vulnerabilities and a comparison operator. +Both CVSS2 and CVSS3 metrics are supported. -All text fields support templating. For example, you can insert the project ID from the entity parameters: +All text fields support templating. For example, you can insert the project ID from the entity properties: ```go-text-template {{ .entity.properties.codescoring_project_id }} @@ -128,10 +136,12 @@ All text fields support templating. For example, you can insert the project ID f ### Configuration parameters -| Name | Description | Allowed values | +The rule supports the following parameters: + +| Name | Description | Possible values | |------------|---------------------------------------------------------------|----------------| -| Project ID | Project identifier in CodeScoring | | -| Conditions | Conditions for comparing vulnerability counts by severity | | +| Project ID | Project identifier in CodeScoring | — | +| Conditions | Conditions for comparing vulnerability counts by severity | — | #### Conditions @@ -149,12 +159,12 @@ conditions: cvss: "cvss2" ``` -| Field | Description | Allowed values | +| Name | Description | Possible values | |----------|---------------------------------|-----------------------------------------------------------------------------------------| | Severity | Severity level | CVSS3: CRITICAL, HIGH, MEDIUM, LOW, NONE, UNKNOWN. CVSS2: HIGH, MEDIUM, LOW, NONE | | Operator | Comparison operator | ==, !=, <, <=, >, >= | -| Value | Target value for the comparison | | -| CVSS | CVSS metric version | cvss2, cvss3 | +| Value | Target value for the comparison | — | +| CVSS | CVSS metric version | `cvss2`, `cvss3` | ### Authorization @@ -166,7 +176,7 @@ A `SonarqubeMetrics` rule checks SonarQube project metrics against configured co The check calls the SonarQube REST API endpoint `/api/measures/component` and compares current metric values with the expected values specified under "Conditions". -All text fields support templating. For example, you can insert the component key from the entity parameters: +All text fields support templating. For example, you can insert the component key from the entity properties: ```go-text-template {{ .entity.properties.sonarqube_project_key }} @@ -174,11 +184,13 @@ All text fields support templating. For example, you can insert the component ke ### Configuration parameters -| Name | Required | Description | Allowed values | +The rule supports the following parameters: + +| Name | Required | Description | Possible values | |-------------|----------|------------------------------------------|----------------| -| Project key | Yes | Project identifier in SonarQube | | -| Branch | No | Project branch from which metrics are read | | -| Conditions | Yes | Conditions for comparing SonarQube metrics | | +| Project key | Yes | Project identifier in SonarQube | — | +| Branch | No | Project branch from which metrics are read | — | +| Conditions | Yes | Conditions for comparing SonarQube metrics | — | #### Conditions @@ -194,11 +206,11 @@ conditions: value: "10" ``` -| Field | Description | Allowed values | +| Name | Description | Possible values | |----------|------------------------------------------------------|-----------------------------------------------------| | Metric | SonarQube metric specified by its metric key | See the metric list in the official SonarQube documentation | | Operator | Comparison operator | ==, !=, <, <=, >, >= | -| Value | Target value for the comparison | | +| Value | Target value for the comparison | — | See the [list of available metrics](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/code-metrics/metrics-definition) for the current SonarQube version. @@ -208,11 +220,13 @@ Authorization is configured in the [SonarQube external service](../external-serv ## SonarQube Quality Gate -A `SonarqubeQualityGate` rule checks the Quality Gate status of a SonarQube project. The check calls the SonarQube REST API endpoint `/api/qualitygates/project_status`. +A `SonarqubeQualityGate` rule checks the Quality Gate status of a SonarQube project. +The check calls the SonarQube REST API endpoint `/api/qualitygates/project_status`. -The rule returns `true` (passes) if the project Quality Gate has the `OK` status. It returns `false` (fails) for all other statuses: `WARN`, `ERROR`, or `NONE`. +The rule returns `true` (passes) if the project Quality Gate has the `OK` status. +It returns `false` (fails) for all other statuses: `WARN`, `ERROR`, or `NONE`. -All text fields support templating. For example, you can insert the project key from the entity parameters: +All text fields support templating. For example, you can insert the project key from the entity properties: ```go-text-template {{ .entity.properties.sonarqube_project_key }} @@ -220,10 +234,12 @@ All text fields support templating. For example, you can insert the project key ### Configuration parameters -| Name | Required | Description | Allowed values | +The rule supports the following parameters: + +| Name | Required | Description | Possible values | |-------------|----------|----------------------------------------------------------------------------------------------|----------------| -| Project key | Yes | Project identifier in SonarQube | | -| Branch | No | Project branch whose Quality Gate is checked. If omitted, the main branch is checked | | +| Project key | Yes | Project identifier in SonarQube | — | +| Branch | No | Project branch whose Quality Gate is checked. If omitted, the main branch is checked | — | {{< alert level="info" >}} Each entity check sends a separate request to SonarQube. Account for this when planning system load. @@ -235,21 +251,25 @@ Authorization is configured in the [SonarQube external service](../external-serv ## URL -A `URL` rule checks the availability of an HTTP or HTTPS endpoint. It sends a request with the configured parameters and evaluates the result against one or more Go template conditions. Conditions can check the response code, headers, response body, and entity parameters. +A `URL` rule checks the availability of an HTTP or HTTPS endpoint. +It sends a request with the configured parameters and evaluates the result against one or more Go template conditions. +Conditions can check the response code, headers, response body, and entity properties. All string fields (URL, request body, and headers) support templating with entity data (`.entity`), for example, `{{ .entity.slug }}`. ### Configuration parameters +The rule supports the following parameters: + | Name | Required | Description | Examples | |---------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------| | URL | Yes | Full request URL | `https://example.com` | | Method | No | HTTP request method | GET, POST | -| Query | No | Query value added to the outgoing request | | -| Save details | No | If enabled, the check table stores and displays the response body and status (code and headers). If disabled, it shows only the condition, result, and error | | +| Query | No | Query value added to the outgoing request | — | +| Save details | No | If enabled, the check table stores and displays the response body and status (code and headers). If disabled, it shows only the condition, result, and error | — | | Conditions | No | Go template expressions used to evaluate the response | See below | | Multiple conditions | No | `AllOf` requires all conditions to pass; `AnyOf` requires at least one | AllOf, AnyOf | -| Request body | No | Request body in YAML format. After template substitution, it is converted to JSON and sent | | +| Request body | No | Request body in YAML format. After template substitution, it is converted to JSON and sent | — | If no conditions are specified, the response code is checked against `200` by default: `{{ eq .status.code 200 }}`. @@ -257,9 +277,11 @@ If no conditions are specified, the response code is checked against `200` by de Conditions can use: -- `.status` — response data: `.status.code` (HTTP code), `.status.status` (status string), `.status.headers` (headers), and `.status.contentLength`. `.status.headers` is a map of header names to value arrays, with names in lowercase. Example: access the first header value with `{{ index (index .status.headers "content-type") 0 }}`; iterate over values with `{{ range index .status.headers "set-cookie" }}...{{ end }}`. -- `.response` — response body with converted types (for a JSON response). -- `.entity` — parameters of the checked entity. +- `.status`: Response data: `.status.code` (HTTP code), `.status.status` (status string), `.status.headers` (headers), and `.status.contentLength`. + `.status.headers` is a map of header names to value arrays, with names in lowercase. + Example: access the first header value with `{{ index (index .status.headers "content-type") 0 }}`; iterate over values with `{{ range index .status.headers "set-cookie" }}...{{ end }}`. +- `.response`: Response body with converted types (for a JSON response). +- `.entity`: Properties of the checked entity. Condition examples: @@ -280,4 +302,5 @@ name: "{{ .entity.name }}" ### Result evaluation -The check passes when all conditions pass in `AllOf` mode or at least one passes in `AnyOf` mode. If evaluating a condition returns an error—for example, the response is not JSON but the condition uses `.response`—the check returns an error. +The check passes when all conditions pass in `AllOf` mode or at least one passes in `AnyOf` mode. +If evaluating a condition returns an error—for example, the response is not JSON but the condition uses `.response`—the check returns an error. diff --git a/content/documentation/admin/healthchecks/types.ru.md b/content/documentation/admin/healthchecks/types.ru.md index 0bbd80c0..e9518752 100644 --- a/content/documentation/admin/healthchecks/types.ru.md +++ b/content/documentation/admin/healthchecks/types.ru.md @@ -8,16 +8,16 @@ weight: 20 Правило типа `Property` проверяет, соответствует ли конкретный параметр сущности заданному шаблонному выражению. -Конфигурация правила состоит из одного параметра — выражения. Для описания выражения используется синтаксис [Go template](https://pkg.go.dev/text/template). +Конфигурация правила состоит из одного параметра — выражения. +Для описания выражения используется синтаксис [Go template](https://pkg.go.dev/text/template). -Примеры выражений: - -- `{{ eq .entity.properties.lifecycle "deployed" }}` — значение свойства `lifecycle` должно быть `"deployed"`; -- `{{ lt .entity.properties.vulnerabilities 10 }}` — значение свойства `vulnerabilities` должно быть меньше `10`. +Например, выражение `{{ eq .entity.properties.lifecycle "deployed" }}` требует, чтобы значение свойства `lifecycle` было `"deployed"`, +а выражение `{{ lt .entity.properties.vulnerabilities 10 }}` — чтобы значение свойства `vulnerabilities` было меньше `10`. ## Prometheus -Правило типа Prometheus проверяет, соответствует ли указанная метрика заданному пороговому значению. В конфигурации указывается запрос PromQL, который должен возвращать результат типа Scalar или Vector с одним значением. +Правило типа Prometheus проверяет, соответствует ли указанная метрика заданному пороговому значению. +В конфигурации указывается запрос PromQL, который должен возвращать результат типа Scalar или Vector с одним значением. Поддерживается шаблонизация, например: @@ -29,14 +29,17 @@ avg(ingress_nginx_detail_request_seconds_sum{location="/{{ .entity.slug }}"}) ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Описание | Возможные значения | |---------------------|--------------------------------------------------------------------|----------------------------------------| -| Запрос | Запрос в формате PromQL к метрике в Prometheus | | +| Запрос | Запрос в формате PromQL к метрике в Prometheus | — | | Оператор | Оператор сравнения между результатом запроса и пороговым значением | Equal, NotEqual, LessThan, GreaterThan | -| Порог | Пороговое значение для сравнения с результатом запроса | | +| Порог | Пороговое значение для сравнения с результатом запроса | — | {{< alert level="info" >}} -Для проверки каждой сущности выполняется отдельный запрос к Prometheus. Рекомендуется учитывать это при планировании нагрузки на систему. +Для проверки каждой сущности выполняется отдельный запрос к Prometheus. +Рекомендуется учитывать это при планировании нагрузки на систему. {{< /alert >}} ### Авторизация @@ -45,7 +48,7 @@ avg(ingress_nginx_detail_request_seconds_sum{location="/{{ .entity.slug }}"}) ## GitLab Pipeline -Правило типа `GitlabPipeline` проверяет, соответствует ли статус последнего pipeline в GitLab для выбранного Ref (ветка или тег) заданному статусу. +Правило типа `GitlabPipeline` проверяет, соответствует ли статус последнего пайплайна в GitLab для выбранного Ref (ветка или тег) заданному статусу. Во всех текстовых полях поддерживается шаблонизация, например, при подобном выражении в поле `Ref`: @@ -57,14 +60,17 @@ avg(ingress_nginx_detail_request_seconds_sum{location="/{{ .entity.slug }}"}) ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Описание | Возможные значения | |---------------------|-------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------| -| ID проекта | ID проекта в GitLab | | -| Ref | Ветка или тег, для которых будет искаться последний pipeline | | -| Статус | Статус pipeline, который будет считаться успешным | created, waiting_for_resource, preparing, pending, running, success, failed, canceled, skipped, manual, scheduled | +| ID проекта | ID проекта в GitLab | — | +| Ref | Ветка или тег, для которых будет искаться последний пайплайн | — | +| Статус | Статус пайплайна, который будет считаться успешным | `created`, `waiting_for_resource`, `preparing`, `pending`, `running`, `success`, `failed`, `canceled`, `skipped`, `manual`, `scheduled` | {{< alert level="info" >}} -Для проверки каждой сущности выполняется отдельный запрос к GitLab. Рекомендуется учитывать это при планировании нагрузки на систему. +Для проверки каждой сущности выполняется отдельный запрос к GitLab. +Рекомендуется учитывать это при планировании нагрузки на систему. {{< /alert >}} ### Авторизация @@ -75,9 +81,10 @@ avg(ingress_nginx_detail_request_seconds_sum{location="/{{ .entity.slug }}"}) Правило типа `DefectDojoFindings` выполняет проверку по количеству активных уязвимостей различной критичности (severity) для заданного продукта в DefectDojo. -Проверка проводится по условиям в блоке `conditions`, где можно указать ожидаемое количество уязвимостей для каждой severity и оператор сравнения (например, Critical < 5). +Проверка проводится по условиям в блоке `conditions`, где можно указать ожидаемое количество уязвимостей для каждого уровня критичности и оператор сравнения (например, Critical < 5). -Во всех текстовых полях поддерживается шаблонизация. Например, можно подставить название продукта из параметров сущности: +Во всех текстовых полях поддерживается шаблонизация. +Например, можно подставить название продукта из параметров сущности: ```go-text-template {{ .entity.properties.defectdojo_product_key }} @@ -85,10 +92,12 @@ avg(ingress_nginx_detail_request_seconds_sum{location="/{{ .entity.slug }}"}) ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Описание | Возможные значения | |---------------------|----------------------------------------------------------|---------------------| -| Название продукта | Идентификатор продукта в DefectDojo | | -| Условия | Условия для сравнения количества уязвимостей по severity | | +| Название продукта | Идентификатор продукта в DefectDojo | — | +| Условия | Условия для сравнения количества уязвимостей по уровню критичности | — | #### Условия @@ -104,11 +113,11 @@ conditions: value: "10" ``` -| Поле | Описание | Возможные значения | +| Название | Описание | Возможные значения | |---------------------|--------------------------------|------------------------------------------| | Уровень критичности | Уровень критичности | Total, Critical, High, Medium, Low, Info | | Оператор | Оператор сравнения | ==, !=, <, <=, >, >= | -| Значение | Целевое значение для сравнения | | +| Значение | Целевое значение для сравнения | — | ### Авторизация @@ -118,7 +127,8 @@ conditions: Правило типа `CodeScoringVulnerabilities` выполняет проверку по количеству уязвимостей различной критичности (severity) для заданного проекта в CodeScoring. -Проверка проводится по условиям в блоке `conditions`, где можно указать ожидаемое количество уязвимостей для каждой severity и оператор сравнения. Поддерживается проверка как по CVSS2, так и по CVSS3 метрикам. +Проверка проводится по условиям в блоке `conditions`, где можно указать ожидаемое количество уязвимостей для каждого уровня критичности и оператор сравнения. +Поддерживается проверка как по CVSS2, так и по CVSS3 метрикам. Во всех текстовых полях поддерживается шаблонизация. Например, можно подставить ID проекта из параметров сущности: @@ -128,10 +138,12 @@ conditions: ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Описание | Возможные значения | |---------------------|----------------------------------------------------------------|--------------------| -| ID проекта | Идентификатор проекта в CodeScoring | | -| Условия | Условия для сравнения количества уязвимостей по severity | | +| ID проекта | Идентификатор проекта в CodeScoring | — | +| Условия | Условия для сравнения количества уязвимостей по уровню критичности | — | #### Условия @@ -149,12 +161,12 @@ conditions: cvss: "cvss2" ``` -| Поле | Описание | Возможные значения | +| Название | Описание | Возможные значения | |---------------------|--------------------------------|-------------------------------------------------------------------------------------------| | Уровень критичности | Уровень критичности | Для CVSS3: CRITICAL, HIGH, MEDIUM, LOW, NONE, UNKNOWN. Для CVSS2: HIGH, MEDIUM, LOW, NONE | | Оператор | Оператор сравнения | ==, !=, <, <=, >, >= | -| Значение | Целевое значение для сравнения | | -| CVSS | Версия CVSS метрики | cvss2, cvss3 | +| Значение | Целевое значение для сравнения | — | +| CVSS | Версия CVSS метрики | `cvss2`, `cvss3` | ### Авторизация @@ -174,11 +186,13 @@ conditions: ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Обязательность | Описание | Возможные значения | |---------------------|----------------|------------------------------------------------------------|---------------------| -| Ключ проекта | Да | Идентификатор проекта в SonarQube | | -| Ветка | Нет | Ветка проекта для которой будут браться метрики | | -| Условия | Да | Условия для сравнения метрик в SonarQube | | +| Ключ проекта | Да | Идентификатор проекта в SonarQube | — | +| Ветка | Нет | Ветка проекта для которой будут браться метрики | — | +| Условия | Да | Условия для сравнения метрик в SonarQube | — | #### Условия @@ -194,11 +208,11 @@ conditions: value: "10" ``` -| Поле | Описание | Возможные значения | +| Название | Описание | Возможные значения | |-----------|----------------------------------------------------------|------------------------------------------------------------------------| | Метрика | Метрика SonarQube. В конфигурации указывается Metric key | См. список метрик в официальной документации SonarQube | | Оператор | Оператор сравнения | ==, !=, <, <=, >, >= | -| Значение | Целевое значение для сравнения | | +| Значение | Целевое значение для сравнения | — | [Список возможных метрик](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/code-metrics/metrics-definition) для текущей версии SonarQube. @@ -208,7 +222,8 @@ conditions: ## SonarQube Quality Gate -Правило типа `SonarqubeQualityGate` проверяет статус Quality Gate проекта в SonarQube. Проверка выполняется с использованием REST API вызова SonarQube `/api/qualitygates/project_status`. +Правило типа `SonarqubeQualityGate` проверяет статус Quality Gate проекта в SonarQube. +Проверка выполняется с использованием REST API вызова SonarQube `/api/qualitygates/project_status`. Правило возвращает `true` (выполняется), если Quality Gate проекта имеет статус `OK`, и `false` (не выполняется) во всех остальных случаях (статусы `WARN`, `ERROR`, `NONE`). @@ -220,13 +235,16 @@ conditions: ### Параметры конфигурации +Правило поддерживает следующие параметры: + | Название | Обязательность | Описание | Возможные значения | |---------------------|----------------|------------------------------------------------------------|---------------------| -| Ключ проекта | Да | Идентификатор проекта в SonarQube | | -| Ветка | Нет | Ветка проекта для которой будет проверяться Quality Gate. Если не указана, проверяется основная ветка | | +| Ключ проекта | Да | Идентификатор проекта в SonarQube | — | +| Ветка | Нет | Ветка проекта для которой будет проверяться Quality Gate. Если не указана, проверяется основная ветка | — | {{< alert level="info" >}} -Для проверки каждой сущности выполняется отдельный запрос к SonarQube. Рекомендуется учитывать это при планировании нагрузки на систему. +Для проверки каждой сущности выполняется отдельный запрос к SonarQube. +Рекомендуется учитывать это при планировании нагрузки на систему. {{< /alert >}} ### Авторизация @@ -235,21 +253,25 @@ conditions: ## URL -Правило типа `URL` проверяет доступность HTTP/HTTPS-эндпоинта: отправляется запрос с заданными параметрами, результат оценивается по одному или нескольким условиям — выражениям Go template. В условиях можно проверять код ответа, заголовки, тело ответа и параметры сущности. +Правило типа `URL` проверяет доступность HTTP/HTTPS-эндпоинта. +Отправляется запрос с заданными параметрами, а результат оценивается по одному или нескольким условиям — выражениям Go template. +В условиях можно проверять код ответа, заголовки, тело ответа и параметры сущности. Во всех строковых полях (URL, тело запроса, заголовки) доступна шаблонизация с подстановкой данных сущности (`.entity`), например: `{{ .entity.slug }}`. ### Параметры конфигурации -| Название | Обязательность | Описание | Примеры | +Правило поддерживает следующие параметры: + +| Название | Обязательность | Описание | Пример | |----------------------------|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------| | URL | Да | Полный адрес, по которому выполняется запрос | `https://example.com` | | Метод | Нет | HTTP-метод запроса | GET, POST | -| Query | Нет | Значение query, подставляемое в исходящий запрос | | -| Сохранять детали | Нет | Если включено — в таблице проверок сохраняются и отображаются тело ответа и статус (код, заголовки). Если выключено — только условие, результат и ошибка | | +| Query | Нет | Значение query, подставляемое в исходящий запрос | — | +| Сохранять детали | Нет | Если включено — в таблице проверок сохраняются и отображаются тело ответа и статус (код, заголовки). Если выключено — только условие, результат и ошибка | — | | Условия | Нет | Выражения Go template, по которым оценивается ответ | См. ниже | | При нескольких условиях | Нет | `AllOf` — должны выполниться все условия; `AnyOf` — достаточно одного | AllOf, AnyOf | -| Тело запроса | Нет | Тело запроса в формате YAML. После подстановки шаблонов преобразуется в JSON и отправляется | | +| Тело запроса | Нет | Тело запроса в формате YAML. После подстановки шаблонов преобразуется в JSON и отправляется | — | Если условия не заданы, по умолчанию используется проверка кода ответа 200: `{{ eq .status.code 200 }}`. @@ -257,7 +279,9 @@ conditions: В условиях доступны: -- `.status` — данные ответа: `.status.code` (код HTTP), `.status.status` (строка статуса), `.status.headers` (заголовки), `.status.contentLength`. `.status.headers` — карта «название заголовка → массив значений» (названия в нижнем регистре). Пример: первый элемент заголовка — `{{ index (index .status.headers "content-type") 0 }}`; перебор — `{{ range index .status.headers "set-cookie" }}...{{ end }}`. +- `.status` — данные ответа: `.status.code` (код HTTP), `.status.status` (строка статуса), `.status.headers` (заголовки), `.status.contentLength`. + `.status.headers` — карта «название заголовка → массив значений» (названия в нижнем регистре). + Пример: первый элемент заголовка — `{{ index (index .status.headers "content-type") 0 }}`; перебор — `{{ range index .status.headers "set-cookie" }}...{{ end }}`. - `.response` — тело ответа с приведёнными типами (для JSON-ответа). - `.entity` — параметры проверяемой сущности. @@ -280,4 +304,5 @@ name: "{{ .entity.name }}" ### Проверка результата -Проверка считается успешной, если при режиме AllOf выполняются все условия, при AnyOf — хотя бы одно. Если при вычислении условия возникает ошибка (например, ответ не в JSON, а в условии используется `.response`), проверка завершается с ошибкой. +Проверка считается успешной, если при режиме AllOf выполняются все условия, при AnyOf — хотя бы одно. +Если при вычислении условия возникает ошибка (например, ответ не в JSON, а в условии используется `.response`), проверка завершается с ошибкой. diff --git a/content/documentation/admin/home/_index.md b/content/documentation/admin/home/_index.md new file mode 100644 index 00000000..bc9bfd05 --- /dev/null +++ b/content/documentation/admin/home/_index.md @@ -0,0 +1,4 @@ +--- +title: Home +weight: 25 +--- diff --git a/content/documentation/admin/home/_index.ru.md b/content/documentation/admin/home/_index.ru.md index c0d75178..e883f20b 100644 --- a/content/documentation/admin/home/_index.ru.md +++ b/content/documentation/admin/home/_index.ru.md @@ -1,4 +1,4 @@ --- -title: Главная +title: Главная страница weight: 25 --- diff --git a/content/documentation/admin/home/mapping.md b/content/documentation/admin/home/mapping.md new file mode 100644 index 00000000..17540451 --- /dev/null +++ b/content/documentation/admin/home/mapping.md @@ -0,0 +1,383 @@ +--- +title: Mapping rules +weight: 30 +description: Reference for DDP Home mapping sets — the set form, areas, resource, relation, and property roles, action slots, template actions, widget slots, and validation errors. +--- + +Mapping rules map catalog resources, relations, properties, processes, and widgets to Home page concepts. +The rules are stored in Home mapping sets; the Home page uses the default set. +How the Home page selects a set is described in [Overview](overview/#default-mapping-set). + +## The "Mapping rules" page + +Mapping sets are located in "Administration" → "Directories" → "Mapping rules". + +The panel above the table contains: + +- The "Show Home" toggle: Enables and disables the Home page for all users. +- The "Create" button: Opens the form for a new set. +- The "Search" field: Filters sets by name and ID. + +The sets table displays the following columns: + +| Column | Content | +| --- | --- | +| "Name" | Set name | +| "Identifier" | Set ID | +| "Default for Home" | Default set toggle. The toggle is unavailable for the current default set: to change the set, enable the toggle for another set | +| "Resources" | Number of mapped resource roles | +| "Relations" | Number of mapped relation roles | +| "Properties" | Number of mapped property roles | +| "Action slots" | Number of filled action slots | +| "Templates" | Number of templates with at least one bound process | +| "Widgets" | Number of filled widget slots | + +To delete a set, enter its ID in the confirmation window. The default set cannot be deleted. + +Permissions for working with sets: + +- `create:home-mapping-sets`: Create sets. +- `update:home-mapping-sets`: Edit sets, select the default set, and use the "Show Home" toggle. +- `delete:home-mapping-sets`: Delete sets. + +No permission is required to view sets, since every Home page reads them. +For selection lists to be populated in the set form, the user also needs permissions to view resources, resource relations, processes (`read:processes`), widgets (`read:widgets`), and templates (`read:template-packs`). + +## Set form + +The set form opens with the "Create" button or the edit button in a table row. The form contains two tabs. + +On the "Main information" tab, fill in the following fields: + +- "Name": From 3 to 64 characters. +- "Identifier": A stable set ID: from 3 to 64 characters, lowercase Latin letters, digits, and hyphens. + Cannot be changed after creation. +- "Default for Home": Makes the set the default set. + The first set created becomes the default set automatically. + +On the "Catalog mapping" tab, rules are grouped by Home page areas. +Each area expands separately and contains the following blocks: + +| Block | Purpose | +| --- | --- | +| "Catalog resource" | The resource the area is built on | +| "Catalog resources" | Several area resources, each with its own properties and relations. Used in the "Microservices" and "Shared resources" areas | +| "Relations" | Relations the Home page uses to traverse the area's entities | +| "Properties" | IDs of entity properties the Home page reads | +| "Actions" | Action slots of the area | +| "Template actions" | Processes bound to a microservice template. Only in the "Microservices" area | +| "Widgets" | Widget slots. Only in the "Microservices" area | + +Each form field has a tooltip describing the role's purpose, its effect, and its place on the Home page. + +The "Specification editor" button opens the entire set as a JSON document. The "Back to form" button returns you to the form. +Deleting a key in the specification text does not remove the value from the form. Clear the value in the form or replace it in the text. + +### Selecting relations and properties + +The list of relations and properties for a role is built from the resource of its parent role. +For example, the `has_deployment` relation is selected from the relations of the `microservice` role resource, and the `environment_domain` property from the properties of the `environment` role resource. + +Until the parent role is mapped to a resource, the field is unavailable and the tooltip "Configure the mapping of the related resource role first to select items from its catalog" is displayed. + +When a role's resource changes, the form clears the relations and properties that depend on that role. +For example, when the `system` role resource changes, the `contains_service` and `contains_shared` relations are cleared in all resources of the "Microservices" and "Shared resources" areas. +Clearing happens in the form before saving; save the set to apply the changes. + +### Multiple resources per area + +In the "Microservices" and "Shared resources" areas, a role can be mapped to several catalog resources, for example, microservices from different accounting systems. +Each resource has its own properties and relations. + +To add a resource, click "Add resource" and fill in the resource card. +A relation whose parent is in another area, for example, `contains_service` from a system to a microservice, becomes available for selection after that area's resource is mapped. +When the resource in a card changes, its properties and relations are cleared. + +## Mapping areas + +Each mapping area belongs to one Home page section. The table lists the areas, sections, and their roles: + +| Area | Home page section | Resource role | Relation roles | Property roles | Slots | +| --- | --- | --- | --- | --- | --- | +| "Systems" | "Systems" | `system` | `has_ingress`, `system_has_deployment`, `system_has_integration` | `system_domain`, `system_lifecycle` | — | +| "Microservices" | "Microservices" | `microservice` (multiple resources) | `contains_service`, `has_deployment` | `microservice_*` | `deploy_microservice`, `delete_microservice`; template actions; widget slots | +| "Environments" | "Environments" | `environment` | `environment_hosts_ingress` | `environment_type`, `environment_ttl`, `environment_marked_for_deletion`, `environment_domain` | `create_environment`, `delete_environment` | +| "Shared resources" | "Resource ordering" | `shared_resource` (multiple resources) | `contains_shared`, `shared_has_deployment` | `shared_environment`, `shared_kind`, `shared_provider` | `order_resource`, `connect_shared_resource`, `disconnect_shared_resource`, `delete_shared_resource` | +| "Deployments" | "System deployment" | `deployment` | `deployment_in_environment` | `deployment_*` | — | +| "Ingress" | "System deployment" | `ingress` | `ingress_routes_to` | `ingress_host`, `ingress_routes` | — | +| "Clusters" | "Clusters and networks" | `cluster` | `cluster_hosts_environment` | `cluster_region`, `cluster_provider` | — | +| "Guides" | "How the platform works" | `guide` | — | `guide_category`, `guide_video_url`, `guide_doc_url` | — | +| "Integrations" | "Integrations" | `integration` | `integration_targets_system` | `integration_criticality`, `integration_link_type` | — | +| "Version control namespaces" | "Create microservice" | `vcs_namespace` | — | `vcs_namespace_id` | — | + +If the set contains keys that do not belong to known areas, the form displays them in the "Other" area. + +The "Teams", "Diagrams", and "Resource consumption" sections do not have their own areas and use the roles of other areas. + +## Resource roles + +A resource role specifies which catalog resource's entities the Home page displays as objects of a certain kind. +The "Canonical resource" column shows the resource created by the "Canonical architecture (schema)" dataset. + +| Role | Name in the form | Purpose | Canonical resource | +| --- | --- | --- | --- | +| `system` | "System" | Systems: domain tree, dependencies, composition, owners | "Systems" (`systems`) | +| `microservice` | "Microservice" | Microservices: list, card, deployment, upgrade from template | "Microservices" (`microservices`) | +| `environment` | "Environment" | Environments. An environment is a Kubernetes namespace | "Namespaces" (`kubernetes-namespaces`) | +| `shared_resource` | "Shared resource" | Shared resources: databases, queues, caches | "Shared resources" (`shared-resources`) | +| `deployment` | "Deployment" | Deployments of microservices and systems to environments | "Deployments" (`kubernetes-deployments`) | +| `ingress` | "Ingress" | Entry points on the deployment diagram | "Ingresses" (`kubernetes-ingresses`) | +| `cluster` | "Cluster" | Clusters that host environments | "Clusters" (`clusters`) | +| `guide` | "Guide" | Cards in the "How the platform works" section | "Help" (`guides`) | +| `integration` | "Integration" | Integrations between systems | "Integrations" (`integrations`) | +| `vcs_namespace` | "Version control namespace" | Groups in which microservice repositories are created | "Groups" (`gitlab-groups`) | + +## Relation roles + +A relation role specifies which catalog relation the Home page uses to navigate from one entity to another. + +| Role | Name in the form | Direction | Canonical relation | +| --- | --- | --- | --- | +| `contains_service` | "Contains microservice" | System → microservice | "System — microservice" | +| `contains_shared` | "Contains shared resource" | System → shared resource | "System — shared resource" | +| `system_has_integration` | "System takes part in integration" | Client system → integration | "System — integration" | +| `integration_targets_system` | "Integration targets system" | Integration → server system | "Integration — system" | +| `has_ingress` | "Has ingress" | System → Ingress | "System — ingress" | +| `environment_hosts_ingress` | "Environment hosts ingress" | Environment → Ingress | "Namespace — ingress" | +| `ingress_routes_to` | "Ingress routes to" | Ingress → microservice | "Ingress — microservice" | +| `has_deployment` | "Has deployment" | Microservice → deployment | "Microservice — deployment" | +| `system_has_deployment` | "System has deployment" | System → deployment | "System — deployment" | +| `shared_has_deployment` | "Shared resource has deployment" | Shared resource → deployment | "Shared resource — deployment" | +| `deployment_in_environment` | "Deployment in environment" | Deployment → environment | "Deployment — environment" | +| `cluster_hosts_environment` | "Cluster hosts environment" | Cluster → environment | "Cluster — environment" | + +Systems are related to each other only through integrations. +A client system is related to an integration by the `system_has_integration` role, and an integration is related to a server system by the `integration_targets_system` role. + +If a relation role is not mapped, the Home page uses any relation between entities of the corresponding resources. +This lets you work with a partially filled set. + +## Property roles + +A property role contains the ID of an entity property. +The property is selected from the properties of the parent role's resource: for `system_*`, the `system` role resource; for `microservice_*`, the `microservice` role resource; and so on. + +### Systems, integrations, clusters, and guides + +Property roles for systems, integrations, clusters, and guides: + +| Role | Name in the form | Where it is displayed | Canonical property | +| --- | --- | --- | --- | +| `system_domain` | "System domain" | The "Domains" tree in the "Systems" section, the "Domain" column in the "Microservices" section | `domain` | +| `system_lifecycle` | "System lifecycle" | "Lifecycle" on the system's "Overview" tab | `lifecycle` | +| `integration_criticality` | "Integration criticality" | Integration "Criticality", the "Critical links" card | `criticality` | +| `integration_link_type` | "Integration link type" | Integration "Link type" | `link_type` | +| `cluster_region` | "Cluster region" | Cluster card | `region` | +| `cluster_provider` | "Cluster provider" | Cluster card | `provider` | +| `guide_category` | "Guide category" | Guide grouping and filter | `category` | +| `guide_video_url` | "Guide video URL" | The "Watch video" button | `video_url` | +| `guide_doc_url` | "Guide documentation URL" | The "Open documentation" button | `doc_url` | + +An integration is considered critical if the `integration_criticality` property value is `high`, case-insensitive. + +### Microservices + +Property roles for microservices. +The values of the `microservice_binding_*` roles are written by the process that creates a microservice from a template; [upgrading from a template](../templates/updates/) relies on them. + +| Role | Name in the form | Purpose | Canonical property | +| --- | --- | --- | --- | +| `microservice_language` | "Microservice language" | The "Language" column, the "All languages" filter | `language` | +| `microservice_repository` | "Microservice repository" | Repository link; `.context.repository.url` for widgets | `repository` | +| `microservice_gitlab_project_id` | "GitLab project ID" | `.context.repository.id` for widgets | `gitlab_repository_id` | +| `microservice_binding_template_id` | "Microservice template ID" | The template the microservice was created from. Used to select template actions | `template_id` | +| `microservice_binding_template_version` | "Microservice template version" | Current template version in the repository | `template_version` | +| `microservice_binding_template_source` | "Microservice template source" | Name of the registry the template was obtained from | `template_source` | +| `microservice_binding_template_update_policy` | "Microservice template update policy" | `manual` or `review-auto` | `template_update_policy` | +| `microservice_binding_template_upgrade_strategy` | "Microservice template upgrade strategy" | Upgrade strategy set for the microservice | `template_upgrade_strategy` | +| `microservice_binding_template_upgrade_overwrite` | "Microservice upgrade overwrite paths" | List of paths to overwrite set for the microservice | `template_upgrade_overwrite` | +| `microservice_binding_template_upgrade_add_if_missing` | "Microservice upgrade add-if-missing paths" | List of paths to add set for the microservice | `template_upgrade_add_if_missing` | +| `microservice_vcs_provider` | "Microservice VCS provider" | Microservice repository provider | `vcs_provider` | +| `microservice_vcs_external_service_uuid` | "Microservice VCS external service" | The GitLab external service that hosts the repository | `vcs_external_service_uuid` | +| `microservice_default_branch` | "Microservice default branch" | The branch to which the merge request with the upgrade is created | `default_branch` | +| `microservice_open_mr_count` | "Open merge requests" | The "Open MRs" metric | `open_mr_count` | +| `microservice_last_pipeline_status` | "Last pipeline status" | The "Last pipeline" metric | `last_pipeline_status` | +| `microservice_last_pipeline_id` | "Last pipeline ID" | Pipeline number in the "Last pipeline" metric | `last_pipeline_id` | +| `microservice_last_pipeline_web_url` | "Last pipeline link" | Link to the pipeline | `last_pipeline_web_url` | +| `microservice_last_commit_sha` | "Last commit SHA" | The "Last delivery" line | `last_commit_sha` | +| `microservice_last_commit_message` | "Last commit message" | The "Last delivery" line | `last_commit_message` | +| `microservice_last_commit_author` | "Last commit author" | The "Last delivery" line | `last_commit_author` | + +If the `microservice_binding_*`, `microservice_vcs_*`, or `microservice_default_branch` roles are not mapped, the upgrade-from-template mechanism uses the canonical property IDs from the table. + +### Environments + +Property roles for environments: + +| Role | Name in the form | Purpose | Canonical property | +| --- | --- | --- | --- | +| `environment_type` | "Environment type" | The "Type" column; environment color on the deployment diagram | `type` | +| `environment_ttl` | "Environment TTL" | The "TTL" column. An environment with a TTL is considered temporary | `deletion_ttl` | +| `environment_marked_for_deletion` | "Environment marked for deletion" | The "Marked for deletion" tag when the value is `true`, `1`, or `yes` | `marked_for_deletion` | +| `environment_domain` | "Environment domain" | The "Domain" column. The value is changed from the environment card | `domain` | + +An environment is also considered temporary if its type contains `temp` or `preview`, case-insensitive. + +In the canonical model, the `deletion_ttl` property is filled in from the namespace's `ddp.deckhouse.io/deletion-ttl` label on every synchronization. +The `type`, `domain`, and `marked_for_deletion` properties are not synchronized from the cluster and are set in the catalog. + +### Shared resources and deployments + +Property roles for shared resources, deployments, Ingresses, and VCS namespaces: + +| Role | Name in the form | Purpose | Canonical property | +| --- | --- | --- | --- | +| `shared_environment` | "Shared resource environment" | The environment that hosts the resource | `environment` | +| `shared_kind` | "Shared resource type" | Resource type, for example, PostgreSQL | `kind` | +| `shared_provider` | "Shared resource provider" | Provider, for example, Deckhouse | `provider` | +| `deployment_replicas` | "Deployment replicas" | Number of replicas | `replicas` | +| `deployment_cpu_request` | "Deployment CPU request" | CPU request | `cpu_request` | +| `deployment_memory_request` | "Deployment memory request" | Memory request | `memory_request` | +| `deployment_cpu_limit` | "Deployment CPU limit" | CPU limit | `cpu_limit` | +| `deployment_memory_limit` | "Deployment memory limit" | Memory limit | `memory_limit` | +| `deployment_image_tag` | "Deployment image tag" | Image version | `image_tag` | +| `ingress_host` | "Ingress host" | The "Host" line on the Ingress card | `host` | +| `ingress_routes` | "Ingress routes" | Routes: a list of objects with the `path` and `microservice` (microservice ID) fields | `routes` | +| `vcs_namespace_id` | "Version control namespace id" | ID of the group in which the repository is created | `id` | + +CPU and memory values are specified in the Kubernetes format, for example, `200m`, `0.5`, `256Mi`, `1Gi`. + +A shared resource is displayed on the environment diagram if the `shared_environment` property is empty or equals the environment ID. + +## Action slots + +An action slot contains processes that the Home page runs with a button or menu item. +Slots are filled in the area's "Actions" block. + +| Slot | Name in the form | Section and button | Categories | +| --- | --- | --- | --- | +| `deploy_microservice` | "Deploy microservice to an environment (no template)" | "System deployment" → "Deploy microservice" for microservices without a template | No | +| `delete_microservice` | "Delete microservice from an environment (no template)" | "System deployment" → deleting a deployment of a microservice without a template | No | +| `create_environment` | "Create environment" | "Environments" → "Create environment" | No | +| `delete_environment` | "Delete environment" | "Environments" → environment card → "Delete environment" | No | +| `order_resource` | "Order resource" | "Resource ordering" and "System deployment" → "Order resource" | Resource type, for example, `PostgreSQL` | +| `connect_shared_resource` | "Connect shared resource" | "System deployment" → dragging a resource onto a deployment | No | +| `disconnect_shared_resource` | "Disconnect shared resource" | "System deployment" → dragging a resource onto a connected deployment | No | +| `delete_shared_resource` | "Delete shared resource" | "Resource ordering" and "System deployment" → deleting a resource | Resource provider and type, for example, `Deckhouse PostgreSQL` | + +You can add several processes to a slot with the "Add process" button. +If a slot contains one process, it is selected automatically in the run window; if there are several, the user selects a process in the run window. + +### Categories + +Categories separate processes within a slot when different processes run for different resource types. +Categories are used only in the `order_resource` and `delete_shared_resource` slots; in other slots, the category field is not displayed. + +To add a category, click "Add category" and specify a value in the "Resource category" field. +The `default` category contains processes without a category. +They are displayed first and are used when there is no exact match. + +In the `order_resource` slot, the category is the type of the resource being ordered. +The Home page groups processes by category in the "Service" list and builds a type filter on the process cards. + +In the `delete_shared_resource` slot, the deletion process is selected based on the properties of the specific resource in the following order: + +1. The ` ` category, for example, `Deckhouse PostgreSQL`, based on the values of the `shared_provider` and `shared_kind` roles. +1. The `` category, for example, `PostgreSQL`. +1. The `default` category. + +The first non-empty category is used. If there are no matching processes, the resource delete button is unavailable. + +A category can contain Latin letters, digits, spaces, and the `_`, `.`, and `-` characters, must start with a letter or digit, and can be up to 64 characters long. + +## Template actions + +Template actions define processes for microservices created from a specific registry template. +The block is located in the "Microservices" area. + +Each row of the block corresponds to one template. For a row, select a template in the "Template" field and the action processes: + +| Action | Slot | Where it is run | +| --- | --- | --- | +| "Create microservice" | `create_microservice` | "Create microservice" → "Create microservice" | +| "Deploy microservice to an environment" | `deploy_microservice` | "System deployment" → "Deploy microservice" | +| "Delete microservice from an environment" | `delete_microservice` | "System deployment" → deleting a deployment | +| "Upgrade microservice from template" | `upgrade_service_from_template` | "Microservices" → microservice card → "Upgrade", as well as automatic upgrades | + +One process is selected for each template action. +A template can be added to only one row. +The "Add template" button is unavailable while templates are loading, while any row has no template selected, or when no unused templates are left. + +The "Template" list displays templates from the [template registry](../templates/registry/) in their latest available version. +If a template with bound processes is no longer available in the registry, the row is marked "not in the registry". +If the registry is empty, the tooltip "No templates available in the template registry — synchronize the registry to bind actions" is displayed. + +The Home page determines a microservice's template by the `microservice_binding_template_id` property role in that microservice's resource and selects processes as follows. +If the microservice has a template, the process bound to that template is used. +If no process is bound for an action, the action is unavailable and shows a tooltip, for example, "No deploy process is set for the {template} template". +If the microservice has no template, deployment to and deletion from an environment use the processes of the `deploy_microservice` and `delete_microservice` slots from the "Actions" block. + +A process bound to a different template is not used for the microservice, and processes from the "Actions" block do not replace a missing template binding. + +The `create_microservice` and `upgrade_service_from_template` processes are set only in the "Template actions" block; the "Actions" block has no such slots. + +## Widget slots + +A widget slot displays an existing widget in a fixed place on the Home page screen. +Slots are filled in the "Widgets" block of the "Microservices" area. + +| Slot | Name in the form | Where it is displayed | +| --- | --- | --- | +| `microservice_repository_widget` | "'Pipelines' tab widget" | "Microservices" → microservice card → "Pipelines" tab | +| `microservice_merge_requests_widget` | "'MRs' tab widget" | "Microservices" → microservice card → "MRs" tab | + +Exactly one widget is selected for each slot. If a slot is not filled, the tab displays "This section is not available yet". + +The Home page passes the selected microservice's context to the widget. In the widget configuration, the context is available through templating: + +| Path | Value | +| --- | --- | +| `.context.microservice.uuid` | UUID of the microservice entity | +| `.context.microservice.slug` | Microservice ID | +| `.context.microservice.name` | Microservice name | +| `.context.repository.id` | Value of the `microservice_gitlab_project_id` role; an empty string if the value is not set | +| `.context.repository.url` | Value of the `microservice_repository` role | + +For a configuration example, see [Widget on a microservice tab](../examples/home-widget-slot/). + +## Configuring mapping from the Home page + +You can change a section's mapping rules directly on the Home page without going to "Administration". +Changes are saved to the default mapping set. + +To change a section's rules: + +1. At the bottom of the Home page side menu, enable the "Configure mapping" toggle. +1. Click the settings icon next to the section name. The icon is displayed for sections that have mapping areas. +1. In the "Mapping: {section}" window, change the fields of the section's areas and click "Save". + +After saving, Home page pages load data according to the new rules. + +The "Configure mapping" toggle is available to users with the `update:home-mapping-sets` permission. +If there is no mapping set, the window displays the message "No active mapping set. Create one in Administration → Directories → Mapping rules.". + +## Validation on save + +Before saving, the form validates field values and checks that the selected objects exist in the catalog. + +| Message | Cause | +| --- | --- | +| "Enter a name" | The "Name" field is empty | +| "Some mapping targets were deleted from the catalog. Update or clear them: {details}" | A resource, relation, property, process, or widget selected in the set has been deleted from the catalog. `{details}` lists the roles, for example, `resource "system"` | +| "Failed to load catalog data for mapping validation. Try again later." | Failed to load catalog objects for validation | +| "Fix the errors in the specification editor before saving" | The specification editor contains errors | +| "Invalid mapping document: {details}" | A value failed format validation when saving a section from the Home page. `{details}` contains the path to the value | +| "Invalid Home mapping document" | The set document failed portal validation | +| "Cannot unset the default home mapping set without assigning another default" | The "Default for Home" flag was disabled for the default set | +| "Cannot delete the default Home mapping set" | An attempt to delete the default set | + +The portal validates the value format: + +- Property ID: Lowercase Latin letters, digits, `_`, and `-`, up to 64 characters. +- Template ID: Lowercase Latin letters, digits, and the `.`, `_`, `/`, and `-` characters, up to 128 characters. +- Widget slot: Exactly one widget. diff --git a/content/documentation/admin/home/mapping.ru.md b/content/documentation/admin/home/mapping.ru.md index 3ee6237a..d076bdc5 100644 --- a/content/documentation/admin/home/mapping.ru.md +++ b/content/documentation/admin/home/mapping.ru.md @@ -1,11 +1,12 @@ --- title: Правила маппинга weight: 30 -description: Справочник по наборам маппинга главной DDP — форма набора, области, роли ресурсов, связей и свойств, слоты действий, действия по шаблонам, слоты виджетов и ошибки проверки. +description: Справочник по наборам маппинга главной страницы DDP — форма набора, области, роли ресурсов, связей и свойств, слоты действий, действия по шаблонам, слоты виджетов и ошибки проверки. --- -Правила маппинга сопоставляют понятиям главной ресурсы, связи, параметры, процессы и виджеты каталога. -Правила хранятся в наборах маппинга главной; главная использует набор по умолчанию. Как главная выбирает набор, описано в разделе [«Обзор»](overview/#набор-маппинга-по-умолчанию). +Правила маппинга сопоставляют понятиям главной страницы ресурсы, связи, параметры, процессы и виджеты каталога. +Правила хранятся в наборах маппинга главной страницы; главная страница использует набор по умолчанию. +Как главная страница выбирает набор, описано в разделе [«Обзор»](overview/#набор-маппинга-по-умолчанию). ## Страница «Правила маппинга» @@ -13,7 +14,7 @@ description: Справочник по наборам маппинга глав На панели над таблицей расположены: -- переключатель «Показывать главную» — включает и выключает главную для всех пользователей; +- переключатель «Показывать главную» — включает и выключает главную страницу для всех пользователей; - кнопка «Создать» — открывает форму нового набора; - поле «Поиск» — фильтрует наборы по названию и идентификатору. @@ -39,7 +40,7 @@ description: Справочник по наборам маппинга глав - `update:home-mapping-sets` — изменение наборов, выбор набора по умолчанию, переключатель «Показывать главную»; - `delete:home-mapping-sets` — удаление наборов. -Для просмотра наборов разрешение не требуется: наборы читает каждая страница главной. +Для просмотра наборов разрешение не требуется, поскольку наборы читает каждая страница главной страницы. Чтобы в форме набора заполнялись списки выбора, пользователю также нужны разрешения на просмотр ресурсов, связей ресурсов, процессов (`read:processes`), виджетов (`read:widgets`) и шаблонов (`read:template-packs`). ## Форма набора @@ -49,29 +50,33 @@ description: Справочник по наборам маппинга глав На вкладке «Основная информация» заполняются поля: - «Название» — от 3 до 64 символов; -- «Идентификатор» — стабильный идентификатор набора: от 3 до 64 символов, строчные латинские буквы, цифры и дефис. После создания не меняется; -- «По умолчанию для главной» — делает набор набором по умолчанию. Первый созданный набор становится набором по умолчанию автоматически. +- «Идентификатор» — стабильный идентификатор набора: от 3 до 64 символов, строчные латинские буквы, цифры и дефис. + После создания не меняется; +- «По умолчанию для главной» — делает набор набором по умолчанию. + Первый созданный набор становится набором по умолчанию автоматически. -На вкладке «Маппинг каталога» правила сгруппированы по областям главной. Каждая область раскрывается отдельно и содержит блоки: +На вкладке «Маппинг каталога» правила сгруппированы по областям главной страницы. +Каждая область раскрывается отдельно и содержит блоки: | Блок | Назначение | | --- | --- | | «Ресурс каталога» | Ресурс, на котором строится область | | «Ресурсы каталога» | Несколько ресурсов области, у каждого свои свойства и связи. Используется в областях «Микросервисы» и «Общие ресурсы» | -| «Связи» | Связи, по которым главная обходит сущности области | -| «Свойства» | Идентификаторы параметров сущностей, которые читает главная | +| «Связи» | Связи, по которым главная страница обходит сущности области | +| «Свойства» | Идентификаторы параметров сущностей, которые читает главная страница | | «Действия» | Слоты действий области | | «Действия по шаблонам» | Процессы, привязанные к шаблону микросервиса. Только в области «Микросервисы» | | «Виджеты» | Слоты виджетов. Только в области «Микросервисы» | -У каждого поля формы есть подсказка с описанием назначения роли, её действия и места на главной. +У каждого поля формы есть подсказка с описанием назначения роли, её действия и места на главной странице. Кнопка «Редактор спецификации» открывает весь набор в виде документа JSON. Кнопка «К форме» возвращает к форме. -Удаление ключа в тексте спецификации не удаляет значение из формы: очистите значение в форме или замените его в тексте. +Удаление ключа в тексте спецификации не удаляет значение из формы. Очистите значение в форме или замените его в тексте. ### Выбор связей и свойств -Список связей и свойств роли строится по ресурсу её родительской роли. Например, связь `has_deployment` выбирается из связей ресурса роли `microservice`, а свойство `environment_domain` — из параметров ресурса роли `environment`. +Список связей и свойств роли строится по ресурсу её родительской роли. +Например, связь `has_deployment` выбирается из связей ресурса роли `microservice`, а свойство `environment_domain` — из параметров ресурса роли `environment`. Пока родительская роль не сопоставлена ресурсу, поле недоступно и отображается подсказка «Сначала настройте маппинг связанной роли ресурса, чтобы выбрать элементы из его каталога». @@ -81,7 +86,8 @@ description: Справочник по наборам маппинга глав ### Несколько ресурсов области -В областях «Микросервисы» и «Общие ресурсы» роль можно сопоставить нескольким ресурсам каталога, например микросервисам из разных систем учёта. Для каждого ресурса задаются собственные свойства и связи. +В областях «Микросервисы» и «Общие ресурсы» роль можно сопоставить нескольким ресурсам каталога, например микросервисам из разных систем учёта. +Для каждого ресурса задаются собственные свойства и связи. Чтобы добавить ресурс, нажмите «Добавить ресурс» и заполните карточку ресурса. Связь, родитель которой находится в другой области, например `contains_service` от системы к микросервису, доступна для выбора после того, как сопоставлен ресурс этой области. @@ -89,9 +95,9 @@ description: Справочник по наборам маппинга глав ## Области маппинга -Каждая область маппинга принадлежит одному разделу главной. В таблице перечислены области, разделы и их роли: +Каждая область маппинга принадлежит одному разделу главной страницы. В таблице перечислены области, разделы и их роли: -| Область | Раздел главной | Роль ресурса | Роли связей | Роли свойств | Слоты | +| Область | Раздел главной страницы | Роль ресурса | Роли связей | Роли свойств | Слоты | | --- | --- | --- | --- | --- | --- | | «Системы» | «Системы» | `system` | `has_ingress`, `system_has_deployment`, `system_has_integration` | `system_domain`, `system_lifecycle` | — | | «Микросервисы» | «Микросервисы» | `microservice` (несколько ресурсов) | `contains_service`, `has_deployment` | `microservice_*` | `deploy_microservice`, `delete_microservice`; действия по шаблонам; слоты виджетов | @@ -110,7 +116,8 @@ description: Справочник по наборам маппинга глав ## Роли ресурсов -Роль ресурса указывает, сущности какого ресурса каталога главная показывает как объекты определённого вида. В столбце «Каноничный ресурс» указан ресурс, который создаёт набор данных «Каноничная архитектура (схема)». +Роль ресурса указывает, сущности какого ресурса каталога главная страница показывает как объекты определённого вида. +В столбце «Каноничный ресурс» указан ресурс, который создаёт набор данных «Каноничная архитектура (схема)». | Роль | Название в форме | Назначение | Каноничный ресурс | | --- | --- | --- | --- | @@ -127,7 +134,7 @@ description: Справочник по наборам маппинга глав ## Роли связей -Роль связи указывает, по какой связи каталога главная переходит от одной сущности к другой. +Роль связи указывает, по какой связи каталога главная страница переходит от одной сущности к другой. | Роль | Название в форме | Направление | Каноничная связь | | --- | --- | --- | --- | @@ -144,13 +151,16 @@ description: Справочник по наборам маппинга глав | `deployment_in_environment` | «Развёртывание в окружении» | Развёртывание → окружение | «Deployment — окружение» | | `cluster_hosts_environment` | «Кластер размещает окружение» | Кластер → окружение | «Кластер — окружение» | -Системы связаны друг с другом только через интеграции: система-клиент связана с интеграцией ролью `system_has_integration`, а интеграция с системой-сервером — ролью `integration_targets_system`. +Системы связаны друг с другом только через интеграции. +Система-клиент связана с интеграцией ролью `system_has_integration`, а интеграция с системой-сервером — ролью `integration_targets_system`. -Если роль связи не сопоставлена, главная использует любую связь между сущностями соответствующих ресурсов. Это позволяет работать с частично заполненным набором. +Если роль связи не сопоставлена, главная страница использует любую связь между сущностями соответствующих ресурсов. +Это позволяет работать с частично заполненным набором. ## Роли свойств -Роль свойства содержит идентификатор параметра сущности. Параметр выбирается из параметров ресурса родительской роли: для `system_*` — ресурса роли `system`, для `microservice_*` — ресурса роли `microservice` и т. д. +Роль свойства содержит идентификатор параметра сущности. +Параметр выбирается из параметров ресурса родительской роли: для `system_*` — ресурса роли `system`, для `microservice_*` — ресурса роли `microservice` и т. д. ### Системы, интеграции, кластеры, гайды @@ -172,7 +182,8 @@ description: Справочник по наборам маппинга глав ### Микросервисы -Роли свойств микросервисов. Значения ролей `microservice_binding_*` записывает процесс создания микросервиса из шаблона; по ним работает [обновление из шаблона](../templates/updates/). +Роли свойств микросервисов. +Значения ролей `microservice_binding_*` записывает процесс создания микросервиса из шаблона; по ним работает [обновление из шаблона](../templates/updates/). | Роль | Название в форме | Назначение | Каноничный параметр | | --- | --- | --- | --- | @@ -188,7 +199,7 @@ description: Справочник по наборам маппинга глав | `microservice_binding_template_upgrade_add_if_missing` | «Пути, добавляемые при обновлении» | Список добавляемых путей, заданный для микросервиса | `template_upgrade_add_if_missing` | | `microservice_vcs_provider` | «Провайдер системы контроля версий» | Провайдер репозитория микросервиса | `vcs_provider` | | `microservice_vcs_external_service_uuid` | «Внешний сервис системы контроля версий» | Внешний сервис GitLab, в котором находится репозиторий | `vcs_external_service_uuid` | -| `microservice_default_branch` | «Ветка по умолчанию микросервиса» | Ветка, в которую создаётся запрос на слияние с обновлением | `default_branch` | +| `microservice_default_branch` | «Ветка по умолчанию микросервиса» | Ветка, в которую создаётся запрос на слияние (Merge Request) с обновлением | `default_branch` | | `microservice_open_mr_count` | «Открытые merge request» | Показатель «Открытые MR» | `open_mr_count` | | `microservice_last_pipeline_status` | «Статус последнего пайплайна» | Показатель «Последний пайплайн» | `last_pipeline_status` | | `microservice_last_pipeline_id` | «ID последнего пайплайна» | Номер пайплайна в показателе «Последний пайплайн» | `last_pipeline_id` | @@ -212,7 +223,8 @@ description: Справочник по наборам маппинга глав Окружение также считается временным, если его тип содержит `temp` или `preview` без учёта регистра. -В каноничной модели параметр `deletion_ttl` заполняется из лейбла `ddp.deckhouse.io/deletion-ttl` неймспейса при каждой синхронизации. Параметры `type`, `domain` и `marked_for_deletion` из кластера не синхронизируются и задаются в каталоге. +В каноничной модели параметр `deletion_ttl` заполняется из лейбла `ddp.deckhouse.io/deletion-ttl` неймспейса при каждой синхронизации. +Параметры `type`, `domain` и `marked_for_deletion` из кластера не синхронизируются и задаются в каталоге. ### Общие ресурсы и развёртывания @@ -239,7 +251,8 @@ description: Справочник по наборам маппинга глав ## Слоты действий -Слот действия содержит процессы, которые главная запускает кнопкой или пунктом меню. Слоты заполняются в блоке «Действия» области. +Слот действия содержит процессы, которые главная страница запускает кнопкой или пунктом меню. +Слоты заполняются в блоке «Действия» области. | Слот | Название в форме | Раздел и кнопка | Категории | | --- | --- | --- | --- | @@ -252,21 +265,25 @@ description: Справочник по наборам маппинга глав | `disconnect_shared_resource` | «Отключить общий ресурс» | «Развертывание систем» → перетаскивание ресурса на подключённое развёртывание | Нет | | `delete_shared_resource` | «Удалить общий ресурс» | «Заказ ресурсов» и «Развертывание систем» → удаление ресурса | Провайдер и тип ресурса, например `Deckhouse PostgreSQL` | -В слот можно добавить несколько процессов кнопкой «Добавить процесс». Если в слоте один процесс, он выбирается в окне запуска автоматически; если несколько — пользователь выбирает процесс в окне запуска. +В слот можно добавить несколько процессов кнопкой «Добавить процесс». +Если в слоте один процесс, он выбирается в окне запуска автоматически; если несколько — пользователь выбирает процесс в окне запуска. ### Категории -Категории разделяют процессы внутри слота, когда для разных типов ресурсов запускаются разные процессы. Категории используются только в слотах `order_resource` и `delete_shared_resource`; в остальных слотах поле категории не отображается. +Категории разделяют процессы внутри слота, когда для разных типов ресурсов запускаются разные процессы. +Категории используются только в слотах `order_resource` и `delete_shared_resource`; в остальных слотах поле категории не отображается. Чтобы добавить категорию, нажмите «Добавить категорию» и укажите значение в поле «Категория ресурса». -Категория `default` содержит процессы без категории: они отображаются первыми и используются, когда точного совпадения нет. +Категория `default` содержит процессы без категории. +Они отображаются первыми и используются, когда точного совпадения нет. -В слоте `order_resource` категория — это тип заказываемого ресурса. Главная группирует по ней процессы в списке «Сервис» и строит фильтр по типу на карточках процессов. +В слоте `order_resource` категория — это тип заказываемого ресурса. +Главная страница группирует по ней процессы в списке «Сервис» и строит фильтр по типу на карточках процессов. В слоте `delete_shared_resource` процесс удаления выбирается по параметрам конкретного ресурса в следующем порядке: -1. Категория `<провайдер> <тип>`, например `Deckhouse PostgreSQL`, по значениям ролей `shared_provider` и `shared_kind`. -1. Категория `<тип>`, например `PostgreSQL`. +1. Категория ` `, например `Deckhouse PostgreSQL`, по значениям ролей `shared_provider` и `shared_kind`. +1. Категория ``, например `PostgreSQL`. 1. Категория `default`. Используется первая непустая категория. Если подходящих процессов нет, кнопка удаления ресурса недоступна. @@ -275,7 +292,8 @@ description: Справочник по наборам маппинга глав ## Действия по шаблонам -Действия по шаблонам задают процессы для микросервисов, созданных из конкретного шаблона реестра. Блок находится в области «Микросервисы». +Действия по шаблонам задают процессы для микросервисов, созданных из конкретного шаблона реестра. +Блок находится в области «Микросервисы». Каждая строка блока соответствует одному шаблону. Для строки выберите шаблон в поле «Шаблон» и процессы действий: @@ -286,16 +304,18 @@ description: Справочник по наборам маппинга глав | «Удалить микросервис с окружения» | `delete_microservice` | «Развертывание систем» → удаление развёртывания | | «Обновить микросервис из шаблона» | `upgrade_service_from_template` | «Микросервисы» → карточка микросервиса → «Обновить», а также автоматическое обновление | -Для каждого действия шаблона выбирается один процесс. Шаблон можно добавить только в одну строку. Кнопка «Добавить шаблон» недоступна, пока шаблоны загружаются, пока у какой-либо строки не выбран шаблон или когда свободных шаблонов не осталось. +Для каждого действия шаблона выбирается один процесс. +Шаблон можно добавить только в одну строку. +Кнопка «Добавить шаблон» недоступна, пока шаблоны загружаются, пока у какой-либо строки не выбран шаблон или когда свободных шаблонов не осталось. В списке «Шаблон» отображаются шаблоны из [реестра шаблонов](../templates/registry/) в последней доступной версии. Если шаблон, к которому привязаны процессы, больше не доступен в реестре, строка отмечается «нет в реестре». Если реестр пуст, отображается подсказка «В реестре шаблонов нет доступных шаблонов — синхронизируйте реестр, чтобы привязать действия». -Главная определяет шаблон микросервиса по роли свойства `microservice_binding_template_id` в ресурсе этого микросервиса и выбирает процессы следующим образом: - -- у микросервиса есть шаблон — используется процесс, привязанный к этому шаблону. Если процесс для действия не привязан, действие недоступно с подсказкой, например «Для шаблона {template} не задан процесс развёртывания»; -- у микросервиса нет шаблона — для развёртывания и удаления с окружения используются процессы слотов `deploy_microservice` и `delete_microservice` из блока «Действия». +Главная страница определяет шаблон микросервиса по роли свойства `microservice_binding_template_id` в ресурсе этого микросервиса и выбирает процессы следующим образом. +Если у микросервиса есть шаблон, используется процесс, привязанный к этому шаблону. +Если процесс для действия не привязан, действие недоступно с подсказкой, например «Для шаблона {template} не задан процесс развёртывания». +Если у микросервиса нет шаблона, для развёртывания и удаления с окружения используются процессы слотов `deploy_microservice` и `delete_microservice` из блока «Действия». Процесс, привязанный к другому шаблону, для микросервиса не используется, а процессы из блока «Действия» не заменяют отсутствующую привязку шаблона. @@ -303,7 +323,8 @@ description: Справочник по наборам маппинга глав ## Слоты виджетов -Слот виджета выводит существующий виджет в фиксированном месте экрана главной. Слоты заполняются в блоке «Виджеты» области «Микросервисы». +Слот виджета выводит существующий виджет в фиксированном месте экрана главной страницы. +Слоты заполняются в блоке «Виджеты» области «Микросервисы». | Слот | Название в форме | Где отображается | | --- | --- | --- | @@ -312,7 +333,7 @@ description: Справочник по наборам маппинга глав В каждый слот выбирается ровно один виджет. Если слот не заполнен, на вкладке отображается «Раздел пока недоступен». -Главная передаёт виджету контекст выбранного микросервиса. В конфигурации виджета контекст доступен через шаблонизацию: +Главная страница передаёт виджету контекст выбранного микросервиса. В конфигурации виджета контекст доступен через шаблонизацию: | Путь | Значение | | --- | --- | @@ -324,17 +345,18 @@ description: Справочник по наборам маппинга глав Пример настройки — в разделе [«Виджет на вкладке микросервиса»](../examples/home-widget-slot/). -## Настройка маппинга с главной +## Настройка маппинга с главной страницы -Правила маппинга раздела можно изменить прямо на главной, не переходя в «Администрирование». Изменения сохраняются в набор маппинга по умолчанию. +Правила маппинга раздела можно изменить прямо на главной странице, не переходя в «Администрирование». +Изменения сохраняются в набор маппинга по умолчанию. Чтобы изменить правила раздела: -1. В нижней части бокового меню главной включите переключатель «Настроить маппинг». +1. В нижней части бокового меню главной страницы включите переключатель «Настроить маппинг». 1. Нажмите значок настройки рядом с названием раздела. Значок отображается у разделов, у которых есть области маппинга. 1. В окне «Маппинг: {раздел}» измените поля областей раздела и нажмите «Сохранить». -После сохранения страницы главной загружают данные по новым правилам. +После сохранения страницы главной страницы загружают данные по новым правилам. Переключатель «Настроить маппинг» доступен пользователям с разрешением `update:home-mapping-sets`. Если набора маппинга нет, в окне отображается сообщение «Нет активного набора маппинга. Создайте его в Администрирование → Справочники → Правила маппинга.». @@ -349,7 +371,7 @@ description: Справочник по наборам маппинга глав | «Некоторые цели маппинга удалены из каталога. Обновите или очистите: {details}» | Ресурс, связь, параметр, процесс или виджет, выбранный в наборе, удалён из каталога. В `{details}` перечислены роли, например `ресурс «system»` | | «Не удалось загрузить данные каталога для проверки маппинга. Попробуйте позже.» | Не удалось загрузить объекты каталога для проверки | | «Исправьте ошибки в редакторе спецификации перед сохранением» | В редакторе спецификации есть ошибки | -| «Некорректный документ маппинга: {details}» | Значение не прошло проверку формата при сохранении раздела с главной. В `{details}` указан путь к значению | +| «Некорректный документ маппинга: {details}» | Значение не прошло проверку формата при сохранении раздела с главной страницы. В `{details}` указан путь к значению | | «Некорректный документ маппинга главной» | Документ набора не прошёл проверку портала | | «Нельзя снять признак набора по умолчанию без назначения другого набора» | Выключен признак «По умолчанию для главной» у набора по умолчанию | | «Нельзя удалить набор маппинга главной по умолчанию» | Попытка удалить набор по умолчанию | diff --git a/content/documentation/admin/home/overview.md b/content/documentation/admin/home/overview.md new file mode 100644 index 00000000..d21b6a5e --- /dev/null +++ b/content/documentation/admin/home/overview.md @@ -0,0 +1,158 @@ +--- +title: Overview +weight: 10 +description: How the DDP Home page gets data from the catalog, which set of mapping rules it uses, how to enable it, and which permissions are required to work with it. +--- + +The Home page is the workspace for developers and system owners in Deckhouse Development Portal (DDP, portal). +It brings together teams, systems and their integrations, microservices, environments, deployments, shared resources, and cluster resource consumption. +From the Home page, users create microservices from templates, deploy them to environments, order resources, and upgrade microservices to new template versions. + +{{< alert level="warning" >}} +The Home page is a Preview feature. +The set of sections, the structure of mapping rules, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +For a description of the screens from the user's perspective, see the Home page user guide. + +## How it works + +The Home page does not store its own data. +All objects it displays are catalog entities, and all actions are catalog processes. +Mapping rules define which resources, relations, properties, processes, and widgets to use. + +Mapping rules map catalog objects to Home page concepts: + +- **Resource role**: A catalog resource whose entities the Home page displays as systems, microservices, environments, and so on. +- **Relation role**: A catalog relation the Home page uses to find, for example, the microservices of a system or the environment of a deployment. +- **Property role**: The ID of an entity property from which the Home page reads, for example, the microservice language or the environment domain. +- **Action slot**: Processes run from the Home page with a button or menu item, for example, "Create environment". +- **Template action**: A process that performs an action on a microservice created from a specific template. +- **Widget slot**: A widget that the Home page displays in a fixed place on the screen. + +The diagram below shows how catalog data reaches the Home page screens: + +```mermaid +flowchart LR + subgraph Catalog["Catalog"] + R["Resources, relations, parameters"] + P["Processes"] + W["Widgets"] + end + M["Home mapping set
(default)"] + H["Home page screens"] + R --> M + P --> M + W --> M + M --> H + H -- "process run
with context" --> P +``` + +Roles are not tied to specific resource IDs, so the Home page can be connected to any catalog model that contains the required resources and relations. +A ready-made catalog model and mapping rules for it are created by the "Canonical architecture (schema)" dataset, which is applied by the [initial setup wizard](setup/). + +For the full list of roles, slots, and rules for filling them in, see [Mapping rules](mapping/). + +## Default mapping set + +Mapping rules are stored in Home mapping sets. +The portal can contain several sets, but the Home page uses only one — the default set. + +The Home page selects a set in the following order: + +1. The set with the "Default for Home" toggle enabled. +1. The set with the `home-default` ID. +1. The first set in the list. + +Only one set can be the default set. +When another set becomes the default set, the flag is automatically cleared on the previous one. +The default set cannot be deleted. + +Mapping rules apply to all portal users. Users cannot select a different set on the Home page. + +## Enabling the Home page + +The Home page is disabled after the portal is installed. +The "Home" tab is hidden for all users, and Home page URLs redirect to the catalog. + +To enable the Home page: + +1. Go to "Administration" → "Directories" → "Mapping rules". +1. Enable the "Show Home" toggle. + +The toggle takes effect immediately for all users. Changing it requires the `update:home-mapping-sets` permission. + +When the Home page is enabled, users see the "Home" tab in the top bar, and clicking it opens the "Teams" section. + +{{< alert level="info" >}} +The "The platform is ready for setup" banner, from which the initial setup wizard is launched, is displayed on the Home page. +While the Home page is disabled, the wizard is available only in "Administration" → "Directories" → "Datasets". +{{< /alert >}} + +## Home page sections + +Home page sections are grouped in the side menu. +Each section requires its own mapping roles; if the section's main role is not mapped to a catalog resource, the section displays the message "Configure mapping rules or apply the 'Canonical architecture' dataset". + +The table lists the sections, their main resource roles, and action slots: + +| Group | Section | Resource roles | Action slots and template actions | +| --- | --- | --- | --- | +| Organization | "Teams" | Portal teams; `system`, `microservice` | — | +| Architecture | "Systems" | `system`, `microservice`, `shared_resource`, `deployment`, `environment`, `cluster`, `integration` | — | +| Architecture | "Integrations" | `system`, `integration` | — | +| Architecture | "Diagrams" | `system`, `microservice`, `shared_resource` | — | +| Architecture | "Clusters and networks" | `cluster`, `environment` | — | +| Architecture | "How the platform works" | `guide` | — | +| Development | "Create microservice" | `system`, `vcs_namespace` | "Create microservice" template action | +| Development | "Microservices" | `microservice`, `system`, `shared_resource`, `deployment`, `environment`, `cluster` | "Upgrade microservice from template" template action; widget slots for the "Pipelines" and "MRs" tabs | +| Development | "System deployment" | `system`, `microservice`, `environment`, `shared_resource`, `ingress`, `deployment` | `deploy_microservice`, `delete_microservice`, `order_resource`, `connect_shared_resource`, `disconnect_shared_resource`, `delete_shared_resource`; "Deploy microservice to an environment" and "Delete microservice from an environment" template actions | +| Development | "Resource ordering" | `shared_resource`, `system` | `order_resource`, `delete_shared_resource` | +| Development | "Environments" | `environment` | `create_environment`, `delete_environment` | +| Development | "Resource consumption" | `deployment` | — | + +The "DORA and SDLC metrics", "Operating costs", "Platform adaptation", "System requirements", "Build and delivery", and "Troubleshooting hub" sections and all sections of the "Security" group are marked "TBD" in the menu. +Opening such a section displays the message "This section is not available yet". + +## Access permissions + +The Home page uses the common portal role model. +There is no separate role for the Home page. +What a user can see and do is determined by their permissions on entities, processes, and Home page settings. + +The table lists the permissions that affect how the Home page works: + +| Permission | Where it is used | +| --- | --- | +| `read:entities` (global or on a resource) | Loading entities for all sections. If a resource's entities are not available to the user, the section looks the same as with an unmapped role | +| `read:processes` | Loading action slot processes. A process that is not available to the user is not displayed in the slot | +| `control:processes` (global, on a resource, or on an entity) | Running processes from the Home page. Run buttons are not disabled; without the permission, the portal returns the "Forbidden by RBAC" error | +| `update:entities` or the `update:entity` permission on an entity | Changing the environment domain in the "Environments" section | +| `run:actions` on the microservice entity | The "Upgrade" button on the microservice card | +| `read:template-packs` | The template gallery in the "Create microservice" section and the new template version notification on the microservice card | +| `read:template-registries` | Notifications about prerelease template versions on the microservice card | +| `update:home-mapping-sets` | The "Show Home" and "Configure mapping" toggles, changing mapping rules | +| `create:home-mapping-sets`, `delete:home-mapping-sets` | Creating and deleting Home mapping sets | +| `apply:seeds` | The "The platform is ready for setup" banner and the initial setup wizard | + +No separate permission is required to view the Home page. +The "Home" tab is available to all users if the Home page is enabled. + +{{< alert level="warning" >}} +The "Developer" role preset does not include the `read:entities` permission. +For developers to see data on the Home page, grant them access to the entities of the required resources through resource roles, or add the `read:entities` permission to their role. +{{< /alert >}} + +For more information about permissions, see [Role model](../security/rbac/). + +## Setup procedure + +To prepare the Home page for use, follow these steps: + +1. Apply the datasets with the [initial setup wizard](setup/) or configure [mapping rules](mapping/) for your own catalog model. +1. Enable the "Show Home" toggle. +1. Connect the [template registry](../templates/registry/) and bind processes to templates in the "Template actions" block. +1. If necessary, add your own processes to action slots. + Requirements for such processes are described in [Home page processes](processes/). + +For a step-by-step scenario, see the [Home page quick start](../examples/home-quick-start/) example. diff --git a/content/documentation/admin/home/overview.ru.md b/content/documentation/admin/home/overview.ru.md index 9786983a..32b80d07 100644 --- a/content/documentation/admin/home/overview.ru.md +++ b/content/documentation/admin/home/overview.ru.md @@ -4,31 +4,33 @@ weight: 10 description: Как главная страница DDP получает данные из каталога, какой набор правил маппинга она использует, как её включить и какие права нужны для работы с ней. --- -Главная — рабочее пространство разработчиков и владельцев систем в Deckhouse Development Portal (DDP, портал). +Главная страница — рабочее пространство разработчиков и владельцев систем в Deckhouse Development Portal (DDP, портал). На ней собраны команды, системы и их интеграции, микросервисы, окружения, развёртывания, общие ресурсы и потребление ресурсов кластера. -С главной пользователи создают микросервисы из шаблонов, разворачивают их на окружения, заказывают ресурсы и обновляют микросервисы до новых версий шаблонов. +С главной страницы пользователи создают микросервисы из шаблонов, разворачивают их на окружения, заказывают ресурсы и обновляют микросервисы до новых версий шаблонов. {{< alert level="warning" >}} -Главная — функциональность на стадии Preview. Состав разделов, структура правил маппинга и API могут измениться в следующих выпусках без сохранения обратной совместимости. +Главная страница — функциональность на стадии Preview. +Состав разделов, структура правил маппинга и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} -Описание экранов с точки зрения пользователя — в [руководстве пользователя по главной](../../user/home/overview/). +Описание экранов с точки зрения пользователя — в [руководстве пользователя по главной странице](../../user/home/overview/). ## Принцип работы -Главная не хранит собственных данных. Все объекты, которые она показывает, — это сущности каталога, а все действия — это процессы каталога. +Главная страница не хранит собственных данных. +Все объекты, которые она показывает, — это сущности каталога, а все действия — это процессы каталога. Какие ресурсы, связи, параметры, процессы и виджеты использовать, задают правила маппинга. -Правила маппинга сопоставляют понятиям главной объекты каталога: +Правила маппинга сопоставляют понятиям главной страницы объекты каталога: -- **роль ресурса** — ресурс каталога, сущности которого главная показывает как системы, микросервисы, окружения и т. п.; -- **роль связи** — связь каталога, по которой главная находит, например, микросервисы системы или окружение развёртывания; -- **роль свойства** — идентификатор параметра сущности, из которого главная читает, например, язык микросервиса или домен окружения; -- **слот действия** — процессы, которые запускаются с главной кнопкой или пунктом меню, например «Создать окружение»; +- **роль ресурса** — ресурс каталога, сущности которого главная страница показывает как системы, микросервисы, окружения и т. п.; +- **роль связи** — связь каталога, по которой главная страница находит, например, микросервисы системы или окружение развёртывания; +- **роль свойства** — идентификатор параметра сущности, из которого главная страница читает, например, язык микросервиса или домен окружения; +- **слот действия** — процессы, которые запускаются с главной страницы кнопкой или пунктом меню, например «Создать окружение»; - **действие по шаблону** — процесс, который выполняет действие над микросервисом, созданным из конкретного шаблона; -- **слот виджета** — виджет, который главная показывает в фиксированном месте экрана. +- **слот виджета** — виджет, который главная страница показывает в фиксированном месте экрана. -Схема ниже показывает, как данные каталога попадают на экраны главной: +Схема ниже показывает, как данные каталога попадают на экраны главной страницы: ```mermaid flowchart LR @@ -37,8 +39,8 @@ flowchart LR P["Процессы"] W["Виджеты"] end - M["Набор маппинга главной
(по умолчанию)"] - H["Экраны главной"] + M["Набор маппинга главной страницы
(по умолчанию)"] + H["Экраны главной страницы"] R --> M P --> M W --> M @@ -46,47 +48,51 @@ flowchart LR H -- "запуск процесса
с контекстом" --> P ``` -Роли не привязаны к конкретным идентификаторам ресурсов: главную можно подключить к любой модели каталога, в которой есть нужные ресурсы и связи. +Роли не привязаны к конкретным идентификаторам ресурсов, поэтому главную страницу можно подключить к любой модели каталога, в которой есть нужные ресурсы и связи. Готовую модель каталога и правила маппинга для неё создаёт набор данных «Каноничная архитектура (схема)», который применяется [мастером первоначальной настройки](setup/). Полный перечень ролей, слотов и правил их заполнения — в разделе [«Правила маппинга»](mapping/). ## Набор маппинга по умолчанию -Правила маппинга хранятся в наборах маппинга главной. В портале может быть несколько наборов, но главная использует только один — набор по умолчанию. +Правила маппинга хранятся в наборах маппинга главной страницы. +В портале может быть несколько наборов, но главная страница использует только один — набор по умолчанию. -Главная выбирает набор в следующем порядке: +Главная страница выбирает набор в следующем порядке: 1. Набор, у которого включён переключатель «По умолчанию для главной». 1. Набор с идентификатором `home-default`. 1. Первый набор в списке. -Набором по умолчанию может быть только один набор. Когда другой набор становится набором по умолчанию, признак у предыдущего снимается автоматически. +Набором по умолчанию может быть только один набор. +Когда другой набор становится набором по умолчанию, признак у предыдущего снимается автоматически. Набор по умолчанию нельзя удалить. -Правила маппинга действуют для всех пользователей портала. Выбрать другой набор на главной пользователь не может. +Правила маппинга действуют для всех пользователей портала. Выбрать другой набор на главной странице пользователь не может. -## Включение главной +## Включение главной страницы -Главная выключена после установки портала: вкладка «Главная» скрыта у всех пользователей, а адреса страниц главной перенаправляют в каталог. +Главная страница выключена после установки портала. +Вкладка «Главная» скрыта у всех пользователей, а адреса страниц главной страницы перенаправляют в каталог. -Чтобы включить главную: +Чтобы включить главную страницу: 1. Перейдите в раздел «Администрирование» → «Справочники» → «Правила маппинга». 1. Включите переключатель «Показывать главную». Переключатель действует сразу для всех пользователей. Для его изменения требуется разрешение `update:home-mapping-sets`. -При включении главной у пользователей в верхней панели появляется вкладка «Главная», а при переходе на неё открывается раздел «Команды». +При включении главной страницы у пользователей в верхней панели появляется вкладка «Главная», а при переходе на неё открывается раздел «Команды». {{< alert level="info" >}} -Баннер «Платформа готова к настройке», из которого запускается мастер первоначальной настройки, отображается на главной. -Пока главная выключена, мастер доступен только в разделе «Администрирование» → «Справочники» → «Наборы данных». +Баннер «Платформа готова к настройке», из которого запускается мастер первоначальной настройки, отображается на главной странице. +Пока главная страница выключена, мастер доступен только в разделе «Администрирование» → «Справочники» → «Наборы данных». {{< /alert >}} -## Разделы главной +## Разделы главной страницы -Разделы главной сгруппированы в боковом меню. Для работы каждого раздела нужны свои роли маппинга; если основная роль раздела не сопоставлена ресурсу каталога, в разделе отображается сообщение «Настройте правила маппинга или примените набор данных «Каноничная архитектура»». +Разделы главной страницы сгруппированы в боковом меню. +Для работы каждого раздела нужны свои роли маппинга; если основная роль раздела не сопоставлена ресурсу каталога, в разделе отображается сообщение «Настройте правила маппинга или примените набор данных «Каноничная архитектура»». В таблице перечислены разделы, их основные роли ресурсов и слоты действий: @@ -110,39 +116,43 @@ flowchart LR ## Права доступа -Главная использует общую ролевую модель портала. Отдельной роли для главной нет: что увидит и сможет сделать пользователь, определяют его разрешения на сущности, процессы и настройки главной. +Главная страница использует общую ролевую модель портала. +Отдельной роли для главной страницы нет. +Что увидит и сможет сделать пользователь, определяют его разрешения на сущности, процессы и настройки главной страницы. -В таблице перечислены разрешения, которые влияют на работу главной: +В таблице перечислены разрешения, которые влияют на работу главной страницы: | Разрешение | Где используется | | --- | --- | | `read:entities` (глобальное или на ресурс) | Загрузка сущностей для всех разделов. Если сущности ресурса недоступны пользователю, раздел выглядит так же, как при несопоставленной роли | | `read:processes` | Загрузка процессов слотов действий. Процесс, недоступный пользователю, не отображается в слоте | -| `control:processes` (глобальное, на ресурс или на сущность) | Запуск процессов с главной. Кнопки запуска не блокируются; при отсутствии разрешения портал возвращает ошибку «Запрещено политиками доступа» | +| `control:processes` (глобальное, на ресурс или на сущность) | Запуск процессов с главной страницы. Кнопки запуска не блокируются; при отсутствии разрешения портал возвращает ошибку «Запрещено политиками доступа» | | `update:entities` или разрешение `update:entity` на сущность | Изменение домена окружения в разделе «Окружения» | | `run:actions` на сущность микросервиса | Кнопка «Обновить» в карточке микросервиса | | `read:template-packs` | Галерея шаблонов в разделе «Создать микросервис» и уведомление о новой версии шаблона в карточке микросервиса | | `read:template-registries` | Уведомления о предварительных (prerelease) версиях шаблонов в карточке микросервиса | | `update:home-mapping-sets` | Переключатели «Показывать главную» и «Настроить маппинг», изменение правил маппинга | -| `create:home-mapping-sets`, `delete:home-mapping-sets` | Создание и удаление наборов маппинга главной | +| `create:home-mapping-sets`, `delete:home-mapping-sets` | Создание и удаление наборов маппинга главной страницы | | `apply:seeds` | Баннер «Платформа готова к настройке» и мастер первоначальной настройки | -Для просмотра главной отдельное разрешение не требуется: вкладка «Главная» доступна всем пользователям, если главная включена. +Для просмотра главной страницы отдельное разрешение не требуется. +Вкладка «Главная» доступна всем пользователям, если главная страница включена. {{< alert level="warning" >}} Пресет роли «Developer» не содержит разрешения `read:entities`. -Чтобы разработчики видели данные на главной, выдайте им доступ к сущностям нужных ресурсов через роли ресурсов или добавьте разрешение `read:entities` в их роль. +Чтобы разработчики видели данные на главной странице, выдайте им доступ к сущностям нужных ресурсов через роли ресурсов или добавьте разрешение `read:entities` в их роль. {{< /alert >}} Подробнее о разрешениях — в разделе [«Ролевая модель»](../security/rbac/). ## Порядок настройки -Чтобы подготовить главную к работе, выполните следующие шаги: +Чтобы подготовить главную страницу к работе, выполните следующие шаги: 1. Примените наборы данных [мастером первоначальной настройки](setup/) или настройте [правила маппинга](mapping/) для собственной модели каталога. 1. Включите переключатель «Показывать главную». 1. Подключите [реестр шаблонов](../templates/registry/) и привяжите процессы к шаблонам в блоке «Действия по шаблонам». -1. При необходимости добавьте собственные процессы в слоты действий. Требования к таким процессам описаны в разделе [«Процессы главной»](processes/). +1. При необходимости добавьте собственные процессы в слоты действий. + Требования к таким процессам описаны в разделе [«Процессы главной страницы»](processes/). -Пошаговый сценарий — в примере [«Быстрая настройка главной»](../examples/home-quick-start/). +Пошаговый сценарий — в примере [«Быстрая настройка главной страницы»](../examples/home-quick-start/). diff --git a/content/documentation/admin/home/processes.md b/content/documentation/admin/home/processes.md new file mode 100644 index 00000000..70451d0a --- /dev/null +++ b/content/documentation/admin/home/processes.md @@ -0,0 +1,186 @@ +--- +title: Home page processes +weight: 40 +description: Requirements for processes run from the DDP Home page — the run entity, the run context and its keys for each scenario, result display, and naming conventions. +--- + +Regular catalog processes are run from the Home page. +The Home page passes the process the entity it runs for and the run context — data about the objects selected on the screen. +The process reads the context in templates of parameters, actions, and entity update rules. + +Processes for the Home page are created the same way as any other process: [in the process editor](../processes/overview/). +The process is then added to an action slot or template action in the [mapping rules](mapping/#action-slots). + +## Running a process from the Home page + +All Home page scenarios end with the "Run process" window. +The window title displays the name of the entity the process is run for. + +The run window works the same way as when running a process from the catalog: + +- If the slot contains several processes, the user selects a process from the list; if there is only one process, it is selected automatically. +- By default, only process parameters marked to be shown in the simplified form and unfilled required parameters are displayed. + The "All process parameters" toggle shows all parameters and the task configuration. +- Default parameter values are displayed as is, including templates such as `{{ .context.environment.slug }}`. + Templates are evaluated when the process is run. + +After you click "Run", the notification "Process '{name}' started" is displayed. + +If a required parameter is still empty after the template is evaluated, for example, because the key is missing from the context, the process does not run, and the "Failed to run process" error is displayed. +If the user does not have the `control:processes` permission, the "Forbidden by RBAC" error is displayed. + +## Run context + +The run context is available in process templates through the `.context` root: in default values of process parameters, in action bodies, in entity creation and update rules, in gateway conditions, and in loops. + +Entities in the context are passed in a single format: + +```yaml +name: +slug: +uuid: +properties: + : +``` + +Where: + +- ``: Entity name. +- ``: Entity ID. +- ``: Entity UUID. +- ``: Parameter ID. +- ``: Parameter value. + +The `properties` keys are the IDs of entity properties in the catalog, not mapping roles. +For example, the environment domain in the canonical model is read as `.context.environment.properties.domain`. + +Examples of accessing the context: + +```go-html-template +{{ .context.environment.slug }} +{{ .context.microservice.name }} +{{ with .context.environment.properties.domain }}{{ $.context.microservice.slug }}.{{ . }}{{ end }} +``` + +In process parameter values, a missing context key evaluates to an empty string, while in action bodies and conditions it fails the step with an error. +Therefore, read the context in default values of process parameters, and use process parameters in actions. +For details, see [Templating](../../user/templating/#process-launch-context). + +## Entity and context by scenario + +The table lists the Home page scenarios, the run entity (`.entity`), and the context keys: + +| Scenario | Slot | Run entity | `.context` keys | +| --- | --- | --- | --- | +| Creating a microservice | `create_microservice` template action | Selected system | `microservice`, `repository`, `system`, `template` | +| Upgrading a microservice from a template | `upgrade_service_from_template` template action | Microservice | `template`, `upgrade`, `review` | +| Deploying a microservice to an environment | `deploy_microservice` or a template action | Microservice | `environment`, `microservice`, `system` | +| Deleting a microservice from an environment | `delete_microservice` or a template action | Microservice | `environment`, `microservice`, `system` | +| Ordering a resource | `order_resource` | Selected system | `environment`, `system` | +| Deleting a shared resource | `delete_shared_resource` | Shared resource | `system` | +| Connecting and disconnecting a shared resource | `connect_shared_resource`, `disconnect_shared_resource` | Shared resource | `deployment`, `environment`, `system`, `microservice` | +| Creating an environment | `create_environment` | The first environment by name; if there are no environments, the first system by name | Not passed | +| Deleting an environment | `delete_environment` | Environment | Not passed | + +The process must be bound to the resource of the run entity from the table. +For example, ordering a shared resource requires binding to the systems resource, deleting it requires binding to the shared resources resource, and creating an environment requires binding to the environments and systems resources. +For existing configurations, check these bindings before running; a resource mismatch causes the run to be rejected. + +The `system` key is passed if a system is selected on the screen. +When connecting and disconnecting a shared resource, the `microservice` key is passed if a microservice is found for the deployment. + +When creating an environment, the run entity is not related to the environment being created: `.entity` in such a process points to an existing environment or system. +The process gets the new environment's data from its own parameters, which the user fills in. + +When deleting a shared resource in the "Resource ordering" section, the `system` key contains the system selected in the section header. + +### Creating a microservice + +The "Create microservice" wizard passes the process a context with the following structure: + +| Path | Value | +| --- | --- | +| `.context.microservice.name` | Microservice name | +| `.context.microservice.slug` | Microservice ID | +| `.context.repository.default_branch` | Value of the template registry's "Default branch" setting; if the setting is empty, `main` | +| `.context.repository.description` | Repository description; can be empty | +| `.context.repository.namespace` | Selected namespace in the version control system: `id` (the `vcs_namespace_id` role value), `name`, `slug`, `uuid` | +| `.context.system` | Selected system in the entity format | +| `.context.template.id` | Template ID | +| `.context.template.version` | Selected template version | +| `.context.template.source` | Name of the registry the template was obtained from | +| `.context.template.language` | Template language | +| `.context.template.values` | Template parameter values from the "Parameters" step. Parameters with the `x-ddp-from` annotation are not passed | + +Template parameters with the `x-ddp-from` annotation are filled in from the same context when the repository is created. +For details, see [Template pack](../templates/packs/#binding-parameters-to-the-launch-context). + +### Upgrading a microservice from a template + +The "Upgrade" button on the microservice card and automatic upgrades pass the same context to the process: + +| Path | Value | +| --- | --- | +| `.context.template.id` | Microservice template ID | +| `.context.template.version` | Target template version — the latest available one | +| `.context.upgrade.strategy` | Upgrade strategy: the value of the microservice's `microservice_binding_template_upgrade_strategy` role if set; otherwise, the strategy from the template pack | +| `.context.upgrade.overwrite` | Paths to overwrite: the microservice or pack value | +| `.context.upgrade.add_if_missing` | Paths to add: the microservice or pack value | +| `.context.review.title` | Merge request title: `Upgrade to ` | + +How the upgrade is performed is described in [Upgrading from a template](../templates/updates/). + +## Displaying the result + +The Home page tracks running processes and displays their state while the process is running. +Process completion notifications are not displayed; the user sees the outcome in the "My activities" panel. + +While a process is running: + +- The top of the Home page displays the line "Processes running: {count}"; for processes awaiting approval — "Awaiting approval: {count}"; for processes of other users — "Launched by: {initiators}". +- The row or card of the object the process is running on is marked with an indicator and the "running" caption, and its action buttons are unavailable. +- For an object being created, a temporary row or card with the "creating" caption is displayed. + +The Home page checks the state of runs at intervals of 2–15 seconds. +Tracking stops when the process completes, when the process timeout expires, or, if no timeout is set, after 30 minutes. +Paused processes and processes awaiting approval are tracked without a time limit. +The state of runs is loaded from the server, so indicators persist after a page reload and are visible to other users. + +After the process completes, the "Systems", "Microservices", "System deployment", "Resource ordering", and "Environments" sections reload their data, and the temporary row is replaced with the created object. + +### Process conventions + +The temporary row is replaced with the created object only if the object has appeared in the catalog and matches the expected one. +For the result to be displayed immediately after the process completes, meet the following conditions: + +- Add a datasource synchronization or entity creation task at the end of the process. + Otherwise, the object appears on the Home page only after the next datasource synchronization. +- In an environment creation process, name the environment ID parameter `slug`. + The Home page uses the value of this parameter to build the temporary row and find the created environment. +- In a microservice deployment process, create a deployment with the same name as the microservice. +- In a resource ordering process, suggest a resource name in the `-` format. + If the user changes the name, the temporary row disappears when the process completes. + +## Dataset processes + +The "Canonical architecture" dataset and related datasets create ready-made processes for Home page slots. +You can use them as a model for your own processes. + +| Process | Dataset | Slot | Context and parameters | +| --- | --- | --- | --- | +| "Create microservice from template" | "Microservice template registry" | `create_microservice` template action | Tasks "Create GitLab project", "Create repository from template", "Register microservice entity". The "GitLab group" parameter — `{{ with .context.repository.namespace }}{{ .id }}{{ end }}` | +| "Upgrade microservice from template" | "Microservice template registry" | `upgrade_service_from_template` template action | Tasks "Update repository from template" and "Create code review" | +| "Deploy microservice to an environment" | "Microservice template registry" | `deploy_microservice` template action | The `environment` parameter — `{{ .context.environment.slug }}`. Ingress host — `.` | +| "Delete microservice from an environment" | "Microservice template registry" | `delete_microservice` template action | — | +| "Create environment" | "Environment management" | `create_environment` | Parameters "Identifier" (`slug`) and "TTL" | +| "Delete environment" | "Environment management" | `delete_environment` | The "Environment ID" parameter — `{{ .entity.slug }}` | +| "Connect secrets to application", "Disconnect shared resource" | "Shared resource binding" | `connect_shared_resource`, `disconnect_shared_resource` | — | +| Processes for ordering and deleting managed services | "Deckhouse managed PostgreSQL", "Deckhouse managed Valkey", "Deckhouse managed Kafka" | `order_resource`, `delete_shared_resource` | — | + +The "Create environment" process creates a Kubernetes namespace with Deckhouse Development Portal (DDP) labels. +The "TTL" parameter accepts the values "1 day", "3 days", "7 days", "14 days", and "1 month" and is written to the `ddp.deckhouse.io/deletion-ttl` label; an empty value creates a permanent environment. +DDP does not delete environments by TTL on its own, since the label is intended for an external cluster cleanup mechanism. + +The "Delete environment" process deletes the namespace with all deployments, waits up to 5 minutes for it to be deleted, and updates the catalog. + +For an example of adding your own process, see [Custom resource ordering process](../examples/home-custom-process/). diff --git a/content/documentation/admin/home/processes.ru.md b/content/documentation/admin/home/processes.ru.md index 7ad8fc28..de45a3ee 100644 --- a/content/documentation/admin/home/processes.ru.md +++ b/content/documentation/admin/home/processes.ru.md @@ -1,25 +1,30 @@ --- -title: Процессы главной +title: Процессы главной страницы weight: 40 -description: Требования к процессам, которые запускаются с главной DDP, — сущность запуска, контекст запуска и его ключи для каждого сценария, отображение результата и соглашения об именах. +description: Требования к процессам, которые запускаются с главной страницы DDP, — сущность запуска, контекст запуска и его ключи для каждого сценария, отображение результата и соглашения об именах. --- -С главной запускаются обычные процессы каталога. Главная передаёт процессу сущность, для которой он выполняется, и контекст запуска — данные о выбранных на экране объектах. +С главной страницы запускаются обычные процессы каталога. +Главная страница передаёт процессу сущность, для которой он выполняется, и контекст запуска — данные о выбранных на экране объектах. Процесс читает контекст в шаблонах параметров, действий и правил обновления сущностей. -Процессы для главной создаются так же, как любые другие процессы: [в редакторе процессов](../processes/overview/). Затем процесс добавляется в слот действия или действие по шаблону в [правилах маппинга](mapping/#слоты-действий). +Процессы для главной страницы создаются так же, как любые другие процессы: [в редакторе процессов](../processes/overview/). +Затем процесс добавляется в слот действия или действие по шаблону в [правилах маппинга](mapping/#слоты-действий). -## Запуск процесса с главной +## Запуск процесса с главной страницы -Все сценарии главной завершаются окном «Запустить процесс». В заголовке окна отображается название сущности, для которой запускается процесс. +Все сценарии главной страницы завершаются окном «Запустить процесс». +В заголовке окна отображается название сущности, для которой запускается процесс. Окно запуска работает так же, как при запуске процесса из каталога: - если в слоте несколько процессов, пользователь выбирает процесс в списке; если процесс один, он выбран автоматически; -- по умолчанию отображаются только параметры процесса с признаком показа в упрощённой форме и незаполненные обязательные параметры. Переключатель «Все параметры процесса» открывает все параметры и конфигурацию задач; -- значения по умолчанию параметров отображаются как есть, в том числе шаблоны вида `{{ .context.environment.slug }}`. Шаблоны вычисляются при запуске процесса. +- по умолчанию отображаются только параметры процесса с признаком показа в упрощённой форме и незаполненные обязательные параметры. + Переключатель «Все параметры процесса» открывает все параметры и конфигурацию задач; +- значения по умолчанию параметров отображаются как есть, в том числе шаблоны вида `{{ .context.environment.slug }}`. + Шаблоны вычисляются при запуске процесса. -После нажатия «Запустить» отображается уведомление «Процесс "{name}" запущен». +После нажатия «Запустить» отображается уведомление «Процесс „{name}“ запущен». Если обязательный параметр после вычисления шаблона остался пустым, например ключа нет в контексте, процесс не запускается и отображается ошибка «Не удалось запустить процесс». Если у пользователя нет разрешения `control:processes`, отображается ошибка «Запрещено политиками доступа». @@ -31,14 +36,23 @@ description: Требования к процессам, которые запу Сущности в контексте передаются в едином формате: ```yaml -name: <название сущности> -slug: <идентификатор сущности> -uuid: +name: +slug: +uuid: properties: - <идентификатор параметра>: <значение> + : ``` -Ключи `properties` — идентификаторы параметров сущности в каталоге, а не роли маппинга. Например, домен окружения в каноничной модели читается как `.context.environment.properties.domain`. +где: + +- `` — название сущности; +- `` — идентификатор сущности; +- `` — UUID сущности; +- `` — идентификатор параметра; +- `` — значение параметра. + +Ключи `properties` — идентификаторы параметров сущности в каталоге, а не роли маппинга. +Например, домен окружения в каноничной модели читается как `.context.environment.properties.domain`. Примеры обращения к контексту: @@ -48,11 +62,13 @@ properties: {{ with .context.environment.properties.domain }}{{ $.context.microservice.slug }}.{{ . }}{{ end }} ``` -В значениях параметров процесса отсутствующий ключ контекста вычисляется в пустую строку, а в телах действий и условиях завершает шаг ошибкой. Поэтому читайте контекст в значениях по умолчанию параметров процесса, а в действиях используйте параметры процесса. Подробнее — в разделе [«Шаблонизация»](../../user/templating/#контекст-запуска-процесса). +В значениях параметров процесса отсутствующий ключ контекста вычисляется в пустую строку, а в телах действий и условиях завершает шаг ошибкой. +Поэтому читайте контекст в значениях по умолчанию параметров процесса, а в действиях используйте параметры процесса. +Подробнее — в разделе [«Шаблонизация»](../../user/templating/#контекст-запуска-процесса). ## Сущность и контекст по сценариям -В таблице перечислены сценарии главной, сущность запуска (`.entity`) и ключи контекста: +В таблице перечислены сценарии главной страницы, сущность запуска (`.entity`) и ключи контекста: | Сценарий | Слот | Сущность запуска | Ключи `.context` | | --- | --- | --- | --- | @@ -66,9 +82,12 @@ properties: | Создание окружения | `create_environment` | Первое по названию окружение, если окружений нет — первая по названию система | Не передаётся | | Удаление окружения | `delete_environment` | Окружение | Не передаётся | -Процесс должен быть привязан к ресурсу сущности запуска из таблицы. Например, заказ общего ресурса требует привязки к ресурсу систем, удаление — к ресурсу общих ресурсов, а создание окружения — к ресурсам окружений и систем. Для существующих настроек проверьте эти привязки перед запуском; несовпадение ресурса приводит к отказу в запуске. +Процесс должен быть привязан к ресурсу сущности запуска из таблицы. +Например, заказ общего ресурса требует привязки к ресурсу систем, удаление — к ресурсу общих ресурсов, а создание окружения — к ресурсам окружений и систем. +Для существующих настроек проверьте эти привязки перед запуском; несовпадение ресурса приводит к отказу в запуске. -Ключ `system` передаётся, если на экране выбрана система. Ключ `microservice` при подключении и отключении общего ресурса передаётся, если у развёртывания найден микросервис. +Ключ `system` передаётся, если на экране выбрана система. +Ключ `microservice` при подключении и отключении общего ресурса передаётся, если у развёртывания найден микросервис. При создании окружения сущность запуска не связана с создаваемым окружением: `.entity` в таком процессе указывает на существующее окружение или систему. Данные нового окружения процесс получает из собственных параметров, которые заполняет пользователь. @@ -93,7 +112,8 @@ properties: | `.context.template.language` | Язык шаблона | | `.context.template.values` | Значения параметров шаблона с шага «Параметры». Параметры с аннотацией `x-ddp-from` не передаются | -Параметры шаблона с аннотацией `x-ddp-from` заполняются из этого же контекста при создании репозитория. Подробнее — в разделе [«Пакет шаблона»](../templates/packs/#связь-параметров-с-контекстом-запуска). +Параметры шаблона с аннотацией `x-ddp-from` заполняются из этого же контекста при создании репозитория. +Подробнее — в разделе [«Пакет шаблона»](../templates/packs/#связь-параметров-с-контекстом-запуска). ### Обновление микросервиса из шаблона @@ -106,51 +126,60 @@ properties: | `.context.upgrade.strategy` | Стратегия обновления: значение роли `microservice_binding_template_upgrade_strategy` микросервиса, если оно задано, иначе стратегия из пакета шаблона | | `.context.upgrade.overwrite` | Перезаписываемые пути: значение микросервиса или пакета | | `.context.upgrade.add_if_missing` | Добавляемые пути: значение микросервиса или пакета | -| `.context.review.title` | Заголовок запроса на слияние: `Upgrade to ` | +| `.context.review.title` | Заголовок запроса на слияние (Merge Request): `Upgrade to ` | Как выполняется обновление, описано в разделе [«Обновление из шаблона»](../templates/updates/). ## Отображение результата -Главная отслеживает запущенные процессы и показывает их состояние, пока процесс выполняется. Уведомления о завершении процесса не отображаются; итог выполнения пользователь видит в панели «Мои активности». +Главная страница отслеживает запущенные процессы и показывает их состояние, пока процесс выполняется. +Уведомления о завершении процесса не отображаются; итог выполнения пользователь видит в панели «Мои активности». Во время выполнения процесса: -- в верхней части главной отображается строка «Выполняются процессы: {count}», для процессов на согласовании — «Ожидают согласования: {count}», для процессов других пользователей — «Запустили: {initiators}»; +- в верхней части главной страницы отображается строка «Выполняются процессы: {count}», для процессов на согласовании — «Ожидают согласования: {count}», для процессов других пользователей — «Запустили: {initiators}»; - строка или карточка объекта, над которым выполняется процесс, отмечается индикатором и подписью «выполняется», а её кнопки действий недоступны; - для создаваемого объекта отображается временная строка или карточка с подписью «создаётся». -Главная проверяет состояние запусков с интервалом от 2 до 15 секунд. Отслеживание прекращается по завершении процесса, по истечении тайм-аута процесса или, если тайм-аут не задан, через 30 минут. Приостановленные процессы и процессы, ожидающие согласования, отслеживаются без ограничения по времени. +Главная страница проверяет состояние запусков с интервалом от 2 до 15 секунд. +Отслеживание прекращается по завершении процесса, по истечении тайм-аута процесса или, если тайм-аут не задан, через 30 минут. +Приостановленные процессы и процессы, ожидающие согласования, отслеживаются без ограничения по времени. Состояние запусков загружается с сервера, поэтому индикаторы сохраняются после перезагрузки страницы и видны другим пользователям. После завершения процесса разделы «Системы», «Микросервисы», «Развертывание систем», «Заказ ресурсов» и «Окружения» загружают данные заново, и временная строка заменяется созданным объектом. ### Соглашения для процессов -Временная строка заменяется созданным объектом, только если объект появился в каталоге и совпал с ожидаемым. Чтобы результат отображался сразу после завершения процесса, выполните следующие условия: +Временная строка заменяется созданным объектом, только если объект появился в каталоге и совпал с ожидаемым. +Чтобы результат отображался сразу после завершения процесса, выполните следующие условия: -- добавьте в конец процесса задачу синхронизации источника данных или создания сущности. Иначе объект появится на главной только после следующей синхронизации источника данных; -- в процессе создания окружения назовите параметр с идентификатором окружения `slug`. По значению этого параметра главная строит временную строку и находит созданное окружение; +- добавьте в конец процесса задачу синхронизации источника данных или создания сущности. + Иначе объект появится на главной странице только после следующей синхронизации источника данных; +- в процессе создания окружения назовите параметр с идентификатором окружения `slug`. + По значению этого параметра главная страница строит временную строку и находит созданное окружение; - в процессе развёртывания микросервиса создавайте развёртывание с названием, совпадающим с названием микросервиса; -- в процессе заказа ресурса предлагайте название ресурса вида `<идентификатор системы>-<идентификатор окружения>`. Если пользователь изменит название, временная строка исчезнет по завершении процесса. +- в процессе заказа ресурса предлагайте название ресурса вида `-`. + Если пользователь изменит название, временная строка исчезнет по завершении процесса. ## Процессы наборов данных -Набор данных «Каноничная архитектура» и связанные с ним наборы создают готовые процессы для слотов главной. Их можно использовать как образец собственных процессов. +Набор данных «Каноничная архитектура» и связанные с ним наборы создают готовые процессы для слотов главной страницы. +Их можно использовать как образец собственных процессов. | Процесс | Набор данных | Слот | Контекст и параметры | | --- | --- | --- | --- | | «Создать микросервис из шаблона» | «Реестр шаблонов микросервисов» | Действие по шаблону `create_microservice` | Задачи «Создание проекта GitLab», «Создание репозитория из шаблона», «Регистрация entity microservice». Параметр «Группа GitLab» — `{{ with .context.repository.namespace }}{{ .id }}{{ end }}` | | «Обновить микросервис из шаблона» | «Реестр шаблонов микросервисов» | Действие по шаблону `upgrade_service_from_template` | Задачи «Обновление репозитория из шаблона» и «Создание код-ревью» | -| «Развернуть микросервис на окружение» | «Реестр шаблонов микросервисов» | Действие по шаблону `deploy_microservice` | Параметр `environment` — `{{ .context.environment.slug }}`. Хост Ingress — `<идентификатор микросервиса>.<домен окружения>` | +| «Развернуть микросервис на окружение» | «Реестр шаблонов микросервисов» | Действие по шаблону `deploy_microservice` | Параметр `environment` — `{{ .context.environment.slug }}`. Хост Ingress — `.` | | «Удалить микросервис с окружения» | «Реестр шаблонов микросервисов» | Действие по шаблону `delete_microservice` | — | | «Создать окружение» | «Управление окружениями» | `create_environment` | Параметры «Идентификатор» (`slug`) и «TTL» | | «Удалить окружение» | «Управление окружениями» | `delete_environment` | Параметр «Идентификатор окружения» — `{{ .entity.slug }}` | | «Подключить секреты к приложению», «Отключить общий ресурс» | «Привязка общих ресурсов» | `connect_shared_resource`, `disconnect_shared_resource` | — | | Процессы заказа и удаления managed-сервисов | «Deckhouse managed PostgreSQL», «Deckhouse managed Valkey», «Deckhouse managed Kafka» | `order_resource`, `delete_shared_resource` | — | -Процесс «Создать окружение» создаёт неймспейс Kubernetes с лейблами DDP. Параметр «TTL» принимает значения «1 день», «3 дня», «7 дней», «14 дней», «1 месяц» и записывается в лейбл `ddp.deckhouse.io/deletion-ttl`; пустое значение создаёт постоянное окружение. -DDP не удаляет окружения по TTL самостоятельно: лейбл предназначен для внешнего механизма очистки кластера. +Процесс «Создать окружение» создаёт неймспейс Kubernetes с лейблами Deckhouse Development Portal (DDP). +Параметр «TTL» принимает значения «1 день», «3 дня», «7 дней», «14 дней», «1 месяц» и записывается в лейбл `ddp.deckhouse.io/deletion-ttl`; пустое значение создаёт постоянное окружение. +DDP не удаляет окружения по TTL самостоятельно, поскольку лейбл предназначен для внешнего механизма очистки кластера. Процесс «Удалить окружение» удаляет неймспейс со всеми развёртываниями, ожидает его удаления до 5 минут и обновляет каталог. diff --git a/content/documentation/admin/home/setup.md b/content/documentation/admin/home/setup.md new file mode 100644 index 00000000..3da1bfc0 --- /dev/null +++ b/content/documentation/admin/home/setup.md @@ -0,0 +1,144 @@ +--- +title: Initial setup +weight: 20 +description: The DDP Home page initial setup wizard — presets, "Canonical architecture" datasets, their parameters, and the steps performed manually after the wizard. +--- + +The initial setup wizard applies prepared datasets that create the catalog model for the Home page, mapping rules, connections to Kubernetes, Vault, and GitLab, datasources, processes, and widgets. +After the wizard completes, the Home page displays data from clusters and repositories and lets you run processes. + +## Before you begin + +The wizard requires the `apply:seeds` permission. + +Prepare the addresses of the external systems to be connected to the portal: + +- Kubernetes API server URL, for example, `https://api.cluster.example.com` +- Vault or Deckhouse Stronghold URL, for example, `https://vault.example.com` +- GitLab URL, for example, `https://gitlab.example.com` + +Datasets do not check whether they have been applied before. +Reapplying a dataset whose objects already exist in the portal fails with an error. +Run the wizard on a portal where the "Canonical architecture" datasets have not been applied yet. + +## Running the wizard + +The wizard is launched with the "Run" button in the "The platform is ready for setup" banner on the Home page +or with the "Initial setup" button in "Administration" → "Directories" → "Datasets". + +Only users with the `apply:seeds` permission see the banner. +The banner is hidden for all users with the "Hide" button or automatically after all selected datasets are applied successfully. +To show the banner again, enable the "Show the initial setup banner" toggle in the "Datasets" section. + +The Home page is disabled after the portal is installed, so on a new installation the banner is not displayed until the "Show Home" toggle is enabled. + +## Wizard steps + +The wizard consists of five steps: "Preset", "Select", "Parameters", "Review", and "Progress". + +### Preset + +At the "Preset" step, select one of the options. +The "Platform setup" preset creates the catalog schema, connections to Kubernetes, Vault, and GitLab, and the Home page processes and widgets. +The "Platform setup with demo data" preset also adds demo data: sample services, resources, and process runs. + +You can delete the demo data later in the "Datasets" section. + +### Selection + +The "Select" step displays the preset's datasets grouped by layer: "Schema", "Demo data", "Infrastructure", "Providers / operations", and "Home wiring". +Clear the checkboxes for the datasets you do not need. + +The wizard does not let you clear a dataset that other selected datasets depend on. +Such a dataset is marked with the "Required" tag and the "Required for: …" caption. +The "Canonical architecture (schema)" and "Canonical architecture (Home bindings)" datasets are locked while datasets with Home page processes or widgets are selected. + +### Parameters + +At the "Parameters" step, a panel with parameters is displayed for each selected dataset. +Panels with unfilled required parameters are marked with an asterisk. + +The wizard fills in some parameters automatically. +External services and datasources created by datasets in the same run are substituted into the parameters of dependent datasets. +Fill in the external system URLs manually. +Dataset parameters are listed in [Wizard datasets](#wizard-datasets). + +### Review + +The "Review" step displays a table of datasets in the order they are applied, with the number of objects in each dataset. +Enable the "Confirm Application" toggle and click "Apply". + +### Progress + +At the "Progress" step, datasets are applied one by one. +Each dataset displays a status: "Pending", "Running", "Success", or "Error". + +If a dataset fails to apply, the queue stops, and the objects of already applied datasets remain in the portal. +Fix the cause of the error and click "Retry from current" to continue from the dataset where the error occurred. +The "Back to review" button returns you to the "Review" step. + +The wizard window cannot be closed while the queue is running. +After all datasets are applied successfully, the message "All selected datasets were applied successfully" is displayed. + +## Wizard datasets + +Datasets are applied in dependency order. The table lists the datasets included in the wizard presets: + +| Dataset | What it creates | Parameters | +| --- | --- | --- | +| "Canonical architecture (schema)" | The "Architecture", "Systems", "Microservices", "Shared resources", "Kubernetes", "Ingresses", "Deployments", "Namespaces", "Secret bindings", "GitLab", "Groups", "Clusters", "Help", and "Integrations" catalog resources, the relations between them, and the "Home (default)" mapping set with the `home-default` ID | — | +| "Canonical architecture (demo data)" | Demo entities of the Billing system: systems, microservices, environments, shared resources, deployments, clusters, guides, and integrations. Included only in the "Platform setup with demo data" preset | — | +| "Kubernetes" | The "Kubernetes" external service and the "Kubernetes token" credential type | "Kubernetes API URL": Required | +| "Vault" | The "Vault" external service and the "Vault token" credential type | "Vault URL": Required | +| "GitLab" | The "GitLab" external service and the "GitLab token" and "GitLab username" credential types | "GitLab URL": Required | +| "Microservice template registry" | The "Create microservice from template", "Upgrade microservice from template", "Deploy microservice to an environment", and "Delete microservice from an environment" actions and processes | "VCS provider", "External service", "Deployments datasource", "Ingresses datasource" | +| "Kubernetes: deployments, ingresses, and namespaces" | Datasources that collect Deployments, Ingresses, and namespaces from the cluster | "Kubernetes external service" | +| "Shared resource binding" | The "Secret bindings" datasource and the "Connect secrets to application" and "Disconnect shared resource" processes | "Kubernetes external service", "Deployments datasource" | +| "Environment management" | The "Create environment" and "Delete environment" processes | "Kubernetes external service", "Namespaces datasource" | +| "GitLab: groups" | A GitLab groups datasource for selecting a namespace when creating a microservice | "GitLab external service" | +| "GitLab: repository activity" | A datasource that fills in the number of open merge requests, the last pipeline, and the last commit on the microservice card | "GitLab external service", "All repositories", "GitLab group IDs", "Include subgroups" | +| "GitLab: widgets" | The "GitLab: repository pipelines" and "GitLab: repository merge requests" widgets for the microservice card tabs | "GitLab external service" | +| "Deckhouse managed PostgreSQL", "Deckhouse managed Valkey", "Deckhouse managed Kafka" | Actions, processes for ordering and deleting the managed service, and a datasource | "Kubernetes external service", "Vault or Stronghold external service", "Vault path prefix", and object creation parameters | +| "Canonical architecture (Home bindings)" | Adds the processes and widgets of the selected datasets to the slots of the `home-default` mapping set. Applied only by the wizard | — | + +If the "All repositories" parameter is disabled in the "GitLab: repository activity" dataset, fill in "GitLab group IDs". + +Kubernetes datasources collect only objects with the `ddp.deckhouse.io/environment` label and skip the `d8-*` and `kube-*` namespaces. + +The table shows which slots the "Canonical architecture (Home bindings)" dataset fills in: + +| Dataset | Action slot | Category | +| --- | --- | --- | +| "Environment management" | `create_environment`, `delete_environment` | `default` | +| "Shared resource binding" | `connect_shared_resource`, `disconnect_shared_resource` | `default` | +| "Deckhouse managed PostgreSQL" | `order_resource`, `delete_shared_resource` | `PostgreSQL`, `Deckhouse PostgreSQL` | +| "Deckhouse managed Valkey" | `order_resource`, `delete_shared_resource` | `Valkey`, `Deckhouse Valkey` | +| "Deckhouse managed Kafka" | `order_resource`, `delete_shared_resource` | `Kafka`, `Deckhouse Kafka` | +| "GitLab: widgets" | Widget slots `microservice_repository_widget`, `microservice_merge_requests_widget` | — | + +The "Microservice template registry" dataset does not add processes to the mapping rules. +They are bound to templates manually after the template registry is connected. + +## Post-wizard steps + +The wizard does not perform some settings that depend on the specific installation. Perform them manually: + +1. Enable the Home page: "Administration" → "Directories" → "Mapping rules" → the "Show Home" toggle. +1. Fill in the credentials in the user profile: the Kubernetes service account token, the Vault token, and the GitLab personal access token and username. + Home page processes perform actions with the credentials of the user who runs them, so every user who runs processes needs credentials. +1. Connect the template registry and synchronize it. + The procedure is described in [Template registry](../templates/registry/). +1. Bind processes to templates: "Mapping rules" → the default set → "Catalog mapping" → "Microservices" → "Template actions". + For each template, select the action processes: the "Create microservice from template" process for the "Create microservice" action, and the processes with the same names for the "Deploy microservice to an environment", "Delete microservice from an environment", and "Upgrade microservice from template" actions. +1. If the catalog contains microservices created without a template, fill in the "Deploy microservice to an environment (no template)" and "Delete microservice from an environment (no template)" slots in "Microservices" → "Actions". +1. In the catalog, fill in the environment properties that do not come from the cluster: type, cluster, domain, and the "marked for deletion" flag. + The environment domain can also be changed from the "Environments" section on the Home page. + +## Deleting a dataset + +To delete a dataset, click "Delete" on its card in the "Datasets" section. + +When you delete a dataset with Home page processes, only the processes and widgets of that dataset are removed from the mapping set slots. +The default mapping set is not deleted when a dataset is deleted. + +For general rules for working with datasets, see [Datasets](../datasets/). diff --git a/content/documentation/admin/home/setup.ru.md b/content/documentation/admin/home/setup.ru.md index 2bfd90cf..f139cb6b 100644 --- a/content/documentation/admin/home/setup.ru.md +++ b/content/documentation/admin/home/setup.ru.md @@ -1,11 +1,11 @@ --- title: Первоначальная настройка weight: 20 -description: Мастер первоначальной настройки главной DDP — пресеты, наборы данных «Каноничной архитектуры», их параметры и шаги, которые выполняются вручную после мастера. +description: Мастер первоначальной настройки главной страницы DDP — пресеты, наборы данных «Каноничной архитектуры», их параметры и шаги, которые выполняются вручную после мастера. --- -Мастер первоначальной настройки применяет подготовленные наборы данных, которые создают модель каталога для главной, правила маппинга, подключения к Kubernetes, Vault и GitLab, источники данных, процессы и виджеты. -После мастера главная показывает данные кластеров и репозиториев и позволяет запускать процессы. +Мастер первоначальной настройки применяет подготовленные наборы данных, которые создают модель каталога для главной страницы, правила маппинга, подключения к Kubernetes, Vault и GitLab, источники данных, процессы и виджеты. +После мастера главная страница показывает данные кластеров и репозиториев и позволяет запускать процессы. ## Перед началом работы @@ -17,20 +17,20 @@ description: Мастер первоначальной настройки гла - URL Vault или Deckhouse Stronghold, например `https://vault.example.com`; - URL GitLab, например `https://gitlab.example.com`. -Наборы данных не проверяют, применялись ли они раньше. Повторное применение набора, объекты которого уже есть в портале, завершается ошибкой. +Наборы данных не проверяют, применялись ли они раньше. +Повторное применение набора, объекты которого уже есть в портале, завершается ошибкой. Запускайте мастер на портале, где наборы «Каноничной архитектуры» ещё не применялись. ## Запуск мастера -Мастер запускается одним из способов: +Мастер запускается кнопкой «Запустить» в баннере «Платформа готова к настройке» на главной странице +или кнопкой «Первоначальная настройка» в разделе «Администрирование» → «Справочники» → «Наборы данных». -- кнопкой «Запустить» в баннере «Платформа готова к настройке» на главной; -- кнопкой «Первоначальная настройка» в разделе «Администрирование» → «Справочники» → «Наборы данных». - -Баннер видят только пользователи с разрешением `apply:seeds`. Баннер скрывается для всех пользователей кнопкой «Скрыть» или автоматически после успешного применения всех выбранных наборов. +Баннер видят только пользователи с разрешением `apply:seeds`. +Баннер скрывается для всех пользователей кнопкой «Скрыть» или автоматически после успешного применения всех выбранных наборов. Чтобы вернуть баннер, включите переключатель «Показывать баннер первоначальной настройки» в разделе «Наборы данных». -Главная выключена после установки портала, поэтому на новой установке баннер не отображается, пока не включён переключатель «Показывать главную». +Главная страница выключена после установки портала, поэтому на новой установке баннер не отображается, пока не включён переключатель «Показывать главную». ## Шаги мастера @@ -38,10 +38,9 @@ description: Мастер первоначальной настройки гла ### Пресет -На шаге «Пресет» выберите один из вариантов: - -- «Настройка платформы» — схема каталога, подключения к Kubernetes, Vault и GitLab, процессы и виджеты главной страницы; -- «Настройка платформы с демоданными» — то же самое плюс демоданные: примеры сервисов, ресурсов и запущенных процессов. +На шаге «Пресет» выберите один из вариантов. +Пресет «Настройка платформы» создаёт схему каталога, подключения к Kubernetes, Vault и GitLab, процессы и виджеты главной страницы. +Пресет «Настройка платформы с демоданными» дополнительно добавляет демоданные: примеры сервисов, ресурсов и запущенных процессов. Демоданные можно удалить позже в разделе «Наборы данных». @@ -50,15 +49,19 @@ description: Мастер первоначальной настройки гла На шаге «Выбор» отображаются наборы данных пресета, сгруппированные по слоям: «Схема», «Демоданные», «Инфраструктура», «Провайдеры и операции», «Привязка процессов». Снимите отметку с наборов, которые не нужны. -Мастер не даёт снять отметку с набора, от которого зависят другие выбранные наборы. Такой набор отмечен тегом «Обязательный» и подписью «Нужен для: …». -Наборы «Каноничная архитектура (схема)» и «Каноничная архитектура (привязки главной)» заблокированы, пока выбраны наборы с процессами или виджетами для главной. +Мастер не даёт снять отметку с набора, от которого зависят другие выбранные наборы. +Такой набор отмечен тегом «Обязательный» и подписью «Нужен для: …». +Наборы «Каноничная архитектура (схема)» и «Каноничная архитектура (привязки главной)» заблокированы, пока выбраны наборы с процессами или виджетами для главной страницы. ### Параметры -На шаге «Параметры» для каждого выбранного набора отображается панель с его параметрами. Панели с незаполненными обязательными параметрами отмечены звёздочкой. +На шаге «Параметры» для каждого выбранного набора отображается панель с его параметрами. +Панели с незаполненными обязательными параметрами отмечены звёздочкой. -Мастер заполняет часть параметров автоматически: внешние сервисы и источники данных, которые создаются наборами этого же запуска, подставляются в параметры зависимых наборов. -Заполните вручную URL внешних систем. Параметры наборов перечислены в разделе [«Наборы данных мастера»](#наборы-данных-мастера). +Мастер заполняет часть параметров автоматически. +Внешние сервисы и источники данных, которые создаются наборами этого же запуска, подставляются в параметры зависимых наборов. +Заполните вручную URL внешних систем. +Параметры наборов перечислены в разделе [«Наборы данных мастера»](#наборы-данных-мастера). ### Проверка @@ -67,12 +70,15 @@ description: Мастер первоначальной настройки гла ### Прогресс -На шаге «Прогресс» наборы применяются по очереди. Для каждого набора отображается статус: «Ожидает», «Выполняется», «Успех» или «Ошибка». +На шаге «Прогресс» наборы применяются по очереди. +Для каждого набора отображается статус: «Ожидает», «Выполняется», «Успех» или «Ошибка». Если применение набора завершилось ошибкой, очередь останавливается, а объекты уже применённых наборов остаются в портале. -Исправьте причину ошибки и нажмите «Повторить с текущего», чтобы продолжить с набора, на котором произошла ошибка. Кнопка «К проверке» возвращает к шагу «Проверка». +Исправьте причину ошибки и нажмите «Повторить с текущего», чтобы продолжить с набора, на котором произошла ошибка. +Кнопка «К проверке» возвращает к шагу «Проверка». -Пока очередь выполняется, окно мастера закрыть нельзя. После успешного применения всех наборов отображается сообщение «Все выбранные наборы успешно применены». +Пока очередь выполняется, окно мастера закрыть нельзя. +После успешного применения всех наборов отображается сообщение «Все выбранные наборы успешно применены». ## Наборы данных мастера @@ -90,7 +96,7 @@ description: Мастер первоначальной настройки гла | «Привязка общих ресурсов» | Источник данных «Привязки секретов», процессы «Подключить секреты к приложению» и «Отключить общий ресурс» | «Внешний сервис Kubernetes», «Источник данных Deployments» | | «Управление окружениями» | Процессы «Создать окружение» и «Удалить окружение» | «Внешний сервис Kubernetes», «Источник данных Namespaces» | | «GitLab: группы» | Источник данных групп GitLab для выбора пространства при создании микросервиса | «Внешний сервис GitLab» | -| «GitLab: активность репозиториев» | Источник данных, который заполняет в карточке микросервиса число открытых запросов на слияние, последний пайплайн и последний коммит | «Внешний сервис GitLab», «Все репозитории», «ID групп GitLab», «Включать подгруппы» | +| «GitLab: активность репозиториев» | Источник данных, который заполняет в карточке микросервиса число открытых запросов на слияние (Merge Request), последний пайплайн и последний коммит | «Внешний сервис GitLab», «Все репозитории», «ID групп GitLab», «Включать подгруппы» | | «GitLab: виджеты» | Виджеты «GitLab: пайплайны репозитория» и «GitLab: merge requests репозитория» для вкладок карточки микросервиса | «Внешний сервис GitLab» | | «Deckhouse managed PostgreSQL», «Deckhouse managed Valkey», «Deckhouse managed Kafka» | Действия, процессы заказа и удаления managed-сервиса, источник данных | «Внешний сервис Kubernetes», «Внешний сервис Vault или Stronghold», «Префикс пути Vault» и параметры создания объектов | | «Каноничная архитектура (привязки главной)» | Добавляет процессы и виджеты выбранных наборов в слоты набора маппинга `home-default`. Применяется только мастером | — | @@ -110,26 +116,29 @@ description: Мастер первоначальной настройки гла | «Deckhouse managed Kafka» | `order_resource`, `delete_shared_resource` | `Kafka`, `Deckhouse Kafka` | | «GitLab: виджеты» | Слоты виджетов `microservice_repository_widget`, `microservice_merge_requests_widget` | — | -Набор «Реестр шаблонов микросервисов» процессы в правила маппинга не добавляет: их привязывают к шаблонам вручную после подключения реестра шаблонов. +Набор «Реестр шаблонов микросервисов» процессы в правила маппинга не добавляет. +Их привязывают к шаблонам вручную после подключения реестра шаблонов. ## Действия после мастера Мастер не выполняет часть настроек, которые зависят от конкретной установки. Выполните их вручную: -1. Включите главную: «Администрирование» → «Справочники» → «Правила маппинга» → переключатель «Показывать главную». +1. Включите главную страницу: «Администрирование» → «Справочники» → «Правила маппинга» → переключатель «Показывать главную». 1. Заполните учётные данные в профиле пользователя: токен сервисного аккаунта Kubernetes, токен Vault, персональный токен и имя пользователя GitLab. - Процессы главной выполняют действия с учётными данными пользователя, который их запускает, поэтому учётные данные нужны каждому пользователю, запускающему процессы. -1. Подключите реестр шаблонов и выполните синхронизацию. Порядок описан в разделе [«Реестр шаблонов»](../templates/registry/). + Процессы главной страницы выполняют действия с учётными данными пользователя, который их запускает, поэтому учётные данные нужны каждому пользователю, запускающему процессы. +1. Подключите реестр шаблонов и выполните синхронизацию. + Порядок описан в разделе [«Реестр шаблонов»](../templates/registry/). 1. Привяжите процессы к шаблонам: «Правила маппинга» → набор по умолчанию → «Маппинг каталога» → «Микросервисы» → «Действия по шаблонам». Для каждого шаблона выберите процессы действий: для действия «Создать микросервис» — процесс «Создать микросервис из шаблона», для действий «Развернуть микросервис на окружение», «Удалить микросервис с окружения» и «Обновить микросервис из шаблона» — одноимённые процессы. 1. Если в каталоге есть микросервисы, созданные без шаблона, заполните в разделе «Микросервисы» → «Действия» слоты «Развернуть микросервис на окружение (без шаблона)» и «Удалить микросервис с окружения (без шаблона)». -1. Заполните в каталоге параметры окружений, которые не приходят из кластера: тип, кластер, домен и признак «помечено на удаление». Домен окружения также меняется из раздела «Окружения» на главной. +1. Заполните в каталоге параметры окружений, которые не приходят из кластера: тип, кластер, домен и признак «помечено на удаление». + Домен окружения также меняется из раздела «Окружения» на главной странице. ## Удаление набора данных Набор данных удаляется кнопкой «Удалить» на его карточке в разделе «Наборы данных». -При удалении набора с процессами для главной из слотов набора маппинга удаляются только процессы и виджеты этого набора. +При удалении набора с процессами для главной страницы из слотов набора маппинга удаляются только процессы и виджеты этого набора. Набор маппинга по умолчанию при удалении набора данных не удаляется. Общие правила работы с наборами данных — в разделе [«Наборы данных»](../datasets/). diff --git a/content/documentation/admin/install.md b/content/documentation/admin/install.md index 82ff8a91..b1c1cda6 100644 --- a/content/documentation/admin/install.md +++ b/content/documentation/admin/install.md @@ -4,19 +4,24 @@ description: Install Deckhouse Development Portal with internal, external, or ma weight: 11 --- -Deckhouse Development Portal (DDP) is installed by the `development-platform` module in a Deckhouse Platform cluster. Before installing it, check the [resource requirements](resource-requirements/). +Deckhouse Development Portal (DDP) is installed by the `development-platform` module in a Deckhouse Platform cluster. +Before installing it, check the [resource requirements](resource-requirements/). -Managed instances are recommended for [demo installations](#installation-with-managed-instances); [external instances](#installation-with-external-instances) are recommended for production. [Internal instances](#installation-with-internal-instances) are available as a separate installation option. +Managed instances are recommended for [demo installations](#installation-with-managed-instances); [external instances](#installation-with-external-instances) are recommended for production. +[Internal instances](#installation-with-internal-instances) are available as a separate installation option. Set `managed`, `external` or `internal` separately for PostgreSQL, Redis and ClickHouse; modes can be combined. -The `postgres.mode`, `redis.mode` and `clickhouse.mode` parameters are required and have no default value. Without them, installation and upgrade fail settings validation. +The `postgres.mode`, `redis.mode` and `clickhouse.mode` parameters are required and have no default value. +Without them, installation and upgrade fail settings validation. -ClickHouse stores the historical data of the portal. To run without features that require ClickHouse, explicitly set `clickhouse.mode: external` and leave `clickhouse.host` empty, as described [below](#running-without-clickhouse). +ClickHouse stores the historical data of the portal. +To run without features that require ClickHouse, explicitly set `clickhouse.mode: external` and leave `clickhouse.host` empty, as described [below](#running-without-clickhouse). ## Installation with managed instances -In the `managed` mode, the module creates PostgreSQL, Valkey (Redis-compatible) and ClickHouse instances. Before installing DDP, the corresponding Deckhouse modules must be enabled in the cluster for each service with `mode: managed`: +In the `managed` mode, the module creates PostgreSQL, Valkey (Redis-compatible) and ClickHouse instances. +Before installing DDP, the corresponding Deckhouse modules must be enabled in the cluster for each service with `mode: managed`: | DDP setting | Module that must be enabled | |---|---| @@ -74,9 +79,12 @@ spec: mode: managed ``` -With `mode: managed`, the connection host and port are resolved automatically. The `host`, `port` and `image` parameters are not used in this mode. +With `mode: managed`, the connection host and port are resolved automatically. +The `host`, `port` and `image` parameters are not used in this mode. -Set instance resources in `instance.cpu`, `instance.memory` and `instance.persistentVolumeClaim`. Select the class with `instance.className`, `default` by default; it defines allowed sizes and placement of the instance. Specify memory and disk sizes as Kubernetes quantities, such as `512Mi` or `20Gi`. +Set instance resources in `instance.cpu`, `instance.memory` and `instance.persistentVolumeClaim`. +Select the class with `instance.className`, `default` by default; it defines allowed sizes and placement of the instance. +Specify memory and disk sizes as Kubernetes quantities, such as `512Mi` or `20Gi`. Example of PostgreSQL resource settings: @@ -99,7 +107,8 @@ The disk size can only be increased, and only if the StorageClass supports volum ## Installation with external instances -For production, connect existing PostgreSQL, Redis and ClickHouse instances with `mode: external`. The sections are independent: the other services can explicitly use `internal` or `managed`. +For production, connect existing PostgreSQL, Redis and ClickHouse instances with `mode: external`. +The sections are independent: the other services can explicitly use `internal` or `managed`. ### Connecting external PostgreSQL @@ -133,7 +142,8 @@ spec: #### pg_trgm extension -The portal requires the PostgreSQL `pg_trgm` extension. If you use an external PostgreSQL instance, enable it before starting DDP: connect to the database as a user with permission to create extensions and run: +The portal requires the PostgreSQL `pg_trgm` extension. +If you use an external PostgreSQL instance, enable it before starting DDP: connect to the database as a user with permission to create extensions and run: ```sql CREATE EXTENSION IF NOT EXISTS pg_trgm; @@ -211,7 +221,8 @@ spec: ## Installation with internal instances -With `mode: internal`, the module deploys PostgreSQL, Redis and ClickHouse in the cluster. Enable `development-platform` with [ModuleConfig](/products/kubernetes-platform/documentation/v1/reference/api/cr.html#moduleconfig), specifying the super administrator, the encryption key and the mode of each service: +With `mode: internal`, the module deploys PostgreSQL, Redis and ClickHouse in the cluster. +Enable `development-platform` with [ModuleConfig](/products/kubernetes-platform/documentation/v1/reference/api/cr.html#moduleconfig), specifying the super administrator, the encryption key and the mode of each service: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -234,13 +245,17 @@ spec: mode: internal ``` -The web interface address is built from the `publicDomainTemplate` cluster parameter and the `domain.prefix` module parameter, `ddp` by default. For example, with `publicDomainTemplate: "%s.example.com"`, the web interface is available at `https://ddp.example.com`. To use another domain, set `domain.useCustomDomain` and `domain.customDomain`. All parameters are listed in the [module settings](/modules/development-platform/configuration.html). +The web interface address is built from the `publicDomainTemplate` cluster parameter and the `domain.prefix` module parameter, `ddp` by default. +For example, with `publicDomainTemplate: "%s.example.com"`, the web interface is available at `https://ddp.example.com`. +To use another domain, set `domain.useCustomDomain` and `domain.customDomain`. +All parameters are listed in the [module settings](/modules/development-platform/configuration.html). This option deploys services through the module itself, without managed operators. ### Configuring internal instances (optional) -To pull internal PostgreSQL, Redis and ClickHouse images from a private registry, create a Secret of the `kubernetes.io/dockerconfigjson` type with the registry credentials in the `d8-development-platform` namespace. Set the images in the `image` parameters and the Secret name in `additionalImagePullSecrets`: +To pull internal PostgreSQL, Redis and ClickHouse images from a private registry, create a Secret of the `kubernetes.io/dockerconfigjson` type with the registry credentials in the `d8-development-platform` namespace. +Set the images in the `image` parameters and the Secret name in `additionalImagePullSecrets`: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -270,11 +285,15 @@ spec: ## ClickHouse -ClickHouse stores historical data, such as the history of entity property changes. Select `internal` for an instance deployed by the module, `managed` to create an instance with the `managed-clickhouse` module, or `external` to connect to an existing server. Use an external instance for production. +ClickHouse stores historical data, such as the history of entity property changes. +Select `internal` for an instance deployed by the module, `managed` to create an instance with the `managed-clickhouse` module, or `external` to connect to an existing server. +Use an external instance for production. ### Internal ClickHouse instance -To deploy ClickHouse as part of the module, explicitly set `clickhouse.mode: internal`. The following example pulls the image from a private registry; first create the `custom-registry-secret` Secret with the registry credentials in the `d8-development-platform` namespace. The `host` parameter is not used in this mode: +To deploy ClickHouse as part of the module, explicitly set `clickhouse.mode: internal`. +The following example pulls the image from a private registry; first create the `custom-registry-secret` Secret with the registry credentials in the `d8-development-platform` namespace. +The `host` parameter is not used in this mode: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -303,7 +322,9 @@ spec: - custom-registry-secret ``` -In this mode, the portal deploys one ClickHouse instance with `10Gi` of persistent storage. The database is created on the first start with an empty volume. After restoring data from a backup or changing the `database` parameter, create the database manually as described [below](#creating-the-clickhouse-database). +In this mode, the portal deploys one ClickHouse instance with `10Gi` of persistent storage. +The database is created on the first start with an empty volume. +After restoring data from a backup or changing the `database` parameter, create the database manually as described [below](#creating-the-clickhouse-database). ### External ClickHouse instance @@ -343,13 +364,16 @@ Create the database before connecting an external instance: the portal applies s With `mode: managed`, the module creates the database automatically. -When connecting an external instance, create the database before starting DDP. Replace `ddp` with the value of `clickhouse.database`: +When connecting an external instance, create the database before starting DDP. +Replace `ddp` with the value of `clickhouse.database`: ```sql CREATE DATABASE IF NOT EXISTS ddp; ``` -With `mode: internal`, the database is created on the first start with an empty volume. If the volume already contains data or you change the `database` parameter, create the database manually. Replace `ddp` with the database name: +With `mode: internal`, the database is created on the first start with an empty volume. +If the volume already contains data or you change the `database` parameter, create the database manually. +Replace `ddp` with the database name: ```shell d8 k -n d8-development-platform exec clickhouse-0 -c clickhouse -- \ @@ -370,18 +394,23 @@ In this case, the features that depend on ClickHouse are unavailable: for exampl ### Data delivery to ClickHouse -The portal workers deliver data from PostgreSQL to ClickHouse and clean it up afterwards, so at least one running worker is required to transfer data. Delivery parameters are set in the `clickhouse.replication` section, the property history retention period and the cleanup interval are set in the `clickhouse.propertyHistory` section. +The portal workers deliver data from PostgreSQL to ClickHouse and clean it up afterwards, so at least one running worker is required to transfer data. +Delivery parameters are set in the `clickhouse.replication` section, the property history retention period and the cleanup interval are set in the `clickhouse.propertyHistory` section. ## Changing the encryption key -DDP encrypts stored credentials with the key from the `security.secretKey` parameter. Replacing the key without re-encryption makes stored data unavailable. +DDP encrypts stored credentials with the key from the `security.secretKey` parameter. +Replacing the key without re-encryption makes stored data unavailable. To change the key: -1. In the DDP web interface, open "Administration" → "Credentials" and click "Rotate encryption key". The button is available to users with the `rotate:encryption-key` permission. +1. In the DDP web interface, open "Administration" → "Credentials" and click "Rotate encryption key". + The button is available to users with the `rotate:encryption-key` permission. 1. Enter the current key in "Old encryption key" and the new key in "New encryption key", then click "Re-encrypt". 1. Check that the results table has no records in the "Failed" column. -1. Set the new key in the `security.secretKey` parameter of ModuleConfig `development-platform`. The DDP pods restart automatically. +1. Set the new key in the `security.secretKey` parameter of ModuleConfig `development-platform`. + The DDP pods restart automatically. -Stored credentials are unavailable between re-encryption and the pod restart with the new key. Changing the key invalidates current user sessions. +Stored credentials are unavailable between re-encryption and the pod restart with the new key. +Changing the key invalidates current user sessions. The full procedure and operation results are described in the [key rotation guide](security/encryption-key-rotation/). diff --git a/content/documentation/admin/install.ru.md b/content/documentation/admin/install.ru.md index 48a0bd5b..683ba6aa 100644 --- a/content/documentation/admin/install.ru.md +++ b/content/documentation/admin/install.ru.md @@ -4,19 +4,24 @@ description: Установка Deckhouse Development Portal с внутренн weight: 11 --- -Deckhouse Development Portal (DDP, портал) устанавливается модулем `development-platform` в кластере Deckhouse Platform. Перед установкой проверьте [требования к вычислительным ресурсам](resource-requirements/). +Deckhouse Development Portal (DDP, портал) устанавливается модулем `development-platform` в кластере Deckhouse Platform. +Перед установкой проверьте [требования к вычислительным ресурсам](resource-requirements/). -Для демо рекомендуется установка с [managed-экземплярами](#установка-с-managed-экземплярами), для production — с [внешними экземплярами](#установка-с-внешними-экземплярами). [Внутренние экземпляры](#установка-с-внутренними-экземплярами) доступны как отдельный вариант установки. +Для демо рекомендуется установка с [managed-экземплярами](#установка-с-managed-экземплярами), для production — с [внешними экземплярами](#установка-с-внешними-экземплярами). +[Внутренние экземпляры](#установка-с-внутренними-экземплярами) доступны как отдельный вариант установки. -Режим `managed`, `external` или `internal` задаётся для PostgreSQL, Redis и ClickHouse отдельно: режимы можно сочетать. +Режим `managed`, `external` или `internal` задаётся для PostgreSQL, Redis и ClickHouse отдельно, и режимы можно сочетать. -Параметры `postgres.mode`, `redis.mode` и `clickhouse.mode` обязательны и не имеют значения по умолчанию. Без них установка и обновление модуля завершаются ошибкой проверки настроек. +Параметры `postgres.mode`, `redis.mode` и `clickhouse.mode` обязательны и не имеют значения по умолчанию. +Без них установка и обновление модуля завершаются ошибкой проверки настроек. -ClickHouse хранит исторические данные портала. Чтобы работать без функциональности, которой нужен ClickHouse, явно укажите `clickhouse.mode: external` и оставьте `clickhouse.host` пустым, как описано [ниже](#работа-без-clickhouse). +ClickHouse хранит исторические данные портала. +Чтобы работать без функциональности, которой нужен ClickHouse, явно укажите `clickhouse.mode: external` и оставьте `clickhouse.host` пустым, как описано [ниже](#работа-без-clickhouse). ## Установка с managed-экземплярами -В режиме `managed` модуль создаёт экземпляры PostgreSQL, Valkey (совместим с Redis) и ClickHouse. До установки DDP в кластере должны быть включены соответствующие модули Deckhouse для каждого сервиса, у которого выбран `mode: managed`: +В режиме `managed` модуль создаёт экземпляры PostgreSQL, Valkey (совместим с Redis) и ClickHouse. +До установки DDP в кластере должны быть включены соответствующие модули Deckhouse для каждого сервиса, у которого выбран `mode: managed`: | Параметр DDP | Модуль, который должен быть включён | |---|---| @@ -49,7 +54,7 @@ spec: enabled: true ``` -Если модуль не включён, портал не установится, а в статусе модуля `development-platform` появится ошибка с названием модуля, который нужно включить. +Если модуль не включён, портал не установится, а в статусе модуля `development-platform` появится ошибка с названием модуля, который не включён. Минимальная конфигурация портала для демо-установки: @@ -74,9 +79,12 @@ spec: mode: managed ``` -В режиме `managed` адрес и порт подключения определяются автоматически. Параметры `host`, `port` и `image` для этого режима не используются. +В режиме `managed` адрес и порт подключения определяются автоматически. +Параметры `host`, `port` и `image` для этого режима не используются. -Ресурсы экземпляра задаются в `instance.cpu`, `instance.memory` и `instance.persistentVolumeClaim`. Класс выбирается параметром `instance.className`, по умолчанию `default`; он определяет допустимые размеры и размещение экземпляра. Размеры памяти и диска задавайте в формате Kubernetes Quantity, например `512Mi` или `20Gi`. +Ресурсы экземпляра задаются в `instance.cpu`, `instance.memory` и `instance.persistentVolumeClaim`. +Класс выбирается параметром `instance.className`, по умолчанию `default`; он определяет допустимые размеры и размещение экземпляра. +Размеры памяти и диска задавайте в формате Kubernetes Quantity, например `512Mi` или `20Gi`. Пример настройки ресурсов PostgreSQL: @@ -99,11 +107,12 @@ spec: ## Установка с внешними экземплярами -Для production подключите уже развёрнутые PostgreSQL, Redis и ClickHouse в режиме `external`. Секции независимы: для остальных сервисов можно явно выбрать `internal` или `managed`. +Для production подключите уже развёрнутые PostgreSQL, Redis и ClickHouse в режиме `external`. +Секции независимы, поэтому для остальных сервисов можно явно выбрать `internal` или `managed`. ### Подключение внешнего PostgreSQL -Для использования внешнего экземпляра PostgreSQL необходимо указать параметры подключения в секции `postgres`: +Для использования внешнего экземпляра PostgreSQL укажите параметры подключения в секции `postgres`: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -133,7 +142,8 @@ spec: #### Расширение pg_trgm -Порталу требуется расширение PostgreSQL `pg_trgm`. Если используется внешний PostgreSQL, включите его до запуска DDP — подключитесь к базе данных под пользователем с правами на создание расширений и выполните: +Порталу требуется расширение PostgreSQL `pg_trgm`. +Если используется внешний PostgreSQL, включите его до запуска DDP — подключитесь к базе данных под пользователем с правами на создание расширений и выполните: ```sql CREATE EXTENSION IF NOT EXISTS pg_trgm; @@ -143,7 +153,7 @@ CREATE EXTENSION IF NOT EXISTS pg_trgm; ### Подключение внешнего Redis -Для использования внешнего экземпляра Redis необходимо указать параметры подключения в секции `redis`: +Для использования внешнего экземпляра Redis укажите параметры подключения в секции `redis`: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -211,7 +221,8 @@ spec: ## Установка с внутренними экземплярами -В режиме `internal` модуль разворачивает PostgreSQL, Redis и ClickHouse в кластере. Включите `development-platform` с помощью [ModuleConfig](/products/kubernetes-platform/documentation/v1/reference/api/cr.html#moduleconfig), указав суперадминистратора, ключ шифрования и режим каждого сервиса: +В режиме `internal` модуль разворачивает PostgreSQL, Redis и ClickHouse в кластере. +Включите `development-platform` с помощью [ModuleConfig](/products/kubernetes-platform/documentation/v1/reference/api/cr.html#moduleconfig), указав суперадминистратора, ключ шифрования и режим каждого сервиса: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -234,13 +245,17 @@ spec: mode: internal ``` -Адрес веб-интерфейса формируется из параметра кластера `publicDomainTemplate` и параметра модуля `domain.prefix`, по умолчанию `ddp`. Например, при `publicDomainTemplate: "%s.example.com"` веб-интерфейс доступен по адресу `https://ddp.example.com`. Для другого домена задайте `domain.useCustomDomain` и `domain.customDomain`. Все параметры приведены [в настройках модуля](/modules/development-platform/configuration.html). +Адрес веб-интерфейса формируется из параметра кластера `publicDomainTemplate` и параметра модуля `domain.prefix`, по умолчанию `ddp`. +Например, при `publicDomainTemplate: "%s.example.com"` веб-интерфейс доступен по адресу `https://ddp.example.com`. +Для другого домена задайте `domain.useCustomDomain` и `domain.customDomain`. +Все параметры приведены [в настройках модуля](/modules/development-platform/configuration.html). Этот вариант разворачивает сервисы самим модулем, без managed-операторов. ### Настройка внутренних экземпляров (опционально) -Чтобы загрузить образы внутренних PostgreSQL, Redis и ClickHouse из приватного хранилища, создайте Secret типа `kubernetes.io/dockerconfigjson` с учётными данными хранилища в неймспейсе `d8-development-platform`. Укажите образы в параметрах `image`, а название Secret в `additionalImagePullSecrets`: +Чтобы загрузить образы внутренних PostgreSQL, Redis и ClickHouse из приватного хранилища, создайте Secret типа `kubernetes.io/dockerconfigjson` с учётными данными хранилища в неймспейсе `d8-development-platform`. +Укажите образы в параметрах `image`, а название Secret в `additionalImagePullSecrets`: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -270,11 +285,15 @@ spec: ## ClickHouse -ClickHouse хранит исторические данные, например [историю изменений параметров сущностей](../user/catalog/#история-параметров). Выберите `internal` для экземпляра в составе модуля, `managed` для создания через модуль `managed-clickhouse` или `external` для подключения существующего сервера. Для промышленной эксплуатации используйте внешний экземпляр. +ClickHouse хранит исторические данные, например [историю изменений параметров сущностей](../user/catalog/#история-параметров). +Выберите `internal` для экземпляра в составе модуля, `managed` для создания через модуль `managed-clickhouse` или `external` для подключения существующего сервера. +Для промышленной эксплуатации используйте внешний экземпляр. ### Внутренний экземпляр ClickHouse -Чтобы развернуть ClickHouse в составе модуля, явно задайте `clickhouse.mode: internal`. В следующем примере образ загружается из приватного хранилища; предварительно создайте Secret `custom-registry-secret` с учётными данными хранилища в неймспейсе `d8-development-platform`. Параметр `host` в этом режиме не используется: +Чтобы развернуть ClickHouse в составе модуля, явно задайте `clickhouse.mode: internal`. +В следующем примере образ загружается из приватного хранилища; предварительно создайте Secret `custom-registry-secret` с учётными данными хранилища в неймспейсе `d8-development-platform`. +Параметр `host` в этом режиме не используется: ```yaml apiVersion: deckhouse.io/v1alpha1 @@ -303,7 +322,9 @@ spec: - custom-registry-secret ``` -В этом режиме портал разворачивает один экземпляр ClickHouse с постоянным хранилищем размером `10Gi`. База данных создаётся при первом запуске на пустом томе. После восстановления данных из резервной копии или изменения параметра `database` создайте базу данных вручную, как описано [ниже](#создание-базы-данных-clickhouse). +В этом режиме портал разворачивает один экземпляр ClickHouse с постоянным хранилищем размером `10Gi`. +База данных создаётся при первом запуске на пустом томе. +После восстановления данных из резервной копии или изменения параметра `database` создайте базу данных вручную, как описано [ниже](#создание-базы-данных-clickhouse). ### Внешний экземпляр ClickHouse @@ -336,20 +357,23 @@ spec: ``` {{< alert level="warning" >}} -Создайте базу данных до подключения внешнего экземпляра: портал применяет миграции схемы, но саму базу данных не создаёт. +Создайте базу данных до подключения внешнего экземпляра, поскольку портал применяет миграции схемы, но саму базу данных не создаёт. {{< /alert >}} ### Создание базы данных ClickHouse При `mode: managed` модуль создаёт базу данных автоматически. -При подключении внешнего экземпляра создайте базу данных до запуска DDP. Замените `ddp` значением параметра `clickhouse.database`: +При подключении внешнего экземпляра создайте базу данных до запуска DDP. +Замените `ddp` значением параметра `clickhouse.database`: ```sql CREATE DATABASE IF NOT EXISTS ddp; ``` -При `mode: internal` база создаётся при первом запуске на пустом томе. Если том уже содержит данные или изменён параметр `database`, создайте базу вручную. Замените `ddp` названием базы: +При `mode: internal` база создаётся при первом запуске на пустом томе. +Если том уже содержит данные или изменён параметр `database`, создайте базу вручную. +Замените `ddp` названием базы: ```shell d8 k -n d8-development-platform exec clickhouse-0 -c clickhouse -- \ @@ -366,22 +390,29 @@ d8 k -n d8-development-platform exec clickhouse-0 -c clickhouse -- \ host: "" ``` -В этом случае возможности, которые зависят от ClickHouse, недоступны: например, не сохраняется история изменений параметров сущностей. +В этом случае возможности, которые зависят от ClickHouse, недоступны. +Например, не сохраняется история изменений параметров сущностей. ### Доставка данных в ClickHouse -Доставку данных из PostgreSQL в ClickHouse и последующую очистку выполняют воркеры портала, поэтому для переноса данных нужен хотя бы один запущенный воркер. Параметры доставки задаются в секции `clickhouse.replication`, [срок хранения истории параметров](../user/catalog/#хранение-истории) и периодичность очистки — в секции `clickhouse.propertyHistory`. Подробнее о воркерах — в разделе [«Воркеры»](architecture/workers/). +Доставку данных из PostgreSQL в ClickHouse и последующую очистку выполняют воркеры портала, поэтому для переноса данных нужен хотя бы один запущенный воркер. +Параметры доставки задаются в секции `clickhouse.replication`, [срок хранения истории параметров](../user/catalog/#хранение-истории) и периодичность очистки — в секции `clickhouse.propertyHistory`. +Подробнее о воркерах — в разделе [«Воркеры»](architecture/workers/). ## Смена ключа шифрования -DDP шифрует сохранённые учётные данные ключом из параметра `security.secretKey`. Если заменить ключ без перешифрования, сохранённые данные станут недоступны. +DDP шифрует сохранённые учётные данные ключом из параметра `security.secretKey`. +Если заменить ключ без перешифрования, сохранённые данные станут недоступны. Чтобы сменить ключ: -1. В веб-интерфейсе DDP откройте «Администрирование» → «Учетные данные» и нажмите «Ротация ключа шифрования». Кнопка доступна пользователям с правом `rotate:encryption-key`. +1. В веб-интерфейсе DDP откройте «Администрирование» → «Учётные данные» и нажмите «Ротация ключа шифрования». + Кнопка доступна пользователям с правом `rotate:encryption-key`. 1. Введите текущий ключ в поле «Старый ключ шифрования», новый в поле «Новый ключ шифрования» и нажмите «Перешифровать». 1. Проверьте, что в таблице результатов нет записей в столбце «Неуспешно». -1. Укажите новый ключ в параметре `security.secretKey` в ModuleConfig `development-platform`. Поды DDP перезапустятся автоматически. +1. Укажите новый ключ в параметре `security.secretKey` в ModuleConfig `development-platform`. + Поды DDP перезапустятся автоматически. -Между перешифрованием и перезапуском подов с новым ключом сохранённые учётные данные недоступны. Смена ключа делает текущие пользовательские сеансы недействительными. +Между перешифрованием и перезапуском подов с новым ключом сохранённые учётные данные недоступны. +Смена ключа делает текущие пользовательские сеансы недействительными. Подробный порядок и результаты операции описаны [в руководстве по ротации ключа шифрования](security/encryption-key-rotation/). diff --git a/content/documentation/admin/overview.md b/content/documentation/admin/overview.md index 23c6c959..547e7cb1 100644 --- a/content/documentation/admin/overview.md +++ b/content/documentation/admin/overview.md @@ -4,4 +4,4 @@ description: Contents of the Deckhouse Development Portal administrator guide. weight: 10 --- -The administrator guide of Deckhouse Development Portal (DDP) describes how to install the portal and configure its mechanisms: data sources, actions, processes, widgets, health checks, and others. The guide is part of the operational documentation for the product. +The administrator guide of Deckhouse Development Portal (DDP) describes how to install the portal and configure its mechanisms: datasources, actions, processes, widgets, health checks, and others. The guide is part of the operational documentation for the product. diff --git a/content/documentation/admin/processes/overview.md b/content/documentation/admin/processes/overview.md index d9af79b3..4493b5e7 100644 --- a/content/documentation/admin/processes/overview.md +++ b/content/documentation/admin/processes/overview.md @@ -8,43 +8,49 @@ Processes are an automation mechanism for complex business scenarios that lets y ## Key concepts +This section describes the main parts of a process. + ### Process elements A process consists of various types of elements: -* "Start" — the process entry point. -* "Task" — runs a specific action. -* "Exclusive gateway" — conditional branching. -* "Parallel gateway" — merges several process branches into one. -* "Loop" — repeats part of the process a fixed number of times, or iterates over a JSON array from the store. -* "Template" — evaluates a Go template and writes the result to the process store. -* "Timer" — pauses until a specified point in time. -* "Note" — a text block. -* "Error" — immediately stops the process with the `Failed` status. -* "End" — completes the process. +* "Start": The process entry point. +* "Task": Runs a specific action. +* "AI agent": Sends a task to an AI agent and writes the result to the process store. +* "Exclusive gateway": Conditional branching. +* "Parallel gateway": Merges several process branches into one. +* "Loop": Repeats part of the process a fixed number of times, or iterates over a JSON array from the store. +* "Template": Evaluates a Go template and writes the result to the process store. +* "Timer": Pauses until a specified point in time. +* "Note": A text block. +* "Error": Immediately stops the process with the `Failed` status. +* "End": Completes the process. ## Creating a process +A process is created and configured in the process editor. + ### Basic information To create a process, go to "Self-service" → "Processes" and click "Create". Fill in the following fields: -* "Name" — the process name. -* "Description" — a detailed description of the process's purpose. -* "Resource" — one or more resources for which the process can be run. -* "Owner" — the user responsible for the process. -* "Owner team" — the team responsible for the process. -* "Tags" — tags used to categorize the process. -* "Icon" — the icon displayed in the interface. +* "Name": The process name. +* "Description": A detailed description of the process's purpose. +* "Resource": One or more resources for which the process can be run. +* "Owner": The user responsible for the process. +* "Owning team": The team responsible for the process. +* "Tags": Tags used to categorize the process. +* "Icon": The icon displayed in the interface. ### Process configuration The process is configured in the visual editor, on the "Configuration" tab. {{< alert level="info" >}} -To configure a process, you must first fill in the basic fields and create it. After that, the "Configuration" and "Parameters" tabs become available. +To configure a process, you must first fill in the basic fields and create it. +After that, the "Configuration" and "Parameters" tabs become available. {{< /alert >}} #### Adding elements @@ -52,168 +58,272 @@ To configure a process, you must first fill in the basic fields and create it. A To add elements to the diagram: 1. Add an element by selecting its type in the editor panel. -1. Configure the element's parameters in the side panel (action, conditions, etc.). +1. Configure the element's parameters in the side panel, for example, the action and conditions. 1. Connect the elements to each other. -#### Element types +### Process parameters + +The "Parameters" tab is used to configure process parameters that can be used in all actions within the process. + +The configuration and use of process parameters are described in [Templating](../../user/templating/#process-parameters). + +### Process store + +The process store is a JSON object used to pass data between steps of a single run: identifiers, arrays, intermediate results, and text produced by the "Template" element. + +For a full description of write rules, operations, loop context, and example scenarios, see [Process store](store/). + +In brief: + +- **One store per run**: Each process instance has its own store; it can be viewed on the "Store" tab when visualizing a run. +- **Nested paths**: Keys are specified with dots: `notification.module_name`, `ctx.job.id`; array indices are supported: `items[0].status`. +- **Rule-based writes**: Data is written to the store after an action completes successfully, or when the "Template" element runs. + Available operations include setting strings and JSON, appending, merging, and deleting, plus a condition for each rule. + Action rules are configured as described in [Process store update](../../actions/overview/#process-store-update). +- **Reading**: Go templates `{{ .store. }}` in action configuration and gateway conditions. + The syntax is described in the [Process store](../../user/templating/#process-store) section of the "Templating" page. + +If a key is not present in the store, the template `{{ .store. }}` will cause the step to fail with an error. -##### Task +## Element types + +A process diagram is built from elements of the following types. + +### Task Each task runs a specific action previously created in "Self-service" → "Actions". -##### Exclusive gateway +### AI agent + +The "AI agent" element sends a task to an [AI agent](../ai-agents/overview/), waits for the agent run to finish, and writes the result to the process store. +The agent runs on portal workers on behalf of the user who started the process. + +The "Timeout (seconds)" field sets how long to wait for the agent run to finish. +If the field is empty, the wait lasts 60 minutes. +When the timeout expires, the agent run is interrupted, and the step gets the `Timeout` status. + +If the agent is unavailable when the step starts, for example, a local agent does not respond, the agent run fails immediately, and the step is handled as an [agent error](#agent-error). +To run the step again, restart the process. + +The element configuration includes the following fields: + +| Name | Required | Description | +| --- | --- | --- | +| "Executor" | Yes | "Agent" from the catalog or "Workspace" | +| "Workspace" | For the "Workspace" executor | Workspace UUID or a Go template, for example, `{{ .process.workspace_uuid }}` | +| "Agent" | For the "Agent" executor | Agent identifier. You can specify a Go template, for example, `{{ .process.agent_slug }}` | +| "Agent message" | Yes | Go template of the message that the agent receives. The `.process`, `.store`, and `.context` roots are available | +| "Output store key" | Yes | Process store dot-path where the result is written, for example, `agent_result` or `analysis.plan`. Defaults to `agent_result` | +| "AI provider" | For agents whose model is provided by the portal | AI provider name. Required for the platform agent and for external agents with the DDP model proxy allowed | + +The AI provider is looked up by name among the providers of the user who started the process. +A provider from a template with a shared token is available to everyone allowed to use the template, and a personal provider is available only to its owner. +If the provider is not set in the element, it can be selected when starting the process. +Without a provider, the process does not start and returns an error. + +The agent gets the tools of its assigned MCP collections that the process initiator can use. +Without collections, the agent works without MCP tools. +Running the step requires the `use:ai-agents` permission or `use:ai-agent` on the selected agent. + +In the "Executor" field, you can also select "Workspace". +In this mode, the step sends the job to the attached chat of the initiator's workspace bound to the process entity. + +#### Agent result + +After the agent run finishes, the portal writes the following object to the store under the key from the "Output store key" field: + +```json +{ + "type": "agent_run", + "runUuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "agentSlug": "ddp-agent", + "status": "succeeded", + "answer": "Agent response text", + "finishedAt": "2026-10-09T10:15:00Z" +} +``` + +The `status` field takes the `succeeded`, `failed`, or `cancelled` value; on error, the `error` field with the error text is added. +If the key already exists in the store, its value is overwritten. + +Subsequent elements get the agent response through the store, for example, `{{ .store.agent_result.answer }}`. +A key with a dot is written as a nested object. +For example, the result under the `analysis.plan` key is read as `{{ .store.analysis.plan.answer }}`. + +#### Agent error + +If the agent run fails, the behavior depends on the element's connections. +If a connection to an exclusive gateway or a conditional connection leaves the element, the portal writes the result with the `status` and `error` fields to the store and continues the process along the outgoing connections. +To route the process to an error-handling branch, check the `{{ eq .store.agent_result.status "succeeded" }}` condition in the gateway. +Otherwise, the process branch ends at this element, and the error is reflected in the final process status. -An exclusive gateway lets you configure process branching based on conditions. By default, the status of the previous task is checked, and depending on it, execution follows the "success" or "failure" branch. +If the user stops the agent run, the process branch ends at this element without following the outgoing connections, and the cancellation is reflected in the [final process status](#process-statuses). + +If the agent run cannot be created, for example, the "Agent message" template refers to a key missing from the store, the step also ends with the `Failed` status. +The error reason is shown on the "Execution log" tab of the step side panel. + +If the agent run succeeds but the result cannot be written to the path from the "Output store key" field, the step ends with the `Failed` status, and the process does not continue along the outgoing connections. +Writing is impossible when the path goes through a value that is not an object, for example, the `catalog.status.answer` key when `catalog.status` contains a string. + +#### Repeated execution + +Each time the process passes through the element again, for example, on a new loop iteration, the portal creates a new agent run. +Agent runs appear in the AI agent [run history](../ai-agents/runs/) with the "Process" trigger, and the agent response and tool calls appear in the element side panel on the run diagram. + +### Exclusive gateway + +An exclusive gateway lets you configure process branching based on conditions. +By default, the status of the previous task is checked, and depending on it, execution follows the "success" or "failure" branch. As conditions for an exclusive gateway, you can set either a check of the previous task's status, or a comparison of values from templates: - To check the status of the previous task, use the construct `{{ .prev_task.status }}`. -- To check a value from the store, use `{{ .store. }}`, including nested keys: `{{ .store.notification.status }}`. -- Inside a loop — fields of the current item: `{{ .store._loop.item.scan_type }}`, and the flags `{{ .store._loop.first }}` and `{{ .store._loop.last }}`. +- To check a value from the store, use `{{ .store. }}`, including nested keys: `{{ .store.notification.status }}`. +- Inside a loop: Fields of the current item: `{{ .store._loop.item.scan_type }}`, and the flags `{{ .store._loop.first }}` and `{{ .store._loop.last }}`. You can check multiple conditions and combine their results using the `AND` or `OR` operator. -If the condition check passes, the process follows the "True" branch (green); if not, it follows the "False" branch (red). The "True" and "False" ports can be placed on any side of the gateway; a connection can be moved to a different port. +If the condition check passes, the process follows the "True" branch (green); if not, it follows the "False" branch (red). +The "True" and "False" ports can be placed on any side of the gateway; a connection can be moved to a different port. -##### Parallel gateway +### Parallel gateway Used to merge several branches into one, based on specified conditions. -In the parallel gateway's configuration, you can set the following waiting parameters: +In the parallel gateway's configuration, you can choose whether to wait for all incoming elements or for at least one incoming element to complete before continuing execution. + +You can also configure what exactly counts as "completion": only successful completion of the tasks feeding into the gateway +or any final status of the incoming tasks (for example, `Failed` or `Skipped`). -- Wait for all incoming elements to complete before continuing execution. -- Wait for at least one incoming element to complete before continuing execution. +A parallel gateway can also be used to split branches, if connected after "Exclusive gateway" or "Loop" elements, or as a helper element to improve the readability of the process diagram. -You can also configure what exactly counts as "completion": +#### Merging branches in a loop -- Only successful completion of the tasks feeding into the gateway. -- Any final status of the incoming tasks (`Failed`, `Skipped`, etc.). +If a parallel gateway merges branches inside a loop or on a return path through a back connection, on each pass the gateway counts only the branches that finished during this pass. +A branch finished on a previous iteration is not counted. -A parallel gateway can also be used to split branches, if connected after "Exclusive gateway" or "Loop" elements, or as a helper element to improve the readability of the process diagram. +Therefore, each branch entering the gateway must reach it on every pass. +If a branch does not reach the gateway within the element timeout (60 minutes by default), the gateway fails with the `ParallelGateway Join timed out` error and the list of unfinished branches. +The timeout is counted from the start of the current pass. -##### Loop +The `tasksCompleted` and `tasksCompletedAny` conditions of the exclusive gateway check whether a task has finished at least once during the whole process run, not only during the current pass. -The "Loop" element repeats a branch of the process either a fixed number of times, or once for each element of a JSON array from the store. Once all iterations are complete, the element connected to the loop's exit is activated. +### Loop -###### Loop mode +The "Loop" element repeats a branch of the process either a fixed number of times, or once for each element of a JSON array from the store. +Once all iterations are complete, the element connected to the loop's exit is activated. -Two modes are available: +#### Loop mode -- "Fixed count" — the "Number of iterations" field, from 1 to 10000. On each iteration, `{{ .store._loop.item }}` holds the iteration number (1, 2, 3…). -- "Foreach collection" — the "Collection template" field: a Go template that, when entering the loop, must produce a JSON array. Typically, this is a path to an array written by a previous task: `{{ .store.notification.engagements }}`. Each array element is one iteration; the current element is available as `{{ .store._loop.item }}`. The array can contain up to 10,000 items; a larger array fails the loop with an error. +Two modes are available. + +In the "Fixed count" mode, set the "Number of iterations" from 1 to 10000. +On each iteration, `{{ .store._loop.item }}` holds the iteration number (1, 2, 3…). + +In the "Foreach collection" mode, set the "Collection template": a Go template that, when entering the loop, must produce a JSON array. +Typically, this is a path to an array written by a previous task: `{{ .store.notification.engagements }}`. +Each array element is one iteration; the current element is available as `{{ .store._loop.item }}`. +The array can contain up to 10,000 items; a larger array fails the loop with an error. If the array is empty or the key is missing, the loop body is not executed, and the process immediately follows the "Exit" connection. For more information, see [Process store](store/#looping-over-a-collection-from-the-store). -###### Outgoing connections +#### Outgoing connections Exactly two connections to different elements must originate from the "Loop" element: -1. "Loop body" — the branch built from this port is executed on each iteration. -1. "Exit" — execution continues along this branch after the last iteration. +1. "Loop body": The branch built from this port is executed on each iteration. +1. "Exit": Execution continues along this branch after the last iteration. The "Loop body" and "Exit" ports can be placed on any side of the element; a connection can be moved to a different port. -###### Usage +#### Usage Typical scenarios: -- repeatedly checking the status of an external system with a fixed number of attempts; -- iterating over a list of objects from an API response: a task writes the array to the store, and a loop in "Foreach collection" mode processes each element; -- nested loops — the parent context is available via `{{ .store._loop.parent }}`. +- Repeatedly checking the status of an external system with a fixed number of attempts. +- Iterating over a list of objects from an API response: a task writes the array to the store, and a loop in "Foreach collection" mode processes each element. +- Nested loops — the parent context is available via `{{ .store._loop.parent }}`. -##### Template +### Template The "Template" element evaluates a Go template without calling an additional action, and writes the result to the store as a string. Configure: -- "Template body" — text with placeholders `{{ .store.* }}`, `{{ .process.* }}`, and, inside a loop, `{{ .store._loop.* }}`; -- "Output store key" — the destination dot-path, e.g. `rendered_message`; -- "Format hint" — how to display the value when viewing the run (`text`, `markdown`, `html`, `json`); does not affect the store's content. +- "Template body": Text with placeholders `{{ .store.* }}`, `{{ .process.* }}`, and, inside a loop, `{{ .store._loop.* }}`. +- "Output store key": The destination dot-path, for example, `rendered_message`. +- "Format hint": How to display the value when viewing the run (`text`, `markdown`, `html`, `json`); does not affect the store's content. For examples and limitations, see [Process store](store/#the-template-element). -##### Timer +### Timer The "Timer" element pauses process execution until a specified point in time, after which the next element is activated. -While the process is only waiting for the timer to fire (no other active tasks), the run is placed in the `Wait` status. The run visualization panel shows the banner "Waiting on timer — not before {ends} ({remaining})" with the estimated resumption time. +While the process is only waiting for the timer to fire (no other active tasks), the run is placed in the `Wait` status. +The run visualization panel shows the banner "Waiting on timer — not before {ends} ({remaining})" with the estimated resumption time. -###### Outgoing connections +#### Outgoing connections -Exactly one connection to the next element must originate from the "Timer" element. Connection is only possible through the left (input) and right (output) ports. +Exactly one connection to the next element must originate from the "Timer" element. +Connection is only possible through the left (input) and right (output) ports. If the timer is passed through again within the same run (for example, via a loop), the trigger time is recalculated. -###### Schedule modes +#### Schedule modes -In the timer's configuration, select a "Schedule": - -- "Delay after this element starts" — a fixed pause from the moment the process reaches the timer. Set the "Delay (seconds)" from 1 to 1,209,600 (14 days). -- "Custom schedule" — triggers at a specified calendar time in the selected time zone (IANA, e.g. `Europe/Moscow`). +In the timer's configuration, select a "Schedule". +The "Delay after this element starts" option sets a fixed pause from the moment the process reaches the timer. +Set the "Delay (seconds)" from 1 to 1,209,600 (14 days). +The "Custom schedule" option triggers the timer at a specified calendar time in the selected time zone (IANA format, for example, `Europe/Moscow`). For "Custom schedule" mode, specify a "Pattern": -- "Specific weekday" — "Day of week", "Time of day" (hour and minute), "Time zone". -- "Specific day each month" — "Day of month" (1–31), "Time of day", "Time zone". If the month does not have that day, the last day of the month is used. -- "Every N days" — "Every N days" (1–365), "Time of day", "Time zone". The first trigger is no earlier than N calendar days from the day the process reached the timer; upon re-entering the element, the calculation is redone. +- "Specific weekday": "Day of week", "Time of day" (hour and minute), "Time zone". +- "Specific day each month": "Day of month" (1–31), "Time of day", "Time zone". + If the month does not have that day, the last day of the month is used. +- "Every N days": "Every N days" (1–365), "Time of day", "Time zone". + The first trigger is no earlier than N calendar days from the day the process reached the timer; upon re-entering the element, the calculation is redone. "Time of day" is set in the selected time zone (the "Time zone" field), if it differs from the browser's time zone. -###### Usage +#### Usage Typical scenarios: a pause before re-checking the status of an external system, a delayed start of the next step, waiting for a maintenance window, or a regular calendar slot. -##### Note +### Note The "Note" element is intended for text annotations on the process diagram: it is not executed at runtime and is not connected to other elements. In the note's configuration, you can set: -- "Text" — content with Markdown support. -- "Background color" — the fill color. -- "Text color" — the text color. +- "Text": Content with Markdown support. +- "Background color": The fill color. +- "Text color": The text color. -A note is always positioned behind other elements and can be used to visually highlight parts of the process. It is also the only element whose size can be changed. +A note is always positioned behind other elements and can be used to visually highlight parts of the process. +It is also the only element whose size can be changed. -##### Error +### Error The "Error" element forcibly transitions a running process to the `Failed` status: when this element is reached, execution of all process actions is interrupted. No connections to subsequent elements should originate from this element. -### Process parameters - -The "Parameters" tab is used to configure process parameters that can be used in all actions within the process. - -The configuration and use of process parameters are described in [Templating](../../user/templating/#process-parameters). - -### Process store - -The process store is a JSON object used to pass data between steps of a single run: identifiers, arrays, intermediate results, and text produced by the "Template" element. - -For a full description of write rules, operations, loop context, and example scenarios, see [Process store](store/). - -In brief: - -- **One store per run** — each process instance has its own store; it can be viewed on the "Store" tab when visualizing a run. -- **Nested paths** — keys are specified with dots: `notification.module_name`, `ctx.job.id`; array indices are supported: `items[0].status`. -- **Rule-based writes** — data is written to the store after an action completes successfully, or when the "Template" element runs. Available operations include setting strings and JSON, appending, merging, and deleting, plus a condition for each rule. Action rules are configured as described in [Process store update](../../actions/overview/#process-store-update). -- **Reading** — Go templates `{{ .store. }}` in action configuration and gateway conditions. The syntax is described in the [Process store](../../user/templating/#process-store) section of the "Templating" page. - -If a key is not present in the store, the template `{{ .store. }}` will cause the step to fail with an error. - ## Running a process +A process can be run manually or by an automation. + ### Manual run To run a process manually: 1. Go to the entity for which the process needs to be run. 1. In the entity's menu, select "Run process". -1. Choose the desired process from the list. If only one process is available, it is selected automatically and the list is not shown. +1. Choose the desired process from the list. + If only one process is available, it is selected automatically and the list is not shown. 1. Fill in the process parameters. 1. Click "Run". @@ -221,60 +331,75 @@ After the run starts, the notification "Process "{name}" started" is shown. ### Launch parameters -The "Run process" dialog opens in simplified mode. It shows only the process parameters with the ["Show in simplified form"](../../user/properties/#configuration) flag and the required parameters that have no value. The other parameters keep their default values and are passed at launch. +The "Run process" dialog opens in simplified mode. +It shows only the process parameters with the ["Show in simplified form"](../../user/properties/#configuration) flag and the required parameters that have no value. +The other parameters keep their default values and are passed at launch. -Above the parameters, the hint "Showing important parameters: {important} of {total}" is shown. If there are no important parameters, "No important parameters" is shown. If nothing needs to be filled in, the message "This process has no parameters to fill in — click "Run" to start it" is shown. +Above the parameters, the hint "Showing important parameters: {important} of {total}" is shown. +If there are no important parameters, "No important parameters" is shown. +If nothing needs to be filled in, the message "This process has no parameters to fill in — click "Run" to start it" is shown. -The "All process parameters" button switches the dialog to full mode, and the "Important parameters only" button switches it back. Full mode has the following sections: +The "All process parameters" button switches the dialog to full mode, and the "Important parameters only" button switches it back. +Full mode has the following sections: -* "Common process properties" — parameters defined in the process configuration; -* "Process team properties" — the team whose variables are used during execution; -* "Configuration" — the process diagram. Click a task to enable or disable its action and fill in its parameters. +* "Common process properties": Parameters defined in the process configuration. +* "Process team properties": The team whose variables are used during execution. +* "Configuration": The process diagram. Click a task to enable or disable its action and fill in its parameters. The process description is shown under the title in a shortened form; the "more" link expands it. -If a required process parameter is not filled in, clicking "Run" shows the error "Fill all required process properties". If a required field of an enabled task is not filled in, the dialog switches to full mode and shows the error "Fill all required fields for all enabled tasks". +If a required process parameter is not filled in, clicking "Run" shows the error "Fill all required process properties". +If a required field of an enabled task is not filled in, the dialog switches to full mode and shows the error "Fill all required fields for all enabled tasks". ### Launch context -The launch context is a set of values that a portal section passes to the process at launch, for example, the environment and the system selected on the home page. The user does not enter the context, and it is not stored in the process configuration. +The launch context is a set of values that a portal section passes to the process at launch, for example, the environment and the system selected on the Home page. +The user does not enter the context, and it is not stored in the process configuration. -In process templates, the context is available via the `.context` root, for example, `{{ .context.environment.slug }}`. A process run from the catalog receives an empty context. +In process templates, the context is available via the `.context` root, for example, `{{ .context.environment.slug }}`. +A process run from the catalog receives an empty context. ## Execution management +While a process runs, you can track its status and control execution. + ### Process statuses The run status is shown as one of the following values: -* `Running` — the process is running. -* `Wait` — the process is only waiting for a timer to fire. -* `Unapproved` — all active tasks are waiting for action approval. -* `Paused` — process execution is paused. -* `Resuming` — the run is being restored after a portal restart. -* `Completed` — the process reached an "End" element, and no task failed or was declined. -* `Partially Completed` — the process reached at least one "End" element, but some tasks failed or were declined. -* `Failed` — the process finished with an error: no "End" element was reached, or the process reached an "Error" element. -* `Canceled` — the run was stopped or canceled by a user. +* `Running`: The process is running. +* `Wait`: The process is only waiting for a timer to fire. +* `Unapproved`: All active tasks are waiting for action approval. +* `Paused`: Process execution is paused. +* `Resuming`: The run is being restored after a portal restart. +* `Completed`: The process reached an "End" element, and no task failed or was declined. +* `Partially Completed`: The process reached at least one "End" element, but some tasks failed or were declined. +* `Failed`: The process finished with an error: no "End" element was reached, or the process reached an "Error" element. +* `Canceled`: The run was stopped or canceled by a user. ### Management operations -Run management buttons are shown on the run card in the "My Activities" panel, on the "Processes" tab. The set of buttons depends on the run status: +Run management buttons are shown on the run card in the "My Activities" panel, on the "Processes" tab. +The set of buttons depends on the run status: -* "Retry process" — restarts the process from the "Start" element; the run timeline is preserved. A run in the `Running`, `Wait`, `Paused`, `Resuming` or `Unapproved` status cannot be retried: stop it first. -* "Pause process" — pauses a run in the `Running` status. -* "Resume process" — resumes a run in the `Paused` status. -* "Cancel process" — cancels a run in the `Running` or `Paused` status. The run gets the `Canceled` status. -* "Stop process" — stops a run in another non-final status, for example, `Wait` or `Unapproved`. The run gets the `Canceled` status. -* "Delete process" — deletes the run. +* "Retry process": Restarts the process from the "Start" element; the run timeline is preserved. + A run in the `Running`, `Wait`, `Paused`, `Resuming` or `Unapproved` status cannot be retried: stop it first. +* "Pause process": Pauses a run in the `Running` status. +* "Resume process": Resumes a run in the `Paused` status. +* "Cancel process": Cancels a run in the `Running` or `Paused` status. The run gets the `Canceled` status. +* "Stop process": Stops a run in another non-final status, for example, `Wait` or `Unapproved`. + The run gets the `Canceled` status. +* "Delete process": Deletes the run. -The same operations are available on the "Process history" tab of the entity. There, canceling and stopping are performed by one button. +The same operations are available in the "Run history" table on the "Processes" tab of the entity. +There, canceling and stopping are performed by one button. ### State tracking -While the user has running processes, the "My Activities" panel icon in the top bar of the portal is replaced by an indicator. The "Processes" tab of the panel shows the number of running processes and the line "Processes running: {count}"; the list is updated when a process starts and finishes. +While the user has running processes, the "My Activities" panel icon in the top bar of the portal is replaced by an indicator. +The "Processes" tab of the panel shows the number of running processes and the line "Processes running: {count}"; the list is updated when a process starts and finishes. -On the "Process history" tab of the entity, you can view: +In the "Run history" table on the "Processes" tab of the entity, you can view: * A list of all process runs for the entity. * Detailed information about each run. @@ -287,41 +412,57 @@ On the "Process history" tab of the entity, you can view: The run visualization panel has a "Timeline" tab that shows the process execution history: for each element that participated in the current run, the start and end times, duration, and status are shown. +#### Run diagram + +While a run is in progress, the diagram is updated every 5 seconds. +The element state is shown by a mark in the corner of the element: completed, completed after retry, error, declined, cancelled, running, waiting, skipped, or awaiting approval. +For a finished run, the side panel of an element that did not finish by itself shows the final run status and its completion time. +A task awaiting approval can be approved with the "Approve" button directly on the diagram. +The button is active only for users from the action's list of [approvers](../../actions/overview/#approval). + +The traversed path is highlighted, and connections the process did not follow are shown in light gray. +Elements traversed on previous loop iterations are dimmed, and the loop shows "Iteration {current} of {total}". +If an element ran several times, its side panel shows the log of each pass separately with the "Visit {n}" heading. + #### Process log -A detailed execution log is available for each process run: a panel on the run diagram, a separate window, or a dock at the bottom of the screen. The log and the store's JSON can be downloaded from the process run dialog panel. +A detailed execution log is available for each process run: a panel on the run diagram, a separate window, or a dock at the bottom of the screen. +The log and the store's JSON can be downloaded from the process run dialog panel. ## Usage examples +The following examples show typical processes. + ### Creating a configured project Typical process diagram: -1. "Start" — starts the process. -1. "Task" — creates a project in GitLab. -1. "Exclusive gateway" — checks whether creation succeeded. +1. "Start": Starts the process. +1. "Task": Creates a project in GitLab. +1. "Exclusive gateway": Checks whether creation succeeded. 1. "Task" (on success) — configures the project's variables. 1. "Task" (on failure) — sends an error notification. -1. "End" — completes the process. +1. "End": Completes the process. ### Deploying an application Typical process diagram: -1. "Start" — starts the deployment process. -1. "Parallel gateway" — splits into branches. +1. "Start": Starts the deployment process. +1. "Parallel gateway": Splits into branches. 1. "Task" (branch 1) — creates a namespace in Kubernetes. 1. "Task" (branch 2) — creates secrets in Vault. -1. "Parallel gateway" — waits for both branches to complete. -1. "Task" — deploys the application. -1. "End" — completes the process. +1. "Parallel gateway": Waits for both branches to complete. +1. "Task": Deploys the application. +1. "End": Completes the process. ## Limitations The following limitations apply to processes: * A "Loop" element in "Fixed count" mode runs from 1 to 10,000 iterations. -* The collection of a "Loop" element in "Foreach collection" mode can contain up to 10,000 items. A larger collection fails the loop with an error. +* The collection of a "Loop" element in "Foreach collection" mode can contain up to 10,000 items. + A larger collection fails the loop with an error. * The "Delay (seconds)" field of a "Timer" element accepts values from 1 to 1,209,600 (14 days), and the "Every N days" field accepts values from 1 to 365. * The body of a "Template" element is limited to 1 MiB. -* If the "Timeout (sec)" field of a task is greater than zero, the task is interrupted after this time and gets the `Timeout` status. +* If the "Timeout (seconds)" field of a task is greater than zero, the task is interrupted after this time and gets the `Timeout` status. diff --git a/content/documentation/admin/processes/overview.ru.md b/content/documentation/admin/processes/overview.ru.md index 1329eb99..68848a13 100644 --- a/content/documentation/admin/processes/overview.ru.md +++ b/content/documentation/admin/processes/overview.ru.md @@ -8,6 +8,8 @@ description: Создание и запуск процессов — элеме ## Основные концепции +В этом разделе описаны основные составляющие процесса. + ### Элементы процесса Процесс состоит из различных типов элементов: @@ -26,6 +28,8 @@ description: Создание и запуск процессов — элеме ## Создание процесса +Процесс создаётся и настраивается в редакторе процессов. + ### Основная информация Для создания процесса перейдите в раздел «Самообслуживание» → «Процессы» и нажмите кнопку «Создать». @@ -34,7 +38,10 @@ description: Создание и запуск процессов — элеме * «Название» — название процесса, от 3 до 64 символов. * «Описание» — подробное описание назначения процесса. -* «Ресурс» — один или несколько ресурсов, для сущностей которых может запускаться процесс. Процесс без ресурсов не запускается. Запуск для сущности другого ресурса, в том числе через API и MCP-сервер портала, отклоняется с ошибкой `422`. [Автоматизацию](../../automations/#выполнение) с процессом, не привязанным к ресурсам, для сущностей которых она его запускает, сохранить нельзя, а [автоматическое обновление из шаблона](../../templates/updates/#автоматическое-обновление) пропускает микросервисы, к ресурсу которых процесс обновления не привязан. +* «Ресурс» — один или несколько ресурсов, для сущностей которых может запускаться процесс. + Процесс без ресурсов не запускается. + Запуск для сущности другого ресурса, в том числе через API и MCP-сервер портала, отклоняется с ошибкой `422`. + [Автоматизацию](../../automations/#выполнение) с процессом, не привязанным к ресурсам, для сущностей которых она его запускает, сохранить нельзя, а [автоматическое обновление из шаблона](../../templates/updates/#автоматическое-обновление) пропускает микросервисы, к ресурсу которых процесс обновления не привязан. * «Владелец» — пользователь, ответственный за процесс. * «Команда-владелец» — команда, ответственная за процесс. * «Теги» — теги для категоризации процесса. @@ -45,59 +52,98 @@ description: Создание и запуск процессов — элеме Настройка процесса происходит в визуальном редакторе на вкладке «Конфигурация». {{< alert level="info" >}} -Вкладки «Конфигурация» и «Параметры» доступны уже при создании процесса. Схема нового процесса начинается со связанных элементов «Начало» и «Конец»: процесс сохраняется только со связной схемой. +Вкладки «Конфигурация» и «Параметры» доступны уже при создании процесса. +Схема нового процесса начинается со связанных элементов «Начало» и «Конец»: процесс сохраняется только со связной схемой. {{< /alert >}} #### Добавление элементов Чтобы добавить элементы на схему: -1. Добавьте элемент, выбрав его тип на панели редактора. Элементы сгруппированы на панели по назначению: «Поток» («Начало», «Конец», «Ошибка»), «Работа» («Задача», «AI-агент», «Шаблон»), «Ветвление» (шлюзы), «Время» («Таймер», «Цикл») и «Разметка» («Примечание»). +1. Добавьте элемент, выбрав его тип на панели редактора. + Элементы сгруппированы на панели по назначению: «Поток» («Начало», «Конец», «Ошибка»), «Работа» («Задача», «AI-агент», «Шаблон»), «Ветвление» (шлюзы), «Время» («Таймер», «Цикл») и «Разметка» («Примечание»). 1. Настройте параметры элемента в боковой панели (действие, условия и др.). 1. Свяжите элементы друг с другом. -#### Типы элементов +### Параметры процесса + +На вкладке «Параметры» настраиваются параметры процесса, которые могут использоваться во всех действиях процесса. + +Конфигурация и использование параметров процесса описаны в разделе [«Шаблонизация»](../../user/templating/#параметры-процесса). + +### Хранилище процесса + +Хранилище процесса — JSON-объект для передачи данных между шагами одного запуска: идентификаторы, массивы, промежуточные результаты и тексты из элемента «Шаблон». + +Полное описание правил записи, операций, контекста цикла и примеров сценариев — в разделе [«Хранилище процесса»](store/). + +Кратко: + +- **Одно хранилище на запуск** — у каждого экземпляра процесса своё хранилище; его можно просмотреть на вкладке «Хранилище» при визуализации запуска. +- **Вложенные пути** — ключи задаются через точку: `notification.module_name`, `ctx.job.id`; поддерживаются индексы массивов: `items[0].status`. +- **Запись по правилам** — данные попадают в хранилище после успешного выполнения действия или при проходе элементов «Шаблон» и «AI-агент». + Доступны операции записи строки и JSON, добавления, слияния и удаления, а также условие на каждое правило. + Настройка правил в действии описана в разделе [«Обновление хранилища процесса»](../../actions/overview/#обновление-хранилища-процесса). +- **Чтение** — Go-шаблоны `{{ .store. }}` в конфигурации действий и условиях шлюзов. + Синтаксис описан в разделе [«Хранилище процесса»](../../user/templating/#хранилище-процесса) страницы «Шаблонизация». -##### Задача +Если ключа нет в хранилище, шаблон `{{ .store. }}` завершит шаг с ошибкой. + +## Типы элементов + +Схема процесса строится из элементов следующих типов. + +### Задача Каждая задача — это запуск конкретного действия, созданного ранее в разделе «Самообслуживание» → «Действия». Если действие требует согласования, согласование запрашивается при каждом выполнении задачи: на каждой итерации цикла и после перезапуска процесса. -Поле «Таймаут (секунды)» задаёт, сколько ждать завершения действия. Если поле не заполнено, ожидание длится 60 минут. По истечении действие отменяется, а задача получает статус `Timeout`. +Поле «Таймаут (секунды)» задаёт, сколько ждать завершения действия. +Если поле не заполнено, ожидание длится 60 минут. +По истечении действие отменяется, а задача получает статус `Timeout`. -Если действие не запустилось из-за [условий выполнения](../../actions/overview/#условия-выполнения), задача получает статус `Declined` и обрабатывается так же, как задача, завершившаяся ошибкой: если из неё выходит связь к эксклюзивному шлюзу или связь с условием, процесс продолжается по исходящим связям, иначе ветка процесса на этой задаче завершается. +Если действие не запустилось из-за [условий выполнения](../../actions/overview/#условия-выполнения), задача получает статус `Declined` и обрабатывается так же, как задача, завершившаяся ошибкой. +Если из неё выходит связь к эксклюзивному шлюзу или связь с условием, процесс продолжается по исходящим связям, иначе ветка процесса на этой задаче завершается. Если пользователь отменил действие задачи, ветка процесса на этой задаче завершается без перехода по исходящим связям, а отмена учитывается в [итоговом статусе процесса](#статусы-процесса). -##### AI-агент +### AI-агент Элемент «AI-агент» отправляет задачу [AI-агенту](../ai-agents/overview/), ждёт завершения его запуска и записывает результат в хранилище процесса. Агент выполняется воркерами портала от имени пользователя, который запустил процесс. -Поле «Таймаут (секунды)» задаёт, сколько ждать завершения запуска агента. Если поле не заполнено, ожидание длится 60 минут. По истечении запуск агента прерывается, а шаг получает статус `Timeout`. +Поле «Таймаут (секунды)» задаёт, сколько ждать завершения запуска агента. +Если поле не заполнено, ожидание длится 60 минут. +По истечении запуск агента прерывается, а шаг получает статус `Timeout`. -Если агент недоступен в момент запуска шага, например локальный агент не отвечает, запуск агента сразу завершается ошибкой, а шаг обрабатывается как при [ошибке агента](#ошибка-агента). Чтобы выполнить шаг снова, перезапустите процесс. +Если агент недоступен в момент запуска шага, например локальный агент не отвечает, запуск агента сразу завершается ошибкой, а шаг обрабатывается как при [ошибке агента](#ошибка-агента). +Чтобы выполнить шаг снова, перезапустите процесс. В конфигурации элемента задаются поля: -| Поле | Обязательность | Описание | +| Название | Обязательность | Описание | | --- | --- | --- | | «Исполнитель» | Да | «Агент» из каталога или «Рабочее пространство» | | «Рабочее пространство» | Для исполнителя «Рабочее пространство» | UUID пространства или Go-шаблон, например `{{ .process.workspace_uuid }}` | | «Агент» | Для исполнителя «Агент» | Идентификатор агента. Можно указать Go-шаблон, например `{{ .process.agent_slug }}` | | «Сообщение агенту» | Да | Go-шаблон сообщения, которое получает агент. Доступны корни `.process`, `.store` и `.context` | | «Ключ результата в хранилище» | Да | Dot-path хранилища процесса, по которому записывается результат, например `agent_result` или `analysis.plan`. По умолчанию — `agent_result` | -| «AI-провайдер» | Для агентов, которым модель предоставляет портал | Название AI-провайдера. Обязателен для платформенного агента и внешних агентов с разрешённым прокси моделей DDP | +| «AI-провайдер» | Для агентов, которым модель предоставляет портал | Название AI-провайдера. Обязателен для платформенного агента и внешних агентов с разрешённым прокси моделей Deckhouse Development Portal (DDP) | -AI-провайдер ищется по названию среди провайдеров пользователя, который запустил процесс: провайдер из шаблона с общим токеном подходит всем, кому разрешён шаблон, а личный провайдер — только его владельцу. -Если провайдер не задан в элементе, его можно выбрать при запуске процесса. Без провайдера процесс не запускается и возвращает ошибку «Укажите AI-провайдера на каждом локальном agent-шаге перед запуском процесса». +AI-провайдер ищется по названию среди провайдеров пользователя, который запустил процесс. +Провайдер из шаблона с общим токеном подходит всем, кому разрешён шаблон, а личный провайдер — только его владельцу. +Если провайдер не задан в элементе, его можно выбрать при запуске процесса. +Без провайдера процесс не запускается и возвращает ошибку «Укажите AI-провайдера на каждом локальном agent-шаге перед запуском процесса». -Агент получает инструменты назначенных ему MCP-коллекций, которыми может пользоваться инициатор процесса. Без коллекций агент работает без MCP-инструментов. Для запуска требуется право `use:ai-agents` или `use:ai-agent` на выбранного агента. +Агент получает инструменты назначенных ему MCP-коллекций, которыми может пользоваться инициатор процесса. +Без коллекций агент работает без MCP-инструментов. +Для запуска требуется право `use:ai-agents` или `use:ai-agent` на выбранного агента. -В поле «Исполнитель» можно также выбрать «Рабочее пространство». В этом режиме шаг отправляет задание в прикреплённый чат пространства инициатора, привязанного к сущности процесса. +В поле «Исполнитель» можно также выбрать «Рабочее пространство». +В этом режиме шаг отправляет задание в прикреплённый чат пространства инициатора, привязанного к сущности процесса. -###### Результат агента +#### Результат агента После завершения запуска агента портал записывает в хранилище по ключу из поля «Ключ результата в хранилище» объект: @@ -115,106 +161,125 @@ AI-провайдер ищется по названию среди провай Поле `status` принимает значения `succeeded`, `failed` или `cancelled`; при ошибке добавляется поле `error` с текстом ошибки. Если ключ уже есть в хранилище, его значение перезаписывается. -Последующие элементы получают ответ агента через хранилище, например `{{ .store.agent_result.answer }}`. Ключ с точкой записывается вложенным объектом: результат по ключу `analysis.plan` читается как `{{ .store.analysis.plan.answer }}`. +Последующие элементы получают ответ агента через хранилище, например `{{ .store.agent_result.answer }}`. +Ключ с точкой записывается вложенным объектом. +Например, результат по ключу `analysis.plan` читается как `{{ .store.analysis.plan.answer }}`. -###### Ошибка агента +#### Ошибка агента -Если запуск агента завершился ошибкой, поведение зависит от связей элемента: - -- если из элемента выходит связь к эксклюзивному шлюзу или связь с условием, портал записывает результат с полями `status` и `error` в хранилище и продолжает процесс по исходящим связям. Чтобы направить процесс по ветке обработки ошибки, проверьте в шлюзе условие `{{ eq .store.agent_result.status "succeeded" }}`; -- иначе ветка процесса на этом элементе завершается, а ошибка учитывается в итоговом статусе процесса. +Если запуск агента завершился ошибкой, поведение зависит от связей элемента. +Если из элемента выходит связь к эксклюзивному шлюзу или связь с условием, портал записывает результат с полями `status` и `error` в хранилище и продолжает процесс по исходящим связям. +Чтобы направить процесс по ветке обработки ошибки, проверьте в шлюзе условие `{{ eq .store.agent_result.status "succeeded" }}`. +В остальных случаях ветка процесса на этом элементе завершается, а ошибка учитывается в итоговом статусе процесса. Если пользователь остановил запуск агента, ветка процесса на этом элементе завершается без перехода по исходящим связям, а отмена учитывается в [итоговом статусе процесса](#статусы-процесса). -Если запуск агента не удалось создать, например шаблон поля «Сообщение агенту» ссылается на ключ, которого нет в хранилище, шаг завершается так же, со статусом `Failed`. Причина ошибки отображается на вкладке «Лог выполнения» боковой панели шага. +Если запуск агента не удалось создать, например шаблон поля «Сообщение агенту» ссылается на ключ, которого нет в хранилище, шаг завершается так же, со статусом `Failed`. +Причина ошибки отображается на вкладке «Лог выполнения» боковой панели шага. -Если запуск агента завершился успешно, но результат нельзя записать по пути из поля «Ключ результата в хранилище», шаг завершается со статусом `Failed`, а процесс по исходящим связям не продолжается. Запись невозможна, когда путь проходит через значение, которое не является объектом, например ключ `catalog.status.answer`, когда в `catalog.status` записана строка. +Если запуск агента завершился успешно, но результат нельзя записать по пути из поля «Ключ результата в хранилище», шаг завершается со статусом `Failed`, а процесс по исходящим связям не продолжается. +Запись невозможна, когда путь проходит через значение, которое не является объектом, например ключ `catalog.status.answer`, когда в `catalog.status` записана строка. -###### Повторное выполнение +#### Повторное выполнение При каждом повторном прохождении элемента, например на новой итерации цикла, портал создаёт новый запуск агента. Запуски агента отображаются в [истории запусков](../ai-agents/runs/) с триггером «Процесс», а ответ агента и вызовы инструментов — в боковой панели элемента на схеме запуска. -##### Эксклюзивный шлюз +### Эксклюзивный шлюз -Эксклюзивный шлюз позволяет настраивать ветвление процесса по условиям. По умолчанию проверяется статус предыдущей задачи, и в зависимости от него выполнение идёт по «успешной» или «неуспешной» ветке. +Эксклюзивный шлюз позволяет настраивать ветвление процесса по условиям. +По умолчанию проверяется статус предыдущей задачи, и в зависимости от него выполнение идёт по «успешной» или «неуспешной» ветке. В качестве условий для эксклюзивного шлюза можно задать либо проверку статуса предыдущей задачи, либо сравнение значений из шаблонов: -- Для проверки статуса предыдущей задачи используйте конструкцию `{{ .prev_task.status }}`. Если в шлюз ведут несколько элементов, проверяется статус того, после которого процесс дошёл до шлюза. -- Для проверки значения из хранилища — `{{ .store.<путь> }}`, в том числе вложенные ключи: `{{ .store.notification.status }}`. +- Для проверки статуса предыдущей задачи используйте конструкцию `{{ .prev_task.status }}`. + Если в шлюз ведут несколько элементов, проверяется статус того, после которого процесс дошёл до шлюза. +- Для проверки значения из хранилища — `{{ .store. }}`, в том числе вложенные ключи: `{{ .store.notification.status }}`. - Внутри цикла — поля текущего элемента: `{{ .store._loop.item.scan_type }}`, флаги `{{ .store._loop.first }}` и `{{ .store._loop.last }}`. Доступна проверка нескольких условий с комбинацией их результатов через оператор `AND` или `OR`. Операции условий: -- `exists` и `not exists` проверяют, есть ли ключ, который читает левая часть условия. Ключ с пустым значением существует. +- `exists` и `not exists` проверяют, есть ли ключ, который читает левая часть условия. + Ключ с пустым значением существует. - `empty` и `not empty` проверяют, пусто ли значение левой части. Отсутствующий ключ считается пустым. - Для типа `Number` операции `==` и `!=` сравнивают значения как числа: `42.0` равно `42`. Процесс с условием, операция которого не поддерживается, например заданным через API, не сохраняется. -Если проверка условий выполняется, процесс идёт по ветке «Истина» (зелёная); если нет — по ветке «Ложь» (красная). Порты «Истина» и «Ложь» можно размещать на любой стороне шлюза; связь можно перенести на другой порт. +Если проверка условий выполняется, процесс идёт по ветке «Истина» (зелёная); если нет — по ветке «Ложь» (красная). +Порты «Истина» и «Ложь» можно размещать на любой стороне шлюза; связь можно перенести на другой порт. -##### Параллельный шлюз +### Параллельный шлюз Применяется для объединения нескольких веток в одну по заданным условиям. -В конфигурации параллельного шлюза можно настроить параметры ожидания: - -- Ожидать выполнения всех входящих элементов для продолжения выполнения. -- Ожидать выполнения как минимум одного входящего элемента для продолжения выполнения. - -При этом можно настроить, что именно считать «выполнением»: +В конфигурации параллельного шлюза можно выбрать, ожидать ли выполнения всех входящих элементов или как минимум одного входящего элемента для продолжения выполнения. -- Только успешное завершение входящих в шлюз задач. -- Переход входящих задач в любой финальный статус (`Failed`, `Declined`, `Canceled`, `Skipped` и т. д.). +При этом можно настроить, что именно считать «выполнением»: только успешное завершение входящих в шлюз задач +или переход входящих задач в любой финальный статус (`Failed`, `Declined`, `Canceled`, `Skipped` и т. д.). При ожидании только успешного завершения входящая задача, которая завершилась ошибкой, отклонена или отменена пользователем, сразу завершает шлюз ошибкой. -Если шлюз ожидает хотя бы один входящий элемент, остальные входящие ветки продолжают выполняться. Запуск завершается после того, как они дойдут до конца. +Если шлюз ожидает хотя бы один входящий элемент, остальные входящие ветки продолжают выполняться. +Запуск завершается после того, как они дойдут до конца. -Поле «Таймаут (секунды)» задаёт, сколько ждать завершения входящих веток. Если поле не заполнено, ожидание длится 60 минут. По истечении шлюз получает статус `Timeout`. Тайм-аут отсчитывается от прихода первой ветки и не начинается заново после перезапуска портала. +Поле «Таймаут (секунды)» задаёт, сколько ждать завершения входящих веток. +Если поле не заполнено, ожидание длится 60 минут. +По истечении шлюз получает статус `Timeout`. +Тайм-аут отсчитывается от прихода первой ветки и не начинается заново после перезапуска портала. -Если шлюз завершился ошибкой — по тайм-ауту или потому, что входящая задача завершилась ошибкой, отклонена или отменена при ожидании только успешного завершения, — входящие в него ветки отменяются вместе с действиями и запусками AI-агентов. Остальные ветки процесса продолжают выполняться. +Если шлюз завершился ошибкой — по тайм-ауту или потому, что входящая задача завершилась ошибкой, отклонена или отменена при ожидании только успешного завершения, — входящие в него ветки отменяются вместе с действиями и запусками AI-агентов. +Остальные ветки процесса продолжают выполняться. -Параллельные ветки должны сходиться только в параллельном шлюзе. Если ветки не объединяются, у каждой из них должен быть свой элемент «Конец». Параллельно выполняются ветки параллельного шлюза и все исходящие связи любого другого элемента, кроме эксклюзивного шлюза и цикла. Процесс не сохраняется, если: - -- параллельные ветки сходятся в элементе, который не является параллельным шлюзом; -- у элемента, кроме «Начало», «Конец», «Ошибка» и «Примечание», нет исходящих связей. +Параллельные ветки должны сходиться только в параллельном шлюзе. +Если ветки не объединяются, у каждой из них должен быть свой элемент «Конец». +Параллельно выполняются ветки параллельного шлюза и все исходящие связи любого другого элемента, кроме эксклюзивного шлюза и цикла. +Процесс не сохраняется, если параллельные ветки сходятся в элементе, который не является параллельным шлюзом, +или у элемента, кроме «Начало», «Конец», «Ошибка» и «Примечание», нет исходящих связей. Ветки эксклюзивного шлюза могут вести к общему элементу, параллельные ветки — к общему элементу «Ошибка». -При сохранении портал также проверяет связность схемы: путь от элемента «Начало» до элемента «Конец», связи циклов и таймеров, настройки элементов «Цикл», «Таймер», «Шаблон» и «AI-агент», например число итераций и часовой пояс. Процесс с ошибкой в схеме не сохраняется, причина указывается в сообщении об ошибке. Запуск процесса, сохранённого с такой ошибкой ранее, отклоняется с той же причиной; сохранить такой процесс можно, только исправив схему. +При сохранении портал также проверяет связность схемы: путь от элемента «Начало» до элемента «Конец», связи циклов и таймеров, настройки элементов «Цикл», «Таймер», «Шаблон» и «AI-агент», например число итераций и часовой пояс. +Процесс с ошибкой в схеме не сохраняется, причина указывается в сообщении об ошибке. +Запуск процесса, сохранённого с такой ошибкой ранее, отклоняется с той же причиной; сохранить такой процесс можно, только исправив схему. Параллельный шлюз также может использоваться для разделения веток, если подключается после элементов «Эксклюзивный шлюз» или «Цикл», либо в качестве вспомогательного элемента для повышения читаемости схемы процесса. -###### Объединение веток в цикле +#### Объединение веток в цикле -Если параллельный шлюз объединяет ветки внутри цикла или на пути возврата по обратной связи, на каждом прохождении шлюз учитывает только ветки, завершившиеся на этом прохождении. Завершение ветки на предыдущей итерации не засчитывается. +Если параллельный шлюз объединяет ветки внутри цикла или на пути возврата по обратной связи, на каждом прохождении шлюз учитывает только ветки, завершившиеся на этом прохождении. +Завершение ветки на предыдущей итерации не засчитывается. Поэтому каждая ветка, входящая в шлюз, должна доходить до него на каждом прохождении. -Если ветка не дошла до шлюза за тайм-аут элемента (по умолчанию 60 минут), шлюз завершается ошибкой `ParallelGateway Join timed out` со списком незавершённых веток. Тайм-аут отсчитывается от начала текущего прохождения. +Если ветка не дошла до шлюза за тайм-аут элемента (по умолчанию 60 минут), шлюз завершается ошибкой `ParallelGateway Join timed out` со списком незавершённых веток. +Тайм-аут отсчитывается от начала текущего прохождения. Условия эксклюзивного шлюза `tasksCompleted` и `tasksCompletedAny` проверяют, завершалась ли задача хотя бы раз за весь запуск процесса, а не только на текущем прохождении. -##### Цикл +### Цикл + +Элемент «Цикл» повторяет ветку процесса либо фиксированное число раз, либо по каждому элементу JSON-массива из хранилища. +После завершения всех итераций активируется элемент, подключённый к выходу из цикла. -Элемент «Цикл» повторяет ветку процесса либо фиксированное число раз, либо по каждому элементу JSON-массива из хранилища. После завершения всех итераций активируется элемент, подключённый к выходу из цикла. +#### Режим цикла -###### Режим цикла +Доступны два режима. -Доступны два режима: +В режиме «Фиксированное число» задайте «Количество итераций» от 1 до 10000. +На каждой итерации в `{{ .store._loop.item }}` доступен номер итерации (1, 2, 3…). -- «Фиксированное число» — поле «Количество итераций» от 1 до 10000. На каждой итерации в `{{ .store._loop.item }}` доступен номер итерации (1, 2, 3…). -- «По коллекции» — поле «Шаблон коллекции»: Go-шаблон, который при входе в цикл должен дать JSON-массив. Обычно указывают путь к массиву, записанному предыдущей задачей: `{{ .store.notification.engagements }}`. Каждый элемент массива — одна итерация; текущий элемент доступен как `{{ .store._loop.item }}`. Массив может содержать до 10 000 элементов; массив большего размера завершает цикл с ошибкой. +В режиме «По коллекции» задайте «Шаблон коллекции» — Go-шаблон, который при входе в цикл должен дать JSON-массив. +Обычно указывают путь к массиву, записанному предыдущей задачей: `{{ .store.notification.engagements }}`. +Каждый элемент массива — одна итерация; текущий элемент доступен как `{{ .store._loop.item }}`. +Массив может содержать до 10 000 элементов; массив большего размера завершает цикл с ошибкой. Если массив пуст или ключ отсутствует, тело цикла не выполняется, процесс сразу переходит по связи «Выход из цикла». Подробнее — в разделе [«Хранилище процесса»](store/#цикл-по-коллекции-из-хранилища). -###### Исходящие связи +#### Исходящие связи Из элемента «Цикл» должны выходить ровно две связи к разным элементам: @@ -223,7 +288,7 @@ AI-провайдер ищется по названию среди провай Порты «Тело цикла» и «Выход из цикла» можно размещать на любой стороне элемента; связь можно перенести на другой порт. -###### Использование +#### Использование Типовые сценарии: @@ -231,54 +296,61 @@ AI-провайдер ищется по названию среди провай - обход списка объектов из ответа API: задача записывает массив в хранилище, цикл в режиме «По коллекции» обрабатывает каждый элемент; - вложенные циклы — контекст родителя доступен через `{{ .store._loop.parent }}`. -##### Шаблон +### Шаблон Элемент «Шаблон» вычисляет Go-шаблон без дополнительного вызова действия и записывает результат в хранилище как строку. Настройте: - «Тело шаблона» — текст с плейсхолдерами `{{ .store.* }}`, `{{ .process.* }}`, внутри цикла — `{{ .store._loop.* }}`; -- «Ключ в хранилище» — dot-path назначения, например `rendered_message` или `notification.summary`. Ключ с точкой записывается вложенным объектом и читается как `{{ .store.notification.summary }}`; +- «Ключ в хранилище» — dot-path назначения, например `rendered_message` или `notification.summary`. + Ключ с точкой записывается вложенным объектом и читается как `{{ .store.notification.summary }}`; - «Подсказка формата» — как отображать значение при просмотре запуска (`text`, `markdown`, `html`, `json`); не влияет на содержимое хранилища. Если шаблон не удалось вычислить или результат нельзя записать по пути из поля «Ключ в хранилище», элемент получает статус `Failed`, а процесс завершается с ошибкой. Примеры и ограничения — в разделе [«Хранилище процесса»](store/#элемент-шаблон). -##### Таймер +### Таймер Элемент «Таймер» приостанавливает выполнение процесса до наступления заданного момента времени, после чего активируется следующий элемент. -Пока процесс ожидает только срабатывания таймера (других активных задач нет), запуск переводится в статус `Wait`. Параллельный шлюз, который ждёт только ветки с ожидающими таймерами, тоже не держит запуск в статусе `Running`. На панели визуализации запуска отображается баннер «Ожидание по таймеру — не ранее {ends} ({remaining})» с ориентировочным временем возобновления. +Пока процесс ожидает только срабатывания таймера (других активных задач нет), запуск переводится в статус `Wait`. +Параллельный шлюз, который ждёт только ветки с ожидающими таймерами, тоже не держит запуск в статусе `Running`. +На панели визуализации запуска отображается баннер «Ожидание по таймеру — не ранее {ends} ({remaining})» с ориентировочным временем возобновления. -###### Исходящие связи +#### Исходящие связи -От элемента «Таймер» должна исходить ровно одна связь к следующему элементу. Подключение возможно только через левый (вход) и правый (выход) порты. +От элемента «Таймер» должна исходить ровно одна связь к следующему элементу. +Подключение возможно только через левый (вход) и правый (выход) порты. При повторном прохождении таймера в том же запуске (например, через цикл) момент срабатывания рассчитывается заново. -###### Режимы расписания - -В конфигурации таймера выберите «Расписание»: +#### Режимы расписания -- «Задержка после входа в элемент» — фиксированная пауза с момента, когда процесс дошёл до таймера. Задайте «Задержка (секунды)» от 1 до 1 209 600 (14 суток). -- «Произвольное расписание» — срабатывание в заданное время по календарю в выбранном часовом поясе (IANA, например `Europe/Moscow`). +В конфигурации таймера выберите «Расписание». +Вариант «Задержка после входа в элемент» задаёт фиксированную паузу с момента, когда процесс дошёл до таймера. +Задайте «Задержка (секунды)» от 1 до 1 209 600 (14 суток). +Вариант «Произвольное расписание» запускает таймер в заданное время по календарю в выбранном часовом поясе (IANA, например `Europe/Moscow`). Для режима «Произвольное расписание» укажите «Шаблон»: - «Определённый день недели» — «День недели», «Время суток» (час и минута), «Часовой пояс». -- «Определённое число каждого месяца» — «Число месяца» (1–31), «Время суток», «Часовой пояс». Если в месяце нет такого числа, используется последний день месяца. -- «Каждые N дней» — «Каждые N дней» (1–365), «Время суток», «Часовой пояс». Первое срабатывание — не ранее чем через N календарных дней от дня, когда процесс дошёл до таймера; при повторном входе в элемент расчёт выполняется снова. +- «Определённое число каждого месяца» — «Число месяца» (1–31), «Время суток», «Часовой пояс». + Если в месяце нет такого числа, используется последний день месяца. +- «Каждые N дней» — «Каждые N дней» (1–365), «Время суток», «Часовой пояс». + Первое срабатывание — не ранее чем через N календарных дней от дня, когда процесс дошёл до таймера; при повторном входе в элемент расчёт выполняется снова. «Время суток» задаётся в выбранном часовом поясе (поле «Часовой пояс»), если он отличается от пояса браузера. -###### Использование +#### Использование Типовые сценарии: пауза перед повторной проверкой статуса внешней системы, отложенный запуск следующего шага, ожидание окна обслуживания или регулярного слота по календарю. -##### Примечание +### Примечание -Элемент «Примечание» предназначен для текстовых пояснений на схеме процесса: он не выполняется при запуске и не соединяется с другими элементами. +Элемент «Примечание» предназначен для текстовых пояснений на схеме процесса. +Он не выполняется при запуске и не соединяется с другими элементами. В конфигурации примечания можно задать: @@ -286,113 +358,123 @@ AI-провайдер ищется по названию среди провай - «Цвет фона» — цвет заливки фона. - «Цвет текста» — цвет текста. -Примечание всегда позиционируется за остальными элементами и может использоваться для визуального выделения частей процесса. Также это единственный элемент, размер которого можно изменить. +Примечание всегда позиционируется за остальными элементами и может использоваться для визуального выделения частей процесса. +Также это единственный элемент, размер которого можно изменить. -##### Ошибка +### Ошибка -Элемент «Ошибка» принудительно переводит запущенный процесс в статус `Failed`: при достижении этого элемента выполнение всех действий процесса прерывается. +Элемент «Ошибка» принудительно переводит запущенный процесс в статус `Failed`. +При достижении этого элемента выполнение всех действий процесса прерывается. От элемента не должно исходить связей к следующим элементам. -### Параметры процесса - -На вкладке «Параметры» настраиваются параметры процесса, которые могут использоваться во всех действиях процесса. - -Конфигурация и использование параметров процесса описаны в разделе [«Шаблонизация»](../../user/templating/#параметры-процесса). - -### Хранилище процесса - -Хранилище процесса — JSON-объект для передачи данных между шагами одного запуска: идентификаторы, массивы, промежуточные результаты и тексты из элемента «Шаблон». - -Полное описание правил записи, операций, контекста цикла и примеров сценариев — в разделе [«Хранилище процесса»](store/). - -Кратко: - -- **Одно хранилище на запуск** — у каждого экземпляра процесса своё хранилище; его можно просмотреть на вкладке «Хранилище» при визуализации запуска. -- **Вложенные пути** — ключи задаются через точку: `notification.module_name`, `ctx.job.id`; поддерживаются индексы массивов: `items[0].status`. -- **Запись по правилам** — данные попадают в хранилище после успешного выполнения действия или при проходе элементов «Шаблон» и «AI-агент». Доступны операции записи строки и JSON, добавления, слияния и удаления, а также условие на каждое правило. Настройка правил в действии описана в разделе [«Обновление хранилища процесса»](../../actions/overview/#обновление-хранилища-процесса). -- **Чтение** — Go-шаблоны `{{ .store.<путь> }}` в конфигурации действий и условиях шлюзов. Синтаксис описан в разделе [«Хранилище процесса»](../../user/templating/#хранилище-процесса) страницы «Шаблонизация». - -Если ключа нет в хранилище, шаблон `{{ .store.<путь> }}` завершит шаг с ошибкой. - ## Запуск процесса +Процесс можно запустить вручную или с помощью автоматизации. + ### Ручной запуск Чтобы запустить процесс вручную: -1. Перейдите к сущности, для которой нужно запустить процесс. +1. Перейдите к сущности, для которой запускается процесс. 1. В меню сущности выберите «Запустить процесс» или нажмите «Запустить» рядом с нужным процессом в одном из блоков: «Запуск» на вкладке «Обзор» или «Что можно запустить» на вкладке «Процессы». 1. Выберите процесс в списке. Если доступен один процесс, он выбран автоматически и список не отображается. 1. Заполните параметры процесса. 1. Нажмите «Запустить». -После запуска отображается уведомление «Процесс "{name}" запущен». +После запуска отображается уведомление «Процесс „{name}“ запущен». ### Параметры запуска -Окно «Запустить процесс» открывается в упрощённом режиме. В нём отображаются только параметры процесса с признаком [«Показывать в упрощённой форме»](../../user/properties/#конфигурация) и обязательные параметры, у которых нет значения. Остальные параметры сохраняют значения по умолчанию и передаются при запуске. +Окно «Запустить процесс» открывается в упрощённом режиме. +В нём отображаются только параметры процесса с признаком [«Показывать в упрощённой форме»](../../user/properties/#конфигурация) и обязательные параметры, у которых нет значения. +Остальные параметры сохраняют значения по умолчанию и передаются при запуске. -Над параметрами отображается подсказка «Показаны важные параметры: {important} из {total}». Если важных параметров нет, отображается «Важных параметров нет», а если заполнять ничего не нужно — сообщение «Для запуска этого процесса не нужно заполнять параметры — нажмите «Запустить»». +Над параметрами отображается подсказка «Показаны важные параметры: {important} из {total}». +Если важных параметров нет, отображается «Важных параметров нет», а если заполнять параметры не требуется — сообщение «Для запуска этого процесса не нужно заполнять параметры — нажмите «Запустить»». -Кнопка «Все параметры процесса» переключает окно в полный режим, кнопка «Только важные параметры» — обратно. В полном режиме доступны разделы: +Кнопка «Все параметры процесса» переключает окно в полный режим, кнопка «Только важные параметры» — обратно. +В полном режиме доступны разделы: * «Общие параметры процесса» — параметры, определённые в конфигурации процесса; * «Командные параметры процесса» — команда, переменные которой используются при выполнении; -* «Конфигурация» — схема процесса. Нажмите на задачу, чтобы включить или выключить её действие и заполнить его параметры. +* «Конфигурация» — схема процесса. + Нажмите на задачу, чтобы включить или выключить её действие и заполнить его параметры. Для элементов «AI-агент» и «Шаблон» на схеме доступен переключатель «Включить шаг»: если он выключен, шаг пропускается в этом запуске. -Для элементов «AI-агент», которым модель предоставляет портал, в боковой панели шага выбирается AI-провайдер для этого запуска. Если провайдер не задан ни в конфигурации, ни при запуске, отображается ошибка «На agent-шагах, где модель предоставляет DDP, укажите AI-провайдера (клик по шагу на графе справа): {steps}». +Для элементов «AI-агент», которым модель предоставляет портал, в боковой панели шага выбирается AI-провайдер для этого запуска. +Если провайдер не задан ни в конфигурации, ни при запуске, отображается ошибка «На agent-шагах, где модель предоставляет DDP, укажите AI-провайдера (клик по шагу на графе справа): {steps}». Описание процесса отображается под заголовком в сокращённом виде; ссылка «подробнее» раскрывает его полностью. -Запуск выполняется по схеме процесса на момент запуска: изменение процесса не влияет на уже идущие запуски, их возобновление и перезапуск. Новая схема применяется к следующим запускам. +Запуск выполняется по схеме процесса на момент запуска. +Изменение процесса не влияет на уже идущие запуски, их возобновление и перезапуск. +Новая схема применяется к следующим запускам. -Если обязательный параметр процесса не заполнен, при нажатии «Запустить» отображается ошибка «Заполните все обязательные параметры процесса». Если не заполнено обязательное поле включённой задачи, окно переключается в полный режим с ошибкой «Заполните все обязательные поля для всех включённых задач». +Если обязательный параметр процесса не заполнен, при нажатии «Запустить» отображается ошибка «Заполните все обязательные параметры процесса». +Если не заполнено обязательное поле включённой задачи, окно переключается в полный режим с ошибкой «Заполните все обязательные поля для всех включённых задач». ### Контекст запуска -Контекст запуска — значения, которые раздел портала передаёт процессу при запуске, например окружение и система, выбранные на главной. Пользователь контекст не вводит, и в конфигурации процесса он не хранится. +Контекст запуска — значения, которые раздел портала передаёт процессу при запуске, например окружение и система, выбранные на главной странице. +Пользователь контекст не вводит, и в конфигурации процесса он не хранится. -В шаблонах процесса контекст доступен через корень `.context`, например `{{ .context.environment.slug }}`. Процесс, запущенный из каталога, получает пустой контекст. +В шаблонах процесса контекст доступен через корень `.context`, например `{{ .context.environment.slug }}`. +Процесс, запущенный из каталога, получает пустой контекст. -Состав контекста для каждого сценария главной описан в разделе [«Процессы главной»](../home/processes/#сущность-и-контекст-по-сценариям). +Состав контекста для каждого сценария главной страницы описан в разделе [«Процессы главной страницы»](../home/processes/#сущность-и-контекст-по-сценариям). -Процессы развёртывания и удаления микросервиса из набора данных реестра шаблонов требуют контекст запуска. Без контекста такой процесс не запускается и возвращает ошибку «Этот процесс требует контекст запуска и не может быть запущен напрямую». +Процессы развёртывания и удаления микросервиса из набора данных реестра шаблонов требуют контекст запуска. +Без контекста такой процесс не запускается и возвращает ошибку «Этот процесс требует контекст запуска и не может быть запущен напрямую». На странице сущности такие процессы отображаются, только если для сущности найдено окружение, в котором она развёрнута; при запуске в окне выбирается «Окружение». ## Управление выполнением +Во время выполнения процесса можно отслеживать его состояние и управлять выполнением. + ### Статусы процесса Статус запуска отображается одним из следующих значений: * `Running` — процесс выполняется. * `Wait` — процесс ожидает только срабатывания таймера, в том числе когда параллельный шлюз ждёт только ветки с ожидающими таймерами. -* `Unapproved` — в процессе не осталось другой работы, кроме задач, ожидающих согласования действия. Пока в соседней ветке выполняется шаг «AI-агент» или ожидает таймер, запуск остаётся в статусе `Running` или `Wait`. +* `Unapproved` — в процессе не осталось другой работы, кроме задач, ожидающих согласования действия. + Пока в соседней ветке выполняется шаг «AI-агент» или ожидает таймер, запуск остаётся в статусе `Running` или `Wait`. * `Paused` — выполнение процесса приостановлено. * `Resuming` — запуск восстанавливается после перезапуска портала. * `Completed` — все ветки процесса завершились, процесс дошёл до элемента «Конец», и каждая ошибка обработана: после задачи или шага «AI-агент», завершившихся ошибкой, или отклонённой задачи ветку продолжил эксклюзивный шлюз или параллельный шлюз, который принимает любой финальный статус. -* `Partially Completed` — процесс дошёл хотя бы до одного элемента «Конец», но часть веток остановилась: на задаче или шаге «AI-агент», которые завершились ошибкой без обработки, на отклонённой задаче без обработки, на шаге, который отменил пользователь, или на параллельном шлюзе, который завершился ошибкой. Статус ставится, когда в запуске не осталось выполняющихся шагов: пока другая ветка работает, например ждёт согласования, запуск остаётся в статусе `Running`, `Unapproved` или `Wait`. +* `Partially Completed` — процесс дошёл хотя бы до одного элемента «Конец», но часть веток остановилась: на задаче или шаге «AI-агент», которые завершились ошибкой без обработки, на отклонённой задаче без обработки, на шаге, который отменил пользователь, или на параллельном шлюзе, который завершился ошибкой. + Статус ставится, когда в запуске не осталось выполняющихся шагов. + Пока другая ветка работает, например ждёт согласования, запуск остаётся в статусе `Running`, `Unapproved` или `Wait`. * `Failed` — процесс завершился с ошибкой: ни один элемент «Конец» не достигнут или процесс дошёл до элемента «Ошибка». -* `Canceled` — пользователь остановил или отменил запуск. Этот же статус получает запуск, который не дошёл ни до одного элемента «Конец», если его ветки остановились только на шагах, отменённых пользователем. +* `Canceled` — пользователь остановил или отменил запуск. + Этот же статус получает запуск, который не дошёл ни до одного элемента «Конец», если его ветки остановились только на шагах, отменённых пользователем. ### Операции управления -Кнопки управления запуском отображаются на карточке запуска в панели «Мои активности» на вкладке «Процессы». Набор кнопок зависит от статуса запуска: +Кнопки управления запуском отображаются на карточке запуска в панели «Мои активности» на вкладке «Процессы». +Набор кнопок зависит от статуса запуска: -* «Перезапустить процесс» — запускает процесс заново с элемента «Начало» по схеме, с которой запуск начался; таймлайн запуска сохраняется, хранилище процесса очищается, согласование действий запрашивается заново. Запуск в статусе `Running`, `Wait`, `Paused`, `Resuming` или `Unapproved` перезапустить нельзя: сначала остановите его. При перезапуске останавливаются выполняющиеся запуски AI-агентов процесса. +* «Перезапустить процесс» — запускает процесс заново с элемента «Начало» по схеме, с которой запуск начался; таймлайн запуска сохраняется, хранилище процесса очищается, согласование действий запрашивается заново. + Запуск в статусе `Running`, `Wait`, `Paused`, `Resuming` или `Unapproved` перезапустить нельзя. + Сначала остановите его. + При перезапуске останавливаются выполняющиеся запуски AI-агентов процесса. * «Приостановить процесс» — приостанавливает запуск в статусе `Running`. * «Возобновить процесс» — возобновляет запуск в статусе `Paused`. * «Отменить процесс» — отменяет запуск в статусе `Running` или `Paused`. Запуск получает статус `Canceled`. -* «Остановить процесс» — останавливает запуск в другом незавершённом статусе, например `Wait` или `Unapproved`. Запуск получает статус `Canceled`. -* «Удалить процесс» — удаляет запуск в любом статусе. Незавершённый запуск сначала останавливается: его действия и запуски AI-агентов отменяются. +* «Остановить процесс» — останавливает запуск в другом незавершённом статусе, например `Wait` или `Unapproved`. + Запуск получает статус `Canceled`. +* «Удалить процесс» — удаляет запуск в любом статусе. + Незавершённый запуск сначала останавливается, а его действия и запуски AI-агентов отменяются. -Те же операции доступны в таблице «История запусков» на вкладке «Процессы» сущности. Отмена и остановка там выполняются одной кнопкой. Кнопки запуска процессов и управления запусками на этой вкладке неактивны, если у пользователя нет разрешения [`control:processes`](../security/rbac/) глобально, на ресурс сущности или на саму сущность. +Те же операции доступны в таблице «История запусков» на вкладке «Процессы» сущности. +Отмена и остановка там выполняются одной кнопкой. +Кнопки запуска процессов и управления запусками на этой вкладке неактивны, если у пользователя нет разрешения [`control:processes`](../security/rbac/) глобально, на ресурс сущности или на саму сущность. ### Отслеживание состояния -Пока у пользователя выполняются процессы, значок панели «Мои активности» в верхней панели портала заменяется индикатором. На вкладке «Процессы» панели отображается число выполняющихся процессов и строка «Выполняются процессы: {count}»; список обновляется при запуске и завершении процесса. +Пока у пользователя выполняются процессы, значок панели «Мои активности» в верхней панели портала заменяется индикатором. +На вкладке «Процессы» панели отображается число выполняющихся процессов и строка «Выполняются процессы: {count}»; список обновляется при запуске и завершении процесса. В таблице «История запусков» на вкладке «Процессы» сущности можно просмотреть: @@ -405,23 +487,31 @@ AI-провайдер ищется по названию среди провай #### Таймлайн -На панели визуализации запуска процесса доступна вкладка «Таймлайн», на которой отображается хронология выполнения процесса: для каждого элемента, который участвовал в текущем запуске, показаны время начала и окончания, длительность и состояние. +На панели визуализации запуска процесса доступна вкладка «Таймлайн», на которой отображается хронология выполнения процесса. +Для каждого элемента, который участвовал в текущем запуске, показаны время начала и окончания, длительность и состояние. -Состояние элемента отображается цветом полосы и подписью в легенде: «Выполнено», «Выполнено после повтора», «Выполняется», «Ожидание», «Ждёт подтверждения», «Ошибка», «Отклонено», «Отменено» или «Пропущено». «Отклонено» означает задачу, действие которой не запустилось из-за [условий выполнения](../../actions/overview/#условия-выполнения), «Пропущено» — шаг, выключенный при запуске. +Состояние элемента отображается цветом полосы и подписью в легенде: «Выполнено», «Выполнено после повтора», «Выполняется», «Ожидание», «Ждёт подтверждения», «Ошибка», «Отклонено», «Отменено» или «Пропущено». +«Отклонено» означает задачу, действие которой не запустилось из-за [условий выполнения](../../actions/overview/#условия-выполнения), «Пропущено» — шаг, выключенный при запуске. -Пока запуск выполняется, незавершённые элементы продолжаются до отметки «Сейчас». После завершения запуска элемент, который не завершился сам, например цикл, на итерации которого процесс завершился с ошибкой, заканчивается в момент завершения запуска и получает его итоговый статус. +Пока запуск выполняется, незавершённые элементы продолжаются до отметки «Сейчас». +После завершения запуска элемент, который не завершился сам, например цикл, на итерации которого процесс завершился с ошибкой, заканчивается в момент завершения запуска и получает его итоговый статус. #### Схема запуска -Пока запуск выполняется, схема обновляется каждые 5 секунд. Состояние элемента показывает отметка в углу элемента: выполнен, выполнен после повтора, ошибка, отклонён, отменён, выполняется, ожидание, пропущен или ожидает подтверждения. Для завершённого запуска боковая панель элемента, который не завершился сам, показывает итоговый статус запуска и время его завершения. -Задачу, которая ожидает подтверждения, можно подтвердить кнопкой «Подтвердить» прямо на схеме. Кнопка активна только для пользователей из списка [подтверждающих](../../actions/overview/#подтверждение) действия. +Пока запуск выполняется, схема обновляется каждые 5 секунд. +Состояние элемента показывает отметка в углу элемента: выполнен, выполнен после повтора, ошибка, отклонён, отменён, выполняется, ожидание, пропущен или ожидает подтверждения. +Для завершённого запуска боковая панель элемента, который не завершился сам, показывает итоговый статус запуска и время его завершения. +Задачу, которая ожидает подтверждения, можно подтвердить кнопкой «Подтвердить» прямо на схеме. +Кнопка активна только для пользователей из списка [подтверждающих](../../actions/overview/#подтверждение) действия. -Пройденный путь выделяется цветом, связи, по которым процесс не прошёл, отображаются светло-серыми. Элементы, пройденные на предыдущих итерациях цикла, отображаются приглушёнными, а цикл показывает «Итерация {current} из {total}». +Пройденный путь выделяется цветом, связи, по которым процесс не прошёл, отображаются светло-серыми. +Элементы, пройденные на предыдущих итерациях цикла, отображаются приглушёнными, а цикл показывает «Итерация {current} из {total}». Если элемент выполнялся несколько раз, в его боковой панели лог каждого прохождения отображается отдельно с заголовком «Посещение {n}». #### Лог процесса -Для каждого запуска процесса доступен подробный лог выполнения. На схеме запуска он свёрнут в строку «Лог выполнения процесса»; если в логе есть ошибки, рядом отображается их число «Ошибок: {count}». +Для каждого запуска процесса доступен подробный лог выполнения. +На схеме запуска он свёрнут в строку «Лог выполнения процесса»; если в логе есть ошибки, рядом отображается их число «Ошибок: {count}». Чтобы просмотреть лог: @@ -432,12 +522,18 @@ AI-провайдер ищется по названию среди провай Выбор, открыт лог или свёрнут, и его положение сохраняются в браузере. -Кнопка «Скачать диагностику» в окне запуска процесса скачивает JSON-файл для разбора запуска. В поле `instance` файла — описание запуска: статус, элементы, история событий и содержимое хранилища. В поле `executionLog` — полный лог выполнения построчно, без цветовой разметки. +Кнопка «Скачать диагностику» в окне запуска процесса скачивает JSON-файл для разбора запуска. +В поле `instance` файла — описание запуска: статус, элементы, история событий и содержимое хранилища. +В поле `executionLog` — полный лог выполнения построчно, без цветовой разметки. -Минимальный уровень сообщений в логе задаёт параметр модуля `logger.executionLevel`: по умолчанию `info`, сообщения уровня `debug` не отображаются. Параметр действует также на логи действий, синхронизаций источников данных и проверок состояния. +Минимальный уровень сообщений в логе задаёт параметр модуля `logger.executionLevel`. +По умолчанию используется уровень `info`, и сообщения уровня `debug` не отображаются. +Параметр действует также на логи действий, синхронизаций источников данных и проверок состояния. ## Примеры использования +Ниже приведены примеры типовых процессов. + ### Создание проекта с настройкой Типовая схема процесса: @@ -466,7 +562,8 @@ AI-провайдер ищется по названию среди провай На процессы действуют следующие ограничения: * Элемент «Цикл» в режиме «Фиксированное число» выполняет от 1 до 10 000 итераций. -* Коллекция элемента «Цикл» в режиме «По коллекции» может содержать до 10 000 элементов. Коллекция большего размера завершает цикл с ошибкой. +* Коллекция элемента «Цикл» в режиме «По коллекции» может содержать до 10 000 элементов. + Коллекция большего размера завершает цикл с ошибкой. * Поле «Задержка (секунды)» элемента «Таймер» принимает значения от 1 до 1 209 600 (14 суток), поле «Каждые N дней» — от 1 до 365. * Размер тела элемента «Шаблон» — не более 1 МиБ. * Если поле «Время на выполнение (сек)» задачи больше нуля, задача прерывается по истечении этого времени и получает статус `Timeout`. diff --git a/content/documentation/admin/processes/store.md b/content/documentation/admin/processes/store.md index 5d51f922..a28542d8 100644 --- a/content/documentation/admin/processes/store.md +++ b/content/documentation/admin/processes/store.md @@ -12,30 +12,41 @@ params: url: ../../../user/templating/#process-store --- -The process store is a JSON object shared by a single process run. Tasks use it to pass data to each other: identifiers, arrays for loop iteration, intermediate results, and generated text. +The process store is a JSON object shared by a single process run. +Tasks use it to pass data to each other: identifiers, arrays for loop iteration, intermediate results, and generated text. -Writing is done **only via rules** in the configuration of actions and "Template" elements. Reading is done via Go templates `{{ .store. }}` in the request body, gateway conditions, and other fields that support templating. +Writing is done **only via rules** in the configuration of actions and "Template" elements. +Reading is done via Go templates `{{ .store. }}` in the request body, gateway conditions, and other fields that support templating. ## Data model -- **One store per run** — each process instance has its own store; it is preserved between steps and available when viewing the run. -- **Nested paths** — keys are specified as dot-paths without a leading dot: `notification.module_name`, `ctx.job.id`. Intermediate objects are created automatically. -- **Array indices** — a path can reference an array element: `items[0].status`, `branches[2].name`. -- **Value types** — depending on the operation, strings, numbers, objects, and JSON arrays can end up in the store. The "Set string" and "Append string" operations always work with strings; operations with the JSON suffix store the parsed structure. +The process store follows these rules: + +- **One store per run**: Each process instance has its own store; it is preserved between steps and available when viewing the run. +- **Nested paths**: Keys are specified as dot-paths without a leading dot: `notification.module_name`, `ctx.job.id`. + Intermediate objects are created automatically. +- **Array indices**: A path can reference an array element: `items[0].status`, `branches[2].name`. +- **Value types**: Depending on the operation, strings, numbers, objects, and JSON arrays can end up in the store. + The "Set string" and "Append string" operations always work with strings; operations with the JSON suffix store the parsed structure. {{< alert level="info" >}} -The service key `_loop` is populated by the process engine while a loop is running. Do not write to `_loop` manually using action rules — use it for reading in templates only. +The service key `_loop` is populated by the process engine while a loop is running. +Do not write to `_loop` manually using action rules — use it for reading in templates only. {{< /alert >}} ## Store update rules -Rules are configured in the action, on the "Update" tab, in the "Updating process store" section. They run **after the action completes successfully**, **in list order**. Each subsequent rule sees the changes made by the previous rules of the same action. +Rules are configured in the action, on the "Update" tab, in the "Updating process store" section. +They run **after the action completes successfully**, **in list order**. +Each subsequent rule sees the changes made by the previous rules of the same action. In the process task configuration, rules are shown in read-only mode; to change them, open the action from the task's side panel. ### Rule fields -| Field | Required | Description | +Each store update rule has the following fields: + +| Name | Required | Description | | ---- | -------------- | -------- | | When | No | A Go template. An empty value means the rule always runs. After rendering, the result must be `true`, `false`, `1`, or `0`; otherwise the rule is skipped | | Operation | Yes | The way the value at the "Target" path is changed | @@ -44,6 +55,8 @@ In the process task configuration, rules are shown in read-only mode; to change ### Operations +The following operations are available: + | Operation | Result | | -------- | --------- | | Set string | Replaces the value at the path with the text string from the source; JSON is not parsed | @@ -53,7 +66,8 @@ In the process task configuration, rules are shown in read-only mode; to change | Merge JSON (shallow) | Merges the JSON object from the source with the object at the path: top-level keys are overwritten, nested objects are replaced entirely | | Delete | Deletes the key at the path | -For the **Set JSON**, **Append JSON**, and **Merge JSON** operations, the source must render valid JSON: pass the value through `toJSON`, for example, `{{ toJSON .response.items }}`. If the source is a single path, such as `{{ .response.items }}`, the portal substitutes the value at this path without serialization. +For the **Set JSON**, **Append JSON**, and **Merge JSON** operations, the source must render valid JSON: pass the value through `toJSON`, for example, `{{ toJSON .response.items }}`. +If the source is a single path, such as `{{ .response.items }}`, the portal substitutes the value at this path without serialization. ### Rule examples @@ -61,25 +75,25 @@ For the **Set JSON**, **Append JSON**, and **Merge JSON** operations, the source | When | Operation | Target | Source | | ------- | -------- | ---- | -------- | -| | Set string | `deploy.job_id` | `{{ .response.id }}` | +| — | Set string | `deploy.job_id` | `{{ .response.id }}` | **Write an array for a subsequent loop:** | When | Operation | Target | Source | | ------- | -------- | ---- | -------- | -| | Set JSON | `notification.engagements` | `{{ toJSON .response.engagements }}` | +| — | Set JSON | `notification.engagements` | `{{ toJSON .response.engagements }}` | **Append a string to a log:** | When | Operation | Target | Source | | ------- | -------- | ---- | -------- | -| | Append string | `run.log` | `step {{ .store._loop.index }}: ok\n` | +| — | Append string | `run.log` | `step {{ .store._loop.index }}: ok\n` | **Update only part of an object:** | When | Operation | Target | Source | | ------- | -------- | ---- | -------- | -| | Merge JSON (shallow) | `meta` | `{{ toJSON (dict "status" "ready" "updated_by" .entity.slug) }}` | +| — | Merge JSON (shallow) | `meta` | `{{ toJSON (dict "status" "ready" "updated_by" .entity.slug) }}` | **Run a rule only on the first loop iteration:** @@ -91,18 +105,19 @@ For the **Set JSON**, **Append JSON**, and **Merge JSON** operations, the source | When | Operation | Target | Source | | ------- | -------- | ---- | -------- | -| | Delete | `temp.payload` | | +| — | Delete | `temp.payload` | — | ### "Loop context" panel -The action's rule editor has a **Loop context** panel: it shows the loop context keys (`_loop.item`, `_loop.index`, etc.). Click a key to insert it into a rule. +The action's rule editor has a **Loop context** panel: it shows the loop context keys, such as `_loop.item` and `_loop.index`. +Click a key to insert it into a rule. ## Reading from the store In process templates, use: ```go-text-template -{{ .store. }} +{{ .store. }} ``` For nested fields, the path matches the "Target" in the write rules: @@ -117,7 +132,8 @@ Read an array element with the `index` function: {{ (index .store.items 0).id }} ``` -An index in square brackets, such as `items[0].id`, works only in write paths, for example in the "Target" field of write rules. In a Go template it fails the step with an error. +An index in square brackets, such as `items[0].id`, works only in write paths, for example in the "Target" field of write rules. +In a Go template it fails the step with an error. Process launch parameters are available in a separate context: @@ -128,10 +144,11 @@ Process launch parameters are available in a separate context: For more information on templating contexts, see [Templating](../../../user/templating/). {{< alert level="warning" >}} -If a key is not present in the store (the action has not yet run, the rule didn't fire, or the condition was false), the template `{{ .store. }}` will cause the step to fail with an error. Make sure preceding tasks have written the required data. +If a key is not present in the store (the action has not yet run, the rule didn't fire, or the condition was false), the template `{{ .store. }}` will cause the step to fail with an error. +Make sure preceding tasks have written the required data. {{< /alert >}} -## Loop context `_loop` +## Loop context _loop While the loop body is running, the `_loop` object is available in the store: @@ -163,8 +180,10 @@ In exclusive gateway conditions inside a loop: The "Loop" element supports two modes (the "Loop mode" field): -1. **Fixed count** — the body runs a specified number of times (1–10000). `_loop.item` holds the iteration number (1, 2, 3…). -1. **Foreach collection** — when entering the loop, the "Collection template" Go template is evaluated; each element of the resulting **JSON array** is one iteration. The array can contain up to 10,000 items. +1. **Fixed count**: The body runs a specified number of times (1–10000). + `_loop.item` holds the iteration number (1, 2, 3…). +1. **Foreach collection**: When entering the loop, the "Collection template" Go template is evaluated; each element of the resulting **JSON array** is one iteration. + The array can contain up to 10,000 items. ### Collection template @@ -182,25 +201,29 @@ An alternative is to build the array in the template: **Edge cases:** -- An empty array or a missing key — 0 iterations, execution follows the "Exit" connection; a warning appears in the process log. -- A value at the path that is not a JSON array — a validation or loop execution error. +- An empty array or a missing key: 0 iterations, execution follows the "Exit" connection, and a warning appears in the process log. +- A string containing a JSON array, for example, the result of a "Set string" rule with the `{{ toJSON .response.items }}` source: The string is parsed as an array. +- A value at the path that is not a JSON array: A validation or loop execution error. ### Scenario: iterating over a list from an API +To iterate over a list returned by an API, configure the process as follows: + 1. **Task** "Get engagements" — a **Set JSON** rule, target `notification.engagements`, source `{{ toJSON .response.engagements }}`. 1. **Loop**, **Foreach collection** mode, collection template `{{ .store.notification.engagements }}`. 1. **Task** in the loop body — use `{{ .store._loop.item.id }}`, `{{ .store._loop.item.name }}` in the request body. -1. **Exclusive gateway** in the body — a condition based on an item field, e.g. left value `{{ .store._loop.item.status }}`, right value `active`. +1. **Exclusive gateway** in the body — a condition based on an item field, for example, left value `{{ .store._loop.item.status }}`, right value `active`. 1. **Exit** connection — continuation after iterating over all elements. ## The Template element -The "Template" element evaluates a Go template as the process runs and writes a **string** to the store. JSON in the result is not parsed — the text is stored in the store as-is. +The "Template" element evaluates a Go template as the process runs and writes a **string** to the store. +JSON in the result is not parsed — the text is stored in the store as-is. -| Field | Description | +| Name | Description | | ---- | -------- | | Template body | A Go template; `{{ .store.* }}`, `{{ .process.* }}` are available, and, inside a loop, `{{ .store._loop.* }}` | -| Output store key | The destination dot-path, e.g. `rendered_message` or `notification.summary` | +| Output store key | The destination dot-path, for example, `rendered_message` or `notification.summary` | | Format hint | A hint used when viewing the run (`text`, `markdown`, `html`, `json`); does not affect the write | Example body: @@ -216,21 +239,21 @@ Subsequent tasks read the result via `{{ .store.rendered_message }}` or the corr ## Viewing the store during execution -On the process run visualization screen, open the **Store** tab: - -- **Tree** — navigate nested keys; the type and value of the selected node are shown on the right. -- **JSON** — the full contents of the store in JSON format. +On the process run visualization screen, open the **Store** tab. +The **Tree** view lets you navigate nested keys and shows the type and value of the selected node on the right. +The **JSON** view shows the full contents of the store in JSON format. You can copy a value, refresh the data, and download the run's JSON (button on the run dialog panel). -The task's side panel on the run diagram shows the selected action's **Process store update rules**. Compare them with the actual contents of the store to find a rule that did not run. +The task's side panel on the run diagram shows the selected action's **Process store update rules**. +Compare them with the actual contents of the store to find a rule that did not run. ## Process log and debugging The visualization panel provides: -- an **Execution log** tab (including in a separate window or below the diagram); -- **Download log** — the run's text log; -- messages about an empty loop collection and skipped store rules. +- An **Execution log** tab (including in a separate window or below the diagram). +- **Download log**: The run's text log. +- Messages about an empty loop collection and skipped store rules. If a template error occurs, or invalid JSON is used in a rule with a JSON operation, that rule may be skipped (with a warning in the log), while the other rules of the same action continue to run. diff --git a/content/documentation/admin/processes/store.ru.md b/content/documentation/admin/processes/store.ru.md index 087bde8a..d1bb0ac1 100644 --- a/content/documentation/admin/processes/store.ru.md +++ b/content/documentation/admin/processes/store.ru.md @@ -12,31 +12,49 @@ params: url: ../../../user/templating/#хранилище-процесса --- -Хранилище процесса — это JSON-объект, общий для одного запуска процесса. Через него задачи передают друг другу данные: идентификаторы, массивы для обхода в цикле, промежуточные результаты и сформированные тексты. +Хранилище процесса — это JSON-объект, общий для одного запуска процесса. +Через него задачи передают друг другу данные: идентификаторы, массивы для обхода в цикле, промежуточные результаты и сформированные тексты. -Запись выполняется **только по правилам** в конфигурации действий и элементов «Шаблон», а также элементом «AI-агент», который записывает [результат агента](overview/#результат-агента) по заданному ключу. Чтение — через Go-шаблоны `{{ .store.<путь> }}` в теле запроса, условиях шлюзов и других полях с поддержкой шаблонизации. +Запись выполняется **только по правилам** в конфигурации действий и элементов «Шаблон», а также элементом «AI-агент», который записывает [результат агента](overview/#результат-агента) по заданному ключу. +Чтение — через Go-шаблоны `{{ .store. }}` в теле запроса, условиях шлюзов и других полях с поддержкой шаблонизации. ## Модель данных -- **Одно хранилище на запуск** — у каждого экземпляра процесса своё хранилище; оно сохраняется между шагами и доступно при просмотре запуска. Принудительный перезапуск процесса очищает хранилище. -- **Вложенные пути** — ключи задаются dot-path без ведущей точки: `notification.module_name`, `ctx.job.id`. Промежуточные объекты создаются автоматически. Так же записывают значения элементы «Шаблон» и «AI-агент»: ключ `notification.summary` дополняет объект `notification`, а не создаёт ключ с точкой в имени. +Хранилище процесса работает по следующим правилам: + +- **Одно хранилище на запуск** — у каждого экземпляра процесса своё хранилище; оно сохраняется между шагами и доступно при просмотре запуска. + Принудительный перезапуск процесса очищает хранилище. +- **Вложенные пути** — ключи задаются dot-path без ведущей точки: `notification.module_name`, `ctx.job.id`. + Промежуточные объекты создаются автоматически. + Так же записывают значения элементы «Шаблон» и «AI-агент»: ключ `notification.summary` дополняет объект `notification`, а не создаёт ключ с точкой в имени. - **Занятый путь** — если путь проходит через значение, которое не является объектом, например ключ `notification.module_name.short`, когда в `notification.module_name` записана строка, элементы «Шаблон» и «AI-агент» завершаются с ошибкой `write store key`. -- **Индексы массивов** — в пути можно указывать элемент массива: `items[0].status`, `branches[2].name`. Индекс — от 0 до 10000. Синтаксис пути в поле «Цель» проверяется при сохранении действия: некорректный путь отклоняется с ошибкой «Некорректный путь: ключи через точку, индексы массива в квадратных скобках не больше 10000 (например, items[2].name)». Путь в полях «Ключ в хранилище» элемента «Шаблон» и «Ключ результата в хранилище» элемента «AI-агент» проверяется при запуске процесса: с некорректным путём процесс не запускается. -- **Типы значений** — в зависимости от операции в хранилище попадают строки, числа, объекты и массивы JSON. Операции «Записать строку» и «Добавить строку» всегда работают со строками; операции с суффиксом JSON сохраняют разобранную структуру. +- **Индексы массивов** — в пути можно указывать элемент массива: `items[0].status`, `branches[2].name`. + Индекс — от 0 до 10000. + Синтаксис пути в поле «Цель» проверяется при сохранении действия. + Некорректный путь отклоняется с ошибкой «Некорректный путь: ключи через точку, индексы массива в квадратных скобках не больше 10000 (например, items[2].name)». + Путь в полях «Ключ в хранилище» элемента «Шаблон» и «Ключ результата в хранилище» элемента «AI-агент» проверяется при запуске процесса. + С некорректным путём процесс не запускается. +- **Типы значений** — в зависимости от операции в хранилище попадают строки, числа, объекты и массивы JSON. + Операции «Записать строку» и «Добавить строку» всегда работают со строками; операции с суффиксом JSON сохраняют разобранную структуру. {{< alert level="info" >}} -Служебный ключ `_loop` заполняется движком процесса во время выполнения цикла. Не записывайте в `_loop` вручную правилами действий — используйте его только для чтения в шаблонах. +Служебный ключ `_loop` заполняется движком процесса во время выполнения цикла. +Не записывайте в `_loop` вручную правилами действий — используйте его только для чтения в шаблонах. {{< /alert >}} ## Правила обновления хранилища -Правила настраиваются в действии на вкладке «Обновление» в разделе «Обновление хранилища процесса». Они выполняются **после успешного завершения** действия, **в порядке списка**. Каждое следующее правило видит изменения, внесённые предыдущими правилами того же действия. +Правила настраиваются в действии на вкладке «Обновление» в разделе «Обновление хранилища процесса». +Они выполняются **после успешного завершения** действия, **в порядке списка**. +Каждое следующее правило видит изменения, внесённые предыдущими правилами того же действия. В конфигурации задачи процесса правила отображаются в режиме только для чтения; для изменения откройте действие из боковой панели задачи. ### Поля правила -| Поле | Обязательность | Описание | +Каждое правило обновления хранилища содержит следующие поля: + +| Название | Обязательность | Описание | | ---- | -------------- | -------- | | Условие | Нет | Go-шаблон. Пустое значение — правило выполняется всегда. После рендеринга результат должен быть `true`, `false`, `1` или `0`; иначе правило пропускается | | Операция | Да | Способ изменения значения по пути «Цель» | @@ -45,6 +63,8 @@ params: ### Операции +Доступны следующие операции: + | Операция | Результат | | -------- | --------- | | Записать строку | Заменить значение по пути текстовой строкой из источника; JSON не разбирается | @@ -54,7 +74,8 @@ params: | Слить JSON (поверхностно) | Объединить JSON-объект из источника с объектом по пути: ключи верхнего уровня перезаписываются, вложенные объекты заменяются целиком | | Удалить | Удалить ключ по пути | -Для операций **Записать JSON**, **Добавить JSON** и **Слить JSON** источник должен давать корректный JSON: передайте значение через `toJSON`, например `{{ toJSON .response.items }}`. Если источник — один путь, например `{{ .response.items }}`, портал подставляет значение по этому пути без сериализации. +Для операций **Записать JSON**, **Добавить JSON** и **Слить JSON** источник должен давать корректный JSON: передайте значение через `toJSON`, например `{{ toJSON .response.items }}`. +Если источник — один путь, например `{{ .response.items }}`, портал подставляет значение по этому пути без сериализации. ### Примеры правил @@ -62,25 +83,25 @@ params: | Условие | Операция | Цель | Источник | | ------- | -------- | ---- | -------- | -| | Записать строку | `deploy.job_id` | `{{ .response.id }}` | +| — | Записать строку | `deploy.job_id` | `{{ .response.id }}` | **Записать массив для последующего цикла:** | Условие | Операция | Цель | Источник | | ------- | -------- | ---- | -------- | -| | Записать JSON | `notification.engagements` | `{{ toJSON .response.engagements }}` | +| — | Записать JSON | `notification.engagements` | `{{ toJSON .response.engagements }}` | **Дописать строку в лог:** | Условие | Операция | Цель | Источник | | ------- | -------- | ---- | -------- | -| | Добавить строку | `run.log` | `step {{ .store._loop.index }}: ok\n` | +| — | Добавить строку | `run.log` | `step {{ .store._loop.index }}: ok\n` | **Обновить только часть объекта:** | Условие | Операция | Цель | Источник | | ------- | -------- | ---- | -------- | -| | Слить JSON (поверхностно) | `meta` | `{{ toJSON (dict "status" "ready" "updated_by" .entity.slug) }}` | +| — | Слить JSON (поверхностно) | `meta` | `{{ toJSON (dict "status" "ready" "updated_by" .entity.slug) }}` | **Выполнить правило только на первой итерации цикла:** @@ -92,18 +113,19 @@ params: | Условие | Операция | Цель | Источник | | ------- | -------- | ---- | -------- | -| | Удалить | `temp.payload` | | +| — | Удалить | `temp.payload` | — | ### Панель «Контекст цикла» -В редакторе правил действия доступна панель **Контекст цикла**: она показывает ключи контекста цикла (`_loop.item`, `_loop.index` и др.). Нажмите на ключ, чтобы вставить его в правило. +В редакторе правил действия доступна панель **Контекст цикла**: она показывает ключи контекста цикла (`_loop.item`, `_loop.index` и др.). +Нажмите на ключ, чтобы вставить его в правило. ## Чтение из хранилища В шаблонах процесса используйте: ```go-text-template -{{ .store.<путь> }} +{{ .store. }} ``` Для вложенных полей путь совпадает с «Целью» в правилах записи: @@ -118,21 +140,23 @@ params: {{ (index .store.items 0).id }} ``` -Индекс в квадратных скобках, например `items[0].id`, работает только в путях записи, например в поле «Цель» правил записи. В Go-шаблоне такая запись завершит шаг с ошибкой. +Индекс в квадратных скобках, например `items[0].id`, работает только в путях записи, например в поле «Цель» правил записи. +В Go-шаблоне такая запись завершит шаг с ошибкой. Параметры запуска процесса доступны отдельным контекстом: ```go-text-template -{{ .process.<идентификатор_параметра> }} +{{ .process. }} ``` Подробнее о контекстах шаблонизации — в разделе [«Шаблонизация»](../../../user/templating/). {{< alert level="warning" >}} -Если ключа нет в хранилище (действие ещё не выполнялось, правило не сработало или условие было ложным), шаблон `{{ .store.<путь> }}` завершит шаг с ошибкой. Убедитесь, что предшествующие задачи записали нужные данные. +Если ключа нет в хранилище (действие ещё не выполнялось, правило не сработало или условие было ложным), шаблон `{{ .store. }}` завершит шаг с ошибкой. +Убедитесь, что предшествующие задачи записали нужные данные. {{< /alert >}} -## Контекст цикла `_loop` +## Контекст цикла _loop Пока выполняется тело цикла, в хранилище доступен объект `_loop`: @@ -164,8 +188,10 @@ params: Элемент «Цикл» поддерживает два режима (поле «Режим цикла»): -1. **Фиксированное число** — тело выполняется заданное количество раз (1–10000). В `_loop.item` — номер итерации (1, 2, 3…). -1. **По коллекции** — при входе в цикл вычисляется Go-шаблон «Шаблон коллекции»; каждый элемент полученного **JSON-массива** — одна итерация. Массив может содержать до 10 000 элементов. +1. **Фиксированное число** — тело выполняется заданное количество раз (1–10000). + В `_loop.item` — номер итерации (1, 2, 3…). +1. **По коллекции** — при входе в цикл вычисляется Go-шаблон «Шаблон коллекции»; каждый элемент полученного **JSON-массива** — одна итерация. + Массив может содержать до 10 000 элементов. ### Шаблон коллекции @@ -189,6 +215,8 @@ params: ### Сценарий: обход списка из API +Чтобы обойти список, полученный из API, настройте процесс следующим образом: + 1. **Задача** «Получить engagements» — правило **Записать JSON**, цель `notification.engagements`, источник `{{ toJSON .response.engagements }}`. 1. **Цикл**, режим **По коллекции**, шаблон коллекции `{{ .store.notification.engagements }}`. 1. **Задача** в теле цикла — в теле запроса использовать `{{ .store._loop.item.id }}`, `{{ .store._loop.item.name }}`. @@ -197,9 +225,10 @@ params: ## Элемент «Шаблон» -Элемент «Шаблон» вычисляет Go-шаблон при проходе процесса и записывает **строку** в хранилище. JSON из результата не разбирается — в хранилище сохраняется текст как есть. +Элемент «Шаблон» вычисляет Go-шаблон при проходе процесса и записывает **строку** в хранилище. +JSON из результата не разбирается — в хранилище сохраняется текст как есть. -| Поле | Описание | +| Название | Описание | | ---- | -------- | | Тело шаблона | Go-шаблон; доступны `{{ .store.* }}`, `{{ .process.* }}`, внутри цикла — `{{ .store._loop.* }}` | | Ключ в хранилище | Dot-path назначения, например `rendered_message` или `notification.summary` | @@ -218,20 +247,22 @@ params: ## Просмотр хранилища при выполнении -На экране визуализации запуска процесса откройте вкладку **Хранилище**: - -- **Дерево** — навигация по вложенным ключам; справа — тип и значение выбранного узла. -- **JSON** — полное содержимое хранилища в формате JSON. +На экране визуализации запуска процесса откройте вкладку **Хранилище**. +В режиме **Дерево** можно перемещаться по вложенным ключам, справа отображаются тип и значение выбранного узла. +В режиме **JSON** отображается полное содержимое хранилища в формате JSON. -Доступны копирование значения и обновление данных. Содержимое хранилища вместе с описанием запуска и логом скачивается кнопкой «Скачать диагностику» в окне запуска процесса. +Доступны копирование значения и обновление данных. +Содержимое хранилища вместе с описанием запуска и логом скачивается кнопкой «Скачать диагностику» в окне запуска процесса. -В боковой панели задачи на схеме запуска отображаются **Правила обновления хранилища** выбранного действия. Сравните их с фактическим содержимым хранилища, чтобы найти правило, которое не сработало. +В боковой панели задачи на схеме запуска отображаются **Правила обновления хранилища** выбранного действия. +Сравните их с фактическим содержимым хранилища, чтобы найти правило, которое не сработало. ## Лог процесса и отладка На панели визуализации доступны: -- **Лог выполнения процесса** — по умолчанию свёрнут под схемой и раскрывается кнопкой «Показать лог»; доступен также слева от схемы и в отдельном окне. Подробнее — в разделе [«Лог процесса»](overview/#лог-процесса); +- **Лог выполнения процесса** — по умолчанию свёрнут под схемой и раскрывается кнопкой «Показать лог»; доступен также слева от схемы и в отдельном окне. + Подробнее — в разделе [«Лог процесса»](overview/#лог-процесса); - **Скачать диагностику** — JSON-файл с описанием запуска, содержимым хранилища и полным логом; - сообщения о пустой коллекции цикла и пропущенных правилах хранилища. diff --git a/content/documentation/admin/resource-requirements.md b/content/documentation/admin/resource-requirements.md index 6b21ba39..963e43bf 100644 --- a/content/documentation/admin/resource-requirements.md +++ b/content/documentation/admin/resource-requirements.md @@ -100,7 +100,7 @@ switch to the profiles with user load. Select a profile by the expected number of active users and the catalog size. In the examples, one running process has two steps active at the same time, each of which takes one worker slot. -Background tasks include data source synchronizations, status checks and other operations from the shared queue: +Background tasks include datasource synchronizations, status checks and other operations from the shared queue: | Scenario parameter | 10 users | 100 users | 200 users | 500 users | 1000 users | | --- | --- | --- | --- | --- | --- | @@ -285,7 +285,7 @@ Before selecting a profile, collect the following parameters: | --- | --- | --- | | User activity | Number of active users, request rate, catalog search and filtering, number of open widgets | API and PostgreSQL. Widgets also call external systems | | Process execution | Number of processes running at the same time, parallel branches, action duration, size of the context and results | API keeps the execution state. Workers run the tasks. PostgreSQL stores the run records | -| Catalog synchronization | Number of data sources, schedule, number and size of objects in one fetch, entity matching and relation creation | Worker memory and CPU, PostgreSQL, external APIs | +| Catalog synchronization | Number of datasources, schedule, number and size of objects in one fetch, entity matching and relation creation | Worker memory and CPU, PostgreSQL, external APIs | | Status checks | Number of entities and rules, frequency, check duration | Workers and external systems | | Property history | Number of changes, size of the old and new value, retention period, queries over long periods | PostgreSQL before the transfer, ClickHouse after the transfer, background worker operations | | Events and task exchange | Rate and size of events, number of streams, queue length, locks, size of results and number of task completions | Redis: CPU, memory and disk. PostgreSQL stores the events | diff --git a/content/documentation/admin/resource-requirements.ru.md b/content/documentation/admin/resource-requirements.ru.md index 57c86fbf..70e88498 100644 --- a/content/documentation/admin/resource-requirements.ru.md +++ b/content/documentation/admin/resource-requirements.ru.md @@ -10,12 +10,12 @@ Deckhouse Development Portal (DDP) устанавливается модулем | Профиль | DDP: CPU / память | PostgreSQL: CPU / память / диск | Redis: CPU / память / диск | ClickHouse: CPU / память / диск | | --- | --- |------------------------------------------------|------------------------------------------------|------------------------------------------------| -| Демо-установка | 4 CPU / 8 GB | 2 CPU / 4 GB / 20 GB | 1 CPU / 2 GB / 10 GB | 2 CPU / 8 GB / 50 GB | -| 10 пользователей | 8 CPU / 32 GB | 2 CPU / 8 GB / 32 GB | 2 CPU / 4 GB / 16 GB | 4 CPU / 16 GB / 64 GB | -| 100 пользователей | 16 CPU / 32 GB | 2 CPU / 16 GB / 64 GB | 2 CPU / 8 GB / 16 GB | 4 CPU / 16 GB / 64 GB | -| 200 пользователей | 16 CPU / 64 GB | 2 CPU / 16 GB / 64 GB | 2 CPU / 16 GB / 32 GB | 4 CPU / 16 GB / 128 GB | -| 500 пользователей | 32 CPU / 64 GB | 4 CPU / 64 GB / 256 GB | 2 CPU / 32 GB / 64 GB | 4 CPU / 16 GB / 256 GB | -| 1000 пользователей | 32 CPU / 128 GB | 16 CPU / 64 GB / 512 GB | 2 CPU / 32 GB / 128 GB | 4 CPU / 32 GB / 512 GB | +| Демо-установка | 4 CPU / 8 ГБ | 2 CPU / 4 ГБ / 20 ГБ | 1 CPU / 2 ГБ / 10 ГБ | 2 CPU / 8 ГБ / 50 ГБ | +| 10 пользователей | 8 CPU / 32 ГБ | 2 CPU / 8 ГБ / 32 ГБ | 2 CPU / 4 ГБ / 16 ГБ | 4 CPU / 16 ГБ / 64 ГБ | +| 100 пользователей | 16 CPU / 32 ГБ | 2 CPU / 16 ГБ / 64 ГБ | 2 CPU / 8 ГБ / 16 ГБ | 4 CPU / 16 ГБ / 64 ГБ | +| 200 пользователей | 16 CPU / 64 ГБ | 2 CPU / 16 ГБ / 64 ГБ | 2 CPU / 16 ГБ / 32 ГБ | 4 CPU / 16 ГБ / 128 ГБ | +| 500 пользователей | 32 CPU / 64 ГБ | 4 CPU / 64 ГБ / 256 ГБ | 2 CPU / 32 ГБ / 64 ГБ | 4 CPU / 16 ГБ / 256 ГБ | +| 1000 пользователей | 32 CPU / 128 ГБ | 16 CPU / 64 ГБ / 512 ГБ | 2 CPU / 32 ГБ / 128 ГБ | 4 CPU / 32 ГБ / 512 ГБ | Бюджет DDP включает API, веб-интерфейс, платформенный AI-агент и воркеры. Для демо-установки рекомендуется режим `managed` для баз данных, для остальных профилей — режим `external`. @@ -52,16 +52,16 @@ ClickHouse хранит историю параметров, доступную | --- | --- | | Пользовательская нагрузка | 1 пользователь | | CPU | 9 CPU с учётом managed-экземпляров | -| Память | 22 GB с учётом managed-экземпляров | +| Память | 22 ГБ с учётом managed-экземпляров | | Одновременно выполняющиеся процессы | 1–2 | -| Постоянный диск | 80 GB: PostgreSQL — 20 GB, Valkey — 10 GB, ClickHouse — 50 GB | +| Постоянный диск | 80 ГБ: PostgreSQL — 20 ГБ, Valkey — 10 ГБ, ClickHouse — 50 ГБ | | `workers.replicas` | `1` | | `workers.maxTasks` | `5` | | ClickHouse | Включён, режим `managed` | -Бюджет компонентов портала для демо составляет 4 CPU и 8 GB памяти. -Managed-экземпляры по умолчанию добавляют 5 CPU по сумме лимитов и 14 GB памяти. -Сумма составляет 9 CPU и 22 GB памяти. +Бюджет компонентов портала для демо составляет 4 CPU и 8 ГБ памяти. +Managed-экземпляры по умолчанию добавляют 5 CPU по сумме лимитов и 14 ГБ памяти. +Сумма составляет 9 CPU и 22 ГБ памяти. При `coreFraction: 50` для PostgreSQL и `coreFraction: "50%"` для Valkey и ClickHouse гарантированный запрос CPU managed-экземпляров составляет суммарно 2,5 CPU. Бюджет рассчитан по полным лимитам CPU. @@ -118,7 +118,8 @@ spec: Число зарегистрированных пользователей влияет на накопление запусков процессов, а число активных пользователей — на частоту запросов к API и базам данных. Установка на 10 пользователей с частыми синхронизациями большого каталога может потребовать больше воркеров, чем профиль на 100 пользователей. -Число сущностей само по себе также не задаёт необходимую память: учитывайте размер параметров и объём одной синхронизации. +Число сущностей само по себе также не задаёт необходимую память. +Учитывайте размер параметров и объём одной синхронизации. API, веб-интерфейс и платформенный AI-агент работают по одной реплике в каждом профиле. Количество воркеров повышает параллельность фоновых задач. @@ -136,17 +137,17 @@ API, веб-интерфейс и платформенный AI-агент ра | Просмотр истории параметров | 10% активных пользователей одновременно. До 1 запроса в секунду на такого пользователя | | Запуски процессов | 2 запуска на пользователя в рабочий день | | Горизонт накопления запусков | 180 календарных дней, приблизительно 129 рабочих дней | -| Размер данных одного запуска | 256 KB суммарно для процесса, его действий, контекста, результатов и журналов | -| Размер текущей сущности | 2 KB | +| Размер данных одного запуска | 256 КБ суммарно для процесса, его действий, контекста, результатов и журналов | +| Размер текущей сущности | 2 КБ | | Изменения сущности | 5 изменений в сутки, каждое создаёт событие и запись истории параметра | -| Размер полного события | 8 KB, включая старое и новое состояние сущности | +| Размер полного события | 8 КБ, включая старое и новое состояние сущности | | Хранение событий в PostgreSQL | 4 дня и до 1 дня ожидания очередной очистки | | Потоки событий Redis | Около 10 000 событий на каждый ресурс каталога. Новые события продлевают срок жизни потока | | Пик синхронизации | В 100 раз выше средней суточной скорости изменений | -| Размер записи истории параметра | 1 KB до сжатия | +| Размер записи истории параметра | 1 КБ до сжатия | | Хранение истории параметров | 180 дней | -| Очередь задач | До 10 000 задач по 16 KB | -| Временный результат задачи | 64 KB, хранение 3 минуты | +| Очередь задач | До 10 000 задач по 16 КБ | +| Временный результат задачи | 64 КБ, хранение 3 минуты | | Длительность задачи для расчёта обмена | 5 секунд. Число завершений в секунду равно числу мест воркеров, делённому на 5 | | Автоматизации по событиям | До 2 получателей на событие. Задачи, которые они создают, входят в общий предел параллельности | | Свободный диск | 30% после размещения данных и запаса на обслуживание | @@ -163,16 +164,16 @@ API, веб-интерфейс и платформенный AI-агент ра | Компонент | CPU | Память | | --- | --- | --- | -| API (`backend`) | 4 CPU | 8,59 GB | -| Веб-интерфейс (`frontend`) | 1 CPU | 2,15 GB | -| Платформенный AI-агент (`agent`) | 1 CPU | 1,07 GB | -| Один воркер (`worker`) | 2 CPU | 8,59 GB | +| API (`backend`) | 4 CPU | 8,59 ГБ | +| Веб-интерфейс (`frontend`) | 1 CPU | 2,15 ГБ | +| Платформенный AI-агент (`agent`) | 1 CPU | 1,07 ГБ | +| Один воркер (`worker`) | 2 CPU | 8,59 ГБ | Для `N` воркеров сумма ресурсов API, веб-интерфейса, AI-агента и воркеров составляет -`6 + 2 × N` CPU и около `11,81 + 8,59 × N` GB памяти. +`6 + 2 × N` CPU и около `11,81 + 8,59 × N` ГБ памяти. Например, для двух воркеров сумма для портала равна `6 + 2 × 2 = 10` CPU -и примерно `11,81 + 8,59 × 2 = 28,99` GB памяти. -После округления вверх бюджет составит 16 CPU и 32 GB памяти без баз данных. +и примерно `11,81 + 8,59 × 2 = 28,99` ГБ памяти. +После округления вверх бюджет составит 16 CPU и 32 ГБ памяти без баз данных. ## Расчёт CPU и памяти баз данных @@ -188,8 +189,8 @@ API, веб-интерфейс и платформенный AI-агент ра | --- | --- | | PostgreSQL: пакет чтения каталога и событий | 2 мс. Для запросов связанных объектов и проверки доступа — 4 мс | | PostgreSQL: поиск по 100 000 сущностей | 40 мс. Масштабируется пропорционально размеру каталога | -| PostgreSQL: обновление сущности с историей и событием | 1 мс, с запасом на размер события 8 KB | -| Redis: запись или доставка события 8 KB | 0,03 мс | +| PostgreSQL: обновление сущности с историей и событием | 1 мс, с запасом на размер события 8 КБ | +| Redis: запись или доставка события 8 КБ | 0,03 мс | | Redis: короткая команда координации | 0,01 мс | | Redis: обмен задачей и результатом между воркером и бэкендом | 0,4 мс, с запасом на отдельные команды и дополнительные обращения | | ClickHouse: запрос страницы, окна истории или состояния на дату | 16 мс | @@ -210,10 +211,10 @@ API, веб-интерфейс и платформенный AI-агент ра Рабочий набор памяти включает текущий каталог, события за 5 дней и данные запусков за последние 30 календарных дней, приблизительно 22 рабочих дня. Объём рабочего набора умножается на 1,5 для индексов и кеширования. -Расчёт дополнительно добавляет служебный запас 2 GB, -32 MB на чтение каждого активного пользователя -и по 8 MB на каждое из 10 параллельных обновлений одной фоновой задачи. -Минимальный бюджет памяти в модели составляет 8 GB. +Расчёт дополнительно добавляет служебный запас 2 ГБ, +32 МБ на чтение каждого активного пользователя +и по 8 МБ на каждое из 10 параллельных обновлений одной фоновой задачи. +Минимальный бюджет памяти в модели составляет 8 ГБ. Учтите параллельные операции и соединения также в настройках PostgreSQL. PostgreSQL расходует память сортировок и хеш-операций на каждую операцию, как описано [в документации PostgreSQL](https://www.postgresql.org/docs/current/runtime-config-resource.html). @@ -247,11 +248,11 @@ PostgreSQL расходует память сортировок и хеш-опе К событиям расчёт добавляет очередь из 10 000 задач и результаты завершённых задач за 3 минуты. Общий объём умножается на 1,3 для структур Redis и ещё на 2 для временной копии при сохранении данных. -Расчёт добавляет 0,5 GB служебного запаса и по 1 MB буферов на активного пользователя. -Минимальный бюджет памяти в модели равен 4 GB. +Расчёт добавляет 0,5 ГБ служебного запаса и по 1 МБ буферов на активного пользователя. +Минимальный бюджет памяти в модели равен 4 ГБ. -В профиле на 1000 пользователей полезные данные занимают около 8,54 GB. -Расчёт с запасами даёт около 23 GB и округляется до 32 GB. +В профиле на 1000 пользователей полезные данные занимают около 8,54 ГБ. +Расчёт с запасами даёт около 23 ГБ и округляется до 32 ГБ. Влияние сохранения данных описано [в документации Redis](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/). ### CPU и память ClickHouse @@ -263,12 +264,12 @@ PostgreSQL расходует память сортировок и хеш-опе После умножения на 4 потребление остаётся ниже минимального бюджета модели в 4 CPU. Поэтому CPU в указанных профилях одинаковый. -Расчёт памяти складывается из 8 GB служебного запаса, -0,5 GB на каждого пользователя, который одновременно просматривает историю, +Расчёт памяти складывается из 8 ГБ служебного запаса, +0,5 ГБ на каждого пользователя, который одновременно просматривает историю, и кеша размером 25% объёма истории за последний месяц. Расчёт дополнительно учитывает четыре копии пакета из 10 000 записей при обработке вставки. -Минимальный бюджет памяти в модели равен 16 GB. -Для профиля на 1000 пользователей расчёт даёт около 22 GB и округляется до 32 GB. +Минимальный бюджет памяти в модели равен 16 ГБ. +Для профиля на 1000 пользователей расчёт даёт около 22 ГБ и округляется до 32 ГБ. Расход памяти на чтение и слияния зависит от запроса, а не только от числа возвращённых строк. Зависимость ресурсов от запросов описана [в рекомендациях ClickHouse](https://clickhouse.com/docs/guides/oss/best-practices/sizing-and-hardware-recommendations). @@ -276,12 +277,12 @@ PostgreSQL расходует память сортировок и хеш-опе Для нескольких серверов базы данных умножьте бюджет на их число. Если сервер обслуживает другие приложения, добавьте ресурсы для DDP к бюджетам этих приложений. -## От чего зависит потребление +## Исходные данные для расчёта Основные источники нагрузки различаются по компонентам. Перед выбором профиля соберите следующие параметры: -| Источник нагрузки | Что учитывать | Основной потребитель | +| Источник нагрузки | Параметры нагрузки | Основной потребитель | | --- | --- | --- | | Работа пользователей | Число активных пользователей, частота запросов, поиск и фильтрация каталога, число открытых виджетов | API и PostgreSQL. Виджеты также обращаются к внешним системам | | Выполнение процессов | Число одновременно выполняющихся процессов, параллельные ветки, длительность действий, объём контекста и результатов | API хранит состояние выполнения. Воркеры выполняют задачи. PostgreSQL хранит записи запусков | @@ -338,42 +339,43 @@ PostgreSQL расходует память сортировок и хеш-опе | Компонент | Размер тома в демо-установке | | --- | --- | -| PostgreSQL | 20 GB | -| Valkey | 10 GB | -| ClickHouse | 50 GB | -| Всего | 80 GB | +| PostgreSQL | 20 ГБ | +| Valkey | 10 ГБ | +| ClickHouse | 50 ГБ | +| Всего | 80 ГБ | -Эти размеры заданы по умолчанию для managed-экземпляров. Они не увеличиваются при изменении числа пользователей или воркеров. +Эти размеры заданы по умолчанию для managed-экземпляров. +Они не увеличиваются при изменении числа пользователей или воркеров. При росте данных увеличьте тома или перейдите к профилю с выделенными базами данных. При размещении баз данных в кластере дополнительно учтите репликацию хранилища и резервные копии. В профилях на 10–1000 пользователей диск каждой базы данных должен быть не меньше её тома в демо-установке. После округления вверх до степени двойки минимальные бюджеты составляют -32 GB для PostgreSQL, 16 GB для Redis и 64 GB для ClickHouse. +32 ГБ для PostgreSQL, 16 ГБ для Redis и 64 ГБ для ClickHouse. Для каждого профиля выберите больший из минимального бюджета и бюджета по расчёту ниже. ### Диск PostgreSQL Объём полезных данных `D` складывается из: -- текущего каталога: `число сущностей × 2 KB`; -- событий: `число сущностей × 5 изменений × 5 дней × 8 KB`; -- запусков процессов и действий: `число пользователей × 2 запуска × 129 рабочих дней × 256 KB`; -- очереди переноса истории за сутки: `число сущностей × 5 изменений × 1 KB`. +- текущего каталога: `число сущностей × 2 КБ`; +- событий: `число сущностей × 5 изменений × 5 дней × 8 КБ`; +- запусков процессов и действий: `число пользователей × 2 запуска × 129 рабочих дней × 256 КБ`; +- очереди переноса истории за сутки: `число сущностей × 5 изменений × 1 КБ`. В модели `D` удваивается для индексов и места, которое расходуют обновления записей. Для журнала предзаписи (WAL) расчёт добавляет больший из двух запасов: -8 GB или двукратный суточный объём записываемых данных. +8 ГБ или двукратный суточный объём записываемых данных. Суточный объём записи складывается из изменений каталога -`число сущностей × 5 × (2 + 8 + 1) KB` -и данных запусков `число пользователей × 2 × 256 KB` в рабочий день. +`число сущностей × 5 × (2 + 8 + 1) КБ` +и данных запусков `число пользователей × 2 × 256 КБ` в рабочий день. Бюджет диска равен `(2 × D + запас WAL) / 0,7`, округлённым вверх до степени двойки. -Минимальный бюджет составляет 32 GB и покрывает том 20 GB из демо-установки. +Минимальный бюджет составляет 32 ГБ и покрывает том 20 ГБ из демо-установки. Деление на 0,7 оставляет 30% свободного места. -Для 1000 пользователей полезные данные занимают около 88,83 GB. -С учётом индексов, обновлений, WAL и свободного места требуется около 271 GB. -После округления бюджет составляет 512 GB. +Для 1000 пользователей полезные данные занимают около 88,83 ГБ. +С учётом индексов, обновлений, WAL и свободного места требуется около 271 ГБ. +После округления бюджет составляет 512 ГБ. Этот расчёт охватывает данные заданного сценария. Диалоги AI, крупные контексты процессов, дополнительные связи и более подробные логи увеличивают объём. @@ -394,15 +396,15 @@ PostgreSQL расходует память сортировок и хеш-опе Расчёт дополнительно добавляет час записей при пиковой частоте событий и завершений задач. При `p` событиях и `q` завершениях задач в секунду часовой объём записи равен -`(p × 8 KB + q × (16 + 64) KB) × 3600`. +`(p × 8 КБ + q × (16 + 64) КБ) × 3600`. Бюджет диска равен `(3 × 1,3 × B + часовой объём записи) / 0,7`, -округлённым вверх до степени двойки, с минимумом 16 GB, который покрывает том 10 GB из демо-установки. -Для профиля на 1000 пользователей расчёт даёт около 79 GB и округляется до 128 GB. +округлённым вверх до степени двойки, с минимумом 16 ГБ, который покрывает том 10 ГБ из демо-установки. +Для профиля на 1000 пользователей расчёт даёт около 79 ГБ и округляется до 128 ГБ. Бюджет рассчитан для включённого сохранения данных с регулярной перезаписью журнала AOF. При другой политике RDB/AOF, редкой перезаписи или длительной записи на пиковой скорости пересчитайте место под журнал AOF и временные файлы. -Диск Redis не заменяет память: потоки, очереди и результаты должны помещаться в RAM. +Диск Redis не заменяет память, поскольку потоки, очереди и результаты должны помещаться в RAM. ### Диск ClickHouse @@ -417,20 +419,20 @@ PostgreSQL расходует память сортировок и хеш-опе По умолчанию история хранится 180 дней. Срок задаёт параметр `clickhouse.propertyHistory.retentionDays`. -В профилях приняты 5 изменений параметров на сущность в сутки и размер записи 1 KB до сжатия. +В профилях приняты 5 изменений параметров на сущность в сутки и размер записи 1 КБ до сжатия. Выигрыш от сжатия в расчёте не учитывается. -Бюджет диска включает 16 GB базового запаса, +Бюджет диска включает 16 ГБ базового запаса, место для истории и её временной копии при обслуживании, а также 30% свободного пространства. -Итоговый бюджет равен `(16 + 2 × объём истории) / 0,7` GB, -округлённым вверх до степени двойки, с минимумом 64 GB, который покрывает том 50 GB из демо-установки: +Итоговый бюджет равен `(16 + 2 × объём истории) / 0,7` ГБ, +округлённым вверх до степени двойки, с минимумом 64 ГБ, который покрывает том 50 ГБ из демо-установки: | Число сущностей | Число записей истории за 180 дней | Объём записей до сжатия | Бюджет диска ClickHouse | | --- | --- | --- | --- | -| 1000 | 900 000 | Около 0,92 GB | 64 GB | -| 10 000 | 9 000 000 | Около 9,2 GB | 64 GB | -| 20 000 | 18 000 000 | Около 18,4 GB | 128 GB | -| 50 000 | 45 000 000 | Около 46,1 GB | 256 GB | -| 100 000 | 90 000 000 | Около 92,2 GB | 512 GB | +| 1000 | 900 000 | Около 0,92 ГБ | 64 ГБ | +| 10 000 | 9 000 000 | Около 9,2 ГБ | 64 ГБ | +| 20 000 | 18 000 000 | Около 18,4 ГБ | 128 ГБ | +| 50 000 | 45 000 000 | Около 46,1 ГБ | 256 ГБ | +| 100 000 | 90 000 000 | Около 92,2 ГБ | 512 ГБ | Выберите том не меньше расчётного бюджета. При изменении частоты изменений, размера записей или срока хранения пересчитайте бюджет диска. @@ -441,5 +443,5 @@ PostgreSQL расходует память сортировок и хеш-опе На узлах отдельно выделите временное дисковое пространство. API и воркеры используют временные тома `emptyDir`, в том числе для кеша и работы с репозиториями. -Запрос модуля на `ephemeral-storage` составляет около 0,052 GB на контейнер и покрывает только логи. +Запрос модуля на `ephemeral-storage` составляет около 0,052 ГБ на контейнер и покрывает только логи. Клонируемые репозитории, пакеты шаблонов и образы контейнеров в этот запрос не входят. diff --git a/content/documentation/admin/security/audit-logs.md b/content/documentation/admin/security/audit-logs.md index ef51b876..e27eb384 100644 --- a/content/documentation/admin/security/audit-logs.md +++ b/content/documentation/admin/security/audit-logs.md @@ -4,31 +4,29 @@ description: Audit log contents, storage, filtering, retention, and CSV export i weight: 40 --- -Audit logs record all operations that users perform through the Deckhouse Development Portal (DDP) API. The logs are stored in a PostgreSQL database and support auditing of user activity. +Audit logs record all operations that users perform through the Deckhouse Development Portal (DDP) API. +The logs are stored in a PostgreSQL database and support auditing of user activity. ## Components -The following components create and store audit logs: - -- DDP Backend creates audit log entries. -- PostgreSQL stores the data. +DDP Backend creates audit log entries, and PostgreSQL stores the data. ## Audit log contents Each HTTP request to the API, except `GET` requests, creates an audit log entry with the following fields: -- "Email" — email address of the user who made the request. -- "IP" — client IP address. -- "Body" — HTTP request body. -- "Endpoint" — requested API path. -- "Method" — request HTTP method (`POST`, `PUT`, `DELETE`, or `PATCH`). -- "Status" — response HTTP status code. -- "Timestamp" — request date and time. +- "Email": Email address of the user who made the request. +- "IP": Client IP address. +- "Body": HTTP request body. +- "Endpoint": Requested API path. +- "Method": Request HTTP method (`POST`, `PUT`, `DELETE`, or `PATCH`). +- "Status": Response HTTP status code. +- "Timestamp": Request date and time. The following requests are not recorded in audit logs: -- `POST /api/v2/users/access-credentials` — saving user credentials. -- `POST /api/v2/security/encryption-key/rotate` — [encryption key rotation](../encryption-key-rotation/). +- `POST /api/v2/users/access-credentials`: Saving user credentials. +- `POST /api/v2/security/encryption-key/rotate`: [Encryption key rotation](../encryption-key-rotation/). - `POST /api/v2/widgets/data/` and `POST /api/v2/widgets/data//stream` — loading widget data. ## How it works @@ -37,35 +35,41 @@ DDP Backend automatically creates audit logs through request-processing middlewa To reduce database load, entries are buffered with the following settings: -- Batch size — 40 entries. -- Write interval — 20 seconds. -- In-memory buffer size — 4 entries. +- Batch size: 40 entries. +- Write interval: 20 seconds. +- In-memory buffer size: 4 entries. ## Storage -Audit logs are stored in the PostgreSQL `audit_logs` table. The table is partitioned by day based on the `timestamp` field. +Audit logs are stored in the PostgreSQL `audit_logs` table. +The table is partitioned by day based on the `timestamp` field. -The table structure is maintained automatically. Every day at `00:00` UTC, the system prepares space for logs for the next 7 days. +The table structure is maintained automatically. +Every day at `00:00` UTC, the system prepares space for logs for the next 7 days. -Logs are retained indefinitely and old entries are not deleted automatically. To control retention, configure external tools, such as cron jobs or database cleanup scripts, to delete old log partitions automatically. +Logs are retained indefinitely and old entries are not deleted automatically. +To control retention, configure external tools, such as cron jobs or database cleanup scripts, to delete old log partitions automatically. ## Viewing logs -Audit logs are available in the web interface under "Administration" → "Audit". You can filter logs by the following fields: +Audit logs are available in the web interface under "Administration" → "Audit". +You can filter logs by the following fields: - "Start of period" and "End of period" — date and time range. -- "Email" — user email. -- "Path" — beginning of the API path. -- "Method" — request method. -- "Status" — response status. -- "Search" — a substring of the email, IP address, path, method, or status. +- "Email": User email. +- "Path": Beginning of the API path. +- "Method": Request method. +- "Status": Response status. +- "Search": A substring of the email, IP address, path, method, or status. ## Exporting to CSV The audit log page provides a "Download .csv" button. Export is available only with permission to read audit logs. -The file includes all entries that match the current filters and sorting. Export does not run if more than 100,000 events match. +The file includes all entries that match the current filters and sorting. +Export does not run if more than 100,000 events match. ## Configuration -Audit logging is enabled by default and requires no additional configuration. To control log retention, configure automatic deletion of old database partitions. +Audit logging is enabled by default and requires no additional configuration. +To control log retention, configure automatic deletion of old database partitions. diff --git a/content/documentation/admin/security/audit-logs.ru.md b/content/documentation/admin/security/audit-logs.ru.md index d9d3e15a..4bd5b8f6 100644 --- a/content/documentation/admin/security/audit-logs.ru.md +++ b/content/documentation/admin/security/audit-logs.ru.md @@ -4,14 +4,12 @@ description: Содержимое, хранение, фильтрация, ср weight: 40 --- -Аудит-логи — это механизм записи всех операций, выполняемых пользователями через API Deckhouse Development Portal (DDP). Логи сохраняются в базе данных PostgreSQL и используются для аудита действий пользователей. +Аудит-логи — это механизм записи всех операций, выполняемых пользователями через API Deckhouse Development Portal (DDP). +Логи сохраняются в базе данных PostgreSQL и используются для аудита действий пользователей. ## Компоненты -В формировании и хранении аудит-логов участвуют следующие компоненты: - -- DDP Backend — формирует записи аудит-логов. -- PostgreSQL — обеспечивает хранение данных. +Записи аудит-логов формирует DDP Backend, а хранение данных обеспечивает PostgreSQL. ## Содержимое аудит-логов @@ -43,15 +41,20 @@ weight: 40 ## Хранение -Аудит-логи хранятся в таблице `audit_logs` базы данных PostgreSQL. Таблица партиционирована на основе поля `timestamp` с разделением по дням. +Аудит-логи хранятся в таблице `audit_logs` базы данных PostgreSQL. +Таблица партиционирована на основе поля `timestamp` с разделением по дням. -Структура таблицы поддерживается автоматически: ежедневно в `00:00` UTC подготавливается пространство для записи логов на следующие 7 дней. +Структура таблицы поддерживается автоматически. +Ежедневно в `00:00` UTC подготавливается пространство для записи логов на следующие 7 дней. -Логи хранятся неограниченно долго. Автоматическая очистка старых записей не выполняется. Для управления временем хранения необходимо настроить автоматическое удаление старых групп логов через внешние инструменты (например, cron-задачи или скрипты очистки базы данных). +Логи хранятся неограниченно долго. +Автоматическая очистка старых записей не выполняется. +Для управления временем хранения настройте автоматическое удаление старых групп логов через внешние инструменты (например, cron-задачи или скрипты очистки базы данных). ## Просмотр логов -Аудит-логи доступны через веб-интерфейс в разделе «Администрирование» → «Аудит». Логи можно фильтровать по следующим параметрам: +Аудит-логи доступны через веб-интерфейс в разделе «Администрирование» → «Аудит». +Логи можно фильтровать по следующим параметрам: - «Начало периода» и «Окончание периода» — интервал даты и времени. - «Email» — адрес электронной почты пользователя. @@ -62,10 +65,13 @@ weight: 40 ## Выгрузка в CSV -На странице просмотра аудит-логов доступна кнопка «Скачать .csv». Выгрузка выполняется только при наличии разрешения на чтение аудит-логов. +На странице просмотра аудит-логов доступна кнопка «Скачать .csv». +Выгрузка выполняется только при наличии разрешения на чтение аудит-логов. -В файл попадают все записи, соответствующие текущим фильтрам и сортировке. Если число подходящих событий превышает лимит в 100 000 записей, выгрузка не выполняется. +В файл попадают все записи, соответствующие текущим фильтрам и сортировке. +Если число подходящих событий превышает лимит в 100 000 записей, выгрузка не выполняется. ## Настройка -Механизм аудит-логирования включён по умолчанию и не требует дополнительной настройки. Для управления временем хранения логов необходимо настроить автоматическое удаление старых партиций базы данных. +Механизм аудит-логирования включён по умолчанию и не требует дополнительной настройки. +Для управления временем хранения логов настройте автоматическое удаление старых партиций базы данных. diff --git a/content/documentation/admin/security/credentials.md b/content/documentation/admin/security/credentials.md new file mode 100644 index 00000000..208d78c8 --- /dev/null +++ b/content/documentation/admin/security/credentials.md @@ -0,0 +1,212 @@ +--- +title: Credentials +weight: 30 +--- + +Credentials let you securely store and use access details for external services in actions, datasources, widgets, and other Deckhouse Development Portal (DDP, portal) components. +All credentials are encrypted before being saved to the database and decrypted only when used. + +## How it works + +Credentials are stored in the portal in encrypted form and substituted into requests at run time. + +### Credential types + +The portal administrator creates credential types in the "Administration" → "Credentials" section. Each type has the following fields: + +- "Name": Display name of the type. +- "Identifier": Unique identifier used in configurations. +- "Description": Hint for users. + +### User credentials + +Users fill in their personal credentials in the "Profile" → "Credentials" section. +For each credential type, a user can specify their own value (for example, an access token, password, or API key). + +After saving, a user cannot view the credential value, only update it. +The profile shows whether each credential is filled in. + +### Selecting storage for a credential type + +When you create or edit a credential type, you specify the storage. +By default, "Database" is used: values are stored in PostgreSQL. +If you select Vault, values are stored in HashiCorp Vault or Deckhouse Stronghold. +This option is available only if the Vault integration is enabled and configured in the portal. + +A credential type always uses one selected storage. +You can change the storage of an existing type; however, credentials already saved in the old storage are not moved automatically. + +### Storing in the database + +Credentials with the "Database" storage type are saved in PostgreSQL. +Before saving, values are encrypted using the AES-GCM algorithm. + +Encryption parameters: + +- Algorithm: AES-GCM. +- Key size: 16, 24, or 32 bytes (128, 192, or 256 bits). +- Nonce size: 12 bytes. +- Encryption key: The `security.secretKey` module parameter. For details, see [Encryption key](#encryption-key). + +Encrypted values are saved in the database with the `GCM:` prefix, which lets the system identify the encryption method during decryption. + +{{< alert level="warning" >}} +If you change the encryption key (`security.secretKey`) in the module settings without re-encrypting first, all current credentials become unavailable. +Use [encryption key rotation](../encryption-key-rotation/) in the web interface. +{{< /alert >}} + +### Storing in HashiCorp Vault + +If the Vault storage is selected for a credential type, the portal saves user credentials in HashiCorp Vault or Deckhouse Stronghold. + +How it works: + +- Vault uses the KV Secrets Engine v2. + The secrets path is set in the Vault settings in DDP (for example, `secrets/data/ddp`). +- A separate secret is created for each user at the `{path}/credentials/{type_uuid}/users/{user_uuid}` path. + The secret contains a single `value` key whose value is the encrypted credentials. + Encryption uses the DDP key (`security.secretKey`). +- The connection to Vault uses `AppRole` (AppRole Role ID and AppRole Secret ID). + AppRole Role ID and AppRole Secret ID are stored in the DDP database in encrypted form. + The Vault token is renewed automatically; if renewal fails, the portal signs in again using AppRole. + +To configure Vault in DDP, follow these steps: + +1. In the "Administration" → "Credentials" section, click "Vault settings". +1. Enable Vault ("Enabled"). +1. Fill in the parameters: + - `URL`: Vault server address (for example, `https://vault.example.com`). + - "AppRole Role ID": AppRole ID obtained when creating the role in Vault. + - "AppRole Secret ID": AppRole secret, used together with Role ID for authentication in Vault. + - "Path": Path to secrets in KV v2. + For KV v2, the path must contain the `/data/` segment (for example, `secrets/data/ddp` or `secrets/data/ddp/credentials`). + The mount (for example, `secrets`) must be created in Vault in advance; the subdirectories after `data/` are created by the portal automatically when credentials are saved. +1. Click "Test connection" to make sure DDP can authenticate and access Vault. +1. Save the configuration. + +After the configuration is saved, the Vault option becomes available in the storage list when you create or edit a credential type. +If Vault is disabled or not configured, types with Vault storage remain in the list, but credentials of these types cannot be filled in or used until Vault is enabled and configured. + +#### Access permissions + +To view and change the Vault configuration and test the connection, the global permission to edit credential types is required: `edit:user-access-credentials-types`. + +#### Configuration specifics + +When configuring the Vault integration, consider the following: + +- Only KV Secrets Engine v2 is supported. + The path in the settings must include `/data/` (for example, `mount/data/subdirectory`). +- There is one Vault configuration per DDP instance: one URL, one AppRole, and one base path. + All credential types with Vault storage use this path (subdirectories are created automatically based on the type UUID). +- You can clear all saved values of a type from the current storage (database or Vault) at any time with the "Clear storage" action in the credential types table. +- Changing the DDP encryption key (`security.secretKey`) without re-encrypting first also makes credentials in Vault unreadable, because values in Vault are stored encrypted. + Use [encryption key rotation](../encryption-key-rotation/). + +### Using credentials + +Credentials are decrypted only when they need to be used, immediately before accessing an external service. +After use, decrypted values are not kept in memory longer than necessary. + +## Integration with portal components + +Credentials are used by actions, datasources, widgets, and status checks. + +### Actions + +In the action configuration, you can specify the list of required credentials in the "Credentials" field. +For each entry in the list, you set an "Identifier" that matches the credential type ID and a "Credential type" selected from the list. + +When running an action, the system does the following: + +1. Determines the user on whose behalf the action runs (the initiator, or the account selected in the "Account for execution" field if the "Select account for execution" option is enabled). +1. Retrieves this user's credentials from the database. +1. Decrypts the credential values. +1. Substitutes the decrypted values into the action configuration templates (URL, headers, request body) using placeholders like `{{.credentials.identifier}}`. + +### Datasources + +In the datasource configuration, you can specify the list of required credentials in the same way as for actions. +When synchronizing data, the system does the following: + +1. Uses the credentials of the system user specified in the datasource configuration (the "System account" field). +1. Retrieves and decrypts the system user's credentials. +1. Substitutes the values into the datasource request templates. + +{{< alert level="warning" >}} +Datasources always use the credentials of the system user, not of the user who started the synchronization. +{{< /alert >}} + +### Widgets + +Widgets can use credentials to get data from external services. +The mechanism is similar to actions: + +1. The user is determined (the request initiator, or the account selected in the "Account for widget" field if the "Select account for widget" option is enabled). +1. The credentials are retrieved and decrypted. +1. The values are substituted into the widget configuration. + +### Status checks + +Status checks use credentials to check the state of entities. +In the status check rule configuration, you can specify the list of required credentials. +When running a check, the system does the following: + +1. Uses the credentials of the system user specified in the status check rule configuration (the "System account" field). +1. Retrieves and decrypts the system user's credentials. +1. Substitutes the values into the rule configuration templates (URL, headers, request parameters) using placeholders like `{{.credentials.identifier}}`. + +{{< alert level="warning" >}} +Status checks always use the credentials of the system user specified in the rule configuration. +If no system user is specified, the rule is skipped during the check. +{{< /alert >}} + +### External services + +External services can have their own list of credentials. +If an action, datasource, or widget uses an external service (the "Use external service" option is enabled), then: + +1. The component inherits the credentials from the external service configuration if its own configuration does not specify credentials. +1. Credentials specified directly in the component configuration take precedence. + +## Configuration + +To work with credentials, configure the encryption key. + +### Encryption key + +The encryption key is set in the `security.secretKey` parameter of the `development-platform` module: in the `development-platform` ModuleConfig (`spec.settings.security.secretKey`) or in the module settings in the Deckhouse web UI. + +Example of a ModuleConfig fragment: + +```yaml +apiVersion: deckhouse.io/v1alpha1 +kind: ModuleConfig +metadata: + name: development-platform +spec: + settings: + security: + secretKey: +``` + +Key requirements: + +- Length: 16, 24, or 32 printable ASCII characters (128, 192, or 256 bits). +- The key must not consist of a single repeated character. +- The key must not match common values, such as `1234567890123456` or `passwordpassword`. + +If the key does not meet the requirements, DDP Backend does not start. + +### Vault integration + +The connection to HashiCorp Vault (URL, AppRole, KV v2 path) is configured in the web interface in the "Administration" → "Credentials" → "Vault settings" section. +The module settings define only the encryption key (`security.secretKey`), which is also used to encrypt values stored in Vault. + +## Security + +Credentials are protected as follows: + +- Credentials are never sent to the user in decrypted form. +- Decryption happens only immediately before a request is sent. +- Decrypted values are not logged. diff --git a/content/documentation/admin/security/credentials.ru.md b/content/documentation/admin/security/credentials.ru.md index 0e56d1be..1ecce930 100644 --- a/content/documentation/admin/security/credentials.ru.md +++ b/content/documentation/admin/security/credentials.ru.md @@ -3,10 +3,13 @@ title: Учётные данные weight: 30 --- -Механизм учётных данных позволяет безопасно хранить и использовать реквизиты доступа к внешним сервисам в действиях, источниках данных, виджетах и других компонентах Deckhouse Development Portal (DDP, портал). Все учётные данные шифруются перед сохранением в базе данных и расшифровываются только при использовании. +Механизм учётных данных позволяет безопасно хранить и использовать реквизиты доступа к внешним сервисам в действиях, источниках данных, виджетах и других компонентах Deckhouse Development Portal (DDP, портал). +Все учётные данные шифруются перед сохранением в базе данных и расшифровываются только при использовании. ## Принцип работы +Учётные данные хранятся в портале в зашифрованном виде и подставляются в запросы при выполнении. + ### Типы учётных данных Администратор портала создаёт типы учётных данных в разделе «Администрирование» → «Учётные данные». Каждый тип имеет: @@ -17,34 +20,39 @@ weight: 30 ### Учётные данные пользователей -Пользователи заполняют свои персональные учётные данные в разделе «Профиль» → «Учётные данные». Для каждого типа учётных данных пользователь может указать свое значение (например, токен доступа, пароль, ключ API). +Пользователи заполняют свои персональные учётные данные в разделе «Профиль» → «Учётные данные». +Для каждого типа учётных данных пользователь может указать свое значение (например, токен доступа, пароль, ключ API). -После сохранения пользователь не может просмотреть значение учётных данных, только обновить его. В профиле отображается информация о том, заполнены ли те или иные учётные данные. +После сохранения пользователь не может просмотреть значение учётных данных, только обновить его. +В профиле отображается информация о том, заполнены ли те или иные учётные данные. ### Выбор хранилища для типа учётных данных -При создании или редактировании типа учётных данных указывается хранилище: - -- «База данных» — значения хранятся в PostgreSQL (по умолчанию). -- Vault — значения хранятся в HashiCorp Vault или в Deckhouse Stronghold. Доступно только если в портале включена и настроена интеграция с Vault. +При создании или редактировании типа учётных данных указывается хранилище. +По умолчанию используется «База данных»: значения хранятся в PostgreSQL. +При выборе Vault значения хранятся в HashiCorp Vault или в Deckhouse Stronghold. +Этот вариант доступен, только если в портале включена и настроена интеграция с Vault. -Один и тот же тип учётных данных всегда использует одно выбранное хранилище. Изменить хранилище для существующего типа можно; при этом уже сохранённые учётные данные в старом хранилище не переносятся автоматически. +Один и тот же тип учётных данных всегда использует одно выбранное хранилище. +Изменить хранилище для существующего типа можно; при этом уже сохранённые учётные данные в старом хранилище не переносятся автоматически. ### Хранение в базе данных -Учётные данные с типом хранилища «База данных» сохраняются в PostgreSQL. Перед сохранением значения шифруются с использованием алгоритма AES-GCM. +Учётные данные с типом хранилища «База данных» сохраняются в PostgreSQL. +Перед сохранением значения шифруются с использованием алгоритма AES-GCM. Параметры шифрования: - Алгоритм: AES-GCM. - Размер ключа: 16, 24 или 32 байта (128, 192 или 256 бит). - Размер nonce: 12 байт. -- Ключ шифрования: параметр модуля `security.secretKey` (см. [«Ключ шифрования»](#ключ-шифрования)). +- Ключ шифрования: параметр модуля `security.secretKey`, подробнее — в разделе [«Ключ шифрования»](#ключ-шифрования). Зашифрованные значения сохраняются в базе данных с префиксом `GCM:`, что позволяет системе определить метод шифрования при расшифровке. {{< alert level="warning" >}} -При изменении ключа шифрования (`security.secretKey`) в настройках модуля без предварительного перешифрования все текущие учётные данные станут недоступны. Используйте [ротацию ключа шифрования](../encryption-key-rotation/) в веб-интерфейсе. +При изменении ключа шифрования (`security.secretKey`) в настройках модуля без предварительного перешифрования все текущие учётные данные станут недоступны. +Используйте [ротацию ключа шифрования](../encryption-key-rotation/) в веб-интерфейсе. {{< /alert >}} ### Хранение в HashiCorp Vault @@ -53,9 +61,14 @@ weight: 30 Как это устроено: -- В Vault используется движок KV Secrets Engine v2. Путь к секретам задаётся в настройках Vault в DDP (например, `secrets/data/ddp`). -- Для каждого пользователя создаётся отдельный секрет по пути `{path}/credentials/{uuid_типа}/users/{uuid_пользователя}`. Внутри секрета один ключ `value`, значение — зашифрованные учётные данные. Шифрование выполняется ключом DDP (`security.secretKey`). -- Подключение к Vault выполняется по `AppRole` (AppRole Role ID и AppRole Secret ID). AppRole Role ID и AppRole Secret ID сохраняются в БД DDP в зашифрованном виде. Токен Vault продлевается автоматически; при сбое продления выполняется повторный вход по AppRole. +- В Vault используется движок KV Secrets Engine v2. + Путь к секретам задаётся в настройках Vault в DDP (например, `secrets/data/ddp`). +- Для каждого пользователя создаётся отдельный секрет по пути `{path}/credentials/{uuid_типа}/users/{uuid_пользователя}`. + Внутри секрета один ключ `value`, значение — зашифрованные учётные данные. + Шифрование выполняется ключом DDP (`security.secretKey`). +- Подключение к Vault выполняется по `AppRole` (AppRole Role ID и AppRole Secret ID). + AppRole Role ID и AppRole Secret ID сохраняются в БД DDP в зашифрованном виде. + Токен Vault продлевается автоматически; при сбое продления выполняется повторный вход по AppRole. Настройка Vault в DDP: @@ -65,11 +78,14 @@ weight: 30 - `URL` — адрес сервера Vault (например, `https://vault.example.com`). - «AppRole Role ID» — идентификатор AppRole, полученный при создании роли в Vault. - «AppRole Secret ID» — секрет AppRole, используется вместе с Role ID для аутентификации в Vault. - - «Путь» — путь к секретам в KV v2. Для KV v2 путь должен содержать сегмент `/data/` (например, `secrets/data/ddp` или `secrets/data/ddp/credentials`). Mount (например, `secrets`) должен быть заранее создан в Vault; подкаталоги после `data/` создаются порталом автоматически при сохранении учётных данных. + - «Путь» — путь к секретам в KV v2. + Для KV v2 путь должен содержать сегмент `/data/` (например, `secrets/data/ddp` или `secrets/data/ddp/credentials`). + Mount (например, `secrets`) должен быть заранее создан в Vault; подкаталоги после `data/` создаются порталом автоматически при сохранении учётных данных. 1. Нажмите «Проверить подключение», чтобы убедиться, что DDP может аутентифицироваться и обращаться к Vault. 1. Сохраните конфигурацию. -После сохранения конфигурации при создании или редактировании типа учётных данных в списке хранилищ будет доступен вариант Vault. Если Vault выключен или не настроен, типы с хранилищем Vault останутся в списке, но учётные данные такого типа заполнять и использовать будет нельзя до включения и настройки Vault. +После сохранения конфигурации при создании или редактировании типа учётных данных в списке хранилищ будет доступен вариант Vault. +Если Vault выключен или не настроен, типы с хранилищем Vault останутся в списке, но учётные данные такого типа заполнять и использовать будет нельзя до включения и настройки Vault. #### Права доступа @@ -77,23 +93,29 @@ weight: 30 #### Особенности конфигурации -- Поддерживается только KV Secrets Engine v2. Путь в настройках должен включать `/data/` (например, `mount/data/подкаталог`). -- Одна конфигурация Vault на экземпляр DDP: один URL, одна AppRole, один базовый путь. Все типы учётных данных с хранилищем Vault используют этот путь (подкаталоги формируются автоматически по UUID типа). +При настройке интеграции с Vault учитывайте следующие особенности: + +- Поддерживается только KV Secrets Engine v2. + Путь в настройках должен включать `/data/` (например, `mount/data/подкаталог`). +- Одна конфигурация Vault на экземпляр DDP: один URL, одна AppRole, один базовый путь. + Все типы учётных данных с хранилищем Vault используют этот путь (подкаталоги формируются автоматически по UUID типа). - Очистить все сохранённые значения типа из текущего хранилища (база данных или Vault) в любой момент можно через действие «Очистить хранилище» в таблице типов учётных данных. -- Смена ключа шифрования DDP (`security.secretKey`) без предварительного перешифрования делает нечитаемыми и учётные данные в Vault, так как значения в Vault хранятся в зашифрованном виде. Используйте [ротацию ключа шифрования](../encryption-key-rotation/). +- Смена ключа шифрования DDP (`security.secretKey`) без предварительного перешифрования делает нечитаемыми и учётные данные в Vault, так как значения в Vault хранятся в зашифрованном виде. + Используйте [ротацию ключа шифрования](../encryption-key-rotation/). ### Использование учётных данных -Учётные данные расшифровываются только при необходимости их использования, непосредственно перед обращением к внешнему сервису. После использования расшифрованные значения не сохраняются в памяти дольше необходимого. +Учётные данные расшифровываются только при необходимости их использования, непосредственно перед обращением к внешнему сервису. +После использования расшифрованные значения не сохраняются в памяти дольше необходимого. ## Интеграция в компоненты портала -### Действия +Учётные данные используются действиями, источниками данных, виджетами и проверками статуса. -В конфигурации действия можно указать список требуемых учётных данных через поле «Учётные данные». Для каждой записи в списке задаются: +### Действия -- «Идентификатор» — идентификатор записи (соответствует идентификатору типа учётных данных). -- «Тип учётных данных» — выбор типа учётных данных из списка. +В конфигурации действия можно указать список требуемых учётных данных через поле «Учётные данные». +Для каждой записи в списке задаются «Идентификатор», соответствующий идентификатору типа учётных данных, и «Тип учётных данных», который выбирается из списка. При выполнении действия система: @@ -104,7 +126,8 @@ weight: 30 ### Источники данных -В конфигурации источника данных можно указать список требуемых учётных данных аналогично действиям. При синхронизации данных система: +В конфигурации источника данных можно указать список требуемых учётных данных аналогично действиям. +При синхронизации данных система: 1. Использует учётные данные системного пользователя, указанного в конфигурации источника данных (поле «Системная учётная запись»). 1. Извлекает и расшифровывает учётные данные системного пользователя. @@ -116,7 +139,8 @@ weight: 30 ### Виджеты -Виджеты могут использовать учётные данные для получения данных из внешних сервисов. Механизм работы аналогичен действиям: +Виджеты могут использовать учётные данные для получения данных из внешних сервисов. +Механизм работы аналогичен действиям: 1. Определяется пользователь (инициатор запроса или учётная запись, выбранная в поле «Учётная запись для виджета», если включена опция «Выбрать учётную запись для виджета»). 1. Извлекаются и расшифровываются учётные данные. @@ -124,25 +148,31 @@ weight: 30 ### Проверки статуса -Проверки статуса используют учётные данные для выполнения проверок состояния сущностей. В конфигурации правил проверки статуса можно указать список требуемых учётных данных. При выполнении проверки система: +Проверки статуса используют учётные данные для выполнения проверок состояния сущностей. +В конфигурации правил проверки статуса можно указать список требуемых учётных данных. +При выполнении проверки система: 1. Использует учётные данные системного пользователя, указанного в конфигурации правила проверки статуса (поле «Системная учётная запись»). 1. Извлекает и расшифровывает учётные данные системного пользователя. 1. Подставляет значения в шаблоны конфигурации правила (URL, заголовки, параметры запросов) через плейсхолдеры вида `{{.credentials.идентификатор}}`. {{< alert level="warning" >}} -Проверки статуса всегда используют учётные данные системного пользователя, указанного в конфигурации правила. Если системный пользователь не указан, правило пропускается при выполнении проверки. +Проверки статуса всегда используют учётные данные системного пользователя, указанного в конфигурации правила. +Если системный пользователь не указан, правило пропускается при выполнении проверки. {{< /alert >}} ### Внешние сервисы -Внешние сервисы могут иметь собственный список учётных данных. Если действие, источник данных или виджет использует внешний сервис (включена опция «Использовать внешний сервис»), то: +Внешние сервисы могут иметь собственный список учётных данных. +Если действие, источник данных или виджет использует внешний сервис (включена опция «Использовать внешний сервис»), то: 1. Учётные данные из конфигурации внешнего сервиса наследуются компонентом, если в его конфигурации не указаны собственные учётные данные. 1. Приоритет имеют учётные данные, указанные непосредственно в конфигурации компонента. ## Настройка +Для работы с учётными данными настройте ключ шифрования. + ### Ключ шифрования Ключ шифрования задаётся в параметре `security.secretKey` модуля `development-platform`: в ModuleConfig `development-platform` (`spec.settings.security.secretKey`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. @@ -170,10 +200,13 @@ spec: ### Интеграция с Vault -Подключение к HashiCorp Vault (URL, AppRole, путь к KV v2) настраивается в веб-интерфейсе в разделе «Администрирование» → «Учётные данные» → «Настройки Vault». В настройках модуля задаётся только ключ шифрования (`security.secretKey`), который используется в том числе для шифрования значений, хранящихся в Vault. +Подключение к HashiCorp Vault (URL, AppRole, путь к KV v2) настраивается в веб-интерфейсе в разделе «Администрирование» → «Учётные данные» → «Настройки Vault». +В настройках модуля задаётся только ключ шифрования (`security.secretKey`), который используется в том числе для шифрования значений, хранящихся в Vault. ## Безопасность +Учётные данные защищены следующим образом: + - Учётные данные никогда не передаются пользователю в расшифрованном виде. - Расшифровка происходит только непосредственно перед отправкой запроса. - Расшифрованные значения не логируются. diff --git a/content/documentation/admin/security/encryption-key-rotation.md b/content/documentation/admin/security/encryption-key-rotation.md index ce5b4de2..38d4623a 100644 --- a/content/documentation/admin/security/encryption-key-rotation.md +++ b/content/documentation/admin/security/encryption-key-rotation.md @@ -4,7 +4,8 @@ description: Safely re-encrypt stored credentials and replace the DDP Backend en weight: 35 --- -Deckhouse Development Portal (DDP) lets you securely replace the encryption key (`security.secretKey`) without losing credentials or other encrypted values. The operation runs from the web interface and re-encrypts all data stored with the current key. +Deckhouse Development Portal (DDP) lets you securely replace the encryption key (`security.secretKey`) without losing credentials or other encrypted values. +The operation runs from the web interface and re-encrypts all data stored with the current key. ## Reasons to rotate the key @@ -13,7 +14,8 @@ Rotate the encryption key when you need to replace the `security.secretKey` modu The parameter is set in the `development-platform` ModuleConfig (`spec.settings.security.secretKey`) or in the module settings in the Deckhouse Platform web interface. {{< alert level="warning" >}} -Do not change `security.secretKey` in the module settings before re-encryption finishes in the web interface. Otherwise, the stored values will become unavailable. +Do not change `security.secretKey` in the module settings before re-encryption finishes in the web interface. +Otherwise, the stored values will become unavailable. {{< /alert >}} ## Access permissions @@ -24,15 +26,18 @@ Key rotation requires the global `rotate:encryption-key` permission. The operation affects the following data categories: -- "User credentials" — values in PostgreSQL for credential types that use the "Database" storage. -- "AI provider credentials" — personal credentials for AI integrations. -- "Action temporary responses" — encrypted temporary responses in action execution records. -- "Vault secrets" — credential values stored in HashiCorp Vault or Deckhouse Stronghold. -- "Vault configuration" — the AppRole Role ID and AppRole Secret ID in the Vault integration settings. -- Template registry connection passwords. The results table has no separate row for them: they are counted in the "Total" row. +- "User credentials": Values in PostgreSQL for credential types that use the "Database" storage. +- "AI provider credentials": Personal credentials for AI integrations. +- "Action temporary responses": Encrypted temporary responses in action execution records. +- "Vault secrets": Credential values stored in HashiCorp Vault or Deckhouse Stronghold. +- "Vault configuration": The AppRole Role ID and AppRole Secret ID in the Vault integration settings. +- Template registry connection passwords. + The results table has no separate row for them: they are counted in the "Total" row. ## Procedure +To rotate the encryption key, follow these steps: + 1. Back up the DDP PostgreSQL database. If re-encryption fails, you can restore the encrypted values from the backup. 1. Go to "Administration" → "Credentials". 1. Click "Rotate encryption key". @@ -43,7 +48,8 @@ The operation affects the following data categories: - The key must not be a commonly used value, such as `1234567890123456` or `passwordpassword`. - The new key must differ from the old one. 1. Click "Re-encrypt". -1. Wait for the operation to finish and check the results table. For each category, the table shows the number of successfully re-encrypted, skipped, and failed records. +1. Wait for the operation to finish and check the results table. + For each category, the table shows the number of successfully re-encrypted, skipped, and failed records. 1. Set the new key in the `security.secretKey` module parameter: in the `development-platform` ModuleConfig (`spec.settings.security.secretKey`) or in the module settings in the Deckhouse Platform web interface. Example of a ModuleConfig fragment: @@ -64,19 +70,23 @@ The operation affects the following data categories: {{< alert level="info" >}} After re-encryption and until DDP Backend restarts with the new key, the stored values cannot be decrypted. -Values that users save in this interval are encrypted with the old key and cannot be read after the restart. To re-encrypt them, run the rotation again with the same old and new keys: values that are already encrypted with the new key are skipped. +Values that users save in this interval are encrypted with the old key and cannot be read after the restart. +To re-encrypt them, run the rotation again with the same old and new keys: values that are already encrypted with the new key are skipped. {{< /alert >}} -Browser sessions and impersonation sessions are signed with `security.secretKey`. After the key changes, current sessions become invalid: the web interface tries to renew the session through Dex and redirects the user to the sign-in page if renewal fails. Active impersonation sessions end. +Browser sessions and impersonation sessions are signed with `security.secretKey`. +After the key changes, current sessions become invalid: the web interface tries to renew the session through Dex and redirects the user to the sign-in page if renewal fails. +Active impersonation sessions end. ## Operation results The results table shows three counters for each data category: -- "Succeeded" — records re-encrypted with the new key. -- "Skipped" — records already accessible with the new key, for example, records re-encrypted earlier, and records without a stored value. -- "Failed" — records that could not be re-encrypted, usually because the old key is incorrect or the data is corrupted. +- "Succeeded": Records re-encrypted with the new key. +- "Skipped": Records already accessible with the new key, for example, records re-encrypted earlier, and records without a stored value. +- "Failed": Records that could not be re-encrypted, usually because the old key is incorrect or the data is corrupted. The "Total" row shows totals across all categories. -If the "Failed" column contains non-zero values, do not change the key in the module settings until you resolve the errors. Verify the old key and repeat the operation. +If the "Failed" column contains non-zero values, do not change the key in the module settings until you resolve the errors. +Verify the old key and repeat the operation. diff --git a/content/documentation/admin/security/encryption-key-rotation.ru.md b/content/documentation/admin/security/encryption-key-rotation.ru.md index 8dd29743..37dc5e2a 100644 --- a/content/documentation/admin/security/encryption-key-rotation.ru.md +++ b/content/documentation/admin/security/encryption-key-rotation.ru.md @@ -4,11 +4,12 @@ description: Безопасное перешифрование сохранён weight: 35 --- -Deckhouse Development Portal (DDP) позволяет безопасно сменить ключ шифрования (`security.secretKey`) без потери учётных данных и других зашифрованных значений. Операция выполняется из веб-интерфейса и перешифровывает все данные, которые хранятся с использованием текущего ключа. +Deckhouse Development Portal (DDP) позволяет безопасно сменить ключ шифрования (`security.secretKey`) без потери учётных данных и других зашифрованных значений. +Операция выполняется из веб-интерфейса и перешифровывает все данные, которые хранятся с использованием текущего ключа. ## Основания для ротации ключа -Выполните ротацию ключа шифрования, если необходимо заменить параметр модуля `security.secretKey` — например, по политике безопасности или после компрометации ключа. +Выполните ротацию ключа шифрования при замене параметра модуля `security.secretKey` — например, по политике безопасности или после компрометации ключа. Параметр задаётся в ModuleConfig `development-platform` (`spec.settings.security.secretKey`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. @@ -29,11 +30,15 @@ Deckhouse Development Portal (DDP) позволяет безопасно сме - «Временные ответы действий» — зашифрованные временные ответы в записях выполнения действий. - «Секреты Vault» — значения учётных данных, хранящихся в HashiCorp Vault или Deckhouse Stronghold. - «Конфигурация Vault» — AppRole Role ID и AppRole Secret ID в настройках интеграции с Vault. -- Пароли подключений [реестра шаблонов](../templates/registry/). Отдельной строки в таблице результатов для них нет: они учитываются в строке «Итого». +- Пароли подключений [реестра шаблонов](../templates/registry/). + Отдельной строки в таблице результатов для них нет, они учитываются в строке «Итого». ## Порядок выполнения -1. Создайте резервную копию базы данных PostgreSQL портала. Если перешифрование завершится с ошибкой, зашифрованные значения можно будет восстановить из резервной копии. +Чтобы выполнить ротацию ключа шифрования, выполните следующие действия: + +1. Создайте резервную копию базы данных PostgreSQL портала. + Если перешифрование завершится с ошибкой, зашифрованные значения можно будет восстановить из резервной копии. 1. Перейдите в раздел «Администрирование» → «Учётные данные». 1. Нажмите «Ротация ключа шифрования». 1. В поле «Старый ключ шифрования» введите текущий ключ (параметр модуля `security.secretKey`). @@ -43,7 +48,8 @@ Deckhouse Development Portal (DDP) позволяет безопасно сме - ключ не должен совпадать с распространёнными значениями, например `1234567890123456` или `passwordpassword`; - новый ключ должен отличаться от старого. 1. Нажмите «Перешифровать». -1. Дождитесь завершения операции и проверьте таблицу результатов. Для каждой категории отображается количество успешно перешифрованных, пропущенных и неуспешных записей. +1. Дождитесь завершения операции и проверьте таблицу результатов. + Для каждой категории отображается количество успешно перешифрованных, пропущенных и неуспешных записей. 1. Укажите новый ключ в параметре модуля `security.secretKey`: в ModuleConfig `development-platform` (`spec.settings.security.secretKey`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. Пример фрагмента ModuleConfig: @@ -64,10 +70,15 @@ Deckhouse Development Portal (DDP) позволяет безопасно сме {{< alert level="info" >}} После перешифрования и до перезапуска DDP Backend с новым ключом сохранённые значения расшифровать нельзя. -Значения, которые пользователи сохранят в этот промежуток, будут зашифрованы старым ключом и после перезапуска станут нечитаемыми. Чтобы перешифровать их, повторите ротацию с той же парой старого и нового ключей: значения, уже зашифрованные новым ключом, будут пропущены. +Значения, которые пользователи сохранят в этот промежуток, будут зашифрованы старым ключом и после перезапуска станут нечитаемыми. +Чтобы перешифровать их, повторите ротацию с той же парой старого и нового ключей. +Значения, уже зашифрованные новым ключом, будут пропущены. {{< /alert >}} -Сессии в браузере и сессии имперсонации подписываются ключом `security.secretKey`. После смены ключа текущие сессии становятся недействительными: веб-интерфейс пытается обновить сессию через Dex, а если это не удаётся, перенаправляет пользователя на страницу входа. Активные сессии имперсонации завершаются. +Сессии в браузере и сессии имперсонации подписываются ключом `security.secretKey`. +После смены ключа текущие сессии становятся недействительными. +Веб-интерфейс пытается обновить сессию через Dex, а если это не удаётся, перенаправляет пользователя на страницу входа. +Активные сессии имперсонации завершаются. ## Результаты операции @@ -79,4 +90,5 @@ Deckhouse Development Portal (DDP) позволяет безопасно сме Строка «Итого» содержит суммарные значения по всем категориям. -Если в столбце «Неуспешно» есть ненулевые значения, не меняйте ключ в настройках модуля до устранения причины ошибок. Проверьте корректность старого ключа и повторите операцию. +Если в столбце «Неуспешно» есть ненулевые значения, не меняйте ключ в настройках модуля до устранения причины ошибок. +Проверьте корректность старого ключа и повторите операцию. diff --git a/content/documentation/admin/security/http-security-headers.md b/content/documentation/admin/security/http-security-headers.md new file mode 100644 index 00000000..96ad8bed --- /dev/null +++ b/content/documentation/admin/security/http-security-headers.md @@ -0,0 +1,147 @@ +--- +title: HTTP security headers +weight: 50 +--- + +Deckhouse Development Portal (DDP) supports the following HTTP headers to improve interaction security: + +1. `Content-Security-Policy` + - Configurable content security policy. + - For a detailed description, see [Content Security Policy](#content-security-policy). + +1. `X-Frame-Options` + - Protection against clickjacking attacks. + - Default value: `SAMEORIGIN`. + - Configured in the `security.headers.xFrameOptions` module parameter. + - Possible values: `DENY`, `SAMEORIGIN`. + +1. `X-Content-Type-Options` + - Prevention of MIME sniffing. + - Value: `nosniff`. + +1. `X-XSS-Protection` + - Protection against XSS attacks (for legacy browsers). + - Value: `1; mode=block`. + +1. `Referrer-Policy` + - Control of referrer information. + - Value: `strict-origin-when-cross-origin`. + +1. `Permissions-Policy` (formerly Feature-Policy) + - Restriction of browser features. + - Value in DDP Frontend responses: `geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()`. + - Value in DDP Backend responses: `geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), autoplay=(), encrypted-media=()`. + +1. `Strict-Transport-Security` (HSTS) + - Enforcement of HTTPS. + - Value: `max-age=31536000; includeSubDomains; preload`. + - DDP Backend adds the header only if the TLS connection is terminated on DDP Backend itself. + DDP Frontend does not add this header. + +{{< alert level="info" >}} +In a standard installation, the TLS connection is terminated on the Ingress controller, so DDP does not add the `Strict-Transport-Security` header. +To enable HSTS, configure it on the Ingress controller, for example, in the [`hsts`](/modules/ingress-nginx/cr.html#ingressnginxcontroller-v1-spec-hsts) parameter of IngressNginxController. +{{< /alert >}} + +## Configuration + +The headers are configured in the `security.headers` parameter of the `development-platform` module: in the `development-platform` ModuleConfig (`spec.settings.security.headers`) or in the module settings in the Deckhouse web UI. + +Example of a ModuleConfig fragment with default values: + +```yaml +apiVersion: deckhouse.io/v1alpha1 +kind: ModuleConfig +metadata: + name: development-platform +spec: + settings: + security: + headers: + # Enable or disable all security headers. + enabled: true + csp: + # Allow loading images from any source. + allowExternalImages: false + # Allow embedding the portal in an iframe on any site and loading any site in a portal iframe. + allowIframe: false + # Space-separated additional sources added to the img-src, connect-src, frame-src, frame-ancestors CSP directives. + # For example: https://example.com. + additionalSources: "" + # Value of the X-Frame-Options header (DENY or SAMEORIGIN). + xFrameOptions: "SAMEORIGIN" +``` + +The `enabled` parameter enables or disables all security headers. +When set to `true`, the headers are added to HTTP responses; when set to `false`, they are not added. + +## Applying headers + +DDP Frontend adds the headers at the web server level when serving static files and HTML pages. +DDP Backend adds the headers through middleware to all API responses. + +{{< alert level="info" >}} +All security headers are enabled by default (`enabled: true`). +If necessary, you can disable or configure them in the `security.headers` module parameter. +{{< /alert >}} + +## Content Security Policy + +Content Security Policy (CSP) is a security mechanism that helps prevent XSS attacks and other code injections by restricting the sources from which resources (scripts, styles, images, and others) can be loaded. + +### Default CSP + +DDP Frontend and DDP Backend send different CSP policies. + +Default DDP Frontend policy: + +```text +default-src 'self'; +script-src 'self'; +style-src 'self' 'unsafe-inline'; +font-src 'self' data:; +img-src 'self' data:; +connect-src 'self' wss: ws:; +frame-src 'self'; +worker-src 'self' blob:; +object-src 'none'; +base-uri 'self'; +form-action 'self'; +frame-ancestors 'self'; +upgrade-insecure-requests; +``` + +Default DDP Backend policy: + +```text +default-src 'self'; +script-src 'none'; +style-src 'none'; +img-src 'none'; +font-src 'none'; +connect-src 'self'; +frame-src 'none'; +frame-ancestors 'none'; +object-src 'none'; +base-uri 'self'; +form-action 'self'; +upgrade-insecure-requests +``` + +### Changing CSP + +The `security.headers.csp` parameters change the policy as follows: + +- `allowExternalImages: true`: Allows images from any source. In the DDP Frontend policy, the `img-src` directive is set to `'self' data: *`; in the DDP Backend policy, it is set to `*`. + This is used, for example, for DDP object icons from external sources. +- `allowIframe: true`: Sets the `frame-src` and `frame-ancestors` directives to `*` in both policies. + This is used, for example, for iframe widgets. +- `additionalSources`: Adds the listed sources to the `img-src`, `connect-src`, `frame-src`, and `frame-ancestors` directives in both policies. + +{{< alert level="warning" >}} +With `allowIframe: true`, the portal can be embedded in an iframe on any site, and any site can be opened in portal iframe widgets. +The `X-Frame-Options` header is still sent, but modern browsers ignore it when the `frame-ancestors` directive is present. +This weakens protection against clickjacking attacks. + +To allow only trusted sites, keep `allowIframe: false` and list them in the `additionalSources` parameter. +{{< /alert >}} diff --git a/content/documentation/admin/security/http-security-headers.ru.md b/content/documentation/admin/security/http-security-headers.ru.md index 87f0f38a..dcf11306 100644 --- a/content/documentation/admin/security/http-security-headers.ru.md +++ b/content/documentation/admin/security/http-security-headers.ru.md @@ -35,10 +35,12 @@ Deckhouse Development Portal (DDP) поддерживает следующие H 1. `Strict-Transport-Security` (HSTS) - Принудительное использование HTTPS. - Значение: `max-age=31536000; includeSubDomains; preload`. - - DDP Backend добавляет заголовок, только если TLS-соединение завершается на самом DDP Backend. DDP Frontend этот заголовок не добавляет. + - DDP Backend добавляет заголовок, только если TLS-соединение завершается на самом DDP Backend. + DDP Frontend этот заголовок не добавляет. {{< alert level="info" >}} -При стандартной установке TLS-соединение завершается на Ingress-контроллере, поэтому DDP не добавляет заголовок `Strict-Transport-Security`. Чтобы включить HSTS, настройте его на Ingress-контроллере, например в параметре [`hsts`](/modules/ingress-nginx/cr.html#ingressnginxcontroller-v1-spec-hsts) IngressNginxController. +При стандартной установке TLS-соединение завершается на Ingress-контроллере, поэтому DDP не добавляет заголовок `Strict-Transport-Security`. +Чтобы включить HSTS, настройте его на Ingress-контроллере, например в параметре [`hsts`](/modules/ingress-nginx/cr.html#ingressnginxcontroller-v1-spec-hsts) IngressNginxController. {{< /alert >}} ## Конфигурация @@ -70,15 +72,17 @@ spec: xFrameOptions: "SAMEORIGIN" ``` -Параметр `enabled` включает или отключает все заголовки безопасности. При значении `true` заголовки добавляются к HTTP-ответам, при значении `false` заголовки не добавляются. +Параметр `enabled` включает или отключает все заголовки безопасности. +При значении `true` заголовки добавляются к HTTP-ответам, при значении `false` заголовки не добавляются. ## Применение -- DDP Frontend: заголовки добавляются на уровне веб-сервера для раздачи статических файлов и HTML-страниц. -- DDP Backend: заголовки добавляются через middleware для всех ответов API. +DDP Frontend добавляет заголовки на уровне веб-сервера для раздачи статических файлов и HTML-страниц. +DDP Backend добавляет заголовки через middleware для всех ответов API. {{< alert level="info" >}} -Все заголовки безопасности включены по умолчанию (`enabled: true`). При необходимости их можно отключить или настроить в параметре модуля `security.headers`. +Все заголовки безопасности включены по умолчанию (`enabled: true`). +При необходимости их можно отключить или настроить в параметре модуля `security.headers`. {{< /alert >}} ## Content Security Policy @@ -128,12 +132,16 @@ upgrade-insecure-requests Параметры `security.headers.csp` изменяют политику следующим образом: -- `allowExternalImages: true` — разрешает изображения из любых источников: в политике DDP Frontend директива `img-src` принимает значение `'self' data: *`, в политике DDP Backend — `*`. Используется, например, для иконок объектов DDP из внешних источников. -- `allowIframe: true` — задаёт значение `*` для директив `frame-src` и `frame-ancestors` в обеих политиках. Используется, например, для iframe-виджетов. +- `allowExternalImages: true` — разрешает изображения из любых источников: в политике DDP Frontend директива `img-src` принимает значение `'self' data: *`, в политике DDP Backend — `*`. + Используется, например, для иконок объектов DDP из внешних источников. +- `allowIframe: true` — задаёт значение `*` для директив `frame-src` и `frame-ancestors` в обеих политиках. + Используется, например, для iframe-виджетов. - `additionalSources` — добавляет перечисленные источники к директивам `img-src`, `connect-src`, `frame-src` и `frame-ancestors` в обеих политиках. {{< alert level="warning" >}} -При `allowIframe: true` портал можно встроить в iframe на любом сайте, а в iframe-виджетах портала можно открыть любой сайт. Заголовок `X-Frame-Options` при этом по-прежнему отправляется, но современные браузеры при наличии директивы `frame-ancestors` его не учитывают. Это снижает защиту от clickjacking-атак. +При `allowIframe: true` портал можно встроить в iframe на любом сайте, а в iframe-виджетах портала можно открыть любой сайт. +Заголовок `X-Frame-Options` при этом по-прежнему отправляется, но современные браузеры при наличии директивы `frame-ancestors` его не учитывают. +Это снижает защиту от clickjacking-атак. Чтобы разрешить только доверенные сайты, оставьте `allowIframe: false` и перечислите их в параметре `additionalSources`. {{< /alert >}} diff --git a/content/documentation/admin/security/impersonation.md b/content/documentation/admin/security/impersonation.md index 4b45767e..78d740ba 100644 --- a/content/documentation/admin/security/impersonation.md +++ b/content/documentation/admin/security/impersonation.md @@ -4,7 +4,7 @@ description: Start, end, restrict, and audit temporary sessions performed as ano weight: 25 --- -DDP (portal) supports impersonation: a user with the global `impersonate:users` permission can temporarily use the web interface as another user. +Deckhouse Development Portal (DDP, portal) supports impersonation: a user with the global `impersonate:users` permission can temporarily use the web interface as another user. {{< alert level="info" >}} Impersonation is available only for browser sign-in through a Dex session. API tokens are not supported. @@ -12,9 +12,12 @@ Impersonation is available only for browser sign-in through a Dex session. API t ## Starting and ending impersonation +To start impersonation, follow these steps: + 1. Go to "Administration" → "Users". 1. In the target user's row, click "Sign in as this user". -1. The portal switches the session to the selected user. A "Signed in as: …" banner at the bottom of the screen shows the time remaining before the session ends automatically. +1. The portal switches the session to the selected user. + A "Signed in as: …" banner at the bottom of the screen shows the time remaining before the session ends automatically. 1. To end impersonation early, click "End session" in the banner. The "Sign in as this user" button is unavailable for blocked users and your own account. diff --git a/content/documentation/admin/security/impersonation.ru.md b/content/documentation/admin/security/impersonation.ru.md index 98c9d7b1..75dd086f 100644 --- a/content/documentation/admin/security/impersonation.ru.md +++ b/content/documentation/admin/security/impersonation.ru.md @@ -4,7 +4,8 @@ description: Запуск, завершение, ограничения и ау weight: 25 --- -DDP (портал) поддерживает режим имперсонации: пользователь с глобальным разрешением `impersonate:users` может временно работать в веб-интерфейсе от имени другого пользователя. +Deckhouse Development Portal (DDP, портал) поддерживает режим имперсонации. +Пользователь с глобальным разрешением `impersonate:users` может временно работать в веб-интерфейсе от имени другого пользователя. {{< alert level="info" >}} Имперсонация доступна только при входе через браузер (сессия Dex). Запуск через API-токены не поддерживается. @@ -12,6 +13,8 @@ DDP (портал) поддерживает режим имперсонации: ## Запуск и завершение +Чтобы начать имперсонацию, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Пользователи». 1. В строке нужного пользователя нажмите «Войти как этот пользователь». 1. Портал переключит сессию на выбранного пользователя; внизу экрана появится баннер «Вы вошли как: …» с таймером до автоматического завершения. diff --git a/content/documentation/admin/security/overview.md b/content/documentation/admin/security/overview.md new file mode 100644 index 00000000..5ef97169 --- /dev/null +++ b/content/documentation/admin/security/overview.md @@ -0,0 +1,84 @@ +--- +title: Overview +weight: 10 +--- + +Deckhouse Development Portal (DDP, portal) provides a set of built-in security mechanisms for access control, credential protection, and auditing of user actions in the portal. + +## Authentication + +DDP authenticates users through the external Dex service deployed as part of Deckhouse Platform. + +Dex integrates with external authentication providers (Keycloak, LDAP, and others) through the standard OIDC and LDAP protocols. +DDP Backend uses signing keys obtained from Dex to verify JWT tokens and authenticate API requests. +Authentication is configured on the Deckhouse Platform side; no additional configuration is required in DDP. + +## Role model (RBAC) + +DDP implements a role-based access model that separates user permissions and controls the operations performed in the portal. + +The model supports a role hierarchy and permission checks at the level of the super administrator, global roles, resource roles, and entity roles. +For details, see [Role model](../rbac/). + +## Impersonation + +DDP lets a user with the `impersonate:users` permission temporarily work in the interface on behalf of another user to check access permissions and troubleshoot problems. +The session is time-limited; operations with the target user's credentials and secrets are unavailable in this mode. + +For details, see [Impersonation](../impersonation/). + +## Credentials + +DDP provides centralized and secure storage of the credentials used to integrate with external systems and services. +Credentials are stored and processed by DDP Backend using a PostgreSQL database. + +Before being saved to the database, credentials are encrypted with the AES-GCM algorithm. +DDP Backend decrypts them only when they are used in actions, datasources, or widgets. +For details, see [Credentials](../credentials/). + +## Encryption key rotation + +When you change the encryption key (the `security.secretKey` module parameter), DDP lets you re-encrypt all related data from the web interface without losing user credentials, Vault secrets, and other encrypted values. +The operation is available to users with the `rotate:encryption-key` permission. +For details, see [Encryption key rotation](../encryption-key-rotation/). + +## Trusted certificates + +DDP lets you add root and intermediate certificates (CA) or server certificates to the store. +They are used for TLS verification in outgoing HTTPS requests to external services (in actions, widgets, datasources, and other components). + +Trusted certificates are managed in the web interface, in the "Administration" → "Trusted certificates" section. +For details, see [Trusted certificates](../trusted-certificates/). + +## Audit logs + +Audit logs record user actions and help control operations performed through the portal API. +Audit logs are generated by DDP Backend. + +These logs are created automatically for HTTP requests to the API, except for `GET` requests and several requests listed in the [audit log documentation](../audit-logs/#audit-log-contents). +Each record contains information about the user, client IP address, endpoint, HTTP method, and response status. + +Audit logs are stored in the PostgreSQL database and can be viewed in the portal web interface. +You can also export audit logs to CSV from the portal interface. +For details, see [Audit logs](../audit-logs/). + +## HTTP security headers + +DDP uses standard HTTP security headers to protect the web interface and API. +They are generated and applied by DDP Frontend and DDP Backend. +The headers reduce the risk of XSS and clickjacking attacks, prevent MIME sniffing, control referrer information, and enforce secure HTTPS connections. + +The portal uses the following HTTP security headers: + +- Content Security Policy (CSP). +- X-Frame-Options. +- X-Content-Type-Options. +- X-XSS-Protection. +- Referrer-Policy. +- Permissions-Policy. +- Strict-Transport-Security (HSTS). + DDP Backend adds this header only if the TLS connection is terminated on DDP Backend itself. + In a standard installation, the TLS connection is terminated on the Ingress controller, so HSTS is configured there. + +The headers are configured in the `security.headers` parameter of the `development-platform` module: in the `development-platform` ModuleConfig (`spec.settings.security.headers`) or in the module settings in the Deckhouse web UI. +For details, see [HTTP security headers](../http-security-headers/). diff --git a/content/documentation/admin/security/overview.ru.md b/content/documentation/admin/security/overview.ru.md index 7d2ab950..25fe6e6a 100644 --- a/content/documentation/admin/security/overview.ru.md +++ b/content/documentation/admin/security/overview.ru.md @@ -10,7 +10,8 @@ Deckhouse Development Portal (DDP, портал) предоставляет на Аутентификация пользователей в DDP выполняется с использованием внешнего сервиса Dex, развернутого в составе Deckhouse Platform. Dex обеспечивает интеграцию с внешними провайдерами аутентификации (Keycloak, LDAP и другими) через стандартные протоколы OIDC и LDAP. -DDP Backend использует ключи подписи, получаемые от Dex, для проверки JWT-токенов и аутентификации запросов к API. Настройка выполняется на стороне Deckhouse Platform, дополнительная настройка в DDP не требуется. +DDP Backend использует ключи подписи, получаемые от Dex, для проверки JWT-токенов и аутентификации запросов к API. +Настройка выполняется на стороне Deckhouse Platform, дополнительная настройка в DDP не требуется. ## Ролевая модель (RBAC) @@ -21,36 +22,44 @@ DDP Backend использует ключи подписи, получаемые ## Имперсонация -DDP позволяет пользователю с разрешением `impersonate:users` временно работать в интерфейсе от имени другого пользователя для проверки прав доступа и диагностики. Сессия ограничена по времени; операции с учётными данными и секретами целевого пользователя в этом режиме недоступны. +DDP позволяет пользователю с разрешением `impersonate:users` временно работать в интерфейсе от имени другого пользователя для проверки прав доступа и диагностики. +Сессия ограничена по времени; операции с учётными данными и секретами целевого пользователя в этом режиме недоступны. Подробнее — [в документации по имперсонации](../impersonation/). ## Учётные данные -DDP обеспечивает централизованное и безопасное хранение учётных данных, используемых для интеграции с внешними системами и сервисами. Хранение и обработка учётных данных выполняются на стороне DDP Backend с использованием базы данных PostgreSQL. +DDP обеспечивает централизованное и безопасное хранение учётных данных, используемых для интеграции с внешними системами и сервисами. +Хранение и обработка учётных данных выполняются на стороне DDP Backend с использованием базы данных PostgreSQL. -Перед сохранением в базе данных учётные данные шифруются с применением алгоритма AES-GCM. Расшифровка выполняется DDP Backend только в момент использования учётных данных в действиях, источниках данных или виджетах. +Перед сохранением в базе данных учётные данные шифруются с применением алгоритма AES-GCM. +Расшифровка выполняется DDP Backend только в момент использования учётных данных в действиях, источниках данных или виджетах. Подробнее — [в документации по учётным данным](../credentials/). ## Ротация ключа шифрования -При смене ключа шифрования (параметр модуля `security.secretKey`) DDP позволяет перешифровать все связанные данные из веб-интерфейса, не теряя учётные данные пользователей, секреты Vault и другие зашифрованные значения. Операция доступна пользователям с разрешением `rotate:encryption-key`. +При смене ключа шифрования (параметр модуля `security.secretKey`) DDP позволяет перешифровать все связанные данные из веб-интерфейса, не теряя учётные данные пользователей, секреты Vault и другие зашифрованные значения. +Операция доступна пользователям с разрешением `rotate:encryption-key`. Подробнее — [в документации по ротации ключа шифрования](../encryption-key-rotation/). ## Доверенные сертификаты -DDP позволяет добавлять в хранилище корневые и промежуточные сертификаты (CA) или сертификаты серверов. Они используются при проверке TLS в исходящих HTTPS-запросах к внешним сервисам (в действиях, виджетах, источниках данных и др.). +DDP позволяет добавлять в хранилище корневые и промежуточные сертификаты (CA) или сертификаты серверов. +Они используются при проверке TLS в исходящих HTTPS-запросах к внешним сервисам (в действиях, виджетах, источниках данных и др.). Управление доверенными сертификатами осуществляется через веб-интерфейс в разделе «Администрирование» → «Доверенные сертификаты». Подробнее — [в документации по доверенным сертификатам](../trusted-certificates/). ## Аудит-логи -Аудит-логи предназначены для регистрации действий пользователей и контроля операций, выполняемых через API портала. Формирование аудит-логов выполняется на стороне DDP Backend. +Аудит-логи предназначены для регистрации действий пользователей и контроля операций, выполняемых через API портала. +Формирование аудит-логов выполняется на стороне DDP Backend. -Такие логи создаются автоматически для HTTP-запросов к API, кроме запросов `GET` и нескольких запросов, перечисленных в [документации по аудит-логам](../audit-logs/#содержимое-аудит-логов). Каждая запись содержит информацию о пользователе, IP-адресе клиента, эндпоинте, HTTP-методе и статусе ответа. +Такие логи создаются автоматически для HTTP-запросов к API, кроме запросов `GET` и нескольких запросов, перечисленных в [документации по аудит-логам](../audit-logs/#содержимое-аудит-логов). +Каждая запись содержит информацию о пользователе, IP-адресе клиента, эндпоинте, HTTP-методе и статусе ответа. -Аудит-логи сохраняются в базе данных PostgreSQL и доступны для просмотра через веб-интерфейс портала. Также возможна выгрузка аудит-логов в CSV из интерфейса портала. +Аудит-логи сохраняются в базе данных PostgreSQL и доступны для просмотра через веб-интерфейс портала. +Также возможна выгрузка аудит-логов в CSV из интерфейса портала. Подробнее — [в документации по аудит-логам](../audit-logs/). ## HTTP-заголовки безопасности @@ -67,6 +76,9 @@ DDP позволяет добавлять в хранилище корневые - X-XSS-Protection. - Referrer-Policy. - Permissions-Policy. -- Strict-Transport-Security (HSTS). DDP Backend добавляет этот заголовок, только если TLS-соединение завершается на самом DDP Backend. При стандартной установке TLS-соединение завершается на Ingress-контроллере, поэтому HSTS настраивается на нём. +- Strict-Transport-Security (HSTS). + DDP Backend добавляет этот заголовок, только если TLS-соединение завершается на самом DDP Backend. + При стандартной установке TLS-соединение завершается на Ingress-контроллере, поэтому HSTS настраивается на нём. -Заголовки настраиваются в параметре `security.headers` модуля `development-platform`: в ModuleConfig `development-platform` (`spec.settings.security.headers`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. Подробнее — [в документации по HTTP-заголовкам безопасности](../http-security-headers/). +Заголовки настраиваются в параметре `security.headers` модуля `development-platform`: в ModuleConfig `development-platform` (`spec.settings.security.headers`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. +Подробнее — [в документации по HTTP-заголовкам безопасности](../http-security-headers/). diff --git a/content/documentation/admin/security/rbac.md b/content/documentation/admin/security/rbac.md index e8f8c252..b01e9c7d 100644 --- a/content/documentation/admin/security/rbac.md +++ b/content/documentation/admin/security/rbac.md @@ -4,7 +4,8 @@ description: Roles, permissions, bindings, ownership, and access control in Deck weight: 20 --- -The Deckhouse Development Portal (DDP, portal) role model defines which actions users can perform in the portal and which objects they can access. The model controls access to the API and web interface at both the portal and individual object levels. +The Deckhouse Development Portal (DDP, portal) role model defines which actions users can perform in the portal and which objects they can access. +The model controls access to the API and web interface at both the portal and individual object levels. The role model is implemented in DDP Backend and uses a PostgreSQL database to store roles, permissions, and their relationships. @@ -16,201 +17,201 @@ The role model consists of the following components: - A role combines a set of permissions. - A role binding associates a role with users or teams. -Each DDP object has its own permissions, roles, and role bindings. Global roles, permissions, and role bindings allow operations at the portal level. +Each DDP object has its own permissions, roles, and role bindings. +Global roles, permissions, and role bindings allow operations at the portal level. {{< alert level="info" >}} -Without the required permissions, a user cannot perform operations in the portal. The system checks permissions for every operation. +Without the required permissions, a user cannot perform operations in the portal. +The system checks permissions for every operation. {{< /alert >}} ## Object types and permissions +Permissions in the role model are global or object-level. + ### Global permissions Global permissions apply across the portal and grant access to all objects of a specific type. Resources: -- `create:resources` — create resources. -- `read:resources` — view resources. -- `update:resources` — edit resources. -- `update:resources-order` — change the order and grouping of resources in the catalog. -- `delete:resources` — delete resources. +- `create:resources`: Create resources. +- `read:resources`: View resources. +- `update:resources`: Edit resources. +- `update:resources-order`: Change the order and grouping of resources in the catalog. +- `delete:resources`: Delete resources. Resource relations: -- `create:resource-relations` — create relations between resources. -- `read:resource-relations` — view relations between resources. -- `update:resource-relations` — edit relations between resources. -- `delete:resource-relations` — delete relations between resources. +- `create:resource-relations`: Create relations between resources. +- `read:resource-relations`: View relations between resources. +- `update:resource-relations`: Edit relations between resources. +- `delete:resource-relations`: Delete relations between resources. Entities: -- `create:entities` — create entities. -- `read:entities` — view entities. -- `update:entities` — edit entities. -- `delete:entities` — delete entities. +- `create:entities`: Create entities. +- `read:entities`: View entities. +- `update:entities`: Edit entities. +- `delete:entities`: Delete entities. -Data sources: +Datasources: -- `create:datasources` — create data sources. -- `read:datasources` — view data sources. -- `update:datasources` — edit data sources. -- `sync:datasources` — synchronize data sources. -- `delete:datasources` — delete data sources. +- `create:datasources`: Create datasources. +- `read:datasources`: View datasources. +- `update:datasources`: Edit datasources. +- `sync:datasources`: Synchronize datasources. +- `delete:datasources`: Delete datasources. Actions: -- `create:actions` — create actions. -- `read:actions` — view actions. -- `update:actions` — edit actions. -- `run:actions` — run actions. -- `delete:actions` — delete actions. +- `create:actions`: Create actions. +- `read:actions`: View actions. +- `update:actions`: Edit actions. +- `run:actions`: Run actions. +- `delete:actions`: Delete actions. Automations: -- `create:automations` — create automations. -- `read:automations` — view automations. -- `update:automations` — edit automations. -- `delete:automations` — delete automations. +- `create:automations`: Create automations. +- `read:automations`: View automations. +- `update:automations`: Edit automations. +- `delete:automations`: Delete automations. Workflows: -- `create:workflows` — create workflows. -- `read:workflows` — view workflows. -- `update:workflows` — edit workflows. -- `delete:workflows` — delete workflows. +- `create:workflows`: Create workflows. +- `read:workflows`: View workflows. +- `update:workflows`: Edit workflows. +- `delete:workflows`: Delete workflows. Webhooks: -- `create:webhooks` — create webhooks. -- `read:webhooks` — view webhooks. -- `update:webhooks` — edit webhooks. -- `delete:webhooks` — delete webhooks. +- `create:webhooks`: Create webhooks. +- `read:webhooks`: View webhooks. +- `update:webhooks`: Edit webhooks. +- `delete:webhooks`: Delete webhooks. Widgets: -- `create:widgets` — create widgets. -- `read:widgets` — view widgets. -- `update:widgets` — edit widgets. -- `run:widget-actions` — run widget actions. -- `delete:widgets` — delete widgets. +- `create:widgets`: Create widgets. +- `read:widgets`: View widgets. +- `update:widgets`: Edit widgets. +- `run:widget-actions`: Run widget actions. +- `delete:widgets`: Delete widgets. Dashboards: -- `create:dashboards` — create dashboards. -- `read:dashboards` — view dashboards. -- `update:dashboards` — edit dashboards. -- `delete:dashboards` — delete dashboards. -- `create:page-dashboards` — add dashboards to the "Administration", "Catalog", and "Self-Service" pages. -- `delete:page-dashboards` — remove dashboards from the "Administration", "Catalog", and "Self-Service" pages. +- `create:dashboards`: Create dashboards. +- `read:dashboards`: View dashboards. +- `update:dashboards`: Edit dashboards. +- `delete:dashboards`: Delete dashboards. +- `create:page-dashboards`: Add dashboards to the "Administration", "Catalog", and "Self-Service" pages. +- `delete:page-dashboards`: Remove dashboards from the "Administration", "Catalog", and "Self-Service" pages. MCP: -- `read:mcp-servers` — view connected MCP servers. -- `edit:mcp-servers` — connect, edit, synchronize the catalog of, and delete MCP servers. -- `read:mcp-collections` — view MCP collections. -- `edit:mcp-collections` — create, edit, and delete MCP collections. -- `read:mcp-tools` — view custom MCP tools. -- `edit:mcp-tools` — create, edit, and delete custom MCP tools. +- `read:mcp-servers`: View connected MCP servers. +- `edit:mcp-servers`: Connect, edit, synchronize the catalog of, and delete MCP servers. +- `read:mcp-collections`: View MCP collections. +- `edit:mcp-collections`: Create, edit, and delete MCP collections. +- `read:mcp-tools`: View custom MCP tools. +- `edit:mcp-tools`: Create, edit, and delete custom MCP tools. External services: -- `create:external-services` — create external services. -- `read:external-services` — view external services. -- `update:external-services` — edit external services. -- `delete:external-services` — delete external services. +- `create:external-services`: Create external services. +- `read:external-services`: View external services. +- `update:external-services`: Edit external services. +- `delete:external-services`: Delete external services. Trusted certificates: -- `create:trusted-certificates` — add trusted certificates. -- `read:trusted-certificates` — view trusted certificates. -- `update:trusted-certificates` — edit trusted certificates. -- `delete:trusted-certificates` — delete trusted certificates. +- `create:trusted-certificates`: Add trusted certificates. +- `read:trusted-certificates`: View trusted certificates. +- `update:trusted-certificates`: Edit trusted certificates. +- `delete:trusted-certificates`: Delete trusted certificates. Processes: -- `create:processes` — create processes. -- `read:processes` — view processes. -- `update:processes` — edit processes. -- `delete:processes` — delete processes. -- `control:processes` — run, pause, resume, stop, retry, and delete process instances for entities. +- `create:processes`: Create processes. +- `read:processes`: View processes. +- `update:processes`: Edit processes. +- `delete:processes`: Delete processes. +- `control:processes`: Run, pause, resume, stop, retry, and delete process instances for entities. Teams: -- `create:teams` — create teams. -- `update:teams` — edit teams. -- `delete:teams` — delete teams. -- `update:team-variables` — edit team variables. -- `edit:team-filter-rules` — configure group filtering rules during synchronization from Dex. +- `create:teams`: Create teams. +- `update:teams`: Edit teams. +- `delete:teams`: Delete teams. +- `update:team-variables`: Edit team variables. +- `edit:team-filter-rules`: Configure group filtering rules during synchronization from Dex. Datasets: -- `read:seeds` — view datasets. -- `apply:seeds` — apply datasets, run the initial setup wizard, and use the initial setup banner on the home page. -- `delete:seeds` — delete datasets. +- `read:seeds`: View datasets. +- `apply:seeds`: Apply datasets, run the initial setup wizard, and use the initial setup banner on the Home page. +- `delete:seeds`: Delete datasets. Home page mapping rules: -- `create:home-mapping-sets` — create home page mapping sets. -- `update:home-mapping-sets` — edit home page mapping sets, select the default set, and enable or disable the home page. -- `delete:home-mapping-sets` — delete home page mapping sets. +- `create:home-mapping-sets`: Create Home page mapping sets. +- `update:home-mapping-sets`: Edit Home page mapping sets, select the default set, and enable or disable the Home page. +- `delete:home-mapping-sets`: Delete Home page mapping sets. Microservice templates: -- `read:template-packs` — view template versions: the microservice creation gallery and new template version notifications. -- `edit:template-packs` — deprecate, restore, and delete template versions. -- `read:template-registries` — view template registry connections, settings, and synchronization runs. -- `edit:template-registries` — edit template registry connections and settings, and run synchronization. +- `read:template-packs`: View template versions: the microservice creation gallery and new template version notifications. +- `edit:template-packs`: Deprecate, restore, and delete template versions. +- `read:template-registries`: View template registry connections, settings, and synchronization runs. +- `edit:template-registries`: Edit template registry connections and settings, and run synchronization. Tags: -- `create:tags` — create tags. -- `update:tags` — edit tags. -- `delete:tags` — delete tags. +- `create:tags`: Create tags. +- `update:tags`: Edit tags. +- `delete:tags`: Delete tags. System alerts: -- `create:system-alerts` — create system alerts. -- `read:system-alerts` — view system alerts. -- `update:system-alerts` — edit system alerts. -- `delete:system-alerts` — delete system alerts. - -Icons: - -- `create:icons` — create icons. -- `delete:icons` — delete icons. +- `create:system-alerts`: Create system alerts. +- `read:system-alerts`: View system alerts. +- `update:system-alerts`: Edit system alerts. +- `delete:system-alerts`: Delete system alerts. -User credential types: +Icon permissions are `create:icons` (create icons) and `delete:icons` (delete icons). -- `edit:user-access-credentials-types` — create, edit, and delete credential types; configure the Vault integration, including viewing and changing the configuration and testing the connection. -- `rotate:encryption-key` — rotate the encryption key. For details, see [Encryption key rotation](../encryption-key-rotation/). +For user credential types, the `edit:user-access-credentials-types` permission is available. +It allows creating, editing, and deleting credential types and configuring the Vault integration, including viewing and changing the configuration and testing the connection. +The `rotate:encryption-key` permission allows rotating the encryption key. +For details, see [Encryption key rotation](../encryption-key-rotation/). Users: -- `edit:users` — create, block, unblock, and delete users. -- `create:users` — the permission is listed in the role form, but the portal does not check it. Creating users requires `edit:users`. -- `impersonate:users` — start and end user impersonation. For details, see [Impersonation](../impersonation/). +- `edit:users`: Create, block, unblock, and delete users. +- `create:users`: The permission is listed in the role form, but the portal does not check it. + Creating users requires `edit:users`. +- `impersonate:users`: Start and end user impersonation. For details, see [Impersonation](../impersonation/). -Roles and role bindings: +Role and role binding permissions are `edit:roles` (create, edit, and delete roles) +and `edit:role-bindings` (create, edit, and delete role bindings for any object). -- `edit:roles` — create, edit, and delete roles. -- `edit:role-bindings` — create, edit, and delete role bindings for any object. - -Audit logs: - -- `read:audit-logs` — view audit logs and export them to CSV. For details, see [Audit logs](../audit-logs/). +For audit logs, the `read:audit-logs` permission allows viewing audit logs and exporting them to CSV. +For details, see [Audit logs](../audit-logs/). {{< alert level="info" >}} -The `update:team-variables` permission allows users to edit variables only for teams of which they are members. Even a super administrator cannot change variables for a team to which they do not belong. +The `update:team-variables` permission allows users to edit variables only for teams of which they are members. +Even a super administrator cannot change variables for a team to which they do not belong. {{< /alert >}} #### Page view permissions Permissions with the `view:` prefix control access to sections of the portal interface: -- `view:admin-page` — access the "Administration" section. -- `view:self-service-page` — access the "Self-Service" section. -- `view:ai-page` — access the "AI" section. +- `view:admin-page`: Access the "Administration" section. +- `view:self-service-page`: Access the "Self-Service" section. +- `view:ai-page`: Access the "AI" section. {{< alert level="info" >}} Without the corresponding `view:` permission, a user cannot see a section in the navigation menu even if they have other permissions for objects in that section. @@ -222,72 +223,133 @@ Each object type has permissions that apply only to a specific object. For resources: -- `read:resource` — view a specific resource. -- `update:resource` — edit a specific resource. -- `delete:resource` — delete a specific resource. -- `create:entities` — create resource entities. -- `read:entities` — view resource entities. -- `update:entities` — edit resource entities. -- `delete:entities` — delete resource entities. -- `run:actions` — run actions for resource entities. -- `control:processes` — control processes for resource entities. -- `edit:role-bindings` — edit role bindings for the resource. +- `read:resource`: View a specific resource. +- `update:resource`: Edit a specific resource. +- `delete:resource`: Delete a specific resource. +- `create:entities`: Create resource entities. +- `read:entities`: View resource entities. +- `update:entities`: Edit resource entities. +- `delete:entities`: Delete resource entities. +- `run:actions`: Run actions for resource entities. +- `control:processes`: Control processes for resource entities. +- `edit:role-bindings`: Edit role bindings for the resource. For entities: -- `read:entity` — view a specific entity. -- `update:entity` — edit a specific entity. -- `delete:entity` — delete a specific entity. -- `run:actions` — run actions for the entity. -- `control:processes` — control processes for the entity. -- `edit:role-bindings` — edit role bindings for the entity. +- `read:entity`: View a specific entity. +- `update:entity`: Edit a specific entity. +- `delete:entity`: Delete a specific entity. +- `run:actions`: Run actions for the entity. +- `control:processes`: Control processes for the entity. +- `edit:role-bindings`: Edit role bindings for the entity. -For actions, automations, data sources, workflows, webhooks, widgets, dashboards, and processes: +For actions, automations, datasources, workflows, webhooks, widgets, dashboards, and processes: -- `read:[object-type]` — view the object, for example, `read:action`. -- `update:[object-type]` — edit the object. -- `delete:[object-type]` — delete the object. -- `edit:role-bindings` — edit role bindings for the object. +- `read:[object-type]`: View the object, for example, `read:action`. +- `update:[object-type]`: Edit the object. +- `delete:[object-type]`: Delete the object. +- `edit:role-bindings`: Edit role bindings for the object. Some object types have additional permissions: -- `run:action` — run a specific action. -- `sync:datasource` — synchronize a specific data source. -- `run:widget-action` — run actions of a specific widget. +- `run:action`: Run a specific action. +- `sync:datasource`: Synchronize a specific datasource. +- `run:widget-action`: Run actions of a specific widget. #### MCP collections -For MCP collections: +For MCP collections, the `use:mcp-collections` permission allows calling collection tools in the AI assistant and through the portal MCP server, +and the `edit:role-bindings` permission allows editing role bindings for the collection. + +#### AI provider templates + +For a specific template, the `read:ai-provider-template`, `edit:ai-provider-template`, `use:ai-provider-template`, and `edit:role-bindings` permissions are used. +The global `use:ai-provider-templates` permission allows using templates across the installation. + +#### AI agents + +For a specific connection, the `read:ai-agent`, `edit:ai-agent`, `use:ai-agent`, and `edit:role-bindings` permissions are used. +For an agent source, the `read:ai-agent-source`, `edit:ai-agent-source`, and `edit:role-bindings` permissions are used. + +Agent usage is not limited to the owner. +Grant `use:ai-agent` to the required users or teams through a role binding. +Ownership and membership in the owner team grant permissions when the `owner-is-admin` setting is enabled. + +#### Agent skills + +For a skill, the `read:agent-skill`, `edit:agent-skill`, and `edit:role-bindings` permissions are used. +For a skill source, the `read:agent-skill-source`, `edit:agent-skill-source`, and `edit:role-bindings` permissions are used. -- `use:mcp-collections` — call collection tools in the AI assistant and through the portal MCP server. -- `edit:role-bindings` — edit role bindings for the collection. +A skill assigned to an agent does not grant additional permissions. +Reading a skill during a run requires the `get_skill` tool, available through the MCP collections of the agent and of the user who started the run. + +#### Workspaces and templates + +Permissions can be granted on an individual object: + +| Object | Permissions | +| --- | --- | +| Workspace | `read:workspace`, `update:workspace`, `cancel:workspace`, `delete:workspace`, `edit:role-bindings` | +| Template | `read:workspace-template`, `edit:workspace-template`, `use:workspace-template`, `edit:role-bindings` | +| Template source | `read:workspace-template-source`, `edit:workspace-template-source`, `edit:role-bindings` | + +`update:workspace` allows starting, updating, and opening the IDE, and `cancel:workspace` allows stopping. +Retrying an operation also checks the permission for its type. +Creating a workspace always requires the global `create:workspaces` permission and the permission to use the selected template. + +Attaching a workspace to a chat and running process jobs require the user's own workspace. +A process also requires a binding to its entity. + +### Action run records + +Permissions for an action run record are checked through the object it belongs to: the entity, its resource, or the action. +Super administrator and global permissions apply as usual. + +| Operation | Process record | Action record for an entity | Action record without an entity | +| --- | --- | --- | --- | +| Viewing the record and its visibility in the list | Global or resource-level `read:entities`, `read:entity`, or entity ownership | Global or resource-level `read:entities`, `read:entity`, or entity ownership | Global `read:actions` or `read:action` on the action | +| Cancelling, restarting, and deleting | `control:processes` globally, on the resource, or on the entity | `run:actions` globally, on the resource, or on the entity | Global `run:actions` or `run:action` on the action | + +The run initiator and approvers always see the record, for example, in the "My activities" panel, but can manage it only with the permissions from the table. +Only a user from the list of [approvers](../../actions/overview/#approval) can approve a run, and only the initiator can delete a temporary response. + +Without the required permission, the record management buttons are disabled. ## Permission check hierarchy -The role model is hierarchical. When processing a request, DDP Backend checks access rights in a specific order. For example, to determine whether a user can edit a specific entity, the backend performs the following checks: +The role model is hierarchical. +When processing a request, DDP Backend checks access rights in a specific order. +For example, to determine whether a user can edit a specific entity, the backend performs the following checks: ### 1. Super administrator -- Check whether the user is a super administrator. If so, stop further checks. +The portal checks whether the user is a super administrator. If so, no further checks are performed. ### 2. Global roles +At this step, the portal performs the following checks: + - Read the user's group membership from the JWT. - Find global roles for the user and their groups through global role bindings. -- Check permissions in the global roles. If any global role bound to the user or their team contains `update:entities`, the user can edit any entity in DDP, and no further checks are performed. +- Check permissions in the global roles. + If any global role bound to the user or their team contains `update:entities`, the user can edit any entity in DDP, and no further checks are performed. ### 3. Resource roles -- Find resource roles for the user and their groups through role bindings for the specific resource. -- Check permissions in the resource roles. If any resource role bound to the user or their team contains `update:entities`, the user can edit any entity of that resource, and no further checks are performed. +The portal finds resource roles for the user and their groups through role bindings for the specific resource. +Then it checks permissions in the resource roles. +If any resource role bound to the user or their team contains `update:entities`, the user can edit any entity of that resource, and no further checks are performed. ### 4. Entity roles -- Find entity roles for the user and their groups through role bindings for the specific entity. -- Check permissions in the entity roles. If any entity role bound to the user or their team contains `update:entity`, the user can edit that entity. +The portal finds entity roles for the user and their groups through role bindings for the specific entity. +Then it checks permissions in the entity roles. +If any entity role bound to the user or their team contains `update:entity`, the user can edit that entity. ### 5. Object ownership when ownerIsAdmin is enabled +At this step, the portal performs the following checks: + - Check whether the user owns the object. - Check whether the user belongs to the team that owns the object. - If the user owns the object or belongs to its owner team, grant the user all administrator permissions for the object. @@ -295,7 +357,8 @@ The role model is hierarchical. When processing a request, DDP Backend checks ac If the required permission is not found at any level, the action is denied. {{< alert level="info" >}} -Ownership is checked only when `ownerIsAdmin` is enabled in the portal configuration. For details, see [Object ownership](#object-ownership). +Ownership is checked only when `ownerIsAdmin` is enabled in the portal configuration. +For details, see [Object ownership](#object-ownership). {{< /alert >}} ## Object ownership @@ -315,9 +378,8 @@ When `ownerIsAdmin` is enabled, an object owner receives all administrator permi ### OwnerAsAdmin option The `ownerIsAdmin` option controls access rights for object owners. - -- "Enabled (`true`)" — object owners receive full administrator permissions for their objects. -- "Disabled (`false`)" — object owners receive no automatic permissions; roles alone control access. +When it is "Enabled (`true`)", object owners receive full administrator permissions for their objects. +When it is "Disabled (`false`)", object owners receive no automatic permissions, and roles alone control access. {{< alert level="info" >}} A portal administrator must configure `ownerIsAdmin` in the configuration file. The option is disabled by default. @@ -325,13 +387,17 @@ A portal administrator must configure `ownerIsAdmin` in the configuration file. ### Automatic owner assignment on creation -When a user creates an object, such as an action, data source, widget, or resource, the portal automatically assigns the current user as its owner. The owner can be reassigned, or the object can be created without an owner. +When a user creates an object, such as an action, datasource, widget, or resource, the portal automatically assigns the current user as its owner. +The owner can be reassigned, or the object can be created without an owner. ### Ownership examples +The following examples show how ownership affects access rights. + #### Resource ownership -When a user creates a resource, they automatically become its owner. If `ownerIsAdmin` is enabled, the user receives all administrator permissions for that resource, including: +When a user creates a resource, they automatically become its owner. +If `ownerIsAdmin` is enabled, the user receives all administrator permissions for that resource, including: - Managing resource entities. - Configuring role bindings. @@ -351,53 +417,66 @@ If a team owns an object and `ownerIsAdmin` is enabled, all team members receive ## Default role -The portal allows one global role to be set as the default. Its permissions apply to all authenticated users. Configure the default role under "Administration" → "RBAC" by using the switch in the "Roles" table. +The portal allows one global role to be set as the default. +Its permissions apply to all authenticated users. +Configure the default role under "Administration" → "RBAC" by using the switch in the "Roles" table. Only a global role can be set as the default. ## Teams -Teams group users and allow roles to be assigned collectively. A user can belong to multiple teams, and their permissions are combined from all teams of which they are a member. +Teams group users and allow roles to be assigned collectively. +A user can belong to multiple teams, and their permissions are combined from all teams of which they are a member. {{< alert level="info" >}} -Teams and team membership are synchronized from the external authentication system, Dex, each time a user signs in. You can also create, edit, and delete teams in the web interface under "Administration" → "Teams" with the `create:teams`, `update:teams`, and `delete:teams` permissions. Team membership changed manually is overwritten from Dex the next time the user signs in. +Teams and team membership are synchronized from the external authentication system, Dex, each time a user signs in. +You can also create, edit, and delete teams in the web interface under "Administration" → "Teams" with the `create:teams`, `update:teams`, and `delete:teams` permissions. +Team membership changed manually is overwritten from Dex the next time the user signs in. {{< /alert >}} ## Configuring roles and managing access +Roles and role bindings are configured in "Administration" → "RBAC". + ### Creating a role +To create a role, follow these steps: + 1. Go to "Administration" → "RBAC". 1. Select the "Roles" tab. 1. Click "Create role". 1. Complete the form: - - Name — unique role name. - - Description — role purpose. - - Object type — select the scope of the role: - - `Global` — global permissions. - - `Resources` — resource-level permissions. - - `Entities` — entity-level permissions. - - `Actions` — action-level permissions. + - Name: Unique role name. + - Description: Role purpose. + - Object type: Select the scope of the role: + - `Global`: Global permissions. + - `Resources`: Resource-level permissions. + - `Entities`: Entity-level permissions. + - `Actions`: Action-level permissions. - Other object types. - - Permissions — select the required permissions. + - Permissions: Select the required permissions. 1. Click "Save". ### Assigning a role to users +To assign a role to users, follow these steps: + 1. Go to "Administration" → "RBAC". 1. Select the "Role bindings" tab. 1. Click "Create role binding". 1. Complete the form: - - Name — role binding name. - - Description — role binding purpose. - - Role — select the role. - - Object — select a specific object if the role is not global. - - Users — add the users to whom the role is assigned. - - Teams — add the teams to which the role is assigned. + - Name: Role binding name. + - Description: Role binding purpose. + - Role: Select the role. + - Object: Select a specific object if the role is not global. + - Users: Add the users to whom the role is assigned. + - Teams: Add the teams to which the role is assigned. 1. Click "Save". ### Configuring the default role +To set the default role, follow these steps: + 1. Go to "Administration" → "RBAC". 1. Select the "Roles" tab. 1. Find the global role to set as the default. @@ -410,6 +489,8 @@ Only a global role can be the default. ### Editing roles +To edit a role, follow these steps: + 1. Go to "Administration" → "RBAC". 1. Select the "Roles" tab. 1. Find the required role and click "Edit". @@ -420,6 +501,8 @@ Only a global role can be the default. ### Editing role bindings +To edit a role binding, follow these steps: + 1. Go to "Administration" → "RBAC". 1. Select the "Role bindings" tab. 1. Find the required role binding and click "Edit". @@ -431,6 +514,8 @@ Only a global role can be the default. ### Deleting roles and bindings +To delete a role or binding, follow these steps: + 1. Go to the corresponding section. 1. Find the required role or binding. 1. Click "Delete". @@ -442,23 +527,31 @@ Deleting a role also deletes all associated role bindings. ### Viewing permissions for a user or team +You can view the effective permissions of a user or a team. + #### For a user +To view user permissions, follow these steps: + 1. Go to "Administration" → "Users". 1. In the target user's row, click "View user permissions". 1. In the "User permissions" dialog, review: - - "Global permissions" — the user's global permissions. - - "Permissions for ..." — object-level permissions, one block per object. Each block shows the object type, the object name, and the role binding that grants the permissions. + - "Global permissions": The user's global permissions. + - "Permissions for ...": Object-level permissions, one block per object. + Each block shows the object type, the object name, and the role binding that grants the permissions. To filter the permissions, use the "Search" field. #### For a team +To view team permissions, follow these steps: + 1. Go to "Administration" → "Teams". 1. In the target team's row, click "View team permissions". 1. In the "Team permissions" dialog, review: - - "Global permissions" — the team's global permissions. - - "Permissions for ..." — object-level permissions, one block per object. Each block shows the object type, the object name, and the role binding that grants the permissions. + - "Global permissions": The team's global permissions. + - "Permissions for ...": Object-level permissions, one block per object. + Each block shows the object type, the object name, and the role binding that grants the permissions. To filter the permissions, use the "Search" field. @@ -466,19 +559,53 @@ Deleting a role also deletes all associated role bindings. Team membership is synchronized from the external authentication system, Dex. {{< /alert >}} -### Role presets +### Role configuration examples + +The following examples show how to configure typical roles. + +#### "System administrator" role + +Configure the role as follows: + +- Type: `Global`. +- Permissions: all global permissions. Use the "Admin" preset. +- Assignment: super administrators. + +#### "Resource administrator" role + +Configure the role as follows: + +- Type: `Resources`. +- Permissions: all resource permissions. Use the "Resource admin" preset. +- Assignment: a specific resource and the "Administrators" team. + +#### "Process operator" role + +Configure the role as follows: + +- Type: `Processes`. +- Permissions: `delete:process`, `edit:role-bindings`, `read:process`, `update:process`. Use the "Process admin" preset. +- Assignment: the "Process operators" team. + +## Role presets The portal provides role presets for common access scenarios. -#### Global presets +### Global presets -##### "Admin" preset +The following presets are available for global roles. + +#### "Admin" preset + +The preset has the following settings: - Type: `Global`. - Permissions: all global permissions. - Purpose: system administrators. -##### "Viewer" preset +#### "Viewer" preset + +The preset has the following settings: - Type: `Global`. - Permissions: @@ -491,7 +618,9 @@ The portal provides role presets for common access scenarios. - `read:audit-logs`, `view:admin-page`, `view:ai-page`, `view:self-service-page`. - Purpose: users with read-only access. -##### "Developer" preset +#### "Developer" preset + +The preset has the following settings: - Type: `Global`. - Permissions: @@ -499,41 +628,56 @@ The portal provides role presets for common access scenarios. - `read:processes`, `read:template-packs`, `read:widgets`, `read:workflows`. - `run:actions`, `run:widget-actions`, `control:processes`. - `update:team-variables`. -- Purpose: developers who need to view information and run actions but do not need to create, edit, or delete objects. Developers see only entities to which role bindings at the resource or entity level grant them access. +- Purpose: developers who need to view information and run actions but do not need to create, edit, or delete objects. + Developers see only entities to which role bindings at the resource or entity level grant them access. + +#### "Platform engineer" preset -##### "Platform engineer" preset +The preset has the following settings: - Type: `Global`. - Permissions: - Catalog: all permissions for resources, resource relations, and entities, including `update:resources-order`. - - "Self-Service" page: `view:self-service-page` and all permissions for actions, automations, dashboards, data sources, webhooks, workflows, processes, and widgets, including `run:actions`, `sync:datasources`, `control:processes`, `run:widget-actions`, `create:page-dashboards`, and `delete:page-dashboards`. + - "Self-Service" page: `view:self-service-page` and all permissions for actions, automations, dashboards, datasources, webhooks, workflows, processes, and widgets, including `run:actions`, `sync:datasources`, `control:processes`, `run:widget-actions`, `create:page-dashboards`, and `delete:page-dashboards`. - `update:team-variables`. - "AI" page: `view:ai-page`, `read:mcp-collections`, `edit:mcp-collections`, `read:mcp-servers`, `edit:mcp-servers`, `read:mcp-tools`, and `edit:mcp-tools`. -- Purpose: engineers who configure the portal, including processes, data sources, and dashboards. +- Purpose: engineers who configure the portal, including processes, datasources, and dashboards. + +### Process presets -#### Process presets +The following presets are available for process-level roles. -##### "Process admin" preset +#### "Process admin" preset + +The preset has the following settings: - Type: `Processes`. - Permissions: `delete:process`, `edit:role-bindings`, `read:process`, `update:process`. - Purpose: process administrators. -##### "Process viewer" preset +#### "Process viewer" preset + +The preset has the following settings: - Type: `Processes`. - Permissions: `read:process`. - Purpose: users with permission to view processes. -#### Resource presets +### Resource presets + +The following preset is available for resource-level roles. -##### "Resource admin" preset +#### "Resource admin" preset + +The preset has the following settings: - Type: `Resources`. - Permissions: all resource permissions. - Purpose: administrators of specific resources. -#### Using presets +### Using presets + +To create a role from a preset, follow these steps: 1. Go to "Administration" → "RBAC". 1. Select the "Roles" tab. @@ -545,30 +689,14 @@ The portal provides role presets for common access scenarios. - Add or remove permissions. 1. Click "Save". -### Role configuration examples - -#### "System administrator" role - -- Type: `Global`. -- Permissions: all global permissions. Use the "Admin" preset. -- Assignment: super administrators. - -#### "Resource administrator" role - -- Type: `Resources`. -- Permissions: all resource permissions. Use the "Resource admin" preset. -- Assignment: a specific resource and the "Administrators" team. - -#### "Process operator" role - -- Type: `Processes`. -- Permissions: `delete:process`, `edit:role-bindings`, `read:process`, `update:process`. Use the "Process admin" preset. -- Assignment: the "Process operators" team. - ## Best practices +Follow these recommendations when configuring the role model. + ### Creating roles +When creating roles, follow these recommendations: + 1. Determine the access level: decide whether you need a global role or a role for a specific object. 1. Select the required permissions according to the principle of least privilege. 1. Create the role in the corresponding administration section. @@ -576,6 +704,8 @@ The portal provides role presets for common access scenarios. ### Managing access +When managing access, follow these recommendations: + 1. Use teams to manage access for groups. 1. Use default roles to grant basic permissions to all users. 1. Follow the hierarchy: use global roles for broad access and object roles for specific access. @@ -583,6 +713,8 @@ The portal provides role presets for common access scenarios. ### Security +To keep access secure, follow these recommendations: + 1. Apply the principle of least privilege: grant only the required permissions. 1. Audit regularly: review assigned roles and their use. 1. Use teams instead of individual assignments to simplify management. diff --git a/content/documentation/admin/security/rbac.ru.md b/content/documentation/admin/security/rbac.ru.md index 91322620..19db706a 100644 --- a/content/documentation/admin/security/rbac.ru.md +++ b/content/documentation/admin/security/rbac.ru.md @@ -4,7 +4,8 @@ description: Роли, разрешения, привязки ролей, вла weight: 20 --- -Ролевая модель Deckhouse Development Portal (DDP, портал) определяет, какие действия пользователи могут выполнять в портале и к каким объектам они имеют доступ. Модель используется для разграничения прав при работе с API и веб-интерфейсом и применяется на уровне портала в целом и отдельных объектов. +Ролевая модель Deckhouse Development Portal (DDP, портал) определяет, какие действия пользователи могут выполнять в портале и к каким объектам они имеют доступ. +Модель используется для разграничения прав при работе с API и веб-интерфейсом и применяется на уровне портала в целом и отдельных объектов. Ролевая модель реализована в DDP Backend и использует базу данных PostgreSQL для хранения ролей, разрешений и их связей. @@ -16,14 +17,18 @@ weight: 20 - «Роль» — объединяет в себе набор тех или иных разрешений. - «Привязка роли» — связывает роль с пользователями или командами. -Для каждого объекта DDP существует свой набор разрешений, ролей и привязок ролей. Также есть глобальные роли, разрешения и привязки ролей, которые разрешают операции на глобальном уровне. +Для каждого объекта DDP существует свой набор разрешений, ролей и привязок ролей. +Также есть глобальные роли, разрешения и привязки ролей, которые разрешают операции на глобальном уровне. {{< alert level="info" >}} -Если у пользователя нет соответствующих разрешений, он не сможет выполнять никакие операции на портале. Система проверяет разрешения для каждой операции. +Если у пользователя нет соответствующих разрешений, он не сможет выполнять никакие операции на портале. +Система проверяет разрешения для каждой операции. {{< /alert >}} ## Типы объектов и разрешения +Разрешения в ролевой модели делятся на глобальные и объектные. + ### Глобальные разрешения Глобальные разрешения действуют на уровне всего портала и предоставляют доступ ко всем объектам определённого типа. @@ -165,21 +170,23 @@ AI-агенты и навыки: Наборы данных: - `read:seeds` — просмотр наборов данных. -- `apply:seeds` — применение наборов данных, мастер первоначальной настройки и баннер первоначальной настройки на главной. +- `apply:seeds` — применение наборов данных, мастер первоначальной настройки и баннер первоначальной настройки на главной странице. - `delete:seeds` — удаление наборов данных. -Правила маппинга главной: +Правила маппинга главной страницы: -- `create:home-mapping-sets` — создание наборов маппинга главной. -- `update:home-mapping-sets` — изменение наборов маппинга главной, выбор набора по умолчанию, включение и выключение главной. Подробнее — [в документации по правилам маппинга](../home/mapping/). -- `delete:home-mapping-sets` — удаление наборов маппинга главной. +- `create:home-mapping-sets` — создание наборов маппинга главной страницы. +- `update:home-mapping-sets` — изменение наборов маппинга главной страницы, выбор набора по умолчанию, включение и выключение главной страницы. + Подробнее — [в документации по правилам маппинга](../home/mapping/). +- `delete:home-mapping-sets` — удаление наборов маппинга главной страницы. Шаблоны микросервисов: - `read:template-packs` — просмотр версий шаблонов: галерея создания микросервиса и уведомления о новой версии шаблона. - `edit:template-packs` — отзыв, возврат и удаление версий шаблонов. - `read:template-registries` — просмотр подключений, настроек и запусков синхронизации реестра шаблонов. -- `edit:template-registries` — изменение подключений и настроек реестра шаблонов, запуск синхронизации. Подробнее — [в документации по реестру шаблонов](../templates/registry/). +- `edit:template-registries` — изменение подключений и настроек реестра шаблонов, запуск синхронизации. + Подробнее — [в документации по реестру шаблонов](../templates/registry/). Теги: @@ -194,33 +201,30 @@ AI-агенты и навыки: - `update:system-alerts` — редактирование системных оповещений. - `delete:system-alerts` — удаление системных оповещений. -Иконки: - -- `create:icons` — создание иконок. -- `delete:icons` — удаление иконок. - -Типы учётных данных: +Для иконок предусмотрены разрешения `create:icons` (создание иконок) и `delete:icons` (удаление иконок). -- `edit:user-access-credentials-types` — создание, редактирование и удаление типов учётных данных; настройка интеграции с Vault (просмотр и изменение конфигурации, проверка подключения). -- `rotate:encryption-key` — ротация ключа шифрования. Подробнее — [в документации по ротации ключа шифрования](../encryption-key-rotation/). +Для типов учётных данных предусмотрено разрешение `edit:user-access-credentials-types`. +Оно позволяет создавать, редактировать и удалять типы учётных данных, а также настраивать интеграцию с Vault, включая просмотр и изменение конфигурации и проверку подключения. +Разрешение `rotate:encryption-key` позволяет выполнять ротацию ключа шифрования. +Подробнее — [в документации по ротации ключа шифрования](../encryption-key-rotation/). Пользователи: - `edit:users` — создание, блокировка, разблокировка и удаление пользователей, управление AI-провайдерами сервис-аккаунтов и просмотр AI-провайдеров всех пользователей. -- `create:users` — разрешение есть в списке разрешений роли, но портал его не проверяет. Для создания пользователей требуется `edit:users`. -- `impersonate:users` — запуск и завершение имперсонации пользователей. Подробнее — [в документации по имперсонации](../impersonation/). - -Роли и привязки ролей: - -- `edit:roles` — создание, редактирование и удаление ролей. -- `edit:role-bindings` — создание, редактирование и удаление привязок ролей для любых объектов. +- `create:users` — разрешение есть в списке разрешений роли, но портал его не проверяет. + Для создания пользователей требуется `edit:users`. +- `impersonate:users` — запуск и завершение имперсонации пользователей. + Подробнее — [в документации по имперсонации](../impersonation/). -Аудит-логи: +Для ролей и привязок ролей предусмотрены разрешения `edit:roles` (создание, редактирование и удаление ролей) +и `edit:role-bindings` (создание, редактирование и удаление привязок ролей для любых объектов). -- `read:audit-logs` — просмотр аудит-логов и их выгрузка в CSV. Подробнее — [в документации по аудит-логам](../audit-logs/). +Для аудит-логов предусмотрено разрешение `read:audit-logs` — просмотр аудит-логов и их выгрузка в CSV. +Подробнее — [в документации по аудит-логам](../audit-logs/). {{< alert level="info" >}} -Разрешение `update:team-variables` позволяет редактировать переменные только тех команд, участником которых является пользователь. Даже супер-администратор не сможет изменить переменные команд, в которых не состоит. +Разрешение `update:team-variables` позволяет редактировать переменные только тех команд, участником которых является пользователь. +Даже супер-администратор не сможет изменить переменные команд, в которых не состоит. {{< /alert >}} #### Разрешения на просмотр страниц @@ -229,7 +233,8 @@ AI-агенты и навыки: - `view:admin-page` — доступ к разделу «Администрирование». - `view:self-service-page` — доступ к разделу «Самообслуживание». -- `view:ai-page` — доступ к разделу «AI». Для работы с AI-ассистентом требуется доступ хотя бы к одному включённому агенту через `use:ai-agents`, `use:ai-agent` или владение при включённом `owner-is-admin`. +- `view:ai-page` — доступ к разделу «AI». + Для работы с AI-ассистентом требуется доступ хотя бы к одному включённому агенту через `use:ai-agents`, `use:ai-agent` или владение при включённом `owner-is-admin`. {{< alert level="info" >}} Без соответствующих `view:` разрешений пользователь не сможет увидеть разделы в навигационном меню, даже если у него есть другие разрешения для работы с объектами в этих разделах. @@ -276,26 +281,30 @@ AI-агенты и навыки: #### MCP-коллекции -Для MCP-коллекций действуют разрешения: - -- `use:mcp-collections` — вызов инструментов коллекции в AI-ассистенте и через MCP-сервер портала. -- `edit:role-bindings` — редактирование привязок ролей для коллекции. +Для MCP-коллекций действуют разрешения `use:mcp-collections` (вызов инструментов коллекции в AI-ассистенте и через MCP-сервер портала) +и `edit:role-bindings` (редактирование привязок ролей для коллекции). #### Шаблоны AI-провайдеров -Для конкретного шаблона используются `read:ai-provider-template`, `edit:ai-provider-template`, `use:ai-provider-template` и `edit:role-bindings`. Глобальное `use:ai-provider-templates` разрешает использование шаблонов на уровне установки. +Для конкретного шаблона используются `read:ai-provider-template`, `edit:ai-provider-template`, `use:ai-provider-template` и `edit:role-bindings`. +Глобальное `use:ai-provider-templates` разрешает использование шаблонов на уровне установки. #### AI-агенты -Для конкретного подключения используются `read:ai-agent`, `edit:ai-agent`, `use:ai-agent` и `edit:role-bindings`. Для источника — `read:ai-agent-source`, `edit:ai-agent-source` и `edit:role-bindings`. +Для конкретного подключения используются `read:ai-agent`, `edit:ai-agent`, `use:ai-agent` и `edit:role-bindings`. +Для источника — `read:ai-agent-source`, `edit:ai-agent-source` и `edit:role-bindings`. -Использование агента не ограничено владельцем: выдайте `use:ai-agent` нужным пользователям или командам через привязку роли. Владение и участие в команде-владельце предоставляют права при включённой настройке `owner-is-admin`. +Использование агента не ограничено владельцем. +Выдайте `use:ai-agent` нужным пользователям или командам через привязку роли. +Владение и участие в команде-владельце предоставляют права при включённой настройке `owner-is-admin`. #### Навыки агентов -Для навыка используются `read:agent-skill`, `edit:agent-skill` и `edit:role-bindings`. Для источника навыков — `read:agent-skill-source`, `edit:agent-skill-source` и `edit:role-bindings`. +Для навыка используются `read:agent-skill`, `edit:agent-skill` и `edit:role-bindings`. +Для источника навыков — `read:agent-skill-source`, `edit:agent-skill-source` и `edit:role-bindings`. -Назначенный агенту навык не выдаёт дополнительных разрешений. Чтение навыка в запуске требует инструмента `get_skill`, доступного через MCP-коллекции агента и запускающего пользователя. +Назначенный агенту навык не выдаёт дополнительных разрешений. +Чтение навыка в запуске требует инструмента `get_skill`, доступного через MCP-коллекции агента и запускающего пользователя. #### Рабочие пространства и шаблоны @@ -307,11 +316,15 @@ AI-агенты и навыки: | Шаблон | `read:workspace-template`, `edit:workspace-template`, `use:workspace-template`, `edit:role-bindings` | | Источник шаблонов | `read:workspace-template-source`, `edit:workspace-template-source`, `edit:role-bindings` | -`update:workspace` разрешает запуск, обновление и открытие IDE, `cancel:workspace` — остановку. Повтор операции дополнительно проверяет право на её вид. Создание рабочего пространства всегда требует глобального `create:workspaces` и права использования выбранного шаблона. +`update:workspace` разрешает запуск, обновление и открытие IDE, `cancel:workspace` — остановку. +Повтор операции дополнительно проверяет право на её вид. +Создание рабочего пространства всегда требует глобального `create:workspaces` и права использования выбранного шаблона. -Прикрепление к чату и выполнение заданий процесса требуют пространства самого пользователя. Для процесса также необходима привязка к его сущности. +Прикрепление к чату и выполнение заданий процесса требуют пространства самого пользователя. +Для процесса также необходима привязка к его сущности. Для других объектов (действия, автоматизации, процессы, вебхуки, виджеты, дашборды, внешние сервисы и т. д.): + - `read:[object-type]` — просмотр объекта. - `update:[object-type]` — редактирование объекта. - `delete:[object-type]` — удаление объекта. @@ -319,42 +332,53 @@ AI-агенты и навыки: ### Записи запусков действий -Права на запись запуска действия проверяются через объект, к которому она относится: сущность, её ресурс или действие. Супер-администратор и глобальные разрешения действуют как обычно. +Права на запись запуска действия проверяются через объект, к которому она относится: сущность, её ресурс или действие. +Супер-администратор и глобальные разрешения действуют как обычно. | Операция | Запись процесса | Запись действия, запущенного для сущности | Запись действия без сущности | | --- | --- | --- | --- | | Просмотр записи и её видимость в списке | `read:entities` глобально или на ресурс, `read:entity`, владение сущностью | `read:entities` глобально или на ресурс, `read:entity`, владение сущностью | `read:actions` глобально, `read:action` на действие | | Отмена, перезапуск и удаление | `control:processes` глобально, на ресурс или на сущность | `run:actions` глобально, на ресурс или на сущность | `run:actions` глобально, `run:action` на действие | -Инициатор запуска и подтверждающие всегда видят запись, например в панели «Мои активности», но управлять ею могут только с разрешениями из таблицы. Подтвердить запуск может только пользователь из списка [подтверждающих](../../actions/overview/#подтверждение), а удалить временный ответ — только инициатор. +Инициатор запуска и подтверждающие всегда видят запись, например в панели «Мои активности», но управлять ею могут только с разрешениями из таблицы. +Подтвердить запуск может только пользователь из списка [подтверждающих](../../actions/overview/#подтверждение), а удалить временный ответ — только инициатор. Без нужного разрешения кнопки управления записью неактивны. ## Иерархия проверки разрешений -Ролевая модель иерархическая, при обработке запроса DDP Backend проверяет права доступа в определенном порядке. Например, чтобы проверить, может ли пользователь изменять конкретную сущность, выполняется следующая последовательность действий: +Ролевая модель иерархическая, при обработке запроса DDP Backend проверяет права доступа в определённом порядке. +Например, чтобы проверить, может ли пользователь изменять конкретную сущность, выполняется следующая последовательность действий: ### 1. Супер-администратор -- Проверка, является ли пользователь супер-администратором. Если пользователь является супер-администратором, то дальнейшие проверки не производятся. +Проверяется, является ли пользователь супер-администратором. Если является, дальнейшие проверки не производятся. ### 2. Глобальные роли +На этом шаге выполняются следующие проверки: + - Проверка по JWT-токену пользователя, в каких группах он состоит. - Поиск глобальных ролей для пользователя и его групп по привязкам глобальных ролей. - Проверка разрешений в глобальных ролях: если в одной из глобальных ролей, привязанных к пользователю, либо его команде, присутствует разрешение `update:entities`, то пользователь будет обладать правами на редактирование любых сущностей в DDP, дальнейшие проверки не производятся. ### 3. Роли ресурса -- Поиск ролей ресурса для пользователя и его групп по привязкам ролей конкретного ресурса. -- Проверка разрешений в ролях ресурса: если в одной из ролей ресурса, привязанных к пользователю, либо его команде, присутствует разрешение `update:entities`, то пользователь будет обладать правами на редактирование любых сущностей данного ресурса, дальнейшие проверки не производятся. +Выполняется поиск ролей ресурса для пользователя и его групп по привязкам ролей конкретного ресурса. +Затем проверяются разрешения в ролях ресурса. +Если в одной из ролей ресурса, привязанных к пользователю или его команде, присутствует разрешение `update:entities`, +пользователь получает права на редактирование любых сущностей данного ресурса, и дальнейшие проверки не производятся. ### 4. Роли сущностей -- Поиск ролей сущностей для пользователя и его групп по привязкам ролей конкретной сущности. -- Проверка разрешений в ролях сущности: если в одной из ролей сущности, привязанных к пользователю, либо его команде, присутствует разрешение `update:entity`, то пользователь будет обладать правами на редактирование данной сущности. +Выполняется поиск ролей сущностей для пользователя и его групп по привязкам ролей конкретной сущности. +Затем проверяются разрешения в ролях сущности. +Если в одной из ролей сущности, привязанных к пользователю или его команде, присутствует разрешение `update:entity`, +пользователь получает права на редактирование данной сущности. -### 5. Владение объектом (при включенной опции ownerIsAdmin) +### 5. Владение объектом (при включённой опции ownerIsAdmin) + +На этом шаге выполняются следующие проверки: - Проверка, является ли пользователь владельцем объекта. - Проверка, состоит ли пользователь в команде-владельце объекта. @@ -363,7 +387,8 @@ AI-агенты и навыки: Если ни на одном уровне не было найдено соответствующего разрешения, то действие будет запрещено. {{< alert level="info" >}} -Проверка владения включается только если в конфигурации портал включена опция `ownerIsAdmin`. Подробнее о владении объектами — в разделе [«Владение объектами»](#владение-объектами). +Проверка владения включается только если в конфигурации портал включена опция `ownerIsAdmin`. +Подробнее о владении объектами — в разделе [«Владение объектами»](#владение-объектами). {{< /alert >}} ## Владение объектами @@ -374,7 +399,8 @@ AI-агенты и навыки: ### Влияние владения на права доступа -При включённой опции `ownerIsAdmin` владелец объекта получает все права администратора для этого объекта. В этом случае владелец может: +При включённой опции `ownerIsAdmin` владелец объекта получает все права администратора для этого объекта. +В этом случае владелец может: - читать, изменять и удалять объект; - управлять привязками ролей и доступом других пользователей; @@ -383,23 +409,27 @@ AI-агенты и навыки: ### Опция OwnerAsAdmin Опция `ownerIsAdmin` задаёт поведение прав доступа для владельцев объектов. - -- «Включена (true)» — владельцы объектов получают полные права администратора на свои объекты. -- «Отключена (false)» — владельцы объектов не получают автоматических прав; доступ контролируется только через роли. +При значении «Включена (true)» владельцы объектов получают полные права администратора на свои объекты. +При значении «Отключена (false)» владельцы объектов не получают автоматических прав, и доступ контролируется только через роли. {{< alert level="info" >}} -Опция `ownerIsAdmin` должна быть настроена администратором портала в конфигурационном файле. По умолчанию опция выключена. +Опция `ownerIsAdmin` должна быть настроена администратором портала в конфигурационном файле. +По умолчанию опция выключена. {{< /alert >}} ### Автоматическое назначение владельца при создании -При создании нового объекта (действия, источника данных, виджета, ресурса и других объектов) портал автоматически устанавливает текущего пользователя в качестве владельца объекта. При необходимости можно переназначить владельца, либо создать объект без владельца. +При создании нового объекта (действия, источника данных, виджета, ресурса и других объектов) портал автоматически устанавливает текущего пользователя в качестве владельца объекта. +При необходимости можно переназначить владельца, либо создать объект без владельца. ### Примеры использования владения +Ниже приведены примеры того, как владение влияет на права доступа. + #### Владение ресурсом -Если пользователь создаёт ресурс, он автоматически становится его владельцем. При включенной опции `ownerIsAdmin` он получает все права администратора на этот ресурс, включая: +Если пользователь создаёт ресурс, он автоматически становится его владельцем. +При включённой опции `ownerIsAdmin` он получает все права администратора на этот ресурс, включая: - Управление сущностями ресурса. - Настройку привязок ролей. @@ -415,26 +445,34 @@ AI-агенты и навыки: #### Команда-владелец -Если владельцем объекта назначена команда, то при включенной опции `ownerIsAdmin` все участники этой команды получают права администратора на объект. +Если владельцем объекта назначена команда, то при включённой опции `ownerIsAdmin` все участники этой команды получают права администратора на объект. ## Роль по умолчанию -Портал позволяет назначить одну глобальную роль по умолчанию, разрешения к которой применяются ко всем авторизованным пользователям. Настройка выполняется в разделе «Администрирование» → «Управление доступом» с помощью переключателя в таблице «Роли». +Портал позволяет назначить одну глобальную роль по умолчанию, разрешения к которой применяются ко всем авторизованным пользователям. +Настройка выполняется в разделе «Администрирование» → «Управление доступом» с помощью переключателя в таблице «Роли». Ролью по умолчанию может быть назначена только глобальная роль. ## Команды -Команды используются для группировки пользователей и коллективного назначения ролей. Пользователь может состоять в нескольких командах, в этом случае его разрешения будут объединены из всех команд, в которых он состоит. +Команды используются для группировки пользователей и коллективного назначения ролей. +Пользователь может состоять в нескольких командах, в этом случае его разрешения будут объединены из всех команд, в которых он состоит. {{< alert level="info" >}} -Команды и их состав синхронизируются из внешней системы аутентификации (Dex) при каждом входе пользователя. Создавать, редактировать и удалять команды можно также в веб-интерфейсе в разделе «Администрирование» → «Команды» с разрешениями `create:teams`, `update:teams` и `delete:teams`. Состав команды, изменённый вручную, перезаписывается данными из Dex при следующем входе пользователя. +Команды и их состав синхронизируются из внешней системы аутентификации (Dex) при каждом входе пользователя. +Создавать, редактировать и удалять команды можно также в веб-интерфейсе в разделе «Администрирование» → «Команды» с разрешениями `create:teams`, `update:teams` и `delete:teams`. +Состав команды, изменённый вручную, перезаписывается данными из Dex при следующем входе пользователя. {{< /alert >}} ## Настройка ролей и управление доступом +Роли и привязки ролей настраиваются в разделе «Администрирование» → «RBAC». + ### Создание роли +Чтобы создать роль, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Роли». 1. Нажмите кнопку «Создать роль». @@ -452,6 +490,8 @@ AI-агенты и навыки: ### Назначение роли пользователям +Чтобы назначить роль пользователям, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Привязки ролей». 1. Нажмите кнопку «Создать привязку роли». @@ -466,6 +506,8 @@ AI-агенты и навыки: ### Настройка роли по умолчанию +Чтобы назначить роль по умолчанию, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Роли». 1. Найдите глобальную роль, которую хотите сделать ролью по умолчанию. @@ -478,6 +520,8 @@ AI-агенты и навыки: ### Редактирование существующих ролей +Чтобы изменить роль, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Роли». 1. Найдите нужную роль и нажмите «Редактировать». @@ -488,6 +532,8 @@ AI-агенты и навыки: ### Редактирование привязок ролей +Чтобы изменить привязку роли, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Привязки ролей». 1. Найдите нужную привязку и нажмите «Редактировать». @@ -499,6 +545,8 @@ AI-агенты и навыки: ### Удаление ролей и привязок +Чтобы удалить роль или привязку, выполните следующие действия: + 1. Перейдите в соответствующий раздел. 1. Найдите нужную роль или привязку. 1. Нажмите кнопку «Удалить». @@ -510,23 +558,31 @@ AI-агенты и навыки: ### Просмотр разрешений пользователя или команды +Итоговые разрешения можно просмотреть для пользователя или для команды. + #### Для пользователя +Чтобы просмотреть разрешения пользователя, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Пользователи». 1. В строке нужного пользователя нажмите «Посмотреть разрешения пользователя». 1. В диалоге «Разрешения пользователя» просмотрите: - «Глобальные разрешения» — глобальные разрешения пользователя. - - «Разрешения для …» — разрешения на уровне объектов, по одному блоку на объект. В каждом блоке указаны тип объекта, название объекта и привязка роли, которая предоставляет разрешения. + - «Разрешения для …» — разрешения на уровне объектов, по одному блоку на объект. + В каждом блоке указаны тип объекта, название объекта и привязка роли, которая предоставляет разрешения. Чтобы отфильтровать разрешения, используйте поле «Поиск». #### Для команды +Чтобы просмотреть разрешения команды, выполните следующие действия: + 1. Перейдите в раздел «Администрирование» → «Команды». 1. В строке нужной команды нажмите «Посмотреть разрешения команды». 1. В диалоге «Разрешения команды» просмотрите: - «Глобальные разрешения» — глобальные разрешения команды. - - «Разрешения для …» — разрешения на уровне объектов, по одному блоку на объект. В каждом блоке указаны тип объекта, название объекта и привязка роли, которая предоставляет разрешения. + - «Разрешения для …» — разрешения на уровне объектов, по одному блоку на объект. + В каждом блоке указаны тип объекта, название объекта и привязка роли, которая предоставляет разрешения. Чтобы отфильтровать разрешения, используйте поле «Поиск». @@ -534,19 +590,53 @@ AI-агенты и навыки: Состав команды синхронизируется из внешней системы аутентификации (Dex). {{< /alert >}} -### Пресеты ролей +### Примеры настройки ролей + +Ниже приведены примеры настройки типовых ролей. + +#### Роль «Администратор системы» + +Роль настраивается следующим образом: + +- Тип: `глобальные`. +- Разрешения: все глобальные разрешения (используйте пресет «Admin»). +- Назначение: супер-администраторы. + +#### Роль «Администратор ресурса» + +Роль настраивается следующим образом: + +- Тип: `ресурсы`. +- Разрешения: все разрешения для ресурсов (используйте пресет «Resource admin»). +- Назначение: конкретный ресурс, команда «Администраторы». + +#### Роль «Оператор процессов» + +Роль настраивается следующим образом: + +- Тип: `процессы`. +- Разрешения: `delete:process`, `edit:role-bindings`, `read:process`, `update:process` (используйте пресет «Process admin»). +- Назначение: команда «Операторы процессов». + +## Пресеты ролей Портал предоставляет готовые пресеты ролей для быстрой настройки типовых сценариев доступа. -#### Глобальные пресеты +### Глобальные пресеты -##### Пресет «Admin» +Для глобальных ролей доступны следующие пресеты. + +#### Пресет «Admin» + +Пресет имеет следующие настройки: - Тип: `глобальные`. - Разрешения: все глобальные разрешения. - Назначение: администраторы системы. -##### Пресет «Viewer» +#### Пресет «Viewer» + +Пресет имеет следующие настройки: - Тип: `глобальные`. - Разрешения: @@ -560,7 +650,9 @@ AI-агенты и навыки: - `read:audit-logs`, `view:admin-page`, `view:ai-page`, `view:self-service-page`. - Назначение: пользователи с правами только на просмотр. -##### Пресет «Developer» +#### Пресет «Developer» + +Пресет имеет следующие настройки: - Тип: `глобальные`. - Разрешения: @@ -568,11 +660,16 @@ AI-агенты и навыки: - `read:processes`, `read:template-packs`, `read:widgets`, `read:workflows`. - `run:actions`, `run:widget-actions`, `control:processes`. - `update:team-variables`. -- Назначение: разработчики, которым нужен доступ к просмотру информации и выполнению действий, но не требуется доступ к созданию, изменению или удалению объектов. Разработчики видят только те сущности, к которым им предоставлен доступ через привязки ролей на уровне ресурсов или сущностей. +- Назначение: разработчики, которым нужен доступ к просмотру информации и выполнению действий, но не требуется доступ к созданию, изменению или удалению объектов. + Разработчики видят только те сущности, к которым им предоставлен доступ через привязки ролей на уровне ресурсов или сущностей. + +Пресет «Developer» также включает `view:ai-page`, `use:ai-agents`, просмотр агентов, шаблонов AI-провайдеров и MCP, просмотр и остановку своих запусков, чтение журнала MCP-вызовов, `create:workspaces`, `read:workspace-templates` и `use:workspace-templates`. +Доступ к своим пространствам предоставляется владением при включённом `owner-is-admin`; глобальные права управления всеми пространствами в пресет не входят. +Инструменты MCP и использование AI-провайдеров из шаблонов предоставляются отдельно. -Пресет «Developer» также включает `view:ai-page`, `use:ai-agents`, просмотр агентов, шаблонов AI-провайдеров и MCP, просмотр и остановку своих запусков, чтение журнала MCP-вызовов, `create:workspaces`, `read:workspace-templates` и `use:workspace-templates`. Доступ к своим пространствам предоставляется владением при включённом `owner-is-admin`; глобальные права управления всеми пространствами в пресет не входят. Инструменты MCP и использование AI-провайдеров из шаблонов предоставляются отдельно. +#### Пресет «Platform engineer» -##### Пресет «Platform engineer» +Пресет имеет следующие настройки: - Тип: `глобальные`. - Разрешения: @@ -581,33 +678,46 @@ AI-агенты и навыки: - `update:team-variables`. - Страница «AI»: права из «Developer», управление агентами, источниками агентов и шаблонами AI-провайдеров, использование шаблонов AI-провайдеров и MCP-коллекций, чтение и изменение MCP, навыков и их источников, общая статистика AI, просмотр, запуск, остановка, обновление и удаление рабочих пространств. -Создание и редактирование шаблонов рабочих пространств, управление их источниками и лимитами установки предоставляются отдельно. Созданные ранее роли не обновляются при изменении пресета: проверьте их фактический состав. +Создание и редактирование шаблонов рабочих пространств, управление их источниками и лимитами установки предоставляются отдельно. +Созданные ранее роли не обновляются при изменении пресета. Проверьте их фактический состав. Пресет предназначен для инженеров, которые настраивают портал. -#### Пресеты для процессов +### Пресеты для процессов -##### Пресет «Process admin» +Для ролей уровня процессов доступны следующие пресеты. + +#### Пресет «Process admin» + +Пресет имеет следующие настройки: - Тип: `процессы`. - Разрешения: `delete:process`, `edit:role-bindings`, `read:process`, `update:process`. - Назначение: администраторы процессов. -##### Пресет «Process viewer» +#### Пресет «Process viewer» + +Пресет имеет следующие настройки: - Тип: `процессы`. - Разрешения: `read:process`. - Назначение: пользователи с правами на просмотр процессов. -#### Пресеты для ресурсов +### Пресеты для ресурсов + +Для ролей уровня ресурсов доступен следующий пресет. + +#### Пресет «Resource admin» -##### Пресет «Resource admin» +Пресет имеет следующие настройки: - Тип: `ресурсы`. - Разрешения: все разрешения для ресурсов. - Назначение: администраторы конкретных ресурсов. -#### Использование пресетов +### Использование пресетов + +Чтобы создать роль на основе пресета, выполните следующие действия: 1. Перейдите в раздел «Администрирование» → «Управление доступом». 1. Выберите вкладку «Роли». @@ -619,30 +729,14 @@ AI-агенты и навыки: - Добавьте или удалите разрешения. 1. Нажмите «Сохранить». -### Примеры настройки ролей - -#### Роль «Администратор системы» - -- Тип: `глобальные`. -- Разрешения: все глобальные разрешения (используйте пресет «Admin»). -- Назначение: супер-администраторы. - -#### Роль «Администратор ресурса» - -- Тип: `ресурсы`. -- Разрешения: все разрешения для ресурсов (используйте пресет «Resource admin»). -- Назначение: конкретный ресурс, команда «Администраторы». - -#### Роль «Оператор процессов» - -- Тип: `процессы`. -- Разрешения: `delete:process`, `edit:role-bindings`, `read:process`, `update:process` (используйте пресет «Process admin»). -- Назначение: команда «Операторы процессов». - ## Практические рекомендации +Ниже приведены рекомендации по настройке ролевой модели. + ### Создание ролей +При создании ролей придерживайтесь следующих рекомендаций: + 1. Определите уровень доступа: решите, нужна ли глобальная роль или роль для конкретного объекта. 1. Выберите необходимые разрешения: используйте принцип минимальных привилегий. 1. Создайте роль в соответствующем разделе администрирования. @@ -650,6 +744,8 @@ AI-агенты и навыки: ### Управление доступом +При управлении доступом придерживайтесь следующих рекомендаций: + 1. Используйте команды для группового управления доступом. 1. Применяйте роли по умолчанию для базовых разрешений всех пользователей. 1. Используйте иерархию: глобальные роли для широких прав, роли объектов для специфических прав. @@ -657,6 +753,8 @@ AI-агенты и навыки: ### Безопасность +Для обеспечения безопасности придерживайтесь следующих рекомендаций: + 1. Принцип минимальных привилегий: предоставляйте только необходимые разрешения. 1. Регулярный аудит: проверяйте назначенные роли и их использование. 1. Используйте команды вместо индивидуальных назначений для упрощения управления. diff --git a/content/documentation/admin/templates/_index.md b/content/documentation/admin/templates/_index.md new file mode 100644 index 00000000..5ba353b5 --- /dev/null +++ b/content/documentation/admin/templates/_index.md @@ -0,0 +1,4 @@ +--- +title: Microservice templates +weight: 26 +--- diff --git a/content/documentation/admin/templates/overview.md b/content/documentation/admin/templates/overview.md new file mode 100644 index 00000000..76e3399c --- /dev/null +++ b/content/documentation/admin/templates/overview.md @@ -0,0 +1,97 @@ +--- +title: Overview +weight: 10 +description: Microservice templates in DDP — template packs in an OCI registry, the portal's template registry, creating repositories from a template, and upgrading them to new versions through a merge request. +--- + +Microservice templates define the repository structure of a new microservice: boilerplate code, CI/CD, deployment manifests, and configuration. +Deckhouse Development Portal (DDP) creates a microservice repository from a template, and when a new template version is released, it carries the changes over to the repository through a merge request. + +{{< alert level="warning" >}} +The template registry and upgrading from a template are Preview features. +The pack format, the set of settings, and the API may change in future releases without backward compatibility. +{{< /alert >}} + +## Key concepts + +The template mechanism uses the following concepts: + +- **Template pack**: A directory with the `template.yaml` manifest, the `values.yaml` parameter schema, and files written as Go templates. + The pack is published to a container registry as an OCI artifact; the pack version is the artifact tag in semver format. +- **Template registry**: The portal's connections to container registries where packs are published. + The portal synchronizes the registry on a schedule and maintains a catalog of template versions. +- **Latest version**: The recommended template version, that is, the highest stable version among the available ones. + The creation wizard offers it, and microservices are upgraded to it. +- **Lock file**: The `.ddp/template.lock.yaml` file in the microservice repository. + It stores the template identifier, its version, and the parameter values the repository was created with. +- **Microservice-to-template binding**: Properties of the microservice entity in the catalog: the template identifier, version, registry, and upgrade policy. +- **Template actions**: Processes for creating, deploying, removing from an environment, and upgrading, bound to a specific template in the Home page mapping rules. + +## Template lifecycle + +The diagram below shows the path from publishing a template to upgrading a microservice repository: + +```mermaid +sequenceDiagram + participant A as Template author + participant O as Container registry (OCI) + participant D as DDP + participant G as GitLab + A->>O: ddp-template publish (version 1.0.0) + D->>O: Registry sync + Note over D: Version 1.0.0 is the latest + D->>G: Microservice creation: project, files, lock file + A->>O: ddp-template publish (version 1.1.0) + D->>O: Registry sync + Note over D: Version 1.1.0 is the latest + D->>G: Update: branch, commit, merge request + Note over G: Microservice owner merges the merge request + D->>G: Version reconciliation from the lock file + Note over D: Microservice version in the catalog is 1.1.0 +``` + +Lifecycle stages: + +1. The template author prepares a pack and publishes a version with the `ddp-template` utility. + The pack format is described in [Template pack](packs/). +1. The portal synchronizes the [template registry](registry/) and adds the version to the version catalog. +1. The administrator binds processes to the template in the "Template actions" block of the [mapping rules](../home/mapping/#template-actions). +1. A developer creates a microservice in the "Create microservice" Home page section. + The creation process creates a GitLab project, writes the rendered template files and the lock file to it, and registers the microservice in the catalog. +1. When a new template version is released, the portal shows the "Version {version} is available" notification on the microservice card. + The upgrade is started with the "Upgrade" button or automatically. +1. The upgrade process creates a branch with the template changes and opens a merge request. + After the merge request is merged, the portal updates the microservice's template version in the catalog. + +The upgrade mechanism is described in detail in [Upgrading from a template](updates/). + +## Participant roles + +Different participants work with templates: + +| Participant | Tasks | Documentation | +| --- | --- | --- | +| Template author | Prepares the pack, selects the upgrade strategy, publishes versions | [Template pack](packs/) | +| Portal administrator | Connects container registries, configures synchronization and automatic upgrades, binds processes to templates | [Template registry](registry/), [Mapping rules](../home/mapping/#template-actions) | +| Developer | Creates a microservice from a template, merges the upgrade merge request | "Microservices" in the user guide | + +## Limitations + +The template mechanism has the following limitations: + +| Limitation | Description | +| --- | --- | +| Pack storage | Only container registries with OCI Distribution Spec v2, for example, Harbor, GitLab Container Registry, and Docker Registry | +| Version control system | Only GitLab. The microservice repository is accessible over HTTPS on the GitLab external service host | +| Versions | Only strict semver without the `v` prefix, for example, `1.2.0`. A published version cannot be overwritten | +| File deletion | The upgrade does not delete files from the repository. Files deleted or renamed in a new template version are deleted manually | +| Intermediate versions | The upgrade moves the repository directly to the latest template version; intermediate versions are not applied one by one | +| Merging | The portal does not merge the upgrade merge request automatically | +| Registry binding | A microservice is upgraded only from the registry it was created from. If the latest template version comes from another registry, no upgrade is offered to the microservice | +| Microservices without a lock file | Repositories created without the `.ddp/template.lock.yaml` lock file cannot be upgraded from a template | +| New templates | For each new template, processes are bound manually in the Home page mapping rules | + +{{< alert level="info" >}} +The [Automatic service upgrades](../../examples/service-autoupdates/) example describes configuring upgrades based on actions, automations, and template Git tags without the template registry. +The mechanism described in this section works with template packs from an OCI registry and is configured without custom automations. +{{< /alert >}} diff --git a/content/documentation/admin/templates/overview.ru.md b/content/documentation/admin/templates/overview.ru.md index 9d3a2d8a..fb9020c6 100644 --- a/content/documentation/admin/templates/overview.ru.md +++ b/content/documentation/admin/templates/overview.ru.md @@ -5,22 +5,27 @@ description: Шаблоны микросервисов в DDP — пакеты --- Шаблоны микросервисов задают структуру репозитория нового микросервиса: код-заготовку, CI/CD, манифесты развёртывания и конфигурацию. -Deckhouse Development Portal (DDP, портал) создаёт репозиторий микросервиса из шаблона, а при выходе новой версии шаблона переносит изменения в репозиторий через запрос на слияние. +Deckhouse Development Portal (DDP, портал) создаёт репозиторий микросервиса из шаблона, а при выходе новой версии шаблона переносит изменения в репозиторий через запрос на слияние (Merge Request). {{< alert level="warning" >}} -Реестр шаблонов и обновление из шаблона — функциональность на стадии Preview. Формат пакета, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. +Реестр шаблонов и обновление из шаблона — функциональность на стадии Preview. +Формат пакета, состав настроек и API могут измениться в следующих выпусках без сохранения обратной совместимости. {{< /alert >}} ## Основные понятия Механизм шаблонов использует следующие понятия: -- **пакет шаблона** — директория с манифестом `template.yaml`, схемой параметров `values.yaml` и файлами на Go-шаблонах. Пакет публикуется в хранилище образов контейнеров как OCI-артефакт; версия пакета — тег артефакта в формате semver; -- **реестр шаблонов** — подключения портала к хранилищам образов контейнеров, в которых опубликованы пакеты. Портал синхронизирует реестр по расписанию и ведёт каталог версий шаблонов; -- **последняя версия** — рекомендованная версия шаблона: максимальная стабильная версия среди доступных. Её предлагает мастер создания и на неё обновляются микросервисы; -- **lock-файл** — файл `.ddp/template.lock.yaml` в репозитории микросервиса. Хранит идентификатор шаблона, его версию и значения параметров, с которыми создан репозиторий; +- **пакет шаблона** — директория с манифестом `template.yaml`, схемой параметров `values.yaml` и файлами на Go-шаблонах. + Пакет публикуется в хранилище образов контейнеров как OCI-артефакт; версия пакета — тег артефакта в формате semver; +- **реестр шаблонов** — подключения портала к хранилищам образов контейнеров, в которых опубликованы пакеты. + Портал синхронизирует реестр по расписанию и ведёт каталог версий шаблонов; +- **последняя версия** — рекомендованная версия шаблона: максимальная стабильная версия среди доступных. + Её предлагает мастер создания и на неё обновляются микросервисы; +- **lock-файл** — файл `.ddp/template.lock.yaml` в репозитории микросервиса. + Хранит идентификатор шаблона, его версию и значения параметров, с которыми создан репозиторий; - **привязка микросервиса к шаблону** — параметры сущности микросервиса в каталоге: идентификатор шаблона, версия, реестр и политика обновления; -- **действия по шаблонам** — процессы создания, развёртывания, удаления с окружения и обновления, привязанные к конкретному шаблону в правилах маппинга главной. +- **действия по шаблонам** — процессы создания, развёртывания, удаления с окружения и обновления, привязанные к конкретному шаблону в правилах маппинга главной страницы. ## Жизненный цикл шаблона @@ -47,12 +52,16 @@ sequenceDiagram Этапы жизненного цикла: -1. Автор шаблона готовит пакет и публикует версию утилитой `ddp-template`. Формат пакета описан в разделе [«Пакет шаблона»](packs/). +1. Автор шаблона готовит пакет и публикует версию утилитой `ddp-template`. + Формат пакета описан в разделе [«Пакет шаблона»](packs/). 1. Портал синхронизирует [реестр шаблонов](registry/) и добавляет версию в каталог версий. 1. Администратор привязывает к шаблону процессы в блоке «Действия по шаблонам» [правил маппинга](../home/mapping/#действия-по-шаблонам). -1. Разработчик создаёт микросервис в разделе главной «Создать микросервис». Процесс создания создаёт проект GitLab, записывает в него отрисованные файлы шаблона и lock-файл, регистрирует микросервис в каталоге. -1. При выходе новой версии шаблона портал показывает в карточке микросервиса уведомление «Доступна версия {version}». Обновление запускается кнопкой «Обновить» или автоматически. -1. Процесс обновления создаёт ветку с изменениями шаблона и открывает запрос на слияние. После принятия запроса на слияние портал обновляет версию шаблона микросервиса в каталоге. +1. Разработчик создаёт микросервис в разделе главной страницы «Создать микросервис». + Процесс создания создаёт проект GitLab, записывает в него отрисованные файлы шаблона и lock-файл, регистрирует микросервис в каталоге. +1. При выходе новой версии шаблона портал показывает в карточке микросервиса уведомление «Доступна версия {version}». + Обновление запускается кнопкой «Обновить» или автоматически. +1. Процесс обновления создаёт ветку с изменениями шаблона и открывает запрос на слияние. + После принятия запроса на слияние портал обновляет версию шаблона микросервиса в каталоге. Подробно механизм обновления описан в разделе [«Обновление из шаблона»](updates/). @@ -80,7 +89,7 @@ sequenceDiagram | Слияние | Портал не принимает запрос на слияние с обновлением автоматически | | Привязка к реестру | Микросервис обновляется только из того реестра, из которого создан. Если последняя версия шаблона пришла из другого реестра, обновление микросервису не предлагается | | Микросервисы без lock-файла | Репозитории, созданные без lock-файла `.ddp/template.lock.yaml`, обновить из шаблона нельзя | -| Новые шаблоны | Для каждого нового шаблона процессы привязываются вручную в правилах маппинга главной | +| Новые шаблоны | Для каждого нового шаблона процессы привязываются вручную в правилах маппинга главной страницы | {{< alert level="info" >}} Пример [«Автоматическое обновление сервисов»](../../examples/service-autoupdates/) описывает настройку обновления на действиях, автоматизациях и Git-тегах шаблона без реестра шаблонов. diff --git a/content/documentation/admin/templates/packs.md b/content/documentation/admin/templates/packs.md new file mode 100644 index 00000000..e3fb0dde --- /dev/null +++ b/content/documentation/admin/templates/packs.md @@ -0,0 +1,328 @@ +--- +title: Template pack +weight: 30 +description: DDP microservice template pack format — the template.yaml manifest, the values.yaml parameter schema, the x-ddp-from annotation, file templating, versions, and publishing with the ddp-template utility. +--- + +A template pack is a directory with the files of a future microservice repository, a manifest, and a parameter schema. +The portal renders the pack files with the Go template engine using the parameters that the user fills in when creating a microservice. +The pack is published to a container registry with the `ddp-template` utility. + +## Pack structure + +A pack contains three service files and the repository files: + +- `template.yaml`: Manifest with the ID, name, language, and upgrade rules. +- `values.yaml`: Template parameter schema. +- `.templateignore`: Paths that are copied to the repository without templating. +- Other files and directories: Contents of the microservice repository. + +Example structure of a Go service pack: + +```text +go-service/ + template.yaml + values.yaml + .templateignore + .gitlab-ci.yml + cmd/{{ .slug }}/main.go + go.mod + deploy/helm/Chart.yaml +``` + +The `template.yaml`, `values.yaml`, and `.templateignore` files are not copied to the microservice repository. +The `.git` directory is not included in the pack. + +Do not place a `.ddp/` directory in the pack, because the portal creates the `.ddp/template.lock.yaml` lock file in it when creating and upgrading the repository. + +## The template.yaml manifest + +The manifest describes the template and its upgrade rules. Example manifest: + +```yaml +id: go-service +name: Go service +description: Go HTTP service with CI and Helm chart +language: Go +tags: + - http + - helm +minDdpVersion: "1.7.0" +update: + strategy: selective_additive + overwrite: + - .gitlab-ci.yml + - deploy/** + - go.mod + addIfMissing: + - .dockerignore + - .editorconfig +``` + +Manifest fields: + +| Name | Required | Description | +| --- | --- | --- | +| `id` | Yes | Template ID: lowercase Latin letters, digits, and hyphens. Matches the repository name in the container registry | +| `name` | Yes | Template name in the gallery | +| `description` | No | Template description in the gallery | +| `language` | Yes | Template language: `Go`, `Vue`, `TypeScript`, `Python`, `Java`, or `Other` | +| `tags` | No | Tags used for search in the gallery | +| `minDdpVersion` | No | Minimum Deckhouse Development Portal (DDP) version in semver format. On an earlier DDP version, the template version gets the "unavailable" status | +| `update` | Yes | Rules for upgrading the repository to a new template version: the `strategy`, `overwrite`, and `addIfMissing` fields | +| `update.strategy` | No | Upgrade strategy: `selective`, `additive`, `selective_additive`, `full`, or `merge`. If not set, `selective` is used, and `update.overwrite` becomes required. The `full` strategy requires no path lists: `update: {strategy: full}` | +| `update.overwrite` | Depends on the strategy | Glob patterns of paths that are overwritten during an upgrade | +| `update.addIfMissing` | Depends on the strategy | Glob patterns of paths that are added during an upgrade if they are missing from the repository | + +No other fields are allowed in the manifest. +Strategies and path list requirements are described in ["Upgrade strategies"](updates/#upgrade-strategies). + +## The values.yaml parameters + +The `values.yaml` file is the template parameter schema in OpenAPI Schema Object format. +The portal uses the schema to build the form on the "Parameters" step of the microservice creation wizard. + +Example parameter schema: + +```yaml +type: object +required: + - slug + - name + - port +properties: + slug: + type: string + title: Service slug + description: Identifier used in paths and module name + x-ddp-from: context.microservice.slug + name: + type: string + title: Display name + x-ddp-from: context.microservice.name + port: + type: integer + title: HTTP port + default: 8080 + database: + type: string + title: Database + enum: + - postgres + - none + default: none + metrics: + type: boolean + title: Expose Prometheus metrics + default: true +``` + +The portal uses the top-level `properties` to build the form: + +- `title`: Field label. If not set, the parameter key is used. +- `description`: Field hint. +- `required`: Whether the field is required in the form. +- `default`: Initial value. + If no default value is set, the empty value of the type is used: an empty string, `0`, `false`, an empty list, or an empty object. + +The form field type depends on the parameter type: + +| Parameter type | Form field | +| --- | --- | +| `string` with `enum` | Drop-down list | +| `string` | Text field | +| `boolean` | Toggle | +| `integer` | Numeric field with a step of 1 | +| `number` | Numeric field with a step of 0.1 | +| `object`, `array`, schemas with `oneOf`, `anyOf`, `allOf`, `$ref` | JSON input field | + +Before rendering the pack, the portal validates the resulting values against the schema. +If they do not match, creation fails with the `values_invalid: values do not match values.yaml schema: ...` error. + +When the pack is rendered, unset parameters get the empty values of their types, so `required` does not guarantee a non-empty value. +To prohibit an empty string, use schema constraints, for example, `minLength: 1`. + +The schema is defined as an object. A list of parameters in `values.yaml` is not supported. + +### Binding parameters to the launch context + +The `x-ddp-from` annotation fills a parameter from the launch context of the microservice creation process. +Such a parameter is not shown in the wizard form, so the user does not re-enter data already provided on the "Service" step. + +The annotation value is a path in the launch context that starts with `context.`: + +| Path | Value | +| --- | --- | +| `context.microservice.slug` | Microservice ID | +| `context.microservice.name` | Microservice name | +| `context.system.slug` | ID of the system that the microservice belongs to | +| `context.system.name` | System name | +| `context.repository.default_branch` | Default branch | +| `context.repository.description` | Repository description | +| `context.template.version` | Template version | + +The full contents of the creation context are described in ["Home page processes"](../home/processes/#creating-a-microservice). + +Annotation rules: + +- The value from the context replaces the value passed in the process parameters. +- If the path is missing from the context or its value is `null`, creation fails with the `values_invalid: values.yaml property "k": x-ddp-from "context.x": path not found in launch context` error. +- If the annotation is empty, creation fails with the `values_invalid: values.yaml property "k": x-ddp-from is empty` error. +- The annotation is applied only when the repository is created. During an upgrade, the values from the lock file are used. + +## File templating + +Pack files are rendered with the Go `text/template` engine. +Template parameters are available at the root: `{{ .slug }}`, `{{ .port }}`. + +Example pack file: + +```go-html-template +package main + +// {{ .name }} listens on port {{ .port }}. +const port = {{ .port }} +{{- if .metrics }} + +const metricsPath = "/metrics" +{{- end }} +``` + +Templating rules: + +- Referencing a missing parameter makes rendering fail. +- Templates can use the [portal templating functions](../../user/templating/#built-in-functions) and Sprig library functions, except `env`, `expandenv`, and `getHostByName`. +- File and directory names are templated, for example, `cmd/{{ .slug }}/main.go`. + A path that points outside the repository after rendering makes rendering fail. +- A file that is empty or contains only whitespace after rendering is not written to the repository. + This is how optional files are defined in a pack. + +### Files without templating + +The `.templateignore` file lists paths that are copied to the repository as is, without templating. +Use it for files with their own `{{ }}` syntax, for example, Helm templates. + +Example `.templateignore`: + +```text +# Helm templates use their own {{ .Values }} syntax. +deploy/helm/templates/** +``` + +Each line is a glob pattern of a path relative to the pack root. The `**` syntax is supported. +Lines that start with `#` are comments. +Path patterns in `.templateignore` can contain `{{ }}` expressions themselves. + +## Versions + +A pack version is an artifact tag in the container registry in strict semver format without the `v` prefix, for example, `1.2.0` or `2.0.0-rc.1`. + +Versioning rules: + +- A published version cannot be overwritten. To fix it, publish a new version. +- Increment the major version for breaking changes to the repository structure. +- Prerelease versions, for example, `2.0.0-rc.1`, are not installed by automatic upgrades and are visible in the microservice card only to users with the `read:template-registries` permission. + +Before publishing a version with breaking changes, check the following: + +- Files renamed or moved in the new version remain at the old paths in microservice repositories, because an upgrade does not delete files. + Describe the manual cleanup in the version description. +- New required files are added to `update.overwrite` or `update.addIfMissing` if users may already have their own copies of these files. +- `update.overwrite` contains only files owned by the platform, for example, CI configuration and deployment manifests. + Move files that developers edit to `update.addIfMissing` or leave them out of the lists. + +## The ddp-template utility + +The `ddp-template` utility validates, builds, publishes, and renders template packs locally. + +Utility commands: + +| Command | Purpose | +| --- | --- | +| `ddp-template lint ` | Validates `template.yaml`, `values.yaml`, `.templateignore`, and the upgrade path lists, and performs a trial render of the pack | +| `ddp-template pack ` | Builds a pack archive without the `.git` directory | +| `ddp-template publish --version ` | Validates, builds, and publishes the pack to the container registry. Outputs JSON with the `templateId`, `version`, `ociRef`, and `sha256` fields | +| `ddp-template pull --version ` | Downloads and unpacks a published pack | +| `ddp-template render ` | Renders the pack locally, including simulation of an upgrade strategy | + +Exit codes of `ddp-template lint`: `0` if there are no errors, `1` if there are errors, `2` if there are warnings. +The `--strict` flag turns warnings into errors, and the `--render-smoke` flag performs only rendering with default values. + +### Connecting to the registry + +Registry connection parameters are set with flags, environment variables, or a configuration file. +Flags take precedence over environment variables, and environment variables take precedence over a profile from the configuration file. + +| Parameter | Flag | Environment variable | +| --- | --- | --- | +| Configuration file | `--config` | `DDP_TEMPLATE_CONFIG` | +| Profile | `--profile` | `DDP_TEMPLATE_PROFILE` | +| Registry host | `--registry` | `DDP_TEMPLATE_REGISTRY` | +| Repository prefix | `--repository-prefix` | `DDP_TEMPLATE_REPOSITORY_PREFIX` | +| Username | `--registry-user` | `DDP_TEMPLATE_REGISTRY_USER` | +| Password or token | `--registry-token` | `DDP_TEMPLATE_REGISTRY_TOKEN` | + +If no username is set, the password is used as a Bearer token. + +The configuration file contains connection profiles: + +```yaml +default: company +registries: + company: + registry: registry.example.com + repositoryPrefix: ddp-templates + auth: + username: + password: +``` + +Where: + +- ``: Registry username. +- ``: Registry password or token. + +If the `default` parameter is set or there is only one profile, that profile is used when no profile is specified. + +### Publishing from CI + +Versions are published from CI by a Git tag. +Example of a GitLab CI job that publishes the `go-service` template by the `go-service/vX.Y.Z` tag: + +```yaml +publish-go-service: + rules: + - if: $CI_COMMIT_TAG =~ /^go-service\/v\d+\.\d+\.\d+$/ + script: + - VERSION="${CI_COMMIT_TAG#go-service/v}" + - ddp-template publish ./template-packs/go-service + --version "$VERSION" + --registry "$REGISTRY" + --repository-prefix ddp-templates +``` + +After publishing, the version appears in the portal on the next template registry sync or after you click "Sync" on the "Sync runs" tab. +If the "Repository IDs" field is filled in for the connection, add the new template ID to it. + +### Checking an upgrade locally + +The utility renders a new pack version with the values of an existing microservice without accessing GitLab. +This lets you check which files an upgrade will change. + +The following commands download a published version and render it with a simulated upgrade strategy: + +```shell +ddp-template pull go-service --version 1.1.0 \ + --registry registry.example.com \ + --repository-prefix ddp-templates \ + --output ./packs/go-service-1.1.0 +ddp-template render ./packs/go-service-1.1.0 \ + --values ./values.yaml \ + --use-overwrite \ + --output ./render-out +``` + +Where `./values.yaml` is a file with the parameter values from the `values` section of the microservice lock file. + +The `ddp-template render` command does not apply `x-ddp-from` annotations. +Pass the values of such parameters in the `--values` file. diff --git a/content/documentation/admin/templates/packs.ru.md b/content/documentation/admin/templates/packs.ru.md index a78dd8a3..81e64dc5 100644 --- a/content/documentation/admin/templates/packs.ru.md +++ b/content/documentation/admin/templates/packs.ru.md @@ -4,7 +4,8 @@ weight: 30 description: Формат пакета шаблона микросервиса DDP — манифест template.yaml, схема параметров values.yaml, аннотация x-ddp-from, шаблонизация файлов, версии и публикация утилитой ddp-template. --- -Пакет шаблона — это директория с файлами будущего репозитория микросервиса, манифестом и схемой параметров. Портал отрисовывает файлы пакета Go-шаблонизатором с параметрами, которые пользователь заполняет при создании микросервиса. +Пакет шаблона — это директория с файлами будущего репозитория микросервиса, манифестом и схемой параметров. +Портал отрисовывает файлы пакета Go-шаблонизатором с параметрами, которые пользователь заполняет при создании микросервиса. Пакет публикуется в хранилище образов контейнеров утилитой `ddp-template`. ## Структура пакета @@ -29,9 +30,10 @@ go-service/ deploy/helm/Chart.yaml ``` -Файлы `template.yaml`, `values.yaml` и `.templateignore` в репозиторий микросервиса не копируются. Директория `.git` в пакет не включается. +Файлы `template.yaml`, `values.yaml` и `.templateignore` в репозиторий микросервиса не копируются. +Директория `.git` в пакет не включается. -Не размещайте в пакете директорию `.ddp/`: портал создаёт в ней lock-файл `.ddp/template.lock.yaml` при создании и обновлении репозитория. +Не размещайте в пакете директорию `.ddp/`, поскольку портал создаёт в ней lock-файл `.ddp/template.lock.yaml` при создании и обновлении репозитория. ## Манифест template.yaml @@ -59,24 +61,26 @@ update: Поля манифеста: -| Поле | Обязательное | Описание | +| Название | Обязательное | Описание | | --- | --- | --- | | `id` | Да | Идентификатор шаблона: строчные латинские буквы, цифры и дефис. Совпадает с именем репозитория в хранилище образов | | `name` | Да | Название шаблона в галерее | | `description` | Нет | Описание шаблона в галерее | | `language` | Да | Язык шаблона: `Go`, `Vue`, `TypeScript`, `Python`, `Java` или `Other` | | `tags` | Нет | Теги для поиска в галерее | -| `minDdpVersion` | Нет | Минимальная версия DDP в формате semver. На более ранней версии DDP версия шаблона получает статус «недоступна» | +| `minDdpVersion` | Нет | Минимальная версия Deckhouse Development Portal (DDP) в формате semver. На более ранней версии DDP версия шаблона получает статус «недоступна» | | `update` | Да | Правила обновления репозитория до новой версии шаблона: поля `strategy`, `overwrite` и `addIfMissing` | | `update.strategy` | Нет | Стратегия обновления: `selective`, `additive`, `selective_additive`, `full` или `merge`. Если не задана, используется `selective`, и тогда `update.overwrite` обязателен. Для стратегии `full` списки путей не нужны: `update: {strategy: full}` | | `update.overwrite` | Зависит от стратегии | Glob-шаблоны путей, которые перезаписываются при обновлении | | `update.addIfMissing` | Зависит от стратегии | Glob-шаблоны путей, которые добавляются при обновлении, если их нет в репозитории | -Другие поля в манифесте не допускаются. Стратегии и требования к спискам путей описаны в разделе [«Стратегии обновления»](updates/#стратегии-обновления). +Другие поля в манифесте не допускаются. +Стратегии и требования к спискам путей описаны в разделе [«Стратегии обновления»](updates/#стратегии-обновления). ## Параметры values.yaml -Файл `values.yaml` — схема параметров шаблона в формате OpenAPI Schema Object. По схеме портал строит форму шага «Параметры» мастера создания микросервиса. +Файл `values.yaml` — схема параметров шаблона в формате OpenAPI Schema Object. +По схеме портал строит форму шага «Параметры» мастера создания микросервиса. Пример схемы параметров: @@ -118,7 +122,8 @@ properties: - `title` — подпись поля, при отсутствии — ключ параметра; - `description` — подсказка поля; - `required` — обязательность поля в форме; -- `default` — начальное значение. Если значение по умолчанию не задано, используется пустое значение типа: пустая строка, `0`, `false`, пустой список или объект. +- `default` — начальное значение. + Если значение по умолчанию не задано, используется пустое значение типа: пустая строка, `0`, `false`, пустой список или объект. Тип поля формы определяется типом параметра: @@ -131,15 +136,18 @@ properties: | `number` | Числовое поле с шагом 0,1 | | `object`, `array`, схемы с `oneOf`, `anyOf`, `allOf`, `$ref` | Поле для ввода JSON | -Перед отрисовкой пакета портал проверяет итоговые значения по схеме. При несоответствии создание завершается ошибкой `values_invalid: values do not match values.yaml schema: ...`. +Перед отрисовкой пакета портал проверяет итоговые значения по схеме. +При несоответствии создание завершается ошибкой `values_invalid: values do not match values.yaml schema: ...`. -При отрисовке пакета незаданные параметры получают пустые значения типа, поэтому `required` не гарантирует непустое значение. Чтобы запретить пустую строку, используйте ограничения схемы, например `minLength: 1`. +При отрисовке пакета незаданные параметры получают пустые значения типа, поэтому `required` не гарантирует непустое значение. +Чтобы запретить пустую строку, используйте ограничения схемы, например `minLength: 1`. Схема задаётся объектом. Список параметров в `values.yaml` не поддерживается. ### Связь параметров с контекстом запуска -Аннотация `x-ddp-from` заполняет параметр из контекста запуска процесса создания микросервиса. Такой параметр не отображается в форме мастера: пользователь не вводит повторно данные, которые уже указал на шаге «Сервис». +Аннотация `x-ddp-from` заполняет параметр из контекста запуска процесса создания микросервиса. +Такой параметр не отображается в форме мастера, поэтому пользователь не вводит повторно данные, которые уже указал на шаге «Сервис». Значение аннотации — путь в контексте запуска, начинающийся с `context.`: @@ -153,7 +161,7 @@ properties: | `context.repository.description` | Описание репозитория | | `context.template.version` | Версия шаблона | -Полный состав контекста создания описан в разделе [«Процессы главной»](../home/processes/#создание-микросервиса). +Полный состав контекста создания описан в разделе [«Процессы главной страницы»](../home/processes/#создание-микросервиса). Правила применения аннотации: @@ -164,7 +172,8 @@ properties: ## Шаблонизация файлов -Файлы пакета отрисовываются шаблонизатором Go `text/template`. Параметры шаблона доступны в корне: `{{ .slug }}`, `{{ .port }}`. +Файлы пакета отрисовываются шаблонизатором Go `text/template`. +Параметры шаблона доступны в корне: `{{ .slug }}`, `{{ .port }}`. Пример файла пакета: @@ -183,12 +192,15 @@ const metricsPath = "/metrics" - обращение к отсутствующему параметру завершает отрисовку ошибкой; - в шаблонах доступны [функции шаблонизации портала](../../user/templating/#встроенные-функции) и функции библиотеки Sprig, кроме `env`, `expandenv` и `getHostByName`; -- шаблонизируются имена файлов и директорий, например `cmd/{{ .slug }}/main.go`. Путь, который после отрисовки выходит за пределы репозитория, завершает отрисовку ошибкой; -- файл, который после отрисовки пуст или содержит только пробельные символы, в репозиторий не записывается. Так в пакете задаются необязательные файлы. +- шаблонизируются имена файлов и директорий, например `cmd/{{ .slug }}/main.go`. + Путь, который после отрисовки выходит за пределы репозитория, завершает отрисовку ошибкой; +- файл, который после отрисовки пуст или содержит только пробельные символы, в репозиторий не записывается. + Так в пакете задаются необязательные файлы. ### Файлы без шаблонизации -Файл `.templateignore` перечисляет пути, которые копируются в репозиторий как есть, без шаблонизации. Используйте его для файлов с собственным синтаксисом `{{ }}`, например шаблонов Helm. +Файл `.templateignore` перечисляет пути, которые копируются в репозиторий как есть, без шаблонизации. +Используйте его для файлов с собственным синтаксисом `{{ }}`, например шаблонов Helm. Пример `.templateignore`: @@ -197,7 +209,9 @@ const metricsPath = "/metrics" deploy/helm/templates/** ``` -Каждая строка — glob-шаблон пути относительно корня пакета, поддерживается синтаксис `**`. Строки, начинающиеся с `#`, — комментарии. Шаблоны путей в `.templateignore` сами могут содержать выражения `{{ }}`. +Каждая строка — glob-шаблон пути относительно корня пакета, поддерживается синтаксис `**`. +Строки, начинающиеся с `#`, — комментарии. +Шаблоны путей в `.templateignore` сами могут содержать выражения `{{ }}`. ## Версии @@ -211,9 +225,11 @@ deploy/helm/templates/** Перед публикацией версии с несовместимыми изменениями проверьте: -- файлы, переименованные или перемещённые в новой версии, остаются в старых путях репозиториев микросервисов: обновление не удаляет файлы. Опишите ручную очистку в описании версии; +- файлы, переименованные или перемещённые в новой версии, остаются в старых путях репозиториев микросервисов: обновление не удаляет файлы. + Опишите ручную очистку в описании версии; - новые обязательные файлы добавлены в `update.overwrite` или в `update.addIfMissing`, если у пользователей уже могут быть свои копии этих файлов; -- `update.overwrite` содержит только файлы, которыми владеет платформа, например CI и манифесты развёртывания. Файлы, которые редактируют разработчики, перенесите в `update.addIfMissing` или оставьте вне списков. +- `update.overwrite` содержит только файлы, которыми владеет платформа, например CI и манифесты развёртывания. + Файлы, которые редактируют разработчики, перенесите в `update.addIfMissing` или оставьте вне списков. ## Утилита ddp-template @@ -223,17 +239,19 @@ deploy/helm/templates/** | Команда | Назначение | | --- | --- | -| `ddp-template lint ` | Проверка `template.yaml`, `values.yaml`, `.templateignore`, списков путей обновления и пробная отрисовка пакета | -| `ddp-template pack ` | Сборка архива пакета без директории `.git` | -| `ddp-template publish --version ` | Проверка, сборка и публикация пакета в хранилище образов. Выводит JSON с полями `templateId`, `version`, `ociRef`, `sha256` | +| `ddp-template lint ` | Проверка `template.yaml`, `values.yaml`, `.templateignore`, списков путей обновления и пробная отрисовка пакета | +| `ddp-template pack ` | Сборка архива пакета без директории `.git` | +| `ddp-template publish --version ` | Проверка, сборка и публикация пакета в хранилище образов. Выводит JSON с полями `templateId`, `version`, `ociRef`, `sha256` | | `ddp-template pull --version ` | Загрузка и распаковка опубликованного пакета | -| `ddp-template render ` | Локальная отрисовка пакета, в том числе с имитацией стратегии обновления | +| `ddp-template render ` | Локальная отрисовка пакета, в том числе с имитацией стратегии обновления | -Коды завершения `ddp-template lint`: `0` — ошибок нет, `1` — есть ошибки, `2` — есть предупреждения. Флаг `--strict` превращает предупреждения в ошибки, флаг `--render-smoke` выполняет только отрисовку со значениями по умолчанию. +Коды завершения `ddp-template lint`: `0` — ошибок нет, `1` — есть ошибки, `2` — есть предупреждения. +Флаг `--strict` превращает предупреждения в ошибки, флаг `--render-smoke` выполняет только отрисовку со значениями по умолчанию. ### Подключение к хранилищу -Параметры подключения к хранилищу задаются флагами, переменными окружения или файлом конфигурации. Флаги имеют приоритет над переменными окружения, переменные окружения — над профилем из файла конфигурации. +Параметры подключения к хранилищу задаются флагами, переменными окружения или файлом конфигурации. +Флаги имеют приоритет над переменными окружения, переменные окружения — над профилем из файла конфигурации. | Параметр | Флаг | Переменная окружения | | --- | --- | --- | @@ -268,7 +286,8 @@ registries: ### Публикация из CI -Версии публикуются из CI по Git-тегу. Пример задачи GitLab CI, которая публикует шаблон `go-service` по тегу `go-service/vX.Y.Z`: +Версии публикуются из CI по Git-тегу. +Пример задачи GitLab CI, которая публикует шаблон `go-service` по тегу `go-service/vX.Y.Z`: ```yaml publish-go-service: @@ -287,7 +306,8 @@ publish-go-service: ### Локальная проверка обновления -Утилита отрисовывает новую версию пакета со значениями существующего микросервиса без обращения к GitLab. Так проверяется, какие файлы изменит обновление. +Утилита отрисовывает новую версию пакета со значениями существующего микросервиса без обращения к GitLab. +Так проверяется, какие файлы изменит обновление. Команды загружают опубликованную версию и отрисовывают её с имитацией стратегии обновления: @@ -304,4 +324,5 @@ ddp-template render ./packs/go-service-1.1.0 \ Где `./values.yaml` — файл со значениями параметров из раздела `values` lock-файла микросервиса. -Команда `ddp-template render` не применяет аннотации `x-ddp-from`: передайте значения таких параметров в файле `--values`. +Команда `ddp-template render` не применяет аннотации `x-ddp-from`. +Передайте значения таких параметров в файле `--values`. diff --git a/content/documentation/admin/templates/registry.md b/content/documentation/admin/templates/registry.md new file mode 100644 index 00000000..f89efbb6 --- /dev/null +++ b/content/documentation/admin/templates/registry.md @@ -0,0 +1,243 @@ +--- +title: Template registry +weight: 20 +description: Connecting container registries with template packs to DDP, sync and automatic upgrade settings, sync runs, the template version catalog, and version statuses. +--- + +The template registry is a set of portal connections to container registries where template packs are published, together with their sync settings. +The portal syncs the connected registries, maintains a catalog of template versions, and determines the latest version of each template. + +The template registry is located in "Administration" → "Integrations" → "Templates". +The page contains the "Registries", "Settings", "Sync runs", and "Templates" tabs. + +## Quick start + +To connect a registry and get templates in the Home page gallery, follow these steps: + +1. On the "Registries" tab, click "Connect registry", fill in the "Name", "Registry", "Repository prefix", "Username", and "Password" fields, and save the connection. +1. On the "Settings" tab, turn on the "Enable sync" toggle and save the settings. +1. On the "Sync runs" tab, click "Sync" and wait for the "Success" status. +1. On the "Templates" tab, make sure that template versions have the "available" status. +1. Bind processes to templates in the Home page mapping rules: "Microservices" → "[Template actions](../home/mapping/#template-actions)". + +After that, the templates are displayed in the "Create microservice" section of the Home page. + +## Access permissions + +The following permissions are used to work with the template registry: + +| Permission | Grants | +| --- | --- | +| `read:template-packs` | Viewing template versions: the "Create microservice" gallery and the new version notification in the microservice card | +| `edit:template-packs` | Deprecating, restoring, and deleting template versions | +| `read:template-registries` | Viewing connections, settings, and sync runs; notifications about prerelease template versions in the microservice card | +| `edit:template-registries` | Changing connections and settings, starting a sync | + +Without the `read:template-registries` permission, the page shows the "You do not have permission to manage the template registry." message. + +## Connecting a registry + +Container registry connections are added on the "Registries" tab with the "Connect registry" button. +The portal supports registries that implement OCI Distribution Spec v2, for example, Harbor, GitLab Container Registry, and Docker Registry. + +Connection fields: + +| Name | Description | +| --- | --- | +| "Name" | Unique registry name, up to 128 characters. Written to microservices created from this registry's templates | +| "Registry" | Container registry host, for example, `registry.vendor.example`. If no scheme is specified, HTTPS is used | +| "Repository prefix" | Path prefix inside the registry, for example, `ddp-templates` | +| "Repository IDs" | IDs of the templates that the portal tracks in the registry | +| "Username" | Registry username | +| "Password" | Registry password or token. If no username is set, the value is used as a Bearer token | +| "Skip TLS verification" | Only for lab environments and self-signed certificates. Allows connecting over HTTP | + +The password is stored encrypted and is not returned to the interface. +To keep the current password when editing a connection, leave the mask in the "Password" field unchanged. + +The portal uses the [trusted certificates](../trusted-certificates/) added to the portal when connecting to the registry. + +The portal does not accept the following in the "Registry" field: + +- The `http://` scheme unless the "Skip TLS verification" option is enabled +- Credentials, query parameters, and fragments in the address +- `localhost` and `*.localhost` names +- IP addresses of loopback, private, link-local, and multicast networks + +### Tracked templates + +The "Repository IDs" field defines how the portal finds templates in the registry. + +If the field is empty, the portal requests the registry's repository catalog with the prefix from the "Repository prefix" field. +New templates appear automatically, and a template deleted from the registry is deprecated entirely. + +If the field is filled in, the portal requests only the listed repositories. +This mode suits large registries and tokens without permission to view the catalog. +New templates are added to the list manually, and a template deleted from the registry remains in the gallery. + +In both modes, versions deleted from tracked repositories are deprecated. + +A template ID is the repository name in the registry without the prefix. +A pack is published at `//:`. + +### Deleting and renaming a connection + +When a connection is deleted or renamed, the available versions of its templates get the "unavailable" status with the `source removed from settings` reason. +Version records are not deleted from the catalog. + +If a connection with the same name is added again, these versions become available on the next sync. + +Versions of deleted connections are shown on the "Templates" tab with the "Registry removed" tag. +The "Delete orphaned ({count})" button deletes them permanently. To confirm, enter `DELETE`. + +## Settings + +The "Settings" tab contains parameters shared by all connections. Changes are applied without restarting the portal. + +The "Synchronization" section: + +| Name | Default value | Description | +| --- | --- | --- | +| "Enable sync" | Disabled | Enables scheduled sync and reconciliation of the microservice template version with the lock file | +| "Sync interval" | `*/15 * * * *` | Cron expression for the sync schedule, in UTC | +| "Max template size (kilobytes)" | `51200` | A pack larger than the limit is rejected during sync | + +The "Defaults for created services" section: + +| Name | Default value | Description | +| --- | --- | --- | +| "Default branch" | `main` | Default branch for created microservices | +| "Upgrade branch prefix" | `ddp/template-upgrade-` | Prefix of the template upgrade branch. The version is appended to it, for example, `ddp/template-upgrade-1.3.0`. Ends with `-` or `/`, contains no spaces or `..`, up to 128 characters | + +Changing the upgrade branch prefix does not take into account merge requests already opened from a branch with the old prefix. + +The "Version reconcile and automation" section: + +| Name | Default value | Description | +| --- | --- | --- | +| "Template version reconcile interval" | `*/5 * * * *` | Cron expression for the microservice template version reconciliation schedule | +| "Automation user" | Not set | User on whose behalf automatic upgrades run and version reconciliation is performed. If not set, automatic upgrades and version reconciliation are disabled | +| "Upgrade queue rate limit" | `5` | Maximum number of automatic upgrades started after a single sync. A value from 1 to 1000 | + +Requirements for the automation user are described in ["Template upgrades"](updates/#automatic-upgrade). + +## Sync + +Sync loads new template versions from the connected registries into the version catalog. + +Sync runs on the schedule from the "Sync interval" parameter if sync is enabled, +or when you click "Sync" on the "Sync runs" tab. +The button starts a sync even when the "Enable sync" parameter is off. + +Only one sync runs at a time. +Starting another sync while one is running fails with the "Template registry sync is already running" error. + +For each connection, sync performs the following steps: + +1. Gets the list of repositories from the "Repository IDs" field or from the registry catalog. +1. For each semver tag that is not yet in the version catalog, downloads the pack and checks its size, the `template.yaml` manifest, the `values.yaml` schema, and the `minDdpVersion` requirement. +1. Writes the version to the catalog with the "available" status or with the reason why the version is unavailable. +1. Deprecates versions whose tags were deleted from the registry. +1. Recalculates the latest version of each template. + +Tags that are not in strict semver format, for example, `v1.2.0` or `latest`, are skipped. +Versions that have already been loaded are not loaded again. + +If the latest version of a template has changed, an [automatic upgrade](updates/#automatic-upgrade) of microservices starts after the sync. + +A connection error for one registry, for example, an authorization error, interrupts the sync of that registry but does not affect the sync of the others. +In this case, the run gets the "Error" status. + +A sync that runs longer than 2 hours is marked as failed with the `interrupted: sync run exceeded stale threshold` error when the portal restarts. + +### Sync runs + +The "Sync runs" tab shows the last 10 runs. +The summary of the last run is displayed above the table, for example, "Last successful synchronization: {time}" or "The last synchronization run failed.". + +Table columns: + +- "Status": "Running", "Success", or "Error". +- "Time": Run start time. +- "Changes": Number of added, deprecated, conflicting, orphaned, and restored versions, or "No changes". +- "Error": Error text. + +The "Refresh" button reloads the list of runs. + +## Version catalog + +The "Templates" tab shows all template versions loaded from the connected registries. + +For each version, the tab shows the template, version, name, registry, status, status reason, sync time, image reference, and SHA-256. +The "Latest" tag marks the recommended template version. + +### Version statuses + +A template version can have the following statuses: + +| Status | Assigned when | Effect on the version | +| --- | --- | --- | +| "available" | The pack is loaded and has passed the checks | Shown in the gallery and used for creation and upgrades | +| "invalid" | The pack could not be downloaded, unpacked, or validated | Not used. The reason is shown in the "Status reason" column | +| "unavailable" | The version requires a newer Deckhouse Development Portal (DDP) version set in `minDdpVersion`, or the connection was deleted | Not used | +| "withdrawn" | The tag was deleted from the registry, or an administrator deprecated the version | Hidden from the gallery and automatic upgrades | + +The portal does not recheck versions with the "invalid" status or versions unavailable because of `minDdpVersion`. +To make the portal load such a version again, delete it on the "Templates" tab. On the next sync, the tag is loaded from the registry again. +To fix a pack, publish a new version. + +### Latest version + +The latest template version is the highest stable version with the "available" status across all connections. +If there are no stable versions, the highest prerelease version, for example, `2.0.0-rc.1`, becomes the latest. + +The latest version is not always the highest version according to semver rules, because deprecated versions are not taken into account. + +### Registry conflict + +If the same template version exists in several connections, the version from the connection that loaded it first is used. +The version shows the "Conflict" tag with a list of the other registries. + +If the version from the first connection becomes unavailable or deprecated, an available copy from another connection replaces it. + +### Deprecating, restoring, and deleting a version + +Managing versions requires the `edit:template-packs` permission. + +The following actions are available for a version: + +- "Deprecate version": The version gets the "withdrawn" status and is hidden from the gallery and automatic upgrades. + Specify the reason in the "Reason" field. + The tag is not deleted from the registry. +- "Restore version": A deprecated version becomes available again. + If the tag is missing from the registry, the next sync may deprecate the version again. +- "Delete": The version record is deleted from the portal. + The tag remains in the registry, and the next sync loads the version again. + +The "invalid" and "unavailable" statuses cannot be changed manually. +Deprecating, restoring, and deleting a version recalculate the latest template version but do not start an automatic upgrade of microservices. + +## Sync errors + +Sync errors are shown in the "Error" column of the run, and errors of individual versions are shown in the "Status reason" column of the version catalog. + +| Message | Cause | Action | +| --- | --- | --- | +| `registry authorization failed` | The registry rejected the credentials | Check the "Username" and "Password" fields of the connection | +| `registry temporarily unavailable` | The registry is unavailable or returned a 429 or 5xx error | Retry the sync later | +| `list repositories: ...` | Failed to get the repository catalog | Check the token's permission to view the catalog or fill in the "Repository IDs" field | +| `pack size N exceeds maxPackSize M` | The pack is larger than the "Maximum template size" parameter | Reduce the pack size or increase the limit, delete the version, and retry the sync | +| `invalid template.yaml: ...` | The manifest failed validation | Fix the manifest and publish a new version | +| `manifest id "a" does not match repository template id "b"` | The `id` field of the manifest does not match the repository name in the registry | Publish the pack to a repository whose name equals `id` | +| `requires DDP version X or newer (running Y)` | The DDP version is lower than the pack's `minDdpVersion` | Update DDP and delete the version so that it is loaded again | +| `tag removed from registry` | The tag was deleted from the registry | — | +| `source removed from settings` | The connection was deleted or renamed | Restore the connection with the same name or delete the orphaned versions | + +Template registry API messages: + +| Message | Cause | +| --- | --- | +| "Invalid template registry" | The connection fields failed validation, for example, the address points to a private network | +| "Invalid template registry settings" | Invalid cron expression, upgrade branch prefix, or limit | +| "Template registry sync is already running" | Another sync was started before the current one finished | +| "Invalid template version status change" | Attempt to change a version status other than "available" or "withdrawn" | diff --git a/content/documentation/admin/templates/registry.ru.md b/content/documentation/admin/templates/registry.ru.md index f461f95f..c8ef7d94 100644 --- a/content/documentation/admin/templates/registry.ru.md +++ b/content/documentation/admin/templates/registry.ru.md @@ -7,19 +7,20 @@ description: Подключение хранилищ образов с паке Реестр шаблонов — это подключения портала к хранилищам образов контейнеров, в которых опубликованы пакеты шаблонов, и настройки их синхронизации. Портал синхронизирует подключённые хранилища, ведёт каталог версий шаблонов и определяет последнюю версию каждого шаблона. -Реестр шаблонов находится в разделе «Администрирование» → «Интеграции» → «Шаблоны». Страница содержит вкладки «Реестры», «Настройки», «Запуски синхронизации» и «Шаблоны». +Реестр шаблонов находится в разделе «Администрирование» → «Интеграции» → «Шаблоны». +Страница содержит вкладки «Реестры», «Настройки», «Запуски синхронизации» и «Шаблоны». ## Быстрый старт -Чтобы подключить хранилище и получить шаблоны в галерее главной: +Чтобы подключить хранилище и получить шаблоны в галерее главной страницы: 1. На вкладке «Реестры» нажмите «Подключить реестр», заполните поля «Название», «Реестр», «Префикс репозиториев», «Имя пользователя», «Пароль» и сохраните подключение. 1. На вкладке «Настройки» включите переключатель «Включить синхронизацию» и сохраните настройки. 1. На вкладке «Запуски синхронизации» нажмите «Синхронизировать» и дождитесь статуса «Успех». -1. На вкладке «Шаблоны» проверьте, что у версий шаблонов статус «доступна». -1. Привяжите процессы к шаблонам в правилах маппинга главной: «Микросервисы» → «[Действия по шаблонам](../home/mapping/#действия-по-шаблонам)». +1. На вкладке «Шаблоны» проверьте, что у версий шаблонов статус «Доступна». +1. Привяжите процессы к шаблонам в правилах маппинга главной страницы: «Микросервисы» → «[Действия по шаблонам](../home/mapping/#действия-по-шаблонам)». -После этого шаблоны отображаются в разделе главной «Создать микросервис». +После этого шаблоны отображаются в разделе главной страницы «Создать микросервис». ## Права доступа @@ -36,11 +37,12 @@ description: Подключение хранилищ образов с паке ## Подключение хранилища -Подключения к хранилищам образов добавляются на вкладке «Реестры» кнопкой «Подключить реестр». Портал поддерживает хранилища с OCI Distribution Spec v2, например Harbor, GitLab Container Registry, Docker Registry. +Подключения к хранилищам образов добавляются на вкладке «Реестры» кнопкой «Подключить реестр». +Портал поддерживает хранилища с OCI Distribution Spec v2, например Harbor, GitLab Container Registry, Docker Registry. Поля подключения: -| Поле | Описание | +| Название | Описание | | --- | --- | | «Название» | Уникальное название реестра, до 128 символов. Записывается в микросервисы, созданные из шаблонов этого реестра | | «Реестр» | Хост хранилища образов, например `registry.vendor.example`. Без схемы используется HTTPS | @@ -50,7 +52,8 @@ description: Подключение хранилищ образов с паке | «Пароль» | Пароль или токен хранилища. Если имя пользователя не задано, значение используется как Bearer-токен | | «Пропускать проверку TLS» | Только для лабораторных сред и самоподписанных сертификатов. Разрешает подключение по HTTP | -Пароль хранится в зашифрованном виде и не возвращается в интерфейс. Чтобы сохранить текущий пароль при изменении подключения, оставьте маску в поле «Пароль» без изменений. +Пароль хранится в зашифрованном виде и не возвращается в интерфейс. +Чтобы сохранить текущий пароль при изменении подключения, оставьте маску в поле «Пароль» без изменений. Портал использует [доверенные сертификаты](../trusted-certificates/), добавленные в портал, при подключении к хранилищу. @@ -63,22 +66,29 @@ description: Подключение хранилищ образов с паке ### Отслеживаемые шаблоны -Поле «Идентификаторы репозиториев» определяет, как портал находит шаблоны в хранилище: +Поле «Идентификаторы репозиториев» определяет, как портал находит шаблоны в хранилище. -- поле пустое — портал запрашивает каталог репозиториев хранилища с префиксом из поля «Префикс репозиториев». Новые шаблоны появляются автоматически, а шаблон, удалённый из хранилища, отзывается целиком; -- поле заполнено — портал запрашивает только перечисленные репозитории. Режим подходит для больших хранилищ и токенов без прав на просмотр каталога. Новые шаблоны добавляются в список вручную, а шаблон, удалённый из хранилища, остаётся в галерее. +Если поле пустое, портал запрашивает каталог репозиториев хранилища с префиксом из поля «Префикс репозиториев». +Новые шаблоны появляются автоматически, а шаблон, удалённый из хранилища, отзывается целиком. + +Если поле заполнено, портал запрашивает только перечисленные репозитории. +Режим подходит для больших хранилищ и токенов без прав на просмотр каталога. +Новые шаблоны добавляются в список вручную, а шаблон, удалённый из хранилища, остаётся в галерее. В обоих режимах версии, удалённые из отслеживаемых репозиториев, отзываются. -Идентификатор шаблона — это имя репозитория в хранилище без префикса. Пакет публикуется по адресу `<реестр>/<префикс репозиториев>/<идентификатор шаблона>:<версия>`. +Идентификатор шаблона — это имя репозитория в хранилище без префикса. +Пакет публикуется по адресу `//:`. ### Удаление и переименование подключения -При удалении или переименовании подключения доступные версии его шаблонов получают статус «недоступна» с причиной `source removed from settings`. Записи о версиях в каталоге не удаляются. +При удалении или переименовании подключения доступные версии его шаблонов получают статус «недоступна» с причиной `source removed from settings`. +Записи о версиях в каталоге не удаляются. Если подключение с тем же названием будет добавлено снова, такие версии становятся доступными при следующей синхронизации. -Версии удалённых подключений отображаются на вкладке «Шаблоны» с тегом «реестр удалён». Кнопка «Удалить осиротевшие ({count})» удаляет их безвозвратно; для подтверждения введите `УДАЛИТЬ`. +Версии удалённых подключений отображаются на вкладке «Шаблоны» с тегом «реестр удалён». +Кнопка «Удалить осиротевшие ({count})» удаляет их безвозвратно; для подтверждения введите `УДАЛИТЬ`. ## Настройки @@ -86,7 +96,7 @@ description: Подключение хранилищ образов с паке Раздел «Синхронизация»: -| Параметр | По умолчанию | Описание | +| Название | Значение по умолчанию | Описание | | --- | --- | --- | | «Включить синхронизацию» | Выключено | Включает синхронизацию по расписанию и сверку версии шаблона микросервисов с lock-файлом | | «Интервал синхронизации» | `*/15 * * * *` | Cron-выражение расписания синхронизации, время UTC | @@ -94,16 +104,16 @@ description: Подключение хранилищ образов с паке Раздел «Значения по умолчанию для создаваемых сервисов»: -| Параметр | По умолчанию | Описание | +| Название | Значение по умолчанию | Описание | | --- | --- | --- | | «Ветка по умолчанию» | `main` | Ветка по умолчанию для создаваемых микросервисов | | «Префикс ветки обновления» | `ddp/template-upgrade-` | Префикс ветки обновления шаблона; к нему добавляется версия, например `ddp/template-upgrade-1.3.0`. Заканчивается на `-` или `/`, без пробелов и `..`, до 128 символов | -Смена префикса ветки обновления не учитывает запросы на слияние, уже открытые из ветки со старым префиксом. +Смена префикса ветки обновления не учитывает запросы на слияние (Merge Request), уже открытые из ветки со старым префиксом. Раздел «Сверка версии и автоматизация»: -| Параметр | По умолчанию | Описание | +| Название | Значение по умолчанию | Описание | | --- | --- | --- | | «Интервал сверки версии шаблона» | `*/5 * * * *` | Cron-выражение расписания сверки версии шаблона микросервисов | | «Пользователь автоматизации» | Не задан | Пользователь, от имени которого запускаются автоматические обновления и выполняется сверка версии. Если не задан, автоматическое обновление и сверка версии выключены | @@ -115,12 +125,12 @@ description: Подключение хранилищ образов с паке Синхронизация загружает в каталог версий новые версии шаблонов из подключённых хранилищ. -Синхронизация запускается: - -- по расписанию из параметра «Интервал синхронизации», если включена синхронизация; -- кнопкой «Синхронизировать» на вкладке «Запуски синхронизации». Кнопка запускает синхронизацию и при выключенном параметре «Включить синхронизацию». +Синхронизация запускается по расписанию из параметра «Интервал синхронизации», если включена синхронизация, +или кнопкой «Синхронизировать» на вкладке «Запуски синхронизации». +Кнопка запускает синхронизацию и при выключенном параметре «Включить синхронизацию». -Одновременно выполняется только одна синхронизация. Повторный запуск во время синхронизации завершается ошибкой «Синхронизация реестра шаблонов уже выполняется». +Одновременно выполняется только одна синхронизация. +Повторный запуск во время синхронизации завершается ошибкой «Синхронизация реестра шаблонов уже выполняется». Для каждого подключения синхронизация выполняет следующие шаги: @@ -130,17 +140,20 @@ description: Подключение хранилищ образов с паке 1. Отзывает версии, теги которых удалены из хранилища. 1. Пересчитывает последнюю версию каждого шаблона. -Теги не в формате strict semver, например `v1.2.0` или `latest`, пропускаются. Уже загруженные версии повторно не загружаются. +Теги не в формате strict semver, например `v1.2.0` или `latest`, пропускаются. +Уже загруженные версии повторно не загружаются. Если у шаблона изменилась последняя версия, после синхронизации запускается [автоматическое обновление](updates/#автоматическое-обновление) микросервисов. -Ошибка подключения к одному хранилищу, например ошибка авторизации, прерывает синхронизацию этого хранилища, но не мешает синхронизации остальных. Запуск в этом случае получает статус «Ошибка». +Ошибка подключения к одному хранилищу, например ошибка авторизации, прерывает синхронизацию этого хранилища, но не мешает синхронизации остальных. +Запуск в этом случае получает статус «Ошибка». Синхронизация, которая выполняется дольше 2 часов, при перезапуске портала отмечается как завершённая с ошибкой `interrupted: sync run exceeded stale threshold`. ### Запуски синхронизации -На вкладке «Запуски синхронизации» отображаются последние 10 запусков. Над таблицей выводится итог последнего запуска, например «Последняя успешная синхронизация: {time}» или «Последний запуск синхронизации завершился с ошибкой.». +На вкладке «Запуски синхронизации» отображаются последние 10 запусков. +Над таблицей выводится итог последнего запуска, например «Последняя успешная синхронизация: {time}» или «Последний запуск синхронизации завершился с ошибкой.». Колонки таблицы: @@ -166,21 +179,24 @@ description: Подключение хранилищ образов с паке | --- | --- | --- | | «доступна» | Пакет загружен и прошёл проверки | Отображается в галерее, используется для создания и обновления | | «некорректна» | Пакет не удалось загрузить, распаковать или проверить | Не используется. Причина указана в колонке «Причина статуса» | -| «недоступна» | Версия требует более новой версии DDP (`minDdpVersion`) или подключение удалено | Не используется | +| «недоступна» | Версия требует более новой версии Deckhouse Development Portal (DDP), заданной в `minDdpVersion`, или подключение удалено | Не используется | | «отозвана» | Тег удалён из хранилища или администратор отозвал версию | Скрыта из галереи и автоматического обновления | Портал не проверяет повторно версии со статусом «некорректна» и версии, недоступные из-за `minDdpVersion`. -Чтобы портал загрузил такую версию заново, удалите её на вкладке «Шаблоны»: при следующей синхронизации тег будет загружен из хранилища снова. Если пакет нужно исправить, опубликуйте новую версию. +Чтобы портал загрузил такую версию заново, удалите её на вкладке «Шаблоны»: при следующей синхронизации тег будет загружен из хранилища снова. +Чтобы исправить пакет, опубликуйте новую версию. ### Последняя версия -Последняя версия шаблона — максимальная стабильная версия со статусом «доступна» среди всех подключений. Если стабильных версий нет, последней становится максимальная предварительная (prerelease) версия, например `2.0.0-rc.1`. +Последняя версия шаблона — максимальная стабильная версия со статусом «доступна» среди всех подключений. +Если стабильных версий нет, последней становится максимальная предварительная (prerelease) версия, например `2.0.0-rc.1`. -Последняя версия — это не всегда максимальная версия по правилам semver: отозванные версии не учитываются. +Последняя версия — это не всегда максимальная версия по правилам semver, поскольку отозванные версии не учитываются. ### Конфликт реестров -Если одна и та же версия шаблона есть в нескольких подключениях, используется версия из подключения, которое загрузило её первым. У версии отображается тег «Конфликт» с перечнем других реестров. +Если одна и та же версия шаблона есть в нескольких подключениях, используется версия из подключения, которое загрузило её первым. +У версии отображается тег «Конфликт» с перечнем других реестров. Если версия первого подключения стала недоступной или отозванной, её заменяет доступная копия из другого подключения. @@ -190,9 +206,13 @@ description: Подключение хранилищ образов с паке С версией доступны следующие действия: -- «Отозвать версию» — версия получает статус «отозвана» и скрывается из галереи и автоматического обновления. В поле «Причина» укажите причину отзыва. Тег в хранилище не удаляется; -- «Вернуть версию» — отозванная версия снова становится доступной. Если тега нет в хранилище, следующая синхронизация может снова отозвать версию; -- «Удалить» — запись о версии удаляется из портала. Тег в хранилище остаётся, и следующая синхронизация загрузит версию заново. +- «Отозвать версию» — версия получает статус «отозвана» и скрывается из галереи и автоматического обновления. + В поле «Причина» укажите причину отзыва. + Тег в хранилище не удаляется; +- «Вернуть версию» — отозванная версия снова становится доступной. + Если тега нет в хранилище, следующая синхронизация может снова отозвать версию; +- «Удалить» — запись о версии удаляется из портала. + Тег в хранилище остаётся, и следующая синхронизация загрузит версию заново. Статусы «некорректна» и «недоступна» вручную не меняются. Отзыв, возврат и удаление версии пересчитывают последнюю версию шаблона, но не запускают автоматическое обновление микросервисов. diff --git a/content/documentation/admin/templates/updates.md b/content/documentation/admin/templates/updates.md new file mode 100644 index 00000000..9c34299f --- /dev/null +++ b/content/documentation/admin/templates/updates.md @@ -0,0 +1,261 @@ +--- +title: Template upgrades +weight: 40 +description: How DDP upgrades microservice repositories to a new template version — template binding, manual and automatic upgrades, upgrade strategies, the merge request, version reconciliation, and troubleshooting. +--- + +A template upgrade transfers the changes of a new template version to the repository of a microservice created from this template. +The portal renders the new pack version with the microservice parameter values, applies the changes according to the upgrade strategy in a separate branch, and opens a merge request. +The changes reach the main branch after the microservice owner accepts the merge request. + +## Before you begin + +To upgrade from a template, make sure the following conditions are met: + +- The [template registry](registry/) is connected and synced. +- In the Home page mapping rules, a process for the "Upgrade microservice from template" action is bound to the template: "Microservices" → "[Template actions](../home/mapping/#template-actions)". + The "Microservice template registry" dataset creates the "Upgrade microservice from template" process, which can be bound to any template. +- The microservice was created from a template: the repository contains the `.ddp/template.lock.yaml` lock file, and the template binding properties are filled in for the microservice entity. + +## Binding a microservice to a template + +When a microservice is created from a template, the portal writes the template information to the repository and to the catalog. + +The `.ddp/template.lock.yaml` lock file is written to the repository: + +```yaml +templateId: go-service +templateVersion: 1.2.0 +schemaVersion: 1 +values: + port: 8080 + database: postgres +``` + +The lock file contains the parameter values passed at creation, without the default values from the schema. +The portal uses the lock file to determine the current template version in the repository and the parameter values for rendering a new version. +Do not delete or edit the lock file manually, because the repository cannot be upgraded without it. + +The binding properties are written to the microservice entity. +The table lists the properties of the canonical catalog model and the mapping roles through which the portal finds them: + +| Property | Name | Role | Value | +| --- | --- | --- | --- | +| `template_id` | "Template ID" | `microservice_binding_template_id` | Template ID | +| `template_version` | "Template version" | `microservice_binding_template_version` | Current template version in the repository | +| `template_source` | "Template source" | `microservice_binding_template_source` | Name of the registry the template was obtained from | +| `template_update_policy` | "Microservice template update policy" | `microservice_binding_template_update_policy` | "Manual" (`manual`) or "Auto review" (`review-auto`) | +| `template_upgrade_strategy` | "Microservice template upgrade strategy" | `microservice_binding_template_upgrade_strategy` | Upgrade strategy for this microservice | +| `template_upgrade_overwrite` | "Microservice upgrade overwrite paths" | `microservice_binding_template_upgrade_overwrite` | List of overwritten paths for this microservice | +| `template_upgrade_add_if_missing` | "Microservice upgrade add-if-missing paths" | `microservice_binding_template_upgrade_add_if_missing` | List of added paths for this microservice | +| `default_branch` | — | `microservice_default_branch` | Branch that the merge request with the upgrade targets | +| `vcs_provider` | — | `microservice_vcs_provider` | Version control system provider | +| `vcs_external_service_uuid` | "VCS external service" | `microservice_vcs_external_service_uuid` | GitLab external service that hosts the repository | + +A microservice is bound to a "template and registry" pair: upgrades are offered only from versions of the template in the same registry. + +### Upgrade policy + +The upgrade policy defines whether an upgrade starts automatically after a new template version is released. + +With the "Manual" (`manual`) policy, an upgrade starts only with the "Upgrade" button in the microservice card. +This policy is assigned when a microservice is created. + +With the "Auto review" (`review-auto`) policy, the portal starts an upgrade on its own after the sync that brought a new latest version, and opens a merge request. + +To change the policy, open the microservice entity in the catalog and change the "Microservice template update policy" property. + +### Microservice upgrade settings + +The upgrade strategy and path lists are defined in the template pack manifest. +For an individual microservice, you can override them with the "Microservice template upgrade strategy", "Microservice upgrade overwrite paths", and "Microservice upgrade add-if-missing paths" entity properties. + +The portal selects upgrade settings in the following order: + +1. Upgrade process parameters, if they are filled in at run time. +1. Microservice entity properties, if they are filled in. +1. The `update.strategy`, `update.overwrite`, and `update.addIfMissing` fields of the new template version manifest. +1. The `selective` strategy, if the strategy is not set anywhere. + +The "Upgrade" button and automatic upgrades pass the selected settings in the process launch context. +If the "Upgrade microservice from template" process from the dataset is run without a context, for example, from the catalog, and the "Upgrade strategy" parameter is empty, `selective` is used. + +## Detecting a new version + +A new template version is detected during a template registry sync. +If the sync changes the latest template version, the portal starts an automatic upgrade of the matching microservices. + +In the microservice card on the Home page, the "Version {version} is available" notification is shown when the following conditions are met: + +- The template is set for the microservice entity. +- The template in the same registry has a latest version with the "available" status. +- The latest version is higher than the microservice template version. +- The user has the `read:template-packs` permission. + +Notifications about prerelease versions, for example, `2.0.0-rc.1`, are visible only to users with the `read:template-registries` permission. +Downgrading to an earlier version is not offered. + +## Manual upgrade + +A user starts a manual upgrade from the microservice card on the Home page. +A manual upgrade is available with any upgrade policy. + +To upgrade a microservice, follow these steps: + +1. Open the "Microservices" section of the Home page and select the microservice in the table. +1. On the "Overview" tab, in the "Version {version} is available" block, click "Upgrade". +1. In the "Run process" window, check the parameters and click "Run". +1. Wait for the process to finish and open the merge request in GitLab. + The link to the merge request is saved in the process store. + +The "Upgrade" button is unavailable in the following cases: + +| Tooltip | Cause | +| --- | --- | +| "You do not have permission to run processes on this entity." | The user does not have permission to run actions for the microservice entity | +| "A template upgrade process is already running for this service." | An upgrade process is already running for the microservice | +| "No upgrade process is set for the {template} template. Set it in the Home page mapping rules, in the template actions." | No process for the "Upgrade microservice from template" action is bound to the template | +| "The service has no template, so upgrading from a template is unavailable." | No template is set for the microservice entity | + +## Automatic upgrade + +An automatic upgrade runs the upgrade process without user involvement after a sync that brought a new latest version of the template. + +The portal starts an automatic upgrade of a microservice if all of the following conditions are met: + +- The "Automation user" is set in the template registry settings. +- The microservice has the "Auto review" (`review-auto`) upgrade policy. +- The new latest version is stable, not a prerelease. +- The microservice's template and registry match the template and registry of the new version. +- The microservice template version is in semver format and is lower than the new version. +- The microservice repository is hosted in GitLab. +- A process for the "Upgrade microservice from template" action is bound to the template. +- The upgrade process is bound to the microservice resource in the "Resource" field of the process. +- No upgrade process is running for the microservice. +- The repository has no open merge request from a branch with the prefix from the "Upgrade branch prefix" setting. + +After a single sync, no more upgrades start than the number set in the "Upgrade queue rate limit" setting. +Upgrades with the largest version gap start first: first by major version, then by minor and patch. + +{{< alert level="warning" >}} +Microservices that did not fit within the limit or were skipped because of an open merge request are not queued for an upgrade again until the next template version is released. +Upgrade such microservices with the "Upgrade" button or increase the "Upgrade queue rate limit" before the next version is published. +{{< /alert >}} + +An automatic upgrade also starts after a sync triggered with the "Sync" button, including when the "Enable sync" parameter is off. +Deprecating, restoring, and deleting a version on the "Templates" tab do not start an automatic upgrade. + +### Automation user + +Automatic upgrade processes run on behalf of the automation user, and the process actions are performed with this user's credentials. + +To prepare the automation user, follow these steps: + +1. Create a user, for example, a service user. + An automatic process run does not check the user's permissions on microservice entities. +1. In the user's profile, fill in the GitLab credentials — a personal access token and a username — for the GitLab external service that hosts the microservice repositories. +1. Select the user in the "Automation user" field on the "Settings" tab of the template registry. + +The automation user's credentials are also used to check for open merge requests and to reconcile the template version. + +During automatic upgrades, merge requests are created on behalf of the automation user. +Grant this user's GitLab account only the permissions required to create branches and merge requests in microservice repositories. + +## Upgrade execution + +The "Upgrade microservice from template" process from the "Microservice template registry" dataset consists of two tasks: "Upgrade repository from a template pack" and "Create code review". + +The "Upgrade repository from a template pack" task performs the following steps: + +1. Determines the target version: the version from the "Template version" parameter or the latest available template version from the microservice registry. +1. Clones the main branch of the repository and reads the lock file. + If the version in the lock file differs from the version in the catalog, the portal corrects the version in the catalog according to the lock file. +1. If the version in the lock file is not lower than the target version, completes the task without changes. No merge request is created. +1. Renders the new pack version. + Parameter values: the default values from the new version schema, overridden by the values from the lock file, overridden by the values passed to the process. +1. Creates the `` branch, for example, `ddp/template-upgrade-1.3.0`, from the main branch. +1. Applies the changes according to the upgrade strategy. +1. Writes the new version and parameter values to the lock file. +1. Creates the `chore(template): upgrade -> ` commit and pushes the branch to GitLab. + +The "Create code review" task opens a merge request from the upgrade branch with the `Upgrade to ` title. +The merge request targets the branch from the microservice's `default_branch` property or, if the property is not set, `main`. + +If a merge request from the same branch is already open, the task uses it. +If a merge request from another branch with the same prefix is open, the task fails with the `review_already_open` error. + +The portal does not accept the merge request automatically, does not assign reviewers, and does not send notifications. +The process result is shown in the "My activities" panel and in the process run history. + +### Upgrade strategies + +The upgrade strategy defines which repository files an upgrade changes. Strategies and path list requirements: + +| Strategy | `overwrite` | `addIfMissing` | Behavior | +| --- | --- | --- | --- | +| `selective` | Required | Not used | Overwrites files whose paths match `overwrite` | +| `additive` | Not used | Required | Adds files from `addIfMissing` if they are missing from the repository | +| `selective_additive` | Required | Required | First overwrites files from `overwrite`, then adds files from `addIfMissing` | +| `full` | Optional | Optional | Writes the entire rendered pack over the repository and overwrites every matching file | +| `merge` | Required | Optional | Performs a three-way merge of files from `overwrite`, then adds files from `addIfMissing` | + +Rules for all strategies: + +- Files outside the strategy scope are not changed. +- Files are not deleted: files deleted or renamed in the new template version remain in the repository. +- `template.yaml`, `values.yaml`, and `.templateignore` are not copied to the repository. + +Path lists are glob patterns relative to the repository root. The `**` syntax is supported, for example, `deploy/**`. + +If a list required by the strategy is empty, the upgrade fails with the `invalid_upgrade_config` error. + +### Merging + +The `merge` strategy preserves the changes that developers made to files from `overwrite`. +For each file, the portal compares three versions: + +- Base: The file rendered from the template version specified in the lock file. +- Current: The file in the microservice repository. +- New: The file rendered from the new template version. + +If the file is missing from the repository, the new version of the file is written. +CRLF line endings and the trailing newline at the end of the file are preserved. + +Any merge conflict, including a difference in binary files, aborts the entire upgrade. +Nothing is written to the repository, and the process fails with the `merge_conflict: merge conflict in files: ` error. +To upgrade a microservice with conflicts, set another strategy for it, for example, `selective`, and transfer the changes to the merge request manually. + +## Version reconciliation after merging + +After the merge request is accepted, the portal updates the microservice template version in the catalog. +Reconciliation runs on the schedule from the "Template version reconcile interval" setting. + +Reconciliation runs if the "Enable sync" parameter is on in the registry settings and the "Automation user" is set. +The portal checks microservices whose template version in the catalog is lower than the latest available version, reads the lock file from the `default_branch` branch (or `main`) through the GitLab API, and raises the "Template version" property if the version in the lock file is higher. + +The version in the catalog can only be raised. +After reconciliation, the "Version {version} is available" notification disappears from the microservice card. + +If the automation user is not set, the version in the catalog does not change after the merge request is accepted until the next upgrade run, because the upgrade process corrects the version according to the lock file. + +## Troubleshooting + +Upgrade errors are shown in the process task log. The message starts with an error code. + +| Error code | Cause | Action | +| --- | --- | --- | +| `lock_not_found` | The repository has no `.ddp/template.lock.yaml` file | Restore the lock file. Repositories created without a lock file cannot be upgraded from a template | +| `lock_mismatch` | The lock file was created for a different template | Check the "Template ID" property of the microservice and the lock file | +| `lock_invalid`, `unsupported_lock_schema` | The lock file is corrupted or has an unsupported schema version | Restore the lock file from the repository history | +| `merge_conflict` | Merge conflict with the `merge` strategy | Change the microservice strategy or perform the upgrade manually | +| `invalid_upgrade_config` | A path list required by the strategy is not set | Set the path lists in the pack manifest or in the microservice properties | +| `review_already_open` | A merge request from another upgrade branch is open | Accept or close the open merge request and retry the upgrade | +| `push_failed` | Failed to push the branch to GitLab, for example, a branch with the same name already exists | Delete the upgrade branch in GitLab and retry the upgrade | +| `pack_not_found` | The microservice registry has no suitable template version | Check the microservice template registry and the version status | +| `pack_deprecated`, `pack_unavailable`, `pack_invalid` | The target version is deprecated, unavailable, or invalid | Select another version or restore the version on the "Templates" tab | +| `values_invalid` | The parameter values do not match the new version schema | Pass the missing values to the upgrade process or fix the schema in the new template version | +| `render_failed` | Pack file templating error | Fix the templates and publish a new version | +| `clone_failed` | Failed to clone the repository | Check the GitLab credentials of the user who ran the process | +| `unsupported_vcs_provider` | The microservice version control system provider is not GitLab | — | + +To retry the upgrade, run the process again with the "Upgrade" button. diff --git a/content/documentation/admin/templates/updates.ru.md b/content/documentation/admin/templates/updates.ru.md index dcce00f1..134aca07 100644 --- a/content/documentation/admin/templates/updates.ru.md +++ b/content/documentation/admin/templates/updates.ru.md @@ -5,14 +5,16 @@ description: Как DDP обновляет репозитории микросе --- Обновление из шаблона переносит изменения новой версии шаблона в репозиторий микросервиса, созданного из этого шаблона. -Портал отрисовывает новую версию пакета со значениями параметров микросервиса, применяет изменения по стратегии обновления в отдельной ветке и открывает запрос на слияние. Изменения попадают в основную ветку после того, как владелец микросервиса примет запрос на слияние. +Портал отрисовывает новую версию пакета со значениями параметров микросервиса, применяет изменения по стратегии обновления в отдельной ветке и открывает запрос на слияние (Merge Request). +Изменения попадают в основную ветку после того, как владелец микросервиса примет запрос на слияние. ## Перед началом работы Для обновления из шаблона выполните следующие условия: - подключён и синхронизирован [реестр шаблонов](registry/); -- в правилах маппинга главной для шаблона привязан процесс действия «Обновить микросервис из шаблона»: «Микросервисы» → «[Действия по шаблонам](../home/mapping/#действия-по-шаблонам)». Набор данных «Реестр шаблонов микросервисов» создаёт процесс «Обновить микросервис из шаблона», который можно привязать к любому шаблону; +- в правилах маппинга главной страницы для шаблона привязан процесс действия «Обновить микросервис из шаблона»: «Микросервисы» → «[Действия по шаблонам](../home/mapping/#действия-по-шаблонам)». + Набор данных «Реестр шаблонов микросервисов» создаёт процесс «Обновить микросервис из шаблона», который можно привязать к любому шаблону; - микросервис создан из шаблона: в репозитории есть lock-файл `.ddp/template.lock.yaml`, а у сущности микросервиса заполнены параметры привязки к шаблону. ## Привязка микросервиса к шаблону @@ -30,10 +32,12 @@ values: database: postgres ``` -Lock-файл содержит значения параметров, переданные при создании, без значений по умолчанию из схемы. По lock-файлу портал определяет текущую версию шаблона в репозитории и значения параметров для отрисовки новой версии. -Не удаляйте и не изменяйте lock-файл вручную: без него репозиторий обновить нельзя. +Lock-файл содержит значения параметров, переданные при создании, без значений по умолчанию из схемы. +По lock-файлу портал определяет текущую версию шаблона в репозитории и значения параметров для отрисовки новой версии. +Не удаляйте и не изменяйте lock-файл вручную, поскольку без него репозиторий обновить нельзя. -В сущность микросервиса записываются параметры привязки. В таблице указаны параметры каноничной модели каталога и роли маппинга, через которые портал их находит: +В сущность микросервиса записываются параметры привязки. +В таблице указаны параметры каноничной модели каталога и роли маппинга, через которые портал их находит: | Параметр | Название | Роль маппинга | Значение | | --- | --- | --- | --- | @@ -52,16 +56,19 @@ Lock-файл содержит значения параметров, перед ### Политика обновления -Политика обновления определяет, запускается ли обновление автоматически после выхода новой версии шаблона: +Политика обновления определяет, запускается ли обновление автоматически после выхода новой версии шаблона. -- «Вручную» (`manual`) — обновление запускается только кнопкой «Обновить» в карточке микросервиса. Эта политика назначается при создании микросервиса; -- «Ревью автоматически» (`review-auto`) — портал сам запускает обновление после синхронизации, на которой появилась новая последняя версия, и открывает запрос на слияние. +При политике «Вручную» (`manual`) обновление запускается только кнопкой «Обновить» в карточке микросервиса. +Эта политика назначается при создании микросервиса. + +При политике «Ревью автоматически» (`review-auto`) портал сам запускает обновление после синхронизации, на которой появилась новая последняя версия, и открывает запрос на слияние. Чтобы изменить политику, откройте сущность микросервиса в каталоге и измените параметр «Политика обновления шаблона». ### Настройки обновления микросервиса -Стратегия и списки путей обновления задаются в манифесте пакета шаблона. Для отдельного микросервиса их можно переопределить параметрами сущности «Стратегия обновления шаблона», «Перезаписываемые пути обновления» и «Добавляемые пути обновления». +Стратегия и списки путей обновления задаются в манифесте пакета шаблона. +Для отдельного микросервиса их можно переопределить параметрами сущности «Стратегия обновления шаблона», «Перезаписываемые пути обновления» и «Добавляемые пути обновления». Портал выбирает настройки обновления в следующем порядке: @@ -70,31 +77,36 @@ Lock-файл содержит значения параметров, перед 1. Поля `update.strategy`, `update.overwrite` и `update.addIfMissing` манифеста новой версии шаблона. 1. Стратегия `selective`, если стратегия нигде не задана. -Кнопка «Обновить» и автоматическое обновление передают выбранные настройки в контексте запуска процесса. Если процесс «Обновить микросервис из шаблона» из набора данных запускается без контекста, например из каталога, при пустом параметре «Стратегия обновления» используется `selective`. +Кнопка «Обновить» и автоматическое обновление передают выбранные настройки в контексте запуска процесса. +Если процесс «Обновить микросервис из шаблона» из набора данных запускается без контекста, например из каталога, при пустом параметре «Стратегия обновления» используется `selective`. ## Обнаружение новой версии -Новая версия шаблона обнаруживается при синхронизации реестра шаблонов. Если в результате синхронизации изменилась последняя версия шаблона, портал запускает автоматическое обновление подходящих микросервисов. +Новая версия шаблона обнаруживается при синхронизации реестра шаблонов. +Если в результате синхронизации изменилась последняя версия шаблона, портал запускает автоматическое обновление подходящих микросервисов. -В карточке микросервиса на главной уведомление «Доступна версия {version}» отображается, если выполнены условия: +В карточке микросервиса на главной странице уведомление «Доступна версия {version}» отображается, если выполнены условия: - у сущности микросервиса задан шаблон; - у шаблона того же реестра есть последняя версия со статусом «доступна»; - последняя версия выше версии шаблона микросервиса; - у пользователя есть разрешение `read:template-packs`. -Уведомления о предварительных версиях, например `2.0.0-rc.1`, видят только пользователи с разрешением `read:template-registries`. Переход на более раннюю версию не предлагается. +Уведомления о предварительных версиях, например `2.0.0-rc.1`, видят только пользователи с разрешением `read:template-registries`. +Переход на более раннюю версию не предлагается. ## Ручное обновление -Ручное обновление запускает пользователь из карточки микросервиса на главной. Ручное обновление доступно при любой политике обновления. +Ручное обновление запускает пользователь из карточки микросервиса на главной странице. +Ручное обновление доступно при любой политике обновления. Чтобы обновить микросервис: -1. Откройте раздел главной «Микросервисы» и выберите микросервис в таблице. +1. Откройте раздел главной страницы «Микросервисы» и выберите микросервис в таблице. 1. На вкладке «Справка» в блоке «Доступна версия {version}» нажмите «Обновить». 1. В окне «Запустить процесс» проверьте параметры и нажмите «Запустить». -1. Дождитесь завершения процесса и откройте запрос на слияние в GitLab. Ссылка на запрос на слияние сохраняется в хранилище процесса. +1. Дождитесь завершения процесса и откройте запрос на слияние в GitLab. + Ссылка на запрос на слияние сохраняется в хранилище процесса. Кнопка «Обновить» недоступна в следующих случаях: @@ -122,7 +134,8 @@ Lock-файл содержит значения параметров, перед - для микросервиса не выполняется процесс обновления; - в репозитории нет открытого запроса на слияние из ветки с префиксом из настройки «Префикс ветки обновления». -После одной синхронизации запускается не больше обновлений, чем задано в настройке «Лимит очереди обновлений». Первыми запускаются обновления с наибольшим разрывом версий: сначала по major-версии, затем по minor и patch. +После одной синхронизации запускается не больше обновлений, чем задано в настройке «Лимит очереди обновлений». +Первыми запускаются обновления с наибольшим разрывом версий: сначала по major-версии, затем по minor и patch. {{< alert level="warning" >}} Микросервисы, которые не попали в лимит или были пропущены из-за открытого запроса на слияние, повторно не ставятся на обновление до выхода следующей версии шаблона. @@ -145,7 +158,8 @@ Lock-файл содержит значения параметров, перед Учётные данные пользователя автоматизации используются также для проверки открытых запросов на слияние и для сверки версии шаблона. -Запросы на слияние при автоматическом обновлении создаются от имени пользователя автоматизации. Выдайте его учётной записи GitLab только права, необходимые для создания веток и запросов на слияние в репозиториях микросервисов. +Запросы на слияние при автоматическом обновлении создаются от имени пользователя автоматизации. +Выдайте его учётной записи GitLab только права, необходимые для создания веток и запросов на слияние в репозиториях микросервисов. ## Выполнение обновления @@ -154,22 +168,24 @@ Lock-файл содержит значения параметров, перед Задача «Обновление репозитория из шаблона» выполняет следующие шаги: 1. Определяет целевую версию: версию из параметра «Версия шаблона» или последнюю доступную версию шаблона из реестра микросервиса. -1. Клонирует основную ветку репозитория и читает lock-файл. Если версия в lock-файле отличается от версии в каталоге, портал исправляет версию в каталоге по lock-файлу. +1. Клонирует основную ветку репозитория и читает lock-файл. + Если версия в lock-файле отличается от версии в каталоге, портал исправляет версию в каталоге по lock-файлу. 1. Если версия в lock-файле не ниже целевой, завершает задачу без изменений; запрос на слияние не создаётся. -1. Отрисовывает новую версию пакета. Значения параметров: значения по умолчанию из схемы новой версии, поверх них — значения из lock-файла, поверх них — значения, переданные в процесс. -1. Создаёт ветку `<префикс ветки обновления><версия>`, например `ddp/template-upgrade-1.3.0`, от основной ветки. +1. Отрисовывает новую версию пакета. + Значения параметров: значения по умолчанию из схемы новой версии, поверх них — значения из lock-файла, поверх них — значения, переданные в процесс. +1. Создаёт ветку ``, например `ddp/template-upgrade-1.3.0`, от основной ветки. 1. Применяет изменения по стратегии обновления. 1. Записывает в lock-файл новую версию и значения параметров. 1. Создаёт коммит `chore(template): upgrade <старая версия> -> <новая версия>` и отправляет ветку в GitLab. -Задача «Создание код-ревью» открывает запрос на слияние из ветки обновления: - -- в ветку из параметра `default_branch` микросервиса, если он не задан — в `main`; -- с заголовком `Upgrade to `. +Задача «Создание код-ревью» открывает запрос на слияние из ветки обновления с заголовком `Upgrade to `. +Запрос на слияние создаётся в ветку из параметра `default_branch` микросервиса, а если параметр не задан — в `main`. -Если запрос на слияние из этой же ветки уже открыт, задача использует его. Если открыт запрос на слияние из другой ветки с тем же префиксом, задача завершается ошибкой `review_already_open`. +Если запрос на слияние из этой же ветки уже открыт, задача использует его. +Если открыт запрос на слияние из другой ветки с тем же префиксом, задача завершается ошибкой `review_already_open`. -Портал не принимает запрос на слияние автоматически, не назначает ревьюеров и не отправляет уведомлений. Результат процесса отображается в панели «Мои активности» и в истории запусков процесса. +Портал не принимает запрос на слияние автоматически, не назначает ревьюеров и не отправляет уведомлений. +Результат процесса отображается в панели «Мои активности» и в истории запусков процесса. ### Стратегии обновления @@ -195,27 +211,32 @@ Lock-файл содержит значения параметров, перед ### Слияние -Стратегия `merge` сохраняет изменения, которые разработчики внесли в файлы из `overwrite`. Для каждого файла портал сравнивает три версии: +Стратегия `merge` сохраняет изменения, которые разработчики внесли в файлы из `overwrite`. +Для каждого файла портал сравнивает три версии: - базовую — файл, отрисованный из версии шаблона, указанной в lock-файле; - текущую — файл в репозитории микросервиса; - новую — файл, отрисованный из новой версии шаблона. -Если файла нет в репозитории, записывается новая версия файла. Переводы строк CRLF и перевод строки в конце файла сохраняются. +Если файла нет в репозитории, записывается новая версия файла. +Переводы строк CRLF и перевод строки в конце файла сохраняются. -Любой конфликт слияния, в том числе различие бинарных файлов, прерывает обновление целиком: в репозиторий ничего не записывается, а процесс завершается ошибкой `merge_conflict: merge conflict in files: <файлы>`. +Любой конфликт слияния, в том числе различие бинарных файлов, прерывает обновление целиком. +В репозиторий ничего не записывается, а процесс завершается ошибкой `merge_conflict: merge conflict in files: <файлы>`. Чтобы обновить микросервис с конфликтами, задайте для него другую стратегию, например `selective`, и перенесите изменения вручную в запрос на слияние. ## Сверка версии после слияния -После принятия запроса на слияние портал обновляет версию шаблона микросервиса в каталоге. Сверка выполняется по расписанию из настройки «Интервал сверки версии шаблона». +После принятия запроса на слияние портал обновляет версию шаблона микросервиса в каталоге. +Сверка выполняется по расписанию из настройки «Интервал сверки версии шаблона». Сверка выполняется, если в настройках реестра включён параметр «Включить синхронизацию» и задан «Пользователь автоматизации». Портал проверяет микросервисы, у которых версия шаблона в каталоге ниже последней доступной версии, читает lock-файл из ветки `default_branch` (или `main`) через API GitLab и повышает параметр «Версия шаблона», если версия в lock-файле выше. -Версия в каталоге только повышается. После сверки уведомление «Доступна версия {version}» в карточке микросервиса исчезает. +Версия в каталоге только повышается. +После сверки уведомление «Доступна версия {version}» в карточке микросервиса исчезает. -Если пользователь автоматизации не задан, версия в каталоге после принятия запроса на слияние не меняется до следующего запуска обновления: процесс обновления исправляет версию по lock-файлу. +Если пользователь автоматизации не задан, версия в каталоге после принятия запроса на слияние не меняется до следующего запуска обновления, поскольку процесс обновления исправляет версию по lock-файлу. ## Устранение ошибок diff --git a/content/documentation/admin/trusted-certificates.md b/content/documentation/admin/trusted-certificates.md index 7ec8dd69..575e3fde 100644 --- a/content/documentation/admin/trusted-certificates.md +++ b/content/documentation/admin/trusted-certificates.md @@ -5,12 +5,14 @@ description: Add certificates for secure HTTPS connections from Deckhouse Develo weight: 73 --- -Trusted certificates allow you to upload root and intermediate certificate authority (CA) certificates or server certificates to Deckhouse Development Portal (DDP, portal). The portal uses them for TLS/SSL verification when connecting to external services over HTTPS, for example when accessing external service APIs from data sources and widgets. +Trusted certificates allow you to upload root and intermediate certificate authority (CA) certificates or server certificates to Deckhouse Development Portal (DDP, portal). +The portal uses them for TLS/SSL verification when connecting to external services over HTTPS, for example when accessing external service APIs from datasources and widgets. This mechanism provides secure connections to services that use self-signed or corporate certificates without disabling SSL verification. {{< alert level="info" >}} -Add certificates for Dex, PostgreSQL, and Redis to the `extraCA` module parameter in ModuleConfig `development-platform` (`spec.settings.extraCA`) or in the module settings in the Deckhouse Platform web interface. DDP connects to these internal services before enabling the trusted certificate mechanism. +Add certificates for Dex, PostgreSQL, and Redis to the `extraCA` module parameter in ModuleConfig `development-platform` (`spec.settings.extraCA`) or in the module settings in the Deckhouse Platform web interface. +DDP connects to these internal services before enabling the trusted certificate mechanism. {{< /alert >}} Configure trusted certificates under "Administration" → "Trusted certificates". @@ -19,7 +21,7 @@ Configure trusted certificates under "Administration" → "Trusted certificates" Specify the following parameters when adding a trusted certificate: -| Parameter | Description | +| Name | Description | |-----------|-------------| | "Name" | Certificate name displayed in the interface, for example "Corporate CA" | | "Certificate (PEM)" | Certificate content in PEM format. Required when creating the certificate | @@ -35,19 +37,22 @@ MIIDXTCCAkWgAwIBAgIJAKL... After you save the certificate, its card displays data extracted from the PEM content, including the subject, issuer, validity period, and alternative names. -When editing a certificate, the "Certificate (PEM)" field is hidden. For security, the API does not return the saved value. To update a certificate, create a new record and delete the old one if necessary. +When editing a certificate, the "Certificate (PEM)" field is hidden. +For security, the API does not return the saved value. +To update a certificate, create a new record and delete the old one if necessary. ## Usage -Uploaded trusted certificates are automatically added to the root certificate pool used by DDP Backend for outgoing HTTPS requests. This pool is used for: +Uploaded trusted certificates are automatically added to the root certificate pool used by DDP Backend for outgoing HTTPS requests. +This pool is used for requests to external services from actions, widgets, datasources, and status checks, +as well as for requests to infrastructure system APIs such as GitLab, Kubernetes, Vault, and Prometheus. -- requests to external services from actions, widgets, data sources, and status checks; -- requests to infrastructure system APIs such as GitLab, Kubernetes, Vault, and Prometheus. - -If an external service uses a certificate issued by your own or a corporate CA, add the corresponding root or intermediate certificate under "Trusted certificates". The portal then trusts the connection without disabling SSL verification. +If an external service uses a certificate issued by your own or a corporate CA, add the corresponding root or intermediate certificate under "Trusted certificates". +The portal then trusts the connection without disabling SSL verification. {{< alert level="info" >}} -Instead of disabling SSL verification for an external service with the "Disable SSL verification" option, add the required certificates as trusted. This preserves authentication and connection security. +Instead of disabling SSL verification for an external service with the "Disable SSL verification" option, add the required certificates as trusted. +This preserves authentication and connection security. {{< /alert >}} Changes to the trusted certificate list, including additions, updates, and deletions, apply to new outgoing connections without restarting DDP. @@ -56,9 +61,9 @@ Changes to the trusted certificate list, including additions, updates, and delet Trusted certificate management is controlled by the following global permissions: -- `read:trusted-certificates` — view the certificate list and details; -- `create:trusted-certificates` — add certificates; -- `update:trusted-certificates` — edit the name of an existing certificate; -- `delete:trusted-certificates` — delete certificates. +- `read:trusted-certificates`: View the certificate list and details. +- `create:trusted-certificates`: Add certificates. +- `update:trusted-certificates`: Edit the name of an existing certificate. +- `delete:trusted-certificates`: Delete certificates. For details about the role model, refer to the [RBAC documentation](../security/rbac/). diff --git a/content/documentation/admin/trusted-certificates.ru.md b/content/documentation/admin/trusted-certificates.ru.md index 64af1737..602428cc 100644 --- a/content/documentation/admin/trusted-certificates.ru.md +++ b/content/documentation/admin/trusted-certificates.ru.md @@ -5,12 +5,14 @@ description: Добавление сертификатов для защищён weight: 73 --- -Механизм доверенных сертификатов позволяет загрузить в Deckhouse Development Portal (DDP, портал) корневые и промежуточные сертификаты (CA) или сертификаты серверов. Портал использует их при проверке TLS/SSL при подключении к внешним сервисам по HTTPS — например, при обращении к API внешних сервисов в источниках данных, виджетах и т. д. +Механизм доверенных сертификатов позволяет загрузить в Deckhouse Development Portal (DDP, портал) корневые и промежуточные сертификаты (CA) или сертификаты серверов. +Портал использует их при проверке TLS/SSL при подключении к внешним сервисам по HTTPS — например, при обращении к API внешних сервисов в источниках данных, виджетах и т. д. Это даёт возможность безопасно работать с сервисами, использующими самоподписанные или корпоративные сертификаты, без отключения проверки SSL. {{< alert level="info" >}} -Для Dex, PostgreSQL и Redis, используемых порталом в качестве служебных сервисов, сертификаты необходимо добавлять в параметр модуля `extraCA` в ModuleConfig `development-platform` (`spec.settings.extraCA`) или в настройках модуля в веб-интерфейсе Deckhouse Platform: соединение с этими компонентами устанавливается до включения механизма доверенных сертификатов. +Для Dex, PostgreSQL и Redis, используемых порталом в качестве служебных сервисов, сертификаты добавляйте в параметр модуля `extraCA` в ModuleConfig `development-platform` (`spec.settings.extraCA`) или в настройках модуля в веб-интерфейсе Deckhouse Platform. +Соединение с этими компонентами устанавливается до включения механизма доверенных сертификатов. {{< /alert >}} Настройка доверенных сертификатов осуществляется в разделе «Администрирование» → «Доверенные сертификаты». @@ -19,7 +21,7 @@ weight: 73 При добавлении доверенного сертификата указываются следующие параметры: -| Параметр | Описание | +| Название | Описание | |-----------------------|-------------------------------------------------------------------------------| | «Название» | Отображаемое название сертификата в интерфейсе (например, «Корпоративный CA») | | «Сертификат (PEM)» | Содержимое сертификата в формате PEM. Обязателен при создании | @@ -35,19 +37,22 @@ MIIDXTCCAkWgAwIBAgIJAKL... После сохранения в карточке сертификата отображаются данные, извлечённые из PEM: субъект, издатель, срок действия, альтернативные имена и т. д. -При редактировании сертификата поле «Сертификат (PEM)» скрыто. Сохранённое значение не возвращается API из соображений безопасности. Чтобы обновить сертификат, создайте новую запись и, при необходимости, удалите старую. +При редактировании сертификата поле «Сертификат (PEM)» скрыто. +Сохранённое значение не возвращается API из соображений безопасности. +Чтобы обновить сертификат, создайте новую запись и, при необходимости, удалите старую. ## Использование -Загруженные доверенные сертификаты автоматически добавляются в пул корневых сертификатов, используемый DDP Backend при исходящих HTTPS-запросах. Этот пул применяется при: +Загруженные доверенные сертификаты автоматически добавляются в пул корневых сертификатов, используемый DDP Backend при исходящих HTTPS-запросах. +Этот пул применяется при обращении к внешним сервисам (действия, виджеты, источники данных, проверки статуса) +и при запросах к API инфраструктурных систем (GitLab, Kubernetes, Vault, Prometheus и др.). -- обращении к внешним сервисам (действия, виджеты, источники данных, проверки статуса); -- запросах к API инфраструктурных систем (GitLab, Kubernetes, Vault, Prometheus и др.). - -Если внешний сервис использует сертификат, выпущенный вашим или корпоративным CA, добавьте соответствующий корневой или промежуточный сертификат в разделе «Доверенные сертификаты». После этого портал доверяет таким соединениям без отключения проверки SSL. +Если внешний сервис использует сертификат, выпущенный вашим или корпоративным CA, добавьте соответствующий корневой или промежуточный сертификат в разделе «Доверенные сертификаты». +После этого портал доверяет таким соединениям без отключения проверки SSL. {{< alert level="info" >}} -Вместо отключения проверки SSL во внешнем сервисе (опция «Выключить проверку SSL») добавьте нужные сертификаты в доверенные. Это сохраняет проверку подлинности и защиту соединения. +Вместо отключения проверки SSL во внешнем сервисе (опция «Выключить проверку SSL») добавьте нужные сертификаты в доверенные. +Это сохраняет проверку подлинности и защиту соединения. {{< /alert >}} Изменения списка доверенных сертификатов (добавление, изменение, удаление) применяются к новым исходящим соединениям без перезапуска DDP. diff --git a/content/documentation/admin/webhooks.md b/content/documentation/admin/webhooks.md new file mode 100644 index 00000000..77c2cec7 --- /dev/null +++ b/content/documentation/admin/webhooks.md @@ -0,0 +1,14 @@ +--- +title: Webhooks +menuTitle: Webhooks +description: Receiving data from external systems using the push model and processing it according to webhook rules. +weight: 71 +--- + +Webhooks work similarly to datasources. +However, a datasource uses the pull model, that is, it polls infrastructure systems itself and tries to load data from them, while webhooks expect data to be sent from outside, that is, they use the push model. + +Processing rules (creation, matching, update, and relation creation) are configured the same way as similar rules in datasources. + +Each webhook has a unique URL built using the following template: `/webhooks/`. +A webhook accepts POST requests with an array of data in any format, which is processed according to the webhook rules. diff --git a/content/documentation/admin/webhooks.ru.md b/content/documentation/admin/webhooks.ru.md index 74deec2c..f35dd711 100644 --- a/content/documentation/admin/webhooks.ru.md +++ b/content/documentation/admin/webhooks.ru.md @@ -5,8 +5,10 @@ description: Приём данных из внешних систем по push- weight: 71 --- -По механизму действия вебхуки похожи на источники данных. При этом, если источник данных работает по pull-модели, то есть сам опрашивает инфраструктурные системы и пытается загрузить из них данные, то вебхуки ожидают, что данные будут отправлены извне, то есть работают по push-модели. +По механизму действия вебхуки похожи на источники данных. +При этом, если источник данных работает по pull-модели, то есть сам опрашивает инфраструктурные системы и пытается загрузить из них данные, то вебхуки ожидают, что данные будут отправлены извне, то есть работают по push-модели. При этом настройка правил обработки (создание, сопоставление, обновление, создание связей) аналогична настройке подобных правил в источниках данных. -У каждого вебхука есть уникальный URL, который формируется по шаблону: `/webhooks/`. Вебхук принимает POST-запросы с массивом данных любого формата, который обрабатывается на основе правил вебхука. +У каждого вебхука есть уникальный URL, который формируется по шаблону: `/webhooks/`. +Вебхук принимает POST-запросы с массивом данных любого формата, который обрабатывается на основе правил вебхука. diff --git a/content/documentation/admin/widgets/ai/chat.md b/content/documentation/admin/widgets/ai/chat.md index 30fb681f..f2ae1741 100644 --- a/content/documentation/admin/widgets/ai/chat.md +++ b/content/documentation/admin/widgets/ai/chat.md @@ -4,10 +4,13 @@ description: Configuration and usage of the language-model chat widget weight: 10 --- -The AI chat widget sends requests to a language model through the selected AI provider. You can configure general instructions (the Global prompt) and a set of quick-question buttons (Quick questions). +The AI chat widget sends requests to a language model through the selected AI provider. +You can configure general instructions (the Global prompt) and a set of quick-question buttons (Quick questions). ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Global prompt | No | General instructions for each request. The widget combines them with the prompt of the selected quick question before sending it | @@ -33,9 +36,7 @@ Example prompt for a quick question: To use the widget, add at least one [AI provider](../../../../user/ai-assistant/#connecting-an-ai-provider). -The chat does not retain history: - -- It displays only one response to the most recent question. -- The response is not retained when the user navigates to another page or refreshes the page. +The chat does not retain history. +It displays only one response to the most recent question, and the response is not retained when the user navigates to another page or refreshes the page. Before sending a question, the user can customize the prompt by selecting **Send with customization** from the question button menu. diff --git a/content/documentation/admin/widgets/ai/chat.ru.md b/content/documentation/admin/widgets/ai/chat.ru.md index ddfa0aa3..279a415f 100644 --- a/content/documentation/admin/widgets/ai/chat.ru.md +++ b/content/documentation/admin/widgets/ai/chat.ru.md @@ -8,6 +8,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------ | | Агент | Нет | Агент, который отвечает в виджете. По умолчанию — платформенный агент. Задаётся только в настройках виджета, при работе с виджетом агента сменить нельзя | @@ -21,7 +23,9 @@ weight: 10 | Название вопроса | Да | Короткая подпись, отображаемая на нижней панели виджета и в чате | | Промпт | Да | Инструкция для модели при нажатии на эту кнопку; допускается использование Go-шаблонизации | -При заполнении промпта явно укажите названия инструментов Model Context Protocol (MCP), которые должен вызвать агент при подготовке ответа. Агент получает инструменты назначенных ему MCP-коллекций, которыми может пользоваться запускающий пользователь. Без коллекций агент работает без MCP-инструментов. +При заполнении промпта явно укажите названия инструментов Model Context Protocol (MCP), которые должен вызвать агент при подготовке ответа. +Агент получает инструменты назначенных ему MCP-коллекций, которыми может пользоваться запускающий пользователь. +Без коллекций агент работает без MCP-инструментов. Чтобы использовать `get_external_data` в промпте, включите его в [MCP-коллекции агента](../../ai-agents/platform-agent/#изменение-инструментов-и-навыков) и предоставьте пользователю доступ к этому инструменту через коллекцию. @@ -34,13 +38,12 @@ weight: 10 ## Использование виджета -Для работы с виджетом требуется глобальное `use:ai-agents` или объектное `use:ai-agent` на выбранного агента. Если модель агенту предоставляет портал (платформенный агент или внешний агент с разрешённым прокси моделей DDP), у пользователя должен быть [AI-провайдер](../../../../user/ai-assistant/#подключение-ai-провайдера). +Для работы с виджетом требуется глобальное `use:ai-agents` или объектное `use:ai-agent` на выбранного агента. +Если модель агенту предоставляет портал, например платформенному агенту или внешнему агенту с разрешённым прокси моделей Deckhouse Development Portal (DDP), у пользователя должен быть [AI-провайдер](../../../../user/ai-assistant/#подключение-ai-провайдера). Для виджетов на странице сущности агент получает UUID сущности в контексте задачи. -У чата не предусмотрена история: - -- Выводится только один ответ на последний заданный вопрос. -- Ответ не сохраняется при переходе на другую страницу или при обновлении страницы. +У чата не предусмотрена история. +Выводится только один ответ на последний заданный вопрос, и ответ не сохраняется при переходе на другую страницу или при обновлении страницы. Перед отправкой вопроса измените промпт, выбрав пункт «Отправить с изменением промпта» в выпадающем меню кнопки вопроса. diff --git a/content/documentation/admin/widgets/bitbucket/pull-requests.md b/content/documentation/admin/widgets/bitbucket/pull-requests.md index 40d00d68..5c161c48 100644 --- a/content/documentation/admin/widgets/bitbucket/pull-requests.md +++ b/content/documentation/admin/widgets/bitbucket/pull-requests.md @@ -1,5 +1,5 @@ --- -title: Bitbucket. Pull Requests +title: Bitbucket. Pull requests description: Configuration, status filtering, and actions for Bitbucket pull requests. weight: 10 --- @@ -8,6 +8,8 @@ The widget displays Bitbucket Pull Request (PR) data and provides actions for ma ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Example | | ------------- | -------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------- | | Project key | Yes | The part of the repository URL immediately after `/projects/` | For `https:///projects/MYTEAM/repos/backend`, specify `MYTEAM` | @@ -15,16 +17,17 @@ The widget displays Bitbucket Pull Request (PR) data and provides actions for ma where: -- `` — the hostname of the Bitbucket server. +- ``: The hostname of the Bitbucket server. ## Filtering by status -The widget can filter displayed Pull Requests by status. Select one of the following statuses in the widget request settings: +The widget can filter displayed Pull Requests by status. +Select one of the following statuses in the widget request settings: -- **Open** — displays only open PRs. -- **Merged** — displays only merged PRs. -- **Declined** — displays only declined PRs. -- **All** — displays PRs in any status. +- **Open**: Displays only open PRs. +- **Merged**: Displays only merged PRs. +- **Declined**: Displays only declined PRs. +- **All**: Displays PRs in any status. By default, the widget displays only open PRs. @@ -32,16 +35,16 @@ By default, the widget displays only open PRs. The widget provides the following actions: -- **Merge** — merges an open Pull Request. This action is available only for open PRs. -- **Close** — declines a Pull Request. -- **Changes** — displays the diff for a Pull Request. -- **Comments** — displays and adds comments to a PR. -- **Create PR** — creates a Pull Request with a source branch, target branch, reviewers, title, and description. +- **Merge**: Merges an open Pull Request. This action is available only for open PRs. +- **Close**: Declines a Pull Request. +- **Changes**: Displays the diff for a Pull Request. +- **Comments**: Displays and adds comments to a PR. +- **Create PR**: Creates a Pull Request with a source branch, target branch, reviewers, title, and description. {{< alert level="info" >}} Pull Request actions require the corresponding permissions in the Bitbucket repository. {{< /alert >}} -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#bitbucket). diff --git a/content/documentation/admin/widgets/bitbucket/pull-requests.ru.md b/content/documentation/admin/widgets/bitbucket/pull-requests.ru.md index c2811d0a..d00b1745 100644 --- a/content/documentation/admin/widgets/bitbucket/pull-requests.ru.md +++ b/content/documentation/admin/widgets/bitbucket/pull-requests.ru.md @@ -8,6 +8,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Пример | | ------------------------- | -------------- | ------------------------------------------------------------ | --------------------------------------------------------------------- | | Ключ проекта | Да | Часть URL репозитория, которая идёт сразу после `/projects/` | Для `https:///projects/MYTEAM/repos/backend` укажите `MYTEAM` | @@ -19,7 +21,8 @@ weight: 10 ## Фильтрация по статусу -Виджет позволяет фильтровать отображаемые запросы на слияние по статусу. В настройках запроса виджета можно выбрать один из следующих статусов: +Виджет позволяет фильтровать отображаемые запросы на слияние по статусу. +В настройках запроса виджета можно выбрать один из следующих статусов: - «Открыт» — показывает только открытые PR. - «Слит» — показывает только слитые PR. diff --git a/content/documentation/admin/widgets/bitbucket/tags.md b/content/documentation/admin/widgets/bitbucket/tags.md index bf844941..7fe2e891 100644 --- a/content/documentation/admin/widgets/bitbucket/tags.md +++ b/content/documentation/admin/widgets/bitbucket/tags.md @@ -8,6 +8,8 @@ The widget displays data about tags in a Bitbucket repository. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Example | | ----------- | -------- | -------------------------------------------------------------- | ---------------------------------------------------------- | | Project key | Yes | The part of the repository URL immediately after `/projects/` | For `https:///projects/MYTEAM/repos/backend`, specify `MYTEAM` | @@ -15,7 +17,7 @@ The widget displays data about tags in a Bitbucket repository. where: -- `` — the hostname of the Bitbucket server. +- ``: The hostname of the Bitbucket server. ## Displayed data @@ -24,18 +26,22 @@ including the hash, message, author, creation date, and a link to the commit in ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Creating tags The widget can create tags in Bitbucket directly from Deckhouse Development Portal (DDP). #### Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | | ----------- | -------- | ---------------------------------------------------------------------------- | | Name | Yes | The name of the tag to create | | Create from | Yes | The branch or existing tag from which to create the new tag. Select it from the list | | Description | No | The description of the tag to create | -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#bitbucket). diff --git a/content/documentation/admin/widgets/bitbucket/tags.ru.md b/content/documentation/admin/widgets/bitbucket/tags.ru.md index 04ec7239..1637dc5b 100644 --- a/content/documentation/admin/widgets/bitbucket/tags.ru.md +++ b/content/documentation/admin/widgets/bitbucket/tags.ru.md @@ -8,6 +8,8 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Пример | | ------------ | -------------- | ------------------------------------------------------------ | --------------------------------------------------------------------- | | Ключ проекта | Да | Часть URL репозитория, которая идёт сразу после `/projects/` | Для `https:///projects/MYTEAM/repos/backend` укажите `MYTEAM` | @@ -24,12 +26,16 @@ weight: 20 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Создание тегов Виджет позволяет создавать теги в Bitbucket напрямую из Deckhouse Development Portal (DDP). #### Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | | ---------- | -------------- | ---------------------------------------------------------------------------------- | | Название | Да | Название создаваемого тега | diff --git a/content/documentation/admin/widgets/clickhouse/metrics-range.md b/content/documentation/admin/widgets/clickhouse/metrics-range.md index aa4b80d6..7e0785da 100644 --- a/content/documentation/admin/widgets/clickhouse/metrics-range.md +++ b/content/documentation/admin/widgets/clickhouse/metrics-range.md @@ -22,6 +22,8 @@ ORDER BY time ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------- | -------- | ----------------------------------------------------------------------------------------------- | ------------- | | Query | Yes | Read-only SQL query. Use `{{from}}` and `{{to}}` to specify the time range. The widget substitutes them with the interval boundaries in UTC in the `YYYY-MM-DD hh:mm:ss` format without quotes | — | diff --git a/content/documentation/admin/widgets/clickhouse/metrics-range.ru.md b/content/documentation/admin/widgets/clickhouse/metrics-range.ru.md index 8e191447..2637604f 100644 --- a/content/documentation/admin/widgets/clickhouse/metrics-range.ru.md +++ b/content/documentation/admin/widgets/clickhouse/metrics-range.ru.md @@ -22,6 +22,8 @@ ORDER BY time ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------- | --------------------- | | Запрос | Да | SQL-запрос только для чтения. Используйте `{{from}}` и `{{to}}` для подстановки интервала. Виджет подставляет вместо них границы интервала в UTC в формате `YYYY-MM-DD hh:mm:ss` без кавычек | — | diff --git a/content/documentation/admin/widgets/clickhouse/metrics-single.md b/content/documentation/admin/widgets/clickhouse/metrics-single.md index 0fbaa36a..ddfb9ff5 100644 --- a/content/documentation/admin/widgets/clickhouse/metrics-single.md +++ b/content/documentation/admin/widgets/clickhouse/metrics-single.md @@ -18,6 +18,8 @@ WHERE timestamp >= '{{from}}' AND timestamp < '{{to}}' ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- | ------------- | | Query | Yes | Read-only SQL query. Use `{{from}}` and `{{to}}` to specify the time range. The widget substitutes them with the interval boundaries in UTC in the `YYYY-MM-DD hh:mm:ss` format without quotes | — | diff --git a/content/documentation/admin/widgets/clickhouse/metrics-single.ru.md b/content/documentation/admin/widgets/clickhouse/metrics-single.ru.md index f63f97ca..5ba9690b 100644 --- a/content/documentation/admin/widgets/clickhouse/metrics-single.ru.md +++ b/content/documentation/admin/widgets/clickhouse/metrics-single.ru.md @@ -6,7 +6,7 @@ weight: 20 Виджет выводит одно число на основе SQL-запроса только для чтения к ClickHouse. Для числа можно задать единицу измерения и пороговое значение. -Запрос должен возвращать одну строку: виджет отображает значение первого столбца. +Запрос должен возвращать одну строку, поскольку виджет отображает значение первого столбца. Пример корректного запроса для виджета: @@ -18,6 +18,8 @@ WHERE timestamp >= '{{from}}' AND timestamp < '{{to}}' ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Запрос | Да | SQL-запрос только для чтения. Используйте `{{from}}` и `{{to}}` для подстановки интервала. Виджет подставляет вместо них границы интервала в UTC в формате `YYYY-MM-DD hh:mm:ss` без кавычек | — | diff --git a/content/documentation/admin/widgets/clickhouse/table.md b/content/documentation/admin/widgets/clickhouse/table.md index 183b0aab..9fedd510 100644 --- a/content/documentation/admin/widgets/clickhouse/table.md +++ b/content/documentation/admin/widgets/clickhouse/table.md @@ -9,6 +9,8 @@ Use the `{{from}}` and `{{to}}` placeholders in the query. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------- | -------- | ------------------------------------------------------------------------------------------------- | ------------- | | Query | Yes | Read-only SQL query. Use `{{from}}` and `{{to}}` to specify the time range. The widget substitutes them with the interval boundaries in UTC in the `YYYY-MM-DD hh:mm:ss` format without quotes | — | diff --git a/content/documentation/admin/widgets/clickhouse/table.ru.md b/content/documentation/admin/widgets/clickhouse/table.ru.md index eb158bb3..c9f6f519 100644 --- a/content/documentation/admin/widgets/clickhouse/table.ru.md +++ b/content/documentation/admin/widgets/clickhouse/table.ru.md @@ -10,6 +10,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------- | --------------------- | | Запрос | Да | SQL-запрос только для чтения. Используйте `{{from}}` и `{{to}}` для подстановки интервала. Виджет подставляет вместо них границы интервала в UTC в формате `YYYY-MM-DD hh:mm:ss` без кавычек | — | diff --git a/content/documentation/admin/widgets/clickhouse/top-n.md b/content/documentation/admin/widgets/clickhouse/top-n.md index cd9581da..56d40876 100644 --- a/content/documentation/admin/widgets/clickhouse/top-n.md +++ b/content/documentation/admin/widgets/clickhouse/top-n.md @@ -20,6 +20,8 @@ ORDER BY value DESC ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------- | -------- | ------------------------------------------------------------------------------------------------- | ------------- | | Query | Yes | Read-only SQL query. Use `{{from}}` and `{{to}}` to specify the time range. The widget substitutes them with the interval boundaries in UTC in the `YYYY-MM-DD hh:mm:ss` format without quotes | — | diff --git a/content/documentation/admin/widgets/clickhouse/top-n.ru.md b/content/documentation/admin/widgets/clickhouse/top-n.ru.md index f77de512..e462b04c 100644 --- a/content/documentation/admin/widgets/clickhouse/top-n.ru.md +++ b/content/documentation/admin/widgets/clickhouse/top-n.ru.md @@ -20,6 +20,8 @@ ORDER BY value DESC ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------- | --------------------- | | Запрос | Да | SQL-запрос только для чтения. Используйте `{{from}}` и `{{to}}` для подстановки интервала. Виджет подставляет вместо них границы интервала в UTC в формате `YYYY-MM-DD hh:mm:ss` без кавычек | — | diff --git a/content/documentation/admin/widgets/codescoring/dependencies.md b/content/documentation/admin/widgets/codescoring/dependencies.md index 341a19d2..d92ecd1f 100644 --- a/content/documentation/admin/widgets/codescoring/dependencies.md +++ b/content/documentation/admin/widgets/codescoring/dependencies.md @@ -4,15 +4,18 @@ description: Product dependency details retrieved from CodeScoring weight: 10 --- -The widget displays a table of product dependencies based on CodeScoring data. For each dependency, the table includes its name, version, license, number of vulnerabilities, and other information. +The widget displays a table of product dependencies based on CodeScoring data. +For each dependency, the table includes its name, version, license, number of vulnerabilities, and other information. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | -------------------------- | ------------- | | URL | Yes | CodeScoring URL | — | | Project ID | Yes | Project ID in CodeScoring | — | -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#codescoring). diff --git a/content/documentation/admin/widgets/codescoring/dependencies.ru.md b/content/documentation/admin/widgets/codescoring/dependencies.ru.md index 1d799eee..3e20ca5f 100644 --- a/content/documentation/admin/widgets/codescoring/dependencies.ru.md +++ b/content/documentation/admin/widgets/codescoring/dependencies.ru.md @@ -8,6 +8,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ----------------------------------- | --------------------- | | URL | Да | URL CodeScoring | — | diff --git a/content/documentation/admin/widgets/codescoring/secrets.md b/content/documentation/admin/widgets/codescoring/secrets.md index 3edb05f9..56dc4b16 100644 --- a/content/documentation/admin/widgets/codescoring/secrets.md +++ b/content/documentation/admin/widgets/codescoring/secrets.md @@ -4,15 +4,18 @@ description: Project secret findings and scan controls from CodeScoring weight: 30 --- -The widget displays a table of secrets detected in a project by CodeScoring. It can start or cancel secret scanning for the selected branch or tag. +The widget displays a table of secrets detected in a project by CodeScoring. +It can start or cancel secret scanning for the selected branch or tag. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | -------------------------- | ------------- | | URL | Yes | CodeScoring URL | — | | Project ID | Yes | Project ID in CodeScoring | — | -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#codescoring). diff --git a/content/documentation/admin/widgets/codescoring/secrets.ru.md b/content/documentation/admin/widgets/codescoring/secrets.ru.md index 5cb3271d..678e5765 100644 --- a/content/documentation/admin/widgets/codescoring/secrets.ru.md +++ b/content/documentation/admin/widgets/codescoring/secrets.ru.md @@ -4,10 +4,13 @@ description: Найденные секреты проекта и управле weight: 30 --- -Виджет позволяет вывести таблицу найденных секретов проекта из CodeScoring. Поддерживаются запуск либо отмена сканирования секретов по выбранной ветке или тегу. +Виджет позволяет вывести таблицу найденных секретов проекта из CodeScoring. +Поддерживаются запуск либо отмена сканирования секретов по выбранной ветке или тегу. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ----------------------------------- | --------------------- | | URL | Да | URL CodeScoring | — | diff --git a/content/documentation/admin/widgets/codescoring/vulnerabilities.md b/content/documentation/admin/widgets/codescoring/vulnerabilities.md index fffe5178..586752c1 100644 --- a/content/documentation/admin/widgets/codescoring/vulnerabilities.md +++ b/content/documentation/admin/widgets/codescoring/vulnerabilities.md @@ -4,15 +4,18 @@ description: Product vulnerability details retrieved from CodeScoring weight: 20 --- -The widget displays a table of product vulnerabilities based on CodeScoring data. For each vulnerability, the table includes its code, severity, exploit availability, and fixed version. +The widget displays a table of product vulnerabilities based on CodeScoring data. +For each vulnerability, the table includes its code, severity, exploit availability, and fixed version. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | -------------------------- | ------------- | | URL | Yes | CodeScoring URL | — | | Project ID | Yes | Project ID in CodeScoring | — | -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#codescoring). diff --git a/content/documentation/admin/widgets/codescoring/vulnerabilities.ru.md b/content/documentation/admin/widgets/codescoring/vulnerabilities.ru.md index ca728e97..0a439213 100644 --- a/content/documentation/admin/widgets/codescoring/vulnerabilities.ru.md +++ b/content/documentation/admin/widgets/codescoring/vulnerabilities.ru.md @@ -8,6 +8,8 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ----------------------------------- | --------------------- | | URL | Да | URL CodeScoring | — | diff --git a/content/documentation/admin/widgets/defectdojo/product-findings-summary.md b/content/documentation/admin/widgets/defectdojo/product-findings-summary.md index 36d9bb0b..fa87117a 100644 --- a/content/documentation/admin/widgets/defectdojo/product-findings-summary.md +++ b/content/documentation/admin/widgets/defectdojo/product-findings-summary.md @@ -8,6 +8,8 @@ The widget displays a chart with the total number of product vulnerabilities fro ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------ | -------- | ------------------------------------------------------------ | ------------- | | URL | Yes | DefectDojo URL without the API path (`/api/v2`) | — | @@ -15,11 +17,16 @@ The widget displays a chart with the total number of product vulnerabilities fro ## Additional widget features -When viewing the widget, configure the following parameters: +When viewing the widget, configure the following parameters. + +If **Active vulnerabilities** is enabled, the widget loads product vulnerabilities with the `Active` flag set to `true`. +If it is disabled, the widget loads vulnerabilities with the `Active` flag set to `false`. +The parameter is enabled by default. -- **Active vulnerabilities** — when enabled, loads product vulnerabilities with the `Active` flag set to `true`. When disabled, loads vulnerabilities with the `Active` flag set to `false`. Enabled by default. -- **Duplicate vulnerabilities** — when enabled, loads product vulnerabilities with the `Duplicate` flag set to `true`. When disabled, loads vulnerabilities with the `Duplicate` flag set to `false`. Disabled by default. +If **Duplicate vulnerabilities** is enabled, the widget loads product vulnerabilities with the `Duplicate` flag set to `true`. +If it is disabled, the widget loads vulnerabilities with the `Duplicate` flag set to `false`. +The parameter is disabled by default. -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#defectdojo). diff --git a/content/documentation/admin/widgets/defectdojo/product-findings-summary.ru.md b/content/documentation/admin/widgets/defectdojo/product-findings-summary.ru.md index 3b804516..3b2fc483 100644 --- a/content/documentation/admin/widgets/defectdojo/product-findings-summary.ru.md +++ b/content/documentation/admin/widgets/defectdojo/product-findings-summary.ru.md @@ -8,6 +8,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------- | -------------- | ------------------------------------------------------ | --------------------- | | URL | Да | URL DefectDojo. Указывается без пути к API (`/api/v2`) | — | @@ -15,10 +17,15 @@ weight: 30 ## Дополнительные возможности виджета -При просмотре виджета настройте следующие параметры: +При просмотре виджета настройте следующие параметры. + +Если параметр «Активные уязвимости» включён, загружаются уязвимости продукта с флагом `Active`, равным `true`. +Если параметр отключён, загружаются уязвимости продукта с флагом `Active`, равным `false`. +По умолчанию параметр включён. -* «Активные уязвимости» — если включено, загружаются уязвимости продукта с флагом `Active`, равным `true`. Если отключено, загружаются уязвимости продукта с флагом `Active`, равным `false`. Включено по умолчанию. -* «Дублирующиеся уязвимости» — если включено, загружаются уязвимости продукта с флагом `Duplicate`, равным `true`. Если отключено, загружаются уязвимости продукта с флагом `Duplicate`, равным `false`. Отключено по умолчанию. +Если параметр «Дублирующиеся уязвимости» включён, загружаются уязвимости продукта с флагом `Duplicate`, равным `true`. +Если параметр отключён, загружаются уязвимости продукта с флагом `Duplicate`, равным `false`. +По умолчанию параметр отключён. ## Авторизация diff --git a/content/documentation/admin/widgets/defectdojo/product-findings.md b/content/documentation/admin/widgets/defectdojo/product-findings.md index 4b7c7435..5eb4ebf7 100644 --- a/content/documentation/admin/widgets/defectdojo/product-findings.md +++ b/content/documentation/admin/widgets/defectdojo/product-findings.md @@ -4,10 +4,13 @@ description: Detailed product vulnerabilities retrieved from DefectDojo weight: 20 --- -The widget displays a table of product vulnerabilities based on DefectDojo data. For each vulnerability, the table includes its severity, description, and detection date. +The widget displays a table of product vulnerabilities based on DefectDojo data. +For each vulnerability, the table includes its severity, description, and detection date. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------ | -------- | ------------------------------------------------------------ | ------------- | | URL | Yes | DefectDojo URL without the API path (`/api/v2`) | — | @@ -15,11 +18,16 @@ The widget displays a table of product vulnerabilities based on DefectDojo data. ## Additional widget features -When viewing the widget, configure the following parameters: +When viewing the widget, configure the following parameters. + +If **Active vulnerabilities** is enabled, the widget loads product vulnerabilities with the `Active` flag set to `true`. +If it is disabled, the widget loads vulnerabilities with the `Active` flag set to `false`. +The parameter is enabled by default. -- **Active vulnerabilities** — when enabled, loads product vulnerabilities with the `Active` flag set to `true`. When disabled, loads vulnerabilities with the `Active` flag set to `false`. Enabled by default. -- **Duplicate vulnerabilities** — when enabled, loads product vulnerabilities with the `Duplicate` flag set to `true`. When disabled, loads vulnerabilities with the `Duplicate` flag set to `false`. Disabled by default. +If **Duplicate vulnerabilities** is enabled, the widget loads product vulnerabilities with the `Duplicate` flag set to `true`. +If it is disabled, the widget loads vulnerabilities with the `Duplicate` flag set to `false`. +The parameter is disabled by default. -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#defectdojo). diff --git a/content/documentation/admin/widgets/defectdojo/product-findings.ru.md b/content/documentation/admin/widgets/defectdojo/product-findings.ru.md index d1e8ab36..d425aa91 100644 --- a/content/documentation/admin/widgets/defectdojo/product-findings.ru.md +++ b/content/documentation/admin/widgets/defectdojo/product-findings.ru.md @@ -8,6 +8,8 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------- | -------------- | ------------------------------------------------------ | --------------------- | | URL | Да | URL DefectDojo. Указывается без пути к API (`/api/v2`) | — | @@ -15,10 +17,15 @@ weight: 20 ## Дополнительные возможности виджета -При просмотре виджета настройте следующие параметры: +При просмотре виджета настройте следующие параметры. + +Если параметр «Активные уязвимости» включён, загружаются уязвимости продукта с флагом `Active`, равным `true`. +Если параметр отключён, загружаются уязвимости продукта с флагом `Active`, равным `false`. +По умолчанию параметр включён. -* «Активные уязвимости» — если включено, загружаются уязвимости продукта с флагом `Active`, равным `true`. Если отключено, загружаются уязвимости продукта с флагом `Active`, равным `false`. Включено по умолчанию. -* «Дублирующиеся уязвимости» — если включено, загружаются уязвимости продукта с флагом `Duplicate`, равным `true`. Если отключено, загружаются уязвимости продукта с флагом `Duplicate`, равным `false`. Отключено по умолчанию. +Если параметр «Дублирующиеся уязвимости» включён, загружаются уязвимости продукта с флагом `Duplicate`, равным `true`. +Если параметр отключён, загружаются уязвимости продукта с флагом `Duplicate`, равным `false`. +По умолчанию параметр отключён. ## Авторизация diff --git a/content/documentation/admin/widgets/defectdojo/product.md b/content/documentation/admin/widgets/defectdojo/product.md index aebbdaba..9e717218 100644 --- a/content/documentation/admin/widgets/defectdojo/product.md +++ b/content/documentation/admin/widgets/defectdojo/product.md @@ -8,6 +8,8 @@ The widget displays product vulnerabilities from DefectDojo, grouped by engageme ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | -------------- | -------- | -------------------------------------------------------------------------------------------------------- | -------------------------------- | | URL | Yes | DefectDojo URL without the API path (`/api/v2`) | — | @@ -16,24 +18,35 @@ The widget displays product vulnerabilities from DefectDojo, grouped by engageme ## Request parameters -In the widget request settings, select the severity levels to load only vulnerabilities with those levels. By default, the widget uses the levels from its configuration. Changing the levels reloads data from DefectDojo. +In the widget request settings, select the severity levels to load only vulnerabilities with those levels. +By default, the widget uses the levels from its configuration. +Changing the levels reloads data from DefectDojo. ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Filters -- **Engagement** — selects a product engagement. By default, the most recently created engagement, with the highest ID, is selected. Changing the engagement reloads the data. -- **Filters** — filters vulnerabilities by severity, tags, tests, and components. Tag, test, and component filters apply only to already loaded vulnerabilities and do not send new requests to DefectDojo. +The **Engagement** list selects a product engagement. +By default, the most recently created engagement, with the highest ID, is selected. +Changing the engagement reloads the data. + +The **Filters** panel filters vulnerabilities by severity, tags, tests, and components. +Tag, test, and component filters apply only to already loaded vulnerabilities and do not send new requests to DefectDojo. ### Tabs -- **Overview** — displays vulnerabilities by severity, tags (top 10), tests (top 10), and components (top 10). Charts use the filtered vulnerability set. -- **Details** — displays a table with details for each vulnerability. +The **Overview** tab displays vulnerabilities by severity, tags (top 10), tests (top 10), and components (top 10). +Charts use the filtered vulnerability set. + +The **Details** tab displays a table with details for each vulnerability. {{< alert level="info" >}} -If the selected Engagement and severity levels contain more than 1,000 vulnerabilities, the widget displays the first 1,000 records and a partial-load warning. Tag, test, and component filters apply only to the loaded set. +If the selected Engagement and severity levels contain more than 1,000 vulnerabilities, the widget displays the first 1,000 records and a partial-load warning. +Tag, test, and component filters apply only to the loaded set. {{< /alert >}} -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#defectdojo). diff --git a/content/documentation/admin/widgets/defectdojo/product.ru.md b/content/documentation/admin/widgets/defectdojo/product.ru.md index 92d8be53..860466e3 100644 --- a/content/documentation/admin/widgets/defectdojo/product.ru.md +++ b/content/documentation/admin/widgets/defectdojo/product.ru.md @@ -8,6 +8,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------ | -------------- | ------------------------------------------------------------------------------------------------ | --------------------------------- | | URL | Да | URL DefectDojo. Указывается без пути к API (`/api/v2`) | — | @@ -16,22 +18,33 @@ weight: 10 ## Параметры запроса -В настройках запроса виджета выберите уровни критичности, чтобы загрузить только соответствующие уязвимости. По умолчанию используются уровни из конфигурации виджета. Изменение уровней приводит к повторной загрузке данных из DefectDojo. +В настройках запроса виджета выберите уровни критичности, чтобы загрузить только соответствующие уязвимости. +По умолчанию используются уровни из конфигурации виджета. +Изменение уровней приводит к повторной загрузке данных из DefectDojo. ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Фильтры -* «Engagement» — выбор объекта Engagement для продукта. По умолчанию выбирается последний созданный объект Engagement (с наибольшим идентификатором). При смене объекта Engagement данные загружаются повторно. -* «Фильтры» — панель фильтров по уровням критичности, тегам, тестам и компонентам. Фильтры по тегам, тестам и компонентам применяются только к уже загруженным уязвимостям и не вызывают новых запросов к DefectDojo. +В списке «Engagement» выбирается объект Engagement для продукта. +По умолчанию выбирается последний созданный объект Engagement (с наибольшим идентификатором). +При смене объекта Engagement данные загружаются повторно. + +Панель «Фильтры» позволяет фильтровать уязвимости по уровням критичности, тегам, тестам и компонентам. +Фильтры по тегам, тестам и компонентам применяются только к уже загруженным уязвимостям и не вызывают новых запросов к DefectDojo. ### Вкладки -* «Обзор» — уязвимости по уровню критичности, по тегам (топ-10), по тестам (топ-10), по компонентам (топ-10). Диаграммы строятся по отфильтрованному набору уязвимостей. -* «Детали» — таблица уязвимостей с деталями по каждой из них. +На вкладке «Обзор» отображаются уязвимости по уровню критичности, по тегам (топ-10), по тестам (топ-10) и по компонентам (топ-10). +Диаграммы строятся по отфильтрованному набору уязвимостей. + +На вкладке «Детали» отображается таблица уязвимостей с деталями по каждой из них. {{< alert level="info" >}} -Если уязвимостей для выбранного Engagement и уровней критичности больше 1000, в виджете отображаются первые 1000 записей и предупреждение о частичной загрузке. Фильтры по тегам, тестам и компонентам действуют только в пределах загруженного набора. +Если уязвимостей для выбранного Engagement и уровней критичности больше 1000, в виджете отображаются первые 1000 записей и предупреждение о частичной загрузке. +Фильтры по тегам, тестам и компонентам действуют только в пределах загруженного набора. {{< /alert >}} ## Авторизация diff --git a/content/documentation/admin/widgets/entities/calendar.md b/content/documentation/admin/widgets/entities/calendar.md index f365b36a..bd1ca100 100644 --- a/content/documentation/admin/widgets/entities/calendar.md +++ b/content/documentation/admin/widgets/entities/calendar.md @@ -6,22 +6,28 @@ weight: 10 The widget displays entities of the selected resource in a calendar. -## Displayed data - -- **Weekly calendar** — a seven-day grid for the current week. -- **Entities by date** — all entities whose selected date field matches a given day. -- **Entity information** — the name and description, if specified, of each entity. -- **Week navigation** — buttons for moving to the previous or next week. - ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |------------|----------|-------------------------------------------------------------------------------------------------------------------------------|---------| | Resource | Yes | Resource whose entities are displayed in the calendar | — | -| Date field | Yes | Field containing the date used to display the entity in the calendar. It can be a system field (`createdAt`, `updatedAt`) or a `Date` parameter | — | +| Date field | Yes | Field containing the date used to display the entity in the calendar. It can be a system field (`createdAt`, `updatedAt`) or a `Date` property | — | + +## Displayed data + +The widget displays the following data: + +- **Weekly calendar**: A seven-day grid for the current week. +- **Entities by date**: All entities whose selected date field matches a given day. +- **Entity information**: The name and description, if specified, of each entity. +- **Week navigation**: Buttons for moving to the previous or next week. ## Notes +The widget has the following specifics: + - The widget displays the current week, from Monday through Sunday, by default. - Use the **Previous week** and **Next week** buttons to navigate between weeks. - Each day displays its date in `DD.MM` format. diff --git a/content/documentation/admin/widgets/entities/calendar.ru.md b/content/documentation/admin/widgets/entities/calendar.ru.md index d7641a33..339e4e7f 100644 --- a/content/documentation/admin/widgets/entities/calendar.ru.md +++ b/content/documentation/admin/widgets/entities/calendar.ru.md @@ -6,22 +6,28 @@ weight: 10 Виджет отображает сущности выбранного ресурса в календаре. -## Отображаемые данные - -- «Недельный календарь» — сетка из 7 дней текущей недели. -- «Сущности по датам» — для каждого дня отображаются все сущности, у которых дата в выбранном поле соответствует этому дню. -- «Информация о сущностях» — для каждой сущности отображаются название и описание (если указано). -- «Навигация по неделям» — кнопки для перехода к предыдущей и следующей неделе. - ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Ресурс | Да | Ресурс, для которого отображается календарь | — | | Поле даты | Да | Поле, из которого берётся дата для отображения сущности в календаре. Может быть системным полем (`createdAt`, `updatedAt`) или параметром типа `Date` | — | +## Отображаемые данные + +Виджет отображает следующие данные: + +- «Недельный календарь» — сетка из 7 дней текущей недели. +- «Сущности по датам» — для каждого дня отображаются все сущности, у которых дата в выбранном поле соответствует этому дню. +- «Информация о сущностях» — для каждой сущности отображаются название и описание (если указано). +- «Навигация по неделям» — кнопки для перехода к предыдущей и следующей неделе. + ## Особенности +Виджет имеет следующие особенности: + - Виджет отображает текущую неделю по умолчанию (с понедельника по воскресенье). - Доступна навигация между неделями с помощью кнопок «Предыдущая неделя» и «Следующая неделя». - Для каждого дня отображается дата в формате `DD.MM`. diff --git a/content/documentation/admin/widgets/entities/entity-card.md b/content/documentation/admin/widgets/entities/entity-card.md new file mode 100644 index 00000000..83c04df4 --- /dev/null +++ b/content/documentation/admin/widgets/entities/entity-card.md @@ -0,0 +1,32 @@ +--- +title: Entity card +description: Description, team, owner, and properties of an entity on its page. +weight: 70 +--- + +The widget displays the main information about the entity on whose page it is placed. + +## Configuration + +The widget does not require additional configuration. + +## Displayed data + +The widget displays the same information as the entity page in the catalog: + +- Entity description with Markdown support: A long description is collapsed to three lines and expands with the "Show more" button. +- "Team" and "Owner": The team and the user that own the entity. +- "Properties" block: Values of entity properties, except for hidden resource properties. + +The "Properties" block works the same way as on the entity page. +Its heading shows how many properties are filled in, and the tooltip lists the empty properties. +Properties of the "JSON", "YAML", "Markdown", and "Object" types are displayed in a separate "Documents" row. +The clock icon next to a property name opens its change history, and the "As of a moment" button shows the values of all properties at the selected moment. + +## Placement + +The widget works only on an entity page. +Add it to a dashboard that is displayed on the entity page. +The ways to connect dashboards to a resource are described in the "Dashboards" section. + +If the widget is opened outside an entity page, it displays the "The widget must be bound to an entity" message. diff --git a/content/documentation/admin/widgets/entities/entity-card.ru.md b/content/documentation/admin/widgets/entities/entity-card.ru.md index 7c15295a..6b2a0d4c 100644 --- a/content/documentation/admin/widgets/entities/entity-card.ru.md +++ b/content/documentation/admin/widgets/entities/entity-card.ru.md @@ -6,6 +6,10 @@ weight: 70 Виджет показывает основные сведения о сущности, на странице которой он размещён. +## Конфигурация + +Виджет не требует дополнительной конфигурации. + ## Отображаемые данные Виджет показывает те же сведения, что и страница сущности в каталоге: @@ -14,14 +18,15 @@ weight: 70 - «Команда» и «Владелец» — команда и пользователь, владеющие сущностью; - блок «Параметры» — значения параметров сущности, кроме скрытых параметров ресурса. -Блок «Параметры» устроен так же, как [на странице сущности](../../../user/catalog/#блок-параметры). В его заголовке отображается заполненность параметров, подсказка к ней перечисляет пустые параметры. Параметры типов «JSON», «YAML», «Markdown» и «Object» выводятся отдельной строкой «Документы». Значок часов рядом с названием параметра открывает историю его изменений, кнопка «На момент времени» — значения всех параметров на выбранный момент. - -## Конфигурация - -Виджет не требует дополнительной конфигурации. +Блок «Параметры» устроен так же, как [на странице сущности](../../../user/catalog/#блок-параметры). +В его заголовке отображается заполненность параметров, подсказка к ней перечисляет пустые параметры. +Параметры типов «JSON», «YAML», «Markdown» и «Object» выводятся отдельной строкой «Документы». +Значок часов рядом с названием параметра открывает историю его изменений, кнопка «На момент времени» — значения всех параметров на выбранный момент. ## Размещение -Виджет работает только на странице сущности. Добавьте его на дашборд, который выводится на странице сущности. Варианты подключения дашбордов к ресурсу описаны в разделе [«Дашборды»](../../../user/catalog/#дашборды). +Виджет работает только на странице сущности. +Добавьте его на дашборд, который выводится на странице сущности. +Варианты подключения дашбордов к ресурсу описаны в разделе [«Дашборды»](../../../user/catalog/#дашборды). Если виджет открыт не на странице сущности, он показывает сообщение «Виджет должен быть привязан к сущности». diff --git a/content/documentation/admin/widgets/entities/entity-relations.md b/content/documentation/admin/widgets/entities/entity-relations.md new file mode 100644 index 00000000..9998662c --- /dev/null +++ b/content/documentation/admin/widgets/entities/entity-relations.md @@ -0,0 +1,25 @@ +--- +title: Entity relations +description: Entities related to the current entity, grouped by resource relation tabs. +weight: 80 +--- + +The widget displays entities related to the entity on whose page it is placed. + +## Configuration + +The widget does not require additional configuration. + +## Displayed data + +For each resource relation through which the entity has related entities, the widget displays a separate tab named after the relation. +The tab contains a table of related entities. +It includes both parent and child entities. + +## Placement + +The widget works only on an entity page. +Add it to a dashboard that is displayed on the entity page. +The ways to connect dashboards to a resource are described in the "Dashboards" section. + +If the widget is opened outside an entity page, it displays the "The widget must be bound to an entity" message. diff --git a/content/documentation/admin/widgets/entities/entity-relations.ru.md b/content/documentation/admin/widgets/entities/entity-relations.ru.md index c3c622a0..f2c184e2 100644 --- a/content/documentation/admin/widgets/entities/entity-relations.ru.md +++ b/content/documentation/admin/widgets/entities/entity-relations.ru.md @@ -6,16 +6,20 @@ weight: 80 Виджет показывает сущности, связанные с сущностью, на странице которой он размещён. -## Отображаемые данные - -Для каждой связи ресурса, по которой у сущности есть связанные сущности, виджет показывает отдельную вкладку с названием связи. Во вкладке выводится таблица связанных сущностей. В неё попадают и родительские, и дочерние сущности. - ## Конфигурация Виджет не требует дополнительной конфигурации. +## Отображаемые данные + +Для каждой связи ресурса, по которой у сущности есть связанные сущности, виджет показывает отдельную вкладку с названием связи. +Во вкладке выводится таблица связанных сущностей. +В неё попадают и родительские, и дочерние сущности. + ## Размещение -Виджет работает только на странице сущности. Добавьте его на дашборд, который выводится на странице сущности. Варианты подключения дашбордов к ресурсу описаны в разделе [«Дашборды»](../../../user/catalog/#дашборды). +Виджет работает только на странице сущности. +Добавьте его на дашборд, который выводится на странице сущности. +Варианты подключения дашбордов к ресурсу описаны в разделе [«Дашборды»](../../../user/catalog/#дашборды). Если виджет открыт не на странице сущности, он показывает сообщение «Виджет должен быть привязан к сущности». diff --git a/content/documentation/admin/widgets/entities/entity-status.md b/content/documentation/admin/widgets/entities/entity-status.md index 10297a5b..1a14caaa 100644 --- a/content/documentation/admin/widgets/entities/entity-status.md +++ b/content/documentation/admin/widgets/entities/entity-status.md @@ -6,6 +6,13 @@ weight: 50 The widget displays the entity status and status check results. +## Configuration + +The widget requires no additional configuration. + +To use the widget, configure status checks for the resource associated with the entity. +For details, refer to [status check configuration](../../healthchecks/overview/). + ## Displayed data The widget displays the following information. @@ -19,21 +26,21 @@ The **successful check count** shows the number of successful checks out of all The following information is displayed for each status check: -- **Check name** — the name of the check rule. -- **Status** — the check result: - - **Passed** — the check completed successfully. - - **Failed** — the check did not pass, but no execution error occurred. - - **Error** — an error occurred while running the check. -- **Last check time** — the date and time when the check last ran. -- **Error message** — the error text, displayed if the check ended with an error. +- **Check name**: The name of the check rule. +- **Status**: The check result: + - **Passed**: The check completed successfully. + - **Failed**: The check did not pass, but no execution error occurred. + - **Error**: An error occurred while running the check. +- **Last check time**: The date and time when the check last ran. +- **Error message**: The error text, displayed if the check ended with an error. ### Statistics The bottom of the widget displays summary check statistics: -- **Passed** — the number of successful checks. -- **Failed** — the number of checks that did not pass without execution errors. -- **Error** — the number of checks that ended with an error. +- **Passed**: The number of successful checks. +- **Failed**: The number of checks that did not pass without execution errors. +- **Error**: The number of checks that ended with an error. ### Blocked actions @@ -47,13 +54,6 @@ Display conditions: The widget displays the action name and description, if specified. -## Configuration - -The widget requires no additional configuration. - -To use the widget, configure status checks for the resource associated with the entity. -For details, refer to [status check configuration](../../healthchecks/overview/). - ## Notes If no status checks are configured for the entity, the widget indicates that no checks are available. diff --git a/content/documentation/admin/widgets/entities/entity-status.ru.md b/content/documentation/admin/widgets/entities/entity-status.ru.md index 5f847cfb..edf59a65 100644 --- a/content/documentation/admin/widgets/entities/entity-status.ru.md +++ b/content/documentation/admin/widgets/entities/entity-status.ru.md @@ -6,6 +6,13 @@ weight: 50 Виджет отображает информацию о статусе сущности и результатах проверок статуса. +## Конфигурация + +Виджет не требует дополнительной конфигурации. + +Настройте проверки статуса для ресурса, связанного с сущностью. +Инструкции приведены в разделе [«Проверки статуса»](../../healthchecks/overview/). + ## Отображаемые данные Виджет показывает следующую информацию. @@ -46,13 +53,6 @@ weight: 50 Виджет отображает название действия и его описание, если оно указано. -## Конфигурация - -Виджет не требует дополнительной конфигурации. - -Настройте проверки статуса для ресурса, связанного с сущностью. -Инструкции приведены в разделе [«Проверки статуса»](../../healthchecks/overview/). - ## Особенности Если для сущности не настроено ни одной проверки статуса, виджет сообщает, что проверки отсутствуют. diff --git a/content/documentation/admin/widgets/entities/entity-table.md b/content/documentation/admin/widgets/entities/entity-table.md index bcfd5f30..aa16f4db 100644 --- a/content/documentation/admin/widgets/entities/entity-table.md +++ b/content/documentation/admin/widgets/entities/entity-table.md @@ -8,7 +8,9 @@ The widget displays entities created in Deckhouse Development Portal (DDP) as a ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |--------------|----------|---------------------------------------------------------------------------------------------------------------|---------| | Resource | Yes | Resource whose entities are displayed in the table | — | | Show actions | No | Whether to display entity actions, such as running actions and scenarios or deleting entities | `false` | diff --git a/content/documentation/admin/widgets/entities/entity-table.ru.md b/content/documentation/admin/widgets/entities/entity-table.ru.md index 83c54a12..646e61e2 100644 --- a/content/documentation/admin/widgets/entities/entity-table.ru.md +++ b/content/documentation/admin/widgets/entities/entity-table.ru.md @@ -8,6 +8,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------- | | Ресурс | Да | Ресурс, сущности которого отображаются в таблице | — | diff --git a/content/documentation/admin/widgets/entities/kanban.md b/content/documentation/admin/widgets/entities/kanban.md index c0a0bbf4..4d6c737f 100644 --- a/content/documentation/admin/widgets/entities/kanban.md +++ b/content/documentation/admin/widgets/entities/kanban.md @@ -6,19 +6,24 @@ weight: 20 The widget displays entities of the selected resource on a Kanban board. -## Displayed data - -- **Columns** — configured board columns and an **Unassigned** column for entities without a matching status property value. -- **Entity cards** — each entity displays its name, description if specified, check status, owner, and update date. -- **Moving cards** — dragging a card between columns updates the entity's status property value. This requires permission to modify entities. - ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |-----------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| | Resource | Yes | Resource whose entities are displayed on the board | — | -| Status property | Yes | Entity parameter that determines the card column. Supported types: `String`, `Number`, `Boolean`, `Enum`, `List`, `Date`, `Percentage`, and `URL` | — | -| Columns | Yes | List of board columns. For each column, specify a name (the board heading), value (the status property value; for `Enum` and `List` parameters, select from the available options), and color (the tag color in the heading). Drag columns to change their order | — | +| Status property | Yes | Entity property that determines the card column. Supported types: `String`, `Number`, `Boolean`, `Enum`, `List`, `Date`, `Percentage`, and `URL` | — | +| Columns | Yes | List of board columns. For each column, specify a name (the board heading), value (the status property value; for `Enum` and `List` properties, select from the available options), and color (the tag color in the heading). Drag columns to change their order | — | + +## Displayed data + +The widget displays the following data: + +- **Columns**: Configured board columns and an **Unassigned** column for entities without a matching status property value. +- **Entity cards**: Each entity displays its name, description if specified, check status, owner, and update date. +- **Moving cards**: Dragging a card between columns updates the entity's status property value. + This requires permission to modify entities. ## Notes diff --git a/content/documentation/admin/widgets/entities/kanban.ru.md b/content/documentation/admin/widgets/entities/kanban.ru.md index 16fe49ea..bb2bf81c 100644 --- a/content/documentation/admin/widgets/entities/kanban.ru.md +++ b/content/documentation/admin/widgets/entities/kanban.ru.md @@ -6,25 +6,29 @@ weight: 20 Виджет отображает сущности выбранного ресурса на Kanban-доске. -## Отображаемые данные - -- «Колонки» — настроенные колонки доски и колонка «Без статуса» для сущностей без подходящего значения параметра состояния. -- «Карточки сущностей» — для каждой сущности отображаются название, описание (если указано), статус проверок, владелец и дата обновления. -- «Перемещение карточек» — перетаскивание карточки между колонками обновляет значение параметра состояния сущности (доступно при наличии прав на изменение сущностей). - ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Ресурс | Да | Ресурс, сущности которого отображаются на доске | — | | Параметр состояния | Да | Параметр сущности, определяющий колонку карточки. Поддерживаются типы `String`, `Number`, `Boolean`, `Enum`, `List`, `Date`, `Percentage`, `URL`. Можно выбрать только редактируемый параметр, который не скрыт | — | | Колонки | Да | Список колонок доски. Для каждой колонки задаются: название (заголовок на доске), значение (значение параметра состояния; для параметров типа `Enum` и `List` выбирается из доступных опций) и цвет (цвет тега в заголовке). Порядок колонок настраивается перетаскиванием | — | +## Отображаемые данные + +Виджет отображает следующие данные: + +- «Колонки» — настроенные колонки доски и колонка «Без статуса» для сущностей без подходящего значения параметра состояния. +- «Карточки сущностей» — для каждой сущности отображаются название, описание (если указано), статус проверок, владелец и дата обновления. +- «Перемещение карточек» — перетаскивание карточки между колонками обновляет значение параметра состояния сущности (доступно при наличии прав на изменение сущностей). + ## Особенности Сущности без подходящего значения параметра состояния отображаются в колонке «Без статуса». -Перемещение карточек недоступно в следующих случаях: - -- у пользователя нет прав на изменение сущностей — на доске отображается сообщение «Нет прав на перемещение карточек»; -- параметр состояния стал нередактируемым или скрытым после настройки виджета — на доске отображается сообщение «Параметр состояния недоступен для редактирования, карточки нельзя перемещать». +Перемещение карточек недоступно, если у пользователя нет прав на изменение сущностей. +В этом случае на доске отображается сообщение «Нет прав на перемещение карточек». +Перемещение также недоступно, если параметр состояния стал нередактируемым или скрытым после настройки виджета. +В этом случае на доске отображается сообщение «Параметр состояния недоступен для редактирования, карточки нельзя перемещать». diff --git a/content/documentation/admin/widgets/entities/property-history.md b/content/documentation/admin/widgets/entities/property-history.md new file mode 100644 index 00000000..8d7350bf --- /dev/null +++ b/content/documentation/admin/widgets/entities/property-history.md @@ -0,0 +1,44 @@ +--- +title: Property history +description: Chart of entity property changes over the selected period. +weight: 60 +--- + +The widget plots a chart of entity property changes over the selected period. +The period is selected in the widget header. + +## Configuration + +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | +|----------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +| Resource | No | Resource whose schema provides the properties. If no resource is specified, properties are set by identifiers, and the chart is plotted for the resource of the current entity | — | +| Properties | Yes | Properties whose changes the chart displays. Supported types: `Number`, `Percentage`, and `Boolean`. Multiple properties must be of the same type | — | +| Default interval | No | Period for which the widget plots the chart when opened | Last 30 days | +| Threshold | No | Horizontal line on the chart, drawn only for numeric properties | — | +| Axis minimum | No | Lower bound of the value axis | Based on data | +| Axis maximum | No | Upper bound of the value axis | Based on data | + +## Displayed data + +The widget displays the following data: + +- "Chart": Numeric properties are displayed as a value line, flags are displayed on an axis with the "No" and "Yes" values. +- "Chart point": A property change. The tooltip shows the value, the change source, and the author. +- "Legend": Displayed if the chart contains more than one property. +- "Retention boundary": A vertical mark on the chart; changes to the left of it have already been deleted. + +## Notes + +Property change history is recorded only when ClickHouse is connected. +If the storage is not configured, the widget reports that property history is not recorded. + +The history retention period is limited. +If the entire selected period is older than the retention period, the widget reports that changes for it have already been deleted. + +If the selected period contains more changes than fit on the chart, the widget displays a warning and lists the properties for which some changes are not shown. +Reduce the period or keep fewer properties on the chart. + +If a non-numeric value, such as text, is written to a numeric property, it cannot be displayed on the axis. +At this point, the line breaks and continues from the next numeric value, and the value itself is visible in the tooltip. diff --git a/content/documentation/admin/widgets/entities/property-history.ru.md b/content/documentation/admin/widgets/entities/property-history.ru.md index ad76cb99..cd91cb44 100644 --- a/content/documentation/admin/widgets/entities/property-history.ru.md +++ b/content/documentation/admin/widgets/entities/property-history.ru.md @@ -7,15 +7,10 @@ weight: 60 Виджет строит график изменений параметров сущности за выбранный период. Период выбирается в заголовке виджета. -## Отображаемые данные - -- «График» — числовые параметры отображаются линией значений, флаги — по оси со значениями «Нет» и «Да». -- «Точка на графике» — изменение параметра. В подсказке отображаются значение, источник изменения и автор. -- «Легенда» — отображается, если на графике больше одного параметра. -- «Граница хранения» — вертикальная отметка на графике, левее которой изменения уже удалены. - ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Ресурс | Нет | Ресурс, из схемы которого выбираются параметры. Если ресурс не указан, параметры задаются идентификаторами, а график строится по ресурсу текущей сущности | — | @@ -25,12 +20,25 @@ weight: 60 | Минимум оси | Нет | Нижняя граница оси значений | По данным | | Максимум оси | Нет | Верхняя граница оси значений | По данным | +## Отображаемые данные + +Виджет отображает следующие данные: + +- «График» — числовые параметры отображаются линией значений, флаги — по оси со значениями «Нет» и «Да». +- «Точка на графике» — изменение параметра. В подсказке отображаются значение, источник изменения и автор. +- «Легенда» — отображается, если на графике больше одного параметра. +- «Граница хранения» — вертикальная отметка на графике, левее которой изменения уже удалены. + ## Особенности -История изменений параметров ведётся только при подключённом ClickHouse. Если хранилище не настроено, виджет сообщает, что история параметров не ведётся. +История изменений параметров ведётся только при подключённом ClickHouse. +Если хранилище не настроено, виджет сообщает, что история параметров не ведётся. -Срок хранения истории ограничен. Если выбранный период целиком старше срока хранения, виджет сообщает, что изменения за него уже удалены. +Срок хранения истории ограничен. +Если выбранный период целиком старше срока хранения, виджет сообщает, что изменения за него уже удалены. -Если за выбранный период изменений больше, чем помещается на график, виджет показывает предупреждение и называет параметры, часть изменений которых не показана. Уменьшите период или оставьте на графике меньше параметров. +Если за выбранный период изменений больше, чем помещается на график, виджет показывает предупреждение и называет параметры, часть изменений которых не показана. +Уменьшите период или оставьте на графике меньше параметров. -Если в числовой параметр записано нечисловое значение, например текст, показать его на оси невозможно. В этом месте линия прерывается и продолжается со следующего числового значения, а само значение видно в подсказке. +Если в числовой параметр записано нечисловое значение, например текст, показать его на оси невозможно. +В этом месте линия прерывается и продолжается со следующего числового значения, а само значение видно в подсказке. diff --git a/content/documentation/admin/widgets/entities/timeline.md b/content/documentation/admin/widgets/entities/timeline.md index 86abbf8c..47179c92 100644 --- a/content/documentation/admin/widgets/entities/timeline.md +++ b/content/documentation/admin/widgets/entities/timeline.md @@ -6,19 +6,23 @@ weight: 40 The widget displays entities of the selected resource on a timeline. -## Displayed data - -- **Timeline chart** — a horizontal chart where each entity is represented by a bar spanning from its start date to its end date. -- **Entity information** — hovering over a bar displays the entity name and the period's start and end dates. -- **Sorting** — entities are sorted from oldest at the top to newest at the bottom. - ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |----------------|----------|---------------------------------------------------------------------------------------------------------------------|---------| | Resource | Yes | Resource whose entities are displayed on the timeline | — | -| Start date field | Yes | Field containing the period start date. It can be a system field (`createdAt`, `updatedAt`) or a `Date` parameter | — | -| End date field | Yes | Field containing the period end date. It can be a system field (`createdAt`, `updatedAt`) or a `Date` parameter | — | +| Start date field | Yes | Field containing the period start date. It can be a system field (`createdAt`, `updatedAt`) or a `Date` property | — | +| End date field | Yes | Field containing the period end date. It can be a system field (`createdAt`, `updatedAt`) or a `Date` property | — | + +## Displayed data + +The widget displays the following data: + +- **Timeline chart**: A horizontal chart where each entity is represented by a bar spanning from its start date to its end date. +- **Entity information**: Hovering over a bar displays the entity name and the period's start and end dates. +- **Sorting**: Entities are sorted from oldest at the top to newest at the bottom. ## Notes diff --git a/content/documentation/admin/widgets/entities/timeline.ru.md b/content/documentation/admin/widgets/entities/timeline.ru.md index fdfc9b52..e40ed81e 100644 --- a/content/documentation/admin/widgets/entities/timeline.ru.md +++ b/content/documentation/admin/widgets/entities/timeline.ru.md @@ -6,20 +6,24 @@ weight: 40 Виджет отображает сущности выбранного ресурса на временной шкале. -## Отображаемые данные - -- «График временной шкалы» — горизонтальная диаграмма, где каждая сущность отображается в виде полосы, показывающей период времени (от даты начала до даты окончания). -- «Информация о сущностях» — при наведении на полосу отображается название сущности, дата начала и дата окончания периода. -- «Сортировка» — сущности отсортированы от самых старых (сверху) к самым новым (снизу). - ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Ресурс | Да | Ресурс, для которого отображается временная шкала | — | | Поле даты начала | Да | Поле, из которого берётся дата начала периода. Может быть системным полем (`createdAt`, `updatedAt`) или параметром типа `Date` | — | | Поле даты окончания | Да | Поле, из которого берётся дата окончания периода. Может быть системным полем (`createdAt`, `updatedAt`) или параметром типа `Date` | — | +## Отображаемые данные + +Виджет отображает следующие данные: + +- «График временной шкалы» — горизонтальная диаграмма, где каждая сущность отображается в виде полосы, показывающей период времени (от даты начала до даты окончания). +- «Информация о сущностях» — при наведении на полосу отображается название сущности, дата начала и дата окончания периода. +- «Сортировка» — сущности отсортированы от самых старых (сверху) к самым новым (снизу). + ## Особенности Виджет автоматически масштабирует временную шкалу для отображения всех сущностей. diff --git a/content/documentation/admin/widgets/generic/api.md b/content/documentation/admin/widgets/generic/api.md index 7804b589..f6129dfb 100644 --- a/content/documentation/admin/widgets/generic/api.md +++ b/content/documentation/admin/widgets/generic/api.md @@ -4,25 +4,33 @@ description: Configure the API widget to display OpenAPI and Protobuf specificat weight: 10 --- -The widget displays an API specification from a file in a GitLab repository or from a URL in OpenAPI (Swagger) or Protobuf format. For an OpenAPI specification in a YAML or JSON file, the widget displays the Swagger UI. In all other cases, it displays the specification as text. +The widget displays an API specification from a file in a GitLab repository or from a URL in OpenAPI (Swagger) or Protobuf format. +For an OpenAPI specification in a YAML or JSON file, the widget displays the Swagger UI. +In all other cases, it displays the specification as text. ## General configuration -| Name | Required | Description | Possible values | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Possible values | Default value | | ------------------ | -------- | ------------------------------------------------ | ----------------------------------- | ------- | | Specification type | Yes | Specification type | OpenAPI (Swagger), Protocol Buffers | — | | Source type | Yes | Source from which the specification file is loaded | URL, GitLab | — | ## Source type configuration: URL -| Name | Required | Description | Default | +For the URL source type, specify the following parameters: + +| Name | Required | Description | Default value | | ------- | -------- | ------------------------------------------------ | ------- | | URL | Yes | URL of the specification file | — | | Headers | No | Headers used to access the specification file | — | ## Source type configuration: GitLab -| Name | Required | Description | Default | +For the GitLab source type, specify the following parameters: + +| Name | Required | Description | Default value | | ----------- | -------- | ------------------------------------------------------------- | ------- | | GitLab URL | Yes | GitLab URL | — | | Project ID | Yes | ID of the project containing the specification file | — | diff --git a/content/documentation/admin/widgets/generic/api.ru.md b/content/documentation/admin/widgets/generic/api.ru.md index e3c7bdd3..e1daba95 100644 --- a/content/documentation/admin/widgets/generic/api.ru.md +++ b/content/documentation/admin/widgets/generic/api.ru.md @@ -4,10 +4,14 @@ description: Настройка виджета API для отображения weight: 10 --- -Виджет позволяет вывести спецификацию API из файла в репозитории GitLab или по ссылке в формате OpenAPI (Swagger) или Protobuf. При выводе спецификации OpenAPI из файла в формате YAML или JSON виджет отображает интерфейс Swagger. Во всех остальных случаях виджет отображает спецификацию в виде текста. +Виджет позволяет вывести спецификацию API из файла в репозитории GitLab или по ссылке в формате OpenAPI (Swagger) или Protobuf. +При выводе спецификации OpenAPI из файла в формате YAML или JSON виджет отображает интерфейс Swagger. +Во всех остальных случаях виджет отображает спецификацию в виде текста. ## Общая конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Возможные значения | Значение по умолчанию | | ---------------- | -------------- | ------------------------------------------------------------------ | ----------------------------------- | --------------------- | | Тип спецификации | Да | Тип спецификации | OpenAPI (Swagger), Protocol Buffers | — | @@ -15,6 +19,8 @@ weight: 10 ## Конфигурация типа источника: URL +Для типа источника URL задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------- | -------------- | ---------------------------------------------- | --------------------- | | URL | Да | Ссылка на файл со спецификацией | — | @@ -22,6 +28,8 @@ weight: 10 ## Конфигурация типа источника: GitLab +Для типа источника GitLab задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------ | -------------- | ---------------------------------------------------------------------- | --------------------- | | GitLab URL | Да | URL GitLab | — | diff --git a/content/documentation/admin/widgets/generic/docker.md b/content/documentation/admin/widgets/generic/docker.md index 45eff36b..6c47fec5 100644 --- a/content/documentation/admin/widgets/generic/docker.md +++ b/content/documentation/admin/widgets/generic/docker.md @@ -4,11 +4,15 @@ description: Configure the Docker widget to browse container images, tags, and p weight: 70 --- -The widget displays available images in a Docker registry. It shows all available tags and the `docker pull` command. Search is supported. +The widget displays available images in a Docker registry. +It shows all available tags and the `docker pull` command. +Search is supported. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---- | -------- | ---------------------------------------------------------------------------------------------------------------------- | ------- | | URL | Yes | Docker Registry URL used to retrieve available image data | — | | Name | No | Name of the repository from which the widget loads data. Example: `repo`. If omitted, all available images are loaded | — | diff --git a/content/documentation/admin/widgets/generic/docker.ru.md b/content/documentation/admin/widgets/generic/docker.ru.md index bb9d5823..487192a6 100644 --- a/content/documentation/admin/widgets/generic/docker.ru.md +++ b/content/documentation/admin/widgets/generic/docker.ru.md @@ -4,10 +4,14 @@ description: Настройка виджета Docker для просмотра weight: 70 --- -Виджет позволяет отображать данные о доступных образах в Docker Registry. На виджет выводятся все доступные теги и команда `docker pull`. Поддерживается поиск. +Виджет позволяет отображать данные о доступных образах в Docker Registry. +На виджет выводятся все доступные теги и команда `docker pull`. +Поддерживается поиск. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL Docker Registry. Используется для получения данных о доступных образах | — | diff --git a/content/documentation/admin/widgets/generic/event-stats.md b/content/documentation/admin/widgets/generic/event-stats.md index 5cf8e0b2..0e4dd6b4 100644 --- a/content/documentation/admin/widgets/generic/event-stats.md +++ b/content/documentation/admin/widgets/generic/event-stats.md @@ -4,11 +4,12 @@ description: Monitor entity events, Redis streams, and event trends with the Eve weight: 140 --- -The widget displays statistics about events involving entities in Deckhouse Development Portal (DDP). It contains three tabs: +The widget displays statistics about events involving entities in Deckhouse Development Portal (DDP). +It contains three tabs: -1. **Event statistics** — A chart showing the number of events by type over the selected time range, with configurable time grouping. -1. **Top entities** — A table of entities that generated the most events. -1. **Redis events** — A table of Redis event streams. For each stream, it shows: +1. **Event statistics**: A chart showing the number of events by type over the selected time range, with configurable time grouping. +1. **Top entities**: A table of entities that generated the most events. +1. **Redis events**: A table of Redis event streams. For each stream, it shows: - The stream name, which you can select to view all events. - The resource associated with the stream. - The number of events in the stream. @@ -16,7 +17,9 @@ The widget displays statistics about events involving entities in Deckhouse Deve ## Query parameters -| Name | Required | Description | Default | +The widget supports the following query parameters: + +| Name | Required | Description | Default value | | ------------ | -------- | -------------------------------------------------------------------------------------- | ------------ | | Date from | Yes | Start date for selecting events | 3 days ago | | Date to | Yes | End date for selecting events | Current date | @@ -28,12 +31,14 @@ The widget displays statistics about events involving entities in Deckhouse Deve The widget supports the following event types: -- `ENTITY_CREATED` — Entity created. -- `ENTITY_UPDATED` — Entity updated. -- `ENTITY_DELETED` — Entity deleted. +- `ENTITY_CREATED`: Entity created. +- `ENTITY_UPDATED`: Entity updated. +- `ENTITY_DELETED`: Entity deleted. ### Behavior +The widget has the following specifics: + - The chart shows events over the selected time range with configurable time grouping. The default grouping is by hour. - The table displays all events for each entity without date filtering. - Deleted entities are shown using the names extracted from their event specifications. diff --git a/content/documentation/admin/widgets/generic/event-stats.ru.md b/content/documentation/admin/widgets/generic/event-stats.ru.md index d47ffcd9..51d0f89c 100644 --- a/content/documentation/admin/widgets/generic/event-stats.ru.md +++ b/content/documentation/admin/widgets/generic/event-stats.ru.md @@ -4,7 +4,8 @@ description: Мониторинг событий сущностей, поток weight: 140 --- -Виджет отображает статистику событий, происходящих с сущностями в Deckhouse Development Portal (DDP). Виджет содержит три вкладки: +Виджет отображает статистику событий, происходящих с сущностями в Deckhouse Development Portal (DDP). +Виджет содержит три вкладки: 1. «Статистика событий» — график, показывающий количество событий по типам за выбранный временной период с настраиваемой группировкой по времени. 1. «Топ сущностей» — таблица с сущностями, для которых было сгенерировано максимальное количество событий. @@ -16,11 +17,13 @@ weight: 140 ## Параметры запроса +Виджет поддерживает следующие параметры запроса: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------- | -------------- | ------------------------------------------------------------------------------------------ | --------------------- | | Дата от | Да | Начальная дата для выборки событий | 3 дня назад | -| Дата до | Да | Конечная дата для выборки событий | текущая дата | -| Интервал | Нет | Интервал группировки событий на графике (секунды, минуты, часы, дни, недели, месяцы, годы) | час | +| Дата до | Да | Конечная дата для выборки событий | Текущая дата | +| Интервал | Нет | Интервал группировки событий на графике (секунды, минуты, часы, дни, недели, месяцы, годы) | Час | | Шаг интервала | Нет | Количество единиц интервала для группировки | 1 | | Топ сущностей | Нет | Количество сущностей с максимальным количеством событий для отображения в таблице | 10 | @@ -34,6 +37,8 @@ weight: 140 ### Особенности +Виджет имеет следующие особенности: + - График показывает события за выбранный временной период с настраиваемой группировкой по времени (по умолчанию — по часам). - Таблица отображает все события для каждой сущности (без фильтрации по дате). - Для удалённых сущностей отображается их название, извлечённое из спецификации события. @@ -41,7 +46,8 @@ weight: 140 - Для каждого стрима отображается количество событий и информация о последнем событии. - При нажатии на название стрима открывается диалог со всеми событиями из этого стрима. - Стримы автоматически привязываются к ресурсам по UUID, указанному в названии стрима. - - При просмотре событий из стрима отображаются последние 1000 событий (новые первыми). Если в стриме больше 1000 событий, более старые события не отображаются. + - При просмотре событий из стрима отображаются последние 1000 событий (новые первыми). + Если в стриме больше 1000 событий, более старые события не отображаются. - Каждая строка в таблице содержит информацию о последнем событии для сущности. - Доступен просмотр детальной истории изменений для каждой сущности. - События для удалённых ресурсов не отображаются (удаляются из БД при удалении ресурса). diff --git a/content/documentation/admin/widgets/generic/graph.md b/content/documentation/admin/widgets/generic/graph.md index 6536fe81..490fc54c 100644 --- a/content/documentation/admin/widgets/generic/graph.md +++ b/content/documentation/admin/widgets/generic/graph.md @@ -6,15 +6,17 @@ weight: 130 The widget displays information about Deckhouse Development Portal (DDP) objects using one of the following chart types: -* Bar chart. -* Doughnut chart. -* Pie chart. -* Polar area chart. -* Radar chart. +* Bar chart +* Doughnut chart +* Pie chart +* Polar area chart +* Radar chart ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---------------------- | -------- | ----------------------------------------------------------------------------------- | ------- | | Chart type | Yes | Chart visualization type | — | | Table name | Yes | Database table containing the records to visualize | — | @@ -23,12 +25,13 @@ The widget displays information about Deckhouse Development Portal (DDP) objects | Aggregation type | Yes | Method used to group the retrieved records | — | | Aggregation parameters | No | Time range and grouping step used when aggregating records by date | — | -When configuring the widget, account for differences between database field names and object specification field names. When structures are stored in the database, camelCase names from object specifications are converted to snake_case. For example: - -* Specify the `createdAt` field as `created_at` in the widget configuration. -* Specify the `resourceUuid` field as `resource_uuid` in the widget configuration. +When configuring the widget, account for differences between database field names and object specification field names. +When structures are stored in the database, camelCase names from object specifications are converted to snake_case. +For example, specify the `createdAt` field as `created_at` and the `resourceUuid` field as `resource_uuid` in the widget configuration. -Nested values are supported. Separate nesting levels with a period. For example, configure the widget as follows to aggregate entities by status: +Nested values are supported. +Separate nesting levels with a period. +For example, configure the widget as follows to aggregate entities by status: | Table name | Field name | | ---------- | --------------- | @@ -36,35 +39,35 @@ Nested values are supported. Separate nesting levels with a period. For example, ## Aggregation types +The widget supports the following aggregation types. + ### Date Chart data is sorted and grouped by the selected time intervals. -You can configure the following aggregation parameters: - -- **Step unit** — For example, seconds, minutes, hours, or days. -- **Units per step** — For example, 5 minutes, 2 hours, or 1 day. +You can configure the following aggregation parameters: **Step unit**, for example, seconds, minutes, hours, or days, +and **Units per step**, for example, 5 minutes, 2 hours, or 1 day. These parameters control the time-based granularity of the displayed data. ### Value -Chart data is sorted by value. For each unique value in the source data: - -- The number of occurrences is counted. -- The chart displays a value-count pair. +Chart data is sorted by value. +For each unique value in the source data, the number of occurrences is counted, and the chart displays a value-count pair. This aggregation shows the distribution and frequency of values. ### Interval ranges -The **Interval ranges** aggregation divides values into configured numeric ranges. Use it to build histograms and analyze data distributions. +The **Interval ranges** aggregation divides values into configured numeric ranges. +Use it to build histograms and analyze data distributions. Configure intervals in one of two modes: 1. **Automatic division by interval count**. - Specify the number of intervals into which the available data is divided. Intervals are calculated automatically and distributed evenly from the minimum to the maximum value. + Specify the number of intervals into which the available data is divided. + Intervals are calculated automatically and distributed evenly from the minimum to the maximum value. 1. **Manual interval boundaries**. @@ -72,12 +75,7 @@ Configure intervals in one of two modes: The numbers are sorted in ascending order and form these intervals: `[0, 10)`, `[10, 20)`, `[20, 50]`. -Specify at least one of these aggregation parameters: - -- `Count` — Number of intervals. -- `Boundaries` — Interval boundaries. - -Examples: +Specify at least one of these aggregation parameters: `Count` (number of intervals) or `Boundaries` (interval boundaries). -- `Count = 5` — Creates five equal intervals based on the data. -- `Boundaries = 100, 0, 50` — Sorts the boundaries to `[0, 50, 100]` and creates the intervals `[0, 50)` and `[50, 100]`. +For example, `Count = 5` creates five equal intervals based on the data. +`Boundaries = 100, 0, 50` sorts the boundaries to `[0, 50, 100]` and creates the intervals `[0, 50)` and `[50, 100]`. diff --git a/content/documentation/admin/widgets/generic/graph.ru.md b/content/documentation/admin/widgets/generic/graph.ru.md index f762fe6f..0e4a820c 100644 --- a/content/documentation/admin/widgets/generic/graph.ru.md +++ b/content/documentation/admin/widgets/generic/graph.ru.md @@ -6,14 +6,16 @@ weight: 130 Виджет позволяет выводить информацию об объектах Deckhouse Development Portal (DDP) в виде одного из следующих типов графиков: -* Столбчатая диаграмма; -* Кольцевая диаграмма; -* Круговая диаграмма; -* Полярная диаграмма; -* Радарная диаграмма. +* столбчатая диаграмма; +* кольцевая диаграмма; +* круговая диаграмма; +* полярная диаграмма; +* радарная диаграмма. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------- | -------------- | -------------------------------------------------------------------------------- | --------------------- | | Тип графика | Да | Тип визуализации графика | — | @@ -23,12 +25,13 @@ weight: 130 | Тип агрегации | Да | Принцип, по которому будут группироваться полученные записи | — | | Параметры агрегации | Нет | Выбор временного периода и шага группировки при агрегации записей по дате | — | -При настройке виджета учитывайте, что названия полей в базе данных могут отличаться от названий полей в спецификации объектов. Общий принцип таков: формат camelCase в спецификации объектов при сохранении структур в базу данных преобразуется в snake_case. Например: - -* Укажите поле `createdAt` в конфигурации виджета как `created_at`. -* Укажите поле `resourceUuid` в конфигурации виджета как `resource_uuid`. +При настройке виджета учитывайте, что названия полей в базе данных могут отличаться от названий полей в спецификации объектов. +При сохранении структур в базу данных формат camelCase в спецификации объектов преобразуется в snake_case. +Например, укажите поле `createdAt` в конфигурации виджета как `created_at`, а поле `resourceUuid` — как `resource_uuid`. -Доступно обращение к вложенным значениям. В таком случае разделителем для вложенности служит символ точки. Например, чтобы выполнить агрегацию по статусу сущностей, настройте виджет следующим образом: +Доступно обращение к вложенным значениям. +В таком случае разделителем для вложенности служит символ точки. +Например, чтобы выполнить агрегацию по статусу сущностей, настройте виджет следующим образом: | Название таблицы | Название поля | | ---------------- | --------------- | @@ -36,36 +39,34 @@ weight: 130 ## Типы агрегации +Виджет поддерживает следующие типы агрегации. + ### Дата Данные на графике будут отсортированы и сгруппированы по выбранным временным интервалам. -В параметрах агрегации можно задать параметры: - -- «Единица измерения шага» — например: секунды, минуты, часы, дни и т. д. -- «Количество единиц в одном шаге» — например: 5 минут, 2 часа, 1 день и т. п. +В параметрах агрегации можно задать «Единицу измерения шага», например секунды, минуты, часы или дни, +и «Количество единиц в одном шаге», например 5 минут, 2 часа или 1 день. Это позволяет управлять детализацией отображения данных во времени и адаптировать график под нужный масштаб анализа. ### Значение -Данные на графике отображаются в отсортированном порядке — по значениям. -Для каждого уникального значения в исходном наборе данных: - -- Выполняется подсчёт количества вхождений. -- На графике отображается пара: значение — количество. +Данные на графике отображаются в отсортированном порядке — по значениям. +Для каждого уникального значения в исходном наборе данных подсчитывается количество вхождений, и на графике отображается пара «значение — количество». Это позволяет быстро увидеть распределение и частоту повторения различных значений. ### Разбивка по интервалам -Тип агрегации «Разбивка по интервалам» позволяет гибко настроить отображение данных на графике, разделяя значения по заданным числовым диапазонам (интервалам). Это удобно для построения гистограмм и анализа распределения данных. +Тип агрегации «Разбивка по интервалам» позволяет гибко настроить отображение данных на графике, разделяя значения по заданным числовым диапазонам (интервалам). +Это удобно для построения гистограмм и анализа распределения данных. Доступны два режима настройки интервалов: 1. «Автоматическая разбивка по количеству интервалов». - Укажите количество интервалов, на которые нужно разделить доступные данные. + Укажите количество интервалов, на которые делятся доступные данные. Интервалы будут рассчитаны автоматически — равномерно от минимального до максимального значения. 1. «Ручное задание границ интервалов». @@ -79,12 +80,7 @@ weight: 130 - Интервалы сформируются на основе отсортированных значений: `[0, 10)`, `[10, 20)`, `[20, 50]` -Укажите хотя бы один из двух параметров агрегации: - -- `Количество` — количество интервалов; -- `Границы` — границы интервалов. - -Примеры: +Укажите хотя бы один из двух параметров агрегации: `Количество` (количество интервалов) или `Границы` (границы интервалов). -- `Количество = 5` — построится 5 равных интервалов на основании данных. -- `Границы = 100, 0, 50` — после сортировки: `[0, 50, 100]`, график будет построен по интервалам `[0, 50)`, `[50, 100]`. +Например, при `Количество = 5` строится пять равных интервалов на основании данных. +При `Границы = 100, 0, 50` границы сортируются в `[0, 50, 100]`, и график строится по интервалам `[0, 50)` и `[50, 100]`. diff --git a/content/documentation/admin/widgets/generic/helm-releases.md b/content/documentation/admin/widgets/generic/helm-releases.md index 5d678605..711fe88d 100644 --- a/content/documentation/admin/widgets/generic/helm-releases.md +++ b/content/documentation/admin/widgets/generic/helm-releases.md @@ -8,13 +8,15 @@ The widget displays data about Helm releases in Kubernetes and lets you roll bac The widget displays: -* **Helm release list** — Information about current releases created with Helm in the specified Kubernetes namespace. -* **Release manifests** — Manifests associated with Helm releases in the specified Kubernetes namespace, including YAML files that define resource configuration and state. -* **Values** — Variables used to deploy Helm releases. +* **Helm release list**: Information about current releases created with Helm in the specified Kubernetes namespace. +* **Release manifests**: Manifests associated with Helm releases in the specified Kubernetes namespace, including YAML files that define resource configuration and state. +* **Values**: Variables used to deploy Helm releases. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | --------- | -------- | ------------------------------------------------------------------------------------ | ------- | | Namespace | No | Namespace from which the widget loads data. Example: `default` | — | | Release | No | Name of the release from which the widget loads data. Example: `my-release` | — | diff --git a/content/documentation/admin/widgets/generic/helm-releases.ru.md b/content/documentation/admin/widgets/generic/helm-releases.ru.md index 457ef42b..15dc0944 100644 --- a/content/documentation/admin/widgets/generic/helm-releases.ru.md +++ b/content/documentation/admin/widgets/generic/helm-releases.ru.md @@ -9,11 +9,14 @@ weight: 20 Данные, отображаемые на виджете: * «Список релизов Helm» — информация о текущих релизах, созданных с помощью Helm в указанном неймспейсе Kubernetes. -* «Манифесты релизов» — манифесты, связанные с Helm-релизами в указанном неймспейсе Kubernetes. Это включает в себя файлы YAML, которые определяют конфигурацию и состояние ресурсов. +* «Манифесты релизов» — манифесты, связанные с Helm-релизами в указанном неймспейсе Kubernetes. + Это включает в себя файлы YAML, которые определяют конфигурацию и состояние ресурсов. * «Values» — переменные, которые использовались для развёртывания Helm-релизов. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------- | -------------- | ------------------------------------------------------------------------------------ | --------------------- | | Namespace | Нет | Неймспейс, из которого будут загружаться данные в виджет. Пример: `default` | — | diff --git a/content/documentation/admin/widgets/generic/iframe.md b/content/documentation/admin/widgets/generic/iframe.md index e08a05bd..1ec58b3c 100644 --- a/content/documentation/admin/widgets/generic/iframe.md +++ b/content/documentation/admin/widgets/generic/iframe.md @@ -5,13 +5,16 @@ weight: 120 --- {{< alert level="warning" >}} -The Iframe widget works only when `allowIframe: true` is enabled in the security headers configuration (`security.headers.csp.allowIframe`). This option is disabled by default, so the widget does not display content until the configuration is changed. +The Iframe widget works only when `allowIframe: true` is enabled in the security headers configuration (`security.headers.csp.allowIframe`). +This option is disabled by default, so the widget does not display content until the configuration is changed. {{< /alert >}} The widget displays data from an external source. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---- | -------- | --------------------------------------------------- | ------- | | URL | Yes | External source URL used to display data in the widget | — | diff --git a/content/documentation/admin/widgets/generic/iframe.ru.md b/content/documentation/admin/widgets/generic/iframe.ru.md index d487624b..8733a15c 100644 --- a/content/documentation/admin/widgets/generic/iframe.ru.md +++ b/content/documentation/admin/widgets/generic/iframe.ru.md @@ -5,13 +5,16 @@ weight: 120 --- {{< alert level="warning" >}} -Виджет Iframe работает только при включённой опции `allowIframe: true` в конфигурации заголовков безопасности (`security.headers.csp.allowIframe`). По умолчанию эта опция отключена, поэтому виджет не будет отображать контент до изменения конфигурации. +Виджет Iframe работает только при включённой опции `allowIframe: true` в конфигурации заголовков безопасности (`security.headers.csp.allowIframe`). +По умолчанию эта опция отключена, поэтому виджет не будет отображать контент до изменения конфигурации. {{< /alert >}} Виджет позволяет отображать данные из внешнего источника. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------- | -------------- | --------------------------------------------------------------------- | --------------------- | | URL | Да | URL внешнего источника. Используется для отображения данных в виджете | — | diff --git a/content/documentation/admin/widgets/generic/jenkins.md b/content/documentation/admin/widgets/generic/jenkins.md index 27a2fab5..c8bf5c9a 100644 --- a/content/documentation/admin/widgets/generic/jenkins.md +++ b/content/documentation/admin/widgets/generic/jenkins.md @@ -8,7 +8,9 @@ The widget displays Jenkins pipeline data and lets you manage builds. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---- | -------- | ------------------------------------------------------------------------------------ | ------- | | URL | Yes | Jenkins URL used to retrieve data | — | | Name | Yes | Jenkins pipeline name. Nested paths are supported: `folder1/folder2/jobName` | — | @@ -21,17 +23,15 @@ The widget automatically detects the pipeline type and displays the appropriate For regular pipelines, the widget displays: -* **Build list** — A table of all pipeline builds with their number, status, duration, execution time, and user. -* **Latest build** — Information about the latest completed build. -* **Latest successful build** — Information about the latest successful build. -* **Latest failed build** — Information about the latest failed build. +* **Build list**: A table of all pipeline builds with their number, status, duration, execution time, and user. +* **Latest build**: Information about the latest completed build. +* **Latest successful build**: Information about the latest successful build. +* **Latest failed build**: Information about the latest failed build. ### Multibranch pipelines -For multibranch pipelines, the widget displays: - -* **Branch list** — A table of all branches with their status, build count, and latest build. -* All information described for regular pipelines, grouped by branch. +For multibranch pipelines, the widget displays the **Branch list** table with the status, build count, and latest build of each branch. +It also displays all information described for regular pipelines, grouped by branch. ## Additional widget features @@ -39,21 +39,26 @@ The widget supports the following actions. ### Regular pipelines -* **Start build** — Starts a new build. If the build has parameters, the widget opens a dialog for entering: +For regular pipelines, the following actions are available: + +* **Start build**: Starts a new build. If the build has parameters, the widget opens a dialog for entering: * String parameters. * Passwords. * List selections. * Boolean values. -* **Cancel build** — Cancels a running build. -* **Rebuild** — Runs the latest build again. -* **View logs** — Displays build execution logs. +* **Cancel build**: Cancels a running build. +* **Rebuild**: Runs the latest build again. +* **View logs**: Displays build execution logs. ### Multibranch pipelines -* **Start branch build** — Starts a new build for a specific branch. If the build has parameters, the widget opens a dialog for entering them. -* **Get branch builds** — Loads the build list for a specific branch. -* **Scan multibranch** — Starts a multibranch pipeline scan to discover new branches. -* **View logs** — Displays build execution logs. +For multibranch pipelines, the following actions are available: + +* **Start branch build**: Starts a new build for a specific branch. + If the build has parameters, the widget opens a dialog for entering them. +* **Get branch builds**: Loads the build list for a specific branch. +* **Scan multibranch**: Starts a multibranch pipeline scan to discover new branches. +* **View logs**: Displays build execution logs. ## Authorization diff --git a/content/documentation/admin/widgets/generic/jenkins.ru.md b/content/documentation/admin/widgets/generic/jenkins.ru.md index ff0dba4f..47bf371e 100644 --- a/content/documentation/admin/widgets/generic/jenkins.ru.md +++ b/content/documentation/admin/widgets/generic/jenkins.ru.md @@ -8,6 +8,8 @@ weight: 80 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------- | -------------- | ----------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL Jenkins. Используется для получения данных из Jenkins | — | @@ -28,10 +30,8 @@ weight: 80 ### Multibranch пайплайны -Для multibranch пайплайнов виджет отображает: - -* «Список веток» — таблица со всеми ветками с информацией о статусе, количестве сборок и последней сборке для каждой ветки. -* Всю информацию, описанную в разделе «обычные пайплайны», в разрезе каждой ветки. +Для multibranch пайплайнов виджет отображает таблицу «Список веток» с информацией о статусе, количестве сборок и последней сборке для каждой ветки. +Также виджет отображает всю информацию, описанную в разделе «обычные пайплайны», в разрезе каждой ветки. ## Дополнительные возможности виджета @@ -39,6 +39,8 @@ weight: 80 ### Для обычных пайплайнов +Для обычных пайплайнов доступны следующие действия: + * «Запустить сборку» — запуск новой сборки. Если у сборки есть параметры, отображается диалог для их ввода: * Строковые параметры; * Пароли; @@ -50,7 +52,10 @@ weight: 80 ### Для multibranch пайплайнов -* «Запустить сборку ветки» — запуск новой сборки для конкретной ветки. Если у сборки есть параметры, отображается диалог для их ввода. +Для multibranch пайплайнов доступны следующие действия: + +* «Запустить сборку ветки» — запуск новой сборки для конкретной ветки. + Если у сборки есть параметры, отображается диалог для их ввода. * «Получить сборки ветки» — загрузка списка сборок для конкретной ветки. * «Сканировать multibranch» — запуск сканирования multibranch пайплайна для обнаружения новых веток. * «Просмотр логов» — просмотр логов выполнения сборки. diff --git a/content/documentation/admin/widgets/generic/jira.md b/content/documentation/admin/widgets/generic/jira.md index 4577bb69..761ec835 100644 --- a/content/documentation/admin/widgets/generic/jira.md +++ b/content/documentation/admin/widgets/generic/jira.md @@ -8,23 +8,29 @@ The widget displays Jira issues based on a JQL query. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---- | -------- | --------------------------------------------------------------------------- | ------- | | URL | Yes | Jira URL used to retrieve data | — | | JQL | Yes | JQL query used to filter issues. Example: `project = PROJ AND status = Open` | — | ## Query parameters -| Name | Required | Description | Default | +The widget supports the following query parameters: + +| Name | Required | Description | Default value | | --------------- | -------- | ------------------------------------------------------------------------ | ------------------ | | JQL | No | JQL query used to filter issues. If omitted, the configured JQL is used | From configuration | | Maximum results | No | Maximum number of issues to display, from 1 to 1000 | 50 | ## Additional widget features -* **View description** — Opens a dialog with the full issue description. -* **Open in Jira** — Opens the issue in a new tab when you select its key. -* **Dynamic filtering** — Lets you change the JQL query and maximum number of results directly in the widget without changing its configuration. +The widget supports the following additional features: + +* **View description**: Opens a dialog with the full issue description. +* **Open in Jira**: Opens the issue in a new tab when you select its key. +* **Dynamic filtering**: Lets you change the JQL query and maximum number of results directly in the widget without changing its configuration. ## Authorization diff --git a/content/documentation/admin/widgets/generic/jira.ru.md b/content/documentation/admin/widgets/generic/jira.ru.md index e05b1d55..b0fdf43d 100644 --- a/content/documentation/admin/widgets/generic/jira.ru.md +++ b/content/documentation/admin/widgets/generic/jira.ru.md @@ -8,6 +8,8 @@ weight: 110 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------- | -------------- | --------------------------------------------------------------------------- | --------------------- | | URL | Да | URL Jira. Используется для получения данных из Jira | — | @@ -15,6 +17,8 @@ weight: 110 ## Параметры запроса +Виджет поддерживает следующие параметры запроса: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------- | -------------- | --------------------------------------------------------------------------------- | --------------------- | | JQL | Нет | JQL-запрос для фильтрации задач. Если не указан, используется JQL из конфигурации | Из конфигурации | @@ -22,6 +26,8 @@ weight: 110 ## Дополнительные возможности виджета +Виджет поддерживает следующие дополнительные возможности: + * «Просмотр описания» — при клике на кнопку «Просмотр описания» открывается диалоговое окно с полным описанием задачи. * «Переход в Jira» — клик по ключу задачи открывает задачу в Jira в новой вкладке. * «Динамическая фильтрация» — возможность изменить JQL-запрос и максимальное количество результатов прямо в виджете без изменения конфигурации. diff --git a/content/documentation/admin/widgets/generic/markdown.md b/content/documentation/admin/widgets/generic/markdown.md index 94eb6a1c..fa58f560 100644 --- a/content/documentation/admin/widgets/generic/markdown.md +++ b/content/documentation/admin/widgets/generic/markdown.md @@ -8,6 +8,8 @@ The widget displays text written in Markdown. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | -------- | -------- | ------------------------------------------------- | ------- | | Markdown | Yes | Markdown text rendered in the widget | — | diff --git a/content/documentation/admin/widgets/generic/markdown.ru.md b/content/documentation/admin/widgets/generic/markdown.ru.md index 5dbf8b45..6a237ece 100644 --- a/content/documentation/admin/widgets/generic/markdown.ru.md +++ b/content/documentation/admin/widgets/generic/markdown.ru.md @@ -8,6 +8,8 @@ weight: 200 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------- | -------------- | ------------------------------------------------------------------------- | --------------------- | | Markdown | Да | Текст в формате Markdown. Отображается в виджете в отформатированном виде | — | diff --git a/content/documentation/admin/widgets/generic/nexus.md b/content/documentation/admin/widgets/generic/nexus.md index 48d5b74e..f0667930 100644 --- a/content/documentation/admin/widgets/generic/nexus.md +++ b/content/documentation/admin/widgets/generic/nexus.md @@ -8,7 +8,9 @@ The widget displays a list of artifacts in a Nexus repository. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------------------------- | ------- | | URL | Yes | Nexus API URL used to retrieve data | — | | Repository | Yes | Name of the repository whose data is displayed in the widget. Example: `my-repo` | — | diff --git a/content/documentation/admin/widgets/generic/nexus.ru.md b/content/documentation/admin/widgets/generic/nexus.ru.md index c79d5134..0ba99dfe 100644 --- a/content/documentation/admin/widgets/generic/nexus.ru.md +++ b/content/documentation/admin/widgets/generic/nexus.ru.md @@ -8,6 +8,8 @@ weight: 90 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ---------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL Nexus API. Используется для получения данных из Nexus | — | diff --git a/content/documentation/admin/widgets/generic/numeric-value.md b/content/documentation/admin/widgets/generic/numeric-value.md index cd03504f..56979a6b 100644 --- a/content/documentation/admin/widgets/generic/numeric-value.md +++ b/content/documentation/admin/widgets/generic/numeric-value.md @@ -8,6 +8,8 @@ The widget displays a specified numeric value. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | Number | No | Value displayed in the widget. Templating is supported. Without templating: `100`. With templating: `{{ .entity.properties.id }}` | — | diff --git a/content/documentation/admin/widgets/generic/numeric-value.ru.md b/content/documentation/admin/widgets/generic/numeric-value.ru.md index 4e195d7f..7daa64e7 100644 --- a/content/documentation/admin/widgets/generic/numeric-value.ru.md +++ b/content/documentation/admin/widgets/generic/numeric-value.ru.md @@ -8,6 +8,8 @@ weight: 170 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Число | Нет | Значение, которое будет выводиться на виджет. Шаблонизация поддерживается. Пример без шаблонизации: `100`. Пример с шаблонизацией: `{{ .entity.properties.id }}` | — | diff --git a/content/documentation/admin/widgets/generic/opensearch.md b/content/documentation/admin/widgets/generic/opensearch.md index 786c9020..1ccfabe7 100644 --- a/content/documentation/admin/widgets/generic/opensearch.md +++ b/content/documentation/admin/widgets/generic/opensearch.md @@ -4,11 +4,17 @@ description: Search and inspect records from an OpenSearch index or index patter weight: 40 --- -The OpenSearch index widget displays data from a specific index or index pattern in the portal. By default, data is sorted from newest to oldest. Full-text search is available to filter the displayed data. Each record (table row) can be displayed as key-value pairs or as JSON. When an index pattern is specified, the widget provides a link to the Discover page in OpenSearch Dashboards. +The OpenSearch index widget displays data from a specific index or index pattern in the portal. +By default, data is sorted from newest to oldest. +Full-text search is available to filter the displayed data. +Each record (table row) can be displayed as key-value pairs or as JSON. +When an index pattern is specified, the widget provides a link to the Discover page in OpenSearch Dashboards. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------ | | API URL | Yes | OpenSearch API URL used to retrieve data | — | | Dashboards URL | Yes | OpenSearch Dashboards URL used to generate a link for viewing data directly in OpenSearch | — | diff --git a/content/documentation/admin/widgets/generic/opensearch.ru.md b/content/documentation/admin/widgets/generic/opensearch.ru.md index 18e2c962..973ae354 100644 --- a/content/documentation/admin/widgets/generic/opensearch.ru.md +++ b/content/documentation/admin/widgets/generic/opensearch.ru.md @@ -4,10 +4,16 @@ description: Поиск и просмотр записей из индекса weight: 40 --- -Виджет индекса OpenSearch позволяет отображать данные из заданного индекса или шаблона индекса. По умолчанию данные сортируются от новых к старым. Для фильтрации доступен полнотекстовый поиск. Каждую запись в таблице можно просмотреть в формате «ключ — значение» или JSON. Если указан шаблон индекса, виджет отображает ссылку на страницу Discover в OpenSearch Dashboards. +Виджет индекса OpenSearch позволяет отображать данные из заданного индекса или шаблона индекса. +По умолчанию данные сортируются от новых к старым. +Для фильтрации доступен полнотекстовый поиск. +Каждую запись в таблице можно просмотреть в формате «ключ — значение» или JSON. +Если указан шаблон индекса, виджет отображает ссылку на страницу Discover в OpenSearch Dashboards. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------- | | URL API | Да | URL API OpenSearch для получения данных | — | diff --git a/content/documentation/admin/widgets/generic/percent-value.md b/content/documentation/admin/widgets/generic/percent-value.md index 941c9791..27293833 100644 --- a/content/documentation/admin/widgets/generic/percent-value.md +++ b/content/documentation/admin/widgets/generic/percent-value.md @@ -8,6 +8,8 @@ The widget displays a specified percentage value. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | Percent | No | Value displayed in the widget. Templating is supported. Without templating: `100`. With templating: `{{ .entity.properties.id }}` | — | diff --git a/content/documentation/admin/widgets/generic/percent-value.ru.md b/content/documentation/admin/widgets/generic/percent-value.ru.md index b48a3e3f..3bf79db1 100644 --- a/content/documentation/admin/widgets/generic/percent-value.ru.md +++ b/content/documentation/admin/widgets/generic/percent-value.ru.md @@ -8,6 +8,8 @@ weight: 180 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Процент | Нет | Значение, которое будет выводиться на виджет. Шаблонизация поддерживается. Пример без шаблонизации: `100`. Пример с шаблонизацией: `{{ .entity.properties.id }}` | — | diff --git a/content/documentation/admin/widgets/generic/repository-browser.md b/content/documentation/admin/widgets/generic/repository-browser.md index 7b263dbc..0a39ebd5 100644 --- a/content/documentation/admin/widgets/generic/repository-browser.md +++ b/content/documentation/admin/widgets/generic/repository-browser.md @@ -8,7 +8,9 @@ The widget displays the structure and contents of files in GitLab, Bitbucket, an ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ------------ | -------- | -------------------------------------------------------------- | ------- | | Provider | Yes | Service hosting the repository: GitLab, GitHub, or Bitbucket | — | | Branch / Tag | No | Branch name, tag, or commit SHA | `main` | @@ -17,20 +19,26 @@ The widget displays the structure and contents of files in GitLab, Bitbucket, an ## GitLab configuration -| Name | Required | Description | Default | +For GitLab, specify the following parameters: + +| Name | Required | Description | Default value | | ---------- | -------- | ---------------------------------------- | ------- | | Project ID | Yes | GitLab project ID, for example, `12345` | — | ## Bitbucket configuration -| Name | Required | Description | Example | Default | +For Bitbucket, specify the following parameters: + +| Name | Required | Description | Example | Default value | | ------------- | -------- | -------------------------------------------------------- | ------- | ------- | | Project key | Yes | Bitbucket project key, for example, `MYPROJ` | `MYPROJ` | — | | Repository ID | Yes | Bitbucket repository ID, for example, `my-repo` | `my-repo` | — | ## GitHub configuration -| Name | Required | Description | Default | +For GitHub, specify the following parameters: + +| Name | Required | Description | Default value | | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------- | | Repository owner | Yes | Repository owner: an organization or user. For `https://github.com/example/my-repo`, specify `example` | — | | Repository | Yes | Repository name without `.git`. For `https://github.com/example/my-repo`, specify `my-repo` | — | diff --git a/content/documentation/admin/widgets/generic/repository-browser.ru.md b/content/documentation/admin/widgets/generic/repository-browser.ru.md index e050cd40..a08fc58f 100644 --- a/content/documentation/admin/widgets/generic/repository-browser.ru.md +++ b/content/documentation/admin/widgets/generic/repository-browser.ru.md @@ -4,10 +4,13 @@ description: Просмотр файлов и директорий в репоз weight: 190 --- -Виджет позволяет просматривать структуру и содержимое файлов в репозитории. Поддерживаются репозитории GitLab, Bitbucket и GitHub. +Виджет позволяет просматривать структуру и содержимое файлов в репозитории. +Поддерживаются репозитории GitLab, Bitbucket и GitHub. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------- | -------------- | ------------------------------------------------------------------ | --------------------- | | Провайдер | Да | Сервис, в котором размещён репозиторий (GitLab, GitHub, Bitbucket) | — | @@ -17,12 +20,16 @@ weight: 190 ## Конфигурация для GitLab +Для GitLab задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------- | --------------------- | -| ID проекта | Да | ID проекта в GitLab (например, `12345`). | — | +| ID проекта | Да | ID проекта в GitLab (например, `12345`) | — | ## Конфигурация для Bitbucket +Для Bitbucket задайте следующие параметры: + | Название | Обязательность | Описание | Пример | Значение по умолчанию | | ------------------------- | -------------- | --------------------------------------------------------- | ------- | --------------------- | | Ключ проекта | Да | Ключ проекта в Bitbucket (например, `MYPROJ`) | `MYPROJ` | — | @@ -30,6 +37,8 @@ weight: 190 ## Конфигурация для GitHub +Для GitHub задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------- | | Владелец репозитория | Да | Владелец репозитория (организация или пользователь). Пример: для `https://github.com/example/my-repo` укажите `example` | — | diff --git a/content/documentation/admin/widgets/generic/s3.md b/content/documentation/admin/widgets/generic/s3.md index 09e0f7d1..e982467a 100644 --- a/content/documentation/admin/widgets/generic/s3.md +++ b/content/documentation/admin/widgets/generic/s3.md @@ -16,10 +16,8 @@ For each object, you can: ## Using credential templates -You can use credential templating: - -* `{{ .credentials.accessKeyId }}` — Inserts the Access Key ID from the credentials. -* `{{ .credentials.secretAccessKey }}` — Inserts the Secret Access Key from the credentials. +You can use credential templating: `{{ .credentials.accessKeyId }}` inserts the Access Key ID from the credentials, +and `{{ .credentials.secretAccessKey }}` inserts the Secret Access Key. {{< alert level="info" >}} The connected account's permissions determine what information is available in the widget. @@ -27,7 +25,9 @@ The connected account's permissions determine what information is available in t ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ------------------- | -------- | ------------------------------------------------------------------------------------ | ------- | | Bucket name | Yes | Name of the S3 bucket to browse | — | | Endpoint | Yes | S3-compatible storage endpoint URL, for example, `https://storage.yandexcloud.net` | — | @@ -39,15 +39,19 @@ The connected account's permissions determine what information is available in t ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Object search The widget searches for objects by prefix (path). The object list updates to match the specified prefix. {{< alert level="info" >}} -Search matches only characters at the beginning of an object name. Searching by characters in the middle of a name is not supported. +Search matches only characters at the beginning of an object name. +Searching by characters in the middle of a name is not supported. {{< /alert >}} -If the widget configuration specifies an initial prefix, searches are restricted to that prefix. Files with other prefixes cannot be loaded or displayed. +If the widget configuration specifies an initial prefix, searches are restricted to that prefix. +Files with other prefixes cannot be loaded or displayed. ### Downloading files @@ -67,13 +71,12 @@ Select the document icon for an object to view: For buckets containing many objects, use **Load more** to load objects incrementally without reducing performance. -## Authentication - -The widget requires credentials with access to the S3 bucket. It supports: +## Authorization -* Access Key ID and Secret Access Key. -* Different S3-compatible providers through endpoint configuration. +The widget requires credentials with access to the S3 bucket. +It supports authentication with an Access Key ID and Secret Access Key and works with different S3-compatible providers through endpoint configuration. {{< alert level="info" >}} -Unlike other widgets, the S3 widget cannot obtain credentials from external services. Specify all authentication parameters directly in the widget configuration. +Unlike other widgets, the S3 widget cannot obtain credentials from external services. +Specify all authentication parameters directly in the widget configuration. {{< /alert >}} diff --git a/content/documentation/admin/widgets/generic/s3.ru.md b/content/documentation/admin/widgets/generic/s3.ru.md index 7a979c7d..4a631830 100644 --- a/content/documentation/admin/widgets/generic/s3.ru.md +++ b/content/documentation/admin/widgets/generic/s3.ru.md @@ -17,9 +17,7 @@ weight: 100 ## Использование шаблонов для учётных данных Для повышения безопасности можно использовать механизм шаблонизации с учётными данными: - -* `{{ .credentials.accessKeyId }}` — подставить Access Key ID из учётных данных. -* `{{ .credentials.secretAccessKey }}` — подставить Secret Access Key из учётных данных. +`{{ .credentials.accessKeyId }}` подставляет Access Key ID из учётных данных, а `{{ .credentials.secretAccessKey }}` — Secret Access Key. {{< alert level="info" >}} Доступность информации в виджете определяется уровнем прав подключённой учётной записи. @@ -27,6 +25,8 @@ weight: 100 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------- | -------------- | ------------------------------------------------------------------------------------ | --------------------- | | Название S3-бакета | Да | Название S3-бакета для просмотра | — | @@ -39,15 +39,20 @@ weight: 100 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Поиск объектов -Виджет позволяет искать объекты по префиксу (пути). При поиске список объектов обновляется в соответствии с заданным префиксом. +Виджет позволяет искать объекты по префиксу (пути). +При поиске список объектов обновляется в соответствии с заданным префиксом. {{< alert level="info" >}} -Поиск работает только при вводе символов с начала названия объекта. Поиск по символам из середины названия не поддерживается. +Поиск работает только при вводе символов с начала названия объекта. +Поиск по символам из середины названия не поддерживается. {{< /alert >}} -Если в конфигурации виджета задан начальный префикс, поиск в виджете ограничивается этим префиксом. Загрузка и отображение файлов с другим префиксом недоступны. +Если в конфигурации виджета задан начальный префикс, поиск в виджете ограничивается этим префиксом. +Загрузка и отображение файлов с другим префиксом недоступны. ### Загрузка файлов @@ -67,13 +72,12 @@ weight: 100 При наличии большого количества объектов в S3-бакете доступна функция «Загрузить ещё» для пошаговой загрузки объектов без потери производительности. -## Аутентификация - -Для работы с виджетом требуется учётная запись с правами доступа к S3-бакету. Система поддерживает следующие методы аутентификации: +## Авторизация -* Access Key ID и Secret Access Key. -* Поддержка различных S3-совместимых провайдеров через настройку эндпоинта. +Для работы с виджетом требуется учётная запись с правами доступа к S3-бакету. +Виджет поддерживает аутентификацию по Access Key ID и Secret Access Key и работу с различными S3-совместимыми провайдерами через настройку эндпоинта. {{< alert level="info" >}} -В отличие от других виджетов, виджет S3 не поддерживает использование внешних сервисов для передачи учётных данных. Укажите все параметры аутентификации непосредственно в конфигурации виджета. +В отличие от других виджетов, виджет S3 не поддерживает использование внешних сервисов для передачи учётных данных. +Укажите все параметры аутентификации непосредственно в конфигурации виджета. {{< /alert >}} diff --git a/content/documentation/admin/widgets/generic/sonarqube.md b/content/documentation/admin/widgets/generic/sonarqube.md index 590f69b1..d67c03e0 100644 --- a/content/documentation/admin/widgets/generic/sonarqube.md +++ b/content/documentation/admin/widgets/generic/sonarqube.md @@ -8,7 +8,9 @@ The widget displays SonarQube metrics. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | ----------- | -------- | ------------------------------------------------------------------------- | ------------------------------------- | | URL | Yes | SonarQube URL, for example, `https://sonarqube.example.com` | — | | Project key | Yes | Project identifier in SonarQube | — | diff --git a/content/documentation/admin/widgets/generic/sonarqube.ru.md b/content/documentation/admin/widgets/generic/sonarqube.ru.md index 256dbcb0..07a111d7 100644 --- a/content/documentation/admin/widgets/generic/sonarqube.ru.md +++ b/content/documentation/admin/widgets/generic/sonarqube.ru.md @@ -8,6 +8,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------ | -------------- | ------------------------------------------------------------------------------------------ | --------------------------------------- | | URL | Да | Адрес SonarQube, например, `https://sonarqube.example.com` | — | @@ -15,7 +17,7 @@ weight: 30 | Ветка | Нет | Ветка проекта, для которой будут браться метрики | Согласно настройкам проекта в SonarQube | | Метрики | Да | Метрики проекта, которые будут выводиться в виджете. Укажите ключ каждой метрики в конфигурации | — | -Список доступных метрик для текущей версии см. в [документации SonarQube](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/code-metrics/metrics-definition). +Список доступных метрик для текущей версии приведён [в документации SonarQube](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/code-metrics/metrics-definition). ## Дополнительные возможности виджета diff --git a/content/documentation/admin/widgets/generic/svacer.md b/content/documentation/admin/widgets/generic/svacer.md index 1f124f2a..9445acfa 100644 --- a/content/documentation/admin/widgets/generic/svacer.md +++ b/content/documentation/admin/widgets/generic/svacer.md @@ -8,7 +8,9 @@ The widget displays static code analysis results for a project branch in Svacer: ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | --------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- | ------- | | Project name | Yes | Project name in Svacer | — | | Branch name | Yes | Branch name in Svacer, used as the default branch when the widget opens | — | @@ -17,26 +19,31 @@ The widget displays static code analysis results for a project branch in Svacer: | Snapshot marker threshold | No | Number of markers above which a snapshot is considered large | 10,000 | | Large snapshot strategy | No | Behavior when the marker threshold is exceeded | Hybrid | -Large snapshot strategies: - -* **Hybrid** — The unfiltered **Findings** tab is unavailable. The overview is generated using lightweight Svacer requests. -* **Unrestricted** — The full marker list is always loaded. For a large snapshot, the widget only displays a warning. +Two strategies are available for large snapshots. +With **Hybrid**, the unfiltered **Findings** tab is unavailable, and the overview is generated using lightweight Svacer requests. +With **Unrestricted**, the full marker list is always loaded, and for a large snapshot the widget only displays a warning. ## Query parameters The following parameters are available when viewing the widget: -* **Branch** — Svacer branch from which data is loaded. The list is generated for the project in the widget configuration. The configured branch is selected by default. -* **Snapshot** — Branch snapshot from which data is loaded. **Last snapshot** refers to the current branch snapshot when the widget is refreshed. +* **Branch**: Svacer branch from which data is loaded. + The list is generated for the project in the widget configuration. + The configured branch is selected by default. +* **Snapshot**: Branch snapshot from which data is loaded. + **Last snapshot** refers to the current branch snapshot when the widget is refreshed. * **Filters**: - * **Review status** — Marker review status: confirmed, false positive, unclear, no decision, or will not fix. - * **Severity** — Finding severity. - * **Checker** — Checker name, for example, `gosec.G402`. + * **Review status**: Marker review status: confirmed, false positive, unclear, no decision, or will not fix. + * **Severity**: Finding severity. + * **Checker**: Checker name, for example, `gosec.G402`. ## Tabs -* **Overview** — Review progress, number of unreviewed markers, branch findings, findings by severity, finding trends, reviews by status, and comparison with the previous snapshot: new, fixed, matched, and unchanged. -* **Findings** — Paginated marker table with **Severity**, **Confidence**, **Location**, **Checker**, **Review**, **Message**, and **Tags** columns. Each marker links to Svacer. +The **Overview** tab displays review progress, number of unreviewed markers, branch findings, findings by severity, finding trends, reviews by status, +and comparison with the previous snapshot: new, fixed, matched, and unchanged. + +The **Findings** tab displays a paginated marker table with **Severity**, **Confidence**, **Location**, **Checker**, **Review**, **Message**, and **Tags** columns. +Each marker links to Svacer. The widget footer displays summary metrics for the selected snapshot: total markers, unreviewed markers, and filtered findings by severity. diff --git a/content/documentation/admin/widgets/generic/svacer.ru.md b/content/documentation/admin/widgets/generic/svacer.ru.md index f102fa94..4ccd5319 100644 --- a/content/documentation/admin/widgets/generic/svacer.ru.md +++ b/content/documentation/admin/widgets/generic/svacer.ru.md @@ -8,6 +8,8 @@ weight: 50 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------- | | Название проекта | Да | Название проекта в Svacer | — | @@ -15,19 +17,21 @@ weight: 50 | Кэшировать полный список маркеров | Нет | Кеширует на бэкенде Deckhouse Development Portal (DDP) полный список маркеров выбранного снимка из Svacer; ускоряет пагинацию на вкладке «Находки» | Включено | | Время жизни кэша (сек.) | Нет | Сколько секунд хранить ответ в памяти DDP; действует при включённом кеше. Допустимый диапазон при указании значения: 30–86400 | 180 | | Порог маркеров в снимке | Нет | Число маркеров, после которого снимок считается большим | 10 000 | -| Стратегия для больших снимков | Нет | Поведение при превышении порога маркеров (см. ниже) | Гибрид | - -Стратегии для больших снимков: +| Стратегия для больших снимков | Нет | Поведение при превышении порога маркеров. Варианты описаны ниже | Гибрид | -* «Гибрид» — вкладка «Находки» без фильтров недоступна; обзор собирается облегчёнными запросами к Svacer. -* «Без ограничений» — всегда загружается полный список маркеров; при большом снимке отображается только предупреждение. +Для больших снимков доступны две стратегии. +В стратегии «Гибрид» вкладка «Находки» без фильтров недоступна, а обзор собирается облегчёнными запросами к Svacer. +В стратегии «Без ограничений» всегда загружается полный список маркеров, а при большом снимке отображается только предупреждение. ## Параметры запроса При просмотре виджета доступны следующие параметры: -* «Ветка» — ветка Svacer для загрузки данных. Список формируется по проекту из настроек виджета. По умолчанию используется ветка из конфигурации виджета. -* «Снимок» — снимок ветки для загрузки данных. Значение «Последний снимок» соответствует актуальному снимку на ветке в момент обновления виджета. +* «Ветка» — ветка Svacer для загрузки данных. + Список формируется по проекту из настроек виджета. + По умолчанию используется ветка из конфигурации виджета. +* «Снимок» — снимок ветки для загрузки данных. + Значение «Последний снимок» соответствует актуальному снимку на ветке в момент обновления виджета. * «Фильтры»: * «Статус ревью» — фильтр по статусу разметки маркера (подтверждено, ложное срабатывание, неясно, без решения, не исправлять). * «Критичность» — фильтр по уровню критичности находки. @@ -35,8 +39,11 @@ weight: 50 ## Вкладки -* «Обзор» — прогресс ревью, число маркеров без ревью, срабатывания на ветке, распределение по критичности, динамика срабатываний, разбивка ревью по статусам и сравнение с предыдущим снимком (новые, исправленные, совпавшие и без изменений). -* «Находки» — таблица маркеров с колонками «Критичность», «Надёжность», «Место», «Чекер», «Ревью», «Сообщение» и «Теги». Поддерживается пагинация и переход к маркеру в Svacer по ссылке. +На вкладке «Обзор» отображаются прогресс ревью, число маркеров без ревью, срабатывания на ветке, распределение по критичности, динамика срабатываний, +разбивка ревью по статусам и сравнение с предыдущим снимком (новые, исправленные, совпавшие и без изменений). + +На вкладке «Находки» отображается таблица маркеров с колонками «Критичность», «Надёжность», «Место», «Чекер», «Ревью», «Сообщение» и «Теги». +Поддерживается пагинация и переход к маркеру в Svacer по ссылке. В нижней панели виджета отображаются сводные показатели по выбранному снимку: число маркеров в снимке, маркеры без ревью и отфильтрованные находки по уровням критичности. diff --git a/content/documentation/admin/widgets/generic/task-queue.md b/content/documentation/admin/widgets/generic/task-queue.md index db41bc56..f44e1656 100644 --- a/content/documentation/admin/widgets/generic/task-queue.md +++ b/content/documentation/admin/widgets/generic/task-queue.md @@ -4,7 +4,12 @@ description: Monitor background task queues, active workers, and task processing weight: 150 --- -The widget monitors the task queue and the workers that process tasks in the background. It displays queue statistics, worker (consumer) information, and details of every task in the queue. +The widget monitors the task queue and the workers that process tasks in the background. +It displays queue statistics, worker (consumer) information, and details of every task in the queue. + +## Configuration + +The widget requires no additional configuration and works immediately after you add it to the dashboard. ## Displayed data @@ -14,37 +19,34 @@ The widget has three main sections. The top of the widget displays four key metrics: -- **Queue size** — Total number of tasks in the queue. -- **Pending tasks** — Number of tasks waiting to be processed. -- **Active workers** — Number of active workers (consumers) processing tasks. -- **Queued tasks** — Total number of new and in-progress tasks. +- **Queue size**: Total number of tasks in the queue. +- **Pending tasks**: Number of tasks waiting to be processed. +- **Active workers**: Number of active workers (consumers) processing tasks. +- **Queued tasks**: Total number of new and in-progress tasks. ### Workers table The table provides information about each active worker: -- **Consumer name** — Worker (consumer) identifier. -- **Pending tasks** — Number of tasks assigned to the worker and waiting to be processed. -- **Idle time** — Time since the worker's last activity. +- **Consumer name**: Worker (consumer) identifier. +- **Pending tasks**: Number of tasks assigned to the worker and waiting to be processed. +- **Idle time**: Time since the worker's last activity. {{< alert level="info" >}} -The table displays only active workers. Workers that are not processing tasks and have been inactive for more than five minutes are automatically hidden. +The table displays only active workers. +Workers that are not processing tasks and have been inactive for more than five minutes are automatically hidden. {{< /alert >}} ### Tasks table The table provides details about every task in the queue: -- **Task UUID** — Unique task identifier. -- **Type** — Task type, for example, `health_check`. -- **Resource UUID** — Identifier of the resource or entity associated with the task. -- **Consumer** — Name of the consumer processing the task. -- **Idle time** — Time since the task was delivered to the worker. -- **Delivery time** — Time when the task was delivered to the worker. -- **Status** — Current task status: - - **New** — The task has been added to the queue but has not yet been assigned to a worker. - - **In progress** — The task has been assigned to a worker and is being processed. - -## Configuration - -The widget requires no additional configuration and works immediately after you add it to the dashboard. +- **Task UUID**: Unique task identifier. +- **Type**: Task type, for example, `health_check`. +- **Resource UUID**: Identifier of the resource or entity associated with the task. +- **Consumer**: Name of the consumer processing the task. +- **Idle time**: Time since the task was delivered to the worker. +- **Delivery time**: Time when the task was delivered to the worker. +- **Status**: Current task status: + - **New**: The task has been added to the queue but has not yet been assigned to a worker. + - **In progress**: The task has been assigned to a worker and is being processed. diff --git a/content/documentation/admin/widgets/generic/task-queue.ru.md b/content/documentation/admin/widgets/generic/task-queue.ru.md index e4cf31c6..b7ada845 100644 --- a/content/documentation/admin/widgets/generic/task-queue.ru.md +++ b/content/documentation/admin/widgets/generic/task-queue.ru.md @@ -4,7 +4,12 @@ description: Мониторинг очередей фоновых задач, а weight: 150 --- -Виджет позволяет отслеживать состояние очереди задач и работу воркеров, обрабатывающих задачи в фоновом режиме. Виджет отображает статистику очереди, информацию о воркерах (консьюмерах) и детали всех задач в очереди. +Виджет позволяет отслеживать состояние очереди задач и работу воркеров, обрабатывающих задачи в фоновом режиме. +Виджет отображает статистику очереди, информацию о воркерах (консьюмерах) и детали всех задач в очереди. + +## Конфигурация + +Виджет не требует дополнительной конфигурации и работает сразу после добавления на дашборд. ## Отображаемые данные @@ -28,7 +33,8 @@ weight: 150 - «Время простоя» — время с момента последней активности воркера. {{< alert level="info" >}} -В таблице отображаются только активные воркеры. Воркеры, которые не обрабатывают задачи и неактивны более 5 минут, автоматически скрываются из списка. +В таблице отображаются только активные воркеры. +Воркеры, которые не обрабатывают задачи и неактивны более 5 минут, автоматически скрываются из списка. {{< /alert >}} ### Таблица задач @@ -44,7 +50,3 @@ weight: 150 - «Статус» — текущий статус задачи: - «Новая» — задача добавлена в очередь, но ещё не назначена воркеру. - «В обработке» — задача назначена воркеру и обрабатывается. - -## Конфигурация - -Виджет не требует дополнительной конфигурации и работает сразу после добавления на дашборд. diff --git a/content/documentation/admin/widgets/generic/tech-radar.md b/content/documentation/admin/widgets/generic/tech-radar.md index e7dbbdee..0950464a 100644 --- a/content/documentation/admin/widgets/generic/tech-radar.md +++ b/content/documentation/admin/widgets/generic/tech-radar.md @@ -6,10 +6,14 @@ weight: 160 The widget visualizes technologies, tools, and practices used in the company, grouped by maturity level: Adopt, Trial, Assess, and Hold. -The widget displays a circular chart with four quadrants, four rings, and a set of items. Each item has a number, name, quadrant, and ring. Configure the radar contents in the widget settings. +The widget displays a circular chart with four quadrants, four rings, and a set of items. +Each item has a number, name, quadrant, and ring. +Configure the radar contents in the widget settings. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | | --------- | -------- | ----------------------------------------------- | | Quadrants | Yes | Quadrant names | @@ -17,6 +21,8 @@ The widget displays a circular chart with four quadrants, four rings, and a set ### Item configuration +For each radar item, specify the following parameters: + | Name | Required | Description | | ----------- | -------- | ------------------------------------------------------------------- | | Name | Yes | Item name | diff --git a/content/documentation/admin/widgets/generic/tech-radar.ru.md b/content/documentation/admin/widgets/generic/tech-radar.ru.md index a5eb1ed7..99aa5323 100644 --- a/content/documentation/admin/widgets/generic/tech-radar.ru.md +++ b/content/documentation/admin/widgets/generic/tech-radar.ru.md @@ -6,10 +6,13 @@ weight: 160 Виджет позволяет визуализировать технологии, инструменты и практики, используемые в компании, с их разбивкой по уровням зрелости (Adopt, Trial, Assess, Hold). -На виджете отображается круговая диаграмма: четыре квадранта, четыре кольца и набор элементов с номером, названием и привязкой к квадранту и кольцу. Наполнение радара настраивается в конфигурации виджета. +На виджете отображается круговая диаграмма: четыре квадранта, четыре кольца и набор элементов с номером, названием и привязкой к квадранту и кольцу. +Наполнение радара настраивается в конфигурации виджета. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | | --------- | -------------- | ----------------------------------------------------------- | | Квадранты | Да | Названия квадрантов | @@ -17,6 +20,8 @@ weight: 160 ### Конфигурация элемента +Для каждого элемента радара задайте следующие параметры: + | Название | Обязательность | Описание | | -------- | -------------- | ---------------------------------------------------------------------- | | Название | Да | Название элемента | diff --git a/content/documentation/admin/widgets/generic/vault.md b/content/documentation/admin/widgets/generic/vault.md index ced8a332..d52c411a 100644 --- a/content/documentation/admin/widgets/generic/vault.md +++ b/content/documentation/admin/widgets/generic/vault.md @@ -7,7 +7,8 @@ weight: 60 The widget lets you browse secrets in HashiCorp Vault or Deckhouse Stronghold. KV v2 secrets are supported. {{< alert level="info" >}} -The widget does not send secret values to users. Only secret metadata, such as version and creation time, and the key structure without values are sent to the client. +The widget does not send secret values to users. +Only secret metadata, such as version and creation time, and the key structure without values are sent to the client. {{< /alert >}} For each secret, you can: @@ -19,43 +20,44 @@ For each secret, you can: ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- | ------- | | Path | Yes | Path to a secret or directory in Vault. The path must explicitly include `/data/`. Examples: `services/data/`, `services/data/example` | — | | UI prefix | No | UI URL prefix. Use `vault` for HashiCorp Vault or `stronghold` for Deckhouse Stronghold | — | -## Path behavior - -Paths to KV v2 secrets must explicitly include `/data/`. Valid examples: - -* `services/data/` — Browse all secrets in the `services` directory. -* `services/data/example` — View the `example` secret. -* `services/data/nested/secret` — View a nested secret. - ## Displayed data The widget displays the following information. ### Secret structure -* **Directories** — Displayed with a trailing slash, for example, `nested/`, and always identified as directories even if they contain keys. -* **Secrets** — Displayed without a trailing slash and contain keys. +Directories are displayed with a trailing slash, for example, `nested/`, and are always identified as directories even if they contain keys. +Secrets are displayed without a trailing slash and contain keys. ### Secret metadata The following metadata is displayed when available: -* **Version** — Secret version in KV v2. -* **Creation time** — Date and time when the secret was created. -* **Deletion time** — Date and time when the secret version was deleted. -* **Destruction status** — Indicates that the secret was destroyed. +* **Version**: Secret version in KV v2. +* **Creation time**: Date and time when the secret was created. +* **Deletion time**: Date and time when the secret version was deleted. +* **Destruction status**: Indicates that the secret was destroyed. ### Secret keys -Secret keys are displayed in a key-value table: +Secret keys are displayed in a key-value table. +The **Key** column shows the full path to the key in the secret structure, for example, `database.host`. +The **Value** column is always masked as `********` and cannot be revealed. + +## Path behavior + +Paths to KV v2 secrets must explicitly include `/data/`. Valid examples: -* **Key** — Full path to the key in the secret structure, for example, `database.host`. -* **Value** — Always masked as `********` and cannot be revealed. +* `services/data/`: Browse all secrets in the `services` directory. +* `services/data/example`: View the `example` secret. +* `services/data/nested/secret`: View a nested secret. ## Authorization diff --git a/content/documentation/admin/widgets/generic/vault.ru.md b/content/documentation/admin/widgets/generic/vault.ru.md index b385c113..c6ca21cb 100644 --- a/content/documentation/admin/widgets/generic/vault.ru.md +++ b/content/documentation/admin/widgets/generic/vault.ru.md @@ -4,10 +4,12 @@ description: Просмотр метаданных и структуры клю weight: 60 --- -Виджет позволяет просматривать секреты в HashiCorp Vault или Deckhouse Stronghold. Поддерживается работа с KV v2 секретами. +Виджет позволяет просматривать секреты в HashiCorp Vault или Deckhouse Stronghold. +Поддерживается работа с KV v2 секретами. {{< alert level="info" >}} -Виджет не передаёт значения секретов пользователю. На клиентскую сторону передаются только метаданные секретов (версия, время создания и т. д.) и структура ключей без их значений. +Виджет не передаёт значения секретов пользователю. +На клиентскую сторону передаются только метаданные секретов (версия, время создания и т. д.) и структура ключей без их значений. {{< /alert >}} Для каждого секрета доступно: @@ -19,27 +21,21 @@ weight: 60 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------- | | Путь | Да | Путь к секрету или директории в Vault. Необходимо явно указывать путь с `/data/`. Примеры: `services/data/`, `services/data/example` | — | | Префикс UI | Нет | Префикс для URL интерфейса. Используйте `vault` для HashiCorp Vault или `stronghold` для Deckhouse Stronghold | — | -## Особенности работы с путями - -Для работы с KV v2 секретами путь должен явно содержать `/data/`. Примеры корректных путей: - -* `services/data/` — для просмотра всех секретов в директории `services`. -* `services/data/example` — для просмотра конкретного секрета `example`. -* `services/data/nested/secret` — для вложенных секретов. - ## Отображаемые данные Виджет отображает следующую информацию: ### Структура секретов -* «Директории» — отображаются с завершающим слешем (например, `nested/`) и всегда помечаются как директории, даже если содержат ключи. -* «Секреты» — отображаются без завершающего слеша и содержат ключи. +Директории отображаются с завершающим слешем (например, `nested/`) и всегда помечаются как директории, даже если содержат ключи. +Секреты отображаются без завершающего слеша и содержат ключи. ### Метаданные секрета @@ -52,10 +48,17 @@ weight: 60 ### Ключи секрета -Ключи секрета отображаются в формате таблицы «ключ/значение»: +Ключи секрета отображаются в формате таблицы «ключ/значение». +В колонке «Ключ» отображается полный путь к ключу в структуре секрета (например, `database.host`). +Значение всегда маскируется символами `********` и не может быть раскрыто. + +## Особенности работы с путями + +Для работы с KV v2 секретами путь должен явно содержать `/data/`. Примеры корректных путей: -* Ключ — полный путь к ключу в структуре секрета (например, `database.host`). -* Значение — всегда маскируется символами `********` и не может быть раскрыто. +* `services/data/` — для просмотра всех секретов в директории `services`. +* `services/data/example` — для просмотра конкретного секрета `example`. +* `services/data/nested/secret` — для вложенных секретов. ## Авторизация diff --git a/content/documentation/admin/widgets/github/actions.md b/content/documentation/admin/widgets/github/actions.md index bb97dc45..647435c6 100644 --- a/content/documentation/admin/widgets/github/actions.md +++ b/content/documentation/admin/widgets/github/actions.md @@ -4,16 +4,21 @@ description: Filters and actions for GitHub Actions workflow runs, jobs, logs, a weight: 10 --- -The widget displays GitHub Actions runs in a repository. It also displays jobs and artifacts and provides actions for managing them. +The widget displays GitHub Actions runs in a repository. +It also displays jobs and artifacts and provides actions for managing them. ## Account and action initiator -Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. +Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. +If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. -When a workflow is started, canceled, or restarted, or when artifacts and logs are accessed, GitHub identifies the GitHub account that owns the token as the initiator. The login displayed in GitHub may differ from the name in the DDP profile. +When a workflow is started, canceled, or restarted, or when artifacts and logs are accessed, GitHub identifies the GitHub account that owns the token as the initiator. +The login displayed in GitHub may differ from the name in the DDP profile. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Example | | ---------------- | -------- | ----------------------------------------------------- | ------------------------------------------------------------- | | Repository owner | Yes | Repository owner, either an organization or a user | For `https://github.com/example/my-repo`, specify `example` | @@ -23,28 +28,32 @@ When a workflow is started, canceled, or restarted, or when artifacts and logs a Configure the following filters in the widget request settings: -- **Branch** — displays only runs from the specified head branch. -- **Event** — displays only runs triggered by the selected event type. -- **Status** — displays only runs with the selected status or conclusion. -- **Workflow** — displays only runs for the selected workflow file. -- **Triggered by** — displays only runs started by the specified GitHub user. -- **Created at filter** — displays runs created within the specified start and end dates. +- **Branch**: Displays only runs from the specified head branch. +- **Event**: Displays only runs triggered by the selected event type. +- **Status**: Displays only runs with the selected status or conclusion. +- **Workflow**: Displays only runs for the selected workflow file. +- **Triggered by**: Displays only runs started by the specified GitHub user. +- **Created at filter**: Displays runs created within the specified start and end dates. ## Actions The widget provides the following actions: -- **Run workflow** — manually starts a workflow with the `workflow_dispatch` trigger. Select the workflow and branch or tag. If the input YAML declares parameters, the input parameters are displayed. +- **Run workflow**: Manually starts a workflow with the `workflow_dispatch` trigger. + Select the workflow and branch or tag. + If the input YAML declares parameters, the input parameters are displayed. - **Re-run workflow**, **Re-run failed jobs**, and **Cancel workflow** — manage the selected run. -- **Re-run job** — restarts a completed job with the `failure` or `cancelled` conclusion. +- **Re-run job**: Restarts a completed job with the `failure` or `cancelled` conclusion. -Click a run row to expand its jobs and artifacts. In the expanded row, the **Execution log** button opens the job log, and the **Download** button downloads an artifact. The **Show pipeline** button opens the **Jobs and steps** tree of the run. +Click a run row to expand its jobs and artifacts. +In the expanded row, the **Execution log** button opens the job log, and the **Download** button downloads an artifact. +The **Show pipeline** button opens the **Jobs and steps** tree of the run. {{< alert level="info" >}} Workflow and artifact actions require the corresponding permissions in the GitHub repository. {{< /alert >}} -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#github). In the external service settings, set **URL** to `https://api.github.com`. diff --git a/content/documentation/admin/widgets/github/actions.ru.md b/content/documentation/admin/widgets/github/actions.ru.md index d2afa011..c85324a8 100644 --- a/content/documentation/admin/widgets/github/actions.ru.md +++ b/content/documentation/admin/widgets/github/actions.ru.md @@ -8,7 +8,8 @@ weight: 10 ## Учётная запись и автор действий -Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. +Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. +Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. При запуске, отмене и перезапуске рабочего процесса, а также при работе с артефактами и логами в GitHub инициатором считается учётная запись GitHub, которой принадлежит токен. @@ -16,6 +17,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Пример | | -------------------- | -------------- | ---------------------------------------------------- | ---------------------------------------------------------- | | Владелец репозитория | Да | Владелец репозитория (организация или пользователь) | Для `https://github.com/example/my-repo` укажите `example` | @@ -42,7 +45,9 @@ weight: 10 - «Перезапустить workflow», «Перезапустить упавшие jobs», «Отменить workflow» — действия для выбранного запуска. - «Перезапустить job» — перезапуск завершённой задачи с результатом `failure` или `cancelled`. -Нажмите на строку запуска, чтобы раскрыть его задачи и артефакты. В раскрытой строке кнопка «Лог выполнения» открывает лог задачи, а кнопка «Скачать» скачивает артефакт. Кнопка «Показать пайплайн» открывает дерево «Jobs и шаги» запуска. +Нажмите на строку запуска, чтобы раскрыть его задачи и артефакты. +В раскрытой строке кнопка «Лог выполнения» открывает лог задачи, а кнопка «Скачать» скачивает артефакт. +Кнопка «Показать пайплайн» открывает дерево «Jobs и шаги» запуска. {{< alert level="info" >}} Для действий с рабочими процессами и артефактами нужны соответствующие права в репозитории GitHub. diff --git a/content/documentation/admin/widgets/github/pull-requests.md b/content/documentation/admin/widgets/github/pull-requests.md index 6b16fa38..0b1c36d8 100644 --- a/content/documentation/admin/widgets/github/pull-requests.md +++ b/content/documentation/admin/widgets/github/pull-requests.md @@ -1,19 +1,24 @@ --- -title: GitHub. Pull Requests +title: GitHub. Pull requests description: Status filtering and repository actions for GitHub pull requests. weight: 20 --- -The widget displays Pull Requests (PRs) for a GitHub repository. It also provides actions for viewing changes and creating, merging, and closing PRs. +The widget displays Pull Requests (PRs) for a GitHub repository. +It also provides actions for viewing changes and creating, merging, and closing PRs. ## Account and action initiator -Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. +Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. +If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. -When a Pull Request is created, merged, or closed, GitHub identifies the GitHub account that owns the token as the PR author and action initiator. The login and name displayed in GitHub may differ from the name in the DDP profile. +When a Pull Request is created, merged, or closed, GitHub identifies the GitHub account that owns the token as the PR author and action initiator. +The login and name displayed in GitHub may differ from the name in the DDP profile. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Example | | ---------------- | -------- | ----------------------------------------------------- | ------------------------------------------------------------- | | Repository owner | Yes | Repository owner, either an organization or a user | For `https://github.com/example/my-repo`, specify `example` | @@ -23,25 +28,30 @@ When a Pull Request is created, merged, or closed, GitHub identifies the GitHub Filter PRs by status in the widget request settings: -- **Open** — displays only open PRs that are not drafts. -- **Draft** — displays only drafts. -- **Closed** — displays only closed PRs. -- **All** — displays PRs in any status. +- **Open**: Displays only open PRs that are not drafts. +- **Draft**: Displays only drafts. +- **Closed**: Displays only closed PRs. +- **All**: Displays PRs in any status. -By default, the widget displays open PRs. The table displays the number, title, description, status, labels, author, creation date, and update date. An action menu is available for each PR. +By default, the widget displays open PRs. +The table displays the number, title, description, status, labels, author, creation date, and update date. +An action menu is available for each PR. ## Actions -- **Changes** — displays the list of changed files and the diff for each file. -- **Merge** — merges an open PR. This action is available only for open PRs that are not drafts. -- **Close** — closes a PR without merging it. -- **Create PR** — creates a Pull Request. In the dialog, specify the title, source branch, target branch, and description. +The following actions are available for pull requests: + +- **Changes**: Displays the list of changed files and the diff for each file. +- **Merge**: Merges an open PR. This action is available only for open PRs that are not drafts. +- **Close**: Closes a PR without merging it. +- **Create PR**: Creates a Pull Request. + In the dialog, specify the title, source branch, target branch, and description. {{< alert level="info" >}} Pull Request actions require the corresponding permissions in the GitHub repository. {{< /alert >}} -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#github). In the external service settings or widget configuration, set **URL** to `https://api.github.com`. diff --git a/content/documentation/admin/widgets/github/pull-requests.ru.md b/content/documentation/admin/widgets/github/pull-requests.ru.md index b935bf60..0f5a2f81 100644 --- a/content/documentation/admin/widgets/github/pull-requests.ru.md +++ b/content/documentation/admin/widgets/github/pull-requests.ru.md @@ -8,12 +8,16 @@ weight: 20 ## Учётная запись и автор действий -Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. +Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. +Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. -При создании, слиянии и закрытии запроса на слияние в GitHub автором PR и исполнителем действий считается учётная запись GitHub, которой принадлежит этот токен. Логин и имя в интерфейсе GitHub могут не совпадать с именем в профиле DDP. +При создании, слиянии и закрытии запроса на слияние в GitHub автором PR и исполнителем действий считается учётная запись GitHub, которой принадлежит этот токен. +Логин и имя в интерфейсе GitHub могут не совпадать с именем в профиле DDP. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Пример | | -------------------- | -------------- | ---------------------------------------------------- | ---------------------------------------------------------- | | Владелец репозитория | Да | Владелец репозитория (организация или пользователь) | Для `https://github.com/example/my-repo` укажите `example` | @@ -34,6 +38,8 @@ weight: 20 ## Действия +Для запросов на слияние доступны следующие действия: + - «Изменения» — просмотр списка изменённых файлов и сравнение изменений по каждому файлу. - «Слить» — слияние открытого PR (доступно только для открытых PR, не черновиков). - «Закрыть» — закрытие PR без слияния. diff --git a/content/documentation/admin/widgets/github/tags.md b/content/documentation/admin/widgets/github/tags.md index 6a67cbf8..e1cc1bcd 100644 --- a/content/documentation/admin/widgets/github/tags.md +++ b/content/documentation/admin/widgets/github/tags.md @@ -4,20 +4,27 @@ description: Repository tag details and tag creation settings for GitHub. weight: 30 --- -The widget displays GitHub repository tags with commit information, including the author, date, and description. It can also create tags. +The widget displays GitHub repository tags with commit information, including the author, date, and description. +It can also create tags. ## Account and action initiator -Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. +Requests to GitHub use the token from the credentials of the Deckhouse Development Portal (DDP) user on whose behalf the action is invoked. +If **Select account for widget** is enabled in the widget settings, the selected portal user's credentials are used instead of the current user's credentials. -For an annotated tag, where **Description** is provided, the annotation author fields (`tagger`) in the Git tag metadata are populated with the name and email address of the portal user who performed the action, as defined in the DDP profile. If no name is specified, the email address may be used. +For an annotated tag, where **Description** is provided, the annotation author fields (`tagger`) in the Git tag metadata are populated with the name and email address of the portal user who performed the action, as defined in the DDP profile. +If no name is specified, the email address may be used. -For a lightweight tag without a description, no separate Git tag author is set. The tag is created as a reference to a commit. +For a lightweight tag without a description, no separate Git tag author is set. +The tag is created as a reference to a commit. -The API creates the tag using the GitHub account associated with the token. However, the `tagger` data comes from the DDP profile and may not match the GitHub login. +The API creates the tag using the GitHub account associated with the token. +However, the `tagger` data comes from the DDP profile and may not match the GitHub login. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Example | | ---------------- | -------- | ----------------------------------------------------- | ------------------------------------------------------------- | | Repository owner | Yes | Repository owner, either an organization or a user | For `https://github.com/example/my-repo`, specify `example` | @@ -25,10 +32,13 @@ The API creates the tag using the GitHub account associated with the token. Howe ## Displayed data -The table displays the tag, description, commit author, commit link, and commit creation date. The **View** action displays the commit description for each tag. +The table displays the tag, description, commit author, commit link, and commit creation date. +The **View** action displays the commit description for each tag. ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Creating a tag The widget can create tags in GitHub. Specify the following fields in the **Create tag** dialog: @@ -43,7 +53,7 @@ The widget can create tags in GitHub. Specify the following fields in the **Crea Creating tags requires write permissions in the GitHub repository. {{< /alert >}} -## Authentication +## Authorization Authentication is described in [External services](../../external-services/#github). In the external service settings, set **URL** to `https://api.github.com`. diff --git a/content/documentation/admin/widgets/github/tags.ru.md b/content/documentation/admin/widgets/github/tags.ru.md index fa4d3936..5f726a77 100644 --- a/content/documentation/admin/widgets/github/tags.ru.md +++ b/content/documentation/admin/widgets/github/tags.ru.md @@ -8,9 +8,11 @@ weight: 30 ## Учётная запись и автор действий -Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. +Запросы к GitHub выполняются с токеном из учётных данных того пользователя Deckhouse Development Portal (DDP), от имени которого вызывается действие. +Если в настройках виджета включено «Выбрать учётную запись для виджета», используются учётные данные выбранного пользователя портала, а не текущего. -«Аннотированный тег» (поле «Описание» заполнено): в метаданных Git-тега поля автора аннотации (`tagger`) заполняются из имени и email пользователя портала, выполнившего действие (как в профиле DDP). Если имя не задано, может подставляться email. +«Аннотированный тег» (поле «Описание» заполнено): в метаданных Git-тега поля автора аннотации (`tagger`) заполняются из имени и email пользователя портала, выполнившего действие (как в профиле DDP). +Если имя не задано, может подставляться email. «Лёгкий тег» (без описания): отдельный автор тега в Git не задаётся; создаётся ссылка на коммит. @@ -18,6 +20,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Пример | | -------------------- | -------------- | ---------------------------------------------------- | ---------------------------------------------------------- | | Владелец репозитория | Да | Владелец репозитория (организация или пользователь) | Для `https://github.com/example/my-repo` укажите `example` | @@ -31,6 +35,8 @@ weight: 30 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Создание тега Виджет позволяет создавать теги в GitHub. diff --git a/content/documentation/admin/widgets/gitlab/members.md b/content/documentation/admin/widgets/gitlab/members.md index cd353dbf..3bfa44a9 100644 --- a/content/documentation/admin/widgets/gitlab/members.md +++ b/content/documentation/admin/widgets/gitlab/members.md @@ -8,20 +8,13 @@ The widget displays commit activity charts for a GitLab project branch or tag ov ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | | Project ID | Yes | ID of the project from which the widget retrieves data. Example: `12345` | — | -## Displayed data - -The widget displays the following charts with the number of commits per month: - -- the total number of commits in the selected branch or tag; -- a separate chart for each of the 12 authors with the most commits, with the author name, email and number of commits for the period. - -The widget header shows the selected period and the branch or tag. - ## Request parameters The widget request parameters set the branch or tag and the period: @@ -29,14 +22,23 @@ The widget request parameters set the branch or tag and the period: | Name | Required | Description | Default value | | ---- | -------- | ------------------------------------------------- | -------------------------- | | Ref | No | Branch or tag whose commits the widget analyzes | Project default branch | -| from | No | Start date of the period | One year before the current date | -| to | No | End date of the period | Current date | +| `from` | No | Start date of the period | One year before the current date | +| `to` | No | End date of the period | Current date | + +## Displayed data + +The widget displays charts with the number of commits per month: the total number of commits in the selected branch or tag +and a separate chart for each of the 12 authors with the most commits, with the author name, email, and number of commits for the period. + +The widget header shows the selected period and the branch or tag. ## Limitations -- The charts are built from the 1,000 most recent commits of the period. The widget displays the note "Showing the 1,000 most recent commits". -- The period is limited to 730 days. If the selected period is longer, the widget shortens it to 730 days before the end date. +The charts are built from the 1,000 most recent commits of the period. +The widget displays the note "Showing the 1,000 most recent commits". +The period is limited to 730 days. +If the selected period is longer, the widget shortens it to 730 days before the end date. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/members.ru.md b/content/documentation/admin/widgets/gitlab/members.ru.md index 54b3c061..34305566 100644 --- a/content/documentation/admin/widgets/gitlab/members.ru.md +++ b/content/documentation/admin/widgets/gitlab/members.ru.md @@ -8,20 +8,13 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | | ID проекта | Да | ID проекта, из которого будут загружаться данные в виджет. Пример: `12345` | — | -## Отображаемые данные - -Виджет показывает графики с количеством коммитов по месяцам: - -- общее количество коммитов в выбранной ветке или теге; -- отдельный график для каждого из 12 авторов с наибольшим количеством коммитов с именем автора, email и количеством коммитов за период. - -В заголовке виджета отображаются выбранный период и ветка или тег. - ## Параметры запроса В параметрах запроса виджета задаются ветка или тег и период: @@ -32,10 +25,18 @@ weight: 10 | от | Нет | Начальная дата периода | Дата на год раньше текущей | | до | Нет | Конечная дата периода | Текущая дата | +## Отображаемые данные + +Виджет показывает графики с количеством коммитов по месяцам: общее количество коммитов в выбранной ветке или теге +и отдельный график для каждого из 12 авторов с наибольшим количеством коммитов с именем автора, email и количеством коммитов за период. + +В заголовке виджета отображаются выбранный период и ветка или тег. + ## Ограничения -- Графики строятся по 1000 последних коммитов за период. В виджете отображается примечание «Отображается 1000 последних коммитов». -- Период ограничен 730 днями. Если выбранный период длиннее, виджет сокращает его до 730 дней перед конечной датой. +Графики строятся по 1000 последних коммитов за период. +В виджете отображается примечание «Отображается 1000 последних коммитов». +Период ограничен 730 днями. Если выбранный период длиннее, виджет сокращает его до 730 дней перед конечной датой. ## Авторизация diff --git a/content/documentation/admin/widgets/gitlab/merge-requests.md b/content/documentation/admin/widgets/gitlab/merge-requests.md index 8bfbc701..3fe055d2 100644 --- a/content/documentation/admin/widgets/gitlab/merge-requests.md +++ b/content/documentation/admin/widgets/gitlab/merge-requests.md @@ -8,6 +8,8 @@ The widget displays GitLab project merge requests (MRs) and lets you create, mer ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | @@ -17,21 +19,23 @@ The widget displays GitLab project merge requests (MRs) and lets you create, mer Above the table, there are MR state filters with the number of MRs in each state: **All**, **Open**, **Drafts**, **Merged**, **Closed**. -The **Open** filter is selected by default: it shows open MRs except drafts. Open drafts are shown in the **Drafts** filter. +The **Open** filter is selected by default: it shows open MRs except drafts. +Open drafts are shown in the **Drafts** filter. -The **in** list with the **All branches** option filters MRs by target branch. The number of found MRs out of the total number is displayed on the right. +The **in** list with the **All branches** option filters MRs by target branch. +The number of found MRs out of the total number is displayed on the right. ## Table The table contains the following columns: -- **ID** — MR number with a link to GitLab; -- **State** — MR state; -- **Title** — MR title, the **Draft** tag and a conflict icon with the "Conflicts with the target branch" tooltip; -- **Author** and **Reviewers**; -- **Branch** — source branch; the tooltip shows the source and target branches; -- **Updated** — time of the last change; -- the **Actions** menu. +- **ID**: MR number with a link to GitLab. +- **State**: MR state. +- **Title**: MR title, the **Draft** tag and a conflict icon with the "Conflicts with the target branch" tooltip. +- **Author** and **Reviewers**. +- **Branch**: Source branch; the tooltip shows the source and target branches. +- **Updated**: Time of the last change. +- The **Actions** menu. Click a row to expand the MR details: creation and update dates, reviewers, the number of changed files with the number of added and deleted lines, the pipeline status and the **Open in GitLab** link. @@ -39,18 +43,18 @@ Click a row to expand the MR details: creation and update dates, reviewers, the MR actions are available in the expanded row and in the **Actions** menu: -- **Merge** — merges the MR after confirmation; -- **Close** — closes the MR; -- **Mark as draft** and **Mark as ready** — change the draft flag; -- **Diff** — the list of changed files in the expanded row, or a line-by-line file comparison in a separate window from the **Actions** menu; -- **Open in GitLab** — opens the MR in GitLab. +- **Merge**: Merges the MR after confirmation. +- **Close**: Closes the MR. +- **Mark as draft** and **Mark as ready** — change the draft flag. +- **Diff**: The list of changed files in the expanded row, or a line-by-line file comparison in a separate window from the **Actions** menu. +- **Open in GitLab**: Opens the MR in GitLab. If an MR cannot be merged, the reason is displayed next to the buttons: -- "Only an open merge request can be merged"; -- "A draft cannot be merged"; -- "Conflicts with the target branch"; -- "The pipeline is not green" — the latest MR pipeline has not succeeded. +- "Only an open merge request can be merged". +- "A draft cannot be merged". +- "Conflicts with the target branch". +- "The pipeline is not green": The latest MR pipeline has not succeeded. {{< alert level="info" >}} Actions on MRs require the corresponding access permissions in the GitLab repository. @@ -58,15 +62,16 @@ Actions on MRs require the corresponding access permissions in the GitLab reposi ### Creating an MR -The **Create MR** button in the widget header opens the MR creation window. Fill in the **Source branch**, **Target branch**, **Title** and, if needed, **Description** fields and click **Create**. +The **Create MR** button in the widget header opens the MR creation window. +Fill in the **Source branch**, **Target branch**, **Title** and, if needed, **Description** fields and click **Create**. The source and target branches must differ. The **Title** field is required. ## Home page placement -The widget is displayed on the **MRs** tab of a microservice card on the home page if it is selected in the `microservice_merge_requests_widget` slot of the mapping rules. +The widget is displayed on the **MRs** tab of a microservice card on the Home page if it is selected in the `microservice_merge_requests_widget` slot of the mapping rules. In this case, set the **Project ID** field to `{{ .context.repository.id }}`: the microservice card passes the project ID of its repository to the widget. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/merge-requests.ru.md b/content/documentation/admin/widgets/gitlab/merge-requests.ru.md index c883a810..45ea82f5 100644 --- a/content/documentation/admin/widgets/gitlab/merge-requests.ru.md +++ b/content/documentation/admin/widgets/gitlab/merge-requests.ru.md @@ -1,13 +1,15 @@ --- title: GitLab. Запросы слияния -description: Просмотр, фильтрация, создание и слияние merge request проекта GitLab. +description: Просмотр, фильтрация, создание и слияние запросов на слияние проекта GitLab. weight: 20 --- -Виджет показывает merge request (MR) проекта GitLab и позволяет создавать, сливать и закрывать их. +Виджет показывает запросы на слияние (Merge Request, MR) проекта GitLab и позволяет создавать, сливать и закрывать их. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | @@ -17,9 +19,11 @@ weight: 20 Над таблицей расположены фильтры по состоянию MR с числом MR в каждом состоянии: «Все», «Открытые», «Черновики», «Слитые», «Закрытые». -По умолчанию выбран фильтр «Открытые»: он показывает открытые MR без черновиков. Открытые черновики отображаются в фильтре «Черновики». +По умолчанию выбран фильтр «Открытые»: он показывает открытые MR без черновиков. +Открытые черновики отображаются в фильтре «Черновики». -Список «в» с вариантом «Все ветки» фильтрует MR по целевой ветке. Справа отображается число найденных MR из общего числа. +Список «в» с вариантом «Все ветки» фильтрует MR по целевой ветке. +Справа отображается число найденных MR из общего числа. ## Таблица @@ -58,14 +62,16 @@ weight: 20 ### Создание MR -Кнопка «Создать MR» в заголовке виджета открывает окно создания MR. Заполните поля «Ветка-источник», «Целевая ветка», «Название» и, при необходимости, «Описание» и нажмите «Создать». +Кнопка «Создать MR» в заголовке виджета открывает окно создания MR. +Заполните поля «Ветка-источник», «Целевая ветка», «Название» и, при необходимости, «Описание» и нажмите «Создать». Ветка-источник и целевая ветка должны различаться. Поле «Название» обязательное. -## Размещение на главной +## Размещение на главной странице -Виджет выводится на вкладке «MRs» карточки микросервиса на главной, если он выбран в слоте `microservice_merge_requests_widget` [правил маппинга](../../home/mapping/#слоты-виджетов). -В этом случае в поле «ID проекта» укажите `{{ .context.repository.id }}`: карточка микросервиса передаёт виджету ID проекта своего репозитория. +Виджет выводится на вкладке «MRs» карточки микросервиса на главной странице, если он выбран в слоте `microservice_merge_requests_widget` [правил маппинга](../../home/mapping/#слоты-виджетов). +В этом случае в поле «ID проекта» укажите `{{ .context.repository.id }}`. +Карточка микросервиса передаёт виджету ID проекта своего репозитория. ## Авторизация diff --git a/content/documentation/admin/widgets/gitlab/pipeline-editor.md b/content/documentation/admin/widgets/gitlab/pipeline-editor.md index 40b1f987..0d2de138 100644 --- a/content/documentation/admin/widgets/gitlab/pipeline-editor.md +++ b/content/documentation/admin/widgets/gitlab/pipeline-editor.md @@ -9,6 +9,8 @@ and create merge requests with the changes. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | @@ -21,12 +23,16 @@ and a diff view of the original and edited configuration. ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Creating a merge request The widget lets you create a merge request containing pipeline configuration changes. #### Merge request parameters +When creating a merge request, specify the following parameters: + | Name | Required | Description | Default value | | --------------- | -------- | ----------------------------------------------------- | ------------- | | MR title | Yes | Short title describing the purpose of the merge request | — | @@ -37,10 +43,12 @@ The widget lets you create a merge request containing pipeline configuration cha ### Limitations +The widget has the following limitations: + - The widget supports only the `.gitlab-ci.yml` file in the project root. - Creating a merge request requires write access to the repository. - The maximum configuration file size is limited by the GitLab API. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/pipeline-editor.ru.md b/content/documentation/admin/widgets/gitlab/pipeline-editor.ru.md index 7a8a7cc5..5939e20a 100644 --- a/content/documentation/admin/widgets/gitlab/pipeline-editor.ru.md +++ b/content/documentation/admin/widgets/gitlab/pipeline-editor.ru.md @@ -4,10 +4,12 @@ description: Редактирование конфигурации GitLab CI/CD weight: 30 --- -Виджет позволяет редактировать конфигурацию пайплайна GitLab CI/CD (файл `.gitlab-ci.yml`) и создавать запросы на слияние с изменениями. +Виджет позволяет редактировать конфигурацию пайплайна GitLab CI/CD (файл `.gitlab-ci.yml`) и создавать запросы на слияние (Merge Request) с изменениями. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | @@ -20,12 +22,16 @@ weight: 30 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Создание запроса на слияние Виджет позволяет создавать запросы на слияние с изменениями конфигурации пайплайна. #### Параметры запроса на слияние +При создании запроса на слияние задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------- | -------------- | ------------------------------------------------------------ | --------------------- | | Заголовок MR | Да | Краткий заголовок, описывающий цель запроса на слияние | — | @@ -36,6 +42,8 @@ weight: 30 ### Ограничения +Виджет имеет следующие ограничения: + * Виджет работает только с файлом `.gitlab-ci.yml` в корне проекта. * Для создания запроса на слияние требуются права на запись в репозиторий. * Максимальный размер файла конфигурации ограничен возможностями GitLab API. diff --git a/content/documentation/admin/widgets/gitlab/pipeline-statistics.md b/content/documentation/admin/widgets/gitlab/pipeline-statistics.md index 7c9e9130..dd0d505f 100644 --- a/content/documentation/admin/widgets/gitlab/pipeline-statistics.md +++ b/content/documentation/admin/widgets/gitlab/pipeline-statistics.md @@ -9,24 +9,40 @@ including overall statistics and breakdowns by status, source, contributor, and ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | | Project ID | Yes | ID of the project from which the widget retrieves data. Example: `12345` | — | +## Request parameters + +The widget supports the following request parameters: + +| Name | Required | Description | Default value | +| ---------- | -------- | ----------------------------------------------------------------------------------------------- | ------------- | +| Start date | Yes | Start date of the pipeline analysis period in ISO 8601 format. Example: `2024-01-01T00:00:00Z` | — | +| End date | Yes | End date of the pipeline analysis period in ISO 8601 format. Example: `2024-01-31T23:59:59Z` | — | +| Branch | No | Filters by a specific branch. If omitted, the widget analyzes all branches | — | + ## Displayed data The widget displays the following statistics: ### Key metrics -- **Total pipelines** — total number of pipelines during the selected period. -- **Success rate** — percentage of successful pipelines. -- **Failure rate** — percentage of failed pipelines. -- **Average duration** — average pipeline execution time. +The widget displays the following key metrics: + +- **Total pipelines**: Total number of pipelines during the selected period. +- **Success rate**: Percentage of successful pipelines. +- **Failure rate**: Percentage of failed pipelines. +- **Average duration**: Average pipeline execution time. ### Breakdown by status +The breakdown by status shows the following data: + - Successful pipelines. - Failed pipelines. - Canceled pipelines. @@ -35,6 +51,8 @@ The widget displays the following statistics: ### Breakdown by source +The breakdown by source shows the following data: + - Push events (commits). - Merge requests. - Scheduled runs. @@ -42,6 +60,8 @@ The widget displays the following statistics: ### Top contributors +The top contributors section shows the following data: + - Contributors who started the most pipelines. - Contributor avatars, if available. - Number of pipelines for each contributor. @@ -50,20 +70,14 @@ The widget displays the following statistics: The widget shows the branches with the most pipelines and the number of pipelines for each branch. -## Request parameters - -| Name | Required | Description | Default value | -| ---------- | -------- | ----------------------------------------------------------------------------------------------- | ------------- | -| Start date | Yes | Start date of the pipeline analysis period in ISO 8601 format. Example: `2024-01-01T00:00:00Z` | — | -| End date | Yes | End date of the pipeline analysis period in ISO 8601 format. Example: `2024-01-31T23:59:59Z` | — | -| Branch | No | Filters by a specific branch. If omitted, the widget analyzes all branches | — | - ## Limitations +The widget has the following limitations: + - To optimize performance, the widget analyzes no more than 100 pipelines per request. - Statistics include only pipelines with valid data, including a status and execution time. - Data is updated each time the widget refreshes. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/pipeline-statistics.ru.md b/content/documentation/admin/widgets/gitlab/pipeline-statistics.ru.md index 482af281..93ea4d8d 100644 --- a/content/documentation/admin/widgets/gitlab/pipeline-statistics.ru.md +++ b/content/documentation/admin/widgets/gitlab/pipeline-statistics.ru.md @@ -8,17 +8,31 @@ weight: 40 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | | ID проекта | Да | ID проекта, из которого будут загружаться данные в виджет. Пример: `12345` | — | +## Параметры запроса + +Виджет поддерживает следующие параметры запроса: + +| Название | Обязательность | Описание | Значение по умолчанию | +| -------------- | -------------- | ---------------------------------------------------------------------------------------- | --------------------- | +| Начальная дата | Да | Начальная дата для анализа пайплайнов в формате ISO 8601. Пример: `2024-01-01T00:00:00Z` | — | +| Конечная дата | Да | Конечная дата для анализа пайплайнов в формате ISO 8601. Пример: `2024-01-31T23:59:59Z` | — | +| Ветка | Нет | Фильтр по конкретной ветке. Если не указана, анализируются все ветки | — | + ## Отображаемые данные Виджет отображает следующую статистику: ### Основные метрики +Виджет отображает следующие основные метрики: + * «Общее количество пайплайнов» — общее число пайплайнов за выбранный период. * «Процент успеха» — процент успешно выполненных пайплайнов. * «Процент неудач» — процент неудачно выполненных пайплайнов. @@ -26,6 +40,8 @@ weight: 40 ### Распределение по статусам +Распределение по статусам содержит следующие данные: + * Успешные пайплайны. * Неудачные пайплайны. * Отменённые пайплайны. @@ -34,13 +50,17 @@ weight: 40 ### Распределение по источникам +Распределение по источникам содержит следующие данные: + * Отправка изменений (коммиты). -* Запросы на слияние. +* Запросы на слияние (Merge Request). * Запуски по расписанию. * Запуски через веб-интерфейс. ### Топ участников +Раздел «Топ участников» содержит следующие данные: + * Список участников с наибольшим количеством запущенных пайплайнов. * Аватары участников (при наличии). * Количество пайплайнов для каждого участника. @@ -49,16 +69,10 @@ weight: 40 Виджет показывает ветки с наибольшим количеством пайплайнов и количество пайплайнов для каждой ветки. -## Параметры запроса - -| Название | Обязательность | Описание | Значение по умолчанию | -| -------------- | -------------- | ---------------------------------------------------------------------------------------- | --------------------- | -| Начальная дата | Да | Начальная дата для анализа пайплайнов в формате ISO 8601. Пример: `2024-01-01T00:00:00Z` | — | -| Конечная дата | Да | Конечная дата для анализа пайплайнов в формате ISO 8601. Пример: `2024-01-31T23:59:59Z` | — | -| Ветка | Нет | Фильтр по конкретной ветке. Если не указана, анализируются все ветки | — | - ## Ограничения +Виджет имеет следующие ограничения: + * Виджет анализирует максимум 100 пайплайнов за один запрос для оптимизации производительности. * Статистика рассчитывается только для пайплайнов с валидными данными (имеющими статус и время выполнения). * Данные обновляются при каждом обновлении виджета. diff --git a/content/documentation/admin/widgets/gitlab/pipelines.md b/content/documentation/admin/widgets/gitlab/pipelines.md index e9f6a131..7858c37e 100644 --- a/content/documentation/admin/widgets/gitlab/pipelines.md +++ b/content/documentation/admin/widgets/gitlab/pipelines.md @@ -8,6 +8,8 @@ The widget displays GitLab project pipelines with their stages and jobs and lets ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | @@ -17,33 +19,38 @@ The widget displays GitLab project pipelines with their stages and jobs and lets The table contains the following columns: -- **ID** — pipeline number with a link to GitLab; -- **Status** — pipeline state; -- **Ref** — branch or tag; -- **Source** — event that started the pipeline; -- **Initiator** — user who started the pipeline; -- **Duration** and **Finished**; -- the **Actions** menu. +- **ID**: Pipeline number with a link to GitLab. +- **Status**: Pipeline state. +- **Ref**: Branch or tag. +- **Source**: Event that started the pipeline. +- **Initiator**: User who started the pipeline. +- **Duration** and **Finished**. +- The **Actions** menu. The **Actions** menu contains: -- **Rerun pipeline**; -- **Cancel pipeline** — for pending and running pipelines; +- **Rerun pipeline**. +- **Cancel pipeline**: For pending and running pipelines. - **Open in GitLab**. ## Stages and jobs -Click a pipeline row to expand the creation, start and finish times and the pipeline stages. For each stage, the widget displays the status, the number of failed jobs and the stage jobs. If a stage has more than eight jobs, the rest are hidden: to show them, click **Show N more**, where N is the number of hidden jobs. +Click a pipeline row to expand the creation, start and finish times and the pipeline stages. +For each stage, the widget displays the status, the number of failed jobs and the stage jobs. +If a stage has more than eight jobs, the rest are hidden: to show them, click **Show N more**, where N is the number of hidden jobs. -Click a job to open the job panel. The panel displays the job name, the job number with a link to GitLab, the stage, the duration and the following buttons: +Click a job to open the job panel. +The panel displays the job name, the job number with a link to GitLab, the stage, the duration and the following buttons: -- **Run job** — for manual jobs; -- **Rerun job** — unavailable for manual and pending jobs; -- **Cancel job** — for pending, scheduled and running jobs. +- **Run job**: For manual jobs. +- **Rerun job**: Unavailable for manual and pending jobs. +- **Cancel job**: For pending, scheduled and running jobs. ### Job log -The job panel displays the job log: the last 50 lines by default. The **Full log** button shows the entire log, the **Last lines** button returns the shortened view. The job output colors are preserved. +The job panel displays the job log: the last 50 lines by default. +The **Full log** button shows the entire log, the **Last lines** button returns the shortened view. +The job output colors are preserved. If the job has not started yet, the widget displays the message "The job has not started yet — no log". @@ -60,9 +67,9 @@ Run parameters: ## Home page placement -The widget is displayed on the **Pipelines** tab of a microservice card on the home page if it is selected in the `microservice_repository_widget` slot of the mapping rules. +The widget is displayed on the **Pipelines** tab of a microservice card on the Home page if it is selected in the `microservice_repository_widget` slot of the mapping rules. In this case, set the **Project ID** field to `{{ .context.repository.id }}`: the microservice card passes the project ID of its repository to the widget. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/pipelines.ru.md b/content/documentation/admin/widgets/gitlab/pipelines.ru.md index 1a3e9a6a..80d60718 100644 --- a/content/documentation/admin/widgets/gitlab/pipelines.ru.md +++ b/content/documentation/admin/widgets/gitlab/pipelines.ru.md @@ -8,6 +8,8 @@ weight: 50 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | @@ -33,9 +35,12 @@ weight: 50 ## Этапы и задачи -Нажмите на строку пайплайна, чтобы раскрыть время создания, запуска и завершения и этапы пайплайна. Для каждого этапа отображаются статус, число задач с ошибкой и задачи этапа. Если задач больше восьми, остальные скрыты: чтобы их показать, нажмите «Показать ещё N», где N — число скрытых задач. +Нажмите на строку пайплайна, чтобы раскрыть время создания, запуска и завершения и этапы пайплайна. +Для каждого этапа отображаются статус, число задач с ошибкой и задачи этапа. +Если задач больше восьми, остальные скрыты. Чтобы их показать, нажмите «Показать ещё N», где N — число скрытых задач. -Нажмите на задачу, чтобы открыть панель задачи. В панели отображаются название, номер задачи со ссылкой на GitLab, этап, длительность и кнопки: +Нажмите на задачу, чтобы открыть панель задачи. +В панели отображаются название, номер задачи со ссылкой на GitLab, этап, длительность и кнопки: - «Запустить задачу» — для задач с ручным запуском; - «Перезапустить задачу» — недоступна для задач с ручным запуском и ожидающих задач; @@ -43,7 +48,9 @@ weight: 50 ### Журнал задачи -В панели задачи отображается журнал выполнения: по умолчанию последние 50 строк. Кнопка «Полный лог» показывает журнал целиком, кнопка «Последние строки» возвращает сокращённый вид. Цвета вывода задачи сохраняются. +В панели задачи отображается журнал выполнения, по умолчанию — последние 50 строк. +Кнопка «Полный лог» показывает журнал целиком, кнопка «Последние строки» возвращает сокращённый вид. +Цвета вывода задачи сохраняются. Если задача ещё не запускалась, отображается сообщение «Задача ещё не запускалась — лога нет». @@ -58,10 +65,11 @@ weight: 50 | Ref | Да | Целевая ветка или тег для запуска пайплайна | — | | Переменные | Нет | Переменные в формате ключ-значение, которые будут переданы в запускаемый пайплайн | — | -## Размещение на главной +## Размещение на главной странице -Виджет выводится на вкладке «Пайплайны» карточки микросервиса на главной, если он выбран в слоте `microservice_repository_widget` [правил маппинга](../../home/mapping/#слоты-виджетов). -В этом случае в поле «ID проекта» укажите `{{ .context.repository.id }}`: карточка микросервиса передаёт виджету ID проекта своего репозитория. +Виджет выводится на вкладке «Пайплайны» карточки микросервиса на главной странице, если он выбран в слоте `microservice_repository_widget` [правил маппинга](../../home/mapping/#слоты-виджетов). +В этом случае в поле «ID проекта» укажите `{{ .context.repository.id }}`. +Карточка микросервиса передаёт виджету ID проекта своего репозитория. ## Авторизация diff --git a/content/documentation/admin/widgets/gitlab/releases.md b/content/documentation/admin/widgets/gitlab/releases.md index 31ed6292..a177cba3 100644 --- a/content/documentation/admin/widgets/gitlab/releases.md +++ b/content/documentation/admin/widgets/gitlab/releases.md @@ -10,6 +10,8 @@ and a description with Markdown support. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | @@ -17,6 +19,8 @@ and a description with Markdown support. ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Creating a release The widget lets you create a release in GitLab directly from Deckhouse Development Portal (DDP): @@ -29,6 +33,6 @@ The widget lets you create a release in GitLab directly from Deckhouse Developme The created release appears in the list automatically, and the latest release is highlighted. -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/releases.ru.md b/content/documentation/admin/widgets/gitlab/releases.ru.md index 9bb5d8b9..ce181892 100644 --- a/content/documentation/admin/widgets/gitlab/releases.ru.md +++ b/content/documentation/admin/widgets/gitlab/releases.ru.md @@ -8,6 +8,8 @@ weight: 60 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | @@ -15,6 +17,8 @@ weight: 60 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Создание релиза Виджет позволяет создать релиз в GitLab напрямую из Deckhouse Development Portal (DDP): diff --git a/content/documentation/admin/widgets/gitlab/tags.md b/content/documentation/admin/widgets/gitlab/tags.md index 0adf6acb..c33a57e9 100644 --- a/content/documentation/admin/widgets/gitlab/tags.md +++ b/content/documentation/admin/widgets/gitlab/tags.md @@ -8,6 +8,8 @@ The widget displays data about GitLab project tags. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------- | -------- | ------------------------------------------------------------------ | ------------- | | URL | Yes | GitLab API URL used to retrieve data from GitLab | — | @@ -15,18 +17,22 @@ The widget displays data about GitLab project tags. ## Additional widget features +In addition to displaying data, the widget supports the actions described below. + ### Creating tags The widget lets you create GitLab tags directly from Deckhouse Development Portal (DDP). #### Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ----------- | -------- | ---------------------------------------------------- | ------------- | | Name | Yes | Name of the tag to create | — | | Create from | Yes | Branch or existing tag from which to create the tag | — | | Description | No | Description of the tag to create | — | -## Authentication +## Authorization Authentication configuration is described in the [External services](../../external-services/#gitlab) section. diff --git a/content/documentation/admin/widgets/gitlab/tags.ru.md b/content/documentation/admin/widgets/gitlab/tags.ru.md index b8f41806..191e374f 100644 --- a/content/documentation/admin/widgets/gitlab/tags.ru.md +++ b/content/documentation/admin/widgets/gitlab/tags.ru.md @@ -8,6 +8,8 @@ weight: 70 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | -------------------------------------------------------------------------- | --------------------- | | URL | Да | URL GitLab API. Используется для получения данных из GitLab | — | @@ -15,12 +17,16 @@ weight: 70 ## Дополнительные возможности виджета +Помимо отображения данных, виджет поддерживает действия, описанные ниже. + ### Создание тегов Виджет позволяет создавать теги в GitLab напрямую из Deckhouse Development Portal (DDP). #### Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ---------- | -------------- | ----------------------------------------------------------- | --------------------- | | Название | Да | Название создаваемого тега | — | diff --git a/content/documentation/admin/widgets/kafka/acls.md b/content/documentation/admin/widgets/kafka/acls.md index a2941016..51911279 100644 --- a/content/documentation/admin/widgets/kafka/acls.md +++ b/content/documentation/admin/widgets/kafka/acls.md @@ -18,6 +18,8 @@ For each ACL, the widget displays: ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | URL | Yes | Kafka cluster URL | — | @@ -37,18 +39,19 @@ For each ACL, the widget displays: When **Enable widget actions** is on, the widget allows users to create and delete ACL rules. -## Authentication +## Authorization -The widget connects to Kafka with the account set in the **User** and **Password** fields. These fields are needed for the `SASL_PLAINTEXT` and `SASL_SSL` protocols. +The widget connects to Kafka with the account set in the **User** and **Password** fields. +These fields are needed for the `SASL_PLAINTEXT` and `SASL_SSL` protocols. The following authentication protocols are supported: -* `PLAINTEXT`; -* `SASL_PLAINTEXT`; -* `SASL_SSL`. +* `PLAINTEXT` +* `SASL_PLAINTEXT` +* `SASL_SSL` The following SASL mechanisms are supported for the `SASL_PLAINTEXT` and `SASL_SSL` protocols: -* `PLAIN`; -* `SCRAM-SHA-256`; -* `SCRAM-SHA-512`. +* `PLAIN` +* `SCRAM-SHA-256` +* `SCRAM-SHA-512` diff --git a/content/documentation/admin/widgets/kafka/acls.ru.md b/content/documentation/admin/widgets/kafka/acls.ru.md index da9c20e1..d8769426 100644 --- a/content/documentation/admin/widgets/kafka/acls.ru.md +++ b/content/documentation/admin/widgets/kafka/acls.ru.md @@ -18,6 +18,8 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL кластера Kafka | — | @@ -37,9 +39,10 @@ weight: 10 Если включён параметр «Включить действия виджета», виджет позволяет создавать и удалять правила ACL. -## Аутентификация +## Авторизация -Виджет подключается к Kafka с учётной записью, указанной в полях «Пользователь Kafka» и «Пароль». Эти поля нужны для протоколов `SASL_PLAINTEXT` и `SASL_SSL`. +Виджет подключается к Kafka с учётной записью, указанной в полях «Пользователь Kafka» и «Пароль». +Эти поля нужны для протоколов `SASL_PLAINTEXT` и `SASL_SSL`. Поддерживаются протоколы аутентификации: diff --git a/content/documentation/admin/widgets/kafka/topics.md b/content/documentation/admin/widgets/kafka/topics.md index cfed79dd..cfc477ed 100644 --- a/content/documentation/admin/widgets/kafka/topics.md +++ b/content/documentation/admin/widgets/kafka/topics.md @@ -17,6 +17,8 @@ The following information and actions are available for each topic: ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | URL | Yes | Kafka cluster URL | — | @@ -36,21 +38,22 @@ When **Enable widget actions** is on, the widget allows users to: * Send a message to a topic. * Remove all messages from a topic. -## Authentication +## Authorization -The widget connects to Kafka with the account set in the **User** and **Password** fields. These fields are needed for the `SASL_PLAINTEXT` and `SASL_SSL` protocols. +The widget connects to Kafka with the account set in the **User** and **Password** fields. +These fields are needed for the `SASL_PLAINTEXT` and `SASL_SSL` protocols. The following authentication protocols are supported: -* `PLAINTEXT`; -* `SASL_PLAINTEXT`; -* `SASL_SSL`. +* `PLAINTEXT` +* `SASL_PLAINTEXT` +* `SASL_SSL` The following SASL mechanisms are supported for the `SASL_PLAINTEXT` and `SASL_SSL` protocols: -* `PLAIN`; -* `SCRAM-SHA-256`; -* `SCRAM-SHA-512`. +* `PLAIN` +* `SCRAM-SHA-256` +* `SCRAM-SHA-512` {{< alert level="info" >}} The connected account's permissions determine which information is available in the widget. diff --git a/content/documentation/admin/widgets/kafka/topics.ru.md b/content/documentation/admin/widgets/kafka/topics.ru.md index a510e0cf..f9b840c1 100644 --- a/content/documentation/admin/widgets/kafka/topics.ru.md +++ b/content/documentation/admin/widgets/kafka/topics.ru.md @@ -17,6 +17,8 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | ----------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL кластера Kafka | — | @@ -36,9 +38,10 @@ weight: 20 * отправлять сообщение в топик; * очищать топик от сообщений. -## Аутентификация +## Авторизация -Виджет подключается к Kafka с учётной записью, указанной в полях «Пользователь Kafka» и «Пароль». Эти поля нужны для протоколов `SASL_PLAINTEXT` и `SASL_SSL`. +Виджет подключается к Kafka с учётной записью, указанной в полях «Пользователь Kafka» и «Пароль». +Эти поля нужны для протоколов `SASL_PLAINTEXT` и `SASL_SSL`. Поддерживаются протоколы аутентификации: diff --git a/content/documentation/admin/widgets/kaiten/space-cards.md b/content/documentation/admin/widgets/kaiten/space-cards.md index 9efc64ae..5670e3e6 100644 --- a/content/documentation/admin/widgets/kaiten/space-cards.md +++ b/content/documentation/admin/widgets/kaiten/space-cards.md @@ -10,13 +10,17 @@ including status, urgency, blocking state, and assignees. ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |----------|----------|------------------------------------|---------| | Space ID | Yes | Kaiten space identifier | — | ## Query parameters -| Name | Required | Description | Default | +The widget supports the following query parameters: + +| Name | Required | Description | Default value | |---------------|----------|--------------------------------|-------------| | My tasks | No | Filters by the current user | `false` | | Created after | Yes | Start date of the query period | 1 month ago | diff --git a/content/documentation/admin/widgets/kaiten/space-cards.ru.md b/content/documentation/admin/widgets/kaiten/space-cards.ru.md index 38d44a50..1cd65106 100644 --- a/content/documentation/admin/widgets/kaiten/space-cards.ru.md +++ b/content/documentation/admin/widgets/kaiten/space-cards.ru.md @@ -11,12 +11,16 @@ weight: 10 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------- | -------------- | ----------------------------------- | --------------------- | | Идентификатор пространства | Да | Идентификатор пространства в Kaiten | — | ## Параметры запроса +Виджет поддерживает следующие параметры запроса: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------- | -------------- | ------------------------------- | --------------------- | | Мои задачи | Нет | Фильтр по текущему пользователю | `false` | diff --git a/content/documentation/admin/widgets/kaiten/space-stats.md b/content/documentation/admin/widgets/kaiten/space-stats.md index 3002b609..58b9790a 100644 --- a/content/documentation/admin/widgets/kaiten/space-stats.md +++ b/content/documentation/admin/widgets/kaiten/space-stats.md @@ -9,13 +9,17 @@ Use it to analyze team performance and identify bottlenecks in business processe ## Configuration -| Name | Required | Description | Default | +When adding the widget, specify the following parameters: + +| Name | Required | Description | Default value | |----------|----------|------------------------------------|---------| | Space ID | Yes | Kaiten space identifier | — | ## Query parameters -| Name | Required | Description | Default | +The widget supports the following query parameters: + +| Name | Required | Description | Default value | |----------------|----------|-----------------------------------|-------------| | Created after | Yes | Start date of the analysis period | 1 month ago | | Created before | Yes | End date of the analysis period | Now | @@ -28,26 +32,28 @@ The widget contains four tabs. Primary metrics: -- **Queued** — tasks waiting to be processed. -- **Completed** — completed tasks. -- **In progress** — active tasks. +- **Queued**: Tasks waiting to be processed. +- **Completed**: Completed tasks. +- **In progress**: Active tasks. Additional metrics: -- **Blocked** — number of blocked tasks. -- **Blocking** — number of tasks that block other tasks. -- **Archived** — number of archived tasks. -- **Urgent** — number of urgent tasks. -- **Average completion time** — average time to complete a task, in minutes. +- **Blocked**: Number of blocked tasks. +- **Blocking**: Number of tasks that block other tasks. +- **Archived**: Number of archived tasks. +- **Urgent**: Number of urgent tasks. +- **Average completion time**: Average time to complete a task, in minutes. Checklist statistics: -- **Total with checklists** — total number of tasks that have checklists. -- **Checklist completed** — tasks with fully completed checklists. -- **Checklist incomplete** — tasks with incomplete checklists. +- **Total with checklists**: Total number of tasks that have checklists. +- **Checklist completed**: Tasks with fully completed checklists. +- **Checklist incomplete**: Tasks with incomplete checklists. ### By user +The statistics by user include the following data: + - List of users and their assigned task counts. - Progress bar visualization. - Number of tasks assigned to each user. diff --git a/content/documentation/admin/widgets/kaiten/space-stats.ru.md b/content/documentation/admin/widgets/kaiten/space-stats.ru.md index 6992e47d..994e72db 100644 --- a/content/documentation/admin/widgets/kaiten/space-stats.ru.md +++ b/content/documentation/admin/widgets/kaiten/space-stats.ru.md @@ -9,12 +9,16 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------- | -------------- | ----------------------------------- | --------------------- | | Идентификатор пространства | Да | Идентификатор пространства в Kaiten | — | ## Параметры запроса +Виджет поддерживает следующие параметры запроса: + | Название | Обязательность | Описание | Значение по умолчанию | | ------------- | -------------- | -------------------------- | --------------------- | | Создано после | Да | Начальная дата для анализа | 1 месяц назад | @@ -48,6 +52,8 @@ weight: 20 ### По пользователю +Статистика по пользователю содержит следующие данные: + - Список пользователей с количеством назначенных задач. - Визуализация в виде прогресс-баров. - Количество задач на каждого пользователя. diff --git a/content/documentation/admin/widgets/kubernetes/deployments.md b/content/documentation/admin/widgets/kubernetes/deployments.md index 4ff3fffc..5a2feff0 100644 --- a/content/documentation/admin/widgets/kubernetes/deployments.md +++ b/content/documentation/admin/widgets/kubernetes/deployments.md @@ -10,12 +10,20 @@ You can filter Deployments by namespace, label selector, or both. The following actions are available for each Deployment: - View the Deployment specification and status. -- Scale the number of Deployment replicas. After selecting the required number of replicas, apply the change by clicking the floppy-disk **Save** button. +- Scale the number of Deployment replicas. + After selecting the required number of replicas, apply the change by clicking the floppy-disk **Save** button. - View information about pods managed by the Deployment and their containers, including logs for each container. -- View and edit container resources. The widget displays all configured container resources, including CPU, memory, `ephemeral-storage`, and other resource types. You can edit only CPU and memory in the `requests` and `limits` sections. Changes are applied at the Deployment level and propagated to all pods managed by that Deployment. Clearing a CPU or memory value removes the corresponding resource from the container configuration. Other resources, such as `ephemeral-storage`, are displayed but cannot be edited in the widget. +- View and edit container resources. + The widget displays all configured container resources, including CPU, memory, `ephemeral-storage`, and other resource types. + You can edit only CPU and memory in the `requests` and `limits` sections. + Changes are applied at the Deployment level and propagated to all pods managed by that Deployment. + Clearing a CPU or memory value removes the corresponding resource from the container configuration. + Other resources, such as `ephemeral-storage`, are displayed but cannot be edited in the widget. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | Kubernetes API | Yes | Kubernetes API server URL used to retrieve data from Kubernetes | — | diff --git a/content/documentation/admin/widgets/kubernetes/deployments.ru.md b/content/documentation/admin/widgets/kubernetes/deployments.ru.md index 1a4a31d5..5442f88f 100644 --- a/content/documentation/admin/widgets/kubernetes/deployments.ru.md +++ b/content/documentation/admin/widgets/kubernetes/deployments.ru.md @@ -10,12 +10,20 @@ Deployment можно фильтровать по неймспейсу, селе Для каждого Deployment доступны следующие действия: - Просмотр спецификации и статуса Deployment. -- Масштабирование количества реплик Deployment. После выбора требуемого количества реплик нажмите кнопку «Сохранить» с иконкой дискеты. +- Масштабирование количества реплик Deployment. + После выбора требуемого количества реплик нажмите кнопку «Сохранить» с иконкой дискеты. - Просмотр информации о подах, управляемых Deployment, и их контейнерах, включая логи каждого контейнера. -- Просмотр и редактирование ресурсов контейнеров. Виджет отображает все настроенные ресурсы контейнеров, включая CPU, memory, `ephemeral-storage` и другие типы ресурсов. Редактировать можно только CPU и memory в разделах `requests` и `limits`. Изменения применяются на уровне Deployment и распространяются на все поды, которыми он управляет. При очистке значений CPU или memory соответствующие ресурсы удаляются из конфигурации контейнера. Остальные ресурсы, например `ephemeral-storage`, отображаются, но недоступны для редактирования в виджете. +- Просмотр и редактирование ресурсов контейнеров. + Виджет отображает все настроенные ресурсы контейнеров, включая CPU, memory, `ephemeral-storage` и другие типы ресурсов. + Редактировать можно только CPU и memory в разделах `requests` и `limits`. + Изменения применяются на уровне Deployment и распространяются на все поды, которыми он управляет. + При очистке значений CPU или memory соответствующие ресурсы удаляются из конфигурации контейнера. + Остальные ресурсы, например `ephemeral-storage`, отображаются, но недоступны для редактирования в виджете. ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | API Kubernetes | Да | URL сервера API Kubernetes для получения данных из кластера | — | diff --git a/content/documentation/admin/widgets/kubernetes/ingresses.md b/content/documentation/admin/widgets/kubernetes/ingresses.md index af01cd3b..81104978 100644 --- a/content/documentation/admin/widgets/kubernetes/ingresses.md +++ b/content/documentation/admin/widgets/kubernetes/ingresses.md @@ -14,6 +14,8 @@ The following information is available for each Ingress: ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | URL | Yes | Kubernetes API server URL used to retrieve data from Kubernetes | — | diff --git a/content/documentation/admin/widgets/kubernetes/ingresses.ru.md b/content/documentation/admin/widgets/kubernetes/ingresses.ru.md index 15c61a55..59cf54b2 100644 --- a/content/documentation/admin/widgets/kubernetes/ingresses.ru.md +++ b/content/documentation/admin/widgets/kubernetes/ingresses.ru.md @@ -14,6 +14,8 @@ weight: 20 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL сервера API Kubernetes для получения данных из кластера | — | diff --git a/content/documentation/admin/widgets/kubernetes/pods.md b/content/documentation/admin/widgets/kubernetes/pods.md index 928aa76a..a5ef32d6 100644 --- a/content/documentation/admin/widgets/kubernetes/pods.md +++ b/content/documentation/admin/widgets/kubernetes/pods.md @@ -14,6 +14,8 @@ The following information is available for each pod: ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | -------------- | -------- | ------------------------------------------------------------------------------------------------------------------ | ------------- | | URL | Yes | Kubernetes API server URL used to retrieve data from Kubernetes | — | diff --git a/content/documentation/admin/widgets/kubernetes/pods.ru.md b/content/documentation/admin/widgets/kubernetes/pods.ru.md index f8c14009..01c8814c 100644 --- a/content/documentation/admin/widgets/kubernetes/pods.ru.md +++ b/content/documentation/admin/widgets/kubernetes/pods.ru.md @@ -14,6 +14,8 @@ weight: 30 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------- | -------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL сервера API Kubernetes для получения данных из кластера | — | diff --git a/content/documentation/admin/widgets/kubernetes/quotas.md b/content/documentation/admin/widgets/kubernetes/quotas.md index b999cc44..b1c29000 100644 --- a/content/documentation/admin/widgets/kubernetes/quotas.md +++ b/content/documentation/admin/widgets/kubernetes/quotas.md @@ -10,6 +10,8 @@ For each quota, the widget visualizes the resources in use. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | --------- | -------- | ----------------------------------------------------------------------- | ------------- | | URL | Yes | Kubernetes API server URL used to retrieve data from Kubernetes | — | diff --git a/content/documentation/admin/widgets/kubernetes/quotas.ru.md b/content/documentation/admin/widgets/kubernetes/quotas.ru.md index 8bf9161b..fd2061c9 100644 --- a/content/documentation/admin/widgets/kubernetes/quotas.ru.md +++ b/content/documentation/admin/widgets/kubernetes/quotas.ru.md @@ -10,6 +10,8 @@ weight: 40 ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------- | -------------- | --------------------------------------------------------------------------- | --------------------- | | URL | Да | URL сервера API Kubernetes для получения данных из кластера | — | diff --git a/content/documentation/admin/widgets/overview.md b/content/documentation/admin/widgets/overview.md index 36735bf5..cf9a43cd 100644 --- a/content/documentation/admin/widgets/overview.md +++ b/content/documentation/admin/widgets/overview.md @@ -4,12 +4,11 @@ description: Widget purpose, scope, credentials, and configuration principles weight: 10 --- -Widgets are cards that visualize data stored in Deckhouse Development Portal (DDP) and information from infrastructure services. Unlike data sources, widgets retrieve information from infrastructure services when they are displayed in the interface. +Widgets are cards that visualize data stored in Deckhouse Development Portal (DDP) and information from infrastructure services. +Unlike datasources, widgets retrieve information from infrastructure services when they are displayed in the interface. -Widgets can be added to dashboards. Dashboards can be linked to: - -- static pages: **Catalog**, **Self-service**, **AI**, **Administration**, **RBPO**; -- entity cards. +Widgets can be added to dashboards. +Dashboards can be linked to static pages (**Catalog**, **Self-service**, **AI**, **Administration**, **RBPO**) and to entity cards. A widget is also displayed on the **Home** page in a widget slot of a microservice card. @@ -17,16 +16,17 @@ A widget is also displayed on the **Home** page in a widget slot of a microservi A widget configuration includes common parameters and fields specific to the widget type. -Widget configurations support [Go template](https://pkg.go.dev/text/template) syntax for templating during widget processing. For example: - -* `{{ .entity.name }}` — substitutes the value of the entity's `name` parameter. -* `{{ .credentials.token }}` — substitutes credentials named `token`. -* `{{ .context.repository.id }}` — substitutes a value from the home page context. The context is passed only to widgets in home page slots. +Widget configurations support [Go template](https://pkg.go.dev/text/template) syntax for templating during widget processing. +For example: -You can set a scope for each widget: +* `{{ .entity.name }}`: Substitutes the value of the entity's `name` property. +* `{{ .credentials.token }}`: Substitutes credentials named `token`. +* `{{ .context.repository.id }}`: Substitutes a value from the Home page context. + The context is passed only to widgets in Home page slots. -* `Global` — the widget cannot retrieve entity parameters using Go templates. -* `Resource` — the widget can retrieve entity parameters using Go templates. Widgets with the `Resource` scope can only be attached to entity pages. +You can set a scope for each widget. +A widget with the `Global` scope cannot retrieve entity properties using Go templates. +A widget with the `Resource` scope can retrieve entity properties using Go templates and can only be attached to entity pages. In the widget configuration, you can specify the account whose credentials the widget uses to interact with infrastructure systems and select the credentials type. diff --git a/content/documentation/admin/widgets/overview.ru.md b/content/documentation/admin/widgets/overview.ru.md index ccab061f..1602f519 100644 --- a/content/documentation/admin/widgets/overview.ru.md +++ b/content/documentation/admin/widgets/overview.ru.md @@ -4,14 +4,13 @@ description: Назначение, области видимости и прин weight: 10 --- -Виджеты — карточки для визуализации данных, хранящихся в Deckhouse Development Portal (DDP), а также информации из инфраструктурных сервисов. В отличие от источников данных, виджеты получают информацию из инфраструктурных сервисов непосредственно в момент их отображения в интерфейсе. +Виджеты — карточки для визуализации данных, хранящихся в Deckhouse Development Portal (DDP), а также информации из инфраструктурных сервисов. +В отличие от источников данных, виджеты получают информацию из инфраструктурных сервисов непосредственно в момент их отображения в интерфейсе. -Виджеты могут быть добавлены на дашборды. Дашборды, в свою очередь, могут быть привязаны: +Виджеты могут быть добавлены на дашборды. +Дашборды, в свою очередь, могут быть привязаны к статическим страницам («Каталог», «Самообслуживание», «AI», «Администрирование», «РБПО») и к карточкам сущностей. -- к статическим страницам («Каталог», «Самообслуживание», «AI», «Администрирование», «РБПО»); -- к карточкам сущностей. - -Виджет также выводится на главной в [слоте виджета](../home/mapping/#слоты-виджетов) карточки микросервиса. +Виджет также выводится на главной странице в [слоте виджета](../home/mapping/#слоты-виджетов) карточки микросервиса. ## Конфигурация @@ -21,12 +20,12 @@ weight: 10 * `{{ .entity.name }}` — подстановка значения параметра сущности `name`. * `{{ .credentials.token }}` — подстановка учётных данных с названием `token`. -* `{{ .context.repository.id }}` — подстановка значения из контекста главной. Контекст передаётся только виджетам в слотах главной; состав контекста описан в разделе [«Слоты виджетов»](../home/mapping/#слоты-виджетов). - -Для каждого виджета доступно задание области видимости: +* `{{ .context.repository.id }}` — подстановка значения из контекста главной страницы. + Контекст передаётся только виджетам в слотах главной страницы; состав контекста описан в разделе [«Слоты виджетов»](../home/mapping/#слоты-виджетов). -* `Global` — виджет не поддерживает получение параметров сущности через механизм Go template; -* `Resource` — виджет поддерживает получение параметров сущности через механизм Go template. Виджеты с областью видимости `Resource` можно прикрепить только к страницам сущности. +Для каждого виджета можно задать область видимости. +Виджет с областью видимости `Global` не поддерживает получение параметров сущности через механизм Go template. +Виджет с областью видимости `Resource` поддерживает получение параметров сущности через механизм Go template, и его можно прикрепить только к страницам сущности. В конфигурации виджетов возможно задание учётной записи, с данными которой виджет будет взаимодействовать с инфраструктурными системами, а также выбрать тип учётных данных, который будет использоваться. diff --git a/content/documentation/admin/widgets/prometheus/metrics-range.md b/content/documentation/admin/widgets/prometheus/metrics-range.md index 3779c507..f190e890 100644 --- a/content/documentation/admin/widgets/prometheus/metrics-range.md +++ b/content/documentation/admin/widgets/prometheus/metrics-range.md @@ -28,6 +28,8 @@ The chart contains no more than 1100 points, and the minimum step is 30 seconds. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------- | ------------- | | URL | Yes | Prometheus URL | — | diff --git a/content/documentation/admin/widgets/prometheus/metrics-range.ru.md b/content/documentation/admin/widgets/prometheus/metrics-range.ru.md index 8a4c5220..704e811c 100644 --- a/content/documentation/admin/widgets/prometheus/metrics-range.ru.md +++ b/content/documentation/admin/widgets/prometheus/metrics-range.ru.md @@ -4,7 +4,8 @@ description: График временных рядов на основе диа weight: 10 --- -Виджет строит график по результату запроса `query_range` к Prometheus. Запрос в формате PromQL должен возвращать тип `Matrix` (одну или несколько временных серий). +Виджет строит график по результату запроса `query_range` к Prometheus. +Запрос в формате PromQL должен возвращать тип `Matrix` (одну или несколько временных серий). Пример запроса с плейсхолдерами: @@ -26,6 +27,8 @@ sum by (status) (rate(http_requests_total[{{rateInterval}}])) ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------ | --------------------- | | URL | Да | URL Prometheus | — | diff --git a/content/documentation/admin/widgets/prometheus/metrics-single.md b/content/documentation/admin/widgets/prometheus/metrics-single.md index bae30266..99767d05 100644 --- a/content/documentation/admin/widgets/prometheus/metrics-single.md +++ b/content/documentation/admin/widgets/prometheus/metrics-single.md @@ -32,6 +32,8 @@ The query runs at the end of this time range. ## Configuration +When adding the widget, specify the following parameters: + | Name | Required | Description | Default value | | ---------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- | ------------- | | URL | Yes | Prometheus URL | — | diff --git a/content/documentation/admin/widgets/prometheus/metrics-single.ru.md b/content/documentation/admin/widgets/prometheus/metrics-single.ru.md index c8de3b42..e94bdfcf 100644 --- a/content/documentation/admin/widgets/prometheus/metrics-single.ru.md +++ b/content/documentation/admin/widgets/prometheus/metrics-single.ru.md @@ -21,7 +21,8 @@ sum(increase(http_requests_total[{{range}}])) ## Плейсхолдеры в запросе -Используйте плейсхолдеры, если в выражении нужна длительность интервала, выбранного в панели виджета. Запрос выполняется на момент окончания этого интервала. +Используйте плейсхолдеры, если в выражении нужна длительность интервала, выбранного в панели виджета. +Запрос выполняется на момент окончания этого интервала. | Плейсхолдер | Описание | | ------------------ | -------------------------------------------------- | @@ -31,6 +32,8 @@ sum(increase(http_requests_total[{{range}}])) ## Конфигурация +При добавлении виджета задайте следующие параметры: + | Название | Обязательность | Описание | Значение по умолчанию | | -------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------- | | URL | Да | URL Prometheus | — | diff --git a/content/documentation/admin/workflows.md b/content/documentation/admin/workflows.md new file mode 100644 index 00000000..110024d8 --- /dev/null +++ b/content/documentation/admin/workflows.md @@ -0,0 +1,35 @@ +--- +title: Workflows +menuTitle: Workflows +description: Chaining actions together and running them in parallel or sequentially. +weight: 75 +--- + +Workflows are a mechanism for combining actions into a chain and controlling the execution flow. + +Like actions, workflows are bound to specific resources and can be run only for entities of the resource they are bound to. + +## Action run type + +Actions in a workflow can be run in parallel or sequentially. + +If you select a parallel run, all actions start at the same time. +If you select a sequential run, actions start in the order in which they appear in the workflow's action list. +If one of the actions fails, all subsequent actions are created but not started. + +{{< alert level="info" >}} +With a sequential run, if any preceding action requires approval, the actions that follow it start as soon as that action enters the `Unapproved` status. +{{< /alert >}} + +Each workflow action can be either required or optional. +If an action is required, the user running the workflow cannot disable it. +If an action is optional, the user can disable it when running the workflow, and the action will not start. + +## Running a workflow + +When running a workflow, the user is shown a form for filling in the run parameters of each action in the workflow. +Optional actions can be disabled in this form. + +## Workflow parameters + +Configuring and using workflow parameters is described in the ["Templating"](../../user/templating/#workflow-parameters) section. diff --git a/content/documentation/admin/workflows.ru.md b/content/documentation/admin/workflows.ru.md index 3615c7de..aac0570d 100644 --- a/content/documentation/admin/workflows.ru.md +++ b/content/documentation/admin/workflows.ru.md @@ -13,20 +13,22 @@ weight: 75 Действия в одном сценарии могут запускаться параллельно либо последовательно. -При выборе параллельного запуска все действия запустятся одновременно. При выборе последовательного запуска действия будут запускаться в порядке их расположения в списке действий сценария. При этом, если одно из действий выполнилось неуспешно, все последующие будут созданы, но не будут запущены. +При выборе параллельного запуска все действия запустятся одновременно. +При выборе последовательного запуска действия будут запускаться в порядке их расположения в списке действий сценария. +При этом, если одно из действий выполнилось неуспешно, все последующие будут созданы, но не будут запущены. {{< alert level="info" >}} При выборе последовательного запуска и в случае, если какое-либо из вышестоящих действий требует подтверждения, следующие за ним запустятся сразу после того, как данное действие перейдёт в статус `Unapproved`. {{< /alert >}} -Каждое действие сценария может быть обязательным либо опциональным: - -* если действие является обязательным для сценария, то пользователь, запускающий сценарий, не может выключить выполнение данного действия; -* если действие является опциональным, то при запуске сценария пользователь может отключить его, и действие не запустится. +Каждое действие сценария может быть обязательным либо опциональным. +Если действие обязательное, пользователь, запускающий сценарий, не может выключить его выполнение. +Если действие опциональное, при запуске сценария пользователь может отключить его, и действие не запустится. ## Запуск сценария -При запуске сценария пользователю будет предложена форма, в которой он сможет заполнить параметры запуска каждого действия, входящего в сценарий. При этом, если действие является опциональным, оно может быть выключено. +При запуске сценария пользователю будет предложена форма, в которой он сможет заполнить параметры запуска каждого действия, входящего в сценарий. +При этом, если действие является опциональным, оно может быть выключено. ## Параметры сценария diff --git a/content/documentation/admin/workspaces/_index.md b/content/documentation/admin/workspaces/_index.md new file mode 100644 index 00000000..417f6dc3 --- /dev/null +++ b/content/documentation/admin/workspaces/_index.md @@ -0,0 +1,5 @@ +--- +title: Workspaces +description: Configuring workspaces, their templates, and synchronization from GitLab. +weight: 76 +--- diff --git a/content/documentation/admin/workspaces/files.md b/content/documentation/admin/workspaces/files.md new file mode 100644 index 00000000..b169ce78 --- /dev/null +++ b/content/documentation/admin/workspaces/files.md @@ -0,0 +1,145 @@ +--- +title: Template files and scripts +description: Adding files to a workspace, preserving user changes, and scripts for initial setup and start. +weight: 30 +--- + +The starter [workspace template](templates/) delivers files from `files/` to the `/workspace/code` working directory. +Scripts from `scripts/` perform setup after the files are delivered. +The examples below modify the existing starter template. + +## Adding a file to the working directory + +For example, to provide editor settings to every workspace: + +1. Open the template, the "Files" tab, and its draft. +1. Click "Add file" and specify the `files/.vscode/settings.json` path. + You can also use "Upload files" for UTF-8 text files; check the path of each uploaded file. +1. Fill in the file: + + ```json + { + "editor.formatOnSave": true, + "files.insertFinalNewline": true, + "files.trimTrailingWhitespace": true + } + ``` + +1. Click "Save", then publish and activate the new version. +1. Create a workspace from this version and open the IDE. + +`/workspace/code/.vscode/settings.json` appears in the working directory. +The `files/` prefix is not part of the target path. +Nested directories are created automatically. + +By default, a file has the `managed` policy, and its contents are overwritten with the template version contents on every start. +This is suitable for settings managed by the administrator. +For files that the user will change, set a different policy. + +## Preserving user changes in a file + +To provide initial instructions to the agent and allow the owner to change them, create `files/AGENTS.md` or modify the existing file: + +```markdown +# Project instructions + +Read README.md before changing the project. +Run the tests related to changed files. +Show the test results and changed files in the final response. +``` + +In the existing `locals` block of `main.tf`, set the policy by the path relative to `files/`: + +```hcl +file_policies = { + "AGENTS.md" = "create_if_missing" + ".vscode/settings.json" = "create_if_missing" +} +``` + +The `create_if_missing` policy creates a file only if it does not yet exist in the working directory. +An existing file, including one obtained from Git, is preserved. +Changing the file in a new template version does not replace the user's copy. + +The policies work as follows: + +| Policy | On first start | On subsequent starts | +| --- | --- | --- | +| `managed` | Writes the contents from the template, replacing an existing file | Writes the contents from the template version in use again | +| `create_if_missing` | Creates the file only if it is missing | Preserves the existing file | + +In the default template, `AGENTS.md` already has the `create_if_missing` policy. +Other files without an explicit policy use `managed`. + +## Initial setup of a new volume + +For example, to create a directory for results and provide an initial application configuration: + +1. Add the `files/config/application.example.json` file: + + ```json + { + "listen": "0.0.0.0:8080", + "logLevel": "info" + } + ``` + +1. Add the `scripts/create.sh` file: + + ```bash + #!/usr/bin/env bash + set -euo pipefail + + mkdir -p .local/results + if [ ! -e config/application.json ]; then + cp config/application.example.json config/application.json + fi + ``` + +1. Save the files, then publish and activate the version. +1. Create a workspace and check the `.local/results` directory and the `config/application.json` file. + +The script runs from the working directory after the repository is cloned, files are delivered, and skills are prepared. +After a successful run, a mark is saved on the volume; subsequent starts on the same volume skip `create.sh`. +If the script fails, the next attempt runs it again, so check whether files have already been created. + +Adding `create.sh` to a new template version does not repeat an initial setup that has already succeeded on an existing volume. +For setup on every start, use `start.sh`. + +## Setup on every start + +To check the configuration and create temporary directories after every Pod start, add `scripts/start.sh`: + +```bash +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p .local/cache +test -s config/application.json +printf 'Workspace configuration is ready\n' +``` + +For this example, first add `create.sh` and the initial file from the previous example. +On a successful start, the `bootstrap` container outputs `Workspace configuration is ready`. + +The script runs before the agent and IDE start. +Commands must terminate; do not start a server in the script that occupies the process indefinitely. +A script error prevents the Pod from becoming ready and is shown in the `bootstrap` log on the "Diagnostics" tab. + +The default Pod runs with UID/GID `10000`, without privilege escalation, and with a read-only root file system. +Place working data and installed tools on the persistent volume. +For an example of installing Go and configuring the agent and IDE environment, see [the development tools guide](tools/#installing-go). + +## Applying changes to an existing workspace + +For an existing workspace to receive new files: + +1. Publish a new template version. +1. Stop the workspace. +1. Update it to the new version and wait for the operation to succeed. +1. Start the workspace. +1. Check the files in the IDE and the `bootstrap` container log. + +For `managed`, the new contents are applied. +For `create_if_missing`, the existing file is preserved. +Activating a template version does not by itself change files of already created workspaces. diff --git a/content/documentation/admin/workspaces/files.ru.md b/content/documentation/admin/workspaces/files.ru.md index 3a78ac8c..234e64ca 100644 --- a/content/documentation/admin/workspaces/files.ru.md +++ b/content/documentation/admin/workspaces/files.ru.md @@ -4,14 +4,17 @@ description: Добавление файлов в рабочее простра weight: 30 --- -Стартовый [шаблон рабочего пространства](templates/) доставляет файлы из `files/` в рабочую директорию `/workspace/code`. Скрипты из `scripts/` выполняют настройку после доставки файлов. Примеры ниже изменяют существующий стартовый шаблон. +Стартовый [шаблон рабочего пространства](templates/) доставляет файлы из `files/` в рабочую директорию `/workspace/code`. +Скрипты из `scripts/` выполняют настройку после доставки файлов. +Примеры ниже изменяют существующий стартовый шаблон. ## Добавление файла в рабочую директорию Например, чтобы каждое пространство получало настройки редактора: 1. Откройте шаблон, вкладку «Файлы», и его черновик. -1. Нажмите «Добавить файл» и укажите путь `files/.vscode/settings.json`. Можно также использовать «Загрузить файлы» для текстовых файлов в UTF-8; проверьте путь каждого загруженного файла. +1. Нажмите «Добавить файл» и укажите путь `files/.vscode/settings.json`. + Можно также использовать «Загрузить файлы» для текстовых файлов в UTF-8; проверьте путь каждого загруженного файла. 1. Заполните файл: ```json @@ -25,9 +28,13 @@ weight: 30 1. Нажмите «Сохранить», опубликуйте и активируйте новую версию. 1. Создайте рабочее пространство из этой версии и откройте IDE. -В рабочей директории появится `/workspace/code/.vscode/settings.json`. Префикс `files/` в целевой путь не входит. Вложенные директории создаются автоматически. +В рабочей директории появится `/workspace/code/.vscode/settings.json`. +Префикс `files/` в целевой путь не входит. +Вложенные директории создаются автоматически. -По умолчанию файл имеет политику `managed`: при каждом запуске содержимое перезаписывается содержимым версии шаблона. Это подходит для настроек, которыми управляет администратор. Для файлов, которые пользователь будет менять, задайте другую политику. +По умолчанию файл имеет политику `managed`, и при каждом запуске содержимое перезаписывается содержимым версии шаблона. +Это подходит для настроек, которыми управляет администратор. +Для файлов, которые пользователь будет менять, задайте другую политику. ## Файл с сохранением пользовательских изменений @@ -50,7 +57,9 @@ file_policies = { } ``` -Политика `create_if_missing` создаёт файл, только если его ещё нет в рабочей директории. Существующий файл, в том числе полученный из Git, сохраняется. Изменение файла в новой версии шаблона не заменяет пользовательскую копию. +Политика `create_if_missing` создаёт файл, только если его ещё нет в рабочей директории. +Существующий файл, в том числе полученный из Git, сохраняется. +Изменение файла в новой версии шаблона не заменяет пользовательскую копию. Политики действуют следующим образом: @@ -59,7 +68,8 @@ file_policies = { | `managed` | Записывает содержимое из шаблона, включая замену существующего файла | Снова записывает содержимое из используемой версии шаблона | | `create_if_missing` | Создаёт только отсутствующий файл | Сохраняет существующий файл | -В штатном шаблоне `AGENTS.md` уже имеет политику `create_if_missing`. Для остальных файлов без явной политики используется `managed`. +В штатном шаблоне `AGENTS.md` уже имеет политику `create_if_missing`. +Для остальных файлов без явной политики используется `managed`. ## Первоначальная настройка нового тома @@ -89,9 +99,12 @@ file_policies = { 1. Сохраните файлы, опубликуйте и активируйте версию. 1. Создайте рабочее пространство и проверьте директорию `.local/results` и файл `config/application.json`. -Скрипт выполняется из рабочей директории после клонирования репозитория, доставки файлов и подготовки навыков. После успешного выполнения на томе сохраняется отметка; повторный запуск на том же томе пропускает `create.sh`. Если скрипт завершится ошибкой, следующая попытка повторит его, поэтому проверяйте существование уже созданных файлов. +Скрипт выполняется из рабочей директории после клонирования репозитория, доставки файлов и подготовки навыков. +После успешного выполнения на томе сохраняется отметка; повторный запуск на том же томе пропускает `create.sh`. +Если скрипт завершится ошибкой, следующая попытка повторит его, поэтому проверяйте существование уже созданных файлов. -Добавление `create.sh` в новую версию шаблона не повторяет уже успешно выполненную первоначальную настройку существующего тома. Для настройки при каждом запуске используйте `start.sh`. +Добавление `create.sh` в новую версию шаблона не повторяет уже успешно выполненную первоначальную настройку существующего тома. +Для настройки при каждом запуске используйте `start.sh`. ## Настройка при каждом запуске @@ -106,11 +119,16 @@ test -s config/application.json printf 'Workspace configuration is ready\n' ``` -В этом примере сначала добавьте `create.sh` и начальный файл из предыдущего примера. При успешном запуске контейнер `bootstrap` выведет `Workspace configuration is ready`. +В этом примере сначала добавьте `create.sh` и начальный файл из предыдущего примера. +При успешном запуске контейнер `bootstrap` выведет `Workspace configuration is ready`. -Скрипт выполняется до старта агента и IDE. Команды должны завершаться; не запускайте в нём сервер, который занимает процесс навсегда. Ошибка скрипта препятствует готовности пода и отображается в логе `bootstrap` на вкладке «Диагностика». +Скрипт выполняется до старта агента и IDE. +Команды должны завершаться; не запускайте в нём сервер, который занимает процесс навсегда. +Ошибка скрипта препятствует готовности пода и отображается в логе `bootstrap` на вкладке «Диагностика». -Штатный под работает с UID/GID `10000`, без повышения привилегий и с корневой файловой системой только для чтения. Размещайте рабочие данные и устанавливаемые инструменты на постоянном томе. Пример установки Go и настройки окружения агента и IDE — [в руководстве по инструментам разработки](tools/#установка-go). +Штатный под работает с UID/GID `10000`, без повышения привилегий и с корневой файловой системой только для чтения. +Размещайте рабочие данные и устанавливаемые инструменты на постоянном томе. +Пример установки Go и настройки окружения агента и IDE — [в руководстве по инструментам разработки](tools/#установка-go). ## Применение изменений к существующему пространству @@ -122,4 +140,6 @@ printf 'Workspace configuration is ready\n' 1. Запустите рабочее пространство. 1. Проверьте файлы в IDE и лог контейнера `bootstrap`. -Для `managed` применится новое содержимое. Для `create_if_missing` сохранится существующий файл. Активация версии шаблона сама по себе не меняет файлы уже созданных пространств. +Для `managed` применится новое содержимое. +Для `create_if_missing` сохранится существующий файл. +Активация версии шаблона сама по себе не меняет файлы уже созданных пространств. diff --git a/content/documentation/admin/workspaces/network-storage.md b/content/documentation/admin/workspaces/network-storage.md new file mode 100644 index 00000000..f6f1574e --- /dev/null +++ b/content/documentation/admin/workspaces/network-storage.md @@ -0,0 +1,147 @@ +--- +title: Images, Ingress, and storage +description: Examples of configuring image pull secrets, a separate IDE domain, Ingress, TLS, cert-manager, and the workspace persistent volume. +weight: 40 +--- + +Settings for images, IDE publishing, and the persistent volume are located in `main.tf` of the starter [workspace template](templates/). +The examples change values in the existing `locals` block; you do not need to add a second block with the same names. + +## Images from a private registry + +For the workspace Pod to pull private images, create a Secret of the `kubernetes.io/dockerconfigjson` type in the target namespace. +For example, using a prepared Docker config without putting the password on the command line: + +```shell +d8 k -n team-workspaces create secret generic workspace-registry --type=kubernetes.io/dockerconfigjson --from-file=.dockerconfigjson=/secure/path/config.json +``` + +Replace `team-workspaces` with the template "Namespace", and the path with a file that grants access to the required container registry. +The account running the command must have permission to create Secrets in this namespace. + +In `main.tf`, replace the value: + +```hcl +image_pull_secrets = ["workspace-registry"] +``` + +For several registries, specify several Secret names. +The starter template adds them to the Pod `imagePullSecrets`, including for pulling the init container image. + +Save, publish, and activate the template, then create a workspace. +In "Diagnostics", check that the Pod has pulled the images and the containers are ready. + +### Secrets for operation Jobs + +OpenTofu Jobs and workspace Pods use separate image pull settings. +When DDP is installed with the module, Jobs run in `d8-development-platform`; additional Secrets for them are set in `spec.settings.imagePullSecrets` of ModuleConfig: + +```yaml +imagePullSecrets: + - operations-registry +``` + +The `operations-registry` Secret must exist in `d8-development-platform`. +This setting does not create a Secret in the target cluster and does not fill in `local.image_pull_secrets` of the template. +Prepare both locations if private images are used for Jobs and workspaces. + +## Publishing the IDE + +The IDE of each workspace is published on its own HTTPS host. +For the `ide.example.com` domain, the starter template creates an address like `https://ddp-ws-.ide.example.com`. + +Before starting, prepare a `*.ide.example.com` wildcard record that points to the ingress controller of the target cluster. +In `main.tf`, set: + +```hcl +ide_domain = "ide.example.com" +ingress_class = "nginx" +ide_tls_secret = "workspace-ide-tls" +ingress_annotations = { + "nginx.ingress.kubernetes.io/proxy-read-timeout" = "3600" + "nginx.ingress.kubernetes.io/proxy-send-timeout" = "3600" +} +``` + +Replace `nginx` with an existing IngressClass. +The `null` value selects the default class. +The `workspace-ide-tls` Secret must be located in the template namespace and contain a certificate for `*.ide.example.com` with a chain trusted by the browser. + +The annotations in the example are intended for ingress-nginx and increase timeouts for long-lived IDE connections. +For another controller, set the annotations it supports. + +The created Ingress routes traffic to the `gate` access check container, which admits a session opened through the portal. +Keep this route when changing the Ingress. +Publishing `code-server` directly bypasses the access check. + +If the ingress controller already issues a suitable default certificate, set `ide_tls_secret = null`. +Check that the browser trusts the certificate for the workspace host specifically. + +## Issuing a certificate with cert-manager + +If cert-manager is installed and a ClusterIssuer is configured, you can obtain a separate certificate for each workspace. +Replace the values in `main.tf`: + +```hcl +ide_domain = "ide.example.com" +ingress_class = "nginx" +ide_tls_secret = "${local.name}-ide-tls" +ingress_annotations = { + "cert-manager.io/cluster-issuer" = "letsencrypt-production" + "nginx.ingress.kubernetes.io/proxy-read-timeout" = "3600" + "nginx.ingress.kubernetes.io/proxy-send-timeout" = "3600" +} +``` + +Replace `letsencrypt-production` with your ClusterIssuer and ensure that the conditions for its domain validation are met. +After creating a workspace, wait for the certificate to be issued and check that the IDE opens through the portal. + +Cert-manager can keep the issued Secret after the workspace is deleted. +If certificate Secrets must be deleted automatically together with the Certificate, configure cert-manager with `--enable-certificate-owner-ref`; otherwise, include cleanup of such Secrets in your maintenance procedures. + +## Storing data + +The starter template creates a persistent volume with the `ReadWriteOnce` mode. +The repository is located in `/workspace/code`, and the agent state is in `/workspace/state`; both paths are on this volume. + +To select an existing StorageClass, replace the value in `main.tf`: + +```hcl +storage_class = "fast-ssd" +``` + +The `null` value uses the default StorageClass. +The size is set by the `storage_size` variable in `variables.tf`. +For an initial size of `20Gi` and selectable options, replace the existing block: + +```hcl +variable "storage_size" { + description = "Workspace volume size" + type = string + default = "20Gi" + + validation { + condition = contains(["20Gi", "50Gi", "100Gi"], var.storage_size) + error_message = "Select 20Gi, 50Gi, or 100Gi." + } +} +``` + +A new workspace gets the selected size. +Expanding an existing PVC depends on the StorageClass and cluster capabilities. +Do not reduce the size or change the class of an existing volume: the portal rejects an operation that requires deleting or replacing the volume. + +Stopping a workspace keeps the volume; deleting the workspace deletes its persistent data. +Also take into account the reclaim policy of the StorageClass itself. + +## Verifying the result + +After changing the template, test the draft in a new workspace: + +1. On the "Operations" tab, wait for OpenTofu to be applied successfully. +1. In "Diagnostics", check image pulling and the readiness of the containers and the persistent volume. +1. Click "Open IDE" and check the certificate and the terminal. +1. Create a file in the working directory, then stop and start the workspace again. The file must be preserved. + +After testing, publish and activate the version. +For existing workspaces, apply a version update. diff --git a/content/documentation/admin/workspaces/network-storage.ru.md b/content/documentation/admin/workspaces/network-storage.ru.md index 197acd03..700b56ff 100644 --- a/content/documentation/admin/workspaces/network-storage.ru.md +++ b/content/documentation/admin/workspaces/network-storage.ru.md @@ -4,17 +4,20 @@ description: Примеры настройки image pull secrets, отдель weight: 40 --- -Настройки образов, публикации IDE и постоянного тома находятся в `main.tf` стартового [шаблона рабочего пространства](templates/). Примеры меняют значения в существующем блоке `locals`; второй блок с теми же именами добавлять не требуется. +Настройки образов, публикации IDE и постоянного тома находятся в `main.tf` стартового [шаблона рабочего пространства](templates/). +Примеры меняют значения в существующем блоке `locals`; второй блок с теми же именами добавлять не требуется. ## Образы из закрытого хранилища -Чтобы под рабочего пространства скачивал закрытые образы, создайте в целевом неймспейсе Secret типа `kubernetes.io/dockerconfigjson`. Например, используя подготовленный Docker config без размещения пароля в командной строке: +Чтобы под рабочего пространства скачивал закрытые образы, создайте в целевом неймспейсе Secret типа `kubernetes.io/dockerconfigjson`. +Например, используя подготовленный Docker config без размещения пароля в командной строке: ```shell d8 k -n team-workspaces create secret generic workspace-registry --type=kubernetes.io/dockerconfigjson --from-file=.dockerconfigjson=/secure/path/config.json ``` -Замените `team-workspaces` на «Namespace» шаблона, а путь — на файл с доступом к нужному хранилищу образов. Учётная запись, выполняющая команду, должна иметь право создавать Secret в этом неймспейсе. +Замените `team-workspaces` на «Namespace» шаблона, а путь — на файл с доступом к нужному хранилищу образов. +Учётная запись, выполняющая команду, должна иметь право создавать Secret в этом неймспейсе. В `main.tf` замените значение: @@ -22,26 +25,33 @@ d8 k -n team-workspaces create secret generic workspace-registry --type=kubernet image_pull_secrets = ["workspace-registry"] ``` -Для нескольких хранилищ укажите несколько названий Secrets. Стартовый шаблон добавит их в `imagePullSecrets` пода, включая скачивание образа init-контейнера. +Для нескольких хранилищ укажите несколько названий Secrets. +Стартовый шаблон добавит их в `imagePullSecrets` пода, включая скачивание образа init-контейнера. -Сохраните, опубликуйте и активируйте шаблон, затем создайте пространство. В «Диагностике» проверьте, что под скачал образы и контейнеры перешли в готовое состояние. +Сохраните, опубликуйте и активируйте шаблон, затем создайте пространство. +В «Диагностике» проверьте, что под скачал образы и контейнеры перешли в готовое состояние. ### Secrets для Jobs операций -Jobs OpenTofu и поды рабочих пространств используют отдельные настройки скачивания образов. При установке модулем Jobs работают в `d8-development-platform`; дополнительные Secrets для них задаются в `spec.settings.imagePullSecrets` ModuleConfig: +Jobs OpenTofu и поды рабочих пространств используют отдельные настройки скачивания образов. +При установке модулем Jobs работают в `d8-development-platform`; дополнительные Secrets для них задаются в `spec.settings.imagePullSecrets` ModuleConfig: ```yaml imagePullSecrets: - operations-registry ``` -Secret `operations-registry` должен существовать в `d8-development-platform`. Эта настройка не создаёт Secret в целевом кластере и не заполняет `local.image_pull_secrets` шаблона. Подготовьте оба места, если закрытые образы используются для Jobs и рабочих пространств. +Secret `operations-registry` должен существовать в `d8-development-platform`. +Эта настройка не создаёт Secret в целевом кластере и не заполняет `local.image_pull_secrets` шаблона. +Подготовьте оба места, если закрытые образы используются для Jobs и рабочих пространств. ## Публикация IDE -IDE каждого рабочего пространства публикуется на собственном HTTPS-хосте. Для домена `ide.example.com` стартовый шаблон создаёт адрес вида `https://ddp-ws-<суффикс>.ide.example.com`. +IDE каждого рабочего пространства публикуется на собственном HTTPS-хосте. +Для домена `ide.example.com` стартовый шаблон создаёт адрес вида `https://ddp-ws-.ide.example.com`. -Перед запуском подготовьте wildcard-запись `*.ide.example.com`, которая указывает на ingress-контроллер целевого кластера. В `main.tf` задайте: +Перед запуском подготовьте wildcard-запись `*.ide.example.com`, которая указывает на ingress-контроллер целевого кластера. +В `main.tf` задайте: ```hcl ide_domain = "ide.example.com" @@ -53,17 +63,24 @@ ingress_annotations = { } ``` -Замените `nginx` на существующий IngressClass. Значение `null` выбирает класс по умолчанию. Secret `workspace-ide-tls` должен находиться в неймспейсе шаблона и содержать сертификат для `*.ide.example.com` с доверенной браузером цепочкой. +Замените `nginx` на существующий IngressClass. +Значение `null` выбирает класс по умолчанию. +Secret `workspace-ide-tls` должен находиться в неймспейсе шаблона и содержать сертификат для `*.ide.example.com` с доверенной браузером цепочкой. -Аннотации в примере предназначены для ingress-nginx и увеличивают тайм-ауты длительных соединений IDE. Для другого контроллера задайте поддерживаемые им аннотации. +Аннотации в примере предназначены для ingress-nginx и увеличивают тайм-ауты длительных соединений IDE. +Для другого контроллера задайте поддерживаемые им аннотации. -Созданный Ingress направляет трафик в контейнер проверки доступа `gate`, который пропускает сессию, открытую через портал. Сохраняйте этот маршрут при изменении Ingress. Публикация `code-server` напрямую обходит проверку доступа. +Созданный Ingress направляет трафик в контейнер проверки доступа `gate`, который пропускает сессию, открытую через портал. +Сохраняйте этот маршрут при изменении Ingress. +Публикация `code-server` напрямую обходит проверку доступа. -Если ingress-контроллер уже выдаёт подходящий сертификат по умолчанию, задайте `ide_tls_secret = null`. Проверьте, что браузер доверяет сертификату именно для хоста пространства. +Если ingress-контроллер уже выдаёт подходящий сертификат по умолчанию, задайте `ide_tls_secret = null`. +Проверьте, что браузер доверяет сертификату именно для хоста пространства. ## Выдача сертификата через cert-manager -При установленном cert-manager и настроенном ClusterIssuer можно получать отдельный сертификат для каждого пространства. Замените значения в `main.tf`: +При установленном cert-manager и настроенном ClusterIssuer можно получать отдельный сертификат для каждого пространства. +Замените значения в `main.tf`: ```hcl ide_domain = "ide.example.com" @@ -76,13 +93,16 @@ ingress_annotations = { } ``` -Замените `letsencrypt-production` на свой ClusterIssuer и обеспечьте условия его проверки домена. После создания пространства дождитесь выдачи сертификата и проверьте открытие IDE через портал. +Замените `letsencrypt-production` на свой ClusterIssuer и обеспечьте условия его проверки домена. +После создания пространства дождитесь выдачи сертификата и проверьте открытие IDE через портал. -Cert-manager может сохранять выпущенный Secret после удаления пространства. Если требуется автоматическое удаление сертификатных Secrets вместе с Certificate, настройте cert-manager с `--enable-certificate-owner-ref`; иначе включите очистку таких Secrets в процедуры обслуживания. +Cert-manager может сохранять выпущенный Secret после удаления пространства. +Если требуется автоматическое удаление сертификатных Secrets вместе с Certificate, настройте cert-manager с `--enable-certificate-owner-ref`; иначе включите очистку таких Secrets в процедуры обслуживания. ## Хранение данных -Стартовый шаблон создаёт постоянный том с режимом `ReadWriteOnce`. Репозиторий находится в `/workspace/code`, состояние агента — в `/workspace/state`; оба пути размещены на этом томе. +Стартовый шаблон создаёт постоянный том с режимом `ReadWriteOnce`. +Репозиторий находится в `/workspace/code`, состояние агента — в `/workspace/state`; оба пути размещены на этом томе. Для выбора существующего StorageClass замените значение в `main.tf`: @@ -90,7 +110,9 @@ Cert-manager может сохранять выпущенный Secret посл storage_class = "fast-ssd" ``` -Значение `null` использует StorageClass по умолчанию. Размер задаёт переменная `storage_size` в `variables.tf`. Для начального размера `20Gi` и вариантов выбора замените существующий блок: +Значение `null` использует StorageClass по умолчанию. +Размер задаёт переменная `storage_size` в `variables.tf`. +Для начального размера `20Gi` и вариантов выбора замените существующий блок: ```hcl variable "storage_size" { @@ -105,9 +127,12 @@ variable "storage_size" { } ``` -Новое пространство получит выбранный объём. Расширение существующего PVC зависит от StorageClass и возможностей кластера. Не уменьшайте объём и не меняйте класс существующего тома: операция, которая требует удаления или замены тома, отклоняется порталом. +Новое пространство получит выбранный объём. +Расширение существующего PVC зависит от StorageClass и возможностей кластера. +Не уменьшайте объём и не меняйте класс существующего тома, поскольку операция, которая требует удаления или замены тома, отклоняется порталом. -Остановка сохраняет том; удаление пространства удаляет его постоянные данные. Учитывайте также политику освобождения томов самого StorageClass. +Остановка сохраняет том; удаление пространства удаляет его постоянные данные. +Учитывайте также политику освобождения томов самого StorageClass. ## Проверка результата @@ -118,4 +143,5 @@ variable "storage_size" { 1. Нажмите «Открыть IDE» и проверьте сертификат и работу терминала. 1. Создайте файл в рабочей директории, остановите и снова запустите пространство. Файл должен сохраниться. -После проверки опубликуйте и активируйте версию. Для существующих пространств примените [обновление версии](../../user/workspaces/#обновление-шаблона). +После проверки опубликуйте и активируйте версию. +Для существующих пространств примените [обновление версии](../../user/workspaces/#обновление-шаблона). diff --git a/content/documentation/admin/workspaces/overview.md b/content/documentation/admin/workspaces/overview.md new file mode 100644 index 00000000..76b98762 --- /dev/null +++ b/content/documentation/admin/workspaces/overview.md @@ -0,0 +1,85 @@ +--- +title: Preparing workspaces +description: Kubernetes and Git connections, limits, network, storage, and permissions for DDP workspaces. +weight: 10 +--- + +Workspaces run an IDE and an AI agent in Kubernetes based on a workspace template. +The template defines objects in the target cluster; the portal manages creation, start, stop, update, and deletion. + +## Preparing the installation + +Before the first run, prepare the infrastructure and access: + +1. Create a Kubernetes [external service](../external-services/) and fill in the credentials for accessing the target cluster. + Prepare the target namespace. +1. Grant the credentials permissions for the template objects. + The default template creates a StatefulSet, Service, Ingress, PersistentVolumeClaim, ConfigMap, and Secret. + Diagnostics also reads Pods, their logs, and events; workspace management changes the number of StatefulSet replicas and connects to containers. +1. Prepare a storage class for the persistent volume. + The default template uses `ReadWriteOnce`; you can select the class [in the template files](network-storage/#storing-data). +1. Prepare a separate IDE domain, a wildcard DNS record, and TLS. + The IDE address of each workspace must be reachable from the user's browser. + For the setup procedure, see [the Ingress and TLS examples](network-storage/#publishing-the-ide). +1. Ensure that target Pods and operation Jobs can reach the portal HTTPS address with a trusted certificate. + It is used for the OpenTofu state, model requests, MCP, and IDE access checks. +1. If you use private container registries, prepare Secrets for pulling images [in the corresponding namespaces](network-storage/#images-from-a-private-registry). +1. For a template with a repository, create a Git connection and fill in the credentials. + Users will need an [AI provider](../../user/ai-assistant/#connecting-an-ai-provider). + +When DDP is installed with the `development-platform` module, OpenTofu operation Jobs run in the module namespace. +The workspace Pod, volume, and Ingress are created in the cluster and namespace selected in the template. +These locations can differ. + +## Installation limits + +Before creating the first workspace, save the limits in the "AI" → "Workspaces" → "Workspace templates" section, "Installation limits" block: + +| Field | Description | +| --- | --- | +| "Running workspaces per user" | Limits the number of simultaneously running workspaces of a single owner | +| "Running workspaces in total" | Limits the number of simultaneously running workspaces in the installation | + +Both values are integers greater than or equal to one. +Changing the limits requires `edit:workspace-policy`, viewing them requires `read:workspace-policy`. +Workspace creation is unavailable until the limits are saved. +Stopped workspaces do not count toward the running limit. + +## Selecting credentials + +By default, Kubernetes operations use the credentials of the workspace owner, and repository cloning uses the owner's Git token. +The credentials are filled in the user profile for the corresponding external service. + +On the "Connection" tab of the template, you can enable "Use a service account" and select an "Account" separately for Kubernetes and Git. +In this case, operations use the credentials of the selected user. + +The Git token of the selected account is available to the owner inside the workspace. +Select an account with access to the projects that this template is allowed to work with. + +## Granting access + +To allow a user to create workspaces, grant them `create:workspaces` and permission to use the template: the global `use:workspace-templates` or the object-level `use:workspace-template`. +Access to the "AI" section requires `view:ai-page`. + +Viewing, starting, stopping, and deleting are controlled by [workspace permissions](../security/rbac/#workspaces-and-templates). +Ownership grants permissions when the `owner-is-admin` setting is enabled. + +After the preparation, [create and activate a template](templates/), then follow the user procedure for creating a workspace. + +## Module parameters + +When DDP is installed with the module, you can override the backend address and operation Job resources. +Example of a ModuleConfig `spec.settings` fragment: + +```yaml +workspaces: + backendUrl: https://ddp.example.com + jobResources: + cpuMillicores: 500 + memoryBytes: 1073741824 + temporaryBytes: 134217728 +``` + +Without overrides, each Job uses the portal HTTPS address, `500` CPU millicores, `1` GiB of memory, and `128` MiB of temporary storage. +The CPU and memory values set the Job requests and limits. +Container resources of the workspace itself are set in the template. diff --git a/content/documentation/admin/workspaces/overview.ru.md b/content/documentation/admin/workspaces/overview.ru.md index 2c186eb9..18be558f 100644 --- a/content/documentation/admin/workspaces/overview.ru.md +++ b/content/documentation/admin/workspaces/overview.ru.md @@ -4,21 +4,32 @@ description: Подключения Kubernetes и Git, лимиты, сеть, weight: 10 --- -Рабочие пространства запускают IDE и AI-агента в Kubernetes по шаблону рабочего пространства. Шаблон задаёт объекты в целевом кластере; портал управляет созданием, запуском, остановкой, обновлением и удалением. +Рабочие пространства запускают IDE и AI-агента в Kubernetes по шаблону рабочего пространства. +Шаблон задаёт объекты в целевом кластере; портал управляет созданием, запуском, остановкой, обновлением и удалением. ## Подготовка установки Для первого запуска подготовьте инфраструктуру и доступы: -1. Создайте [внешний сервис](../external-services/) Kubernetes и заполните реквизиты доступа к целевому кластеру. Подготовьте целевой неймспейс. -1. Предоставьте реквизитам права на объекты шаблона. Штатный шаблон создаёт StatefulSet, Service, Ingress, PersistentVolumeClaim, ConfigMap и Secret. Диагностика также читает поды, их логи и события; управление пространством изменяет число реплик StatefulSet и подключается к контейнерам. -1. Подготовьте класс хранения для постоянного тома. Штатный шаблон использует `ReadWriteOnce`; класс можно выбрать [в файлах шаблона](network-storage/#хранение-данных). -1. Подготовьте отдельный домен IDE, wildcard-запись DNS и TLS. Адрес IDE каждого пространства должен быть доступен из браузера пользователя. Порядок настройки — [в примерах Ingress и TLS](network-storage/#публикация-ide). -1. Обеспечьте доступ из целевых подов и Jobs операций к HTTPS-адресу портала с доверенным сертификатом. Он используется для состояния OpenTofu, обращения к модели, MCP и проверки доступа в IDE. +1. Создайте [внешний сервис](../external-services/) Kubernetes и заполните реквизиты доступа к целевому кластеру. + Подготовьте целевой неймспейс. +1. Предоставьте реквизитам права на объекты шаблона. + Штатный шаблон создаёт StatefulSet, Service, Ingress, PersistentVolumeClaim, ConfigMap и Secret. + Диагностика также читает поды, их логи и события; управление пространством изменяет число реплик StatefulSet и подключается к контейнерам. +1. Подготовьте класс хранения для постоянного тома. + Штатный шаблон использует `ReadWriteOnce`; класс можно выбрать [в файлах шаблона](network-storage/#хранение-данных). +1. Подготовьте отдельный домен IDE, wildcard-запись DNS и TLS. + Адрес IDE каждого пространства должен быть доступен из браузера пользователя. + Порядок настройки — [в примерах Ingress и TLS](network-storage/#публикация-ide). +1. Обеспечьте доступ из целевых подов и Jobs операций к HTTPS-адресу портала с доверенным сертификатом. + Он используется для состояния OpenTofu, обращения к модели, MCP и проверки доступа в IDE. 1. Если используются закрытые хранилища образов, подготовьте Secrets для скачивания образов [в соответствующих неймспейсах](network-storage/#образы-из-закрытого-хранилища). -1. Для шаблона с репозиторием создайте подключение Git и заполните реквизиты. Пользователям потребуется [AI-провайдер](../../user/ai-assistant/#подключение-ai-провайдера). +1. Для шаблона с репозиторием создайте подключение Git и заполните реквизиты. + Пользователям потребуется [AI-провайдер](../../user/ai-assistant/#подключение-ai-провайдера). -При установке модулем `development-platform` Jobs операций OpenTofu выполняются в неймспейсе модуля. Под, том и Ingress рабочего пространства создаются в кластере и неймспейсе, выбранных в шаблоне. Эти места могут различаться. +При установке модулем `development-platform` Jobs операций OpenTofu выполняются в неймспейсе модуля. +Под, том и Ingress рабочего пространства создаются в кластере и неймспейсе, выбранных в шаблоне. +Эти места могут различаться. ## Лимиты установки @@ -29,27 +40,36 @@ weight: 10 | «Запущенных рабочих пространств на пользователя» | Ограничивает число одновременно запущенных пространств одного владельца | | «Запущенных рабочих пространств всего» | Ограничивает число одновременно запущенных пространств установки | -Оба значения — целые числа не меньше единицы. Для изменения требуется `edit:workspace-policy`, для просмотра — `read:workspace-policy`. Без сохранённых лимитов создание недоступно. Остановленные пространства не учитываются в лимите запущенных. +Оба значения — целые числа не меньше единицы. +Для изменения требуется `edit:workspace-policy`, для просмотра — `read:workspace-policy`. +Без сохранённых лимитов создание недоступно. +Остановленные пространства не учитываются в лимите запущенных. ## Выбор учётных данных -По умолчанию операции в Kubernetes используют реквизиты владельца рабочего пространства, а клонирование репозитория — его токен Git. Реквизиты заполняются в профиле для соответствующего внешнего сервиса. +По умолчанию операции в Kubernetes используют реквизиты владельца рабочего пространства, а клонирование репозитория — его токен Git. +Реквизиты заполняются в профиле для соответствующего внешнего сервиса. -На вкладке «Подключение» шаблона можно отдельно для Kubernetes и Git включить «Использовать сервисную учётную запись» и выбрать «Учётная запись». В этом случае операции используют реквизиты выбранного пользователя. +На вкладке «Подключение» шаблона можно отдельно для Kubernetes и Git включить «Использовать сервисную учётную запись» и выбрать «Учётная запись». +В этом случае операции используют реквизиты выбранного пользователя. -Токен Git выбранной учётной записи доступен владельцу внутри рабочего пространства. Выбирайте учётную запись с доступом к тем проектам, с которыми разрешена работа по этому шаблону. +Токен Git выбранной учётной записи доступен владельцу внутри рабочего пространства. +Выбирайте учётную запись с доступом к тем проектам, с которыми разрешена работа по этому шаблону. ## Выдача доступа -Для создания рабочих пространств выдайте пользователю `create:workspaces` и право использовать шаблон: глобальное `use:workspace-templates` или объектное `use:workspace-template`. Для перехода в раздел «AI» требуется `view:ai-page`. +Для создания рабочих пространств выдайте пользователю `create:workspaces` и право использовать шаблон: глобальное `use:workspace-templates` или объектное `use:workspace-template`. +Для перехода в раздел «AI» требуется `view:ai-page`. -Просмотр, запуск, остановка и удаление регулируются [разрешениями рабочих пространств](../security/rbac/#рабочие-пространства-и-шаблоны). Владение предоставляет права, когда включена настройка `owner-is-admin`. +Просмотр, запуск, остановка и удаление регулируются [разрешениями рабочих пространств](../security/rbac/#рабочие-пространства-и-шаблоны). +Владение предоставляет права, когда включена настройка `owner-is-admin`. После подготовки [создайте и активируйте шаблон](templates/), затем выполните [пользовательский сценарий создания](../../user/workspaces/#создание-рабочего-пространства). ## Параметры модуля -При установке модулем можно переопределить адрес backend и ресурсы Jobs операций. Пример фрагмента `spec.settings` ModuleConfig: +При установке модулем можно переопределить адрес backend и ресурсы Jobs операций. +Пример фрагмента `spec.settings` ModuleConfig: ```yaml workspaces: @@ -60,4 +80,6 @@ workspaces: temporaryBytes: 134217728 ``` -Без переопределения используется HTTPS-адрес портала, `500` millicores CPU, `1` ГиБ памяти и `128` МиБ временного хранилища на Job. Значения CPU и памяти задают requests и limits Jobs. Ресурсы контейнеров самого рабочего пространства задаются в шаблоне. +Без переопределения используется HTTPS-адрес портала, `500` millicores CPU, `1` ГиБ памяти и `128` МиБ временного хранилища на Job. +Значения CPU и памяти задают requests и limits Jobs. +Ресурсы контейнеров самого рабочего пространства задаются в шаблоне. diff --git a/content/documentation/admin/workspaces/sources.md b/content/documentation/admin/workspaces/sources.md new file mode 100644 index 00000000..3c36938e --- /dev/null +++ b/content/documentation/admin/workspaces/sources.md @@ -0,0 +1,104 @@ +--- +title: Templates from GitLab +description: Workspace template repository structure, GitLab source setup, version publishing, and archiving. +weight: 50 +--- + +A template source pulls OpenTofu projects from GitLab manually or on a schedule. +Changed files become a new published version of the template, which is activated immediately. +Files of such a template are edited in GitLab. + +## Preparing the repository + +Place each template in a separate immediate subdirectory of the selected directory. +For example, for the `workspace-templates` source path: + +```text +workspace-templates/ + go-development/ + versions.tf + main.tf + variables.tf + outputs.tf + files/ + AGENTS.md + scripts/ + start.sh + project-review/ + versions.tf + main.tf + variables.tf + outputs.tf + files/ + AGENTS.md +``` + +The template identifiers in the example are `go-development` and `project-review`. +An immediate subdirectory must contain a `.tf` file in its root; nested `files/` and `scripts/` belong to the same template. +Each project must return the [required `ddp_runtime` output](templates/#connecting-to-the-portal). + +To migrate a manual template, place its user files in GitLab with the same relative paths. +Do not add `ddp.tf`, `ddp.auto.tfvars.json`, the OpenTofu state, or `.terraform`, which the portal creates. + +In each project, set its own [IDE domain, Ingress, Secrets, and storage](network-storage/). +Identifiers of new templates must not be used by other templates in the portal. + +## Creating a source + +To connect a repository, prepare a GitLab external service and the credentials of a user with access to the repository. +Then follow these steps: + +1. Open "AI" → "Workspaces" → "Template sources" and click "Create source". +1. Specify the name, identifier, owner, and team. +1. On the "Repository" tab, select "GitLab external service", "Credentials user", "Project", "Branch or tag", and "Templates folder". +1. Specify the project as `group/project` or a numeric identifier, and the path as `workspace-templates`. + For the repository root, use `.`. +1. Select "Kubernetes service" and "Namespace" for new templates of this source. +1. On the "Synchronization" tab, set "Schedule (cron)" and enable "Enabled" if you need automatic synchronization. +1. Save the source and click "Sync now". +1. Open "Sync history" and check the result for each directory. + +New templates get the Kubernetes connection, namespace, owner, and team of the source. +For an existing template, these settings are changed separately; changing the source does not overwrite them. +Configure the Git connection for cloning the user project and the skills in the template itself. +The source repository and the repository the user works with serve different purposes. + +## Updating a version + +To publish a change, edit the files in GitLab, create a commit in the selected branch, and run synchronization or wait for the schedule. + +If the directory files have changed, the portal publishes a new version labeled with the first 12 characters of the commit SHA and activates it. +New workspaces are created from this version. +Existing workspaces stay on their previous versions until they are updated manually. + +A new version is not created if the files have not changed. +If an earlier template version was activated manually, note the "The active version is not the latest one from the repository" mark and check the active version after synchronization. + +A disabled source is synchronized only manually. +Files of a template managed by a source remain available for viewing and comparison in the portal. + +## Synchronization results + +The history shows the time, status, commit, and result for each directory: + +| Result | Description | +| --- | --- | +| "Created" | A new directory was found, and a template was created with a published version | +| "Updated" | The files changed, and a new version was published and activated | +| "No changes" | The files match the already published ones | +| "Archived" | The directory was removed from the repository | +| "Restored" | The directory was returned after being archived by the source | +| "Skipped" | The directory was not processed; check the specified reason | + +If an identifier conflicts with a manual template or a template of another source, the existing object is not overwritten. +If an error occurs, check the permissions in GitLab, the project, branch, path, file validity, and `ddp_runtime`, then run synchronization again. + +## Deleting a directory or source + +Deleting a directory from the selected branch archives the corresponding template. +Created workspaces and published versions are kept; new workspaces cannot be created from an archived template. +Returning the directory restores the template if it was archived by the source. + +To delete a source, archive its templates first. +After the source is deleted, they remain archived manual templates with their versions. +Data of existing workspaces is not deleted. diff --git a/content/documentation/admin/workspaces/sources.ru.md b/content/documentation/admin/workspaces/sources.ru.md index c5916948..13f4786b 100644 --- a/content/documentation/admin/workspaces/sources.ru.md +++ b/content/documentation/admin/workspaces/sources.ru.md @@ -4,11 +4,14 @@ description: Структура репозитория шаблонов рабо weight: 50 --- -Источник шаблонов забирает проекты OpenTofu из GitLab вручную или по расписанию. Изменённые файлы становятся новой опубликованной и сразу активной версией шаблона. Редактирование файлов такого шаблона выполняется в GitLab. +Источник шаблонов забирает проекты OpenTofu из GitLab вручную или по расписанию. +Изменённые файлы становятся новой опубликованной и сразу активной версией шаблона. +Редактирование файлов такого шаблона выполняется в GitLab. ## Подготовка репозитория -Разместите каждый шаблон в отдельной непосредственной поддиректории выбранной директории. Например, для пути источника `workspace-templates`: +Разместите каждый шаблон в отдельной непосредственной поддиректории выбранной директории. +Например, для пути источника `workspace-templates`: ```text workspace-templates/ @@ -30,36 +33,49 @@ workspace-templates/ AGENTS.md ``` -Идентификаторы шаблонов в примере — `go-development` и `project-review`. Непосредственная поддиректория должна содержать файл `.tf` в своём корне; вложенные `files/` и `scripts/` входят в тот же шаблон. Каждый проект должен возвращать [обязательный результат `ddp_runtime`](templates/#связь-с-порталом). +Идентификаторы шаблонов в примере — `go-development` и `project-review`. +Непосредственная поддиректория должна содержать файл `.tf` в своём корне; вложенные `files/` и `scripts/` входят в тот же шаблон. +Каждый проект должен возвращать [обязательный результат `ddp_runtime`](templates/#связь-с-порталом). -Чтобы перенести ручной шаблон, разместите в GitLab его пользовательские файлы с теми же относительными путями. Не добавляйте создаваемые порталом `ddp.tf`, `ddp.auto.tfvars.json`, состояние OpenTofu и `.terraform`. +Чтобы перенести ручной шаблон, разместите в GitLab его пользовательские файлы с теми же относительными путями. +Не добавляйте создаваемые порталом `ddp.tf`, `ddp.auto.tfvars.json`, состояние OpenTofu и `.terraform`. -Задайте в каждом проекте собственные [домен IDE, Ingress, Secrets и хранение](network-storage/). Идентификаторы новых шаблонов должны быть свободны в портале. +Задайте в каждом проекте собственные [домен IDE, Ingress, Secrets и хранение](network-storage/). +Идентификаторы новых шаблонов должны быть свободны в портале. ## Создание источника -Для подключения подготовьте внешний сервис GitLab и реквизиты пользователя с доступом к репозиторию. Затем выполните шаги: +Для подключения подготовьте внешний сервис GitLab и реквизиты пользователя с доступом к репозиторию. +Затем выполните шаги: 1. Откройте «AI» → «Рабочие пространства» → «Источники шаблонов» и нажмите «Создать источник». 1. Укажите название, идентификатор, владельца и команду. 1. На вкладке «Репозиторий» выберите «Внешний сервис GitLab», «Пользователь для реквизитов», «Проект», «Ветка или тег» и «Директория с шаблонами». -1. Укажите проект как `group/project` или числовой идентификатор, путь как `workspace-templates`. Для корня репозитория используйте `.`. +1. Укажите проект как `group/project` или числовой идентификатор, путь как `workspace-templates`. + Для корня репозитория используйте `.`. 1. Выберите «Сервис Kubernetes» и «Namespace» для новых шаблонов этого источника. 1. На вкладке «Синхронизация» задайте «Расписание (cron)» и включите «Включён», если нужна автоматическая синхронизация. 1. Сохраните источник и нажмите «Синхронизировать сейчас». 1. Откройте «История синхронизаций» и проверьте результат по каждой директории. -Новые шаблоны получают Kubernetes-подключение, неймспейс, владельца и команду источника. У уже созданного шаблона эти настройки меняются отдельно; изменение источника их не перезаписывает. Подключение Git для клонирования пользовательского проекта и навыки настройте в самом шаблоне. Репозиторий источника и репозиторий, с которым работает пользователь, выполняют разные задачи. +Новые шаблоны получают Kubernetes-подключение, неймспейс, владельца и команду источника. +У уже созданного шаблона эти настройки меняются отдельно; изменение источника их не перезаписывает. +Подключение Git для клонирования пользовательского проекта и навыки настройте в самом шаблоне. +Репозиторий источника и репозиторий, с которым работает пользователь, выполняют разные задачи. ## Обновление версии Для публикации изменения отредактируйте файлы в GitLab, создайте коммит в выбранной ветке и запустите синхронизацию либо дождитесь расписания. -Если файлы директории изменились, портал публикует новую версию с меткой из первых 12 символов SHA коммита и активирует её. Новые пространства создаются из этой версии. Существующие пространства остаются на прежних версиях до ручного обновления. +Если файлы директории изменились, портал публикует новую версию с меткой из первых 12 символов SHA коммита и активирует её. +Новые пространства создаются из этой версии. +Существующие пространства остаются на прежних версиях до ручного обновления. -Без изменения файлов новая версия не создаётся. Если вручную активирована более ранняя версия шаблона, учитывайте отметку «Активна не последняя версия из репозитория» и проверяйте активную версию после синхронизации. +Без изменения файлов новая версия не создаётся. +Если вручную активирована более ранняя версия шаблона, учитывайте отметку «Активна не последняя версия из репозитория» и проверяйте активную версию после синхронизации. -Выключенный источник синхронизируется только вручную. Файлы управляемого источником шаблона остаются доступны для просмотра и сравнения в портале. +Выключенный источник синхронизируется только вручную. +Файлы управляемого источником шаблона остаются доступны для просмотра и сравнения в портале. ## Результаты синхронизации @@ -74,10 +90,15 @@ workspace-templates/ | «Восстановлен» | Директория вернулась после архивирования источником | | «Пропущен» | Директория не обработана; проверьте указанную причину | -При конфликте идентификатора с ручным шаблоном или шаблоном другого источника существующий объект не перезаписывается. При ошибке проверьте права на GitLab, проект, ветку, путь, допустимость файлов и `ddp_runtime`, затем повторите синхронизацию. +При конфликте идентификатора с ручным шаблоном или шаблоном другого источника существующий объект не перезаписывается. +При ошибке проверьте права на GitLab, проект, ветку, путь, допустимость файлов и `ddp_runtime`, затем повторите синхронизацию. ## Удаление директории или источника -Удаление директории из выбранной ветки архивирует соответствующий шаблон. Созданные пространства и опубликованные версии сохраняются; новые пространства из архивного шаблона не создаются. Возвращение директории восстанавливает шаблон, если он был архивирован источником. +Удаление директории из выбранной ветки архивирует соответствующий шаблон. +Созданные пространства и опубликованные версии сохраняются; новые пространства из архивного шаблона не создаются. +Возвращение директории восстанавливает шаблон, если он был архивирован источником. -Для удаления источника сначала архивируйте его шаблоны. После удаления источника они остаются архивными ручными шаблонами со своими версиями. Данные существующих пространств не удаляются. +Для удаления источника сначала архивируйте его шаблоны. +После удаления источника они остаются архивными ручными шаблонами со своими версиями. +Данные существующих пространств не удаляются. diff --git a/content/documentation/admin/workspaces/templates.md b/content/documentation/admin/workspaces/templates.md new file mode 100644 index 00000000..ff3aeb2c --- /dev/null +++ b/content/documentation/admin/workspaces/templates.md @@ -0,0 +1,155 @@ +--- +title: Creating a template +description: Creating and editing a workspace template, creation form parameters, publishing, testing a draft, and activating a version. +weight: 20 +--- + +A workspace template is an OpenTofu project with a Kubernetes connection, Git settings, and a set of skills. +A new manual template contains a starter project with agent, IDE, and access check containers, a persistent volume, a Service, and an Ingress. + +## First template + +Before creating a template, [prepare workspaces](overview/). Then configure a manual template: + +1. Open "AI" → "Workspaces" → "Workspace templates" and click "Create template". +1. Specify a name and a unique identifier, for example, `team-development`. +1. On the "Connection" tab, select "Kubernetes connection" and "Namespace". + If necessary, select a service account. +1. To work with a project, enable "Initialize with a repository", select "Git connection", and set the HTTPS URL and branch. + If the user selects the project, enable "Allow overriding on creation". + For a workspace without Git, leave initialization disabled. +1. Save the template and open the "Files" tab. +1. In `main.tf`, set `local.ide_domain`, for example, `ide.example.com`, and check the [Ingress, TLS, image, and storage parameters](network-storage/). +1. Click "Save", then "Publish v1". +1. On the "Versions" tab, click "Activate v1". + +A user creates a new workspace from the active version. +A published version is immutable; the next change is made in a draft and published as a new version. + +## Starter project contents + +The files define Kubernetes objects and the contents of the working directory: + +| Path | Description | +| --- | --- | +| `versions.tf` | OpenTofu version, Kubernetes provider version and configuration | +| `main.tf` | StatefulSet, persistent volume, Secrets, ConfigMap, Service, Ingress, and file delivery settings | +| `variables.tf` | User parameters of the creation form | +| `outputs.tf` | Required `ddp_runtime` output | +| `files/` | Text files for the workspace working directory | +| `scripts/create.sh` | Optional initial setup of a new volume | +| `scripts/start.sh` | Optional setup on every start | + +The portal creates `ddp.tf` and `ddp.auto.tfvars.json` itself. +These paths, the `.terraform` directory, and variable names with the `ddp_` prefix are reserved. +Add your own variables without this prefix. + +## Creation form parameters + +A root module variable becomes a field of the workspace creation form. +In the editor, open `variables.tf` and add a variable: + +```hcl +variable "runtime_memory" { + description = "Agent container memory" + type = string + default = "2Gi" + + validation { + condition = contains(["2Gi", "4Gi", "8Gi"], var.runtime_memory) + error_message = "Select 2Gi, 4Gi, or 8Gi." + } +} +``` + +The default template already contains `runtime_memory`. Replace its block instead of adding a second one. +The value is used in `local.runtime_resources`. +After publishing, the form will offer a choice of memory size; if the user does not change it, they get `2Gi`. + +The form supports the `string`, `number`, `bool`, and `list(string)` types. +`description` becomes the field hint, and `default` becomes the initial value. +A variable without `default` is required. +A `contains([...], var.)` check defines the options to select from. +Other `validation` conditions are checked by OpenTofu during the operation. + +Example of a parameter with a list of Secret names: + +```hcl +variable "registry_secrets" { + description = "Secrets for pulling images in the target namespace" + type = list(string) + default = [] +} +``` + +For the value to affect the Pod, replace the corresponding line of the existing `locals` block in `main.tf`: + +```hcl +image_pull_secrets = var.registry_secrets +``` + +A parameter with `sensitive = true` is hidden in the interface. +Set Git and Kubernetes connection credentials through the template connections and accounts. + +## Testing and publishing changes + +To test changes before switching all new workspaces to them: + +1. Open the draft and change the files. +1. Save them. + If another user has changed the draft, refresh it and apply your changes again to the current revision. +1. Click "Check in a workspace". + The draft is available to users with permission to edit the template; before publishing, default parameter values are used. +1. Check the creation result, IDE, files, and commands in the test workspace. +1. Publish the version and compare it with the previous one using the "Compare" button. +1. Activate the required version on the "Versions" tab. + +Activation affects subsequent creations. +Existing workspaces stay on their versions until they are explicitly updated. +To return to the previous template for new creations, activate the previous published version. + +## Connecting to the portal + +`output "ddp_runtime"` is required in a template. The starter project returns: + +```hcl +output "ddp_runtime" { + value = { + statefulset = kubernetes_stateful_set_v1.runtime.metadata[0].name + namespace = var.ddp_namespace + container = "runtime" + engine_port = local.engine_port + ide_container = "ide" + ide_url = local.ide_url + work_directory = local.work_directory + } +} +``` + +The portal uses the StatefulSet to start and stop the workspace, the agent container and its port for jobs, and the `ide_url` address to open the IDE. +When changing the template, keep the output consistent with the objects actually created and with the IDE HTTPS address. + +## Skills and archiving + +On the "Skills" tab, select Deckhouse Development Portal (DDP) [skills](../ai-agents/skills/) and a pinned version or "Latest". +The set is fixed when the workspace is created and on every start. + +For a template with Git, the "Allow repository skills" toggle controls whether the skills of the working copy itself are available. +If it is disabled, the selected "Hidden skill folders" are excluded from the working copy on start. +This only limits file visibility; the files can still be read through Git. + +An archived template keeps its versions and existing workspaces, but you cannot create new workspaces from it. +To resume creation, use "Restore from archive". + +## File limits + +When editing, take the template limits into account: + +| Limit | Value | +| --- | --- | +| Number of files | Up to 256 | +| Size of a single file | Up to 1 MiB | +| Contents | UTF-8 text | +| Path | Relative, without empty segments, `.`, or `..` | + +For practical examples, see [file delivery and scripts](files/), [installing Go and other tools](tools/), [images, Ingress, and storage](network-storage/), and [synchronization from GitLab](sources/). diff --git a/content/documentation/admin/workspaces/templates.ru.md b/content/documentation/admin/workspaces/templates.ru.md index a93790f5..d7020f41 100644 --- a/content/documentation/admin/workspaces/templates.ru.md +++ b/content/documentation/admin/workspaces/templates.ru.md @@ -4,7 +4,8 @@ description: Создание и изменение шаблона рабоче weight: 20 --- -Шаблон рабочего пространства — проект OpenTofu с подключением Kubernetes, настройками Git и набором навыков. Новый ручной шаблон содержит стартовый проект с контейнерами агента, IDE и проверки доступа, постоянным томом, Service и Ingress. +Шаблон рабочего пространства — проект OpenTofu с подключением Kubernetes, настройками Git и набором навыков. +Новый ручной шаблон содержит стартовый проект с контейнерами агента, IDE и проверки доступа, постоянным томом, Service и Ingress. ## Первый шаблон @@ -12,14 +13,18 @@ weight: 20 1. Откройте «AI» → «Рабочие пространства» → «Шаблоны рабочих пространств» и нажмите «Создать шаблон». 1. Укажите название и уникальный идентификатор, например `team-development`. -1. На вкладке «Подключение» выберите «Подключение Kubernetes» и «Namespace». При необходимости выберите сервисную учётную запись. -1. Для работы с проектом включите «Инициализировать репозиторием», выберите «Подключение Git», задайте HTTPS URL и ветку. Если проект выбирает пользователь, включите «Разрешить переопределять при создании». Для пространства без Git оставьте инициализацию выключенной. +1. На вкладке «Подключение» выберите «Подключение Kubernetes» и «Namespace». + При необходимости выберите сервисную учётную запись. +1. Для работы с проектом включите «Инициализировать репозиторием», выберите «Подключение Git», задайте HTTPS URL и ветку. + Если проект выбирает пользователь, включите «Разрешить переопределять при создании». + Для пространства без Git оставьте инициализацию выключенной. 1. Сохраните шаблон и откройте вкладку «Файлы». 1. В `main.tf` задайте `local.ide_domain`, например `ide.example.com`, и проверьте [параметры Ingress, TLS, образов и хранения](network-storage/). 1. Нажмите «Сохранить», затем «Опубликовать v1». 1. На вкладке «Версии» нажмите «Активировать v1». -Пользователь создаёт новое рабочее пространство из активной версии. Опубликованная версия неизменяема; следующая правка выполняется в черновике и публикуется новой версией. +Пользователь создаёт новое рабочее пространство из активной версии. +Опубликованная версия неизменяема; следующая правка выполняется в черновике и публикуется новой версией. ## Состав стартового проекта @@ -35,11 +40,14 @@ weight: 20 | `scripts/create.sh` | Необязательная первоначальная настройка нового тома | | `scripts/start.sh` | Необязательная настройка при каждом запуске | -Портал создаёт `ddp.tf` и `ddp.auto.tfvars.json` самостоятельно. Эти пути, директория `.terraform` и имена переменных с префиксом `ddp_` зарезервированы. Добавляйте собственные переменные без этого префикса. +Портал создаёт `ddp.tf` и `ddp.auto.tfvars.json` самостоятельно. +Эти пути, директория `.terraform` и имена переменных с префиксом `ddp_` зарезервированы. +Добавляйте собственные переменные без этого префикса. ## Параметры формы создания -Переменная корневого модуля становится полем формы рабочего пространства. В редакторе откройте `variables.tf` и добавьте переменную: +Переменная корневого модуля становится полем формы рабочего пространства. +В редакторе откройте `variables.tf` и добавьте переменную: ```hcl variable "runtime_memory" { @@ -54,9 +62,15 @@ variable "runtime_memory" { } ``` -В штатном шаблоне `runtime_memory` уже существует: замените её блок вместо добавления второго. Значение используется в `local.runtime_resources`. После публикации в форме появится выбор объёма памяти; без изменения пользователь получит `2Gi`. +В штатном шаблоне `runtime_memory` уже существует. Замените её блок вместо добавления второго. +Значение используется в `local.runtime_resources`. +После публикации в форме появится выбор объёма памяти; без изменения пользователь получит `2Gi`. -Форма поддерживает типы `string`, `number`, `bool` и `list(string)`. `description` становится пояснением поля, `default` — начальным значением. Переменная без `default` обязательна. Проверка `contains([...], var.)` задаёт варианты выбора. Другие условия `validation` проверяются OpenTofu при операции. +Форма поддерживает типы `string`, `number`, `bool` и `list(string)`. +`description` становится пояснением поля, `default` — начальным значением. +Переменная без `default` обязательна. +Проверка `contains([...], var.)` задаёт варианты выбора. +Другие условия `validation` проверяются OpenTofu при операции. Пример параметра со списком названий Secrets: @@ -74,20 +88,25 @@ variable "registry_secrets" { image_pull_secrets = var.registry_secrets ``` -Параметр с `sensitive = true` скрывается в интерфейсе. Реквизиты подключения Git и Kubernetes задавайте через подключения и учётные записи шаблона. +Параметр с `sensitive = true` скрывается в интерфейсе. +Реквизиты подключения Git и Kubernetes задавайте через подключения и учётные записи шаблона. ## Проверка и публикация изменений Для проверки до переключения всех новых пространств: 1. Откройте черновик и измените файлы. -1. Сохраните их. Если черновик изменён другим пользователем, обновите его и повторно внесите свои изменения в актуальную ревизию. -1. Нажмите «Проверить в рабочем пространстве». Черновик доступен пользователям с правом редактирования шаблона; до публикации используются значения параметров по умолчанию. +1. Сохраните их. + Если черновик изменён другим пользователем, обновите его и повторно внесите свои изменения в актуальную ревизию. +1. Нажмите «Проверить в рабочем пространстве». + Черновик доступен пользователям с правом редактирования шаблона; до публикации используются значения параметров по умолчанию. 1. Проверьте результат создания, IDE, файлы и команды в тестовом рабочем пространстве. 1. Опубликуйте версию и сравните её с предыдущей кнопкой «Сравнить». 1. Активируйте нужную версию на вкладке «Версии». -Активация влияет на последующие создания. Существующие пространства остаются на своих версиях до [явного обновления](../../user/workspaces/#обновление-шаблона). Чтобы вернуть прежний шаблон для новых созданий, активируйте прежнюю опубликованную версию. +Активация влияет на последующие создания. +Существующие пространства остаются на своих версиях до [явного обновления](../../user/workspaces/#обновление-шаблона). +Чтобы вернуть прежний шаблон для новых созданий, активируйте прежнюю опубликованную версию. ## Связь с порталом @@ -107,15 +126,20 @@ output "ddp_runtime" { } ``` -Портал использует StatefulSet для запуска и остановки, контейнер агента и его порт для заданий, адрес `ide_url` для открытия IDE. Сохраняйте соответствие результата фактически созданным объектам и HTTPS-адресу IDE при изменении шаблона. +Портал использует StatefulSet для запуска и остановки, контейнер агента и его порт для заданий, адрес `ide_url` для открытия IDE. +Сохраняйте соответствие результата фактически созданным объектам и HTTPS-адресу IDE при изменении шаблона. ## Навыки и архивирование -На вкладке «Навыки» выберите [навыки DDP](../ai-agents/skills/) и закреплённую версию либо «Последняя». Набор фиксируется при создании и каждом запуске рабочего пространства. +На вкладке «Навыки» выберите [навыки](../ai-agents/skills/) Deckhouse Development Portal (DDP) и закреплённую версию либо «Последняя». +Набор фиксируется при создании и каждом запуске рабочего пространства. -Для шаблона с Git переключатель «Разрешить навыки из репозитория» задаёт доступность навыков самой рабочей копии. Если он выключен, выбранные «Скрытые директории навыков» исключаются из рабочей копии при запуске. Это ограничение видимости файлов; прочитать их через Git всё ещё возможно. +Для шаблона с Git переключатель «Разрешить навыки из репозитория» задаёт доступность навыков самой рабочей копии. +Если он выключен, выбранные «Скрытые директории навыков» исключаются из рабочей копии при запуске. +Это ограничение видимости файлов; прочитать их через Git всё ещё возможно. -Архивный шаблон сохраняет версии и существующие рабочие пространства, но новые пространства из него создавать нельзя. Для возобновления создания используйте «Вернуть из архива». +Архивный шаблон сохраняет версии и существующие рабочие пространства, но новые пространства из него создавать нельзя. +Для возобновления создания используйте «Вернуть из архива». ## Ограничения файлов diff --git a/content/documentation/admin/workspaces/tools.md b/content/documentation/admin/workspaces/tools.md new file mode 100644 index 00000000..c055c917 --- /dev/null +++ b/content/documentation/admin/workspaces/tools.md @@ -0,0 +1,161 @@ +--- +title: Development tools +description: Installing Go in a workspace with a template script, configuring PATH for the agent and IDE, and preserving tools across restarts. +weight: 35 +--- + +You can install development tools with template scripts on the workspace persistent volume. +The agent and IDE share this volume. +An installation in `/workspace/state` persists after a stop and start, and the project files remain in `/workspace/code`. + +The default containers run with UID/GID `10000` and a read-only root file system. +Select a tool distribution that can be extracted to a user directory without `sudo`, `apt`, or `apk`. + +## Installing Go + +The example installs Go `1.27.3` on Linux amd64 or arm64. +The version and SHA-256 checksums of the archives are fixed in the script; they are published [on the Go downloads page](https://go.dev/dl/). + +### Installation script + +Add the `scripts/start.sh` file with the following contents to the template draft. +If the file already contains setup commands, merge them with the example: + +```bash +#!/usr/bin/env bash +set -euo pipefail + +: "${DDP_STATE_DIR:?}" +go_version="1.27.3" + +case "$(uname -m)" in + x86_64) + go_arch="amd64" + go_checksum="65efbc80fdc1fa2cd2631cad5b481777a68e8725f34e89f50fc6ac714e379b40" + ;; + aarch64|arm64) + go_arch="arm64" + go_checksum="a06e99309dbcbdca1a8ccd2282c3ee146e55930886e26b4f1193269587165f49" + ;; + *) + printf 'Unsupported architecture: %s\n' "$(uname -m)" >&2 + exit 1 + ;; +esac + +toolchains_dir="${DDP_STATE_DIR}/toolchains" +go_directory="${toolchains_dir}/go${go_version}-linux-${go_arch}" +mkdir -p "$toolchains_dir" "${DDP_STATE_DIR}/tools" "${DDP_STATE_DIR}/tmp/go" + +if [ ! -d "$go_directory" ]; then + staging_dir="$(mktemp -d "${toolchains_dir}/.go-install.XXXXXX")" + trap 'rm -rf "$staging_dir"' EXIT + + curl -fsSL --retry 3 --connect-timeout 15 --max-time 300 "https://go.dev/dl/go${go_version}.linux-${go_arch}.tar.gz" -o "${staging_dir}/go.tar.gz" + printf '%s go.tar.gz\n' "$go_checksum" > "${staging_dir}/go.sha256" + (cd "$staging_dir" && sha256sum -c go.sha256) + tar -xzf "${staging_dir}/go.tar.gz" -C "$staging_dir" + mv "${staging_dir}/go" "$go_directory" + + rm -rf "$staging_dir" + trap - EXIT +fi + +ln -sfn "$go_directory" "${DDP_STATE_DIR}/tools/go" +"${DDP_STATE_DIR}/tools/go/bin/go" version +``` + +The script downloads and verifies the archive only if the selected version is missing on the volume. +The archive is extracted to a temporary directory on the same volume; the finished installation is moved to the version directory. +On subsequent starts, the saved copy is used. + +The `/workspace/state/tools/go` link points to the selected version. +As a result, the path in `PATH` stays the same when the version is updated. + +Use `start.sh` so that the example applies both to new workspaces and to existing ones after a template update. +`create.sh` is skipped if the initial volume setup has already succeeded. + +### Agent and IDE environment + +In `main.tf`, add the following fields to the existing `local.environment` block, keeping the other fields: + +```hcl +PATH = "${local.state_directory}/tools/go/bin:${local.state_directory}/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +GOPATH = "${local.state_directory}/go" +GOCACHE = "${local.state_directory}/cache/go-build" +GOTMPDIR = "${local.state_directory}/tmp/go" +CGO_ENABLED = "0" +``` + +The default template passes `local.environment` to the initial setup container, the agent, and the IDE. +Go and commands installed with `go install` will be available in all these containers. +The build cache and `GOPATH`, including the module cache, are located on the persistent volume. +`GOTMPDIR` moves temporary compilation files to the same volume so that the build does not fill the container's limited `/tmp`. + +Changing `PATH` with `export` inside `start.sh` affects only the script itself and its child processes. +Therefore, set the variables in `main.tf`. + +In the example, `CGO_ENABLED = "0"` disables the use of a C compiler. +This is suitable for Go projects without C dependencies; projects with CGo also require the corresponding compiler and system libraries. + +### Publishing and verification + +To run the example, the Pod needs HTTPS access to `go.dev` and to the download address after the redirect, usually `dl.google.com`. +Project dependencies also require access to the selected Go module proxy or repositories. +If direct access is blocked, host the same archive in internal storage and change the URL in the script, keeping the SHA-256 check. + +To apply the example: + +1. Save `scripts/start.sh` and `main.tf`, then publish and activate the version. +1. Create a new workspace, or stop an existing one, update its template version, and start it again. +1. In the `bootstrap` container log on the "Diagnostics" tab, check that the archive verification succeeded and that the `go version` line is present. +1. Open the IDE terminal and check the installation: + + ```shell + go version + go env GOPATH GOCACHE GOTMPDIR CGO_ENABLED + command -v go + ``` + +1. Ask the agent in the chat to run `go version`. It must see the same version as the IDE terminal. +1. Stop and start the workspace again. + Go must remain available; the same version is not downloaded again. + +### Verifying the build + +To check the compiler, create and run a program outside the project directory. +The example does not change `go.mod` or the project source files: + +```shell +mkdir -p /workspace/state/checks/go +cat > /workspace/state/checks/go/hello.go <<'EOF' +package main + +import "fmt" + +func main() { + fmt.Println("Go is ready") +} +EOF +go run /workspace/state/checks/go/hello.go +``` + +The expected output is `Go is ready`. +Then run the checks of the project itself, for example, `go test ./...` from its root directory. + +## Updating the tool version + +To update Go, change `go_version` and both archive checksums in `scripts/start.sh`. +Take the values [from the Go downloads page](https://go.dev/dl/), then save and publish a new template version. + +Stop the workspace, update the template, and start the workspace again. +The script installs the new version in a separate directory and switches the `tools/go` link. +The previous version remains on the volume; you can delete its directory from the terminal after checking the new version. + +## Installing other tools + +For other tools, use the same sequence: select an archive for the container architecture and system libraries, verify its checksum, extract it to the persistent volume, and add the executables to the template environment. + +Check compatibility separately in the agent and the IDE. +The default agent uses Alpine Linux with musl; it supports musl-compatible or statically linked binaries. +A matching processor architecture is not enough if the tool depends on system libraries. diff --git a/content/documentation/admin/workspaces/tools.ru.md b/content/documentation/admin/workspaces/tools.ru.md index e9904f6c..b1195745 100644 --- a/content/documentation/admin/workspaces/tools.ru.md +++ b/content/documentation/admin/workspaces/tools.ru.md @@ -4,17 +4,22 @@ description: Установка Go в рабочее пространство с weight: 35 --- -Инструменты разработки можно устанавливать скриптами шаблона на постоянный том рабочего пространства. Агент и IDE используют этот том совместно. Установка в `/workspace/state` сохраняется после остановки и запуска, а файлы проекта остаются в `/workspace/code`. +Инструменты разработки можно устанавливать скриптами шаблона на постоянный том рабочего пространства. +Агент и IDE используют этот том совместно. +Установка в `/workspace/state` сохраняется после остановки и запуска, а файлы проекта остаются в `/workspace/code`. -Штатные контейнеры работают с UID/GID `10000` и корневой файловой системой только для чтения. Выбирайте дистрибутив инструмента, который можно распаковать в пользовательскую директорию без `sudo`, `apt` или `apk`. +Штатные контейнеры работают с UID/GID `10000` и корневой файловой системой только для чтения. +Выбирайте дистрибутив инструмента, который можно распаковать в пользовательскую директорию без `sudo`, `apt` или `apk`. ## Установка Go -Пример устанавливает Go `1.27.3` на Linux amd64 или arm64. Версия и SHA-256 архивов зафиксированы в скрипте; они опубликованы [на странице загрузок Go](https://go.dev/dl/). +Пример устанавливает Go `1.27.3` на Linux amd64 или arm64. +Версия и SHA-256 архивов зафиксированы в скрипте; они опубликованы [на странице загрузок Go](https://go.dev/dl/). ### Скрипт установки -Добавьте в черновик шаблона файл `scripts/start.sh` со следующим содержимым. Если файл уже содержит команды настройки, объедините их с примером: +Добавьте в черновик шаблона файл `scripts/start.sh` со следующим содержимым. +Если файл уже содержит команды настройки, объедините их с примером: ```bash #!/usr/bin/env bash @@ -60,11 +65,15 @@ ln -sfn "$go_directory" "${DDP_STATE_DIR}/tools/go" "${DDP_STATE_DIR}/tools/go/bin/go" version ``` -Скрипт скачивает и проверяет архив только при отсутствии выбранной версии на томе. Распаковка выполняется во временной директории на том же томе; готовая установка переносится в директорию версии. При повторном запуске используется сохранённая копия. +Скрипт скачивает и проверяет архив только при отсутствии выбранной версии на томе. +Распаковка выполняется во временной директории на том же томе; готовая установка переносится в директорию версии. +При повторном запуске используется сохранённая копия. -Ссылка `/workspace/state/tools/go` указывает на выбранную версию. Благодаря этому при обновлении версии путь в `PATH` остаётся прежним. +Ссылка `/workspace/state/tools/go` указывает на выбранную версию. +Благодаря этому при обновлении версии путь в `PATH` остаётся прежним. -Используйте `start.sh`, чтобы пример применялся и к новым, и к уже созданным пространствам после обновления шаблона. `create.sh` пропускается, если первоначальная настройка тома уже успешно выполнялась. +Используйте `start.sh`, чтобы пример применялся и к новым, и к уже созданным пространствам после обновления шаблона. +`create.sh` пропускается, если первоначальная настройка тома уже успешно выполнялась. ### Окружение агента и IDE @@ -78,15 +87,22 @@ GOTMPDIR = "${local.state_directory}/tmp/go" CGO_ENABLED = "0" ``` -Штатный шаблон передаёт `local.environment` контейнеру первоначальной настройки, агенту и IDE. Go и команды, установленные через `go install`, будут доступны во всех этих контейнерах. Кеш сборки и `GOPATH`, включая кеш модулей, располагаются на постоянном томе. `GOTMPDIR` переносит временные файлы компиляции на тот же том, чтобы сборка не занимала ограниченный `/tmp` контейнера. +Штатный шаблон передаёт `local.environment` контейнеру первоначальной настройки, агенту и IDE. +Go и команды, установленные через `go install`, будут доступны во всех этих контейнерах. +Кеш сборки и `GOPATH`, включая кеш модулей, располагаются на постоянном томе. +`GOTMPDIR` переносит временные файлы компиляции на тот же том, чтобы сборка не занимала ограниченный `/tmp` контейнера. -Изменение `PATH` через `export` внутри `start.sh` действует только на сам скрипт и его дочерние процессы. Поэтому задавайте переменные в `main.tf`. +Изменение `PATH` через `export` внутри `start.sh` действует только на сам скрипт и его дочерние процессы. +Поэтому задавайте переменные в `main.tf`. -В примере `CGO_ENABLED = "0"` отключает использование C-компилятора. Он подходит для проектов на Go без зависимостей от C; для проектов с CGo также требуются соответствующий компилятор и системные библиотеки. +В примере `CGO_ENABLED = "0"` отключает использование C-компилятора. +Он подходит для проектов на Go без зависимостей от C; для проектов с CGo также требуются соответствующий компилятор и системные библиотеки. ### Публикация и проверка -Для запуска примера поду нужен HTTPS-доступ к `go.dev` и адресу загрузки после перенаправления, обычно `dl.google.com`. Для зависимостей проекта также нужен доступ к выбранному прокси Go-модулей или репозиториям. Если прямой доступ закрыт, разместите тот же архив во внутреннем хранилище и измените URL в скрипте, сохранив проверку SHA-256. +Для запуска примера поду нужен HTTPS-доступ к `go.dev` и адресу загрузки после перенаправления, обычно `dl.google.com`. +Для зависимостей проекта также нужен доступ к выбранному прокси Go-модулей или репозиториям. +Если прямой доступ закрыт, разместите тот же архив во внутреннем хранилище и измените URL в скрипте, сохранив проверку SHA-256. Чтобы применить пример: @@ -102,11 +118,13 @@ CGO_ENABLED = "0" ``` 1. Попросите агента в чате выполнить `go version`. Он должен увидеть ту же версию, что и терминал IDE. -1. Остановите и запустите пространство ещё раз. Go должен остаться доступным; повторное скачивание той же версии не требуется. +1. Остановите и запустите пространство ещё раз. + Go должен остаться доступным; повторное скачивание той же версии не требуется. ### Проверка сборки -Для проверки компилятора создайте и запустите программу вне директории проекта. Пример не меняет `go.mod` и исходные файлы проекта: +Для проверки компилятора создайте и запустите программу вне директории проекта. +Пример не меняет `go.mod` и исходные файлы проекта: ```shell mkdir -p /workspace/state/checks/go @@ -122,16 +140,22 @@ EOF go run /workspace/state/checks/go/hello.go ``` -Ожидаемый вывод — `Go is ready`. Затем выполните проверки самого проекта, например `go test ./...` из его корневой директории. +Ожидаемый вывод — `Go is ready`. +Затем выполните проверки самого проекта, например `go test ./...` из его корневой директории. ## Обновление версии инструмента -Для обновления Go измените `go_version` и обе контрольные суммы архивов в `scripts/start.sh`. Возьмите значения [со страницы загрузок Go](https://go.dev/dl/), сохраните и опубликуйте новую версию шаблона. +Для обновления Go измените `go_version` и обе контрольные суммы архивов в `scripts/start.sh`. +Возьмите значения [со страницы загрузок Go](https://go.dev/dl/), сохраните и опубликуйте новую версию шаблона. -Остановите пространство, обновите шаблон и снова запустите. Скрипт установит новую версию в отдельную директорию и переключит ссылку `tools/go`. Прежняя версия останется на томе; её директорию можно удалить из терминала после проверки новой версии. +Остановите пространство, обновите шаблон и снова запустите. +Скрипт установит новую версию в отдельную директорию и переключит ссылку `tools/go`. +Прежняя версия останется на томе; её директорию можно удалить из терминала после проверки новой версии. ## Установка других инструментов Для других инструментов используйте ту же последовательность: выберите архив под архитектуру и системные библиотеки контейнера, проверьте его контрольную сумму, распакуйте на постоянный том и добавьте исполняемые файлы в окружение шаблона. -Совместимость проверяйте отдельно в агенте и IDE. Штатный агент использует Alpine Linux с musl; для него подходят совместимые с musl или статически скомпонованные бинарные файлы. Совпадения архитектуры процессора недостаточно, если инструмент зависит от системных библиотек. +Совместимость проверяйте отдельно в агенте и IDE. +Штатный агент использует Alpine Linux с musl; для него подходят совместимые с musl или статически скомпонованные бинарные файлы. +Совпадения архитектуры процессора недостаточно, если инструмент зависит от системных библиотек. diff --git a/content/documentation/user/home/overview.ru.md b/content/documentation/user/home/overview.ru.md index acf32ad4..4ed9ab02 100644 --- a/content/documentation/user/home/overview.ru.md +++ b/content/documentation/user/home/overview.ru.md @@ -96,4 +96,4 @@ description: Главная страница DDP — разделы и нави Пользователи с разрешением `update:home-mapping-sets` видят в нижней части бокового меню переключатель «Настроить маппинг». Когда переключатель включён, рядом с разделами появляется значок настройки правил маппинга раздела. -Порядок настройки описан в разделе [«Правила маппинга»](../../admin/home/mapping/#настройка-маппинга-с-главной). +Порядок настройки описан в разделе [«Правила маппинга»](../../admin/home/mapping/#настройка-маппинга-с-главной-страницы). diff --git a/content/documentation/user/templating.md b/content/documentation/user/templating.md index 1c4d6e5b..765f6469 100644 --- a/content/documentation/user/templating.md +++ b/content/documentation/user/templating.md @@ -303,7 +303,6 @@ Returns: Example in a template: ```go-text-template -{{ encodeUnicode "Привет" }} // Output: "\u041f\u0440\u0438\u0432\u0435\u0442" {{ encodeUnicode "Hello" }} // Output: "\u0048\u0065\u006c\u006c\u006f" ``` @@ -323,7 +322,6 @@ Returns: Example in a template: ```go-text-template -{{ decodeUnicode "\u041f\u0440\u0438\u0432\u0435\u0442" }} // Output: "Привет" {{ decodeUnicode "\u0048\u0065\u006c\u006c\u006f" }} // Output: "Hello" ```