Настройка экземпляров Tarantool
Для каждого экземпляра Tarantool понадобится два файла:
[Необязательный] Файл приложения, содержащий логику данного экземпляра. Поместите его в папку
/usr/share/tarantool/.Например,
/usr/share/tarantool/my_app.lua(здесь мы реализуем его как Lua-модуль, который запускает базу данных и экспортирует функциюstart()для API -вызовов):local function start() box.schema.space.create("somedata") box.space.somedata:create_index("primary") <...> end return { start = start; }
An instance file with instance-specific initialization logic and parameters. Put this file, or a symlink to it, into the instance directory (see
instances_enabledparameter in tt configuration file).Например,
/etc/tarantool/instances.enabled/my_app.lua(здесь мы загружаем модульmy_app.luaи вызываем из него функциюstart()):#!/usr/bin/env tarantool box.cfg { listen = 3301; } -- загрузить модуль my_app и вызвать функцию start() -- некоторые опции приложения под контролем сисадминов local m = require('my_app').start({...})
After this short introduction, you may wonder what an instance file is, what it
is for, and how tt uses it. After all, Tarantool is an application
server, so why not start the application stored in /usr/share/tarantool
directly?
Типичное приложение для Tarantool – это не скрипт, а демон, запущенный в фоновом режиме и обрабатывающий запросы, которые, как правило, посылаются через TCP/IP-сокет. Необходимо запускать этот демон со стартом операционной системы и управлять им с помощью стандартных средств операционной системы для управления сервисами – таких как systemd или init.d. С этой целью и были созданы файлы экземпляра.
Файлов экземпляра может быть больше одного. Например, одно и то же приложение в /usr/share/tarantool может быть запущено на нескольких экземплярах Tarantool, у каждого из которых есть свой файл экземпляра. Или в /usr/share/tarantool может быть несколько приложений, и на каждое из них будет опять же приходиться свой файл экземпляра.
Обычно файл экземпляра создает системный администратор, а файл приложения предоставляет разработчик в Lua-модуле или rpm/deb-пакете.
An instance file is designed to not differ in any way from a Lua application.
It must, however, configure the database, i.e. contain a call to
box.cfg{} somewhere in it, because it’s the
only way to turn a Tarantool script into a background process, and
tt is a tool to manage background processes. Other than that, an
instance file may contain arbitrary Lua code, and, in theory, even include the
entire application business logic in it. We, however, do not recommend this,
since it clutters the instance file and leads to unnecessary copy-paste when
you need to run multiple instances of an application.
Tarantool supports loading and running chunks of Lua code before the loading instance file.
To load or run Lua code immediately upon Tarantool startup, specify the TT_PRELOAD
environment variable. Its value can be either a path to a Lua script or a Lua module name:
To run the Lua script
script.luafrom thepreload/path/directory inside the working directory in Tarantool beforemain.lua, setTT_PRELOADas follows:$ TT_PRELOAD=/preload/path/script.lua tarantool main.lua
Tarantool runs the
script.luacode, waits for it to complete, and then starts runningmain.lua.To load the
preload.moduleinto the Tarantool Lua interpreter executingmain.lua, setTT_PRELOADas follows:$ TT_PRELOAD=preload.module tarantool main.lua
Tarantool loads the
preload.modulecode into the interpreter and starts runningmain.luaas if its first statement wasrequire('preload.module').Предупреждение
TT_PRELOADvalues that end with.luaare considered scripts, so avoid module names with this ending.
To load several scripts or modules, pass them in a single quoted string, separated by semicolons:
$ TT_PRELOAD="/preload/path/script.lua;preload.module" tarantool main.lua
In the preload script, the three dots (...) value contains the module name
if you’re preloading a module or the path to the script if you’re running a script.
The arg value from the main script is visible in the preload script or module.
For example, when preloading this script:
-- preload.lua --
print("Preloading:")
print("... arg is:", ...)
print("Passed args:", arg[1], arg[2])
You get the following output:
$ TT_PRELOAD=preload.lua tarantool main.lua arg1 arg2
Preloading:
... arg is: preload.lua
Passed args: arg1 arg2
'strip_core' is set but unsupported
... main/103/main.lua I> Tarantool 2.11.0-0-g247a9a4 Darwin-x86_64-Release
... main/103/main.lua I> log level 5
... main/103/main.lua I> wal/engine cleanup is paused
< ... >
If an error happens during the execution of the preload script or module, Tarantool reports the problem and exits.
While instance files contain instance configuration, the tt configuration file
contains the configuration that tt uses to set up the application environment.
This includes the path to instance files, various working directories, and other
parameters that connect the application to the system.
To create a default tt configuration, run tt init. This creates a tt.yaml
configuration file. Its location depends on the tt launch mode
(system or local).
Some tt configuration parameters are similar to those used by
box.cfg{}, for example, memxt_dir
or wal_dir. Other parameters define the tt environment, for example,
paths to installation files used by tt or to connected external modules.
Find the detailed information about the tt configuration parameters and launch modes
on the tt configuration page.