G.1. pgpro_datactl — управление файлами данных Postgres Pro Enterprise

G.1.1. Обзор

Утилита pgpro_datactl предоставляет инструменты для управления файлами данных Postgres Pro Enterprise и включает в себя модуль для работы с CFS (Compressed File Storage, сжатая файловая система). Этот модуль предлагает следующую функциональность:

  • Получение метаданных сжатых файлов, включая алгоритм сжатия и их расположение.

  • Распаковка файлов CFS для дальнейшего анализа.

  • Перепаковка сжатых файлов и изменение их уровня сжатия.

  • Предотвращение потенциальных сбоев, вызванных повреждёнными файлами.

G.1.2. Установка

pgpro_datactl поставляется вместе с Postgres Pro Enterprise в виде отдельного пакета pgpro-datactl-ent-13 (подробные инструкции по установке приведены в Главе 17).

G.1.3. Команды

pgpro_datactl поддерживает следующие команды:

G.1.3.1. Важные замечания

Перед запуском этих команд ознакомьтесь со следующими особенностями их работы:

  • Операции repack и unpack требуют остановки кластера Postgres Pro Enterprise. Это необходимо для того, чтобы избежать повреждения данных и обеспечить целостность файлов.

  • При использовании параметра --in-place с командой repack следует учитывать следующее:

    • Табличное пространство будет перезаписано непосредственно в процессе работы.

    • Все существующие данные в целевом табличном пространстве будут заменены.

G.1.3.2. unpack

pgpro_datactl unpack --source=исходный_путь --target=целевой_путь
[--calg=алгоритм_сжатия] [--zero-on-error] [--log-level=уровень_сообщений] [--help]

Распаковывает файлы CFS.

-s=исходный_путь
--source=исходный_путь

Указывает путь к сжатому файлу или каталогу.

Примечание

Путь должен находиться в каталоге с именем PG_версия_дата, содержащем файл pg_compression.

-t=целевой_путь
--target=целевой_путь

Указывает путь к каталогу, в который будут помещены распакованные файлы.

Если исходный и целевой каталоги совпадают, файлы распаковываются с расширением .dec.

-c=алгоритм_сжатия
--calg=алгоритм_сжатия

Указывает используемый алгоритм сжатия. Если параметр не указан, команда unpack возьмёт это значение из файла pg_compression.

--zero-on-error

При указании этого параметра все повреждённые блоки заменяются нулями, что предотвращает аварийное завершение процесса или появление сообщений об ошибках.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

Пример:

pgpro_datactl unpack -s /path/to/archive.cfs -t /path/to/destination -c zstd

В этом примере unpack извлекает файл archive.cfs, сжатый алгоритмом zstd, в каталог /path/to/destination.

G.1.3.3. probe

pgpro_datactl probe --source=исходный_путь [--log-level=уровень_сообщений] [--help]

Анализирует указанный файл и определяет следующее:

  • Тип сжатия. Алгоритм сжатия zlib или zstd.

  • Уровень фрагментации. Анализирует соответствующий файл *.cfm (при его наличии) и сообщает процент неиспользуемого пространства в физическом файле.

  • Принадлежность файла к CFS. Проверяет наличие связанного файла *.cfm, что указывает на принадлежность файла к архиву CFS.

-s=исходный_путь
--source=исходный_путь

Указывает путь к нужному файлу.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

Пример вывода:

Probing path: /data/sample.dat
Has cfm file: Yes
pg_compression: zstd
Actual compression: zstd
Fragmentation: 5%

В этом примере файл сжат алгоритмом zstd, является частью архива CFS и имеет уровень фрагментации пять процентов.

G.1.3.4. info

pgpro_datactl info --source=исходный_путь [--log-level=уровень_сообщений] [--help]

Анализирует файл и отображает следующую информацию:

  • Физический и виртуальный размер файла, а также используемое им пространство в байтах.

  • Включён ли сборщик мусора (GC).

  • Наличие и доступность файла *.cfm.

-s=исходный_путь
--source=исходный_путь

Указывает путь к нужному файлу.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

Пример вывода:

