«Консольные команды Linux» и «Beanstalk Protocol»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Vix
Нет описания правки
 
imported>Supportadmin
(Новая страница: « = Beanstalk Protocol = Protocol -------- The beanstalk protocol runs over TCP using ASCII encoding. Clients connect, send commands and data, wait for responses…»)
 
Строка 1: Строка 1:
== Консольные команды. Часть 1, Администрирование в консоли. ==


*'''login''' запрос от пользователя имени и пароля (запрос от системы к пользователю) для входа в систему( по умолчанию, при наборе пароля, он не отображается).
= Beanstalk Protocol =
*'''logout''' выход из текущего сеанса оболочки.
*'''startx''' команда для запуска графического интерфейса X Window (не путайте с системой Windows.Не бойтесь. Это не она:)).
*'''shutdown''' останавливает систему и предотвращает повреждение файловой системы при этом, но,используется только при работе в консольном режиме.При работе в режиме X Window, не используйте.
*'''halt''' быстрое и корректное выключение системы.
*'''poweroff''' корректное выключение системы.
*'''reboot''' корректное выключение с последущей загрузкой.Перезагрузка.
*'''vmstat''' выдаёт сведения о процессах, памяти и загруженности центрального процессора.
*'''su''' вход в сеанс администратора, но прийдётся ввести пароль.Для выхода из этого сеанса наберите exit и нажмите ENTER.
*'''apropos''' поиск строки в заголовках и названиях документации ( дополнительно вводится слово для поиска). Выдаёт список всего найденного.
*'''cal''' форматированный календарь на текущий месяц ( добавить y и будет календарь на весь текущий год).
*'''date''' отображает текущие дату и время, по системным часам ядра.
*'''oclock''' простые часы, которые висят на рабочем столе (много дополнительных параметров).
*'''finger''' отображение информации о пользователе, имя которого указано в команде.
*'''hostname''' команда отображает идентификатор данного узла сети ( его имя). root может изменить имя узла на новое.
*'''hwclock''' встроенные часы Вашего компьютера.Для изменения даты и времени и синхронизации с системными часами, необходимы привелегии root.
*'''pwd''' отображает полный путь к текущему каталогу.
*'''tzselect''' запуск утилиты, которая позволяет выбрать часовой пояс.
*'''uname''' выводит информацию об используемой операционной системе (при вводе дополнительных параметров команды , выдаёт довольно много информации).
*'''uptime''' показывает текущее время, продолжительность сеанса , количество пользователей и загруженность процессора.
*'''users''' отображает краткий список пользователей работающих в системе в данный момент.
*'''w''' подробная информация о всех пользователях, работающих в данный момент и также простой, вход в систему и др.Если нужен один пользователь, то указать имя в параметре.
*'''whatis''' поиск по базе данных страниц руководства и отображение краткого описания.
*'''who''' список пользователей работающих в системе в данный момент.
*'''whereiz''' находит файлы, страницы справочного руководства для указанной команды.
*'''which''' показывает полный путь к исполняемому файлу команды.
*'''whoami''' показывает текущий идентификатор пользователя, работающего в данном терминале.
*'''write''' отправляет сообщение другому пользователю, находящемуся в системе, путём копирования строк с терминала отправителя на терминал получателя.
*'''wall''' отправляет сообщение на терминал каждого пользователя находящегося в системе в данный момент.
*'''history''' показывает пронумерованный список команд, которые Вы выполняли в этом и предыдущем сеансе. Если в списке историии их довольно много, то увидите последние.
*'''jobs''' выводит список всех выполняемых и приостановленных задач.
*'''kill''' завершить процесс (необходимо указать какой).
*'''killall''' позволят управлять процессами используя их имена или имена файлов, а не идентификаторы как в kill. Завершаются все указанные процессы.
*'''kernelversion''' показывает основную и дополнительную версии ядра.
*'''nice''' позволяет отобразить или настроить приоритет задачи.
*'''ps''' выводит список всех работающих процессов.
*'''pstree''' показывает иерархию процессов системы, что хорошо показывает их взаимозависимость.
*'''renice''' задаёт приоритет для указанной задачи.
*'''script''' позволяет записывать весь вывод с терминала в файл.Что бы остановить запись нажмите Ctrl+d.Если имя файла не указано то записывается в typescript.
*'''times''' показывает полное время выполнения процессов для всей системы и данного пользователя.
*'''top''' запускает программу , которая позволяет управлять процессами.И ещё много дополнительной, полезной информации.
*'''cd''' смена текущего каталога.По умолчанию переходит в домашний каталог текущего пользователя (если без параметров).
*'''dir''' отображает файлы в текущем каталоге в алфавитном порядке и с учётом регистра.
*'''file''' показывает тип содержимого указанного файла(текст, выполняемый, данные).
*'''find''' поиск файлов в текущем каталоге.Если указать путь, можно искать везде.
*'''free''' отображает информацию об оперативной памяти, подкачки, кэше,свободная памать, общая и т.д.
*'''ls''' показывает все файлы в текущем каталоге в алфавитном порядке.Аналогична dir.
*'''last''' показывает список пользователей, которые заходили в систему с момента создания файла /var/log/wtmp.
*'''lastlog''' проверяет историю входа в систему зарегистрированных пользователей.Форматирует и выводит на печать файл /var/log/lastlog.
*'''logger''' посылает запрос демону syslogd с просьбой поместить сообщение в системный журнал.
*'''lpr''' отправляет документ на печать демону печати.
*'''chmod''' изменяет режим доступа к файлу.Символьный или числовой формат.
*'''chown''' смена владельца указанного файла.Требуется доступ root.
*'''chage''' применяется для изменения срока действия учетной записи.Для администрирования.
*'''chfn''' изменяет сведения о пользователе в файле /etc/passwd из которого берёт информацию команда finger .
*'''chgrp''' команда для администратора,для изменения группы владельцев файла.
*'''clear''' очищает экран терминала (если это возможно).
*'''crontab''' обеспечивает возможность выполнения определённых задач по расписанию. Чаще используется администратором, хотя свои задачи могут быть и у пользователей.
*'''csplit''' разбивает файл на несколько частей.Надо задать метод разбивки (строки и т.д.).
*'''cp''' копирует один файл в другой, или несколько файлов в каталог.
*'''dd''' копирование файла с одновременным выполнением различных, дополнительных преобразований.
*'''dc''' калькулятор.
*'''debugfs''' применяется для восстановления файловой системы (ext2,ext3) если недостаточно команды fsck.
*'''df''' показывает количество используемого и свободного дискового пространства для всех подключенных разделов файловой системы.
*'''du''' показывает количество блоков диска, занятых каждым из файлов каталога.
*'''mc''' запускает программу Midnight Commander диспетчер файлов в текстовой консоли. Напоминает MSDOS менеджеры и довольно проста и удобна в использовании.Очень много нужных и удобных функций.
*'''mkdir''' создание указанного каталога.
*'''man''' справочное руководство.
*'''mcat''' копирует необработанные данные на дискету.
*'''mcopy''' использует отформатированную дискету MSDOS для копирования файлов в Линукс и из Линукс без предварительного подключения дискеты к файловой системе.
*'''mdel''' удаляет файл на отформатированной дискете MSDOS.
*'''mdir''' отображает содержимое каталога на дискете MSDOS.
*'''mdu''' показывает дисковое пространство занятое каталогом MSDOS.
*'''mesg''' контролирует доступ к Вашему терминалу, что бы коллеги не могли засыпать Вас сообщениями с помощью команды write
*'''mformat''' создаёт на дискете файловую систему MSDOS.
*'''mkbootdisk''' применяется в некоторых дистрибутивах, для создания загрузочной дискеты, содержащей всё необходимое для аварийной загрузки.
*'''mktemp''' создаёт уникальное имя файла для временной работы.
*'''mlabel''' создаёт метку тома на MSDOS на отформатированной дискете.
*'''mmd''' создаёт подкаталог MSDOS на отформатированной дискете.
*'''mmount''' подключает к файловой системе отформатированное устройство MSDOS.
*'''mmove''' перемещает или переименовывает файл на дискете MSDOS.
*'''more''' средство постраничного просмотра текстового файла.
*'''mv''' переименовывает или перемещает файлы или каталоги.
*'''rm''' удаление указанного файла.Можно и много удалить.
*'''rmdir''' удаление указанного пустого каталога.
*'''safedelete''' удалиние указанного файла в каталог safedelete,где он хранится некоторое время перед необратимым удалением.
*'''stat''' отображение всей доступной информации об указанном файле.
*'''touch''' изменяет время последнего доступа или изменения файла на текущее время.
*'''undelete''' восстанавливает файлы удалённые командой safedelete.
*'''wc''' показывает число строк, слов и символов в файле.
*'''bunzip2''' распаковывает указанный файл на 30%быстрей чем gzip.
*'''bzip2''' сжимает указанный файл по ускоренному алгоритму.
*'''bzip2recover''' делает попытку восстановить данные из повреждённого файла сжатого bzip2.
*'''compress''' сжимает указанный файл по другому алгоритму.
*'''uncompress'''Полужирное начертание распаковывает файл сжатый предыдущей командой.
*'''cpio''' позволяет создавать архивы и извлекать из архивов файлы.Позволяет копировать файлы. Необходимо указывать соответствующие параметры.
*'''gpg''' позволяет зашифровать и расшифровать файл.Метод шифрования открытым ключом. Позволяет создавать электронные подписи.Если этой программы нет у Вас, скачайте http://www.gnupg.org
*'''gzip''' сжимает указанный файл.
*'''gunzip''' распаковывает указанный файл (расширения .Z,.gz,.tgz,.zip ).
*'''gzexe''' позволяет сжать исполняемый файл с указанным именем так, что бы он автоматически распаковывался и выполнялся, когда пользователь даёт команду на выполнение сжатого файла.
*'''gpasswd''' устанавливает пароль группы.
*'''mcrypt''' Шифрует указанный файл.Создаётся новый файл в рабочем каталоге с расширением .enc. Вам будет предложено ввести пароль.Не забудьте его.
*'''mdecrypt''' расшифровывает это же файл.Если этих утилит нет, скачайте http://mcrypt/hellug.grl
*'''tar''' помещает два и более файлов в новый или существующий архив или извлекает их из архива.При задании каталога, заархивирует все файлы в каталоге и подкаталоге.
*'''talk''' позволяет вести интерактивный диалог с пользователем сети ИНТЕРНЕТ.
*'''tee''' отсылет выходные данные на два устройства вывода.Можно одновременно вывести на экран и в файл.
*'''toe''' выдаёт сведения о существующих терминалах, которые могут быть использованы для дальнейшей работы.
*'''touch''' изменяет время создания файла на текущее.Если файл не существует, то создаёт новый, пустой файл.
*'''unarj''' распаковывает или выводит список содержимого указанного архива в формате .ARJ(формат сжатия MS DOS).
*'''unzip''' распаковывает и извлекает файлы из архивов , созданных утилитами ZIP ( Linux,MS DOS,Microsoft Windows ).
*'''zip''' архивирует и сжимает файлы.
*'''zipinfo''' отображает информацию о содержимом архива.Если указать имя, то выдаст информацию о конкретном файле.
*'''zipnote''' позволяет вывести и отредактировать комментарии к файлам из архива ZIP.
*'''zipsplit''' позволяет разделить архив zip на достаточно маленькие части, для записи их на сменные носители, и записывает файлы на указанное устройство(дискеты).
*'''zforce''' добавляет расширение .gz ко всем файлам в рабочем каталоге, или к указанному файлу, которые были сжаты, но не имеют расширения.Т.е. предотвращает повторное сжатие.
*'''uuencode''' кодирует двоичный файл для передачи по ASC11сетям.
*'''uudecode''' декодирует выше названный файл.
*'''autorun''' автоматически распознаёт все доступные приводы CDROM в системе, монтирует их при вставке диска и может запускать отдельные приложения (например проигрыватель).Для использования, необходимо добавить параметры в файл привода.
*'''badblocks''' проверить указанное устройство на наличие повреждённых секторов (указать устройство).
*'''eject''' извлекает носитель из указанного устройства.Если устройство смонтировано то команда производит размонтирование перед извлечением носителя.
*'''e2fsck''' проверяет и при необходимости восстанавливает повреждённый том файловой системы (ext2,ext3).
*'''echo''' выводит строку текста на стандартное устройство вывода.
*'''fdformat''' форматирование гибкого диска.Дополнительно вводится имя устройства и необходимый вид форматирования.
*'''fg''' переводит процесс выполняемый в фоновом режиме в приоритетный режим.
*'''fgconsole''' показывает количество активных виртуальных консолей.
*'''fsck''' проверяет и восстанавливает файловую систему.
*'''mount''' монтирование файловой системы.
*'''umount''' отмонтирование файловой системы (в обоих командах необходимо указать, что именно).
*'''rdev''' при вызове без параметров выводит информацию о текущей файловой системе.
*'''rcp''' применяется для копирования файлов с одного компьютера на другой.
*'''rdate''' получает значение даты и времени от другого узла сети.Используется для синхронизации системного времени узлов.
*'''rename''' переименовывает файлы.Очень удобно, когда много файлов.
*'''resize''' изменяет размер окна виртуального терминала в графическом окружении.
*'''restore''' восстанавливает файлы заархивированные с помощью команды dump.
*'''runlevel''' отображает текущий и предыдущий уровни выполнения.
*'''shred''' выполняет безопасное удаление файла предварительно перезаписав его содержимое на другой диск.
*'''sleep''' приостанавливает начало выполнения процесса на заданное количество секунд.
*'''usleep''' приостанавливает на микросекунды.
*'''sync''' очищает буферы файловой системы.
*'''cmp''' производит быстрое сравнение двух указанных файлов.Если они идентичны, то никакие сообщения не выводятся.
*'''column''' форматирует входной текст из указанного файла в список из пяти колонок.
*'''diff''' сравнивает два указанных текстовых файла.Каждое отличие выводится в контексте. Позволяет сравнивать каталоги.
*'''diff3''' сравнивает три указанных файла и выводит результаты.
*'''enscript''' преобразует указанный текстовый файл в формат Post Script.Вывод может быть направлен на печать или записан в файл.
*'''fmt''' данная утилита производит форматирование каждой строки в указанном файле таким образом, что все строки имеют одинаковую ширину.
*'''head''' утилита выводит первые десять строк файла.Можно и несколько файлов.
*'''ispell''' запуск интерактивной утилиты для проверки орфографии в указанном файле.
*'''id''' отображает действующие значения идентификаторов пользователя и группы для текущего пользователя.
*'''ifconfig''' отображает состояние текущей конфигурации сети или настраивает сетевой интерфейс.
*'''less''' отображает содержимое указанного файла на экране и позволяет удобно просмотреть.
*'''nl''' команда нумерует строки в указанном файле.
*'''paste''' обьединяет соответствующие строки файлов в колонки.При желании можно обьединить несколько файлов.
*'''pdf2ps''' преобразует файл формата PDF в Post Script.Результат записывает на диск.
*'''pdftotext''' преобразует файл из формата PDF в текст и записывает результат на диск.
*'''pr''' подготавливает текст к печати, осуществляя форматирование с разбиением на страницы.Можно подготовить несколько файлов.
*'''sort''' команда позволяет отсортировать строки файла в алфавитном порядке.
*'''split''' разбивает файл на части.
*'''zcat;zmore''' выводит содержимое файла сжатого gzip на экран без распаковки.
*'''zcmp''' сравнивает сжатые gzip два файла без распаковки.
*'''zdiff''' сравнивает сжатые gzip два файла без распаковки.
*'''zegrep;zfgrep;zgrep''' осуществляют поиск указанной строки, выражения в файле сжатом gzip, без распаковки.
*'''aumix''' запускает в интерактивном режиме утилиту, которая управляет различными настройками звуковой карты.
*'''cdda2wav''' утилита предназначена для записи звуковых дорожек с аудиокомпакт диска в файлы формата WAV.Если имя файла не указано, то запись идёт в файл audio.wav в текущем каталоге.
*'''cdlabelgen''' команда предназначена для подготовки обложек к коробкам компакт дисков. Результат в файле формата Post Script.Требуется наличие интерпретатора языка Perl не ниже 5.003 версии.
*'''cdp''' запуск проигрывателя аудиокомпакт дисков в текстовом режиме.
*'''cdparanoia''' считывает звуковые дорожки с аудиокомпактов и записывает в файлы WAV,AIFF,RAW.
*'''combine''' обьединяет два и более графических файла в один.Огромное количество спецэффектов.Является частью пакета Image Magick и можно взять http://www.imagemagick.org
*'''convert''' преобразует указанный входной графический файл, в выходной.Распознаёт множество форматов. Скачать так же как и предидущую.
*'''identify''' определяет формат и характеристики графического файла и проверяет целостность и наличие ошибок.
*'''mogrify''' преобразует графический файл и перезаписывает исходный.
*'''montage''' преобразование нескольких файлов в обьединённое изображение.Скачать http://www.imagemagick.org
*'''mpg123''' воспроизводит на основном устройстве воспроизведения аудио файл в формате MP3. Вписывается имя файла или его адрес в Интернет.Чтобы остановить воспроизведение Ctrl+c.Что бы остановить и выйти из программы Ctrl+c нажать дважды.
*'''play''' воспроизводит звуковой файл с указанным именем.Автоматически распознаёт тип файла. Позволяет добавлять различные звуковые эффекты к воспроизводимым файлам.
*'''playmidi''' воспроизводит зуковые файлы в формате MIDI.
*'''rec''' записывает входной сигнал с микрофона или других входов в звуковой файл. Тип файла следует указать с помощью параметра (type).Есть возможность добавить звуковые эффекты.
*'''sox''' преобразует сэмплы из формата входного сигнала, на выходной с добавлением эффектов.
*'''emacs''' запуск текстового редактора Emacs.
*'''joe''' простой в использовании редактор работающий в текстовом режиме.
*'''pico''' простой и удобный в использовании текстовый редактор.Удобен для редактирования конфигурационных и простых файлов.
*'''vi''' запуск классического текстового редактора VI для UNIX систем.
*'''dmesg''' выводит на экран сообщения ядра, включая отображаемые при запуске и потом. Что бы удобней читать, вводите dmesg|less.
*'''groupadd''' создание группы пользователей с указанным именем.
*'''groupdel''' удаляет группу с указанным именем.
*'''groupmod''' изменяет параметры группы с указанным именем.
*'''mkpasswd''' создаёт высококачественный пароль, состоящий по умолчанию из девяти символов и содержащий по крайней мере буквы в разном регистре и цифры.
*'''passwd''' позволяет пользователю с указанным именем изменять пароль своей учётной записи. root может изменить пароль любого пользователя.
*'''pwgen''' создаёт высококачественный пароль,который хорошо запоминается.Длинна пароля указывается числом. Если этой утилиты нет, скачать  http://metalab.unc.edu/pub/Linux/system/security
*'''quota''' показывает текущую статистику использования диска и текущие ограничения для пользователя или группы с указанным именем.
*'''quotacheck''' исследует файловую систему на предмет использования дискового пространства.
*'''quotaon''' включает и отключает ограничения на использование дискового пространства.
*'''rpm''' запускает менеджер пакетов, утилиту,позволяющую устанавливать , проверять и обновлять пакеты с расширением rpm.
*'''rpmfind''' поиск нужного пакета в базе пакетов RPM через ИНТЕРНЕТ.Последняя версия утилиты http://www.rpm.org
*'''tmpwatch''' удаление всех файлов в указанном каталоге, если к ним не осуществлялся доступ в течении последних n часов.Очищает временные каталоги.
*'''useradd''' создание нового пользователя с указанным именем.
*'''userdel''' удаляет пользователя с указанным именем.
*'''usermod''' изменяет параметры пользователя с указанным именем.
*'''fetchmail''' утилита получения почты.Роботает в фоновом режиме.Скачивает почту с указанного сервера. Если её нет, скачать можно http://www.freshmeat.net
*'''ftp''' устанавливает соединение с указанным узлом и позволяет скачивать или закачивать файлы.
*'''lynx''' запуск консольного WEBброузера.
*'''mail''' утилита редактирования и просмотра электронной почты.Отправка и получение писем.
*'''netstat''' вывод информации о сетевой подсистеме.Очень много настроек и параметров.
*'''ping''' отправка на указанный адрес пакетов для проверки возможности соединения с этим узлом.
*'''telnet''' открывает окно терминала на удалённом узле и запускает интерактивный сеанс.
*'''wvdia'''l программа подключается к ИНТЕРНЕТ по протоколу PPP с использованием параметров, хранящихся в файле /etc/wvdial.conf
*'''wvdialconf''' осуществляет поиск модема, определяет порт, к которому он подключен, его строку инициализации и максимальную скорость передачи данных.Эта информация автоматически записывается в файл (смотри выше).Требуется доступ root.
*'''ar''' средство архивирования, предназначено для создания и распаковки архива.
*'''arch''' отображает данные об архитектуре центрального процессора.
*'''at''' ставит задания в очередь для последующего выполнения в указанное время.
*'''atq''' показывает список заданий которые поставлены в очередь на выполнение.


