Skip to main content
Altcraft Docs LogoAltcraft Docs Logo
User guide iconUser guide
Developer guide iconDeveloper guide
Admin guide iconAdmin guide
English
  • Русский
  • English
Login
    Getting StartedAdministrator documentationFunctional characteristics
      Technology descriptionarrow
    • Architecture OverviewComponent Description
        Deployment schemesarrow
      • Basic schemeFail-safe schemeTypical Placement in Infrastructure
    System requirements
      Admin Panelarrow
      • Account areaarrow
        • Accountsarrow
        • Account UsersAccount Virtual SendersAccount Database Indexes
        TariffsExternal data configurationLDAPTasksSchedule JobsGlobal Stop ListsWebversion Store Policies
        Settingsarrow
      • Databases
          Accessarrow
        • AdminsAPI tokens
        Notifiers
          MTAarrow
        • Default rulesRetry rulesLock rulesBounce patternsStrategiesKeysISPsPools
      Nodes
        Sendersarrow
      • EmailSMSEvent generatorIntegration with SendsayENS: настройка сендера
        Reportsarrow
      • Audit JournalData Usage
        Toolsarrow
      • ARF decoderURL decoderSMID decoderLicense
      Platform installationarrow
    • Automatic installationManual installationRunning the platform in a Docker container
      Platform configurationarrow
    • Configuration fileDomain settingsLDAP access configurationSending Email via SMTP relayPixel and push domain configurationCluster and Replication SetupSystem notifications configurationProcesses UNIX sockets configurationHTTPS ConfigurationMigrating from MongoDB Community Edition to Percona Server for MongoDBAdding sender IP addressesDeduplication request settingsPostgreSQL database for account dataProxy server settingsKeycloak Integration with AltcraftGetting HTTP service statusesConfiguration MongoDB logs rotation
        Configuration of system constants and directoriesarrow
      • Filtering bot actionsDirectory of gender markers
      Platform maintenancearrow
    • Personnel requirementsPlatform maintenance processesPlatform updatingPlatform service monitoringBackup and recoveryTransferring the platform to a new serverCreating, deleting, and populating tables for statistics in ClickHouseUsage of the aktool utilityUsers and directories engaged by the platform
      Custom channels guidearrow
    • OverviewCreating and configuring a channelEntity field configurationTemplate languageEntities
        Pipesarrow
      • Pipe: Basic ConceptsResultErrorsLogPackUnpackHTTP RequestStore SetStore GetSelectorSQLEventerScheduler
        Pipelinesarrow
      • Pipeline: Basic ConceptsMessageScheduleListenerModerateStop
      Extraarrow
    • System page customizationSend Message IDИнструкция по миграции истории в ClickHouseInstructions for migrating history to ClickHouseUtility for importing push subscriptions to Firebase projectUtility for importing push subscriptions to Firebase project
    Processing HTTP/HTTPS traffic
      Administrator APIarrow
      • Accounts admin apiarrow
        • Restricted accessarrow
        • Account Activation and DeactivationAccount Freeze and Unfreeze
        Get accounts listAdd a new accountDelete the account
        Account usersarrow
      • Update an Existing AccountAdd a new accountDelete a userGet a list of usersSending a Welcome Email
        Nodesarrow
      • Synchronize node MTA configurationGet nodes listGet node MTA statusActivate node MTADeactivate node MTA
        Senders admin apiarrow
      • Create or update AKMTA senderGet AKMTA sender informationAssign account to senderGet senders listDelete senderRestore sender
          Sender queuearrow
        • Get sender queue informationHold sender queueRelease sender queueClear sender queue
        Virtual sendersarrow
      • Get virtual senders listGet virtual sender informationCreate virtual senderUpdate virtual senderClone virtual senderDelete virtual sender
    Documentation Archive
  • Extra
  • Инструкция по миграции истории в ClickHouse

Инструкция по миграции истории в ClickHouse

Шаг 1. Установить СУБД ClickHouse, следуя официальным инструкциям.

note

Минимальная требуемая версия для работы платформы >24.8.

Шаг 2. Создать нового пользователя /etc/clickhouse-server/users.d/altcraft.xml (подробнее см. в документации — Настройки пользователей).

<yandex>
<users>
<altcraft>
<password>abcdefghiasdwqedwqjklmnopqrstuvwxyzABCDEF</password>
<networks>
<ip>::/0</ip>
</networks>
<profile>default</profile>
<quota>default</quota>
<allow_databases>
<database>altcraft_system</database>
</allow_databases>
</altcraft>
</users>
</yandex>
caution

В качестве пароля используется набор из символов "abcdefghiasdwqedwqjklmnopqrstuvwxyzABCDEF".
Обязательно сгенерируйте более сложный пароль, состоящий из не менее 32-х символов.