Physical size: 10485760
Virtual size: 9437184
Used size: 7864320
GC active: Yes

G.1.3.5. repack

pgpro_datactl repack --source=исходный_путь --t-calg=целевой_алгоритм_сжатия --target=целевой_путь
[--calg=алгоритм_сжатия] [--clevel=уровень_сжатия]
[--zero-on-error] [--log-level=уровень_сообщений] [--help]

Меняет алгоритм сжатия и/или уровень сжатия файлов CFS.

Возвращает следующую информацию:

  • Идентификатор алгоритма сжатия

  • Уровень сжатия

  • Результат копирования: 1 (завершено) или 0 (не завершено).

Если операция была прервана, при повторном выполнении команды с теми же параметрами сжатия (значения --t-calg и --calg) перепаковка продолжится с момента прерывания благодаря наличию соответствующего каждому файлу данных файла .status.

-s=исходный_путь
--source=исходный_путь

Указывает путь к сжатому файлу или каталогу.

Примечание

Путь должен находиться в каталоге с именем PG_версия_дата, содержащем файл pg_compression.

--t-calg=целевой_алгоритм_сжатия

Указывает целевой алгоритм сжатия. Если параметр опущен, файлы будут распакованы.

-t=целевой_путь
--target=целевой_путь

Указывает путь к каталогу для перепакованных файлов.

-c=алгоритм_сжатия
--calg=алгоритм_сжатия

Указывает текущий алгоритм сжатия. Если параметр не указан, команда repack возьмёт это значение из файла pg_compression.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

--clevel=уровень_сжатия

Определяет уровень сжатия для выбранного алгоритма. Значение по умолчанию — 1.

--zero-on-error

При указании этого параметра все повреждённые блоки заменяются нулями, что предотвращает аварийное завершение процесса или появление сообщений об ошибках.

--in-place

Если указать этот параметр без целевого_пути, перепакованные файлы будут размещены в исходном каталоге.

Предупреждение

При использовании этого параметра все исходные файлы будут удалены из исходного каталога, поэтому применяйте его с осторожностью.

G.1.3.6. ground

pgpro_datactl ground --source=исходный_путь --block-num=номер_блока
[--calg=алгоритм_сжатия] [--log-level=уровень_сообщений] [--help]

Заменяет нулями указанные повреждённые блоки, которые могут появиться при распаковке.

-s=исходный_путь
--source=исходный_путь

Указывает путь к нужному файлу.

--block-num=номер_блока

Указывает номер блока, который нужно заменить.

-c=алгоритм_сжатия
--calg=алгоритм_сжатия

Определяет текущий алгоритм сжатия. Если значение не соответствует алгоритму сжатия табличного пространства CFS, операция завершится ошибкой.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

Пример:

pgpro_datactl ground -s /path/to/archive.cfs --block-num 4 --calg pglz

В этом примере команда ground заменяет блок номер 4 нулём и использует алгоритм pglz для его сжатия.

G.1.3.7. stat

pgpro_datactl stat --source=исходный_путь --cfs
[--log-level=уровень_сообщений] [--help]

Собирает статистику табличного пространства и выводит результат в виде CSV-файла.

Эта команда не вносит изменений в файлы (режим только для чтения). Блокировки не устанавливаются.

-s=исходный_путь
--source=исходный_путь

Указывает путь к сжатому файлу или каталогу.

Примечание

Путь должен находиться в каталоге с именем PG_версия_дата, содержащем файл pg_compression.

--cfs

Указывает тип табличного пространства.

Примечание

В настоящее время реализована поддержка только типа CFS.

--log-level=уровень_сообщений

Устанавливает уровень сообщений. Возможные значения: debug, info, warning и error.

G.1.4. Коды ошибок pgpro_datactl

В Таблице G.1 показаны диапазоны кодов ошибок утилиты pgpro_datactl.

Согласно стандарту SQL, первые два символа кода ошибки обозначают класс ошибок, а последние три — определённое условие в этом классе.

Таблица G.1. Диапазоны кодов ошибок pgpro_datactl