== Консольные команды. Часть 5, управляем файлами-пакетами deb в консоли. ==
Protocol
--------


Приведу примеры использования утилит dpkg и apt отвечающих за управления пакетами в системах семейства Debian.
The beanstalk protocol runs over TCP using ASCII encoding. Clients connect,
send commands and data, wait for responses, and close the connection. For each
connection, the server processes commands serially in the order in which they
were received and sends responses in the same order. All integers in the
protocol are formatted in decimal and (unless otherwise indicated)
nonnegative.


'''DPKGdpkg -i имя_пакета '''установит или обновит ранее установленный пакет.
Names, in this protocol, are ASCII strings. They may contain letters (A-Z and
'''dpkg -r имя_пакета''' удалит ранее установленный пакет, но сохранит файл конфигурации.
a-z), numerals (0-9), hyphen ("-"), plus ("+"), slash ("/"), semicolon (";"),
'''dpkg -l '''отобразит список всех установленных пакетов.
dot ("."), dollar-sign ("$"), underscore ("_"), and parentheses ("(" and ")"),
'''dpkg -l | grep tux '''отобразит список всех установленных пакетов с именем "tux".
but they may not begin with a hyphen. They are terminated by white space
'''dpkg -s имя_пакета''' имя_пакета отобразит информацию по конкретному пакету.
(either a space char or end of line). Each name must be at least one character
'''dpkg -P у '''удалит ранее установленный пакет и удалит файл конфигурации.
long.


