# HG changeset patch # User Yaroslav Zhuravlev # Date 1521225979 -10800 # Node ID b7dd3e8ee9c20833631fd60ca297e0a7a5f950ef # Parent 180269c4a220b6beab4cbb78b9f0b6132fcba7e6 Documented the gRPC proxy module. diff --git a/xml/en/GNUmakefile b/xml/en/GNUmakefile --- a/xml/en/GNUmakefile +++ b/xml/en/GNUmakefile @@ -54,6 +54,7 @@ REFS = \ http/ngx_http_flv_module \ http/ngx_http_geo_module \ http/ngx_http_geoip_module \ + http/ngx_http_grpc_module \ http/ngx_http_gunzip_module \ http/ngx_http_gzip_module \ http/ngx_http_gzip_static_module \ diff --git a/xml/en/docs/http/ngx_http_memcached_module.xml b/xml/en/docs/http/ngx_http_grpc_module.xml copy from xml/en/docs/http/ngx_http_memcached_module.xml copy to xml/en/docs/http/ngx_http_grpc_module.xml --- a/xml/en/docs/http/ngx_http_memcached_module.xml +++ b/xml/en/docs/http/ngx_http_grpc_module.xml @@ -7,19 +7,18 @@ - + rev="1">
-The ngx_http_memcached_module module is used to obtain -responses from a memcached server. -The key is set in the $memcached_key variable. -A response should be put in memcached in advance by means -external to nginx. +The ngx_http_grpc_module module allows passing requests +to a gRPC server (1.13.10). +The module requires the +ngx_http_v2_module module.
@@ -30,14 +29,10 @@ external to nginx. server { + listen 9000 http2; + location / { - set $memcached_key "$uri?$args"; - memcached_pass host:11211; - error_page 404 502 504 = @fallback; - } - - location @fallback { - proxy_pass http://backend; + grpc_pass 127.0.0.1:9000; } } @@ -48,49 +43,48 @@ server {
- + address - [ transparent ] | + [transparent ] | off http server location -0.8.22 -Makes outgoing connections to a memcached server originate -from the specified local IP address with an optional port (1.11.2). -Parameter value can contain variables (1.3.12). -The special value off (1.3.12) cancels the effect -of the memcached_bind directive +Makes outgoing connections to a gRPC server originate +from the specified local IP address with an optional port. +Parameter value can contain variables. +The special value off cancels the effect +of the grpc_bind directive inherited from the previous configuration level, which allows the system to auto-assign the local IP address and port. - -The transparent parameter (1.11.0) allows -outgoing connections to a memcached server originate + +The transparent parameter allows +outgoing connections to a gRPC server originate from a non-local IP address, for example, from a real IP address of a client: -memcached_bind $remote_addr transparent; +grpc_bind $remote_addr transparent; In order for this parameter to work, it is usually necessary to run nginx worker processes with the superuser privileges. -On Linux it is not required (1.13.8) as if +On Linux it is not required as if the transparent parameter is specified, worker processes inherit the CAP_NET_RAW capability from the master process. It is also necessary to configure kernel routing table -to intercept network traffic from the memcached server. +to intercept network traffic from the gRPC server. - + size 4k|8k http @@ -99,14 +93,14 @@ to intercept network traffic from the me Sets the size of the buffer used for reading the response -received from the memcached server. +received from the gRPC server. The response is passed to the client synchronously, as soon as it is received. - + time 60s http @@ -114,54 +108,101 @@ The response is passed to the client syn location -Defines a timeout for establishing a connection with a memcached server. +Defines a timeout for establishing a connection with a gRPC server. It should be noted that this timeout cannot usually exceed 75 seconds. - -on | off -off + +field + http server location -1.7.7 -Enables byte-range support -for both cached and uncached responses from the memcached server -regardless of the
Accept-Ranges
field in these responses. +By default, +nginx does not pass the header fields
Date
, +
Server
, and +
X-Accel-...
from the response of a gRPC +server to a client. +The grpc_hide_header directive sets additional fields +that will not be passed. +If, on the contrary, the passing of fields needs to be permitted, +the directive can be used.
- -flag - + +field ... + http server location -1.3.6 + + +Disables processing of certain response header fields from the gRPC server. +The following fields can be ignored:
X-Accel-Redirect
+and
X-Accel-Charset
. +
-Enables the test for the flag presence in the memcached -server response and sets the “Content-Encoding” -response header field to “gzip” -if the flag is set. +If not disabled, processing of these header fields has the following +effect: + + + +
X-Accel-Redirect
performs an +internal +redirect to the specified URI; +
+ + +
X-Accel-Charset
sets the desired + +of a response. +
+ +
- + +on | off +off +http +server +location + + +Determines whether gRPC server responses with codes greater than or equal +to 300 should be passed to a client +or be intercepted and redirected to nginx for processing +with the directive. + + + + + + error | timeout | - invalid_response | - not_found | + invalid_header | + http_500 | + http_502 | + http_503 | + http_504 | + http_403 | + http_404 | + http_429 | + non_idempotent | off ... error timeout @@ -181,11 +222,39 @@ server, passing a request to it, or read a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header; -invalid_response +invalid_header a server returned an empty or invalid response; -not_found -a response was not found on the server; +http_500 +a server returned a response with the code 500; + +http_502 +a server returned a response with the code 502; + +http_503 +a server returned a response with the code 503; + +http_504 +a server returned a response with the code 504; + +http_403 +a server returned a response with the code 403; + +http_404 +a server returned a response with the code 404; + +http_429 +a server returned a response with the code 429; + +non_idempotent +normally, requests with a +non-idempotent +method +(POST, LOCK, PATCH) +are not passed to the next server +if a request has been sent to an upstream server; +enabling this option explicitly allows retrying such requests; + off disables passing a request to the next server. @@ -205,71 +274,81 @@ The directive also defines what is consi unsuccessful attempt of communication with a server. The cases of error, timeout and -invalid_response are always considered unsuccessful attempts, +invalid_header are always considered unsuccessful attempts, even if they are not specified in the directive. -The case of not_found -is never considered an unsuccessful attempt. +The cases of http_500, http_502, +http_503, http_504, +and http_429 are +considered unsuccessful attempts only if they are specified in the directive. +The cases of http_403 and http_404 +are never considered unsuccessful attempts. Passing a request to the next server can be limited by -the number of tries -and by time. +the number of tries +and by time. - + time 0 http server location -1.7.5 Limits the time during which a request can be passed to the -next server. +next server. The 0 value turns off this limitation. - + number 0 http server location -1.7.5 Limits the number of possible tries for passing a request to the -next server. +next server. The 0 value turns off this limitation. - + address location if in location -Sets the memcached server address. +Sets the gRPC server address. The address can be specified as a domain name or IP address, and a port: -memcached_pass localhost:11211; +grpc_pass localhost:9000; or as a UNIX-domain socket path: -memcached_pass unix:/tmp/memcached.socket; +grpc_pass unix:/tmp/grpc.socket; + +Alternatively, the “grpc://” scheme can be used: + +grpc_pass grpc://127.0.0.1:9000; + +To use gRPC over SSL, the “grpcs://” scheme should be used: + +grpc_pass grpcs://127.0.0.1:443; @@ -283,7 +362,22 @@ In addition, an address can be specified - + +field + +http +server +location + + +Permits passing otherwise disabled header +fields from a gRPC server to a client. + + + + + + time 60s http @@ -291,17 +385,17 @@ In addition, an address can be specified location -Defines a timeout for reading a response from the memcached server. +Defines a timeout for reading a response from the gRPC server. The timeout is set only between two successive read operations, not for the transmission of the whole response. -If the memcached server does not transmit anything within this time, +If the gRPC server does not transmit anything within this time, the connection is closed. - + time 60s http @@ -309,31 +403,255 @@ the connection is closed. location -Sets a timeout for transmitting a request to the memcached server. +Sets a timeout for transmitting a request to the gRPC server. The timeout is set only between two successive write operations, not for the transmission of the whole request. -If the memcached server does not receive anything within this time, +If the gRPC server does not receive anything within this time, the connection is closed. + + +field value +Content-Length $content_length +http +server +location + + +Allows redefining or appending fields to the request header +passed to the gRPC server. +The value can contain text, variables, and their combinations. +These directives are inherited from the previous level if and +only if there are no +grpc_set_header +directives defined on the current level. + + + +If the value of a header field is an empty string then this +field will not be passed to a gRPC server: + +grpc_set_header Accept-Encoding ""; + + + + + + + +file + +http +server +location + + +Specifies a file with the certificate in the PEM format +used for authentication to a gRPC SSL server. + + + + + + +file + +http +server +location + + +Specifies a file with the secret key in the PEM format +used for authentication to a gRPC SSL server. + + + +The value +engine:name:id +can be specified instead of the file, +which loads a secret key with a specified id +from the OpenSSL engine name. + + + + + + +ciphers +DEFAULT +http +server +location + + +Specifies the enabled ciphers for requests to a gRPC SSL server. +The ciphers are specified in the format understood by the OpenSSL library. + + + +The full list can be viewed using the +“openssl ciphers” command. + + + + + + +file + +http +server +location + + +Specifies a file with revoked certificates (CRL) +in the PEM format used to verify +the certificate of the gRPC SSL server. + + + + + + +name +host from grpc_pass +http +server +location + + +Allows overriding the server name used to +verify +the certificate of the gRPC SSL server and to be +passed through SNI +when establishing a connection with the gRPC SSL server. + + + +By default, the host part from is used. + + + + + + +file + +http +server +location + + +Specifies a file with passphrases for +secret keys +where each passphrase is specified on a separate line. +Passphrases are tried in turn when loading the key. + + + + + + +on | off +off +http +server +location + + +Enables or disables passing of the server name through +TLS +Server Name Indication extension (SNI, RFC 6066) +when establishing a connection with the gRPC SSL server. + + + + + + +on | off +on +http +server +location + + +Determines whether SSL sessions can be reused when working with +the gRPC server. +If the errors +“SSL3_GET_FINISHED:digest check failed” +appear in the logs, try disabling session reuse. + + + + + + + + [SSLv2] + [SSLv3] + [TLSv1] + [TLSv1.1] + [TLSv1.2] + [TLSv1.3] +TLSv1 TLSv1.1 TLSv1.2 +http +server +location + + +Enables the specified protocols for requests to a gRPC SSL server. + + + + + + +file + +http +server +location + + +Specifies a file with trusted CA certificates in the PEM format +used to verify +the certificate of the gRPC SSL server. + + + + + + +on | off +off +http +server +location + + +Enables or disables verification of the gRPC SSL server certificate. + + + + + + +number +1 +http +server +location + + +Sets the verification depth in the gRPC SSL server certificates chain. + + + +
- -
- - - - -$memcached_key - -Defines a key for obtaining response from a memcached server. - - - - - -
-
diff --git a/xml/en/docs/index.xml b/xml/en/docs/index.xml --- a/xml/en/docs/index.xml +++ b/xml/en/docs/index.xml @@ -8,7 +8,7 @@
@@ -285,6 +285,11 @@ ngx_http_geoip_module + +ngx_http_grpc_module + + + ngx_http_gunzip_module diff --git a/xml/ru/GNUmakefile b/xml/ru/GNUmakefile --- a/xml/ru/GNUmakefile +++ b/xml/ru/GNUmakefile @@ -42,6 +42,7 @@ REFS = \ http/ngx_http_flv_module \ http/ngx_http_geo_module \ http/ngx_http_geoip_module \ + http/ngx_http_grpc_module \ http/ngx_http_gunzip_module \ http/ngx_http_gzip_module \ http/ngx_http_gzip_static_module \ diff --git a/xml/ru/docs/http/ngx_http_memcached_module.xml b/xml/ru/docs/http/ngx_http_grpc_module.xml copy from xml/ru/docs/http/ngx_http_memcached_module.xml copy to xml/ru/docs/http/ngx_http_grpc_module.xml --- a/xml/ru/docs/http/ngx_http_memcached_module.xml +++ b/xml/ru/docs/http/ngx_http_grpc_module.xml @@ -7,19 +7,18 @@ - + rev="1">
-Модуль ngx_http_memcached_module позволяет получать -ответ из сервера memcached. -Ключ задаётся в переменной $memcached_key. -Ответ в memcached должен быть предварительно помещён внешним по отношению -к nginx’у способом. +Модуль ngx_http_grpc_module позволяет передавать запросы +gRPC-серверу (1.13.10). +Для работы этого модуля необходим +модуль ngx_http_v2_module.
@@ -30,14 +29,10 @@ server { + listen 9000 http2; + location / { - set $memcached_key "$uri?$args"; - memcached_pass host:11211; - error_page 404 502 504 = @fallback; - } - - location @fallback { - proxy_pass http://backend; + grpc_pass 127.0.0.1:9000; } } @@ -48,50 +43,49 @@ server {
- + адрес - [ transparent ] | + [transparent ] | off http server location -0.8.22 -Задаёт локальный IP-адрес с необязательным портом (1.11.2), -который будет использоваться в исходящих соединениях с сервером memcached. -В значении параметра допустимо использование переменных (1.3.12). -Специальное значение off (1.3.12) отменяет действие +Задаёт локальный IP-адрес с необязательным портом, +который будет использоваться в исходящих соединениях с gRPC-сервером. +В значении параметра допустимо использование переменных. +Специальное значение off отменяет действие унаследованной с предыдущего уровня конфигурации -директивы memcached_bind, позволяя системе +директивы grpc_bind, позволяя системе самостоятельно выбирать локальный IP-адрес и порт. - -Параметр transparent (1.11.0) позволяет + +Параметр transparent позволяет задать нелокальный IP-aдрес, который будет использоваться в -исходящих соединениях с сервером memcached, +исходящих соединениях с gRPC-сервером, например, реальный IP-адрес клиента: -memcached_bind $remote_addr transparent; +grpc_bind $remote_addr transparent; Для работы параметра обычно требуется запустить рабочие процессы nginx с привилегиями суперпользователя. -В Linux этого не требуется (1.13.8), так как если +В Linux этого не требуется, так как если указан параметр transparent, то рабочие процессы наследуют capability CAP_NET_RAW из главного процесса. Также необходимо настроить таблицу маршрутизации ядра -для перехвата сетевого трафика с сервера memcached. +для перехвата сетевого трафика с gRPC-сервера. - + размер 4k|8k http @@ -100,14 +94,14 @@ memcached_bind $remote_addr transparent; Задаёт размер буфера, в который будет читаться ответ, -получаемый от сервера memcached. +получаемый от gRPC-сервера. Ответ синхронно передаётся клиенту сразу же по мере его поступления. - + время 60s http @@ -115,54 +109,99 @@ memcached_bind $remote_addr transparent; location -Задаёт таймаут для установления соединения с сервером memcached. +Задаёт таймаут для установления соединения с gRPC-сервером. Необходимо иметь в виду, что этот таймаут обычно не может превышать 75 секунд. - -on | off -off + +поле + http server location -1.7.7 -Включает поддержку диапазонов запрашиваемых байт (byte-range) -для кэшированных и некэшированных ответов сервера memcached -вне зависимости от наличия поля
Accept-Ranges
-в заголовках этих ответов. +По умолчанию +nginx не передаёт клиенту поля заголовка
Date
, +
Server
и +
X-Accel-...
из ответа gRPC-сервера. +Директива grpc_hide_header задаёт дополнительные поля, +которые не будут передаваться. +Если же передачу полей нужно разрешить, можно воспользоваться +директивой .
- -флаг - + +поле ... + http server location -1.3.6 + + +Запрещает обработку некоторых полей заголовка из ответа gRPC-сервера. +В директиве можно указать поля
X-Accel-Redirect
X-Accel-Charset
. +
-Включает проверку указанного флага в ответе -сервера memcached и установку поля “Content-Encoding” -заголовка ответа в “gzip”, если этот флаг установлен. +Если не запрещено, обработка этих полей заголовка заключается в следующем: + + + +
X-Accel-Redirect
производит +внутреннее +перенаправление на указанный URI; +
+ + +
X-Accel-Charset
задаёт желаемую +кодировку +ответа. +
+ +
- + +on | off +off +http +server +location + + +Определяет, передавать ли клиенту ответы gRPC-сервера с кодом +больше либо равным 300, +или же перехватывать их и перенаправлять на обработку nginx’у с помощью +директивы . + + + + + + error | timeout | - invalid_response | - not_found | + invalid_header | + http_500 | + http_502 | + http_503 | + http_504 | + http_403 | + http_404 | + http_429 | + non_idempotent | off ... error timeout @@ -182,11 +221,40 @@ memcached_bind $remote_addr transparent; произошёл таймаут во время соединения с сервером, передачи ему запроса или чтения заголовка ответа сервера; -invalid_response +invalid_header сервер вернул пустой или неверный ответ; -not_found -сервер не нашёл ответ; +http_500 +сервер вернул ответ с кодом 500; + +http_502 +сервер вернул ответ с кодом 502; + +http_503 +сервер вернул ответ с кодом 503; + +http_504 +сервер вернул ответ с кодом 504; + +http_403 +сервер вернул ответ с кодом 403; + +http_404 +сервер вернул ответ с кодом 404; + +http_429 +сервер вернул ответ с кодом 429; + +non_idempotent +обычно запросы с +неидемпотентным +методом +(POST, LOCK, PATCH) +не передаются на другой сервер, +если запрос серверу группы уже был отправлен; +включение параметра явно разрешает повторять подобные запросы; + + off запрещает передачу запроса следующему серверу. @@ -206,71 +274,82 @@ memcached_bind $remote_addr transparent; неудачной попыткой работы с сервером. Случаи error, timeout и -invalid_response +invalid_header всегда считаются неудачными попытками, даже если они не указаны в директиве. -Случай not_found -никогда не считается неудачной попыткой. +Случаи http_500, http_502, +http_503, http_504http_429 +считаются неудачными попытками, только если они указаны в директиве. +Случаи http_403 и http_404 +никогда не считаются неудачными попытками. Передача запроса следующему серверу может быть ограничена по -количеству попыток -и по времени. +количеству попыток +и по времени. - + время 0 http server location -1.7.5 Ограничивает время, в течение которого возможна передача запроса -следующему серверу. +следующему серверу. Значение 0 отключает это ограничение. - + число 0 http server location -1.7.5 Ограничивает число допустимых попыток для передачи запроса -следующему серверу. +следующему серверу. Значение 0 отключает это ограничение. - + адрес location if в location -Задаёт адрес сервера memcached. +Задаёт адрес gRPC-сервера. Адрес может быть указан в виде доменного имени или IP-адреса, и порта: -memcached_pass localhost:11211; +grpc_pass localhost:9000; или в виде пути UNIX-сокета: -memcached_pass unix:/tmp/memcached.socket; +grpc_pass unix:/tmp/grpc.socket; + +Также может использоваться схема “grpc://”: + +grpc_pass grpc://127.0.0.1:9000; + +Для использования gRPC по SSL необходимо использовать схему +“grpcs://”: + +grpc_pass grpcs://127.0.0.1:443; @@ -284,7 +363,22 @@ memcached_pass unix:/tmp/memcached.socke - + +поле + +http +server +location + + +Разрешает передавать от gRPC-сервера клиенту +запрещённые для передачи поля заголовка. + + + + + + время 60s http @@ -292,17 +386,17 @@ memcached_pass unix:/tmp/memcached.socke location -Задаёт таймаут при чтении ответа сервера memcached. +Задаёт таймаут при чтении ответа gRPC-сервера. Таймаут устанавливается не на всю передачу ответа, а только между двумя операциями чтения. -Если по истечении этого времени сервер memcached ничего не передаст, +Если по истечении этого времени gRPC-сервер ничего не передаст, соединение закрывается. - + время 60s http @@ -310,31 +404,254 @@ memcached_pass unix:/tmp/memcached.socke location -Задаёт таймаут при передаче запроса серверу memcached. +Задаёт таймаут при передаче запроса gRPC-серверу. Таймаут устанавливается не на всю передачу запроса, а только между двумя операциями записи. -Если по истечении этого времени сервер memcached не примет новых данных, +Если по истечении этого времени gRPC-сервер не примет новых данных, соединение закрывается. + + +поле значение +Content-Length $content_length +http +server +location + + +Позволяет переопределять или добавлять поля заголовка запроса, +передаваемые gRPC-серверу. +В качестве значения можно использовать текст, переменные и их комбинации. +Директивы наследуются с предыдущего уровня при условии, что на данном +уровне не описаны свои директивы grpc_set_header. + + + +Если значение поля заголовка — пустая строка, то поле вообще +не будет передаваться gRPC-серверу: + +grpc_set_header Accept-Encoding ""; + + + + + + + +файл + +http +server +location + + +Задаёт файл с сертификатом в формате PEM +для аутентификации на gRPC SSL-сервере. + + + + + + +файл + +http +server +location + + +Задаёт файл с секретным ключом в формате PEM +для аутентификации на gRPC SSL-сервере. + + + +Вместо файла можно указать значение +engine:имя:id, +которое загружает ключ с указанным id +из OpenSSL engine с заданным именем. + + + + + + +шифры +DEFAULT +http +server +location + + +Описывает разрешённые шифры для запросов к gRPC SSL-серверу. +Шифры задаются в формате, поддерживаемом библиотекой OpenSSL. + + + +Полный список можно посмотреть с помощью команды +“openssl ciphers”. + + + + + + +файл + +http +server +location + + +Указывает файл с отозванными сертификатами (CRL) +в формате PEM, используемыми при проверке +сертификата gRPC SSL-сервера. + + + + + + +имя +имя хоста из grpc_pass +http +server +location + + +Позволяет переопределить имя сервера, используемое при +проверке +сертификата gRPC SSL-сервера, а также для +передачи его через SNI +при установлении соединения с gRPC SSL-сервером. + + + +По умолчанию используется имя хоста из . + + + + + + +файл + +http +server +location + + +Задаёт файл с паролями от +секретных ключей, +где каждый пароль указан на отдельной строке. +Пароли применяются по очереди в момент загрузки ключа. + + + + + + +on | off +off +http +server +location + + +Разрешает или запрещает передачу имени сервера через +расширение +Server Name Indication протокола TLS (SNI, RFC 6066) +при установлении соединения с gRPC SSL-сервером. + + + + + + +on | off +on +http +server +location + + +Определяет, использовать ли повторно SSL-сессии при +работе с gRPC-сервером. +Если в логах появляются ошибки +“SSL3_GET_FINISHED:digest check failed”, +то можно попробовать выключить +повторное использование сессий. + + + + + + + + [SSLv2] + [SSLv3] + [TLSv1] + [TLSv1.1] + [TLSv1.2] + [TLSv1.3] +TLSv1 TLSv1.1 TLSv1.2 +http +server +location + + +Разрешает указанные протоколы для запросов к gRPC SSL-серверу. + + + + + + +файл + +http +server +location + + +Задаёт файл с доверенными сертификатами CA в формате PEM, +используемыми при проверке +сертификата gRPC SSL-сервера. + + + + + + +on | off +off +http +server +location + + +Разрешает или запрещает проверку сертификата gRPC SSL-сервера. + + + + + + +число +1 +http +server +location + + +Устанавливает глубину проверки в цепочке сертификатов +gRPC SSL-сервера. + + + +
- -
- - - - -$memcached_key - -Задаёт ключ для получения ответа из сервера memcached. - - - - - -
-
diff --git a/xml/ru/docs/index.xml b/xml/ru/docs/index.xml --- a/xml/ru/docs/index.xml +++ b/xml/ru/docs/index.xml @@ -8,7 +8,7 @@
@@ -290,6 +290,11 @@ ngx_http_geoip_module + +ngx_http_grpc_module + + + ngx_http_gunzip_module