Код ошибкиУсловие
00XXXУспех
10XXXПредупреждение
20XXXОшибка командной строки
30XXXОшибка базы данных
40XXXОшибка исходных данных
50XXXОшибка целевых данных
60XXXОшибка файловой системы/ввода-вывода
70XXXОшибка времени выполнения

В Таблице G.2 перечислены все конкретные коды ошибок и действия, которые следует выполнить при их возникновении.

В утилите pgpro_datactl используется формат PRODCTL-XXXXX. Предупреждения возвращают ненулевой код выхода, но работа продолжается. Ошибки приводят к остановке текущей операции.

Таблица G.2. Коды ошибок pgpro_datactl

Код ошибкиСообщениеПричинаДействие
PRODCTL-00000УспехОперация успешно завершена.Никаких действий не требуется.
PRODCTL-10001File not found.Отсутствует необязательный входной файл.Проверьте путь. Если отсутствие файла ожидаемо, предупреждение можно игнорировать.
PRODCTL-10002Failed to read file.Частичное чтение, ошибка прав доступа или временная проблема ввода-вывода.Повторите операцию. Проверьте права доступа пользователя и состояние диска.
PRODCTL-10003Invalid parameter.Неверное значение или формат некритического аргумента.Введите допустимое значение, иначе будет применено значение по умолчанию.
PRODCTL-10004Failed to allocate memory.Нехватка памяти в системе на некритическом этапе.Уменьшите параллелизм или размер данных.
PRODCTL-10005Failed to create working directory.Не удалось определить текущий или рабочий каталог.Проверьте путь, права доступа и свободное место на диске.
PRODCTL-10006File contains invalid content.Необязательный файл не прошёл проверку.Замените или пропустите файл.
PRODCTL-10007Failed to remove file.Файл заблокирован, или отсутствуют права доступа.Закройте все дескрипторы файла и настройте права доступа.
PRODCTL-10008Parameter required but not set.Для необязательной подзадачи не предоставлено обязательное значение, поэтому использовано значение по умолчанию.Укажите отсутствующий параметр, чтобы не использовать резервный вариант.
PRODCTL-20001Required parameter is missing.Отсутствует обязательный параметр командной строки.Добавьте необходимый параметр и перезапустите команду.
PRODCTL-20002Invalid parameter.У параметра командной строки недопустимое значение.Укажите корректное значение согласно документации.
PRODCTL-30001Database connection failed.Возникла ошибка сети, аутентификации или DSN.Проверьте аутентификацию, сетевое соединение и конфигурацию SSL.
PRODCTL-30002Database query failed.Ошибка SQL, тайм-аут или проблема прав доступа.Проверьте SQL и журналы. Поправьте схему или права доступа.
PRODCTL-40001Failed to read source file.Ошибка ввода-вывода входных данных.Убедитесь, что путь существует и пользователь имеет к нему доступ. Повторите попытку.
PRODCTL-40002Source file not found.Требуемый входной файл отсутствует.Укажите верный файл или исправьте путь.
PRODCTL-40003Failed to construct source path.Некорректный корневой путь, переменная окружения или шаблон.Исправьте конфигурацию и шаблон пути.
PRODCTL-40004File contains invalid content.Ошибка проверки обязательных входных данные или несоответствие контрольной суммы.Замените файл или исправьте его формат.
PRODCTL-50001Target file write failed.Ошибка прав доступа, дисковой квоты или диска.Освободите место на диске, исправьте права доступа и повторите попытку.
PRODCTL-50002Target file not found.Отсутствует ожидаемый выходной путь или родительский каталог.Создайте необходимые каталоги, проверьте целевой путь.
PRODCTL-60001File remove failed.Доступ запрещён, или файл используется.Снимите все блокировки с файла, настройте права доступа.
PRODCTL-60002Open file failed.Файл не найден, или доступ был запрещён.Убедитесь, что файл существует, проверьте права доступа.
PRODCTL-60003Open stream failed.Канал, сокет или файловый дескриптор недоступен.Проверьте конечную точку и права доступа.
PRODCTL-60004File write failed.Досрочное завершение записи или общая ошибка ввода-вывода.Повторите попытку. Проверьте состояние диска и файловой системы.
PRODCTL-60005File fsync failed.Не удалось сбросить данные в постоянное хранилище.Проверьте диск, параметры монтирования и журналы ядра (dmesg).
PRODCTL-60006File create failed.Родительский каталог отсутствует, или выданы неверные права доступа.Убедитесь, что родительский каталог существует, исправьте umask или права доступа.
PRODCTL-60007File rename failed.Исходный файл не существует, или прав доступа недостаточно.Убедитесь, что исходный файл существует, проверьте права доступа. Повторите попытку.
PRODCTL-60008Failed to mmap file.Ошибка mmap или нехватка адресного пространства.Переключитесь на буферизованный ввод-вывод или уменьшите размер отображаемых данных.
PRODCTL-60009Failed to stat file.Путь некорректен, или прав доступа недостаточно.Проверьте путь и права доступа пользователя.
PRODCTL-70001Memory allocation failed.Нехватка памяти в системе на критическом этапе.Уменьшите параллелизм или увеличьте системные ограничения памяти.
PRODCTL-70002Failed to create directory.Отсутствует родительский каталог, или прав доступа недостаточно.Создайте родительский каталог, проверьте права доступа.
PRODCTL-70003Failed to open directory.Указанный путь не ведёт к каталогу, или доступ запрещён.Убедитесь, что путь указывает на каталог и доступ к нему разрешён.

