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

Материал из support.qbpro.ru
(Различия между страницами)
imported>Supportadmin
 
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:
Это перевод официального протокола [https://raw.githubusercontent.com/kr/beanstalkd/master/doc/protocol.txt Beanstalk] [[Beanstalk_Protocol|Резервная копия]]


переводчик Андрей Климов.
= Beanstalk Protocol =


08-05-2014
Protocol
==Протокол==
--------


Протокол  beanstalk работает поверх  TCP используя кодировку ASCII. Клиенты могут устанавливать соединение, посылать команды и данные, а так же закрывать соединение. Для каждого соединения, сервер обрабатывает команды последовательно в порядке, в котором они были получены и посылает ответы в том же порядке. Все целые числа в протоколе отформатированы в десятичной форме и (если не указано иное) неотрицательны.
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.


Названия в протоколе — строки в кодировке  ASCII. Они могут содержать буквы (A-Z и a-z), цифры (0-9), знаки "-", "+", "/", ";", ".", "$", "_" и скобки "(" и ")", но не могут начинаться со знака "-". Названия разделяются символом пробел или символом конец строки. Каждое название должно быть длинной не менее одного символа.
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.


Клиент может использовать команду «quit» или просто закрыть  TCP соединение когда он больше не будет использовать сервер. Тем не менее, beanstalkd очень хорошо работает с большим количеством открытых соединений, поэтому обычно лучше для клиента, чтобы тот сохранил своё соединение открытым и использовал его как можно дольше. Это позволяет избежать расходов, связанных на установление новых сессий TCP.
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''' - Сервер не может выделить память для задачи. Клиенту нужно попробовать еще раз позже.
- "OUT_OF_MEMORY\r\n" The server cannot allocate enough memory for the job.
*'''INTERNAL_ERROR\r\n''' - Эта ошибка сигнализирует о критической ошибке сервера. Такого не должно случиться никогда. Если такое произойдет, пожалуйста сообщите по адресу http://groups.google.com/group/beanstalk-talk.
  The client should try again later.
*'''BAD_FORMAT\r\n''' - Клиент послал неверно сформированную команду. Это может случится в случаях, если команда не заканчивается символом \r\n,  если в позиции где ожидаются целое число, а  находится иное, если неправильное количество аргументов или если командная строка неправильно формируется любым другим способом.
*'''UNKNOWN_COMMAND\r\n''' - Клиент послал неизвестную для сервера команду


Эти ошибки не будут описаны в каждой команде индивидуально, но они неявно включены в описание всех команд. Клиенты должны быть готовы получать в ответ ошибку после любой команды.
- "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.


Задачи в beanstalk создаются клиентами командой «'''put'''». На протяжении своей «жизни», задача может находится в одном из четырех состояний: «'''ready'''», «'''reserved'''», «'''delayed'''», или «'''buried'''». После создания командой «'''put'''», задача обычно переходит в состояние '''ready'''. Она ожидает в очереди '''ready''' до тех пор, пока не подключиться исполнитель и не даст команду «'''reserve'''» (прим переводчика: исполнитель может быть уже подключенным и просто дать команду «'''reserve'''» — зарезервировать за собой следующую в очереди задачу, находящуюся в состояние ready, как выполняемую. Можно перефразировать - зарезервировать следующую задачу в очереди '''ready'''. Состояние и очередь в данном случае одно и тоже). Если есть такая задача следующая в очереди, то она будет зарезервирована за исполнителем. Исполнитель выполняет задачу, после чего исполнитель посылает команду «'''delete'''», для её удаления.
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
-------------


    put           reserve               delete
A job in beanstalk gets created by a client with the "put" command. During its
  -----> [READY] ---------> [RESERVED] --------> *poof*
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 with delay              release with delay
  ----------------> [DELAYED] <------------.
                        |                  |
                        | (time passes)    |
                        |                  |
    put                  v    reserve      |      delete
  -----------------> [READY] ---------> [RESERVED] --------> *poof*
                        ^  ^                |  |
                        |  \  release      |  |
                        |    `-------------'  |
                        |                      |
                        | kick                |
                        |                      |
                        |      bury          |
                    [BURIED] <---------------'
                        |
                        |  delete
                        `--------> *poof*


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


Система имеет один или более каналов. Каждый канал состоит из очередей '''ready''' и '''delay'''. Каждое задание проводит всю свою «жизнь» в одном канале. Клиенты могут подписаться на канал, отправив команду «'''watch'''»; они могут отписаться от канала, отправив команду «'''ignore'''». Этот набор каналов, на которых осуществлена подписка, является как говорят, «'''watch list'''» клиента. Когда клиент посылает команду «'''reserve'''», задача может поступить из любого канала в «'''watch list'''».




Когда клиент подключается, его «'''watch list'''» он изначально подписан только на канал «'''default'''». Если он посылает команду «'''reserve'''» без предварительного использования команды «'''use'''», то все его задачи будут находится только в канале «'''default'''».
Here is a picture with more possibilities:




Каналы создаются по запросу, всякий раз когда на них ссылаются. Если канал пуст (это означает, что он не содержит задач со статусом «'''ready'''», «'''delayed'''» или «'''buried'''») и нет подписанных клиентов, канал будет удален.


==Команды генераторов задач==
  put with delay              release with delay
===put===
  ----------------> [DELAYED] <------------.
Команда «'''put'''» предназначена для любого клиента, который желает добавить задачу в очередь. Она включает в себя строку команды с последующей строкой «тела» задачи:
                        |                  |
                        | (time passes)    |
                        |                  |
  put                 v    reserve      |      delete
  -----------------> [READY] ---------> [RESERVED] --------> *poof*
                      ^  ^                |  |
                      |  \  release      |  |
                      |    `-------------'   |
                      |                      |
                      | kick                |
                      |                      |
                      |      bury          |
                    [BURIED] <---------------'
                      |
                      |  delete
                        `--------> *poof*


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


'''<dаta>\r\n'''
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.


Добавляет задачу в используемый клиентом в настоящее время канал (см. ниже команду «'''use'''»).
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".


*'''<pri>''' приоритет - целое число < 2**32. Задачи с меньшим значением приоритета будут выполнены раньше задач с большим значение приоритета. Самая важная задача будет иметь приоритет 0; самая неважная задача будет иметь приоритет 4,294,967,295.
Tubes are created on demand whenever they are referenced. If a tube is empty
*'''<delay>''' отсрочка — целое число секунд ожидания до постановки задачи в очередь «ready». Все это время задача будет иметь статус «'''delayed'''».
(that is, it contains no ready, delayed, or buried jobs) and no client refers
*'''<ttr>''' время выполнения — целое число секунд, которые отводятся исполнителю на выполнение этой задачи. Это время отсчитывается с момента начала выполнения команды «'''reserve'''» для этой задачи. Если исполнитель не даст команду «delete», «release» или «bury» для этой задачи через <ttr> секунд, будет превышено время выполнения и сервер выполнит команду «'''release'''» для этой задачи. Минимальное значение 1. Если клиент устанавливает значение <ttr> равным 0, сервер без предупреждения увеличит его до 1.
to it, it will be deleted.
*'''<bytes>''' размер тела задачи — целое число указывающее размер тела задачи, не включая граничные символы "\r\n". Это значение должно быть меньше чем max-job-size (по умолчанию: 2**16).
*'''<dаta> '''тело задачи — последовательность байтов длиной '''<bytes> '''указанной в строке команды.


После отправки строки команды и тела задачи, клиент должен ожидать один из возможных ответов:
Producer Commands
*'''INSERTED <id>\r\n''' - указывает на успешное добавление задачи.
-----------------
**<id> - целое число, идентификатор новой задачи
*'''BURIED <id>\r\n''' - указывает на то, что серверу не хватило памяти при попытке разобрать структуру данных очереди приоритетов.
**<id> - целое число, идентификатор новой задачи
*'''EXPECTED_CRLF\r\n''' - тело задачи должно оканчиваться парой символов CR-LF, а именно, "\r\n". Эти два байта не учитываются в при расчете длины тела задачи в строке команды put.
*'''JOB_TOO_BIG\r\n''' - клиент передает тело задачи больше чем max-job-size байт
*'''DRAINING\r\n''' - означает, что сервер находится в режиме "drain mode" и больше не принимает новые задачи. Клиент должен попробовать подключиться к другому серверу или повторить подключение позже.


===use===
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:


Команда «'''use'''» предназначена только для генераторов команд. Последующие команды «'''put'''» добавят задачу в канал, предусмотренный настоящей командой. Если не был дана команда «'''use'''», задачи будут добавлены в канал под названием «'''default'''».
put <pri> <delay> <ttr> <bytes>\r\n
<data>\r\n


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


*'''<tube>''' - название канала, длиной не более 200 байт. Указывает какой канал станет текущим для использования. Если такого канала нет, то он будет создан.
- <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
*'''USING <tube>\r\n '''- указывает имя используемого канала
  the ready queue. The job will be in the "delayed" state during this time.
**<tube> - Имя канала, который стал текущим


==Команды исполнителей задач==
- <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.


Клиент, который хочет получить задачу из очереди должен использовать команды «'''reserve'''», «'''delete'''», «'''release'''» и «'''bury'''» (прим переводчика: если точнее, то это набор команд исполнителя для работы с очередью в канале).  
- <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).


===reserve, reserve-with-timeout===
- <data> is the job body -- a sequence of bytes of length <bytes> from the
  previous line.


Первая команда исполнителя «'''reserve'''», выглядит так:
After sending the command line and body, the client waits for a reply, which
may be:


'''reserve\r\n'''
- "INSERTED <id>\r\n" to indicate success.


Альтернативно можно указать тайм-аут следующим образом:
  - <id> is the integer id of the new job


'''reserve-with-timeout <seconds>\r\n'''
- "BURIED <id>\r\n" if the server ran out of memory trying to grow the
  priority queue data structure.


Команды вернут вновь зарезервированную задачу. Если не будет доступных для резервирования задач, beanstalkd будет ожидать возможности послать ответ, до тех пор пока это не станет возможным. После того, как задача будет зарезервирована за для клиента, у клиента есть строго ограниченное время (TTR) для выполнения задачи. При наступлении тайм-аута задачи, сервер будет поставить работу обратно в очередь готовности. И TTR и фактическое время выполнения можно найти в статистике по команде '''stats-job'''.
  - <id> is the integer id of the new job


Если более одной задачи имеют статус ready, beanstalkd выберет одну из них с наименьшим значением приоритета. В рамках одного приоритета, будет выбрана та задача, которая была получена первой.
- "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.


Тайм-аут со значением 0 заставит сервер немедленно возвращать либо ответ или '''TIMED_OUT '''. Положительное значение тайм-аута будет задавать время, в течении которого запросы «'''reserve'''» будет блокированы пока задача снова не станет доступной.
- "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
  than max-job-size bytes.


Всё время TTR зарезервированной задачи, вплоть до последней секунды сервер будет находится в безопасном режиме, при котором исполнитель гарантированно не может получить другую задачу. Если исполнитель дает команду «'''reserve'''» во время безопасного режима или безопасный режим наступает пока исполнитель ожидает ответ на команду «'''reserve'''», сервер может ответить следующим образом:
- "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.


*'''DEADLINE_SOON\r\n''' - дает исполнителю шанс дать команду «'''delete'''» или «'''release'''» для зарезервированной задачи, до того как сервер автоматически даст команду «'''release'''» для зарезервированной задачи.
The "use" command is for producers. Subsequent put commands will put jobs into
*'''TIMED_OUT\r\n''' - если был указан неотрицательный тайм-аут и тайм-аут превышен до момента, когда задача стала доступна, или если соединение клиента является полузакрытыми, сервер ответит TIMED_OUT
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


*'''RESERVED <id><bytes>\r\n''' - успешное резервирование задачи
- <tube> is a name at most 200 bytes. It specifies the tube to use. If the
**'''<id>''' - имя канала, который стал текущим
  tube does not exist, it will be created.
**'''<bytes>''' - целое число указывающее размер тела задачи, не включая граничные символы "\r\n".  
*'''<dаta>\r\n''' - тело успешно зарезервированной задачи — последовательность байтов длиной <bytes> указанной в строке команды. Это точная копия байтов, которые были изначально отправлены на сервер командой «'''put'''» в этой задаче.


===delete===
The only reply is:


Команда «'''delete'''» удаляет задачу с сервера целиком. Эта команда, как правило, используется клиентом, когда задача успешно выполнена. Исполнитель может удалять задания, которые он зарезервировал, а так же задачи со статусом «'''ready'''», «'''delayed'''» или «'''buried'''». Команда «'''delete'''» выглядит следующим образом:
USING <tube>\r\n


'''delete <id>\r\n'''
- <tube> is the name of the tube now being used.


*'''<id>''' - идентификатор задачи, которую следует удалить.
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:


*'''DELETED\r\n - '''сигнализирует об успешности операции
reserve\r\n
*'''NOT_FOUND\r\n''' - если задача не существует, или была зарезервирована не этим исполнителем, была переведена в статус '''ready''' или '''buried''' (прим переводчика: неоднозначный, возможно неправильный перевод). Эта ситуация возможна в случае, когда тайм-аут для задачи наступил раньше, чем клиент дал команду «'''delete'''»


===release===
Alternatively, you can specify a timeout as follows:


Команда «'''release'''» помещает зарезервированную задачу назад в очередь ready (и помечает её статус как «'''ready'''») для запуска любым исполнителем. Обычно это используется, когда выполнить задачу не удается из-за возникшей ошибки.
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.


'''release <id> <pri> <delay>\r\n'''
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.


* '''<id>''' идентификатор задачи, которую следует «реализовать».
A timeout value of 0 will cause the server to immediately return either a
* '''<pri>''' новый приоритет для задачи.
response or TIMED_OUT. A positive value of timeout will limit the amount of
* '''<delay>''' целое число секунд ожилания, до того как задача переместится в очередь ready. В течение этой задержки задача будет иметь статус «'''delayed'''».
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:


*'''RELEASED\r\n''' - сигнализирует об успешности операции
DEADLINE_SOON\r\n
*'''BURIED\r\n''' - указывает на то, что серверу не хватило памяти при попытке разобрать структуру данных очереди приоритетов.
*'''NOT_FOUND\r\n''' - если задача не существует или была зарезервирована не этим исполнителем


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


Команда «'''bury'''» переводит задачу в статус «'''buried'''». Такие задачи помещаются в FIFO подобный список и не обрабатываются сервером до тех пор, пока исполнитель не даст команду «'''kick»'''.
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.


'''bury <id> <pri>\r\n'''
Otherwise, the only other response to this command is a successful reservation
in the form of a text line followed by the job body:


* '''<id>''' идентификатор задачи, которую следует «заморозить» (прим переводчика: в оригинальном тексте про команду release).
RESERVED <id> <bytes>\r\n
* '''<pri>''' новый приоритет, назначенный задаче.
<data>\r\n


Возможны два варианта ответа:
- <id> is the job id -- an integer unique to this job in this instance of
  beanstalkd.


*'''BURIED\r\n''' - сигнализирует об успешности операции
- <bytes> is an integer indicating the size of the job body, not including
*'''NOT_FOUND\r\n''' - если задача не существует или была зарезервирована не этим исполнителем
  the trailing "\r\n".


===touch===
- <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.


Команда "'''touch'''" позволяет исполнителю запросить больше времени на выполнение задачи. Это полезно для задач, которые потенциально выполняются долго, но вы продолжаете использовать преимущества TTR при выполнении затянувшейся задачи не зависшим исполнителем. Исполнитель может ппереодически говорить серверу что он по-прежнему жив и выполняет задачу (например исполнитель может так делать при поступлении команды DEADLINE_SOON). Команда откладывает автоматическое выполнение команды «'''release'''» зарезервированной задачи на TTR секунд с момента поступления команды.
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


'''touch <id>\r\n'''
- <id> is the job id to delete.


* '''<id>''' идентификатор задачи, зарезервированной в текущем соединении.
The client then waits for one line of response, which may be:


Возможны два варианта ответа:
- "DELETED\r\n" to indicate success.


*'''TOUCHED\r\n''' - сигнализирует об успешности операции
- "NOT_FOUND\r\n" if the job does not exist or is not either reserved by the
*'''NOT_FOUND\r\n''' - если задача не существует или была зарезервирована не этим исполнителем
  client, ready, or buried. This could happen if the job timed out before the
  client sent the delete command.


===watch===
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:


Команда «'''watch'''» добавляет именованный канал в '''watch list''' текущего соединения. Команда «'''reserve'''» принимает задачи из любого канала в watch list. Для каждого нового соединения создаётся новый '''watch list''', содержащий только один канал, называемый «'''default'''».
release <id> <pri> <delay>\r\n


Формат команды:
- <id> is the job id to release.


'''watch <tube>\r\n'''
- <pri> is a new priority to assign to the job.


* '''<tube>''' название канала, длиной не более 200 байт. Указывает какой канал будет добавлен в watch list. Если такого канала нет, то он будет создан.
- <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:


'''WATCHING <count>\r\n'''
- "RELEASED\r\n" to indicate success.


* '''<count>''' целое число каналов в текущем watch list.
- "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.


===Группа команд peek===
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.


Группа команд «'''peek'''» позволяют клиенту инспектировать задачи в системе. Всего 4 варианта. Все команды, кроме первой, работают только для текущего именованного канала.
The bury command looks like this:


* '''peek <id>\r\n''' — возвращает задачу по <id>.
bury <id> <pri>\r\n
* '''peek-ready\r\n''' — возвращает следующую задачу со статусом '''ready'''.
* '''peek-delayed\r\n''' — возвращает следующую задачу со статусом '''delayed''' с наименьшим временем задержки.
* '''peek-buried\r\n''' - возвращает следующую в списке задачу со статусом '''buried'''.


Возможны два варианта ответа:
- <id> is the job id to release.
* '''NOT_FOUND\r\n''' — если запрашиваемая задача не создана или нет задачи с запрашиваемым статусом.
* '''FOUND <id> <bytes>\r\n<data>\r\n''' - случае успеха, строка ответа сопровождается строкой данных
** '''<id>''' идентификатор задачи.
** '''<bytes>''' целое число указывающее размер тела задачи, не включая граничные символы "\r\n".
** '''<data>''' тело задачи — последовательность байтов длиной '''<bytes> '''указанной в строке ответа.


===kick===
- <pri> is a new priority to assign to the job.


Команда «'''kick'''» применима только для текущего именованного канала. Она переносит задачи в очередь '''ready'''. Если есть хоть одна задача со статусом «'''buried'''», команда применится только к этим задачам. В противном случае, будут перемещены только задачи со статусом «'''delayed'''».
There are two possible responses:


Формат команды:
- "BURIED\r\n" to indicate success.


'''kick <bound>\r\n'''
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
* '''<bound>''' целое число — количество задач для перемещения. Сервер переместит не более чем <bound> задач.


Возможный ответ:
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.


'''KICKED <count>\r\n'''
The touch command looks like this:
* '''<count>''' целое число, указывающее число действительно перенесенных задач.


===kick-job===
touch <id>\r\n


Команда «'''kick-job'''» вариант команды '''kick''' с указанием конкретной задачи по её идентификатору. Если указываемая по id задача создана и имеет статус buried или delayed, она будет перемещена в очередь ready того же канала, в котором она находилась.  
- <id> is the ID of a job reserved by the current connection.


Формат команды:
There are two possible responses:


'''kick-job <id>\r\n'''
- "TOUCHED\r\n" to indicate success.
* '''<id>''' идентификатор задачи для перемещения.


Возможен один из вариантов ответа:
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.


* '''KICKED\r\n — '''если команда выполнена успешно.
The "watch" command adds the named tube to the watch list for the current
* '''NOT_FOUND\r\n''' — если задачи не существует или у неё не подходящий статус. Это может быть так же внутренней ошибкой.
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".


===stats-job===
watch <tube>\r\n


Команда '''stats-job '''предоставляет статистику об указанной задаче, если указанная задача существует.  
- <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:


'''stats-job <id>\r\n'''
WATCHING <count>\r\n
* '''<id> '''идентификатор задачи


Возможен один из вариантов ответа:
- <count> is the integer number of tubes currently in the watch list.
* '''NOT_FOUND\r\n''' - если задачи не существует.
* '''OK <bytes>\r\n<data>\r\n'''"
** '''<bytes> '''размер последующей секции данных в байтах.
** '''<data>''' последовательность байт длиной <bytes> указанной в предыдущей строке. Это YAML файл со статистикой, представленной в виде словаря (прим переводчика: строки в виде <ключ>:<значение>).  


Статистика содержит следующие параметры:
The "ignore" command is for consumers. It removes the named tube from the
* '''id''' - идентификатор задачи;
watch list for the current connection.
* '''tube''' - название канала, в котором находится задача;
* '''state''' - статус: «'''ready'''», «'''delayed'''», «'''reserved'''» или «'''buried'''»
* '''pri''' - значение приоритета установленного командой «'''put'''», «'''release'''» или «'''bury'''».
* '''age''' - время в секундах с момента создания задачи командой «'''put'''».
* '''time-left''' - количество секунд до момента когда сервер переместит эту задачу в очередь '''ready'''. Это число имеет смысл только если задача имеет статус '''reserved''' или '''delayed'''. Если задача зарезервирована и время истекло раньше изменения статуса, то считается что у задачи тайм-аут.
* '''file''' - количество более ранних файлов binlog, содержащих эту задачу. Если при запуске сервера не была указана опция -b, число будет 0.
* '''reserves''' - количество раз, которое эта задача получала статус '''reserved'''.
* '''timeouts''' - количество раз, которое эта задача получала тайм-аут, находясь в резерве.
* '''releases ''' - количество раз, которое эта задача получала статус '''released''' от исполнителя, находясь в резерве.
* '''buries '''- количество раз, которое эта задача получала статус '''buried'''.
* '''kicks '''- количество раз, которое эта задача получала команду '''kick'''.


===stats-tube===
ignore <tube>\r\n


Команда '''stats-tube''' предоставляет статистику об указанном канале, если такой существует.
The reply is one of:


Формат команды:
- "WATCHING <count>\r\n" to indicate success.


'''stats-tube <tube>\r\n'''
  - <count> is the integer number of tubes currently in the watch list.
* '''<tube>''' - название канала, длиной не более 200 байт. Статистика будет предоставлена для этого канала.


Возможен один из вариантов ответа:
- "NOT_IGNORED\r\n" if the client attempts to ignore the only tube in its
* '''NOT_FOUND\r\n''' — если канала не существует.
  watch list.
* '''OK <bytes>\r\n<data>\r\n'''
** '''<bytes> ''' - размер последующей секции данных в байтах.
** '''<data>''' - последовательность байт длиной <bytes> указанной в предыдущей строке. Это YAML файл со статистикой, представленной в виде словаря (прим переводчика: строки в виде <ключ>:<значение>).  


Статистика содержит следующие параметры:
Other Commands
* '''name''' - имя канала.
--------------
* '''current-jobs-urgent''' - количество задач со статусом '''ready''' и приоритетом < 1024 в этом канале.
* '''current-jobs-ready '''- количество задач в очереди '''ready''' в этом канале.
* '''current-jobs-reserved''' - количество зарезервированных исполнителями задач в канале.
* '''current-jobs-delayed''' - количество задач со статусом '''delayed''' в этом канале.
* '''current-jobs-buried''' - количество задач со статусом '''buried''' в этом канале.
* '''total-jobs''' - общее количество задач созданных в этом канале текущим процессом beanstalkd.
* '''current-using''' - количество открытых соединений использующих этот канал в настоящий момент.
* '''current-waiting''' - количество открытых соединений, которые дали команду '''reserve''', наблюдая за каналом, но ещё не получили ответ.
* '''current-watching''' - количество открытых соединений, которые наблюдают за каналом.
* '''pause''' - количество секунд, которое канал был приостановлен.
* '''cmd-delete''' - общее количество раз, которое была выполнена команда '''delete''' в этом канале.
* '''cmd-pause-tube''' - общее количество раз, которое бал приостановлен канал командой '''pause-tube'''.
* '''pause-time-left''' - количество секунд до запуска канала (прим переводчика: не понял смысла этой фразы «is the number of seconds until the tube is un-paused.»).


===stats===
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.


Команда '''stats''' предоставляет статистику о системе в целом.  
- "peek <id>\r\n" - return job <id>.


'''stats\r\n'''
- "peek-ready\r\n" - return the next ready job.


Ответ сервера:
- "peek-delayed\r\n" - return the delayed job with the shortest delay left.


'''OK <bytes>\r\n<data>\r\n'''
- "peek-buried\r\n" - return the next job in the list of buried jobs.
* '''<bytes>''' размер последующей секции данных в байтах.
* '''<data>''' последовательность байт длиной <bytes> указанной в предыдущей строке. Это YAML файл со статистикой, представленной в виде словаря (прим переводчика: строки в виде <ключ>:<значение>).


Параметры, описываемые как "общее количество", сбрасываются при запуске процесса beanstalkd. При указании опции -b, они не сохраняются на диске.
There are two possible responses, either a single line:


* '''current-jobs-urgent''' - количество задач в очереди (состоянии) '''ready''' с приоритетом менее 1024.
- "NOT_FOUND\r\n" if the requested job doesn't exist or there are no jobs in
* '''current-jobs-ready''' - количество задач в очереди (состоянии) '''ready'''.
  the requested state.
* '''current-jobs-reserved - '''количество задач зарезервированных всеми исполнителями.
* '''current-jobs-delayed '''- количество задач со сотатусом «'''delayed'''».
* '''current-jobs-buried '''- количество задач со сотатусом «'''buried'''».
* '''cmd-put''' - общее количество команд «'''put'''».
* '''cmd-peek''' - общее количество команд «'''peek'''».
* '''cmd-peek-ready''' - общее количество команд «'''peek-ready'''».
* '''cmd-peek-delayed''' - общее количество команд «'''peek-delayed'''».
* '''cmd-peek-buried''' - общее количество команд «'''peek-buried»'''.
* '''cmd-reserve''' - общее количество команд «'''reserve'''».
* '''cmd-use''' - общее количество команд «'''use'''».
* '''cmd-watch''' - общее количество команд «'''watch'''».
* '''cmd-ignore''' - общее количество команд «'''ignore'''».
* '''cmd-delete''' - общее количество команд «'''delete'''».
* '''cmd-release''' - общее количество команд «'''release'''».
* '''cmd-bury''' - общее количество команд «'''bury'''».
* '''cmd-kick''' - общее количество команд «'''kick'''».
* '''cmd-stats''' - общее количество команд «'''stats'''».
* '''cmd-stats-job''' - общее количество команд «'''stats-job»'''.
* '''cmd-stats-tube''' - общее количество команд «'''stats-tube»'''.
* '''cmd-list-tubes''' - общее количество команд «'''list-tubes'''».
* '''cmd-list-tube-used''' - общее количество команд «'''list-tube-used'''».
* '''cmd-list-tubes-watched''' - общее количество команд «'''list-tubes-watched'''».
* '''cmd-pause-tube''' - общее количество команд «'''pause-tube»'''.
* '''job-timeouts''' - общее количество раз, которое задача была в тайм-ауте.(прим переводчика: не точное описание, речь должна идти обо всех задачах, а не об одной)
* '''total-jobs''' - общее количество созданных задач.
* '''max-job-size''' - максимальное число байт в задаче.
* '''current-tubes''' - число существующих в настоящий момент каналов.
* '''current-connections''' - число открытых в настоящее время соединений.
* '''current-producers''' - число открытых соединений, через которое была дана по меньшей мере одна команда «'''put'''».
* '''current-workers''' - число открытых соединений, через которое была дана по меньшей мере одна команда «'''reserve'''».
* '''current-waiting''' - число открытых соединений, через которое была дана команда «reserve», но еще не получен ответ.
* '''total-connections''' - общее количество соединений (прим переводчика: не понятно, о каких соединениях идет речь, об открытых в настоящий момент или с учетом уже закрытых соединений)
* '''pid''' - pid процесса сервера.
* '''version''' - версия сервера.
* '''rusage-utime''' - общее время user CPU процесса в секундах и микросекундах.
* '''rusage-stime'''- общее время system CPU процесса в секундах и микросекундах.
* '''uptime''' - количество секунд с момента запуска процесса.
* '''binlog-oldest-index''' - индекс старейшего файла binlog, необходимого для хранения текущих задач.
* '''binlog-current-index''' -индекс текущего файла binlog, в который производится запись. Если binlog не активен, значение бедт равно 0.
* '''binlog-max-size''' - максимальный размер файла binlog в байтах, после которого будет создан новый.
* '''binlog-records-written''' - общее количество записей сделанных в binlog.
* '''binlog-records-migrated''' - общее количество записей, записанных как части архиров (прим переводчика: не понял смысл).
* '''id''' - случайный текстовый идентификатор для конкретного процесса сервера, генерируется при старте beanstalkd.
* '''hostname''' - hostname машины, выдаваемый командой uname.


===list-tubes===
Or a line followed by a chunk of data, if the command was successful:


Команда '''list-tubes''' возвращает список всех существующих каналов.
FOUND <id> <bytes>\r\n
<data>\r\n


Формат команды:
- <id> is the job id.


'''list-tubes\r\n'''
- <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
'''OK <bytes>\r\n<data>\r\n'''
  previous line.
* '''<bytes> - '''размер последующей секции данных в байтах.
* '''<data>''' - последовательность байт длиной <bytes> указанной в предыдущей строке. Это YAML файл содержащий названия всех каналов в виде списка строк.


===list-tube-used===
The kick command applies only to the currently used tube. It moves jobs into
Команда '''list-tube-used''' возвращает канал, используемый клиентом в настоящее время.  
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


'''list-tube-used\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:


'''USING <tube>\r\n'''
KICKED <count>\r\n
*'''<tube>''' название используемого конала.


===list-tubes-watched===
- <count> is an integer indicating the number of jobs actually kicked.
Команда '''list-tubes-watched'''возвращает список каналов на которые подписан исполнитель в настоящий момент.


Формат команды:
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:


'''list-tubes-watched\r\n'''
kick-job <id>\r\n


Ответ сервера:
- <id> is the job id to kick.


'''OK <bytes>\r\n<data>\r\n'''
The response is one of:
*'''<bytes> - '''размер последующей секции данных в байтах.
*'''<data>''' - последовательность байт длиной <bytes> указанной в предыдущей строке. Это YAML файл содержащий названия всех каналов на которые есть подписка в виде списка строк.


===quit===
- "NOT_FOUND\r\n" if the job does not exist or is not in a kickable state. This
Команда '''quit''' просто закрывает соединение.  
  can also happen upon internal errors.


Формат команды:
- "KICKED\r\n" when the operation succeeded.


'''quit\r\n'''
The stats-job command gives statistical information about the specified job if
it exists. Its form is:


===pause-tube===
stats-job <id>\r\n


Команда '''pause-tube''' позволяет приостановить резервирование новых задач на определенное время.  
- <id> is a job id.


Формат команды:
The response is one of:


'''pause-tube <tube-name> <delay>\r\n'''
- "NOT_FOUND\r\n" if the job does not exist.
* '''<tube>''' - название приостанавливаемого канала
* '''<delay>''' - целое число секунд до момента восстановления возможности резервирования задач из очереди.


Возможны два варианта ответа:
- "OK <bytes>\r\n<data>\r\n"


* '''PAUSED\r\n''' - сигнализирует об успешном выполнении.
  - <bytes> is the size of the following data section in bytes.
* '''NOT_FOUND\r\n''' - если такого канала не существует.


===ignore===
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.


Команда «'''ignore'''» только для исполнителей. Она удаляет именованый канал из watch list для текущего соединения.
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


'''ignore <tube>\r\n'''
- "tube" is the name of the tube that contains this job


Возможен один из вариантов ответа:
- "state" is "ready" or "delayed" or "reserved" or "buried"


* '''WATCHING <count>\r\n''' сигнализирует об успешности операции
- "pri" is the priority value set by the put, release, or bury commands.
** '''<count>''' целое число каналов в текущем watch list.
 
* '''NOT_IGNORED\r\n'''" если клиент пытается игнорировать единственный канал в его watch list.
- "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.