Справочник по настройке
В данном справочнике рассматриваются все опции и параметры, которые можно использовать в командной строке или в файле инициализации.
Tarantool можно запустить путем ввода одной из следующих команд:
$ tarantool $ tarantool options $ tarantool lua-initialization-file [ arguments ]
-
-h
,
--help
¶
Вывод аннотированного списка всех доступных опций и выход.
-
-v
,
-V
,
--version
¶
Print the product name and version.
Example
% tarantool --version Tarantool 2.11.1-0-g96877bd Target: Darwin-arm64-Release ...
В данном примере:
2.11.1
is a Tarantool version. Tarantool follows semantic versioning, which is described in the Tarantool release policy section.Target
is the platform Tarantool is built on. Platform-specific details may follow this line.
-
-e
EXPR
¶ Execute the „EXPR“ string. See also: lua man page.
Example
% tarantool -e "print('Hello, world!')" Hello, world!
-
-l
NAME
¶ Require the „NAME“ library. See also: lua man page.
Example
% tarantool -l luatest.coverage script.lua
-
-j
cmd
¶ Perform a LuaJIT control command. See also: Command Line Options.
Example
% tarantool -j off app.lua
-
-b
...
¶ Save or list bytecode. See also: Command Line Options.
Example
% tarantool -b test.lua test.out
-
-d
SCRIPT
¶ Activate a debugging session for „SCRIPT“. See also: luadebug.lua.
Example
% tarantool -d app.lua
-
-i
[SCRIPT]
¶ Enter an interactive mode after executing „SCRIPT“.
Example
% tarantool -i
-
--
¶
Stop handling options. See also: lua man page.
-
-
¶
Stop handling options and execute the standard input as a file. See also: lua man page.
Some configuration parameters and some functions depend on a URI (Universal Resource Identifier). The URI string format is similar to the generic syntax for a URI schema. It may contain (in order):
- user name for login
- password
- host name or host IP address
- port number.
Only a port number is always mandatory. A password is mandatory if a user name is specified, unless the user name is „guest“.
Formally, the URI
syntax is [host:]port
or [username:password@]host:port
.
If host is omitted, then «0.0.0.0» or «[::]» is assumed
meaning respectively any IPv4 address or any IPv6 address
on the local machine.
If username:password
is omitted, then the «guest» user is assumed. Some examples:
Фрагмент URI | Пример |
---|---|
порт | 3301 |
хост:порт | 127.0.0.1:3301 |
имя-пользователя:пароль@хост:порт | notguest:sesame@mail.ru:3301 |
In code, the URI value can be passed as a number (if only a port is specified) or a string:
box.cfg { listen = 3301 }
box.cfg { listen = "127.0.0.1:3301" }
In certain circumstances, a Unix domain socket may be used where a URI is expected, for example, «unix/:/tmp/unix_domain_socket.sock» or simply «/tmp/unix_domain_socket.sock».
The uri module provides functions that convert URI strings into their components, or turn components into URI strings.
Starting from version 2.10.0, a user can open several listening iproto sockets on a Tarantool instance and, consequently, can specify several URIs in the configuration parameters such as box.cfg.listen and box.cfg.replication.
URI values can be set in a number of ways:
As a string with URI values separated by commas.
box.cfg { listen = "127.0.0.1:3301, /unix.sock, 3302" }
As a table that contains URIs in the string format.
box.cfg { listen = {"127.0.0.1:3301", "/unix.sock", "3302"} }
As an array of tables with the
uri
field.box.cfg { listen = { {uri = "127.0.0.1:3301"}, {uri = "/unix.sock"}, {uri = 3302} } }
In a combined way – an array that contains URIs in both the string and the table formats.
box.cfg { listen = { "127.0.0.1:3301", { uri = "/unix.sock" }, { uri = 3302 } } }
Also, starting from version 2.10.0, it is possible to specify additional parameters for URIs. You can do this in different ways:
Using the
?
delimiter when URIs are specified in a string format.box.cfg { listen = "127.0.0.1:3301?p1=value1&p2=value2, /unix.sock?p3=value3" }
Using the
params
table: a URI is passed in a table with additional parameters in the «params» table. Parameters in the «params» table overwrite the ones from a URI string («value2» overwrites «value1» forp1
in the example below).box.cfg { listen = { "127.0.0.1:3301?p1=value1", params = {p1 = "value2", p2 = "value3"} } }
Using the
default_params
table for specifying default parameter values.In the example below, two URIs are passed in a table. The default value for the
p3
parameter is defined in thedefault_params
table and used if this parameter is not specified in URIs. Parameters in thedefault_params
table are applicable to all the URIs passed in a table.box.cfg { listen = { "127.0.0.1:3301?p1=value1", { uri = "/unix.sock", params = { p2 = "value2" } }, default_params = { p3 = "value3" } } }
The recommended way for specifying URI with additional parameters is the following:
box.cfg { listen = {
{uri = "127.0.0.1:3301", params = {p1 = "value1"}},
{uri = "/unix.sock", params = {p2 = "value2"}},
{uri = 3302, params = {p3 = "value3"}}
}
}
In case of a single URI, the following syntax also works:
box.cfg { listen = {
uri = "127.0.0.1:3301",
params = { p1 = "value1", p2 = "value2" }
}
}
Если команда запуска Tarantool включает в себя файл инициализации, то Tarantool запустится посредством вызова Lua-программы из этого файла, который обычно называется «script.lua
». В Lua-программу можно добавить дополнительные аргументы из командной строки или функции операционной системы, такие как getenv()
. Lua-программа практически всегда запускается посредством вызова box.cfg()
, если будет использоваться сервер базы данных или же необходимо открыть порты. Например, предположим, что файл script.lua
содержит строки:
#!/usr/bin/env tarantool
box.cfg{
listen = os.getenv("LISTEN_URI"),
memtx_memory = 33554432,
pid_file = "tarantool.pid",
wal_max_size = 2500
}
print('Starting ', arg[1])
и предположим, что переменная окружения LISTEN_URI содержит значение 3301, а также предположим, что в командной строке ~/tarantool/src/tarantool script.lua ARG
. Тогда вывод на экране может выглядеть следующим образом:
$ export LISTEN_URI=3301
$ ~/tarantool/src/tarantool script.lua ARG
... main/101/script.lua C> Tarantool 2.8.3-0-g01023dbc2
... main/101/script.lua C> log level 5
... main/101/script.lua I> mapping 33554432 bytes for memtx tuple arena...
... main/101/script.lua I> recovery start
... main/101/script.lua I> recovering from './00000000000000000000.snap'
... main/101/script.lua I> set 'listen' configuration option to "3301"
... main/102/leave_local_hot_standby I> ready to accept requests
Starting ARG
... main C> entering the event loop
Если необходимо начать интерактивную сессию на том же терминале по окончании инициализации, можно использовать console.start().
Конфигурационные параметры выглядят так:
box.cfg{[ключ = значение [, ключ = значение ...]]}
Since box.cfg
may contain many configuration parameters and since some of the
parameters (such as directory addresses) are semi-permanent, it’s best to keep
box.cfg
in a Lua file. Typically this Lua file is the initialization file
which is specified on the Tarantool command line.
Most configuration parameters are for allocating resources, opening ports, and
specifying database behavior. All parameters are optional.
A few parameters are dynamic, that is, they can be changed at runtime by calling box.cfg{}
a second time.
For example, the command below sets the listen port to 3301
.
tarantool> box.cfg{ listen = 3301 }
2023-05-10 13:28:54.667 [31326] main/103/interactive I> tx_binary: stopped
2023-05-10 13:28:54.667 [31326] main/103/interactive I> tx_binary: bound to [::]:3301
2023-05-10 13:28:54.667 [31326] main/103/interactive/box.load_cfg I> set 'listen' configuration option to 3301
---
...
To see all the non-null parameters, execute box.cfg
(no parentheses).
tarantool> box.cfg
---
- replication_skip_conflict: false
wal_queue_max_size: 16777216
feedback_host: https://feedback.tarantool.io
memtx_dir: .
memtx_min_tuple_size: 16
-- other parameters --
...
To see a particular parameter value, call a corresponding box.cfg
option.
For example, box.cfg.listen
shows the specified listen address.
tarantool> box.cfg.listen
---
- 3301
...
Tarantool configuration parameters can be specified in different ways. The priority of parameter sources is the following, from higher to lower:
box.cfg
options- environment variables
- tt configuration
- default values.
Starting from version 2.8.1, you can specify configuration parameters via special environment variables.
The name of a variable should have the following pattern: TT_<NAME>
,
where <NAME>
is the uppercase name of the corresponding box.cfg parameter.
Пример:
TT_LISTEN
– corresponds to thebox.cfg.listen
option.TT_MEMTX_DIR
– corresponds to thebox.cfg.memtx_dir
option.
In case of an array value, separate the array elements by comma without space:
export TT_REPLICATION="localhost:3301,localhost:3302"
If you need to pass additional parameters for URI, use the ?
and &
delimiters:
export TT_LISTEN="localhost:3301?param1=value1¶m2=value2"
An empty variable (TT_LISTEN=
) has the same effect as an unset one meaning that the corresponding configuration parameter won’t be set when calling box.cfg{}
.
The sections that follow describe all configuration parameters for basic operations, storage, binary logging and snapshots, replication, networking, logging, and feedback.
Базовые параметры
- background
- custom_proc_title
- listen
- memtx_dir
- pid_file
- read_only
- sql_cache_size
- vinyl_dir
- vinyl_timeout
- username
- wal_dir
- work_dir
- worker_pool_threads
- strip_core
- memtx_use_mvcc_engine
-
background
¶
Для версий от 1.6.2. и выше. Запуск сервера в виде фоновой задачи. Чтобы это сработало, параметры log и pid_file должны быть не равны нулю.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_BACKGROUND
Динамический: нет
-
custom_proc_title
¶
Для версий от 1.6.7. и выше. Добавление заданной строки к названию процесса сервера (что показано в столбце COMMAND для команд ps -ef
и top -c
.
Например, как правило, ps -ef
показывает процесс Tarantool-сервера так:
$ ps -ef | grep tarantool
1000 14939 14188 1 10:53 pts/2 00:00:13 tarantool <running>
Но если указан конфигурационный параметр custom_proc_title='sessions'
, вывод выглядит так:
$ ps -ef | grep tarantool
1000 14939 14188 1 10:53 pts/2 00:00:16 tarantool <running>: sessions
Тип: строка
По умолчанию: null
Environment variable: TT_CUSTOM_PROC_TITLE
Динамический: да
-
listen
¶
Since version 1.6.4.
The read/write data port number or URI (Universal
Resource Identifier) string. Has no default value, so must be specified
if connections occur from the remote clients that don’t use the
«admin port». Connections made with
listen = URI
are called «binary port» or «binary protocol»
connections.
Как правило, используется значение 3301.
box.cfg { listen = 3301 }
box.cfg { listen = "127.0.0.1:3301" }
Примечание
Реплика также привязана на этот порт и принимает соединения, но эти соединения служат только для чтения до тех пор, пока реплика не станет мастером.
Starting from version 2.10.0, you can specify several URIs,
and the port number is always stored as an integer value.
Тип: целое число или строка
По умолчанию: null
Environment variable: TT_LISTEN
Динамический: да
-
memtx_dir
¶
Для версий от 1.7.4. и выше. Директория, где memtx хранит файлы снимков (.snap). Может относиться к work_dir. Если не указан, по умолчанию work_dir
. См. также wal_dir.
Тип: строка
По умолчанию: «.»
Environment variable: TT_MEMTX_DIR
Динамический: нет
-
pid_file
¶
Для версий от 1.4.9. и выше. Хранение идентификатора процесса в данном файле. Может относиться к work_dir. Как правило, используется значение “tarantool.pid
”.
Тип: строка
По умолчанию: null
Environment variable: TT_PID_FILE
Динамический: нет
-
read_only
¶
Для версий от 1.7.1. и выше. Чтобы ввести экземпляр сервера в режим только для чтения, выполните команду box.cfg{read_only=true...}
. После этого не будут выполняться любые запросы по изменению персистентных данных с ошибкой ER_READONLY
. Режим только для чтения следует использовать в репликации типа мастер-реплика. Режим только для чтения не влияет на запросы по изменению данных в спейсах, которые считаются временными. Хотя режим только для чтения не позволяет серверу делать записи в WAL-файлы, запись диагностической информации в модуле log все равно осуществляется.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_READ_ONLY
Динамический: да
Setting read_only == true
affects spaces differently depending on the
options that were used during
box.schema.space.create,
as summarized by this chart:
Характеристика
Можно создать?
Допускает запись?
Реплицируется?
Сохраняется?
(по умолчанию)
нет
нет
да
да
temporary
нет
да
нет
нет
is_local
нет
да
нет
да
-
sql_cache_size
¶
Максимальное количество байт в кэше для подготовленных операторов SQL. (box.info.sql().cache.size).
Тип: число
По умолчанию: 5242880
Environment variable: TT_SQL_CACHE_SIZE
Динамический: да
-
vinyl_dir
¶
Для версий от 1.7.1. и выше. Директория, где хранятся файлы или поддиректории vinyl’а. Может относиться к work_dir. Если не указан, по умолчанию work_dir
.
Тип: строка
По умолчанию: «.»
Environment variable: TT_VINYL_DIR
Динамический: нет
-
vinyl_timeout
¶
Для версий от 1.7.5. и выше. В движке базы данных vinyl есть планировщик, который осуществляет слияние. Когда vinyl’у не хватает доступной памяти, планировщик не сможет поддерживать скорость слияния в соответствии со входящими запросами обновления. В такой ситуации время ожидания обработки запроса может истечь после vinyl_timeout
секунд. Это происходит редко, поскольку обычно vinyl управляет загрузкой при операциях вставки, когда не хватает скорости для слияния. Слияние можно запустить автоматически с помощью index_object:compact().
Тип: число с плавающей запятой
По умолчанию: 60
Environment variable: TT_VINYL_TIMEOUT
Динамический: да
-
username
¶
Для версий от 1.4.9. и выше. Имя пользователя в UNIX, на которое переключается система после запуска.
Тип: строка
По умолчанию: null
Environment variable: TT_USERNAME
Динамический: нет
-
wal_dir
¶
Для версий от 1.6.2. и выше. Директория, где хранятся файлы журнала упреждающей записи (.xlog). Может относиться к work_dir. Иногда в wal_dir
и memtx_dir указываются разные значения, чтобы WAL-файлы и файлы снимков хранились на разных дисках. Если не указан, по умолчанию work_dir
.
Тип: строка
По умолчанию: «.»
Environment variable: TT_WAL_DIR
Динамический: нет
-
work_dir
¶
Для версий от 1.4.9. и выше. Директория, где хранятся рабочие файлы базы данных. Экземпляр сервера переключается на work_dir
с помощью chdir(2) после запуска. Может относиться к текущей директории. Если не указан, по умолчанию = текущей директории. Другие параметры директории могут относиться к work_dir
, например:
box.cfg{
work_dir = '/home/user/A',
wal_dir = 'B',
memtx_dir = 'C'
}
поместит xlog-файлы в /home/user/A/B
, файлы снимков в /home/user/A/C
, а все остальные файлы или поддиректории в /home/user/A
.
Тип: строка
По умолчанию: null
Environment variable: TT_WORK_DIR
Динамический: нет
-
worker_pool_threads
¶
Для версий от 1.7.5. и выше. Максимальное количество потоков, используемых во время исполнения определенных внутренних процессов (сейчас socket.getaddrinfo() и coio_call()).
Тип: целое число
По умолчанию: 4
Environment variable: TT_WORKER_POOL_THREADS
Динамический: да
-
strip_core
¶
Для версий от 2.2.2. и выше. Указывает, должны ли файлы coredump включать в себя память, выделенную для кортежей. (Эти файлы могут занимать много места, если Tarantool работает под высокой нагрузкой). Если установлено true
, то память, выделенная для кортежей, НЕ включается в файлы coredump. В более старых версиях Tarantool по умолчанию стояло false
.
Тип: логический
По умолчанию: true
Environment variable: TT_STRIP_CORE
Динамический: нет
-
memtx_use_mvcc_engine
¶
Since version 2.6.1.
Enables transactional manager if set to true
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_MEMTX_USE_MVCC_ENGINE
Динамический: нет
Настройка хранения
- memtx_memory
- memtx_max_tuple_size
- memtx_min_tuple_size
- memtx_allocator
- slab_alloc_factor
- slab_alloc_granularity
- vinyl_bloom_fpr
- vinyl_cache
- vinyl_max_tuple_size
- vinyl_memory
- vinyl_page_size
- vinyl_range_size
- vinyl_run_count_per_level
- vinyl_run_size_ratio
- vinyl_read_threads
- vinyl_write_threads
-
memtx_memory
¶
Для версий от 1.7.4. и выше. Количество памяти, которое Tarantool выделяет для фактического хранения кортежей. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше предела memtx_memory
.
Тип: число с плавающей запятой
По умолчанию: 256 * 1024 * 1024 = 268435456 байтов
Minimum: 33554432 bytes (32 MB)
Environment variable: TT_MEMTX_MEMORY
Динамический: да, но нельзя уменьшить
-
memtx_max_tuple_size
¶
Для версий от 1.7.4. и выше. Размер наибольшего блока выделения памяти для движка базы данных memtx. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также vinyl_max_tuple_size.
Тип: целое число
По умолчанию: 1024 * 1024 = 1048576 байтов
Environment variable: TT_MEMTX_MAX_TUPLE_SIZE
Динамический: да
-
memtx_min_tuple_size
¶
Для версий от 1.7.4. и выше. Размер наименьшего блока выделения памяти . Его можно уменьшить, если кортежи очень малого размера. Значение должно быть от 8 до 1 048 280 включительно.
Тип: целое число
По умолчанию: 16 байтов
Environment variable: TT_MEMTX_MIN_TUPLE_SIZE
Динамический: нет
-
memtx_allocator
¶
Since version 2.10.0.
Specifies the allocator used for memtx tuples.
The possible values are system
and small
:
system
is based on the malloc
function.
This allocator allocates memory as needed, checking that the quota is not exceeded.
small
is a special slab allocator.
Note that this allocator is prone to unresolvable fragmentation on specific workloads,
so you can switch to system
in such cases.
Тип: строка
Default: „small“
Environment variable: TT_MEMTX_ALLOCATOR
Dynamic: No
-
slab_alloc_factor
¶
Множитель для вычисления размеров блоков памяти, в которых хранятся кортежи. Уменьшение значения может привести к уменьшению потерь памяти в зависимости от общего объема доступной памяти и распределения размеров элементов. Допустимые значения: от 1 до 2.
See also: slab_alloc_granularity
Тип: число с плавающей запятой
Default: 1.05
Environment variable: TT_SLAB_ALLOC_FACTOR
Динамический: нет
-
slab_alloc_granularity
¶
Since version 2.8.1.
Specifies the granularity (in bytes) of memory allocation in the small allocator.
The value of slab_alloc_granularity
should be a power of two and should be greater than or equal to 4.
Below are few recommendations on how to adjust the slab_alloc_granularity
value:
- To store small tuples of approximately the same size, set
slab_alloc_granularity
to 4 bytes to save memory.
- To store tuples of different sizes, you can increase the
slab_alloc_granularity
value.
This results in allocating tuples from the same mempool
.
See also: slab_alloc_factor
Тип: число
Default: 8 bytes
Environment variable: TT_SLAB_ALLOC_GRANULARITY
Динамический: нет
-
vinyl_bloom_fpr
¶
Для версий от 1.7.4. и выше. Доля ложноположительного срабатывания фильтра Блума – подходящая вероятность того, что фильтр Блума выдаст ошибочный результат. Настройка vinyl_bloom_fpr
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: число с плавающей запятой
По умолчанию: 0.05
Environment variable: TT_VINYL_BLOOM_FPR
Динамический: нет
-
vinyl_cache
¶
Для версий от 1.7.4. и выше. Размер кэша для движка базы данных vinyl. Размер кэша можно изменить динамически.
Тип: целое число
По умолчанию: 128 * 1024 * 1024 = 134217728 байтов
Environment variable: TT_VINYL_CACHE
Динамический: да
-
vinyl_max_tuple_size
¶
Для версий от 1.7.5. и выше. Размер наибольшего блока выделения памяти для движка базы данных vinyl. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также memtx_max_tuple_size.
Тип: целое число
По умолчанию: 1024 * 1024 = 1048576 байтов
Environment variable: TT_VINYL_MAX_TUPLE_SIZE
Динамический: нет
-
vinyl_memory
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов оперативной памяти, которые использует vinyl.
Тип: целое число
По умолчанию: 128 * 1024 * 1024 = 134217728 байтов
Environment variable: TT_VINYL_MEMORY
Динамический: да, но нельзя уменьшить
-
vinyl_page_size
¶
Для версий от 1.7.4. и выше. Размер страницы в байтах. Страница представляет собой блок чтения и записи для операций на диске vinyl. Настройка vinyl_page_size
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: целое число
По умолчанию: 8 * 1024 = 8192 байтов
Environment variable: TT_VINYL_PAGE_SIZE
Динамический: нет
-
vinyl_range_size
¶
Для версий от 1.7.4. и выше. Максимальный размер диапазона для индекса vinyl в байтах. Максимальный размер диапазона влияет на принятие решения о разделении диапазона.
Если vinyl_range_size
содержит не нулевое значение nil и не 0, это значение используется в качестве значения по умолчанию для параметра range_size
в таблице Параметры space_object:create_index().
Если vinyl_range_size
содержит нулевое значение nil или 0, а параметр range_size
не задан при создании индекса, то Tarantool сам задает это значение позднее в результате оценки производительности. Чтобы узнать текущее значение, используйте index_object:stat().range_size.
До версии Tarantool 1.10.2 значение vinyl_range_size
по умолчанию было 1073741824.
Тип: целое число
По умолчанию: nil
Environment variable: TT_VINYL_RANGE_SIZE
Динамический: нет
-
vinyl_run_count_per_level
¶
Для версий от 1.7.4. и выше. Максимальное количество забегов на уровень журнально-структурированного дерева со слиянием в vinyl’е. Настройка vinyl_run_count_per_level
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: целое число
По умолчанию: 2
Environment variable: TT_VINYL_RUN_COUNT_PER_LEVEL
Динамический: нет
-
vinyl_run_size_ratio
¶
Для версий от 1.7.4. и выше. Отношение размеров различных уровней журнально-структурированного дерева со слиянием. Настройка vinyl_run_size_ratio
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: число с плавающей запятой
По умолчанию: 3.5
Environment variable: TT_VINYL_RUN_SIZE_RATIO
Динамический: нет
-
vinyl_read_threads
¶
Для версий от 1.7.5. и выше. Максимальное количество потоков чтения, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое число
По умолчанию: 1
Environment variable: TT_VINYL_READ_THREADS
Динамический: нет
-
vinyl_write_threads
¶
Для версий от 1.7.5. и выше. Максимальное количество потоков записи, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое число
По умолчанию: 4
Environment variable: TT_VINYL_WRITE_THREADS
Динамический: нет
Демон создания контрольных точек
Демон создания контрольных точек – это постоянно работающий файбер. Периодически он может создавать файлы снимка (.snap), а затем может удалять старые файлы снимка.
Настройки конфигурации checkpoint_interval и checkpoint_count определяют длительность интервалов и количество снимков, которое должно присутствовать до начала удалений.
Сборщик мусора Tarantool
Демон создания контрольных точек может запустить сборщик мусора Tarantool, который удаляет старые файлы. Такой сборщик мусора не отличается от сборщика мусора в Lua, который предназначен для Lua-объектов, и от сборщика мусора, который специализируется на обработке блоков шарда.
Если демон создания контрольных точек удаляет старый файл снимка, сборщик мусора Tarantool также удалит любые файлы журнала упреждающей записи (.xlog) старше файла снимка, содержащие информацию, которая присутствует в файле снимка. Он также удаляет устаревшие файлы .run
в vinyl’е.
Демон создания контрольных точек и сборщик мусора Tarantool не удалят файл, если:
- идет резервное копирование, и файл еще не был скопирован (см. «Резервное копирование»), или
- идет репликация, и файл еще не был передан на реплику (см. «Архитектуру механизма репликации»),
- реплика подключается, или
- реплика отстает. Ход выполнения на каждой реплике отслеживается. Если реплика далеко не актуальна, сервер останавливается, чтобы она могла обновиться. Если администратор делает вывод, что реплика окончательно недоступна, необходимо перезагрузить сервер или же (предпочтительно) удалить реплику из кластера.
-
checkpoint_interval
¶
Для версий от 1.7.4. и выше. Промежуток времени между действиями демона создания контрольных точек в секундах. Если значение параметра checkpoint_interval
больше нуля, и выполняется изменение базы данных, то демон создания контрольных точек будет вызывать box.snapshot() каждые checkpoint_interval
секунд, каждый раз создавая новый файл снимка. Если значение параметра checkpoint_interval
равно нулю, то демон создания контрольных точек отключен.
Пример:
box.cfg{checkpoint_interval=60}
приведет к созданию нового снимка базы данных демоном создания контрольных точек каждую минуту, если наблюдается активность в базе данных.
Тип: целое число
По умолчанию: 3600 (один час)
Environment variable: TT_CHECKPOINT_INTERVAL
Динамический: да
-
checkpoint_count
¶
Для версий от 1.7.4. и выше. Максимальное количество снимков, которые могут находиться в директории memtx_dir до того, как демон создания контрольных точек будет удалять старые снимки. Если значение checkpoint_count
равно нулю, то демон создания контрольных точек не удаляет старые снимки. Например:
box.cfg{
checkpoint_interval = 3600,
checkpoint_count = 10
}
заставит демон создания контрольных точек создавать снимок каждый час до тех пор, пока не будет создано десять снимков. Затем самый старый снимок удаляется (а также любые связанные с ним WAL-файлы) после создания нового снимка.
Следует помнить, что как упоминалось выше, снимки не удаляются, если выполняется репликация, и файл еще не был передан на реплику. Таким образом, параметр checkpoint_count
бесполезен, если какая-то реплика неактивна.
Тип: целое число
По умолчанию: 2
Environment variable: TT_CHECKPOINT_COUNT
Динамический: да
-
checkpoint_wal_threshold
¶
Для версий от 2.1.2. и выше. Порог общего размера в байтах всех файлов WAL, созданных с момента последней контрольной точки. После превышения настроенного порога поток WAL уведомляет демона контрольной точки о том, что он должен создать новую контрольную точку и удалить старые файлы WAL.
Этот параметр позволяет администраторам справиться с проблемой, которая может возникнуть при вычислении объема дискового пространства для раздела, содержащего файлы WAL.
Например, предположим, что checkpoint_interval = 2 и checkpoint_count = 5 и в среднем за каждый интервал Tarantool записывает 1 Гб. Тогда можно будет вычислить, что необходимо (2*5*1) 10 Гб. Но это вычисление было бы неправильным, если бы вместо записи 1 ГБ в течение одного интервала между контрольными точками, Tarantool столкнулся с необычным всплеском и попытался записать 11 ГБ, что привело бы к ошибке операционной системы ENOSPC («нет места»). Установив значение checkpoint_wal_threshold
на меньшее, скажем, 9 Гб, администратор может предотвратить ошибку.
Тип: целое число
По умолчанию: 10^18 (большое число: можно считать, что предела нет)
Environment variable: TT_CHECKPOINT_WAL_THRESHOLD
Динамический: да
Записи в бинарный журнал и создание снимков
- force_recovery
- wal_max_size
- snap_io_rate_limit
- wal_mode
- wal_dir_rescan_delay
- wal_queue_max_size
- wal_cleanup_delay
-
force_recovery
¶
Для версий от 1.7.4. и выше. Если значение force_recovery
равно true (правда), Tarantool пытается продолжать работу при обнаружении ошибки во время чтения файла снимка (при запуске экземпляра сервера) или файла журнала упреждающей записи (при запуске экземпляра сервера или применении обновлений к реплике): пропускает нерабочие записи, считывает максимальное количество данных и позволяет завершить процесс предупреждением. Пользователи могут предотвратить повторное появление ошибки, записав данные в базу и выполнив box.snapshot().
В остальных случаях Tarantool прерывает восстановление на ошибке чтения.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_FORCE_RECOVERY
Динамический: нет
-
wal_max_size
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов в отдельном журнале упреждающей записи. Если в результате запроса файл .xlog будет больше, чем указано в параметре wal_max_size
, Tarantool создает другой WAL-файл – то же самое происходит, когда достигнуто количество строк в журнале, указанное в rows_per_wal.
Тип: целое число
По умолчанию: 268435456 (256 * 1024 * 1024) байтов
Environment variable: TT_WAL_MAX_SIZE
Динамический: нет
-
snap_io_rate_limit
¶
Для версий от 1.4.9. и выше. Уменьшение загрузки box.snapshot() при выполнении операций вставки, обновления и удаления (INSERT/UPDATE/DELETE) путем установки предела скорости записи на диск – количества мегабайт в секунду. Того же эффекта можно достичь, разделив директории wal_dir и memtx_dir и перенося снимки на отдельный диск. Такой предел также ограничивает результат box.stat.vinyl().regulator относительно скорости записи дампов в файлы формата .run и .index.
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_SNAP_IO_RATE_LIMIT
Динамический: да
-
wal_mode
¶
Для версий от 1.6.2. и выше. Определение синхронизации работы файбера с журналом упреждающей записи:
none
: журнал упреждающей записи не поддерживается. Узел с wal_mode = none
при репликации не может быть мастером;
write
: файберы ожидают записи данных в журнал упреждающей записи (не fsync(2));
fsync
: файберы ожидают данные, синхронизация fsync(2) следует за каждой операцией записи write(2);
Тип: строка
По умолчанию: «write»
Environment variable: TT_WAL_MODE
Динамический: нет
-
wal_dir_rescan_delay
¶
Для версий от 1.6.2. и выше. Количество секунд между периодическим сканирование директории WAL-файла при проверке изменений в WAL-файле для целей репликации или горячего резервирования.
Тип: число с плавающей запятой
По умолчанию: 2
Environment variable: TT_WAL_DIR_RESCAN_DELAY
Динамический: нет
-
wal_queue_max_size
¶
Since version 2.8.1.
The size of the queue (in bytes) used by a replica to submit
new transactions to a write-ahead log (WAL).
This option helps limit the rate at which a replica submits transactions to the WAL.
Limiting the queue size might be useful when a replica is trying to sync with a master and
reads new transactions faster than writing them to the WAL.
Примечание
You might consider increasing the wal_queue_max_size
value in case of
large tuples (approximately one megabyte or larger).
Тип: число
Default: 16777216 bytes
Environment variable: TT_WAL_QUEUE_MAX_SIZE
Динамический: да
-
wal_cleanup_delay
¶
Since version 2.6.3.
The delay (in seconds) used to prevent the Tarantool garbage collector
from immediately removing write-ahead log files after a node restart.
This delay eliminates possible erroneous situations when the master deletes WALs
needed by replicas after restart.
As a consequence, replicas sync with the master faster after its restart and
don’t need to download all the data again.
Once all the nodes in the replica set are up and running,
automatic cleanup is started again even if wal_cleanup_delay
has not expired.
Примечание
The wal_cleanup_delay
option has no effect on nodes running as
anonymous replicas.
Тип: число
Default: 14400 seconds
Environment variable: TT_WAL_CLEANUP_DELAY
Динамический: да
Горячее резервирование
-
hot_standby
¶
Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словами I> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.
Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словами I> ready to accept requests
(готов принимать запросы).
Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд.
- если wal_mode = „none“; будет работать только при
wal_mode = 'write'
или wal_mode = 'fsync'
.
- со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_HOT_STANDBY
Динамический: нет
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
- background
- custom_proc_title
- listen
- memtx_dir
- pid_file
- read_only
- sql_cache_size
- vinyl_dir
- vinyl_timeout
- username
- wal_dir
- work_dir
- worker_pool_threads
- strip_core
- memtx_use_mvcc_engine
-
background
¶ Для версий от 1.6.2. и выше. Запуск сервера в виде фоновой задачи. Чтобы это сработало, параметры log и pid_file должны быть не равны нулю.
Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_BACKGROUNDДинамический: нет
-
custom_proc_title
¶ Для версий от 1.6.7. и выше. Добавление заданной строки к названию процесса сервера (что показано в столбце COMMAND для команд
ps -ef
иtop -c
.Например, как правило,
ps -ef
показывает процесс Tarantool-сервера так:$ ps -ef | grep tarantool 1000 14939 14188 1 10:53 pts/2 00:00:13 tarantool <running>
Но если указан конфигурационный параметр
custom_proc_title='sessions'
, вывод выглядит так:$ ps -ef | grep tarantool 1000 14939 14188 1 10:53 pts/2 00:00:16 tarantool <running>: sessions
Тип: строкаПо умолчанию: nullEnvironment variable: TT_CUSTOM_PROC_TITLEДинамический: да
-
listen
¶ Since version 1.6.4.
The read/write data port number or URI (Universal Resource Identifier) string. Has no default value, so must be specified if connections occur from the remote clients that don’t use the «admin port». Connections made with
listen = URI
are called «binary port» or «binary protocol» connections.Как правило, используется значение 3301.
box.cfg { listen = 3301 } box.cfg { listen = "127.0.0.1:3301" }
Примечание
Реплика также привязана на этот порт и принимает соединения, но эти соединения служат только для чтения до тех пор, пока реплика не станет мастером.
Starting from version 2.10.0, you can specify several URIs, and the port number is always stored as an integer value.
Тип: целое число или строкаПо умолчанию: nullEnvironment variable: TT_LISTENДинамический: да
-
memtx_dir
¶ Для версий от 1.7.4. и выше. Директория, где memtx хранит файлы снимков (.snap). Может относиться к work_dir. Если не указан, по умолчанию
work_dir
. См. также wal_dir.Тип: строкаПо умолчанию: «.»Environment variable: TT_MEMTX_DIRДинамический: нет
-
pid_file
¶ Для версий от 1.4.9. и выше. Хранение идентификатора процесса в данном файле. Может относиться к work_dir. Как правило, используется значение “
tarantool.pid
”.Тип: строкаПо умолчанию: nullEnvironment variable: TT_PID_FILEДинамический: нет
-
read_only
¶ Для версий от 1.7.1. и выше. Чтобы ввести экземпляр сервера в режим только для чтения, выполните команду
box.cfg{read_only=true...}
. После этого не будут выполняться любые запросы по изменению персистентных данных с ошибкойER_READONLY
. Режим только для чтения следует использовать в репликации типа мастер-реплика. Режим только для чтения не влияет на запросы по изменению данных в спейсах, которые считаются временными. Хотя режим только для чтения не позволяет серверу делать записи в WAL-файлы, запись диагностической информации в модуле log все равно осуществляется.Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_READ_ONLYДинамический: даSetting
read_only == true
affects spaces differently depending on the options that were used during box.schema.space.create, as summarized by this chart:Характеристика Можно создать? Допускает запись? Реплицируется? Сохраняется? (по умолчанию) нет нет да да temporary нет да нет нет is_local нет да нет да
-
sql_cache_size
¶ Максимальное количество байт в кэше для подготовленных операторов SQL. (box.info.sql().cache.size).
Тип: числоПо умолчанию: 5242880Environment variable: TT_SQL_CACHE_SIZEДинамический: да
-
vinyl_dir
¶ Для версий от 1.7.1. и выше. Директория, где хранятся файлы или поддиректории vinyl’а. Может относиться к work_dir. Если не указан, по умолчанию
work_dir
.Тип: строкаПо умолчанию: «.»Environment variable: TT_VINYL_DIRДинамический: нет
-
vinyl_timeout
¶ Для версий от 1.7.5. и выше. В движке базы данных vinyl есть планировщик, который осуществляет слияние. Когда vinyl’у не хватает доступной памяти, планировщик не сможет поддерживать скорость слияния в соответствии со входящими запросами обновления. В такой ситуации время ожидания обработки запроса может истечь после
vinyl_timeout
секунд. Это происходит редко, поскольку обычно vinyl управляет загрузкой при операциях вставки, когда не хватает скорости для слияния. Слияние можно запустить автоматически с помощью index_object:compact().Тип: число с плавающей запятойПо умолчанию: 60Environment variable: TT_VINYL_TIMEOUTДинамический: да
-
username
¶ Для версий от 1.4.9. и выше. Имя пользователя в UNIX, на которое переключается система после запуска.
Тип: строкаПо умолчанию: nullEnvironment variable: TT_USERNAMEДинамический: нет
-
wal_dir
¶ Для версий от 1.6.2. и выше. Директория, где хранятся файлы журнала упреждающей записи (.xlog). Может относиться к work_dir. Иногда в
wal_dir
и memtx_dir указываются разные значения, чтобы WAL-файлы и файлы снимков хранились на разных дисках. Если не указан, по умолчаниюwork_dir
.Тип: строкаПо умолчанию: «.»Environment variable: TT_WAL_DIRДинамический: нет
-
work_dir
¶ Для версий от 1.4.9. и выше. Директория, где хранятся рабочие файлы базы данных. Экземпляр сервера переключается на
work_dir
с помощью chdir(2) после запуска. Может относиться к текущей директории. Если не указан, по умолчанию = текущей директории. Другие параметры директории могут относиться кwork_dir
, например:box.cfg{ work_dir = '/home/user/A', wal_dir = 'B', memtx_dir = 'C' }
поместит xlog-файлы в
/home/user/A/B
, файлы снимков в/home/user/A/C
, а все остальные файлы или поддиректории в/home/user/A
.Тип: строкаПо умолчанию: nullEnvironment variable: TT_WORK_DIRДинамический: нет
-
worker_pool_threads
¶ Для версий от 1.7.5. и выше. Максимальное количество потоков, используемых во время исполнения определенных внутренних процессов (сейчас socket.getaddrinfo() и coio_call()).
Тип: целое числоПо умолчанию: 4Environment variable: TT_WORKER_POOL_THREADSДинамический: да
-
strip_core
¶ Для версий от 2.2.2. и выше. Указывает, должны ли файлы coredump включать в себя память, выделенную для кортежей. (Эти файлы могут занимать много места, если Tarantool работает под высокой нагрузкой). Если установлено
true
, то память, выделенная для кортежей, НЕ включается в файлы coredump. В более старых версиях Tarantool по умолчанию стоялоfalse
.Тип: логическийПо умолчанию: trueEnvironment variable: TT_STRIP_COREДинамический: нет
-
memtx_use_mvcc_engine
¶ Since version 2.6.1. Enables transactional manager if set to
true
.Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_MEMTX_USE_MVCC_ENGINEДинамический: нет
Настройка хранения
- memtx_memory
- memtx_max_tuple_size
- memtx_min_tuple_size
- memtx_allocator
- slab_alloc_factor
- slab_alloc_granularity
- vinyl_bloom_fpr
- vinyl_cache
- vinyl_max_tuple_size
- vinyl_memory
- vinyl_page_size
- vinyl_range_size
- vinyl_run_count_per_level
- vinyl_run_size_ratio
- vinyl_read_threads
- vinyl_write_threads
-
memtx_memory
¶
Для версий от 1.7.4. и выше. Количество памяти, которое Tarantool выделяет для фактического хранения кортежей. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше предела memtx_memory
.
Тип: число с плавающей запятой
По умолчанию: 256 * 1024 * 1024 = 268435456 байтов
Minimum: 33554432 bytes (32 MB)
Environment variable: TT_MEMTX_MEMORY
Динамический: да, но нельзя уменьшить
-
memtx_max_tuple_size
¶
Для версий от 1.7.4. и выше. Размер наибольшего блока выделения памяти для движка базы данных memtx. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также vinyl_max_tuple_size.
Тип: целое число
По умолчанию: 1024 * 1024 = 1048576 байтов
Environment variable: TT_MEMTX_MAX_TUPLE_SIZE
Динамический: да
-
memtx_min_tuple_size
¶
Для версий от 1.7.4. и выше. Размер наименьшего блока выделения памяти . Его можно уменьшить, если кортежи очень малого размера. Значение должно быть от 8 до 1 048 280 включительно.
Тип: целое число
По умолчанию: 16 байтов
Environment variable: TT_MEMTX_MIN_TUPLE_SIZE
Динамический: нет
-
memtx_allocator
¶
Since version 2.10.0.
Specifies the allocator used for memtx tuples.
The possible values are system
and small
:
system
is based on the malloc
function.
This allocator allocates memory as needed, checking that the quota is not exceeded.
small
is a special slab allocator.
Note that this allocator is prone to unresolvable fragmentation on specific workloads,
so you can switch to system
in such cases.
Тип: строка
Default: „small“
Environment variable: TT_MEMTX_ALLOCATOR
Dynamic: No
-
slab_alloc_factor
¶
Множитель для вычисления размеров блоков памяти, в которых хранятся кортежи. Уменьшение значения может привести к уменьшению потерь памяти в зависимости от общего объема доступной памяти и распределения размеров элементов. Допустимые значения: от 1 до 2.
See also: slab_alloc_granularity
Тип: число с плавающей запятой
Default: 1.05
Environment variable: TT_SLAB_ALLOC_FACTOR
Динамический: нет
-
slab_alloc_granularity
¶
Since version 2.8.1.
Specifies the granularity (in bytes) of memory allocation in the small allocator.
The value of slab_alloc_granularity
should be a power of two and should be greater than or equal to 4.
Below are few recommendations on how to adjust the slab_alloc_granularity
value:
- To store small tuples of approximately the same size, set
slab_alloc_granularity
to 4 bytes to save memory.
- To store tuples of different sizes, you can increase the
slab_alloc_granularity
value.
This results in allocating tuples from the same mempool
.
See also: slab_alloc_factor
Тип: число
Default: 8 bytes
Environment variable: TT_SLAB_ALLOC_GRANULARITY
Динамический: нет
-
vinyl_bloom_fpr
¶
Для версий от 1.7.4. и выше. Доля ложноположительного срабатывания фильтра Блума – подходящая вероятность того, что фильтр Блума выдаст ошибочный результат. Настройка vinyl_bloom_fpr
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: число с плавающей запятой
По умолчанию: 0.05
Environment variable: TT_VINYL_BLOOM_FPR
Динамический: нет
-
vinyl_cache
¶
Для версий от 1.7.4. и выше. Размер кэша для движка базы данных vinyl. Размер кэша можно изменить динамически.
Тип: целое число
По умолчанию: 128 * 1024 * 1024 = 134217728 байтов
Environment variable: TT_VINYL_CACHE
Динамический: да
-
vinyl_max_tuple_size
¶
Для версий от 1.7.5. и выше. Размер наибольшего блока выделения памяти для движка базы данных vinyl. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также memtx_max_tuple_size.
Тип: целое число
По умолчанию: 1024 * 1024 = 1048576 байтов
Environment variable: TT_VINYL_MAX_TUPLE_SIZE
Динамический: нет
-
vinyl_memory
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов оперативной памяти, которые использует vinyl.
Тип: целое число
По умолчанию: 128 * 1024 * 1024 = 134217728 байтов
Environment variable: TT_VINYL_MEMORY
Динамический: да, но нельзя уменьшить
-
vinyl_page_size
¶
Для версий от 1.7.4. и выше. Размер страницы в байтах. Страница представляет собой блок чтения и записи для операций на диске vinyl. Настройка vinyl_page_size
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: целое число
По умолчанию: 8 * 1024 = 8192 байтов
Environment variable: TT_VINYL_PAGE_SIZE
Динамический: нет
-
vinyl_range_size
¶
Для версий от 1.7.4. и выше. Максимальный размер диапазона для индекса vinyl в байтах. Максимальный размер диапазона влияет на принятие решения о разделении диапазона.
Если vinyl_range_size
содержит не нулевое значение nil и не 0, это значение используется в качестве значения по умолчанию для параметра range_size
в таблице Параметры space_object:create_index().
Если vinyl_range_size
содержит нулевое значение nil или 0, а параметр range_size
не задан при создании индекса, то Tarantool сам задает это значение позднее в результате оценки производительности. Чтобы узнать текущее значение, используйте index_object:stat().range_size.
До версии Tarantool 1.10.2 значение vinyl_range_size
по умолчанию было 1073741824.
Тип: целое число
По умолчанию: nil
Environment variable: TT_VINYL_RANGE_SIZE
Динамический: нет
-
vinyl_run_count_per_level
¶
Для версий от 1.7.4. и выше. Максимальное количество забегов на уровень журнально-структурированного дерева со слиянием в vinyl’е. Настройка vinyl_run_count_per_level
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: целое число
По умолчанию: 2
Environment variable: TT_VINYL_RUN_COUNT_PER_LEVEL
Динамический: нет
-
vinyl_run_size_ratio
¶
Для версий от 1.7.4. и выше. Отношение размеров различных уровней журнально-структурированного дерева со слиянием. Настройка vinyl_run_size_ratio
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().
Тип: число с плавающей запятой
По умолчанию: 3.5
Environment variable: TT_VINYL_RUN_SIZE_RATIO
Динамический: нет
-
vinyl_read_threads
¶
Для версий от 1.7.5. и выше. Максимальное количество потоков чтения, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое число
По умолчанию: 1
Environment variable: TT_VINYL_READ_THREADS
Динамический: нет
-
vinyl_write_threads
¶
Для версий от 1.7.5. и выше. Максимальное количество потоков записи, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое число
По умолчанию: 4
Environment variable: TT_VINYL_WRITE_THREADS
Динамический: нет
Демон создания контрольных точек
Демон создания контрольных точек – это постоянно работающий файбер. Периодически он может создавать файлы снимка (.snap), а затем может удалять старые файлы снимка.
Настройки конфигурации checkpoint_interval и checkpoint_count определяют длительность интервалов и количество снимков, которое должно присутствовать до начала удалений.
Сборщик мусора Tarantool
Демон создания контрольных точек может запустить сборщик мусора Tarantool, который удаляет старые файлы. Такой сборщик мусора не отличается от сборщика мусора в Lua, который предназначен для Lua-объектов, и от сборщика мусора, который специализируется на обработке блоков шарда.
Если демон создания контрольных точек удаляет старый файл снимка, сборщик мусора Tarantool также удалит любые файлы журнала упреждающей записи (.xlog) старше файла снимка, содержащие информацию, которая присутствует в файле снимка. Он также удаляет устаревшие файлы .run
в vinyl’е.
Демон создания контрольных точек и сборщик мусора Tarantool не удалят файл, если:
- идет резервное копирование, и файл еще не был скопирован (см. «Резервное копирование»), или
- идет репликация, и файл еще не был передан на реплику (см. «Архитектуру механизма репликации»),
- реплика подключается, или
- реплика отстает. Ход выполнения на каждой реплике отслеживается. Если реплика далеко не актуальна, сервер останавливается, чтобы она могла обновиться. Если администратор делает вывод, что реплика окончательно недоступна, необходимо перезагрузить сервер или же (предпочтительно) удалить реплику из кластера.
-
checkpoint_interval
¶
Для версий от 1.7.4. и выше. Промежуток времени между действиями демона создания контрольных точек в секундах. Если значение параметра checkpoint_interval
больше нуля, и выполняется изменение базы данных, то демон создания контрольных точек будет вызывать box.snapshot() каждые checkpoint_interval
секунд, каждый раз создавая новый файл снимка. Если значение параметра checkpoint_interval
равно нулю, то демон создания контрольных точек отключен.
Пример:
box.cfg{checkpoint_interval=60}
приведет к созданию нового снимка базы данных демоном создания контрольных точек каждую минуту, если наблюдается активность в базе данных.
Тип: целое число
По умолчанию: 3600 (один час)
Environment variable: TT_CHECKPOINT_INTERVAL
Динамический: да
-
checkpoint_count
¶
Для версий от 1.7.4. и выше. Максимальное количество снимков, которые могут находиться в директории memtx_dir до того, как демон создания контрольных точек будет удалять старые снимки. Если значение checkpoint_count
равно нулю, то демон создания контрольных точек не удаляет старые снимки. Например:
box.cfg{
checkpoint_interval = 3600,
checkpoint_count = 10
}
заставит демон создания контрольных точек создавать снимок каждый час до тех пор, пока не будет создано десять снимков. Затем самый старый снимок удаляется (а также любые связанные с ним WAL-файлы) после создания нового снимка.
Следует помнить, что как упоминалось выше, снимки не удаляются, если выполняется репликация, и файл еще не был передан на реплику. Таким образом, параметр checkpoint_count
бесполезен, если какая-то реплика неактивна.
Тип: целое число
По умолчанию: 2
Environment variable: TT_CHECKPOINT_COUNT
Динамический: да
-
checkpoint_wal_threshold
¶
Для версий от 2.1.2. и выше. Порог общего размера в байтах всех файлов WAL, созданных с момента последней контрольной точки. После превышения настроенного порога поток WAL уведомляет демона контрольной точки о том, что он должен создать новую контрольную точку и удалить старые файлы WAL.
Этот параметр позволяет администраторам справиться с проблемой, которая может возникнуть при вычислении объема дискового пространства для раздела, содержащего файлы WAL.
Например, предположим, что checkpoint_interval = 2 и checkpoint_count = 5 и в среднем за каждый интервал Tarantool записывает 1 Гб. Тогда можно будет вычислить, что необходимо (2*5*1) 10 Гб. Но это вычисление было бы неправильным, если бы вместо записи 1 ГБ в течение одного интервала между контрольными точками, Tarantool столкнулся с необычным всплеском и попытался записать 11 ГБ, что привело бы к ошибке операционной системы ENOSPC («нет места»). Установив значение checkpoint_wal_threshold
на меньшее, скажем, 9 Гб, администратор может предотвратить ошибку.
Тип: целое число
По умолчанию: 10^18 (большое число: можно считать, что предела нет)
Environment variable: TT_CHECKPOINT_WAL_THRESHOLD
Динамический: да
Записи в бинарный журнал и создание снимков
- force_recovery
- wal_max_size
- snap_io_rate_limit
- wal_mode
- wal_dir_rescan_delay
- wal_queue_max_size
- wal_cleanup_delay
-
force_recovery
¶
Для версий от 1.7.4. и выше. Если значение force_recovery
равно true (правда), Tarantool пытается продолжать работу при обнаружении ошибки во время чтения файла снимка (при запуске экземпляра сервера) или файла журнала упреждающей записи (при запуске экземпляра сервера или применении обновлений к реплике): пропускает нерабочие записи, считывает максимальное количество данных и позволяет завершить процесс предупреждением. Пользователи могут предотвратить повторное появление ошибки, записав данные в базу и выполнив box.snapshot().
В остальных случаях Tarantool прерывает восстановление на ошибке чтения.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_FORCE_RECOVERY
Динамический: нет
-
wal_max_size
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов в отдельном журнале упреждающей записи. Если в результате запроса файл .xlog будет больше, чем указано в параметре wal_max_size
, Tarantool создает другой WAL-файл – то же самое происходит, когда достигнуто количество строк в журнале, указанное в rows_per_wal.
Тип: целое число
По умолчанию: 268435456 (256 * 1024 * 1024) байтов
Environment variable: TT_WAL_MAX_SIZE
Динамический: нет
-
snap_io_rate_limit
¶
Для версий от 1.4.9. и выше. Уменьшение загрузки box.snapshot() при выполнении операций вставки, обновления и удаления (INSERT/UPDATE/DELETE) путем установки предела скорости записи на диск – количества мегабайт в секунду. Того же эффекта можно достичь, разделив директории wal_dir и memtx_dir и перенося снимки на отдельный диск. Такой предел также ограничивает результат box.stat.vinyl().regulator относительно скорости записи дампов в файлы формата .run и .index.
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_SNAP_IO_RATE_LIMIT
Динамический: да
-
wal_mode
¶
Для версий от 1.6.2. и выше. Определение синхронизации работы файбера с журналом упреждающей записи:
none
: журнал упреждающей записи не поддерживается. Узел с wal_mode = none
при репликации не может быть мастером;
write
: файберы ожидают записи данных в журнал упреждающей записи (не fsync(2));
fsync
: файберы ожидают данные, синхронизация fsync(2) следует за каждой операцией записи write(2);
Тип: строка
По умолчанию: «write»
Environment variable: TT_WAL_MODE
Динамический: нет
-
wal_dir_rescan_delay
¶
Для версий от 1.6.2. и выше. Количество секунд между периодическим сканирование директории WAL-файла при проверке изменений в WAL-файле для целей репликации или горячего резервирования.
Тип: число с плавающей запятой
По умолчанию: 2
Environment variable: TT_WAL_DIR_RESCAN_DELAY
Динамический: нет
-
wal_queue_max_size
¶
Since version 2.8.1.
The size of the queue (in bytes) used by a replica to submit
new transactions to a write-ahead log (WAL).
This option helps limit the rate at which a replica submits transactions to the WAL.
Limiting the queue size might be useful when a replica is trying to sync with a master and
reads new transactions faster than writing them to the WAL.
Примечание
You might consider increasing the wal_queue_max_size
value in case of
large tuples (approximately one megabyte or larger).
Тип: число
Default: 16777216 bytes
Environment variable: TT_WAL_QUEUE_MAX_SIZE
Динамический: да
-
wal_cleanup_delay
¶
Since version 2.6.3.
The delay (in seconds) used to prevent the Tarantool garbage collector
from immediately removing write-ahead log files after a node restart.
This delay eliminates possible erroneous situations when the master deletes WALs
needed by replicas after restart.
As a consequence, replicas sync with the master faster after its restart and
don’t need to download all the data again.
Once all the nodes in the replica set are up and running,
automatic cleanup is started again even if wal_cleanup_delay
has not expired.
Примечание
The wal_cleanup_delay
option has no effect on nodes running as
anonymous replicas.
Тип: число
Default: 14400 seconds
Environment variable: TT_WAL_CLEANUP_DELAY
Динамический: да
Горячее резервирование
-
hot_standby
¶
Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словами I> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.
Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словами I> ready to accept requests
(готов принимать запросы).
Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд.
- если wal_mode = „none“; будет работать только при
wal_mode = 'write'
или wal_mode = 'fsync'
.
- со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_HOT_STANDBY
Динамический: нет
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
- memtx_memory
- memtx_max_tuple_size
- memtx_min_tuple_size
- memtx_allocator
- slab_alloc_factor
- slab_alloc_granularity
- vinyl_bloom_fpr
- vinyl_cache
- vinyl_max_tuple_size
- vinyl_memory
- vinyl_page_size
- vinyl_range_size
- vinyl_run_count_per_level
- vinyl_run_size_ratio
- vinyl_read_threads
- vinyl_write_threads
-
memtx_memory
¶ Для версий от 1.7.4. и выше. Количество памяти, которое Tarantool выделяет для фактического хранения кортежей. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку
ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памятиmemtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше пределаmemtx_memory
.Тип: число с плавающей запятойПо умолчанию: 256 * 1024 * 1024 = 268435456 байтовMinimum: 33554432 bytes (32 MB)Environment variable: TT_MEMTX_MEMORYДинамический: да, но нельзя уменьшить
-
memtx_max_tuple_size
¶ Для версий от 1.7.4. и выше. Размер наибольшего блока выделения памяти для движка базы данных memtx. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также vinyl_max_tuple_size.
Тип: целое числоПо умолчанию: 1024 * 1024 = 1048576 байтовEnvironment variable: TT_MEMTX_MAX_TUPLE_SIZEДинамический: да
-
memtx_min_tuple_size
¶ Для версий от 1.7.4. и выше. Размер наименьшего блока выделения памяти . Его можно уменьшить, если кортежи очень малого размера. Значение должно быть от 8 до 1 048 280 включительно.
Тип: целое числоПо умолчанию: 16 байтовEnvironment variable: TT_MEMTX_MIN_TUPLE_SIZEДинамический: нет
-
memtx_allocator
¶ Since version 2.10.0. Specifies the allocator used for memtx tuples. The possible values are
system
andsmall
:system
is based on themalloc
function. This allocator allocates memory as needed, checking that the quota is not exceeded.small
is a special slab allocator. Note that this allocator is prone to unresolvable fragmentation on specific workloads, so you can switch tosystem
in such cases.
Тип: строкаDefault: „small“Environment variable: TT_MEMTX_ALLOCATORDynamic: No
-
slab_alloc_factor
¶ Множитель для вычисления размеров блоков памяти, в которых хранятся кортежи. Уменьшение значения может привести к уменьшению потерь памяти в зависимости от общего объема доступной памяти и распределения размеров элементов. Допустимые значения: от 1 до 2.
See also: slab_alloc_granularity
Тип: число с плавающей запятойDefault: 1.05Environment variable: TT_SLAB_ALLOC_FACTORДинамический: нет
-
slab_alloc_granularity
¶ Since version 2.8.1. Specifies the granularity (in bytes) of memory allocation in the small allocator. The value of
slab_alloc_granularity
should be a power of two and should be greater than or equal to 4. Below are few recommendations on how to adjust theslab_alloc_granularity
value:- To store small tuples of approximately the same size, set
slab_alloc_granularity
to 4 bytes to save memory. - To store tuples of different sizes, you can increase the
slab_alloc_granularity
value. This results in allocating tuples from the samemempool
.
See also: slab_alloc_factor
Тип: числоDefault: 8 bytesEnvironment variable: TT_SLAB_ALLOC_GRANULARITYДинамический: нет- To store small tuples of approximately the same size, set
-
vinyl_bloom_fpr
¶ Для версий от 1.7.4. и выше. Доля ложноположительного срабатывания фильтра Блума – подходящая вероятность того, что фильтр Блума выдаст ошибочный результат. Настройка
vinyl_bloom_fpr
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().Тип: число с плавающей запятойПо умолчанию: 0.05Environment variable: TT_VINYL_BLOOM_FPRДинамический: нет
-
vinyl_cache
¶ Для версий от 1.7.4. и выше. Размер кэша для движка базы данных vinyl. Размер кэша можно изменить динамически.
Тип: целое числоПо умолчанию: 128 * 1024 * 1024 = 134217728 байтовEnvironment variable: TT_VINYL_CACHEДинамический: да
-
vinyl_max_tuple_size
¶ Для версий от 1.7.5. и выше. Размер наибольшего блока выделения памяти для движка базы данных vinyl. Его можно увеличить, если есть необходимость в хранении больших кортежей. См. также memtx_max_tuple_size.
Тип: целое числоПо умолчанию: 1024 * 1024 = 1048576 байтовEnvironment variable: TT_VINYL_MAX_TUPLE_SIZEДинамический: нет
-
vinyl_memory
¶ Для версий от 1.7.4. и выше. Максимальное количество байтов оперативной памяти, которые использует vinyl.
Тип: целое числоПо умолчанию: 128 * 1024 * 1024 = 134217728 байтовEnvironment variable: TT_VINYL_MEMORYДинамический: да, но нельзя уменьшить
-
vinyl_page_size
¶ Для версий от 1.7.4. и выше. Размер страницы в байтах. Страница представляет собой блок чтения и записи для операций на диске vinyl. Настройка
vinyl_page_size
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().Тип: целое числоПо умолчанию: 8 * 1024 = 8192 байтовEnvironment variable: TT_VINYL_PAGE_SIZEДинамический: нет
-
vinyl_range_size
¶ Для версий от 1.7.4. и выше. Максимальный размер диапазона для индекса vinyl в байтах. Максимальный размер диапазона влияет на принятие решения о разделении диапазона.
Если
vinyl_range_size
содержит не нулевое значение nil и не 0, это значение используется в качестве значения по умолчанию для параметраrange_size
в таблице Параметры space_object:create_index().Если
vinyl_range_size
содержит нулевое значение nil или 0, а параметрrange_size
не задан при создании индекса, то Tarantool сам задает это значение позднее в результате оценки производительности. Чтобы узнать текущее значение, используйте index_object:stat().range_size.До версии Tarantool 1.10.2 значение
vinyl_range_size
по умолчанию было 1073741824.Тип: целое числоПо умолчанию: nilEnvironment variable: TT_VINYL_RANGE_SIZEДинамический: нет
-
vinyl_run_count_per_level
¶ Для версий от 1.7.4. и выше. Максимальное количество забегов на уровень журнально-структурированного дерева со слиянием в vinyl’е. Настройка
vinyl_run_count_per_level
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().Тип: целое числоПо умолчанию: 2Environment variable: TT_VINYL_RUN_COUNT_PER_LEVELДинамический: нет
-
vinyl_run_size_ratio
¶ Для версий от 1.7.4. и выше. Отношение размеров различных уровней журнально-структурированного дерева со слиянием. Настройка
vinyl_run_size_ratio
– это значение, которое используется по умолчанию для одного из параметров в таблице Параметры space_object:create_index().Тип: число с плавающей запятойПо умолчанию: 3.5Environment variable: TT_VINYL_RUN_SIZE_RATIOДинамический: нет
-
vinyl_read_threads
¶ Для версий от 1.7.5. и выше. Максимальное количество потоков чтения, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое числоПо умолчанию: 1Environment variable: TT_VINYL_READ_THREADSДинамический: нет
-
vinyl_write_threads
¶ Для версий от 1.7.5. и выше. Максимальное количество потоков записи, которые vinyl может использовать в одновременных операциях, такие как ввод-вывод и компрессия.
Тип: целое числоПо умолчанию: 4Environment variable: TT_VINYL_WRITE_THREADSДинамический: нет
Демон создания контрольных точек
Демон создания контрольных точек – это постоянно работающий файбер. Периодически он может создавать файлы снимка (.snap), а затем может удалять старые файлы снимка.
Настройки конфигурации checkpoint_interval и checkpoint_count определяют длительность интервалов и количество снимков, которое должно присутствовать до начала удалений.
Сборщик мусора Tarantool
Демон создания контрольных точек может запустить сборщик мусора Tarantool, который удаляет старые файлы. Такой сборщик мусора не отличается от сборщика мусора в Lua, который предназначен для Lua-объектов, и от сборщика мусора, который специализируется на обработке блоков шарда.
Если демон создания контрольных точек удаляет старый файл снимка, сборщик мусора Tarantool также удалит любые файлы журнала упреждающей записи (.xlog) старше файла снимка, содержащие информацию, которая присутствует в файле снимка. Он также удаляет устаревшие файлы .run
в vinyl’е.
Демон создания контрольных точек и сборщик мусора Tarantool не удалят файл, если:
- идет резервное копирование, и файл еще не был скопирован (см. «Резервное копирование»), или
- идет репликация, и файл еще не был передан на реплику (см. «Архитектуру механизма репликации»),
- реплика подключается, или
- реплика отстает. Ход выполнения на каждой реплике отслеживается. Если реплика далеко не актуальна, сервер останавливается, чтобы она могла обновиться. Если администратор делает вывод, что реплика окончательно недоступна, необходимо перезагрузить сервер или же (предпочтительно) удалить реплику из кластера.
-
checkpoint_interval
¶
Для версий от 1.7.4. и выше. Промежуток времени между действиями демона создания контрольных точек в секундах. Если значение параметра checkpoint_interval
больше нуля, и выполняется изменение базы данных, то демон создания контрольных точек будет вызывать box.snapshot() каждые checkpoint_interval
секунд, каждый раз создавая новый файл снимка. Если значение параметра checkpoint_interval
равно нулю, то демон создания контрольных точек отключен.
Пример:
box.cfg{checkpoint_interval=60}
приведет к созданию нового снимка базы данных демоном создания контрольных точек каждую минуту, если наблюдается активность в базе данных.
Тип: целое число
По умолчанию: 3600 (один час)
Environment variable: TT_CHECKPOINT_INTERVAL
Динамический: да
-
checkpoint_count
¶
Для версий от 1.7.4. и выше. Максимальное количество снимков, которые могут находиться в директории memtx_dir до того, как демон создания контрольных точек будет удалять старые снимки. Если значение checkpoint_count
равно нулю, то демон создания контрольных точек не удаляет старые снимки. Например:
box.cfg{
checkpoint_interval = 3600,
checkpoint_count = 10
}
заставит демон создания контрольных точек создавать снимок каждый час до тех пор, пока не будет создано десять снимков. Затем самый старый снимок удаляется (а также любые связанные с ним WAL-файлы) после создания нового снимка.
Следует помнить, что как упоминалось выше, снимки не удаляются, если выполняется репликация, и файл еще не был передан на реплику. Таким образом, параметр checkpoint_count
бесполезен, если какая-то реплика неактивна.
Тип: целое число
По умолчанию: 2
Environment variable: TT_CHECKPOINT_COUNT
Динамический: да
-
checkpoint_wal_threshold
¶
Для версий от 2.1.2. и выше. Порог общего размера в байтах всех файлов WAL, созданных с момента последней контрольной точки. После превышения настроенного порога поток WAL уведомляет демона контрольной точки о том, что он должен создать новую контрольную точку и удалить старые файлы WAL.
Этот параметр позволяет администраторам справиться с проблемой, которая может возникнуть при вычислении объема дискового пространства для раздела, содержащего файлы WAL.
Например, предположим, что checkpoint_interval = 2 и checkpoint_count = 5 и в среднем за каждый интервал Tarantool записывает 1 Гб. Тогда можно будет вычислить, что необходимо (2*5*1) 10 Гб. Но это вычисление было бы неправильным, если бы вместо записи 1 ГБ в течение одного интервала между контрольными точками, Tarantool столкнулся с необычным всплеском и попытался записать 11 ГБ, что привело бы к ошибке операционной системы ENOSPC («нет места»). Установив значение checkpoint_wal_threshold
на меньшее, скажем, 9 Гб, администратор может предотвратить ошибку.
Тип: целое число
По умолчанию: 10^18 (большое число: можно считать, что предела нет)
Environment variable: TT_CHECKPOINT_WAL_THRESHOLD
Динамический: да
Записи в бинарный журнал и создание снимков
- force_recovery
- wal_max_size
- snap_io_rate_limit
- wal_mode
- wal_dir_rescan_delay
- wal_queue_max_size
- wal_cleanup_delay
-
force_recovery
¶
Для версий от 1.7.4. и выше. Если значение force_recovery
равно true (правда), Tarantool пытается продолжать работу при обнаружении ошибки во время чтения файла снимка (при запуске экземпляра сервера) или файла журнала упреждающей записи (при запуске экземпляра сервера или применении обновлений к реплике): пропускает нерабочие записи, считывает максимальное количество данных и позволяет завершить процесс предупреждением. Пользователи могут предотвратить повторное появление ошибки, записав данные в базу и выполнив box.snapshot().
В остальных случаях Tarantool прерывает восстановление на ошибке чтения.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_FORCE_RECOVERY
Динамический: нет
-
wal_max_size
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов в отдельном журнале упреждающей записи. Если в результате запроса файл .xlog будет больше, чем указано в параметре wal_max_size
, Tarantool создает другой WAL-файл – то же самое происходит, когда достигнуто количество строк в журнале, указанное в rows_per_wal.
Тип: целое число
По умолчанию: 268435456 (256 * 1024 * 1024) байтов
Environment variable: TT_WAL_MAX_SIZE
Динамический: нет
-
snap_io_rate_limit
¶
Для версий от 1.4.9. и выше. Уменьшение загрузки box.snapshot() при выполнении операций вставки, обновления и удаления (INSERT/UPDATE/DELETE) путем установки предела скорости записи на диск – количества мегабайт в секунду. Того же эффекта можно достичь, разделив директории wal_dir и memtx_dir и перенося снимки на отдельный диск. Такой предел также ограничивает результат box.stat.vinyl().regulator относительно скорости записи дампов в файлы формата .run и .index.
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_SNAP_IO_RATE_LIMIT
Динамический: да
-
wal_mode
¶
Для версий от 1.6.2. и выше. Определение синхронизации работы файбера с журналом упреждающей записи:
none
: журнал упреждающей записи не поддерживается. Узел с wal_mode = none
при репликации не может быть мастером;
write
: файберы ожидают записи данных в журнал упреждающей записи (не fsync(2));
fsync
: файберы ожидают данные, синхронизация fsync(2) следует за каждой операцией записи write(2);
Тип: строка
По умолчанию: «write»
Environment variable: TT_WAL_MODE
Динамический: нет
-
wal_dir_rescan_delay
¶
Для версий от 1.6.2. и выше. Количество секунд между периодическим сканирование директории WAL-файла при проверке изменений в WAL-файле для целей репликации или горячего резервирования.
Тип: число с плавающей запятой
По умолчанию: 2
Environment variable: TT_WAL_DIR_RESCAN_DELAY
Динамический: нет
-
wal_queue_max_size
¶
Since version 2.8.1.
The size of the queue (in bytes) used by a replica to submit
new transactions to a write-ahead log (WAL).
This option helps limit the rate at which a replica submits transactions to the WAL.
Limiting the queue size might be useful when a replica is trying to sync with a master and
reads new transactions faster than writing them to the WAL.
Примечание
You might consider increasing the wal_queue_max_size
value in case of
large tuples (approximately one megabyte or larger).
Тип: число
Default: 16777216 bytes
Environment variable: TT_WAL_QUEUE_MAX_SIZE
Динамический: да
-
wal_cleanup_delay
¶
Since version 2.6.3.
The delay (in seconds) used to prevent the Tarantool garbage collector
from immediately removing write-ahead log files after a node restart.
This delay eliminates possible erroneous situations when the master deletes WALs
needed by replicas after restart.
As a consequence, replicas sync with the master faster after its restart and
don’t need to download all the data again.
Once all the nodes in the replica set are up and running,
automatic cleanup is started again even if wal_cleanup_delay
has not expired.
Примечание
The wal_cleanup_delay
option has no effect on nodes running as
anonymous replicas.
Тип: число
Default: 14400 seconds
Environment variable: TT_WAL_CLEANUP_DELAY
Динамический: да
Горячее резервирование
-
hot_standby
¶
Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словами I> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.
Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словами I> ready to accept requests
(готов принимать запросы).
Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд.
- если wal_mode = „none“; будет работать только при
wal_mode = 'write'
или wal_mode = 'fsync'
.
- со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_HOT_STANDBY
Динамический: нет
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
Демон создания контрольных точек – это постоянно работающий файбер. Периодически он может создавать файлы снимка (.snap), а затем может удалять старые файлы снимка.
Настройки конфигурации checkpoint_interval и checkpoint_count определяют длительность интервалов и количество снимков, которое должно присутствовать до начала удалений.
Сборщик мусора Tarantool
Демон создания контрольных точек может запустить сборщик мусора Tarantool, который удаляет старые файлы. Такой сборщик мусора не отличается от сборщика мусора в Lua, который предназначен для Lua-объектов, и от сборщика мусора, который специализируется на обработке блоков шарда.
Если демон создания контрольных точек удаляет старый файл снимка, сборщик мусора Tarantool также удалит любые файлы журнала упреждающей записи (.xlog) старше файла снимка, содержащие информацию, которая присутствует в файле снимка. Он также удаляет устаревшие файлы .run
в vinyl’е.
Демон создания контрольных точек и сборщик мусора Tarantool не удалят файл, если:
- идет резервное копирование, и файл еще не был скопирован (см. «Резервное копирование»), или
- идет репликация, и файл еще не был передан на реплику (см. «Архитектуру механизма репликации»),
- реплика подключается, или
- реплика отстает. Ход выполнения на каждой реплике отслеживается. Если реплика далеко не актуальна, сервер останавливается, чтобы она могла обновиться. Если администратор делает вывод, что реплика окончательно недоступна, необходимо перезагрузить сервер или же (предпочтительно) удалить реплику из кластера.
-
checkpoint_interval
¶ Для версий от 1.7.4. и выше. Промежуток времени между действиями демона создания контрольных точек в секундах. Если значение параметра
checkpoint_interval
больше нуля, и выполняется изменение базы данных, то демон создания контрольных точек будет вызывать box.snapshot() каждыеcheckpoint_interval
секунд, каждый раз создавая новый файл снимка. Если значение параметраcheckpoint_interval
равно нулю, то демон создания контрольных точек отключен.Пример:
box.cfg{checkpoint_interval=60}
приведет к созданию нового снимка базы данных демоном создания контрольных точек каждую минуту, если наблюдается активность в базе данных.
Тип: целое числоПо умолчанию: 3600 (один час)Environment variable: TT_CHECKPOINT_INTERVALДинамический: да
-
checkpoint_count
¶ Для версий от 1.7.4. и выше. Максимальное количество снимков, которые могут находиться в директории memtx_dir до того, как демон создания контрольных точек будет удалять старые снимки. Если значение
checkpoint_count
равно нулю, то демон создания контрольных точек не удаляет старые снимки. Например:box.cfg{ checkpoint_interval = 3600, checkpoint_count = 10 }
заставит демон создания контрольных точек создавать снимок каждый час до тех пор, пока не будет создано десять снимков. Затем самый старый снимок удаляется (а также любые связанные с ним WAL-файлы) после создания нового снимка.
Следует помнить, что как упоминалось выше, снимки не удаляются, если выполняется репликация, и файл еще не был передан на реплику. Таким образом, параметр
checkpoint_count
бесполезен, если какая-то реплика неактивна.Тип: целое числоПо умолчанию: 2Environment variable: TT_CHECKPOINT_COUNTДинамический: да
-
checkpoint_wal_threshold
¶ Для версий от 2.1.2. и выше. Порог общего размера в байтах всех файлов WAL, созданных с момента последней контрольной точки. После превышения настроенного порога поток WAL уведомляет демона контрольной точки о том, что он должен создать новую контрольную точку и удалить старые файлы WAL.
Этот параметр позволяет администраторам справиться с проблемой, которая может возникнуть при вычислении объема дискового пространства для раздела, содержащего файлы WAL.
Например, предположим, что checkpoint_interval = 2 и checkpoint_count = 5 и в среднем за каждый интервал Tarantool записывает 1 Гб. Тогда можно будет вычислить, что необходимо (2*5*1) 10 Гб. Но это вычисление было бы неправильным, если бы вместо записи 1 ГБ в течение одного интервала между контрольными точками, Tarantool столкнулся с необычным всплеском и попытался записать 11 ГБ, что привело бы к ошибке операционной системы ENOSPC («нет места»). Установив значение
checkpoint_wal_threshold
на меньшее, скажем, 9 Гб, администратор может предотвратить ошибку.Тип: целое числоПо умолчанию: 10^18 (большое число: можно считать, что предела нет)Environment variable: TT_CHECKPOINT_WAL_THRESHOLDДинамический: да
Записи в бинарный журнал и создание снимков
- force_recovery
- wal_max_size
- snap_io_rate_limit
- wal_mode
- wal_dir_rescan_delay
- wal_queue_max_size
- wal_cleanup_delay
-
force_recovery
¶
Для версий от 1.7.4. и выше. Если значение force_recovery
равно true (правда), Tarantool пытается продолжать работу при обнаружении ошибки во время чтения файла снимка (при запуске экземпляра сервера) или файла журнала упреждающей записи (при запуске экземпляра сервера или применении обновлений к реплике): пропускает нерабочие записи, считывает максимальное количество данных и позволяет завершить процесс предупреждением. Пользователи могут предотвратить повторное появление ошибки, записав данные в базу и выполнив box.snapshot().
В остальных случаях Tarantool прерывает восстановление на ошибке чтения.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_FORCE_RECOVERY
Динамический: нет
-
wal_max_size
¶
Для версий от 1.7.4. и выше. Максимальное количество байтов в отдельном журнале упреждающей записи. Если в результате запроса файл .xlog будет больше, чем указано в параметре wal_max_size
, Tarantool создает другой WAL-файл – то же самое происходит, когда достигнуто количество строк в журнале, указанное в rows_per_wal.
Тип: целое число
По умолчанию: 268435456 (256 * 1024 * 1024) байтов
Environment variable: TT_WAL_MAX_SIZE
Динамический: нет
-
snap_io_rate_limit
¶
Для версий от 1.4.9. и выше. Уменьшение загрузки box.snapshot() при выполнении операций вставки, обновления и удаления (INSERT/UPDATE/DELETE) путем установки предела скорости записи на диск – количества мегабайт в секунду. Того же эффекта можно достичь, разделив директории wal_dir и memtx_dir и перенося снимки на отдельный диск. Такой предел также ограничивает результат box.stat.vinyl().regulator относительно скорости записи дампов в файлы формата .run и .index.
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_SNAP_IO_RATE_LIMIT
Динамический: да
-
wal_mode
¶
Для версий от 1.6.2. и выше. Определение синхронизации работы файбера с журналом упреждающей записи:
none
: журнал упреждающей записи не поддерживается. Узел с wal_mode = none
при репликации не может быть мастером;
write
: файберы ожидают записи данных в журнал упреждающей записи (не fsync(2));
fsync
: файберы ожидают данные, синхронизация fsync(2) следует за каждой операцией записи write(2);
Тип: строка
По умолчанию: «write»
Environment variable: TT_WAL_MODE
Динамический: нет
-
wal_dir_rescan_delay
¶
Для версий от 1.6.2. и выше. Количество секунд между периодическим сканирование директории WAL-файла при проверке изменений в WAL-файле для целей репликации или горячего резервирования.
Тип: число с плавающей запятой
По умолчанию: 2
Environment variable: TT_WAL_DIR_RESCAN_DELAY
Динамический: нет
-
wal_queue_max_size
¶
Since version 2.8.1.
The size of the queue (in bytes) used by a replica to submit
new transactions to a write-ahead log (WAL).
This option helps limit the rate at which a replica submits transactions to the WAL.
Limiting the queue size might be useful when a replica is trying to sync with a master and
reads new transactions faster than writing them to the WAL.
Примечание
You might consider increasing the wal_queue_max_size
value in case of
large tuples (approximately one megabyte or larger).
Тип: число
Default: 16777216 bytes
Environment variable: TT_WAL_QUEUE_MAX_SIZE
Динамический: да
-
wal_cleanup_delay
¶
Since version 2.6.3.
The delay (in seconds) used to prevent the Tarantool garbage collector
from immediately removing write-ahead log files after a node restart.
This delay eliminates possible erroneous situations when the master deletes WALs
needed by replicas after restart.
As a consequence, replicas sync with the master faster after its restart and
don’t need to download all the data again.
Once all the nodes in the replica set are up and running,
automatic cleanup is started again even if wal_cleanup_delay
has not expired.
Примечание
The wal_cleanup_delay
option has no effect on nodes running as
anonymous replicas.
Тип: число
Default: 14400 seconds
Environment variable: TT_WAL_CLEANUP_DELAY
Динамический: да
Горячее резервирование
-
hot_standby
¶
Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словами I> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.
Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словами I> ready to accept requests
(готов принимать запросы).
Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд.
- если wal_mode = „none“; будет работать только при
wal_mode = 'write'
или wal_mode = 'fsync'
.
- со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_HOT_STANDBY
Динамический: нет
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
- force_recovery
- wal_max_size
- snap_io_rate_limit
- wal_mode
- wal_dir_rescan_delay
- wal_queue_max_size
- wal_cleanup_delay
-
force_recovery
¶ Для версий от 1.7.4. и выше. Если значение
force_recovery
равно true (правда), Tarantool пытается продолжать работу при обнаружении ошибки во время чтения файла снимка (при запуске экземпляра сервера) или файла журнала упреждающей записи (при запуске экземпляра сервера или применении обновлений к реплике): пропускает нерабочие записи, считывает максимальное количество данных и позволяет завершить процесс предупреждением. Пользователи могут предотвратить повторное появление ошибки, записав данные в базу и выполнив box.snapshot().В остальных случаях Tarantool прерывает восстановление на ошибке чтения.
Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_FORCE_RECOVERYДинамический: нет
-
wal_max_size
¶ Для версий от 1.7.4. и выше. Максимальное количество байтов в отдельном журнале упреждающей записи. Если в результате запроса файл .xlog будет больше, чем указано в параметре
wal_max_size
, Tarantool создает другой WAL-файл – то же самое происходит, когда достигнуто количество строк в журнале, указанное в rows_per_wal.Тип: целое числоПо умолчанию: 268435456 (256 * 1024 * 1024) байтовEnvironment variable: TT_WAL_MAX_SIZEДинамический: нет
-
snap_io_rate_limit
¶ Для версий от 1.4.9. и выше. Уменьшение загрузки box.snapshot() при выполнении операций вставки, обновления и удаления (INSERT/UPDATE/DELETE) путем установки предела скорости записи на диск – количества мегабайт в секунду. Того же эффекта можно достичь, разделив директории wal_dir и memtx_dir и перенося снимки на отдельный диск. Такой предел также ограничивает результат box.stat.vinyl().regulator относительно скорости записи дампов в файлы формата .run и .index.
Тип: число с плавающей запятойПо умолчанию: nullEnvironment variable: TT_SNAP_IO_RATE_LIMITДинамический: да
-
wal_mode
¶ Для версий от 1.6.2. и выше. Определение синхронизации работы файбера с журналом упреждающей записи:
none
: журнал упреждающей записи не поддерживается. Узел сwal_mode = none
при репликации не может быть мастером;write
: файберы ожидают записи данных в журнал упреждающей записи (не fsync(2));fsync
: файберы ожидают данные, синхронизация fsync(2) следует за каждой операцией записи write(2);
Тип: строкаПо умолчанию: «write»Environment variable: TT_WAL_MODEДинамический: нет
-
wal_dir_rescan_delay
¶ Для версий от 1.6.2. и выше. Количество секунд между периодическим сканирование директории WAL-файла при проверке изменений в WAL-файле для целей репликации или горячего резервирования.
Тип: число с плавающей запятойПо умолчанию: 2Environment variable: TT_WAL_DIR_RESCAN_DELAYДинамический: нет
-
wal_queue_max_size
¶ Since version 2.8.1. The size of the queue (in bytes) used by a replica to submit new transactions to a write-ahead log (WAL). This option helps limit the rate at which a replica submits transactions to the WAL. Limiting the queue size might be useful when a replica is trying to sync with a master and reads new transactions faster than writing them to the WAL.
Примечание
You might consider increasing the
wal_queue_max_size
value in case of large tuples (approximately one megabyte or larger).Тип: числоDefault: 16777216 bytesEnvironment variable: TT_WAL_QUEUE_MAX_SIZEДинамический: да
-
wal_cleanup_delay
¶ Since version 2.6.3. The delay (in seconds) used to prevent the Tarantool garbage collector from immediately removing write-ahead log files after a node restart. This delay eliminates possible erroneous situations when the master deletes WALs needed by replicas after restart. As a consequence, replicas sync with the master faster after its restart and don’t need to download all the data again.
Once all the nodes in the replica set are up and running, automatic cleanup is started again even if
wal_cleanup_delay
has not expired.Примечание
The
wal_cleanup_delay
option has no effect on nodes running as anonymous replicas.Тип: числоDefault: 14400 secondsEnvironment variable: TT_WAL_CLEANUP_DELAYДинамический: да
Горячее резервирование
-
hot_standby
¶
Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словами I> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.
Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словами I> ready to accept requests
(готов принимать запросы).
Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд.
- если wal_mode = „none“; будет работать только при
wal_mode = 'write'
или wal_mode = 'fsync'
.
- со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_HOT_STANDBY
Динамический: нет
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
-
hot_standby
¶ Для версий от 1.7.4. и выше. Запуск сервера в режиме горячего резервирования.
Горячее резервирование – это функция, которая обеспечивает простое восстановление после отказа без репликации.
Предполагается, что есть два экземпляра сервера, использующих одну и ту же конфигурацию. Первый из них станет «основным» экземпляром. Тот, который запускается вторым, станет «резервным» экземпляром.
Чтобы создать резервный экземпляр, запустите второй экземпляр Tarantool-сервера на том же компьютере с теми же настройками конфигурации box.cfg – включая одинаковые директории и ненулевые URI – и с дополнительной настройкой конфигурации
hot_standby = true
. В ближайшее время вы увидите уведомление, которое заканчивается словамиI> Entering hot standby mode
(вход в режим горячего резервирования). Всё в порядке – это означает, что резервный экземпляр готов взять работу на себя, если основной экземпляр прекратит работу.Резервный экземпляр начнет инициализацию и попытается заблокировать wal_dir, но не сможет, поскольку директория
wal_dir
заблокирована основным экземпляром. Поэтому резервный экземпляр входит в цикл, выполняя чтение журнала упреждающей записи, в который записывает данные основной экземпляр (поэтому два экземпляра всегда синхронизированы), и пытаясь произвести блокировку. Если основной экземпляр по какой-либо причине прекращает работу, блокировка снимается. В таком случае резервный экземпляр сможет заблокировать директорию на себя, подключится по адресу для прослушивания и станет основным экземпляром. В ближайшее время вы увидите уведомление, которое заканчивается словамиI> ready to accept requests
(готов принимать запросы).Таким образом, если основной экземпляр прекращает работу, время простоя отсутствует.
Функция горячего резервирования не работает:
- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
wal_dir_rescan_delay
секунд. - если wal_mode = „none“; будет работать только при
wal_mode = 'write'
илиwal_mode = 'fsync'
. - со спейсами, созданными на движке vinyl engine = „vinyl“; работает с движком memtx
engine = 'memtx'
.
Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_HOT_STANDBYДинамический: нет- если wal_dir_rescan_delay = большое число (в Mac OS и FreeBSD); на этих платформах цикл запрограммирован на повторение каждые
Репликация
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶
Для версий от 1.7.4. и выше. Если replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметре replication
по URI (унифицированному идентификатору ресурса), например:
konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the
instance where box.cfg{}
is being executed – then it is ignored.
Thus, it is possible to use the same replication
specification on
multiple server instances, as shown in
these examples.
По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметру replication
пустую строку и выполнить следующее:
box.cfg{ replication = новое-значение }
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICATION
Динамический: да
-
replication_anon
¶
Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице _cluster
.
Since an anonymous replica isn’t registered in the _cluster space,
there is no limitation for anonymous replicas count in a replica set:
you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию replication_anon=true
в box.cfg
и установите значение read_only
равным true
.
Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true})
box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к box.cfg
, как обычно.
box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше, replication_anon
может быть true
только вместе с read_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.
tarantool> box.info.id
---
- 0
...
tarantool> box.info.replication
---
- 1:
id: 1
uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f
lsn: 4
upstream:
status: follow
idle: 0.6912029999985
peer:
lag: 0.00014615058898926
...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do
> box.space.loc:insert{i}
> end
---
...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его vclock
:
tarantool> box.info.vclock
---
- {0: 10, 1: 4}
...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false}
2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661
2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false
---
...
tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed
2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5}
2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false}
2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false
---
...
tarantool> box.schema.space.create('test')
---
- engine: memtx
before_replace: 'function: 0x01109f9dc8'
on_replace: 'function: 0x01109f9d90'
ck_constraint: []
field_count: 0
temporary: false
index: []
is_local: false
enabled: false
name: test
id: 513
- created
...
tarantool> box.info.vclock
---
- {0: 10, 1: 5, 2: 2}
...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_ANON
Динамический: да
-
bootstrap_strategy
¶
Since 2.11.0.
Specifies a strategy used to bootstrap a replica set.
The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected.
For example, if the replication parameter contains 2 or 3 nodes,
a node requires 2 connected instances.
In the case of 4 or 5 nodes, at least 3 connected instances are required.
Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.
legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected.
This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строка
Default: auto
Environment variable: TT_BOOTSTRAP_STRATEGY
Динамический: да
-
replication_connect_timeout
¶
Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from
replication_timeout,
which a master uses to disconnect a replica when the master
receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятой
По умолчанию: 30
Environment variable: TT_REPLICATION_CONNECT_TIMEOUT
Динамический: да
-
replication_connect_quorum
¶
Deprecated since 2.11.0.
This option is in effect if bootstrap_strategy is set to legacy
.
Specifies the number of nodes to be up and running to start a replica set.
This parameter has effect during bootstrap or
configuration update.
Setting replication_connect_quorum
to 0
makes Tarantool
require no immediate reconnect only in case of recovery.
See Orphan status for details.
Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое число
По умолчанию: null
Environment variable: TT_REPLICATION_CONNECT_QUORUM
Динамический: да
-
replication_skip_conflict
¶
Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записано NOP
(No operation).
Пример:
box.cfg{replication_skip_conflict=true}
Тип: логический
По умолчанию: false (ложь)
Environment variable: TT_REPLICATION_SKIP_CONFLICT
Динамический: да
Примечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶
Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно replication_sync_lag
.
Если пользователь задает значение replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.
Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятой
По умолчанию: 10
Environment variable: TT_REPLICATION_SYNC_LAG
Динамический: да
-
replication_sync_timeout
¶
Since version 1.10.2.
The number of seconds that a node waits when trying to sync with
other nodes in a replica set (see bootstrap_strategy),
after connecting or during configuration update.
This could fail indefinitely if replication_sync_lag
is smaller
than network latency, or if the replica cannot keep pace with master
updates. If replication_sync_timeout
expires, the replica
enters orphan status.
Тип: число с плавающей запятой
По умолчанию: 300
Environment variable: TT_REPLICATION_SYNC_TIMEOUT
Динамический: да
Примечание
The default replication_sync_timeout
value is going to be changed in future versions from 300
to 0
.
You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶
Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.
И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.
См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое число
По умолчанию: 1
Environment variable: TT_REPLICATION_TIMEOUT
Динамический: да
-
replicaset_uuid
¶
Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (replicaset_uuid
) при первом запуске.
Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме 8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).
Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строка
По умолчанию: null
Environment variable: TT_REPLICASET_UUID
Динамический: нет
-
instance_uuid
¶
Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.
Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строка
По умолчанию: null
Environment variable: TT_INSTANCE_UUID
Динамический: нет
-
replication_synchro_quorum
¶
Since version 2.5.1.
For synchronous replication only.
This option tells how many replicas should confirm the receipt of a
synchronous transaction before it can finish its commit.
Since version 2.5.3,
the option supports dynamic evaluation of the quorum number.
That is, the number of quorum can be specified not as a constant number, but as a function instead.
In this case, the option returns the formula evaluated.
The result is treated as an integer number.
Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where N
is a current number of registered replicas in a cluster.
Keep in mind that the example above represents a canonical quorum definition.
The formula at least 50% of the cluster size + 1
guarantees data reliability.
Using a value less than the canonical one might lead to unexpected results,
including a split-brain.
Since version 2.10.0, this option
does not account for anonymous replicas.
По умолчанию значение параметра равно N / 2 + 1
.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно 1
, синхронные транзакции работают как асинхронные, пока они не настроены. 1
означает, что для коммита достаточно успешной записи в WAL на мастере.
Тип: число
Default: N / 2 + 1 (before version 2.10.0, the default value was 1)
Environment variable: TT_REPLICATION_SYNCHRO_QUORUM
Динамический: да
-
replication_synchro_timeout
¶
Since version 2.5.1.
For synchronous replication only.
Tells how many seconds to wait for a synchronous transaction quorum
replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: число
По умолчанию: 5
Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUT
Динамический: да
-
replication_threads
¶
Since version 2.10.0.
The number of threads spawned to decode the incoming replication data.
The default value is 1
.
It means that a single separate thread handles all the incoming replication streams.
In most cases, one thread is enough for all incoming data.
Therefore, it is likely that the user will not need to set this configuration option.
Possible values range from 1 to 1000.
If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: число
По умолчанию: 1
Possible values: from 1 to 1000
Environment variable: TT_REPLICATION_THREADS
Dynamic: no
-
election_mode
¶
Since version 2.6.1.
Specifies the role of a replica set node in the
leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be
turned on and off by this option.
The default value is off
. All nodes that have values other than off
run the Raft state machine internally talking to other nodes according
to the Raft leader election protocol. When the option is off
, the node
accepts Raft messages
from other nodes, but it doesn’t participate in the election activities,
and this doesn’t affect the node’s state. So, for example, if a node is not
a leader but it has election_mode = 'off'
, it is writable anyway.
You can control which nodes can become a leader. If you want a node
to participate in the election process but don’t want that it becomes
a leaders, set the election_mode
option to voter
. In this case,
the election works as usual, this particular node will vote for other nodes,
but won’t become a leader.
If the node should be able to become a leader, use election_mode = 'candidate'
.
Since version 2.8.2, the manual election mode is introduced.
It may be used when a user wants to control which instance is the leader explicitly instead of relying on
the Raft election algorithm.
When an instance is configured with the election_mode='manual'
, it behaves as follows:
- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round.
If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строка
Default: „off“
Environment variable: TT_ELECTION_MODE
Динамический: да
-
election_timeout
¶
Since version 2.6.1.
Specifies the timeout between election rounds in the
leader election process if the previous round
ended up with a split-vote.
In the leader election process, there
can be an election timeout for the case of a split-vote.
The timeout can be configured using this option; the default value is
5 seconds.
It is quite big, and for most of the cases it can be freely lowered to
300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).
To avoid the split vote repeat, the timeout is randomized on each node
during every new election, from 100% to 110% of the original timeout value.
For example, if the timeout is 300 ms and there are 3 nodes started
the election simultaneously in the same term,
they can set their election timeouts to 300, 310, and 320 respectively,
or to 305, 302, and 324, and so on. In that way, the votes will never be split
because the election on different nodes won’t be restarted simultaneously.
Тип: число
По умолчанию: 5
Environment variable: TT_ELECTION_TIMEOUT
Динамический: да
-
election_fencing_mode
¶
Since version 2.11.0.
In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that
affects the leader election process. When the parameter is set to soft
or strict
, the leader resigns its leadership if it has less than
replication_synchro_quorum
of alive connections to the cluster nodes.
The resigning leader receives the status of a
follower in the current election term and becomes
read-only.
- In
soft
mode, a connection is considered dead if there are no responses for
4*replication_timeout seconds both on the current leader and the followers.
- In
strict
mode, a connection is considered dead if there are no responses
for 2*replication_timeout seconds on the
current leader and
4*replication_timeout seconds on the
followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the
election_mode set to candidate
or manual
.
To turn off leader fencing, set election_fencing_mode
to off
.
Тип: строка
Default: „soft“
Environment variable: TT_ELECTION_FENCING_MODE
Динамический: да
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
- replication
- replication_anon
- bootstrap_strategy
- replication_connect_timeout
- replication_connect_quorum
- replication_skip_conflict
- replication_sync_lag
- replication_sync_timeout
- replication_timeout
- replicaset_uuid
- instance_uuid
- replication_synchro_quorum
- replication_synchro_timeout
- replication_threads
- election_mode
- election_timeout
- election_fencing_mode
-
replication
¶ Для версий от 1.7.4. и выше. Если
replication
не содержит пустую строку, экземпляр считается репликой. Реплика попытается подключиться к мастеру, указанному в параметреreplication
по URI (унифицированному идентификатору ресурса), например:konstantin:secret_password@tarantool.org:3301
Если в наборе реплик более одного источника репликации, укажите массив URI, например (замените „uri“ и „uri2“ в данном примере на рабочие URI):
box.cfg{ replication = { 'uri1', 'uri2' } }
Примечание
Starting from version 2.10.0, there is a number of other ways for specifying several URIs. See syntax examples.
If one of the URIs is «self» – that is, if one of the URIs is for the instance where
box.cfg{}
is being executed – then it is ignored. Thus, it is possible to use the samereplication
specification on multiple server instances, as shown in these examples.По умолчанию, пользователем считается „guest“.
Реплика в режиме только для чтения не принимает запросы по изменению данных по порту для прослушивания.
Параметр
replication
является динамическим, то есть для входа в режим мастера необходимо просто присвоить параметруreplication
пустую строку и выполнить следующее:box.cfg{ replication = новое-значение }
Тип: строкаПо умолчанию: nullEnvironment variable: TT_REPLICATIONДинамический: да
-
replication_anon
¶ Для версий от 2.3.1 и выше. Реплика Tarantool может быть анонимной. Этот тип реплики доступен только для чтения (но вы можете писать во временные и локальные спейсы реплики), и его нет в таблице
_cluster
.Since an anonymous replica isn’t registered in the _cluster space, there is no limitation for anonymous replicas count in a replica set: you can have as many of them as you want.
Чтобы сделать реплику анонимной, передайте опцию
replication_anon=true
вbox.cfg
и установите значениеread_only
равнымtrue
.Попробуем создать анонимную реплику. Предположим, что у нас есть мастер с такой настройкой:
box.cfg{listen=3301}
и создан локальный спейс «loc»:
box.schema.space.create('loc', {is_local=true}) box.space.loc:create_index("pk")
Теперь, чтобы настроить анонимную реплику, нам нужно обратиться к
box.cfg
, как обычно.box.cfg{replication_anon=true, read_only=true, replication=3301}
Как было сказано выше,
replication_anon
может бытьtrue
только вместе сread_only
. Этот экземпляр получит снимок мастера и начнет следить за его изменениями. Он не получит id, поэтому его значение останется нулевым.tarantool> box.info.id --- - 0 ... tarantool> box.info.replication --- - 1: id: 1 uuid: 3c84f8d9-e34d-4651-969c-3d0ed214c60f lsn: 4 upstream: status: follow idle: 0.6912029999985 peer: lag: 0.00014615058898926 ...
Теперь можно использовать реплику. Например, можно сделать вставку в локальный спейс:
tarantool> for i = 1,10 do > box.space.loc:insert{i} > end --- ...
Заметьте, что пока экземпляр анонимный, увеличится нулевая компонента его
vclock
:tarantool> box.info.vclock --- - {0: 10, 1: 4} ...
А теперь давайте сделаем анонимную реплику снова обычной:
tarantool> box.cfg{replication_anon=false} 2019-12-13 20:34:37.423 [71329] main I> assigned id 2 to replica 6a9c2ed2-b9e1-4c57-a0e8-51a46def7661 2019-12-13 20:34:37.424 [71329] main/102/interactive I> set 'replication_anon' configuration option to false --- ... tarantool> 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> subscribed 2019-12-13 20:34:37.424 [71329] main/117/applier/ I> remote vclock {1: 5} local vclock {0: 10, 1: 5} 2019-12-13 20:34:37.425 [71329] main/118/applierw/ C> leaving orphan mode
Эта реплика получила id равный 2. Мы можем снова сделать ее открытой на запись:
tarantool> box.cfg{read_only=false} 2019-12-13 20:35:46.392 [71329] main/102/interactive I> set 'read_only' configuration option to false --- ... tarantool> box.schema.space.create('test') --- - engine: memtx before_replace: 'function: 0x01109f9dc8' on_replace: 'function: 0x01109f9d90' ck_constraint: [] field_count: 0 temporary: false index: [] is_local: false enabled: false name: test id: 513 - created ... tarantool> box.info.vclock --- - {0: 10, 1: 5, 2: 2} ...
Теперь, как и ожидалось, реплика отслеживает свои изменения во 2-й компоненте vclock. С этого момента она также может стать мастером репликации.
Замечания:
- Нельзя реплицироваться от анонимной реплики.
- Чтобы вернуть анонимный экземпляр к обычному состоянию, сначала запустите его как анонимный, а потом вызовите
box.cfg{replication_anon=false}
- Чтобы деанонимизация прошла успешно, экземпляр должен быть скопирован с какого-то экземпляра, открытого на запись, иначе он не может быть добавлен в таблицу
_cluster
.
Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_REPLICATION_ANONДинамический: да
-
bootstrap_strategy
¶ Since 2.11.0.
Specifies a strategy used to bootstrap a replica set. The following strategies are available:
auto
: a node doesn’t boot if a half or more of other nodes in a replica set are not connected. For example, if the replication parameter contains 2 or 3 nodes, a node requires 2 connected instances. In the case of 4 or 5 nodes, at least 3 connected instances are required. Moreover, a bootstrap leader fails to boot unless every connected node has chosen it as a bootstrap leader.legacy
(deprecated since 2.11.0): a node requires the replication_connect_quorum number of other nodes to be connected. This option is added to keep the compatibility with the current versions of Cartridge and might be removed in the future.
Тип: строкаDefault: autoEnvironment variable: TT_BOOTSTRAP_STRATEGYДинамический: да
-
replication_connect_timeout
¶ Для версий от 1.9.0. и выше. Количество секунд, в течение которых реплика ожидает попытки подключения к мастеру в кластере. Для получения подробной информации, см. статус orphan.
This parameter is different from replication_timeout, which a master uses to disconnect a replica when the master receives no acknowledgments of heartbeat messages.
Тип: число с плавающей запятойПо умолчанию: 30Environment variable: TT_REPLICATION_CONNECT_TIMEOUTДинамический: да
-
replication_connect_quorum
¶ Deprecated since 2.11.0. This option is in effect if bootstrap_strategy is set to
legacy
.Specifies the number of nodes to be up and running to start a replica set. This parameter has effect during bootstrap or configuration update. Setting
replication_connect_quorum
to0
makes Tarantool require no immediate reconnect only in case of recovery. See Orphan status for details.Пример:
box.cfg { replication_connect_quorum = 2 }
Тип: целое числоПо умолчанию: nullEnvironment variable: TT_REPLICATION_CONNECT_QUORUMДинамический: да
-
replication_skip_conflict
¶ Для версий от 1.10.1. и выше. По умолчанию, если реплика добавляет уникальный ключ, который уже добавила другая реплика, репликация останавливается с ошибкой = ER_TUPLE_FOUND.
Однако если указать
replication_skip_conflict = true
, пользователи могут задать пропуск таких ошибок. Так, вместо сохранения сломанной транзакции в xlog, там будет записаноNOP
(No operation).Пример:
box.cfg{replication_skip_conflict=true}
Тип: логическийПо умолчанию: false (ложь)Environment variable: TT_REPLICATION_SKIP_CONFLICTДинамический: даПримечание
replication_skip_conflict = true
рекомендуется использовать только для ручного восстановления репликации.
-
replication_sync_lag
¶ Для версий от 1.9.0. и выше. Максимально допустимое отставание для реплики. Если реплика синхронизируется (то есть получает обновления от мастера), она может обновиться не полностью. Количество секунд, когда реплика находится позади мастера, называется «отставание» (lag). Синхронизация считается завершенной, когда отставание реплики меньше или равно
replication_sync_lag
.Если пользователь задает значение
replication_sync_lag
, равное nil или 365 * 100 * 86400 (TIMEOUT_INFINITY), то отставание не имеет значения – реплика всегда будет синхронизирована. Кроме того, отставание не учитывается (считается бесконечным), если мастер работает на версии Tarantool старше 1.7.7, которая не отправляет сообщения контрольного сигнала.Этот параметр не учитывается во время настройки. Для получения подробной информации, см. статус orphan.
Тип: число с плавающей запятойПо умолчанию: 10Environment variable: TT_REPLICATION_SYNC_LAGДинамический: да
-
replication_sync_timeout
¶ Since version 1.10.2. The number of seconds that a node waits when trying to sync with other nodes in a replica set (see bootstrap_strategy), after connecting or during configuration update. This could fail indefinitely if
replication_sync_lag
is smaller than network latency, or if the replica cannot keep pace with master updates. Ifreplication_sync_timeout
expires, the replica enters orphan status.Тип: число с плавающей запятойПо умолчанию: 300Environment variable: TT_REPLICATION_SYNC_TIMEOUTДинамический: даПримечание
The default
replication_sync_timeout
value is going to be changed in future versions from300
to0
. You can learn the reasoning behind this decision from the Default value for replication_sync_timeout topic, which also describes how to try the new behavior in the current version.
-
replication_timeout
¶ Для версий от 1.7.5. и выше. Если у мастера нет обновлений для реплик, он отправляет сообщения контрольного сигнала каждые
replication_timeout
секунд, а каждая реплика возвращает сообщение подтверждения.И мастер, и реплики запрограммированы разорвать соединение при отсутствии сообщений в течение четырех промежутков времени, указанного в параметре
replication_timeout
. После разрыва соединения реплика пытается снова подключиться к мастеру.См. дополнительную информацию в разделе Мониторинг набора реплик.
Тип: целое числоПо умолчанию: 1Environment variable: TT_REPLICATION_TIMEOUTДинамический: да
-
replicaset_uuid
¶ Для версий от 1.9.0. и выше. Как описано в разделе «Архитектура механизма репликации», каждый набор реплик идентифицируется по Универсальному уникальному идентификатору (UUID), который называется UUID набора реплик, и каждый экземпляр идентифицируется по UUID экземпляра.
Как правило, достаточно позволить системе сгенерировать и форматировать строки, содержащие UUID, которые будут храниться постоянно.
Однако, некоторые администраторы предпочитают сохранять конфигурацию Tarantool в центральном репозитории, например, Apache ZooKeeper. Они могут самостоятельно присвоить значения экземплярам (instance_uuid) и набору реплик (
replicaset_uuid
) при первом запуске.Общие правила:
- Значения должны быть действительно уникальными; они не должны одновременно принадлежать другим экземплярам или наборам реплик в той же инфраструктуре.
- Значения должны использоваться постоянно, неизменно с первого запуска (первоначальные значения хранятся в файлах снимков и проверяются при каждом перезапуске системы).
- Значения должны соответствовать требованиям RFC 4122. Нулевой UUID не допускается.
Формат UUID включает в себя шестнадцать октетов, представленных в виде 32 шестнадцатеричных чисел (с основанием 16) в пяти группах, разделенных дефисами в форме
8-4-4-4-12
– 36 символов (32 буквенно-цифровых символа и четыре дефиса).Пример:
box.cfg{replicaset_uuid='7b853d13-508b-4b8e-82e6-806f088ea6e9'}
Тип: строкаПо умолчанию: nullEnvironment variable: TT_REPLICASET_UUIDДинамический: нет
-
instance_uuid
¶ Для версий от 1.9.0. и выше. Для целей администрирования репликации можно самостоятельно присвоить универсально уникальные идентификаторы экземпляру (
instance_uuid
) и набору реплик (replicaset_uuid
) вместо использования сгенерированных системой значений.Для получения подробной информации см. описание параметра replicaset_uuid.
Пример:
box.cfg{instance_uuid='037fec43-18a9-4e12-a684-a42b716fcd02'}
Тип: строкаПо умолчанию: nullEnvironment variable: TT_INSTANCE_UUIDДинамический: нет
-
replication_synchro_quorum
¶ Since version 2.5.1. For synchronous replication only. This option tells how many replicas should confirm the receipt of a synchronous transaction before it can finish its commit.
Since version 2.5.3, the option supports dynamic evaluation of the quorum number. That is, the number of quorum can be specified not as a constant number, but as a function instead. In this case, the option returns the formula evaluated. The result is treated as an integer number. Once any replicas are added or removed, the expression is re-evaluated automatically.
For example,
box.cfg{replication_synchro_quorum = "N / 2 + 1"}
Where
N
is a current number of registered replicas in a cluster.Keep in mind that the example above represents a canonical quorum definition. The formula
at least 50% of the cluster size + 1
guarantees data reliability. Using a value less than the canonical one might lead to unexpected results, including a split-brain.Since version 2.10.0, this option does not account for anonymous replicas.
По умолчанию значение параметра равно
N / 2 + 1
.Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Если значение параметра равно
1
, синхронные транзакции работают как асинхронные, пока они не настроены.1
означает, что для коммита достаточно успешной записи в WAL на мастере.Тип: числоDefault: N / 2 + 1 (before version 2.10.0, the default value was 1)Environment variable: TT_REPLICATION_SYNCHRO_QUORUMДинамический: да
-
replication_synchro_timeout
¶ Since version 2.5.1. For synchronous replication only. Tells how many seconds to wait for a synchronous transaction quorum replication until it is declared failed and is rolled back.
Она не используется на репликах, поэтому если мастер умирает, отложенные синхронные транзакции будут ждать на репликах до тех пор, пока не будет выбран новый мастер.
Тип: числоПо умолчанию: 5Environment variable: TT_REPLICATION_SYNCHRO_TIMEOUTДинамический: да
-
replication_threads
¶ Since version 2.10.0. The number of threads spawned to decode the incoming replication data.
The default value is
1
. It means that a single separate thread handles all the incoming replication streams. In most cases, one thread is enough for all incoming data. Therefore, it is likely that the user will not need to set this configuration option.Possible values range from 1 to 1000. If there are multiple replication threads, connections to serve are distributed evenly between the threads.
Тип: числоПо умолчанию: 1Possible values: from 1 to 1000Environment variable: TT_REPLICATION_THREADSDynamic: no
-
election_mode
¶ Since version 2.6.1. Specifies the role of a replica set node in the leader election process.
Possible values:
- off
- voter
- candidate
- manual.
Participation of a replica set node in the automated leader election can be turned on and off by this option.
The default value is
off
. All nodes that have values other thanoff
run the Raft state machine internally talking to other nodes according to the Raft leader election protocol. When the option isoff
, the node accepts Raft messages from other nodes, but it doesn’t participate in the election activities, and this doesn’t affect the node’s state. So, for example, if a node is not a leader but it haselection_mode = 'off'
, it is writable anyway.You can control which nodes can become a leader. If you want a node to participate in the election process but don’t want that it becomes a leaders, set the
election_mode
option tovoter
. In this case, the election works as usual, this particular node will vote for other nodes, but won’t become a leader.If the node should be able to become a leader, use
election_mode = 'candidate'
.Since version 2.8.2, the manual election mode is introduced. It may be used when a user wants to control which instance is the leader explicitly instead of relying on the Raft election algorithm.
When an instance is configured with the
election_mode='manual'
, it behaves as follows:- By default, the instance acts like a voter – it is read-only and may vote for other instances that are candidates.
- Once box.ctl.promote() is called, the instance becomes a candidate and starts a new election round. If the instance wins the elections, it becomes a leader, but won’t participate in any new elections.
Тип: строкаDefault: „off“Environment variable: TT_ELECTION_MODEДинамический: да
-
election_timeout
¶ Since version 2.6.1. Specifies the timeout between election rounds in the leader election process if the previous round ended up with a split-vote.
In the leader election process, there can be an election timeout for the case of a split-vote. The timeout can be configured using this option; the default value is 5 seconds.
It is quite big, and for most of the cases it can be freely lowered to 300-400 ms. It can be a floating point value (300 ms would be
box.cfg{election_timeout = 0.3}
).To avoid the split vote repeat, the timeout is randomized on each node during every new election, from 100% to 110% of the original timeout value. For example, if the timeout is 300 ms and there are 3 nodes started the election simultaneously in the same term, they can set their election timeouts to 300, 310, and 320 respectively, or to 305, 302, and 324, and so on. In that way, the votes will never be split because the election on different nodes won’t be restarted simultaneously.
Тип: числоПо умолчанию: 5Environment variable: TT_ELECTION_TIMEOUTДинамический: да
-
election_fencing_mode
¶ Since version 2.11.0. In earlier Tarantool versions, use election_fencing_enabled instead.
Specifies the leader fencing mode that affects the leader election process. When the parameter is set to
soft
orstrict
, the leader resigns its leadership if it has less than replication_synchro_quorum of alive connections to the cluster nodes. The resigning leader receives the status of a follower in the current election term and becomes read-only.- In
soft
mode, a connection is considered dead if there are no responses for 4*replication_timeout seconds both on the current leader and the followers. - In
strict
mode, a connection is considered dead if there are no responses for 2*replication_timeout seconds on the current leader and 4*replication_timeout seconds on the followers. This improves chances that there is only one leader at any time.
Fencing applies to the instances that have the election_mode set to
candidate
ormanual
. To turn off leader fencing, setelection_fencing_mode
tooff
.Тип: строкаDefault: „soft“Environment variable: TT_ELECTION_FENCING_MODEДинамический: да- In
Работа с сетями
-
io_collect_interval
¶
Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятой
По умолчанию: null
Environment variable: TT_IO_COLLECT_INTERVAL
Динамический: да
-
net_msg_max
¶
Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.
В более слабых системах уменьшите значение net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.
When net_msg_max
is reached,
Tarantool suspends processing of incoming packages until it
has processed earlier messages. This is not a direct restriction of
the number of fibers that handle network messages, rather it
is a system-wide restriction of channel bandwidth.
This in turn causes restriction of the number of incoming
network messages that the
transaction processor thread
handles, and therefore indirectly affects the fibers that handle
network messages.
(The number of fibers is smaller than the number of messages because
messages can be released as soon as they are delivered, while
incoming requests might not be processed until some time after delivery.)
Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое число
По умолчанию: 768
Environment variable: TT_NET_MSG_MAX
Динамический: да
-
readahead
¶
Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое число
По умолчанию: 16320
Environment variable: TT_READAHEAD
Динамический: да
-
iproto_threads
¶
Since version 2.8.1.
The number of network threads.
There can be unusual workloads where the network thread
is 100% loaded and the transaction processor thread is not, so the network
thread is a bottleneck. In that case set iproto_threads
to 2 or more.
The operating system kernel will determine which connection goes to
which thread.
On typical systems, the default value (1) is correct.
Тип: целое число
По умолчанию: 1
Environment variable: TT_IPROTO_THREADS
Динамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
-
io_collect_interval
¶ Для версий от 1.4.9. и выше. Экземпляр уходит в режим ожидания на io_collect_interval секунд между итерациями событийного цикла. Это можно использовать для снижения загрузки процессора в системах с большим количество клиентских соединений, но нечастыми запросами (например, каждое соединение передает лишь небольшое количество запросов в секунду).
Тип: число с плавающей запятойПо умолчанию: nullEnvironment variable: TT_IO_COLLECT_INTERVALДинамический: да
-
net_msg_max
¶ Для версий от 1.10.1. и выше. Для обработки сообщений Tarantool выделяет файберы. Чтобы не допустить перегрузки файберов, которая влияет на всю систему, Tarantool ограничивает число сообщений, которые могут обрабатывать файберы, чтобы блокировать некоторые отложенные запросы.
В мощных системах увеличьте значение
net_msg_max
, и планировщик немедленно приступит к обработке отложенных запросов.В более слабых системах уменьшите значение
net_msg_max
, чтобы снизить загрузку, хотя это и займет некоторое время, поскольку планировщик будет ожидать завершения уже запущенных запросов.When
net_msg_max
is reached, Tarantool suspends processing of incoming packages until it has processed earlier messages. This is not a direct restriction of the number of fibers that handle network messages, rather it is a system-wide restriction of channel bandwidth. This in turn causes restriction of the number of incoming network messages that the transaction processor thread handles, and therefore indirectly affects the fibers that handle network messages. (The number of fibers is smaller than the number of messages because messages can be released as soon as they are delivered, while incoming requests might not be processed until some time after delivery.)Для стандартных систем подойдет значение, используемое по умолчанию (768).
Тип: целое числоПо умолчанию: 768Environment variable: TT_NET_MSG_MAXДинамический: да
-
readahead
¶ Для версий от 1.6.2. и выше. Размер буфера опережающего считывания, связанный с клиентским соединением. Чем больше буфер, тем больше памяти потребляет активное соединение и тем больше запросов можно считать из буфера операционной системы за отдельный системный вызов. Общее правило состоит в том, чтобы убедиться, что буфер может содержать как минимум несколько десятков соединений. Таким образом, если размер стандартного кортежа в запросе значительный, например, несколько килобайтов или даже мегабайтов, следует увеличить размер буфера опережающего считывания. Если не используется пакетная обработка запросов, будет целесообразно оставить значение, используемое по умолчанию.
Тип: целое числоПо умолчанию: 16320Environment variable: TT_READAHEADДинамический: да
-
iproto_threads
¶ Since version 2.8.1. The number of network threads. There can be unusual workloads where the network thread is 100% loaded and the transaction processor thread is not, so the network thread is a bottleneck. In that case set
iproto_threads
to 2 or more. The operating system kernel will determine which connection goes to which thread.On typical systems, the default value (1) is correct.
Тип: целое числоПо умолчанию: 1Environment variable: TT_IPROTO_THREADSДинамический: нет
Запись в журнал
This section provides information on how to configure options related to logging.
You can also use the log module to configure logging in your
application.
-
log_level
¶
Since version 1.6.2.
Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting log_level
, you can enable logging of all events with severities above
or equal to the given level. Tarantool prints logs to the standard
error stream by default. This can be changed with the
log configuration parameter.
Тип: целое число
По умолчанию: 5
Environment variable: TT_LOG_LEVEL
Динамический: да
Примечание
Prior to Tarantool 1.7.5 there were only six levels and DEBUG
was
level 6. Starting with Tarantool 1.7.5, VERBOSE
is level 6 and DEBUG
is level 7.
VERBOSE
is a new level for monitoring repetitive events which would cause
too much log writing if INFO
were used instead.
-
log
¶
Since version 1.7.4.
By default, Tarantool sends the log to the standard error stream
(stderr
). If log
is specified, Tarantool can send the log to a:
- file
- pipe
- system logger
Example 1: sending the log to the tarantool.log
file.
box.cfg{log = 'tarantool.log'}
-- или
box.cfg{log = 'file:tarantool.log'}
This opens the file tarantool.log
for output on the server’s default
directory. If the log
string has no prefix or has the prefix «file:»,
then the string is interpreted as a file path.
Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'}
-- or
box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and
sends all log messages to the standard input (stdin
) of cronolog
.
If the log
string begins with „|“ or has the prefix «pipe:»,
then the string is interpreted as a Unix
pipeline.
Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'}
-- или
box.cfg{log = 'syslog:facility=user'}
-- или
box.cfg{log = 'syslog:identity=tarantool,facility=user'}
-- или
box.cfg{log = 'syslog:server=unix:/dev/log'}
If the log
string begins with «syslog:», then it is
interpreted as a message for the
syslogd program, which normally
is running in the background on any Unix-like platform.
The setting can be syslog:
, syslog:facility=...
, syslog:identity=...
,
syslog:server=...
, or a combination.
- The
syslog:identity
setting is an arbitrary string, which is placed at
the beginning of all messages. The default value is «tarantool».
- В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user.
- The
syslog:server
setting is the locator for the syslog server.
It can be a Unix socket path beginning with «unix:», or an ipv4 port number.
The default socket value is: dev/log
(on Linux) or /var/run/syslog
(on macOS).
The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP.
When log is a program, its PID is saved in the log.pid
variable. You need to send it a signal to rotate logs.
Тип: строка
По умолчанию: null
Environment variable: TT_LOG
Динамический: нет
-
log_nonblock
¶
Since version 1.7.4.
If log_nonblock
equals true, Tarantool does not block during logging
when the system is not ready for writing, and drops the message
instead. If log_level is high, and many
messages go to the log, setting log_nonblock
to true may improve
logging performance at the cost of some log messages getting lost.
This parameter has effect only if log is
configured to send logs to a pipe or system logger.
The default log_nonblock
value is nil, which means that
blocking behavior corresponds to the logger type:
- false for
stderr
and file loggers.
- true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool
server, the default value was true.
Тип: логический
По умолчанию: nil
Environment variable: TT_LOG_NONBLOCK
Динамический: нет
-
too_long_threshold
¶
Since version 1.6.2.
If processing a request takes longer than the given value (in seconds),
warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятой
По умолчанию: 0.5
Environment variable: TT_TOO_LONG_THRESHOLD
Динамический: да
-
log_format
¶
Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if box.cfg{log_format='plain'}
:
2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if box.cfg{log_format='json'}
:
{"time": "2017-10-16T11:36:17.996-0600",
"level": "INFO",
"message": "set 'log_format' configuration option to \"json\"",
"pid": 18081,|
"cord_name": "main",
"fiber_id": 101,
"fiber_name": "interactive",
"file": "builtin\/box\/load_cfg.lua",
"line": 317}
The log_format='plain'
entry has a time value, process ID,
cord name, fiber_id,
fiber_name,
log level, and message.
The log_format='json'
entry has the same fields along with their labels,
and in addition has the file name and line number of the Tarantool source.
Тип: строка
По умолчанию: „plain“
Environment variable: TT_LOG_FORMAT
Динамический: да
-
log_modules
¶
Since version 2.11.0.
Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger.
Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function.
Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules.
Example: Set a log level for C modules.
Type: table
Default: blank
Environment variable: TT_LOG_MODULES
Динамический: да
Example 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths: test/logging/module1.lua
and test/logging/module2.lua
.
These modules use the default logger and look as follows:
return {
say_hello = function()
local log = require('log')
log.info('Info message from module1')
end
}
To load these modules in your application, you need to add the corresponding require
directives:
module1 = require('test.logging.module1')
module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules.
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function:
box_cfg = { log_modules = {
['test.logging.module1'] = 'verbose',
['test.logging.module2'] = 'error' }
}
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1.say_hello()
shows a message but module2.say_hello()
is swallowed:
-- Prints 'info' messages --
module1.say_hello()
--[[
[92617] main/103/interactive/test.logging.module1 I> Info message from module1
---
...
--]]
-- Swallows 'info' messages --
module2.say_hello()
--[[
---
...
--]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the verbose
level for module1
and the error
level for module2
:
box_cfg = { log_level = 'warn',
log_modules = {
module1 = 'verbose',
module2 = 'error' }
}
To create custom loggers, call the log.new() function:
-- Creates new loggers --
module1_log = require('log').new('module1')
module2_log = require('log').new('module2')
Given that module1
has the verbose
logging level and module2
has the error
level, calling module1_log.info()
shows a message but module2_log.info()
is swallowed:
-- Prints 'info' messages --
module1_log.info('Info message from module1')
--[[
[16300] main/103/interactive/module1 I> Info message from module1
---
...
--]]
-- Swallows 'debug' messages --
module1_log.debug('Debug message from module1')
--[[
---
...
--]]
-- Swallows 'info' messages --
module2_log.info('Info message from module2')
--[[
---
...
--]]
Example 3: Set a log level for C modules
In the example below, the box_cfg
variable contains logging settings that can be passed to the box.cfg()
function.
This example shows how to set the info
level for the tarantool
module:
box_cfg = { log_level = 'warn',
log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi')
-- Prints 'info' messages --
ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module')
--[[
[6024] main/103/interactive I> Info message from C module
---
...
--]]
-- Swallows 'debug' messages --
ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module')
--[[
---
...
--]]
The example above uses the LuaJIT ffi library to call C functions provided by the say
module.
This example illustrates how «rotation» works, that is, what happens when the server
instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session.
Then, use the log
property to send logs to Log_file
and
call log.info
to put a message in the log file.
box.cfg{log='Log_file'}
log = require('log')
log.info('Log Line #1')
In Terminal #2, use the mv
command to rename the log file to Log_file.bak
.
mv Log_file Log_file.bak
As a result, the next log message will go to Log_file.bak
.
Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use ps
to find the process ID of the Tarantool instance.
ps -A | grep tarantool
In Terminal #2, execute kill -HUP
to send a SIGHUP signal to the Tarantool instance.
Tarantool will open Log_file
again, and the next log message will go to Log_file
.
kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use less
to examine files.
Log_file.bak
will have the following lines …
2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1`
2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and Log_file
will look like this:
log file has been reopened
2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
This section provides information on how to configure options related to logging. You can also use the log module to configure logging in your application.
-
log_level
¶ Since version 1.6.2. Specifies the level of detail the log has. There are seven levels:
- 1 –
SYSERROR
- 2 –
ERROR
- 3 –
CRITICAL
- 4 –
WARNING
- 5 –
INFO
- 6 –
VERBOSE
- 7 –
DEBUG
By setting
log_level
, you can enable logging of all events with severities above or equal to the given level. Tarantool prints logs to the standard error stream by default. This can be changed with the log configuration parameter.Тип: целое числоПо умолчанию: 5Environment variable: TT_LOG_LEVELДинамический: даПримечание
Prior to Tarantool 1.7.5 there were only six levels and
DEBUG
was level 6. Starting with Tarantool 1.7.5,VERBOSE
is level 6 andDEBUG
is level 7.VERBOSE
is a new level for monitoring repetitive events which would cause too much log writing ifINFO
were used instead.- 1 –
-
log
¶ Since version 1.7.4. By default, Tarantool sends the log to the standard error stream (
stderr
). Iflog
is specified, Tarantool can send the log to a:- file
- pipe
- system logger
Example 1: sending the log to the
tarantool.log
file.box.cfg{log = 'tarantool.log'} -- или box.cfg{log = 'file:tarantool.log'}
This opens the file
tarantool.log
for output on the server’s default directory. If thelog
string has no prefix or has the prefix «file:», then the string is interpreted as a file path.Example 2: sending the log to a pipe.
box.cfg{log = '| cronolog tarantool.log'} -- or box.cfg{log = 'pipe: cronolog tarantool.log'}
This starts the program cronolog when the server starts, and sends all log messages to the standard input (
stdin
) ofcronolog
. If thelog
string begins with „|“ or has the prefix «pipe:», then the string is interpreted as a Unix pipeline.Example 3: sending the log to syslog.
box.cfg{log = 'syslog:identity=tarantool'} -- или box.cfg{log = 'syslog:facility=user'} -- или box.cfg{log = 'syslog:identity=tarantool,facility=user'} -- или box.cfg{log = 'syslog:server=unix:/dev/log'}
If the
log
string begins with «syslog:», then it is interpreted as a message for the syslogd program, which normally is running in the background on any Unix-like platform. The setting can besyslog:
,syslog:facility=...
,syslog:identity=...
,syslog:server=...
, or a combination.- The
syslog:identity
setting is an arbitrary string, which is placed at the beginning of all messages. The default value is «tarantool». - В настоящий момент настройка
syslog:facility
не учитывается, но будет использоваться в дальнейшем. Ее значением должно быть одно из ключевых слов syslog, которые сообщают программе syslogd, куда отправлять сообщение. Возможные значения: auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, syslog, user, uucp, local0, local1, local2, local3, local4, local5, local6, local7. По умолчанию: user. - The
syslog:server
setting is the locator for the syslog server. It can be a Unix socket path beginning with «unix:», or an ipv4 port number. The default socket value is:dev/log
(on Linux) or/var/run/syslog
(on macOS). The default port value is: 514, the UDP port.
When logging to a file, Tarantool reopens the log on SIGHUP. When log is a program, its PID is saved in the log.pid variable. You need to send it a signal to rotate logs.
Тип: строкаПо умолчанию: nullEnvironment variable: TT_LOGДинамический: нет
-
log_nonblock
¶ Since version 1.7.4. If
log_nonblock
equals true, Tarantool does not block during logging when the system is not ready for writing, and drops the message instead. If log_level is high, and many messages go to the log, settinglog_nonblock
to true may improve logging performance at the cost of some log messages getting lost.This parameter has effect only if log is configured to send logs to a pipe or system logger. The default
log_nonblock
value is nil, which means that blocking behavior corresponds to the logger type:- false for
stderr
and file loggers. - true for a pipe and system logger.
This is a behavior change: in earlier versions of the Tarantool server, the default value was true.
Тип: логическийПо умолчанию: nilEnvironment variable: TT_LOG_NONBLOCKДинамический: нет- false for
-
too_long_threshold
¶ Since version 1.6.2. If processing a request takes longer than the given value (in seconds), warn about it in the log. Has effect only if log_level is greater than or equal to 4 (WARNING).
Тип: число с плавающей запятойПо умолчанию: 0.5Environment variable: TT_TOO_LONG_THRESHOLDДинамический: да
-
log_format
¶ Для версий от 1.7.6. и выше. Данные в журнал записываются в двух форматах:
- „plain“ (по умолчанию) или
- „json“ (более детально с JSON-метками).
Here is what a log entry looks like if
box.cfg{log_format='plain'}
:2017-10-16 11:36:01.508 [18081] main/101/interactive I> set 'log_format' configuration option to "plain"
Here is what a log entry looks like if
box.cfg{log_format='json'}
:{"time": "2017-10-16T11:36:17.996-0600", "level": "INFO", "message": "set 'log_format' configuration option to \"json\"", "pid": 18081,| "cord_name": "main", "fiber_id": 101, "fiber_name": "interactive", "file": "builtin\/box\/load_cfg.lua", "line": 317}
The
log_format='plain'
entry has a time value, process ID, cord name, fiber_id, fiber_name, log level, and message.The
log_format='json'
entry has the same fields along with their labels, and in addition has the file name and line number of the Tarantool source.Тип: строкаПо умолчанию: „plain“Environment variable: TT_LOG_FORMATДинамический: да
-
log_modules
¶ Since version 2.11.0. Configure the specified log levels (log_level) for different modules.
You can specify a logging level for the following module types:
- Modules (files) that use the default logger. Example: Set log levels for files that use the default logger.
- Modules that use custom loggers created using the log.new() function. Example: Set log levels for modules that use custom loggers.
- The
tarantool
module that enables you to configure the logging level for Tarantool core messages. Specifically, it configures the logging level for messages logged from non-Lua code, including C modules. Example: Set a log level for C modules.
Type: tableDefault: blankEnvironment variable: TT_LOG_MODULESДинамический: даExample 1: Set log levels for files that use the default logger
Suppose you have two identical modules placed by the following paths:
test/logging/module1.lua
andtest/logging/module2.lua
. These modules use the default logger and look as follows:return { say_hello = function() local log = require('log') log.info('Info message from module1') end }
To load these modules in your application, you need to add the corresponding
require
directives:module1 = require('test.logging.module1') module2 = require('test.logging.module2')
To configure logging levels, you need to provide module names corresponding to paths to these modules. In the example below, the
box_cfg
variable contains logging settings that can be passed to thebox.cfg()
function:box_cfg = { log_modules = { ['test.logging.module1'] = 'verbose', ['test.logging.module2'] = 'error' } }
Given that
module1
has theverbose
logging level andmodule2
has theerror
level, callingmodule1.say_hello()
shows a message butmodule2.say_hello()
is swallowed:-- Prints 'info' messages -- module1.say_hello() --[[ [92617] main/103/interactive/test.logging.module1 I> Info message from module1 --- ... --]] -- Swallows 'info' messages -- module2.say_hello() --[[ --- ... --]]
Example 2: Set log levels for modules that use custom loggers
In the example below, the
box_cfg
variable contains logging settings that can be passed to thebox.cfg()
function. This example shows how to set theverbose
level formodule1
and theerror
level formodule2
:box_cfg = { log_level = 'warn', log_modules = { module1 = 'verbose', module2 = 'error' } }
To create custom loggers, call the log.new() function:
-- Creates new loggers -- module1_log = require('log').new('module1') module2_log = require('log').new('module2')
Given that
module1
has theverbose
logging level andmodule2
has theerror
level, callingmodule1_log.info()
shows a message butmodule2_log.info()
is swallowed:-- Prints 'info' messages -- module1_log.info('Info message from module1') --[[ [16300] main/103/interactive/module1 I> Info message from module1 --- ... --]] -- Swallows 'debug' messages -- module1_log.debug('Debug message from module1') --[[ --- ... --]] -- Swallows 'info' messages -- module2_log.info('Info message from module2') --[[ --- ... --]]
Example 3: Set a log level for C modules
In the example below, the
box_cfg
variable contains logging settings that can be passed to thebox.cfg()
function. This example shows how to set theinfo
level for thetarantool
module:box_cfg = { log_level = 'warn', log_modules = { tarantool = 'info' } }
The specified level affects messages logged from C modules:
ffi = require('ffi') -- Prints 'info' messages -- ffi.C._say(ffi.C.S_INFO, nil, 0, nil, 'Info message from C module') --[[ [6024] main/103/interactive I> Info message from C module --- ... --]] -- Swallows 'debug' messages -- ffi.C._say(ffi.C.S_DEBUG, nil, 0, nil, 'Debug message from C module') --[[ --- ... --]]
The example above uses the LuaJIT ffi library to call C functions provided by the
say
module.
This example illustrates how «rotation» works, that is, what happens when the server instance is writing to a log and signals are used when archiving it.
Start with two terminal shells: Terminal #1 and Terminal #2.
In Terminal #1, start an interactive Tarantool session. Then, use the
log
property to send logs toLog_file
and calllog.info
to put a message in the log file.box.cfg{log='Log_file'} log = require('log') log.info('Log Line #1')
In Terminal #2, use the
mv
command to rename the log file toLog_file.bak
.mv Log_file Log_file.bak
As a result, the next log message will go to
Log_file.bak
.Go back to Terminal #1 and put a message «Log Line #2» in the log file.
log.info('Log Line #2')
In Terminal #2, use
ps
to find the process ID of the Tarantool instance.ps -A | grep tarantool
In Terminal #2, execute
kill -HUP
to send a SIGHUP signal to the Tarantool instance. Tarantool will openLog_file
again, and the next log message will go toLog_file
.kill -HUP process_id
The same effect could be accomplished by calling log.rotate.
In Terminal #1, put a message «Log Line #3» in the log file.
log.info('Log Line #3')
In Terminal #2, use
less
to examine files.Log_file.bak
will have the following lines …2015-11-30 15:13:06.373 [27469] main/101/interactive I> Log Line #1` 2015-11-30 15:14:25.973 [27469] main/101/interactive I> Log Line #2`
… and
Log_file
will look like this:log file has been reopened 2015-11-30 15:15:32.629 [27469] main/101/interactive I> Log Line #3
Обратная связь
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶
Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение true
, обратная связь будет отправлена, как описано выше. Если задано значение false
, обратная связь не отправляется.
Тип: логический
По умолчанию: true
Environment variable: TT_FEEDBACK_ENABLED
Динамический: да
-
feedback_host
¶
Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строка
Default: https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOST
Динамический: да
-
feedback_interval
¶
Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятой
По умолчанию: 3600
Environment variable: TT_FEEDBACK_INTERVAL
Динамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
By default, a Tarantool daemon sends a small packet
once per hour, to https://feedback.tarantool.io
.
The packet contains three values from box.info:
box.info.version
, box.info.uuid
, and box.info.cluster_uuid
.
By changing the feedback configuration parameters, users can
adjust or turn off this feature.
-
feedback_enabled
¶ Для версий от 1.10.1. и выше. Отправлять обратную связь или нет.
Если задано значение
true
, обратная связь будет отправлена, как описано выше. Если задано значениеfalse
, обратная связь не отправляется.Тип: логическийПо умолчанию: trueEnvironment variable: TT_FEEDBACK_ENABLEDДинамический: да
-
feedback_host
¶ Для версий от 1.10.1. и выше. Адрес, на который отправляется пакет. Как правило, получателем будет Tarantool, но можно указать любой URL.
Тип: строкаDefault:https://feedback.tarantool.io
Environment variable: TT_FEEDBACK_HOSTДинамический: да
-
feedback_interval
¶ Для версий от 1.10.1. и выше. Количество секунд между отправками, обычно 3600 (1 час).
Тип: число с плавающей запятойПо умолчанию: 3600Environment variable: TT_FEEDBACK_INTERVALДинамический: да
Устаревшие параметры
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶
Устаревший, не использовать.
Тип: логический
По умолчанию: false (ложь)
Динамический: нет
-
logger
¶
Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶
Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶
Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логический
По умолчанию: true
Динамический: нет
-
panic_on_wal_error
¶
Устаревший, заменен параметром force_recovery.
Тип: логический
По умолчанию: true
Динамический: да
-
replication_source
¶
Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶
Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памяти memtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.
Тип: число с плавающей запятой
По умолчанию: 1.0
Динамический: нет
-
slab_alloc_maximal
¶
Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶
Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶
Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶
Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶
Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶
Deprecated in favor of
wal_max_size.
The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶
Deprecated in Tarantool v2.11 in favor of
election_fencing_mode.
The parameter does not allow using the strict
fencing mode. Setting to true
is equivalent to setting the soft
election_fencing_mode.
Setting to false
is equivalent to setting the off
election_fencing_mode.
Тип: логический
По умолчанию: true
Environment variable: TT_ELECTION_FENCING_ENABLED
Динамический: да
Данные параметры объявлены устаревшими с версии Tarantool 1.7.4:
- coredump
- logger
- logger_nonblock
- panic_on_snap_error,
- panic_on_wal_error
- replication_source
- slab_alloc_arena
- slab_alloc_maximal
- slab_alloc_minimal
- snap_dir
- snapshot_count
- snapshot_period
- rows_per_wal,
- election_fencing_enabled
-
coredump
¶ Устаревший, не использовать.
Тип: логическийПо умолчанию: false (ложь)Динамический: нет
-
logger
¶ Устаревший, заменен параметром log. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
logger_nonblock
¶ Устаревший, заменен параметром log_nonblock. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
panic_on_snap_error
¶ Устаревший, заменен параметром force_recovery.
Если при чтении файла снимка произошла ошибка (при запуске экземпляра сервера), прервать выполнение.
Тип: логическийПо умолчанию: trueДинамический: нет
-
panic_on_wal_error
¶ Устаревший, заменен параметром force_recovery.
Тип: логическийПо умолчанию: trueДинамический: да
-
replication_source
¶ Устаревший, заменен параметром replication. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_arena
¶ Устаревший, заменен параметром memtx_memory.
Количество памяти, которое Tarantool выделяет для фактического хранения кортежей, в гигабайтах. При достижении предельного значения запросы вставки INSERT или обновления UPDATE выполняться не будут, выдавая ошибку
ER_MEMORY_ISSUE
. Сервер не выходит за установленный предел памятиmemtx_memory
при распределении кортежей, но есть дополнительная память, которая используется для хранения индексов и информации о подключении. В зависимости от рабочей конфигурации и загрузки, Tarantool может потреблять на 20% больше установленного предела.Тип: число с плавающей запятойПо умолчанию: 1.0Динамический: нет
-
slab_alloc_maximal
¶ Устаревший, заменен параметром memtx_max_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
slab_alloc_minimal
¶ Устаревший, заменен параметром memtx_min_tuple_size. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snap_dir
¶ Устаревший, заменен параметром memtx_dir. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_period
¶ Устаревший, заменен параметром checkpoint_interval. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
snapshot_count
¶ Устаревший, заменен параметром checkpoint_count. Параметр был лишь переименован, его тип, значения и семантика остались прежними.
-
rows_per_wal
¶ Deprecated in favor of wal_max_size. The parameter does not allow to properly limit size of WAL logs.
-
election_fencing_enabled
¶ Deprecated in Tarantool v2.11 in favor of election_fencing_mode.
The parameter does not allow using the
strict
fencing mode. Setting totrue
is equivalent to setting thesoft
election_fencing_mode. Setting tofalse
is equivalent to setting theoff
election_fencing_mode.Тип: логическийПо умолчанию: trueEnvironment variable: TT_ELECTION_FENCING_ENABLEDДинамический: да