G.1. pgpro_datactl — manage Postgres Pro Enterprise data files

G.1.1. Overview

The pgpro_datactl utility provides tools for managing Postgres Pro Enterprise data files, including a module for CFS (Compressed File Storage) operations. This module offers the following functionalities:

  • Retrieving metadata from compressed files, including their compression algorithm and location.

  • Unpacking CFS files for further analysis.

  • Repacking compressed files and changing their compression level.

  • Preventing potential failures caused by corrupted files.

G.1.2. Installation

pgpro_datactl is provided with Postgres Pro Enterprise as a separate pre-built package pgpro-datactl-ent-13 (for the detailed installation instructions, see Chapter 17).

G.1.3. Commands

pgpro_datactl supports the following commands:

G.1.3.1. Important Notes

Before running these commands, pay attention to the following operation specifics:

  • The repack and unpack operations require the Postgres Pro Enterprise cluster to be stopped. This is necessary to prevent data corruption and ensure file consistency.

  • When using the --in-place option with the repack command, note that:

    • The tablespace will be overwritten directly during the operation.

    • All the existing data in the target tablespace will be replaced.

G.1.3.2. unpack

pgpro_datactl unpack --source=source_path --target=target_path
[--calg=compression_algorithm] [--zero-on-error] [--log-level=logging_level] [--help]

Unpacks CFS files.

-s=source_path
--source=source_path

Specifies the path to a compressed file or directory.

Note

The path must be in the directory named PG_version_date that contains the pg_compression file.

-t=target_path
--target=target_path

Specifies the path to a directory where the unpacked files will be placed.

If the source and target directories are the same, files are unpacked with a .dec extension.

-c=compression_algorithm
--calg=compression_algorithm

Specifies the compression algorithm used. If omitted, the unpack command will take this value from the pg_compression file.

--zero-on-error

If this option is specified, any corrupted blocks are replaced with zeros, preventing the process termination or error messages.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

Example:

pgpro_datactl unpack -s /path/to/archive.cfs -t /path/to/destination -c zstd

In this example, unpack extracts archive.cfs compressed with the zstd algorithm into the directory /path/to/destination.

G.1.3.3. probe

pgpro_datactl probe --source=source_path [--log-level=logging_level] [--help]

Analyzes the specified file and identifies the following:

  • Compression type: zlib or zstd compression algorithm.

  • Fragmentation level: Analyzes the corresponding *.cfm file (if available) and reports the percentage of unused storage space in the physical file.

  • Whether the file belongs to CFS: Checks the presence of an associated *.cfm file, which indicates whether the file belongs to a CFS archive.

-s=source_path
--source=source_path