'''APTapt-get install имя_пакета '''установит пакет.
The protocol contains two kinds of data: text lines and unstructured chunks of
'''apt-get update '''получить список пакетов доступных для обновления.
data. Text lines are used for client commands and server responses. Chunks are
'''apt-get upgrade '''обновит все установленные пакеты.
used to transfer job bodies and stats information. Each job body is an opaque
'''apt-get remove имя_пакета '''удалит пакет.
sequence of bytes. The server never inspects or modifies a job body and always
'''apt-get check '''поможет узнать о конфликтующих пакетов, а также поломанных зависимостях пакетов .
sends it back in its original form. It is up to the clients to agree on a
'''apt-get -f install''' исправит выявлены нарушенные зависимости.
meaningful interpretation of job bodies.


'''Вам могут быть полезны следующие опции:
The client may issue the "quit" command, or simply close the TCP connection
'''apt-get -h''' справка
when it no longer has use for the server. However, beanstalkd performs very
'''apt-get -d''' только загрузить - не устанавливать и не распаковывать архивы
well with a large number of open connections, so it is usually better for the
'''apt-get -s''' ничего не делать, имитировать выполнение
client to keep its connection open and reuse it as much as possible. This also
'''apt-get -y '''предполагается ответ Yes на все вопросы, сами вопросы не выводить
avoids the overhead of establishing new TCP connections.
'''apt-get -f''' продолжать, даже если проверка целостности не удачна
'''apt-get -u''' плюс ко всему показывать список обновленных пакетов


Скачанные из сети файлы помещаются в каталог '''/var/cache/apt/archives''' их всегда можно найти и удалить используя команду
If a client violates the protocol (such as by sending a request that is not
'''apt-get clean'''
well-formed or a command that does not exist) or if the server has an error,
the server will reply with one of the following error messages:


== Изучаем CronTab. ==
- "OUT_OF_MEMORY\r\n" The server cannot allocate enough memory for the job.
'''CronTab''' – это утилита позволяющая в определенный день и час '''автоматически запускать''' различные программы или скрипты. Согласитесь, очень удобно.
  The client should try again later.


Структура файла с заданиями для '''CronTab.'''
- "INTERNAL_ERROR\r\n" This indicates a bug in the server. It should never
  happen. If it does happen, please report it at
  http://groups.google.com/group/beanstalk-talk.


* <nowiki>* * * * command</nowiki>
- "BAD_FORMAT\r\n" The client sent a command line that was not well-formed.
* - - - - -
  This can happen if the line does not end with \r\n, if non-numeric
* | | | | |
  characters occur where an integer is expected, if the wrong number of
* | | | | +----- День недели (0 - 6) (Sunday=0)
  arguments are present, or if the command line is mal-formed in any other
* | | | +------- Месяц года (1 — 12)
  way.
* | | +--------- День месяца (1 — 31)
* | +----------- Час дня запуска (0 — 23)
* +------------- Минута часа для запуска (0 - 59)


command запускаемая программа или скрипт.
- "UNKNOWN_COMMAND\r\n" The client sent a command that the server does not
  know.


Значок * задаёт параметр (день, год, месяц, час).
These error responses will not be listed in this document for individual
commands in the following sections, but they are implicitly included in the
description of all commands. Clients should be prepared to receive an error
response after any command.


'''Пример'''
As a last resort, if the server has a serious error that prevents it from
continuing service to the current client, the server will close the
connection.


'''01 * * * * command''' запуск программы или скрипта каждый час в одну минуту.
Job Lifecycle
-------------


'''<nowiki>* 6 * * * command</nowiki>''' запуск программы или скрипта каждый день в 6 часов утра.
A job in beanstalk gets created by a client with the "put" command. During its
life it can be in one of four states: "ready", "reserved", "delayed", or
"buried". After the put command, a job typically starts out ready. It waits in
the ready queue until a worker comes along and runs the "reserve" command. If
this job is next in the queue, it will be reserved for the worker. The worker
will execute the job; when it is finished the worker will send a "delete"
command to delete the job.


Значения могут быть числом, трех-буквенным названием, а так же диапазоном например запись «1-5» в поле day будет означать «с понедельника по пятницу». Значения могут отделяться запятыми: «1,15,31» в поле day будет запускать указанную команду 1-го, 15-го и 31-го числа каждого месяца.
Here is a picture of the typical job lifecycle:


Все пять полей времени допускают использование символа звездочка – «*», который обозначает «использовать любое допустимое значение» для этого поля.


'''Для создания задания используйте ниже приведённые команды:'''
  put            reserve              delete
  -----> [READY] ---------> [RESERVED] --------> *poof*


'''crontab -e''' Изменит Ваш crontab файл или создаст новый.
'''crontab -l''' Отобразит содержимое существующего crontab файла.
'''crontab -r''' Удалит Ваш crontab файл.
'''crontab -v''' Отобразит когда в последний раз Вы изменяли свой crontab файла.


'''Сложно работать с консольным редактором?'''Правьте файлы привычным текстовым редактором... Например используйте Gedit.


'''Файлы с заданиями можно найти тут:'''/usr/lib/cronОсновной каталог команд, связанных со временем./usr/spool/cron/crontabsКаталог файлов регулярных действий./usr/lib/cron/logУчетная информация./usr/lib/cron/cron.allowСписок пользователей, которым разрешено выполнять команду crontab./usr/lib/cron/cron.denyСписок пользователей, которым запрещено выполнять команду crontab.
Here is a picture with more possibilities:


  '''hwclock''' - посмотреть время в БИОС
 
  '''/etc/adjtime''' - показывает отклонение часов и какое время они показывают, локальное или UTC
 
  '''/etc/timezone файл''' - используется для установки переменной окружения
  put with delay              release with delay
  '''etc/sysconfig/clock''' -  
  ----------------> [DELAYED] <------------.
  '''sudo dpkg-reconfigure tzdata''' - установка часового пояса
                        |                  |
  '''date 110114312011.00''' - 11-месяц-01-день14-час31-минуты-2011-год.00-секунды - системное время
                        | (time passes)    |
  '''sudo hwclock -w''' - записать системное время в БИОС
                        |                  |
  put                  v    reserve      |      delete
  -----------------> [READY] ---------> [RESERVED] --------> *poof*
                      ^  ^                |  |
                      |  \ release      |  |
                      |    `-------------'   |
                      |                      |
                      | kick                |
                      |                      |
                      |      bury          |
                    [BURIED] <---------------'
                      |
                      |  delete
                        `--------> *poof*
 
 
The system has one or more tubes. Each tube consists of a ready queue and a
delay queue. Each job spends its entire life in one tube. Consumers can show
interest in tubes by sending the "watch" command; they can show disinterest by
sending the "ignore" command. This set of interesting tubes is said to be a
consumer's "watch list". When a client reserves a job, it may come from any of
the tubes in its watch list.
 
When a client connects, its watch list is initially just the tube named
"default". If it submits jobs without having sent a "use" command, they will
live in the tube named "default".
 
Tubes are created on demand whenever they are referenced. If a tube is empty
(that is, it contains no ready, delayed, or buried jobs) and no client refers
to it, it will be deleted.
 
Producer Commands
-----------------
 
The "put" command is for any process that wants to insert a job into the queue.
It comprises a command line followed by the job body:
 
put <pri> <delay> <ttr> <bytes>\r\n
<data>\r\n
 
It inserts a job into the client's currently used tube (see the "use" command
below).
 
- <pri> is an integer < 2**32. Jobs with smaller priority values will be
  scheduled before jobs with larger priorities. The most urgent priority is 0;
  the least urgent priority is 4,294,967,295.
 
- <delay> is an integer number of seconds to wait before putting the job in
  the ready queue. The job will be in the "delayed" state during this time.
 
- <ttr> -- time to run -- is an integer number of seconds to allow a worker
  to run this job. This time is counted from the moment a worker reserves
  this job. If the worker does not delete, release, or bury the job within
  <ttr> seconds, the job will time out and the server will release the job.
  The minimum ttr is 1. If the client sends 0, the server will silently
  increase the ttr to 1.
 
- <bytes> is an integer indicating the size of the job body, not including the
  trailing "\r\n". This value must be less than max-job-size (default: 2**16).
 
- <data> is the job body -- a sequence of bytes of length <bytes> from the
  previous line.
 
After sending the command line and body, the client waits for a reply, which
may be:
 
- "INSERTED <id>\r\n" to indicate success.
 
  - <id> is the integer id of the new job
 
- "BURIED <id>\r\n" if the server ran out of memory trying to grow the
  priority queue data structure.
 
  - <id> is the integer id of the new job
 
- "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
  "\r\n". These two bytes are not counted in the job size given by the client
  in the put command line.
 
- "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
  than max-job-size bytes.
 
- "DRAINING\r\n" This means that the server has been put into "drain mode"
  and is no longer accepting new jobs. The client should try another server
  or disconnect and try again later.
 
The "use" command is for producers. Subsequent put commands will put jobs into
the tube specified by this command. If no use command has been issued, jobs
will be put into the tube named "default".
 
use <tube>\r\n
 
- <tube> is a name at most 200 bytes. It specifies the tube to use. If the
  tube does not exist, it will be created.
 
The only reply is:
 
USING <tube>\r\n
 
- <tube> is the name of the tube now being used.
 
Worker Commands
---------------
 
A process that wants to consume jobs from the queue uses "reserve", "delete",
"release", and "bury". The first worker command, "reserve", looks like this:
 
reserve\r\n
 
Alternatively, you can specify a timeout as follows:
 
reserve-with-timeout <seconds>\r\n
 
This will return a newly-reserved job. If no job is available to be reserved,
beanstalkd will wait to send a response until one becomes available. Once a
job is reserved for the client, the client has limited time to run (TTR) the
job before the job times out. When the job times out, the server will put the
job back into the ready queue. Both the TTR and the actual time left can be
found in response to the stats-job command.
 
If more than one job is ready, beanstalkd will choose the one with the
smallest priority value. Within each priority, it will choose the one that
was received first.
 
A timeout value of 0 will cause the server to immediately return either a
response or TIMED_OUT.  A positive value of timeout will limit the amount of
time the client will block on the reserve request until a job becomes
available.
 
During the TTR of a reserved job, the last second is kept by the server as a
safety margin, during which the client will not be made to wait for another
job. If the client issues a reserve command during the safety margin, or if
the safety margin arrives while the client is waiting on a reserve command,
the server will respond with:
 
DEADLINE_SOON\r\n
 
This gives the client a chance to delete or release its reserved job before
the server automatically releases it.
 
TIMED_OUT\r\n
 
If a non-negative timeout was specified and the timeout exceeded before a job
became available, or if the client's connection is half-closed, the server
will respond with TIMED_OUT.
 
Otherwise, the only other response to this command is a successful reservation
in the form of a text line followed by the job body:
 
RESERVED <id> <bytes>\r\n
<data>\r\n
 
- <id> is the job id -- an integer unique to this job in this instance of
  beanstalkd.
 
- <bytes> is an integer indicating the size of the job body, not including
  the trailing "\r\n".
 
- <data> is the job body -- a sequence of bytes of length <bytes> from the
  previous line. This is a verbatim copy of the bytes that were originally
  sent to the server in the put command for this job.
 
The delete command removes a job from the server entirely. It is normally used
by the client when the job has successfully run to completion. A client can
delete jobs that it has reserved, ready jobs, delayed jobs, and jobs that are
buried. The delete command looks like this:
 
delete <id>\r\n
 
- <id> is the job id to delete.
 
The client then waits for one line of response, which may be:
 
- "DELETED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the job does not exist or is not either reserved by the
  client, ready, or buried. This could happen if the job timed out before the
  client sent the delete command.
 
The release command puts a reserved job back into the ready queue (and marks
its state as "ready") to be run by any client. It is normally used when the job
fails because of a transitory error. It looks like this:
 
release <id> <pri> <delay>\r\n
 
- <id> is the job id to release.
 
- <pri> is a new priority to assign to the job.
 
- <delay> is an integer number of seconds to wait before putting the job in
  the ready queue. The job will be in the "delayed" state during this time.
 
The client expects one line of response, which may be:
 
- "RELEASED\r\n" to indicate success.
 
- "BURIED\r\n" if the server ran out of memory trying to grow the priority
  queue data structure.
 
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
 
The bury command puts a job into the "buried" state. Buried jobs are put into a
FIFO linked list and will not be touched by the server again until a client
kicks them with the "kick" command.
 
The bury command looks like this:
 
bury <id> <pri>\r\n
 
- <id> is the job id to release.
 
- <pri> is a new priority to assign to the job.
 
There are two possible responses:
 
- "BURIED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
 
The "touch" command allows a worker to request more time to work on a job.
This is useful for jobs that potentially take a long time, but you still want
the benefits of a TTR pulling a job away from an unresponsive worker.  A worker
may periodically tell the server that it's still alive and processing a job
(e.g. it may do this on DEADLINE_SOON). The command postpones the auto
release of a reserved job until TTR seconds from when the command is issued.
 
The touch command looks like this:
 
touch <id>\r\n
 
- <id> is the ID of a job reserved by the current connection.
 
There are two possible responses:
 
- "TOUCHED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
 
The "watch" command adds the named tube to the watch list for the current
connection. A reserve command will take a job from any of the tubes in the
watch list. For each new connection, the watch list initially consists of one
tube, named "default".
 
watch <tube>\r\n
 
  - <tube> is a name at most 200 bytes. It specifies a tube to add to the watch
  list. If the tube doesn't exist, it will be created.
 
The reply is:
 
WATCHING <count>\r\n
 
- <count> is the integer number of tubes currently in the watch list.
 
The "ignore" command is for consumers. It removes the named tube from the
watch list for the current connection.
 
ignore <tube>\r\n
 
The reply is one of:
 
- "WATCHING <count>\r\n" to indicate success.
 
  - <count> is the integer number of tubes currently in the watch list.
 
- "NOT_IGNORED\r\n" if the client attempts to ignore the only tube in its
  watch list.
 
Other Commands
--------------
 
The peek commands let the client inspect a job in the system. There are four
variations. All but the first operate only on the currently used tube.
 
- "peek <id>\r\n" - return job <id>.
 
- "peek-ready\r\n" - return the next ready job.
 
- "peek-delayed\r\n" - return the delayed job with the shortest delay left.
 
- "peek-buried\r\n" - return the next job in the list of buried jobs.
 
There are two possible responses, either a single line:
 
- "NOT_FOUND\r\n" if the requested job doesn't exist or there are no jobs in
  the requested state.
 
Or a line followed by a chunk of data, if the command was successful:
 
FOUND <id> <bytes>\r\n
<data>\r\n
 
- <id> is the job id.
 
- <bytes> is an integer indicating the size of the job body, not including
  the trailing "\r\n".
 
- <data> is the job body -- a sequence of bytes of length <bytes> from the
  previous line.
 
The kick command applies only to the currently used tube. It moves jobs into
the ready queue. If there are any buried jobs, it will only kick buried jobs.
Otherwise it will kick delayed jobs. It looks like:
 
kick <bound>\r\n
 
- <bound> is an integer upper bound on the number of jobs to kick. The server
  will kick no more than <bound> jobs.
 
The response is of the form:
 
KICKED <count>\r\n
 
- <count> is an integer indicating the number of jobs actually kicked.
 
The kick-job command is a variant of kick that operates with a single job
identified by its job id. If the given job id exists and is in a buried or
delayed state, it will be moved to the ready queue of the the same tube where it
currently belongs. The syntax is:
 
kick-job <id>\r\n
 
- <id> is the job id to kick.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the job does not exist or is not in a kickable state. This
  can also happen upon internal errors.
 
- "KICKED\r\n" when the operation succeeded.
 
The stats-job command gives statistical information about the specified job if
it exists. Its form is:
 
stats-job <id>\r\n
 
- <id> is a job id.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the job does not exist.
 
- "OK <bytes>\r\n<data>\r\n"
 
  - <bytes> is the size of the following data section in bytes.
 
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.
 
The stats-job data is a YAML file representing a single dictionary of strings
to scalars. It contains these keys:
 
- "id" is the job id
 
- "tube" is the name of the tube that contains this job
 
- "state" is "ready" or "delayed" or "reserved" or "buried"
 
- "pri" is the priority value set by the put, release, or bury commands.
 
- "age" is the time in seconds since the put command that created this job.
 
  - "time-left" is the number of seconds left until the server puts this job
  into the ready queue. This number is only meaningful if the job is
  reserved or delayed. If the job is reserved and this amount of time
  elapses before its state changes, it is considered to have timed out.
 
- "file" is the number of the earliest binlog file containing this job.
  If -b wasn't used, this will be 0.
 
- "reserves" is the number of times this job has been reserved.
 
- "timeouts" is the number of times this job has timed out during a
  reservation.
 
- "releases" is the number of times a client has released this job from a
  reservation.
 
- "buries" is the number of times this job has been buried.
 
- "kicks" is the number of times this job has been kicked.
 
The stats-tube command gives statistical information about the specified tube
if it exists. Its form is:
 
stats-tube <tube>\r\n
 
- <tube> is a name at most 200 bytes. Stats will be returned for this tube.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the tube does not exist.
 
- "OK <bytes>\r\n<data>\r\n"
 
  - <bytes> is the size of the following data section in bytes.
 
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.
 
The stats-tube data is a YAML file representing a single dictionary of strings
to scalars. It contains these keys:
 
- "name" is the tube's name.
 
- "current-jobs-urgent" is the number of ready jobs with priority < 1024 in
  this tube.
 
- "current-jobs-ready" is the number of jobs in the ready queue in this tube.
 
- "current-jobs-reserved" is the number of jobs reserved by all clients in
  this tube.
 
- "current-jobs-delayed" is the number of delayed jobs in this tube.
 
- "current-jobs-buried" is the number of buried jobs in this tube.
 
- "total-jobs" is the cumulative count of jobs created in this tube in
  the current beanstalkd process.
 
- "current-using" is the number of open connections that are currently
  using this tube.
 
- "current-waiting" is the number of open connections that have issued a
  reserve command while watching this tube but not yet received a response.
 
- "current-watching" is the number of open connections that are currently
  watching this tube.
 
- "pause" is the number of seconds the tube has been paused for.
 
- "cmd-delete" is the cumulative number of delete commands for this tube
 
- "cmd-pause-tube" is the cumulative number of pause-tube commands for this
  tube.
 
- "pause-time-left" is the number of seconds until the tube is un-paused.
 
The stats command gives statistical information about the system as a whole.
Its form is:
 
stats\r\n
 
The server will respond:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
- <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file with statistical information represented a dictionary.
 
The stats data for the system is a YAML file representing a single dictionary
of strings to scalars. Entries described as "cumulative" are reset when the
beanstalkd process starts; they are not stored on disk with the -b flag.
 
- "current-jobs-urgent" is the number of ready jobs with priority < 1024.
 
- "current-jobs-ready" is the number of jobs in the ready queue.
 
- "current-jobs-reserved" is the number of jobs reserved by all clients.
 
- "current-jobs-delayed" is the number of delayed jobs.
 
- "current-jobs-buried" is the number of buried jobs.
 
- "cmd-put" is the cumulative number of put commands.
 
- "cmd-peek" is the cumulative number of peek commands.
 
- "cmd-peek-ready" is the cumulative number of peek-ready commands.
 
- "cmd-peek-delayed" is the cumulative number of peek-delayed commands.
 
- "cmd-peek-buried" is the cumulative number of peek-buried commands.
 
- "cmd-reserve" is the cumulative number of reserve commands.
 
- "cmd-use" is the cumulative number of use commands.
 
- "cmd-watch" is the cumulative number of watch commands.
 
- "cmd-ignore" is the cumulative number of ignore commands.
 
- "cmd-delete" is the cumulative number of delete commands.
 
- "cmd-release" is the cumulative number of release commands.
 
- "cmd-bury" is the cumulative number of bury commands.
 
- "cmd-kick" is the cumulative number of kick commands.
 
- "cmd-stats" is the cumulative number of stats commands.
 
- "cmd-stats-job" is the cumulative number of stats-job commands.
 
- "cmd-stats-tube" is the cumulative number of stats-tube commands.
 
- "cmd-list-tubes" is the cumulative number of list-tubes commands.
 
- "cmd-list-tube-used" is the cumulative number of list-tube-used commands.
 
- "cmd-list-tubes-watched" is the cumulative number of list-tubes-watched
  commands.
 
- "cmd-pause-tube" is the cumulative number of pause-tube commands.
 
- "job-timeouts" is the cumulative count of times a job has timed out.
 
- "total-jobs" is the cumulative count of jobs created.
 
- "max-job-size" is the maximum number of bytes in a job.
 
- "current-tubes" is the number of currently-existing tubes.
 
- "current-connections" is the number of currently open connections.
 
- "current-producers" is the number of open connections that have each
  issued at least one put command.
 
- "current-workers" is the number of open connections that have each issued
  at least one reserve command.
 
- "current-waiting" is the number of open connections that have issued a
  reserve command but not yet received a response.
 
- "total-connections" is the cumulative count of connections.
 
- "pid" is the process id of the server.
 
- "version" is the version string of the server.
 
- "rusage-utime" is the cumulative user CPU time of this process in seconds
  and microseconds.
 
- "rusage-stime" is the cumulative system CPU time of this process in
  seconds and microseconds.
 
- "uptime" is the number of seconds since this server process started running.
 
- "binlog-oldest-index" is the index of the oldest binlog file needed to
  store the current jobs.
 
- "binlog-current-index" is the index of the current binlog file being
  written to. If binlog is not active this value will be 0.
 
- "binlog-max-size" is the maximum size in bytes a binlog file is allowed
  to get before a new binlog file is opened.
 
- "binlog-records-written" is the cumulative number of records written
  to the binlog.
 
- "binlog-records-migrated" is the cumulative number of records written
  as part of compaction.
 
  - "id" is a random id string for this server process, generated when each
  beanstalkd process starts.
 
  - "hostname" the hostname of the machine as determined by uname.
 
The list-tubes command returns a list of all existing tubes. Its form is:
 
list-tubes\r\n
 
The response is:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing all tube names as a list of strings.
 
The list-tube-used command returns the tube currently being used by the
client. Its form is:
 
list-tube-used\r\n
 
The response is:
 
USING <tube>\r\n
 
- <tube> is the name of the tube being used.
 
The list-tubes-watched command returns a list tubes currently being watched by
the client. Its form is:
 
list-tubes-watched\r\n
 
The response is:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
- <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing watched tube names as a list of strings.
 
The quit command simply closes the connection. Its form is:
 
quit\r\n
 
The pause-tube command can delay any new job being reserved for a given time. Its form is:
 
pause-tube <tube-name> <delay>\r\n
 
- <tube> is the tube to pause
 
  - <delay> is an integer number of seconds to wait before reserving any more
  jobs from the queue
 
There are two possible responses:
 
  - "PAUSED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the tube does not exist.

Версия от 08:14, 8 мая 2014

Beanstalk Protocol

Protocol


The beanstalk protocol runs over TCP using ASCII encoding. Clients connect, send commands and data, wait for responses, and close the connection. For each connection, the server processes commands serially in the order in which they were received and sends responses in the same order. All integers in the protocol are formatted in decimal and (unless otherwise indicated) nonnegative.

Names, in this protocol, are ASCII strings. They may contain letters (A-Z and a-z), numerals (0-9), hyphen ("-"), plus ("+"), slash ("/"), semicolon (";"), dot ("."), dollar-sign ("$"), underscore ("_"), and parentheses ("(" and ")"), but they may not begin with a hyphen. They are terminated by white space (either a space char or end of line). Each name must be at least one character long.

The protocol contains two kinds of data: text lines and unstructured chunks of data. Text lines are used for client commands and server responses. Chunks are used to transfer job bodies and stats information. Each job body is an opaque sequence of bytes. The server never inspects or modifies a job body and always sends it back in its original form. It is up to the clients to agree on a meaningful interpretation of job bodies.

The client may issue the "quit" command, or simply close the TCP connection when it no longer has use for the server. However, beanstalkd performs very well with a large number of open connections, so it is usually better for the client to keep its connection open and reuse it as much as possible. This also avoids the overhead of establishing new TCP connections.

If a client violates the protocol (such as by sending a request that is not well-formed or a command that does not exist) or if the server has an error, the server will reply with one of the following error messages:

- "OUT_OF_MEMORY\r\n" The server cannot allocate enough memory for the job.
  The client should try again later.
- "INTERNAL_ERROR\r\n" This indicates a bug in the server. It should never
  happen. If it does happen, please report it at
  http://groups.google.com/group/beanstalk-talk.
- "BAD_FORMAT\r\n" The client sent a command line that was not well-formed.
  This can happen if the line does not end with \r\n, if non-numeric
  characters occur where an integer is expected, if the wrong number of
  arguments are present, or if the command line is mal-formed in any other
  way.
- "UNKNOWN_COMMAND\r\n" The client sent a command that the server does not
  know.

These error responses will not be listed in this document for individual commands in the following sections, but they are implicitly included in the description of all commands. Clients should be prepared to receive an error response after any command.

As a last resort, if the server has a serious error that prevents it from continuing service to the current client, the server will close the connection.

Job Lifecycle


A job in beanstalk gets created by a client with the "put" command. During its life it can be in one of four states: "ready", "reserved", "delayed", or "buried". After the put command, a job typically starts out ready. It waits in the ready queue until a worker comes along and runs the "reserve" command. If this job is next in the queue, it will be reserved for the worker. The worker will execute the job; when it is finished the worker will send a "delete" command to delete the job.

Here is a picture of the typical job lifecycle:


  put            reserve               delete
 -----> [READY] ---------> [RESERVED] --------> *poof*


Here is a picture with more possibilities:


  put with delay               release with delay
 ----------------> [DELAYED] <------------.
                       |                   |
                       | (time passes)     |
                       |                   |
  put                  v     reserve       |       delete
 -----------------> [READY] ---------> [RESERVED] --------> *poof*
                      ^  ^                |  |
                      |   \  release      |  |
                      |    `-------------'   |
                      |                      |
                      | kick                 |
                      |                      |
                      |       bury           |
                   [BURIED] <---------------'
                      |
                      |  delete
                       `--------> *poof*


The system has one or more tubes. Each tube consists of a ready queue and a delay queue. Each job spends its entire life in one tube. Consumers can show interest in tubes by sending the "watch" command; they can show disinterest by sending the "ignore" command. This set of interesting tubes is said to be a consumer's "watch list". When a client reserves a job, it may come from any of the tubes in its watch list.

When a client connects, its watch list is initially just the tube named "default". If it submits jobs without having sent a "use" command, they will live in the tube named "default".

Tubes are created on demand whenever they are referenced. If a tube is empty (that is, it contains no ready, delayed, or buried jobs) and no client refers to it, it will be deleted.

Producer Commands


The "put" command is for any process that wants to insert a job into the queue. It comprises a command line followed by the job body:

put <pri> <delay> <ttr> <bytes>\r\n \r\n

It inserts a job into the client's currently used tube (see the "use" command below).

- <pri> is an integer < 2**32. Jobs with smaller priority values will be
  scheduled before jobs with larger priorities. The most urgent priority is 0;
  the least urgent priority is 4,294,967,295.
- <delay> is an integer number of seconds to wait before putting the job in
  the ready queue. The job will be in the "delayed" state during this time.
- <ttr> -- time to run -- is an integer number of seconds to allow a worker
  to run this job. This time is counted from the moment a worker reserves
  this job. If the worker does not delete, release, or bury the job within
  <ttr> seconds, the job will time out and the server will release the job.
  The minimum ttr is 1. If the client sends 0, the server will silently
  increase the ttr to 1.
- <bytes> is an integer indicating the size of the job body, not including the
  trailing "\r\n". This value must be less than max-job-size (default: 2**16).
-  is the job body -- a sequence of bytes of length <bytes> from the
  previous line.

After sending the command line and body, the client waits for a reply, which may be:

- "INSERTED <id>\r\n" to indicate success.
  - <id> is the integer id of the new job
- "BURIED <id>\r\n" if the server ran out of memory trying to grow the
  priority queue data structure.
  - <id> is the integer id of the new job
- "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
  "\r\n". These two bytes are not counted in the job size given by the client
  in the put command line.
- "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
  than max-job-size bytes.
- "DRAINING\r\n" This means that the server has been put into "drain mode"
  and is no longer accepting new jobs. The client should try another server
  or disconnect and try again later.

The "use" command is for producers. Subsequent put commands will put jobs into the tube specified by this command. If no use command has been issued, jobs will be put into the tube named "default".

use <tube>\r\n

- <tube> is a name at most 200 bytes. It specifies the tube to use. If the
  tube does not exist, it will be created.

The only reply is:

USING <tube>\r\n

- <tube> is the name of the tube now being used.

Worker Commands


A process that wants to consume jobs from the queue uses "reserve", "delete", "release", and "bury". The first worker command, "reserve", looks like this:

reserve\r\n

Alternatively, you can specify a timeout as follows:

reserve-with-timeout <seconds>\r\n

This will return a newly-reserved job. If no job is available to be reserved, beanstalkd will wait to send a response until one becomes available. Once a job is reserved for the client, the client has limited time to run (TTR) the job before the job times out. When the job times out, the server will put the job back into the ready queue. Both the TTR and the actual time left can be found in response to the stats-job command.

If more than one job is ready, beanstalkd will choose the one with the smallest priority value. Within each priority, it will choose the one that was received first.

A timeout value of 0 will cause the server to immediately return either a response or TIMED_OUT. A positive value of timeout will limit the amount of time the client will block on the reserve request until a job becomes available.

During the TTR of a reserved job, the last second is kept by the server as a safety margin, during which the client will not be made to wait for another job. If the client issues a reserve command during the safety margin, or if the safety margin arrives while the client is waiting on a reserve command, the server will respond with:

DEADLINE_SOON\r\n

This gives the client a chance to delete or release its reserved job before the server automatically releases it.

TIMED_OUT\r\n

If a non-negative timeout was specified and the timeout exceeded before a job became available, or if the client's connection is half-closed, the server will respond with TIMED_OUT.

Otherwise, the only other response to this command is a successful reservation in the form of a text line followed by the job body:

RESERVED <id> <bytes>\r\n \r\n

- <id> is the job id -- an integer unique to this job in this instance of
  beanstalkd.
- <bytes> is an integer indicating the size of the job body, not including
  the trailing "\r\n".
-  is the job body -- a sequence of bytes of length <bytes> from the
  previous line. This is a verbatim copy of the bytes that were originally
  sent to the server in the put command for this job.

The delete command removes a job from the server entirely. It is normally used by the client when the job has successfully run to completion. A client can delete jobs that it has reserved, ready jobs, delayed jobs, and jobs that are buried. The delete command looks like this:

delete <id>\r\n

- <id> is the job id to delete.

The client then waits for one line of response, which may be:

- "DELETED\r\n" to indicate success.
- "NOT_FOUND\r\n" if the job does not exist or is not either reserved by the
  client, ready, or buried. This could happen if the job timed out before the
  client sent the delete command.

The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. It looks like this:

release <id> <pri> <delay>\r\n

- <id> is the job id to release.
- <pri> is a new priority to assign to the job.
- <delay> is an integer number of seconds to wait before putting the job in
  the ready queue. The job will be in the "delayed" state during this time.

The client expects one line of response, which may be:

- "RELEASED\r\n" to indicate success.
- "BURIED\r\n" if the server ran out of memory trying to grow the priority
  queue data structure.
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.

The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command.

The bury command looks like this:

bury <id> <pri>\r\n

- <id> is the job id to release.
- <pri> is a new priority to assign to the job.

There are two possible responses:

- "BURIED\r\n" to indicate success.
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.

The "touch" command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on DEADLINE_SOON). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued.

The touch command looks like this:

touch <id>\r\n

- <id> is the ID of a job reserved by the current connection.

There are two possible responses:

- "TOUCHED\r\n" to indicate success.
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.

The "watch" command adds the named tube to the watch list for the current connection. A reserve command will take a job from any of the tubes in the watch list. For each new connection, the watch list initially consists of one tube, named "default".

watch <tube>\r\n

- <tube> is a name at most 200 bytes. It specifies a tube to add to the watch
  list. If the tube doesn't exist, it will be created.

The reply is:

WATCHING <count>\r\n

- <count> is the integer number of tubes currently in the watch list.

The "ignore" command is for consumers. It removes the named tube from the watch list for the current connection.

ignore <tube>\r\n

The reply is one of:

- "WATCHING <count>\r\n" to indicate success.
  - <count> is the integer number of tubes currently in the watch list.
- "NOT_IGNORED\r\n" if the client attempts to ignore the only tube in its
  watch list.

Other Commands


The peek commands let the client inspect a job in the system. There are four variations. All but the first operate only on the currently used tube.

- "peek <id>\r\n" - return job <id>.
- "peek-ready\r\n" - return the next ready job.
- "peek-delayed\r\n" - return the delayed job with the shortest delay left.
- "peek-buried\r\n" - return the next job in the list of buried jobs.

There are two possible responses, either a single line:

- "NOT_FOUND\r\n" if the requested job doesn't exist or there are no jobs in
  the requested state.

Or a line followed by a chunk of data, if the command was successful:

FOUND <id> <bytes>\r\n \r\n

- <id> is the job id.
- <bytes> is an integer indicating the size of the job body, not including
  the trailing "\r\n".
-  is the job body -- a sequence of bytes of length <bytes> from the
  previous line.

The kick command applies only to the currently used tube. It moves jobs into the ready queue. If there are any buried jobs, it will only kick buried jobs. Otherwise it will kick delayed jobs. It looks like:

kick <bound>\r\n

- <bound> is an integer upper bound on the number of jobs to kick. The server
  will kick no more than <bound> jobs.

The response is of the form:

KICKED <count>\r\n

- <count> is an integer indicating the number of jobs actually kicked.

The kick-job command is a variant of kick that operates with a single job identified by its job id. If the given job id exists and is in a buried or delayed state, it will be moved to the ready queue of the the same tube where it currently belongs. The syntax is:

kick-job <id>\r\n

- <id> is the job id to kick.

The response is one of:

- "NOT_FOUND\r\n" if the job does not exist or is not in a kickable state. This
  can also happen upon internal errors.
- "KICKED\r\n" when the operation succeeded.

The stats-job command gives statistical information about the specified job if it exists. Its form is:

stats-job <id>\r\n

- <id> is a job id.

The response is one of:

- "NOT_FOUND\r\n" if the job does not exist.
- "OK <bytes>\r\n\r\n"
  - <bytes> is the size of the following data section in bytes.
  -  is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.

The stats-job data is a YAML file representing a single dictionary of strings to scalars. It contains these keys:

- "id" is the job id
- "tube" is the name of the tube that contains this job
- "state" is "ready" or "delayed" or "reserved" or "buried"
- "pri" is the priority value set by the put, release, or bury commands.
- "age" is the time in seconds since the put command that created this job.
- "time-left" is the number of seconds left until the server puts this job
  into the ready queue. This number is only meaningful if the job is
  reserved or delayed. If the job is reserved and this amount of time
  elapses before its state changes, it is considered to have timed out.
- "file" is the number of the earliest binlog file containing this job.
  If -b wasn't used, this will be 0.
- "reserves" is the number of times this job has been reserved.
- "timeouts" is the number of times this job has timed out during a
  reservation.
- "releases" is the number of times a client has released this job from a
  reservation.
- "buries" is the number of times this job has been buried.
- "kicks" is the number of times this job has been kicked.

The stats-tube command gives statistical information about the specified tube if it exists. Its form is:

stats-tube <tube>\r\n

- <tube> is a name at most 200 bytes. Stats will be returned for this tube.

The response is one of:

- "NOT_FOUND\r\n" if the tube does not exist.
- "OK <bytes>\r\n\r\n"
  - <bytes> is the size of the following data section in bytes.
  -  is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.

The stats-tube data is a YAML file representing a single dictionary of strings to scalars. It contains these keys:

- "name" is the tube's name.
- "current-jobs-urgent" is the number of ready jobs with priority < 1024 in
  this tube.
- "current-jobs-ready" is the number of jobs in the ready queue in this tube.
- "current-jobs-reserved" is the number of jobs reserved by all clients in
  this tube.
- "current-jobs-delayed" is the number of delayed jobs in this tube.
- "current-jobs-buried" is the number of buried jobs in this tube.
- "total-jobs" is the cumulative count of jobs created in this tube in
  the current beanstalkd process.
- "current-using" is the number of open connections that are currently
  using this tube.
- "current-waiting" is the number of open connections that have issued a
  reserve command while watching this tube but not yet received a response.
- "current-watching" is the number of open connections that are currently
  watching this tube.
- "pause" is the number of seconds the tube has been paused for.
- "cmd-delete" is the cumulative number of delete commands for this tube
- "cmd-pause-tube" is the cumulative number of pause-tube commands for this
  tube.
- "pause-time-left" is the number of seconds until the tube is un-paused.

The stats command gives statistical information about the system as a whole. Its form is:

stats\r\n

The server will respond:

OK <bytes>\r\n \r\n

- <bytes> is the size of the following data section in bytes.
-  is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file with statistical information represented a dictionary.

The stats data for the system is a YAML file representing a single dictionary of strings to scalars. Entries described as "cumulative" are reset when the beanstalkd process starts; they are not stored on disk with the -b flag.

- "current-jobs-urgent" is the number of ready jobs with priority < 1024.
- "current-jobs-ready" is the number of jobs in the ready queue.
- "current-jobs-reserved" is the number of jobs reserved by all clients.
- "current-jobs-delayed" is the number of delayed jobs.
- "current-jobs-buried" is the number of buried jobs.
- "cmd-put" is the cumulative number of put commands.
- "cmd-peek" is the cumulative number of peek commands.
- "cmd-peek-ready" is the cumulative number of peek-ready commands.
- "cmd-peek-delayed" is the cumulative number of peek-delayed commands.
- "cmd-peek-buried" is the cumulative number of peek-buried commands.
- "cmd-reserve" is the cumulative number of reserve commands.
- "cmd-use" is the cumulative number of use commands.
- "cmd-watch" is the cumulative number of watch commands.
- "cmd-ignore" is the cumulative number of ignore commands.
- "cmd-delete" is the cumulative number of delete commands.
- "cmd-release" is the cumulative number of release commands.
- "cmd-bury" is the cumulative number of bury commands.
- "cmd-kick" is the cumulative number of kick commands.
- "cmd-stats" is the cumulative number of stats commands.
- "cmd-stats-job" is the cumulative number of stats-job commands.
- "cmd-stats-tube" is the cumulative number of stats-tube commands.
- "cmd-list-tubes" is the cumulative number of list-tubes commands.
- "cmd-list-tube-used" is the cumulative number of list-tube-used commands.
- "cmd-list-tubes-watched" is the cumulative number of list-tubes-watched
  commands.
- "cmd-pause-tube" is the cumulative number of pause-tube commands.
- "job-timeouts" is the cumulative count of times a job has timed out.
- "total-jobs" is the cumulative count of jobs created.
- "max-job-size" is the maximum number of bytes in a job.
- "current-tubes" is the number of currently-existing tubes.
- "current-connections" is the number of currently open connections.
- "current-producers" is the number of open connections that have each
  issued at least one put command.
- "current-workers" is the number of open connections that have each issued
  at least one reserve command.
- "current-waiting" is the number of open connections that have issued a
  reserve command but not yet received a response.
- "total-connections" is the cumulative count of connections.
- "pid" is the process id of the server.
- "version" is the version string of the server.
- "rusage-utime" is the cumulative user CPU time of this process in seconds
  and microseconds.
- "rusage-stime" is the cumulative system CPU time of this process in
  seconds and microseconds.
- "uptime" is the number of seconds since this server process started running.
- "binlog-oldest-index" is the index of the oldest binlog file needed to
  store the current jobs.
- "binlog-current-index" is the index of the current binlog file being
  written to. If binlog is not active this value will be 0.
- "binlog-max-size" is the maximum size in bytes a binlog file is allowed
  to get before a new binlog file is opened.
- "binlog-records-written" is the cumulative number of records written
  to the binlog.
- "binlog-records-migrated" is the cumulative number of records written
  as part of compaction.
- "id" is a random id string for this server process, generated when each
  beanstalkd process starts.
- "hostname" the hostname of the machine as determined by uname.

The list-tubes command returns a list of all existing tubes. Its form is:

list-tubes\r\n

The response is:

OK <bytes>\r\n \r\n

- <bytes> is the size of the following data section in bytes.
-  is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing all tube names as a list of strings.

The list-tube-used command returns the tube currently being used by the client. Its form is:

list-tube-used\r\n

The response is:

USING <tube>\r\n

- <tube> is the name of the tube being used.

The list-tubes-watched command returns a list tubes currently being watched by the client. Its form is:

list-tubes-watched\r\n

The response is:

OK <bytes>\r\n \r\n

- <bytes> is the size of the following data section in bytes.
-  is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing watched tube names as a list of strings.

The quit command simply closes the connection. Its form is:

quit\r\n

The pause-tube command can delay any new job being reserved for a given time. Its form is:

pause-tube <tube-name> <delay>\r\n

- <tube> is the tube to pause
- <delay> is an integer number of seconds to wait before reserving any more
  jobs from the queue

There are two possible responses:

- "PAUSED\r\n" to indicate success.
- "NOT_FOUND\r\n" if the tube does not exist.