tarantoolctl utility (deprecated)
Важно
tarantoolctl is deprecated in favor of tt CLI.
Find the instructions on switching from tarantoolctl to tt in
Migration from tarantoolctl to tt.
tarantoolctl is a utility for administering Tarantool
instances,
checkpoint files and
modules.
It is shipped and installed as part of Tarantool distribution.
This utility is intended for use by administrators only.
См. также примеры использования tarantoolctl в разделе Администрирование серверной части.
tarantoolctl COMMAND NAME [URI] [FILE] [OPTIONS..]
где:
COMMAND– это одна из следующих команд, описанных ниже:start,stop,status,restart,logrotate,check,enter,eval,connect,cat,play,rocks.NAME– это имя файла экземпляра или модуля.FILE– это путь к какому-либо файлу (.lua, .xlog или .snap).URI– это URI некого экземпляра Tarantool.OPTIONS– это параметры, которые принимают командыtarantoolctl.
tarantoolctl start NAMEЗапуск экземпляра Tarantool’а.
Кроме того, данная команда задает значение переменной окружения TARANTOOLCTL = „true“ (правда), чтобы отметить, что экземпляр был запущен с помощью
tarantoolctl.Примечание
tarantoolctlработает для экземпляров, где не вызвана функцияbox.cfg{}или вызовbox.cfg{}отложен.Например, это можно использовать для управления экземплярами, которые получают конфигурацию из внешнего сервера. Для таких экземпляров
tarantoolctl startgoes to background whenbox.cfg{}is called, so it will wait until options forbox.cfgare received. However this is not the case for daemon management systems likesystemd, as they handle backgrounding on their side.tarantoolctl stop NAME- Остановка экземпляра Tarantool.
tarantoolctl status NAMEОтображение статуса экземпляра (работает/остановлен). Если есть PID-файл и активный управляющий сокет, возвращается код
0. В остальных случаях возвращается не0.Сообщает о типичных проблемах стандартного вывода ошибок (например, PID-файл есть, а управляющий сокет отсутствует).
tarantoolctl restart NAMEОстановка и запуск экземпляра Tarantool’а.
Кроме того, данная команда задает значение переменной окружения TARANTOOL_RESTARTED = „true“ (правда), чтобы отметить, что экземпляр был перезапущен с помощью
tarantoolctl.tarantoolctl logrotate NAME- Ротация файлов журнала работающего Tarantool-экземпляра. Работает только в том случае, если в файле экземпляра задан параметр записи журнала в файл. Отправка записей в конвейер или системный журнал syslog не имеет значения в данном случае.
tarantoolctl check NAME- Проверка файла экземпляра на ошибки синтаксиса.
tarantoolctl enter NAME [--language=language]Enter an instance’s interactive Lua or SQL console.
Supported option:
--language=languageto set interactive console language. Can be eitherLuaorSQL.
tarantoolctl eval NAME FILE- Выполнение локального Lua-файла на работающем экземпляре Tarantool.
tarantoolctl connect URI- Подключение к экземпляру Tarantool по порту административной консоли. Поддерживаются TCP и Unix сокеты.
tarantoolctl cat FILE.. [--space=space_no ..] [--show-system] [--from=from_lsn] [--to=to_lsn] [--replica=replica_id ..] [--format=format_name]- Стандартный вывод содержимого .snap-файла или .xlog-файла.
tarantoolctl play URI FILE.. [--space=space_no ..] [--show-system] [--from=from_lsn] [--to=to_lsn] [--replica=replica_id ..]- Передача содержимого .snap-файла или .xlog-файла на другой экземпляр Tarantool.
Поддерживаемые опции:
--space=space_noдля фильтрации вывода по номеру спейса. Можно передавать несколько раз.--show-systemдля отображения содержимого системных спейсов.--from=from_lsnдля отображения операций, начиная с заданного LSN.--to=to_lsnдля отображения операций, заканчивая заданным LSN.--replica=replica_idдля фильтрации вывода по идентификатору реплики. Можно передавать несколько раз.--format=format_nameдля указания формата (по умолчаниюyaml, может также принимать значенияjsonиlua).
tarantoolctl rocks build NAME- Build/compile and install a rock. Since version 2.4.1.
tarantoolctl rocks config URI- Query and set the LuaRocks configuration. Since version 2.4.1.
tarantoolctl rocks doc NAME- Отображение документации для установленного модуля.
tarantoolctl rocks download [NAME]- Download a specific rock or rockspec file from a rocks server. Since version 2.4.1.
tarantoolctl rocks help NAME- Помощь по командам.
tarantoolctl rocks init NAME- Initialize a directory for a Lua project using LuaRocks. Since version 2.4.1.
tarantoolctl rocks install NAME- Установка модуля в директорию
.rocks, находящуюся в текущей директории. tarantoolctl rocks lint FILE- Check the syntax of a rockspec. Since version 2.4.1.
tarantoolctl rocks list- Вывод списка всех установленных модулей.
tarantoolctl rocks make- Компиляция пакета в текущем каталоге с помощью rockspec и его установка.
tarantoolctl rocks make_manifest- Компиляция файла-манифеста для репозитория.
tarantoolctl rocks new_version NAME- Auto-write a rockspec for a new version of a rock. Since version 2.4.1.
tarantoolctl rocks pack NAME- Создание модуля путем компоновки исходных или бинарных файлов.
tarantoolctl rocks purge NAME- Remove all installed rocks from a tree. Since version 2.4.1.
tarantoolctl rocks remove NAME- Удаление модуля.
tarantoolctl rocks show NAME- Отображение информации об установленном модуле.
tarantoolctl rocks search NAME- Поиск модулей по репозиторию.
tarantoolctl rocks unpack NAME- Распаковка содержимого модуля.
tarantoolctl rocks which NAME- Tell which file corresponds to a given module name. Since version 2.4.1.
tarantoolctl rocks write_rockspecWrite a template for a rockspec file. Since version 2.4.1.
В качестве аргумента можно указать:
- файл в формате
.rockspecдля создания модуля, который содержит исходные файлы или - имя установленного модуля (с версией, если их больше одной) для создания модуля, который содержит скомпилированные файлы.
- файл в формате
tarantoolctl rocks unpack {<rock_file> | <rockspec> | <имя> [версия]}Распаковка содержимого модуля в новую директорию в текущей директории.
В качестве аргумента можно указать:
- исходные или бинарные файлы модуля,
- файлы
.rockspecили - имя модулей или файлов в формате
.rockspecв удаленных репозиториях (с версией модуля, если их больше одной).
Поддерживаемые опции:
--server=имя_севрерасначала проверить данный сервер, затем по списку.--only-server=имя_серверапроверить только данный сервер, остальные пропустить.
The tarantoolctl configuration file named .tarantoolctl
contains the configuration that tarantoolctl uses to
override instance configuration. In other words, it contains system-wide
configuration defaults. If tarantoolctl fails to find this file with
the method described in the section
Starting/stopping an instance, it uses
default settings.
Most of the parameters are similar to those used by
box.cfg{}. Here are the default settings
(possibly installed in /etc/default/tarantool or /etc/sysconfig/tarantool
as part of Tarantool distribution – see OS-specific default paths in
Notes for operating systems):
default_cfg = {
pid_file = "/var/run/tarantool",
wal_dir = "/var/lib/tarantool",
memtx_dir = "/var/lib/tarantool",
vinyl_dir = "/var/lib/tarantool",
log = "/var/log/tarantool",
username = "tarantool",
language = "Lua",
}
instance_dir = "/etc/tarantool/instances.enabled"
где:
pid_fileDirectory for the pid file and control-socket file;tarantoolctlwill add “/instance_name” to the directory name.wal_dirDirectory for write-ahead .xlog files;tarantoolctlwill add «/instance_name» to the directory name.memtx_dirDirectory for snapshot .snap files;tarantoolctlwill add «/instance_name» to the directory name.vinyl_dirDirectory for vinyl files;tarantoolctlwill add «/instance_name» to the directory name.logThe place where the application log will go;tarantoolctlwill add «/instance_name.log» to the name.usernameThe user that runs the Tarantool instance. This is the operating system user name rather than the Tarantool-client user name. Tarantool will change its effective user to this user after becoming a daemon.languageinstance_dirThe directory where all instance files for this host are stored. Put instance files in this directory, or create symbolic links.The default instance directory depends on Tarantool’s
WITH_SYSVINITbuild option: when ON, it is/etc/tarantool/instances.enabled, otherwise (OFF or not set) it is/etc/tarantool/instances.available. The latter case is typical for Tarantool builds for Linux distros withsystemd.To check the build options, say
tarantool --version.
With tarantoolctl, log rotation is pre-configured to use
logrotate program, which you must have installed.
File /etc/logrotate.d/tarantool is part of the standard Tarantool
distribution, and you can modify it to change the default behavior. This is what
this file is usually like:
/var/log/tarantool/*.log {
daily
size 512k
missingok
rotate 10
compress
delaycompress
create 0640 tarantool adm
postrotate
/usr/bin/tt logrotate `basename ${1%%.*}`
endscript
}
If you use a different log rotation program, you can invoke
tarantoolctl logrotate command to request instances to reopen their log
files after they were moved by the program of your choice.
To make tarantoolctl work along with init.d utilities on FreeBSD, use
paths other than those suggested in
Instance configuration. Instead of
/usr/share/tarantool/ directory, use /usr/local/etc/tarantool/ and
create the following subdirectories:
defaultfortarantoolctldefaults (see example below),instances.availablefor all available instance files, andinstances.enabledfor instance files to be auto-started by sysvinit.
Here is an example of tarantoolctl defaults on FreeBSD:
default_cfg = {
pid_file = "/var/run/tarantool", -- /var/run/tarantool/${INSTANCE}.pid
wal_dir = "/var/db/tarantool", -- /var/db/tarantool/${INSTANCE}/
snap_dir = "/var/db/tarantool", -- /var/db/tarantool/${INSTANCE}
vinyl_dir = "/var/db/tarantool", -- /var/db/tarantool/${INSTANCE}
logger = "/var/log/tarantool", -- /var/log/tarantool/${INSTANCE}.log
username = "admin"
}
-- instances.available - all available instances
-- instances.enabled - instances to autostart by sysvinit
instance_dir = "/usr/local/etc/tarantool/instances.available"
While a Lua application is executed by Tarantool, an instance file is executed
by tarantoolctl which is a Tarantool script.
Here is what tarantoolctl does when you issue the command:
$ tarantoolctl start <instance_name>
Read and parse the command line arguments. The last argument, in our case, contains an instance name.
Read and parse its own configuration file. This file contains
tarantoolctldefaults, like the path to the directory where instances should be searched for.When
tarantoolis invoked by root, it looks for a configuration file in/etc/default/tarantool. Whentarantoolis invoked by a local (non-root) user, it looks for a configuration file first in the current directory ($PWD/.tarantoolctl), and then in the current user’s home directory ($HOME/.config/tarantool/tarantool). If no configuration file is found there, or in the/usr/local/etc/default/tarantoolfile, thentarantoolctlfalls back to built-in defaults.Look up the instance file in the instance directory, for example
/etc/tarantool/instances.enabled. To build the instance file path,tarantoolctltakes the instance name, prepends the instance directory and appends «.lua» extension to the instance file.Override box.cfg{} function to pre-process its parameters and ensure that instance paths are pointing to the paths defined in the
tarantoolctlconfiguration file. For example, if the configuration file specifies that instance work directory must be in/var/tarantool, then the new implementation ofbox.cfg{}ensures that work_dir parameter inbox.cfg{}is set to/var/tarantool/<instance_name>, regardless of what the path is set to in the instance file itself.Create a so-called «instance control file». This is a Unix socket with Lua console attached to it. This file is used later by
tarantoolctlto query the instance state, send commands to the instance and so on.Set the TARANTOOLCTL environment variable to „true“. This allows the user to know that the instance was started by
tarantoolctl.Finally, use Lua
dofilecommand to execute the instance file.
To check the instance file for syntax errors prior to starting my_app
instance, say:
$ tarantoolctl check my_app
To stop a running my_app instance, say:
$ tarantoolctl stop my_app
To restart (i.e. stop and start) a running my_app instance, say:
$ tarantoolctl restart my_app
Sometimes you may need to run a Tarantool instance locally, e.g. for test
purposes. Let’s configure a local instance, then start and monitor it with
tarantoolctl.
First, we create a sandbox directory on the user’s path:
$ mkdir ~/tarantool_test
… and set default tarantoolctl configuration in
$HOME/.config/tarantool/tarantool. Let the file contents be:
default_cfg = {
pid_file = "/home/user/tarantool_test/my_app.pid",
wal_dir = "/home/user/tarantool_test",
snap_dir = "/home/user/tarantool_test",
vinyl_dir = "/home/user/tarantool_test",
log = "/home/user/tarantool_test/log",
}
instance_dir = "/home/user/tarantool_test"
Примечание
- Specify a full path to the user’s home directory instead of «~/».
- Omit
usernameparameter.tarantoolctlnormally doesn’t have permissions to switch current user when invoked by a local user. The instance will be running under „admin“.
Next, we create the instance file ~/tarantool_test/my_app.lua. Let the file
contents be:
box.cfg{listen = 3301}
box.schema.user.passwd('Gx5!')
box.schema.user.grant('guest','read,write,execute','universe')
fiber = require('fiber')
box.schema.space.create('tester')
box.space.tester:create_index('primary',{})
i = 0
while 0 == 0 do
fiber.sleep(5)
i = i + 1
print('insert ' .. i)
box.space.tester:insert{i, 'my_app tuple'}
end
Let’s verify our instance file by starting it without tarantoolctl first:
$ cd ~/tarantool_test
$ tarantool my_app.lua
2017-04-06 10:42:15.762 [54085] main/101/my_app.lua C> version 1.7.3-489-gd86e36d5b
2017-04-06 10:42:15.763 [54085] main/101/my_app.lua C> log level 5
2017-04-06 10:42:15.764 [54085] main/101/my_app.lua I> mapping 268435456 bytes for tuple arena...
2017-04-06 10:42:15.774 [54085] iproto/101/main I> binary: bound to [::]:3301
2017-04-06 10:42:15.774 [54085] main/101/my_app.lua I> initializing an empty data directory
2017-04-06 10:42:15.789 [54085] snapshot/101/main I> saving snapshot `./00000000000000000000.snap.inprogress'
2017-04-06 10:42:15.790 [54085] snapshot/101/main I> done
2017-04-06 10:42:15.791 [54085] main/101/my_app.lua I> vinyl checkpoint done
2017-04-06 10:42:15.791 [54085] main/101/my_app.lua I> ready to accept requests
insert 1
insert 2
insert 3
<...>
Now we tell tarantoolctl to start the Tarantool instance:
$ tarantoolctl start my_app
Expect to see messages indicating that the instance has started. Then:
$ ls -l ~/tarantool_test/my_app
Expect to see the .snap file and the .xlog file. Then:
$ less ~/tarantool_test/log/my_app.log
Expect to see the contents of my_app‘s log, including error messages, if
any. Then:
$ tarantoolctl enter my_app
tarantool> box.cfg{}
tarantool> console = require('console')
tarantool> console.connect('localhost:3301')
tarantool> box.space.tester:select({0}, {iterator = 'GE'})
Expect to see several tuples that my_app has created.
Stop now. A polite way to stop my_app is with tarantoolctl, thus we say:
$ tarantoolctl stop my_app
Finally, we make a cleanup.
$ rm -R tarantool_test
tt is a command-line utility for managing Tarantool applications
that comes to replace tarantoolctl. Starting from version 3.0, tarantoolctl
is no longer shipped as a part of Tarantool distribution; tt is the only
recommended tool for managing Tarantool applications from the command line.
tarantoolctl remains fully compatible with Tarantool 2.* versions. However,
it doesn’t receive major updates anymore.
We recommend that you migrate from tarantoolctl to tt to ensure the full
support and timely updates and fixes.
tt supports system-wide environment configuration by default. If you have
Tarantool instances managed by tarantoolctl in such an environment, you can
switch to tt without additional migration steps or use tt along with tarantoolctl.
Example:
$ sudo tt instances
List of enabled applications:
• example
$ tarantoolctl start example
Starting instance example...
Forwarding to 'systemctl start tarantool@example'
$ tarantoolctl status example
Forwarding to 'systemctl status tarantool@example'
● tarantool@example.service - Tarantool Database Server
Loaded: loaded (/lib/systemd/system/tarantool@.service; enabled; vendor preset: enabled)
Active: active (running)
Docs: man:tarantool(1)
Main PID: 6698 (tarantool)
. . .
$ sudo tt status
• example: RUNNING. PID: 6698.
$ sudo tt connect example
• Connecting to the instance...
• Connected to /var/run/tarantool/example.control
/var/run/tarantool/example.control>
$ sudo tt stop example
• The Instance example (PID = 6698) has been terminated.
$ tarantoolctl status example
Forwarding to 'systemctl status tarantool@example'
○ tarantool@example.service - Tarantool Database Server
Loaded: loaded (/lib/systemd/system/tarantool@.service; enabled; vendor preset: enabled)
Active: inactive (dead)
If you have a local tarantoolctl configuration, create a tt environment
based on the existing .tarantoolctl configuration file. To do this, run
tt init in the directory where the file is located.
Example:
$ cat .tarantoolctl
default_cfg = {
pid_file = "./run/tarantool",
wal_dir = "./lib/tarantool",
memtx_dir = "./lib/tarantool",
vinyl_dir = "./lib/tarantool",
log = "./log/tarantool",
language = "Lua",
}
instance_dir = "./instances.enabled"
$ tt init
• Found existing config '.tarantoolctl'
• Environment config is written to 'tt.yaml'
After that, you can start managing Tarantool instances in this environment with tt:
$ tt start app1
• Starting an instance [app1]...
$ tt status app1
• app1: RUNNING. PID: 33837.
$ tt stop app1
• The Instance app1 (PID = 33837) has been terminated.
$ tt check app1
• Result of check: syntax of file '/home/user/instances.enabled/app1.lua' is OK
Most tarantoolctl commands look the same in tt: tarantoolctl start and
tt start, tarantoolctl play and tt play, and so on. To migrate such
calls, it is usually enough to replace the utility name. There can be slight differences
in command flags and format. For details on tt commands, see the
tt commands reference.
The following commands are different in tt:
tarantoolctl command |
tt command |
|---|---|
tarantoolctl enter |
tt connect |
tarantoolctl eval |
tt connect with -f flag |
Примечание
tt connect also covers tarantoolctl connect with the same syntax.
Example:
# tarantoolctl enter > tt connect
$ tarantoolctl enter app1
connected to unix/:./run/tarantool/app1.control
unix/:./run/tarantool/app1.control>
$ tt connect app1
• Connecting to the instance...
• Connected to /home/user/run/tarantool/app1/app1.control
# tarantoolctl eval > tt connect -f
$ tarantoolctl eval app1 eval.lua
connected to unix/:./run/tarantool/app1.control
---
- 42
...
$ tt connect app1 -f eval.lua
---
- 42
...
# tarantoolctl connect > tt connect
$ tarantoolctl connect localhost:3301
connected to localhost:3301
localhost:3301>
$ tt connect localhost:3301
• Connecting to the instance...
• Connected to localhost:3301