Specifies the path to the required file.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

Example output:

Probing path: /data/sample.dat
Has cfm file: Yes
pg_compression: zstd
Actual compression: zstd
Fragmentation: 5%

In this example, the file is compressed with the zstd algorithm, is part of a CFS archive, and has a fragmentation level of five percent.

G.1.3.4. info

pgpro_datactl info --source=source_path [--log-level=logging_level] [--help]

Analyzes the file and displays the following information:

  • The file physical size, virtual size, and utilized file space in bytes.

  • Whether the garbage collector (GC) is active.

  • Whether the *.cfm file is present and accessible.

-s=source_path
--source=source_path

Specifies the path to the required file.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

Example output:

Physical size: 10485760
Virtual size: 9437184
Used size: 7864320
GC active: Yes

G.1.3.5. repack

pgpro_datactl repack --source=source_path --t-calg=target_compression_algorithm --target=target_path
[--calg=compression_algorithm] [--clevel=compression_level]
[--zero-on-error] [--log-level=logging_level] [--in-place] [--help]

Changes the compression algorithm and/or compression level of CFS files.

Returns the following information:

  • Compression algorithm ID

  • Compression level

  • Copy status: 1 (complete) or 0 (incomplete)

If interrupted, the process can resume from the point of failure by re-executing the command with identical compression options (both --t-calg and --calg values), leveraging per-datafile .status files to maintain the operation state.

-s=source_path
--source=source_path

Specifies the path to a compressed file or directory.

Note

The path must be in the directory named PG_version_date that contains the pg_compression file.

--t-calg=target_compression_algorithm

Specifies the target compression algorithm. If omitted, the files will be decompressed (unpacked).

-t=target_path
--target=target_path

Specifies the output location for recompressed files.

-c=compression_algorithm
--calg=compression_algorithm

Specifies the current compression algorithm. If omitted, the repack command will take this value from the pg_compression file.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

--clevel=compression_level

Specifies the compression level for the chosen target compression algorithm. The default value is 1.

--zero-on-error

If this option is specified, any corrupted blocks are replaced with zeros, preventing the process termination or error messages.

--in-place

If this option is specified while target_path is omitted, the recompressed files will be placed in the source directory.

Warning

Using this option will remove all the source files from the source directory, thus should be considered carefully.

G.1.3.6. ground

pgpro_datactl ground --source=source_path --block-num=block_number
[--calg=compression_algorithm]  [--log-level=logging_level] [--help]

Replaces the specified corrupted blocks, which may appear during decompression, with zeros.

-s=source_path
--source=source_path

Specifies the path to the required file.

--block-num=block_number

Specifies the number of the block that should be replaced.

-c=compression_algorithm
--calg=compression_algorithm

Specifies the current compression algorithm. If the value does not match the CFS tablespace compression algorithm, the operation will complete with an error.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

Example:

pgpro_datactl ground -s /path/to/archive.cfs --block-num 4 --calg pglz

In this example, ground replaces the block number 4 with a zero and uses the pglz algorithm to compress it.

G.1.3.7. stat

pgpro_datactl stat --source=source_path --cfs
[--log-level=logging_level] [--help]

Collects tablespace statistics and outputs the results as a CSV file.

This command does not modify any files (read-only operation). No locks are acquired.

-s=source_path
--source=source_path

Specifies the path to a compressed file or directory.

Note

The path must be in the directory named PG_version_date that contains the pg_compression file.

--cfs

Specifies the tablespace type.

Note

Currently only the CFS type support is implemented.

--log-level=logging_level

Sets the logging level. Possible values: debug, info, warning, and error.

G.1.4. pgpro_datactl Error Codes

Table G.1 displays the error code ranges defined in pgpro_datactl.

According to the SQL standard, the first two characters of an error code denote the class of errors, while the last three characters indicate a specific condition within that class.

Table G.1. pgpro_datactl Error Code Ranges

Error CodeCondition
00XXXSuccess
10XXXWarning
20XXXCommand-line error
30XXXDatabase error
40XXXSource data error
50XXXTarget data error
60XXXFilesystem/IO error
70XXXRuntime error