Шаг 3. Включить опцию input_format_import_nested_json для вставки данных JSON с вложенными объектами (подробнее см. в документации — Профили настроек).

<?xml version="1.0"?>
<yandex>
<!-- Profiles of settings. -->
<profiles>
<!-- Default settings. -->
<default>
<!-- Maximum memory usage for processing single query, in bytes. -->
<max_memory_usage>8589934592</max_memory_usage>
<max_memory_usage_for_user>8589934592</max_memory_usage_for_user>
<max_bytes_before_external_group_by>4294967296</max_bytes_before_external_group_by>
<max_bytes_before_external_sort>4294967296</max_bytes_before_external_sort>
<receive_timeout>3600</receive_timeout>
<send_timeout>3600</send_timeout>
<max_threads>2</max_threads>
<max_partitions_per_insert_block>10000</max_partitions_per_insert_block>
<!-- Use cache of uncompressed blocks of data. Meaningful only for processing many of very short queries. -->
<use_uncompressed_cache>0</use_uncompressed_cache>

<!-- How to choose between replicas during distributed query processing.
random - choose random replica from set of replicas with minimum number of errors
nearest_hostname - from set of replicas with minimum number of errors, choose replica
with minimum number of different symbols between replica's hostname and local hostname
(Hamming distance).
in_order - first live replica is chosen in specified order.
first_or_random - if first replica one has higher number of errors, pick a random one from replicas with minimum number of errors.
-->
<load_balancing>random</load_balancing>
<input_format_import_nested_json>1</input_format_import_nested_json>
</default>

Шаг 4. В главном файле конфигурации main.json настроить параметры для подключения и работы с СУБД ClickHouse.

"CLICKHOUSE_SYSTEM": {
"HOST": "localhost",
"PORT": 9000,
"USER": "altcraft",
"MAX_CONNECTION": 100,
"CONN_TIMEOUT": 15,
"PASSWORD": "abcdefghiasdwqedwqjklmnopqrstuvwxyzABCDEF",
"IS_DEBUG": false
},

Шаг 5. Запустить миграцию. Для этих целей подготовлена специальная утилита — actions_migrate. Полный список доступных параметров:

ПараметрЗначение по умолчаниюОписание
--accounts stringВсе активные аккаунтыСписок аккаунтов для импорта с разделителем через запятую
Пример: "1, 2, 3"
--appname boolfalseПоказать дополнительную информацию об утилите
--batch_timeout int5Время в секундах, по истечению которого будет выполнена вставка
--ch_batch int100000Минимальный батч событий для вставки
--ch_debug boolfalseВключить дополнительный уровень логирования
--ch_host stringИспользуется главная конфигурация main.jsonХост для подключения
--ch_password stringИспользуется главная конфигурация main.jsonПароль для подключения
--ch_port intИспользуется главная конфигурация main.jsonПорт для подключения
--ch_user stringИспользуется главная конфигурация main.jsonПользователь для подключения
--config string/opt/MarketingPlatform/config/main.jsonПуть до файла главной конфигурации main.json
--exclude string""Список аккаунтов для исключения из импорта с разделителем через запятую
Пример: "1, 2, 3"
--level_log stringINFOУровень логирования: TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL, FATAL
--log_path string./actions_migrate.logМесторасположение лог-файла
--range string""Временной диапазон для выборки существующей истории
Формат — "MM.YY-MM.YY", "-MM.YY", "MM.YY-"
--rmq boolfalseДополнительная опция для вставки через RabbitMQ
--version boolfalseПоказать версию утилиты
--worker_size int-1Количество воркеров (по умолчанию соответствует количеству vCPU).

tip

Миграция может занять продолжительное время, до 3-х и более дней. Для продолжения миграции после отключения от сервера можно воспользоваться утилитой screen для работы в отдельной сессии, пример использования screen — https://access.redhat.com/articles/5247.

Пример переноса всех исторических данных по сентябрь 2021 года:

    
/opt/akd/ak/bin/actions_migrate --accounts "1" --config "/opt/akd/config/main.json" --batch_timeout 60 --ch_batch 500000 --range "-09.21"

Пример переноса всех исторических данных за ноябрь 2021 года:

    
/opt/akd/ak/bin/actions_migrate --accounts "1" --config "/opt/akd/config/main.json" --batch_timeout 60 --ch_batch 500000 --range "11.21-11.21"

Пример переноса всех исторических данных с января 2021 года по текущий момент:

    
/opt/akd/ak/bin/actions_migrate --accounts "1" --config "/opt/akd/config/main.json" --batch_timeout 60 --ch_batch 500000 --range "01.21-"

Last updated on Mar 12, 2026
Previous
Send Message ID
Next
Instructions for migrating history to ClickHouse
© 2015 - 2026 Altcraft, LLC. All rights reserved.