Table G.2 lists all specific error codes and the actions that should be taken if these errors occur.

pgpro_datactl uses the PRODCTL-XXXXX format. Warnings return a nonzero exit code but allow the utility to progress. Errors stop the current operation.

Table G.2. pgpro_datactl Error Codes

Error CodeMessageCauseAction
PRODCTL-00000SuccessThe operation completed successfully.No action required.
PRODCTL-10001File not found.An optional input path is missing.Check the path. If intentional, the warning can be ignored.
PRODCTL-10002Failed to read file.A partial read, permission error, or transient IO issue occurred.Retry the operation. Check user permissions and disk status.
PRODCTL-10003Invalid parameter.A noncritical argument is out of range or malformed.Enter a valid value, or a default value will be used to proceed.
PRODCTL-10004Failed to allocate memory.The system was low on memory during a noncritical step.Reduce concurrency or data size.
PRODCTL-10005Failed to create working directory.The current or working directory could not be established.Check the path, permissions, and available disk space.
PRODCTL-10006File contains invalid content.An optional file failed validation.Replace or skip the file.
PRODCTL-10007Failed to remove file.The file is locked, or permission was denied.Close any handles to the file and adjust permissions.
PRODCTL-10008Parameter required but not set.An optional subtask required a value but used the default instead.Provide the missing option to avoid the fallback behavior.
PRODCTL-20001Required parameter is missing.A mandatory command-line option is absent.Supply the required option and rerun the command.
PRODCTL-20002Invalid parameter.A command-line option has an invalid value.Enter a valid value according to the documentation.
PRODCTL-30001Database connection failed.A network, authentication, or DSN error occurred.Check authentication, network connectivity, and SSL configuration.
PRODCTL-30002Database query failed.An SQL error, timeout, or permission issue occurred.Check the SQL and logs. Fix schema or permission issues.
PRODCTL-40001Failed to read source file.An IO error occurred on input.Make sure the path exists and the user has access to it. Retry.
PRODCTL-40002Source file not found.A required input file is missing.Provide the correct file or fix the path.
PRODCTL-40003Failed to construct source path.The root path, environment variable, or template is invalid.Fix the configuration and path template.
PRODCTL-40004File contains invalid content.Required input failed validation, or a checksum mismatch occurred.Replace the file or fix its format.
PRODCTL-50001Target file write failed.A permission, disk quota, or disk error occurred.Free up disk space, fix permissions, and retry.
PRODCTL-50002Target file not found.The expected output path, or its parent directory is missing.Create the necessary directories, verify the target path.
PRODCTL-60001File remove failed.Permission was denied, or the file is in use.Release any locks on the file, adjust permissions.
PRODCTL-60002Open file failed.The file is missing, or access was denied.Make sure the file exists, check permissions.
PRODCTL-60003Open stream failed.A pipe, socket, or file handle was not available.Validate the endpoint, check permissions.
PRODCTL-60004File write failed.A short write or general IO error occurred.Retry. Check the disk and filesystem health.
PRODCTL-60005File fsync failed.Flushing data to persistent storage failed.Inspect the disk, check mount options, review kernel logs (dmesg).
PRODCTL-60006File create failed.The parent directory is missing, or permissions are incorrect.Make sure the parent directory exists, fix umask or permissions.
PRODCTL-60007File rename failed.The source file does not exist, or permissions are insufficient.Make sure the source file exists, verify permissions. Retry.
PRODCTL-60008Failed to mmap file.A memory-mapping error occurred, or the address space is low.Switch to buffered IO or reduce the mapped data size.
PRODCTL-60009Failed to stat file.The path is invalid, or permissions are insufficient.Check the path and user permissions.
PRODCTL-70001Memory allocation failed.The system ran out of memory on a critical path.Reduce parallelism or increase system memory limits.
PRODCTL-70002Failed to create directory.The parent directory is missing, or permissions are insufficient.Create a parent directory, check permissions.
PRODCTL-70003Failed to open directory.The path is not a directory, or access was denied.Make sure the path is a directory with proper access.

FAQ