Merge commit 'eca8662cfe981f66ab92b53bbf83af65da02b2b7' as 'src/deps/src/lua-resty-redis'

This commit is contained in:
Théophile Diot 2023-06-30 15:38:51 -04:00
commit 2f1cde0978
24 changed files with 5396 additions and 0 deletions

View File

@ -0,0 +1 @@
*.t linguist-language=Text

View File

@ -0,0 +1,8 @@
*.swp
*.swo
*~
go
t/servroot/
reindex
*.t_
tags

View File

@ -0,0 +1,3 @@
std = 'ngx_lua'
redefined = false
unused_args = false

View File

@ -0,0 +1,79 @@
sudo: required
dist: bionic
os: linux
language: c
compiler: gcc
addons:
apt:
packages:
- luarocks
services:
- docker
cache:
directories:
- download-cache
env:
global:
- JOBS=3
- NGX_BUILD_JOBS=$JOBS
- LUAJIT_PREFIX=/opt/luajit21
- LUAJIT_LIB=$LUAJIT_PREFIX/lib
- LUAJIT_INC=$LUAJIT_PREFIX/include/luajit-2.1
- LUA_INCLUDE_DIR=$LUAJIT_INC
- OPENSSL_PREFIX=/opt/ssl
- OPENSSL_LIB=$OPENSSL_PREFIX/lib
- OPENSSL_INC=$OPENSSL_PREFIX/include
- OPENSSL_VER=1.1.1l
- LD_LIBRARY_PATH=$LUAJIT_LIB:$LD_LIBRARY_PATH
- TEST_NGINX_SLEEP=0.006
- LUACHECK_VER=0.21.1
jobs:
- NGINX_VERSION=1.21.4
before_install:
- sudo luarocks install luacheck $LUACHECK_VER
- luacheck -q .
install:
- if [ ! -d download-cache ]; then mkdir download-cache; fi
- if [ ! -f download-cache/openssl-$OPENSSL_VER.tar.gz ]; then wget -O download-cache/openssl-$OPENSSL_VER.tar.gz https://www.openssl.org/source/openssl-$OPENSSL_VER.tar.gz; fi
- sudo apt-get install -qq -y cpanminus axel
- sudo cpanm --notest Test::Nginx > build.log 2>&1 || (cat build.log && exit 1)
- git clone https://github.com/openresty/openresty.git ../openresty
- git clone https://github.com/openresty/nginx-devel-utils.git
- git clone https://github.com/openresty/lua-cjson.git
- git clone https://github.com/openresty/lua-nginx-module.git ../lua-nginx-module
- git clone https://github.com/openresty/stream-lua-nginx-module.git ../stream-lua-nginx-module
- git clone https://github.com/openresty/lua-resty-core.git ../lua-resty-core
- git clone https://github.com/openresty/lua-resty-lrucache.git ../lua-resty-lrucache
- git clone https://github.com/openresty/echo-nginx-module.git ../echo-nginx-module
- git clone https://github.com/openresty/no-pool-nginx.git ../no-pool-nginx
- git clone -b v2.1-agentzh https://github.com/openresty/luajit2.git
script:
- sudo iptables -A OUTPUT -p tcp --dst 127.0.0.2 --dport 12345 -j DROP
- cd luajit2/
- make -j$JOBS CCDEBUG=-g Q= PREFIX=$LUAJIT_PREFIX CC=$CC XCFLAGS='-DLUA_USE_APICHECK -DLUA_USE_ASSERT' > build.log 2>&1 || (cat build.log && exit 1)
- sudo make install PREFIX=$LUAJIT_PREFIX > build.log 2>&1 || (cat build.log && exit 1)
- cd ../lua-cjson && make && sudo PATH=$PATH make install && cd ..
- tar zxf download-cache/openssl-$OPENSSL_VER.tar.gz
- cd openssl-$OPENSSL_VER/
- ./config shared --prefix=$OPENSSL_PREFIX -DPURIFY > build.log 2>&1 || (cat build.log && exit 1)
- make -j$JOBS > build.log 2>&1 || (cat build.log && exit 1)
- sudo make PATH=$PATH install_sw > build.log 2>&1 || (cat build.log && exit 1)
- cd ..
- export PATH=$PWD/work/nginx/sbin:$PWD/nginx-devel-utils:$PATH
- export NGX_BUILD_CC=$CC
- ngx-build $NGINX_VERSION --with-ipv6 --with-http_realip_module --with-http_ssl_module --with-cc-opt="-I$OPENSSL_INC" --with-ld-opt="-L$OPENSSL_LIB -Wl,-rpath,$OPENSSL_LIB" --add-module=../echo-nginx-module --add-module=../lua-nginx-module --add-module=../stream-lua-nginx-module --with-stream --with-stream_ssl_module --with-debug > build.log 2>&1 || (cat build.log && exit 1)
- nginx -V
- ldd `which nginx`|grep -E 'luajit|ssl|pcre'
- docker run -d -p 6379:6379 --rm --name redis-redisbloom redislabs/rebloom:latest
- TEST_SUBSYSTEM=http prove -I. -r t
- TEST_SUBSYSTEM=stream prove -I. -r t

View File

@ -0,0 +1,18 @@
OPENRESTY_PREFIX=/usr/local/openresty-debug
PREFIX ?= /usr/local
LUA_INCLUDE_DIR ?= $(PREFIX)/include
LUA_LIB_DIR ?= $(PREFIX)/lib/lua/$(LUA_VERSION)
INSTALL ?= install
.PHONY: all test install
all: ;
install: all
$(INSTALL) -d $(DESTDIR)$(LUA_LIB_DIR)/resty
$(INSTALL) lib/resty/*.lua $(DESTDIR)$(LUA_LIB_DIR)/resty
test: all
PATH=$(OPENRESTY_PREFIX)/nginx/sbin:$$PATH prove -I../test-nginx/lib -r t

View File

@ -0,0 +1,773 @@
Name
====
lua-resty-redis - Lua redis client driver for the ngx_lua based on the cosocket API
Table of Contents
=================
* [Name](#name)
* [Status](#status)
* [Description](#description)
* [Synopsis](#synopsis)
* [Methods](#methods)
* [new](#new)
* [connect](#connect)
* [set_timeout](#set_timeout)
* [set_timeouts](#set_timeouts)
* [set_keepalive](#set_keepalive)
* [get_reused_times](#get_reused_times)
* [close](#close)
* [init_pipeline](#init_pipeline)
* [commit_pipeline](#commit_pipeline)
* [cancel_pipeline](#cancel_pipeline)
* [hmset](#hmset)
* [array_to_hash](#array_to_hash)
* [read_reply](#read_reply)
* [add_commands](#add_commands)
* [Redis Authentication](#redis-authentication)
* [Redis Transactions](#redis-transactions)
* [Load Balancing and Failover](#load-balancing-and-failover)
* [Debugging](#debugging)
* [Automatic Error Logging](#automatic-error-logging)
* [Check List for Issues](#check-list-for-issues)
* [Limitations](#limitations)
* [Installation](#installation)
* [TODO](#todo)
* [Community](#community)
* [English Mailing List](#english-mailing-list)
* [Chinese Mailing List](#chinese-mailing-list)
* [Bugs and Patches](#bugs-and-patches)
* [Author](#author)
* [Copyright and License](#copyright-and-license)
* [See Also](#see-also)
Status
======
This library is considered production ready.
Description
===========
This Lua library is a Redis client driver for the ngx_lua nginx module:
https://github.com/openresty/lua-nginx-module/#readme
This Lua library takes advantage of ngx_lua's cosocket API, which ensures
100% nonblocking behavior.
Note that at least [ngx_lua 0.5.14](https://github.com/chaoslawful/lua-nginx-module/tags) or [OpenResty 1.2.1.14](http://openresty.org/#Download) is required.
Synopsis
========
```lua
# you do not need the following line if you are using
# the OpenResty bundle:
lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
server {
location /test {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
ok, err = red:set("dog", "an animal")
if not ok then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set result: ", ok)
local res, err = red:get("dog")
if not res then
ngx.say("failed to get dog: ", err)
return
end
if res == ngx.null then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if res[1] == false then
ngx.say("failed to run command ", i, ": ", res[2])
else
-- process the table value
end
else
-- process the scalar value
end
end
-- put it into the connection pool of size 100,
-- with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
-- or just close the connection right away:
-- local ok, err = red:close()
-- if not ok then
-- ngx.say("failed to close: ", err)
-- return
-- end
}
}
}
```
[Back to TOC](#table-of-contents)
Methods
=======
All of the Redis commands have their own methods with the same name except all in lower case.
You can find the complete list of Redis commands here:
http://redis.io/commands
You need to check out this Redis command reference to see what Redis command accepts what arguments.
The Redis command arguments can be directly fed into the corresponding method call. For example, the "GET" redis command accepts a single key argument, then you can just call the "get" method like this:
```lua
local res, err = red:get("key")
```
Similarly, the "LRANGE" redis command accepts threee arguments, then you should call the "lrange" method like this:
```lua
local res, err = red:lrange("nokey", 0, 1)
```
For example, "SET", "GET", "LRANGE", and "BLPOP" commands correspond to the methods "set", "get", "lrange", and "blpop".
Here are some more examples:
```lua
-- HMGET myhash field1 field2 nofield
local res, err = red:hmget("myhash", "field1", "field2", "nofield")
```
```lua
-- HMSET myhash field1 "Hello" field2 "World"
local res, err = red:hmset("myhash", "field1", "Hello", "field2", "World")
```
All these command methods returns a single result in success and `nil` otherwise. In case of errors or failures, it will also return a second value which is a string describing the error.
A Redis "status reply" results in a string typed return value with the "+" prefix stripped.
A Redis "integer reply" results in a Lua number typed return value.
A Redis "error reply" results in a `false` value *and* a string describing the error.
A non-nil Redis "bulk reply" results in a Lua string as the return value. A nil bulk reply results in a `ngx.null` return value.
A non-nil Redis "multi-bulk reply" results in a Lua table holding all the composing values (if any). If any of the composing value is a valid redis error value, then it will be a two element table `{false, err}`.
A nil multi-bulk reply returns in a `ngx.null` value.
See http://redis.io/topics/protocol for details regarding various Redis reply types.
In addition to all those redis command methods, the following methods are also provided:
[Back to TOC](#table-of-contents)
new
---
`syntax: red, err = redis:new()`
Creates a redis object. In case of failures, returns `nil` and a string describing the error.
[Back to TOC](#table-of-contents)
connect
-------
`syntax: ok, err = red:connect(host, port, options_table?)`
`syntax: ok, err = red:connect("unix:/path/to/unix.sock", options_table?)`
Attempts to connect to the remote host and port that the redis server is listening to or a local unix domain socket file listened by the redis server.
Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.
The optional `options_table` argument is a Lua table holding the following keys:
* `ssl`
If set to true, then uses SSL to connect to redis (defaults to false).
* `ssl_verify`
If set to true, then verifies the validity of the server SSL certificate (defaults to false). Note that you need to configure the lua_ssl_trusted_certificate to specify the CA (or server) certificate used by your redis server. You may also need to configure lua_ssl_verify_depth accordingly.
* `server_name`
Specifies the server name for the new TLS extension Server Name Indication (SNI) when connecting over SSL.
* `pool`
Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `<host>:<port>` or `<unix-socket-path>`.
* `pool_size`
Specifies the size of the connection pool. If omitted and no `backlog` option was provided, no pool will be created. If omitted but `backlog` was provided, the pool will be created with a default size equal to the value of the [lua_socket_pool_size](https://github.com/openresty/lua-nginx-module#lua_socket_pool_size) directive. The connection pool holds up to `pool_size` alive connections ready to be reused by subsequent calls to [connect](#connect), but note that there is no upper limit to the total number of opened connections outside of the pool. If you need to restrict the total number of opened connections, specify the `backlog` option. When the connection pool would exceed its size limit, the least recently used (kept-alive) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process. Also note that the size of the connection pool cannot be changed once it has been created. Note that at least [ngx_lua 0.10.14](https://github.com/openresty/lua-nginx-module/tags) is required to use this options.
* `backlog`
If specified, this module will limit the total number of opened connections for this pool. No more connections than `pool_size` can be opened for this pool at any time. If the connection pool is full, subsequent connect operations will be queued into a queue equal to this option's value (the "backlog" queue). If the number of queued connect operations is equal to `backlog`, subsequent connect operations will fail and return nil plus the error string `"too many waiting connect operations"`. The queued connect operations will be resumed once the number of connections in the pool is less than `pool_size`. The queued connect operation will abort once they have been queued for more than `connect_timeout`, controlled by [set_timeout](#set_timeout), and will return nil plus the error string "timeout". Note that at least [ngx_lua 0.10.14](https://github.com/openresty/lua-nginx-module/tags) is required to use this options.
[Back to TOC](#table-of-contents)
set_timeout
-----------
`syntax: red:set_timeout(time)`
Sets the timeout (in ms) protection for subsequent operations, including the `connect` method.
Since version `v0.28` of this module, it is advised that
[set_timeouts](#set_timeouts) be used in favor of this method.
[Back to TOC](#table-of-contents)
set_timeouts
------------
`syntax: red:set_timeouts(connect_timeout, send_timeout, read_timeout)`
Respectively sets the connect, send, and read timeout thresholds (in ms), for
subsequent socket operations. Setting timeout thresholds with this method
offers more granularity than [set_timeout](#set_timeout). As such, it is
preferred to use [set_timeouts](#set_timeouts) over
[set_timeout](#set_timeout).
This method was added in the `v0.28` release.
[Back to TOC](#table-of-contents)
set_keepalive
-------------
`syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)`
Puts the current Redis connection immediately into the ngx_lua cosocket connection pool.
You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.
In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
Only call this method in the place you would have called the `close` method instead. Calling this method will immediately turn the current redis object into the `closed` state. Any subsequent operations other than `connect()` on the current object will return the `closed` error.
[Back to TOC](#table-of-contents)
get_reused_times
----------------
`syntax: times, err = red:get_reused_times()`
This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.
If the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.
[Back to TOC](#table-of-contents)
close
-----
`syntax: ok, err = red:close()`
Closes the current redis connection and returns the status.
In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
[Back to TOC](#table-of-contents)
init_pipeline
-------------
`syntax: red:init_pipeline()`
`syntax: red:init_pipeline(n)`
Enable the redis pipelining mode. All subsequent calls to Redis command methods will automatically get cached and will send to the server in one run when the `commit_pipeline` method is called or get cancelled by calling the `cancel_pipeline` method.
This method always succeeds.
If the redis object is already in the Redis pipelining mode, then calling this method will discard existing cached Redis queries.
The optional `n` argument specifies the (approximate) number of commands that are going to add to this pipeline, which can make things a little faster.
[Back to TOC](#table-of-contents)
commit_pipeline
---------------
`syntax: results, err = red:commit_pipeline()`
Quits the pipelining mode by committing all the cached Redis queries to the remote server in a single run. All the replies for these queries will be collected automatically and are returned as if a big multi-bulk reply at the highest level.
This method returns `nil` and a Lua string describing the error upon failures.
[Back to TOC](#table-of-contents)
cancel_pipeline
---------------
`syntax: red:cancel_pipeline()`
Quits the pipelining mode by discarding all existing cached Redis commands since the last call to the `init_pipeline` method.
This method always succeeds.
If the redis object is not in the Redis pipelining mode, then this method is a no-op.
[Back to TOC](#table-of-contents)
hmset
-----
`syntax: res, err = red:hmset(myhash, field1, value1, field2, value2, ...)`
`syntax: res, err = red:hmset(myhash, { field1 = value1, field2 = value2, ... })`
Special wrapper for the Redis "hmset" command.
When there are only three arguments (including the "red" object
itself), then the last argument must be a Lua table holding all the field/value pairs.
[Back to TOC](#table-of-contents)
array_to_hash
-------------
`syntax: hash = red:array_to_hash(array)`
Auxiliary function that converts an array-like Lua table into a hash-like table.
This method was first introduced in the `v0.11` release.
[Back to TOC](#table-of-contents)
read_reply
----------
`syntax: res, err = red:read_reply()`
Reading a reply from the redis server. This method is mostly useful for the [Redis Pub/Sub API](http://redis.io/topics/pubsub/), for example,
```lua
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
red2:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", 6379)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
local res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
res, err = red2:publish("dog", "Hello")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
ngx.say("2: publish: ", cjson.encode(res))
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
return
end
ngx.say("1: receive: ", cjson.encode(res))
red:close()
red2:close()
```
Running this example gives the output like this:
1: subscribe: ["subscribe","dog",1]
2: publish: 1
1: receive: ["message","dog","Hello"]
The following class methods are provieded:
[Back to TOC](#table-of-contents)
add_commands
------------
`syntax: hash = redis.add_commands(cmd_name1, cmd_name2, ...)`
*WARNING* this method is now deprecated since we already do automatic Lua method generation
for any redis commands the user attempts to use and thus we no longer need this.
Adds new redis commands to the `resty.redis` class. Here is an example:
```lua
local redis = require "resty.redis"
redis.add_commands("foo", "bar")
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:foo("a")
if not res then
ngx.say("failed to foo: ", err)
end
res, err = red:bar()
if not res then
ngx.say("failed to bar: ", err)
end
```
[Back to TOC](#table-of-contents)
Redis Authentication
====================
Redis uses the `AUTH` command to do authentication: http://redis.io/commands/auth
There is nothing special for this command as compared to other Redis
commands like `GET` and `SET`. So one can just invoke the `auth` method on your `resty.redis` instance. Here is an example:
```lua
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:auth("foobared")
if not res then
ngx.say("failed to authenticate: ", err)
return
end
```
where we assume that the Redis server is configured with the
password `foobared` in the `redis.conf` file:
requirepass foobared
If the password specified is wrong, then the sample above will output the
following to the HTTP client:
failed to authenticate: ERR invalid password
[Back to TOC](#table-of-contents)
Redis Transactions
==================
This library supports the [Redis transactions](http://redis.io/topics/transactions/). Here is an example:
```lua
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:multi()
if not ok then
ngx.say("failed to run multi: ", err)
return
end
ngx.say("multi ans: ", cjson.encode(ok))
local ans, err = red:set("a", "abc")
if not ans then
ngx.say("failed to run sort: ", err)
return
end
ngx.say("set ans: ", cjson.encode(ans))
local ans, err = red:lpop("a")
if not ans then
ngx.say("failed to run sort: ", err)
return
end
ngx.say("set ans: ", cjson.encode(ans))
ans, err = red:exec()
ngx.say("exec ans: ", cjson.encode(ans))
red:close()
```
Then the output will be
multi ans: "OK"
set ans: "QUEUED"
set ans: "QUEUED"
exec ans: ["OK",[false,"ERR Operation against a key holding the wrong kind of value"]]
[Back to TOC](#table-of-contents)
Redis Module
==================
This library supports the Redis module. Here is an example with RedisBloom module:
```lua
local cjson = require "cjson"
local redis = require "resty.redis"
-- register the module prefix "bf" for RedisBloom
redis.register_module_prefix("bf")
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- call BF.ADD command with the prefix 'bf'
res, err = red:bf():add("dog", 1)
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
-- call BF.EXISTS command
res, err = red:bf():exists("dog")
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
```
Load Balancing and Failover
===========================
You can trivially implement your own Redis load balancing logic yourself in Lua. Just keep a Lua table of all available Redis backend information (like host name and port numbers) and pick one server according to some rule (like round-robin or key-based hashing) from the Lua table at every request. You can keep track of the current rule state in your own Lua module's data, see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker
Similarly, you can implement automatic failover logic in Lua at great flexibility.
[Back to TOC](#table-of-contents)
Debugging
=========
It is usually convenient to use the [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php) library to encode the return values of the redis command methods to JSON. For example,
```lua
local cjson = require "cjson"
...
local res, err = red:mget("h1234", "h5678")
if res then
print("res: ", cjson.encode(res))
end
```
[Back to TOC](#table-of-contents)
Automatic Error Logging
=======================
By default the underlying [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme) module
does error logging when socket errors happen. If you are already doing proper error
handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme)'s [lua_socket_log_errors](https://github.com/openresty/lua-nginx-module/#lua_socket_log_errors) directive, that is,
```nginx
lua_socket_log_errors off;
```
[Back to TOC](#table-of-contents)
Check List for Issues
=====================
1. Ensure you configure the connection pool size properly in the [set_keepalive](#set_keepalive). Basically if your Redis can handle `n` concurrent connections and your NGINX has `m` workers, then the connection pool size should be configured as `n/m`. For example, if your Redis usually handles 1000 concurrent requests and you have 10 NGINX workers, then the connection pool size should be 100. Similarly if you have `p` different NGINX instances, then connection pool size should be `n/m/p`.
2. Ensure the backlog setting on the Redis side is large enough. For Redis 2.8+, you can directly tune the `tcp-backlog` parameter in the `redis.conf` file (and also tune the kernel parameter `SOMAXCONN` accordingly at least on Linux). You may also want to tune the `maxclients` parameter in `redis.conf`.
3. Ensure you are not using too short timeout setting in the [set_timeout](#set_timeout) or [set_timeouts](#set_timeouts) methods. If you have to, try redoing the operation upon timeout and turning off [automatic error logging](#automatic-error-logging) (because you are already doing proper error handling in your own Lua code).
4. If your NGINX worker processes' CPU usage is very high under load, then the NGINX event loop might be blocked by the CPU computation too much. Try sampling a [C-land on-CPU Flame Graph](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt) and [Lua-land on-CPU Flame Graph](https://github.com/agentzh/stapxx#ngx-lj-lua-stacks) for a typical NGINX worker process. You can optimize the CPU-bound things according to these Flame Graphs.
5. If your NGINX worker processes' CPU usage is very low under load, then the NGINX event loop might be blocked by some blocking system calls (like file IO system calls). You can confirm the issue by running the [epoll-loop-blocking-distr](https://github.com/agentzh/stapxx#epoll-loop-blocking-distr) tool against a typical NGINX worker process. If it is indeed the case, then you can further sample a [C-land off-CPU Flame Graph](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt-off-cpu) for a NGINX worker process to analyze the actual blockers.
6. If your `redis-server` process is running near 100% CPU usage, then you should consider scale your Redis backend by multiple nodes or use the [C-land on-CPU Flame Graph tool](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt) to analyze the internal bottlenecks within the Redis server process.
[Back to TOC](#table-of-contents)
Limitations
===========
* This library cannot be used in code contexts like init_by_lua*, set_by_lua*, log_by_lua*, and
header_filter_by_lua* where the ngx_lua cosocket API is not available.
* The `resty.redis` object instance cannot be stored in a Lua variable at the Lua module level,
because it will then be shared by all the concurrent requests handled by the same nginx
worker process (see
https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and
result in bad race conditions when concurrent requests are trying to use the same `resty.redis` instance
(you would see the "bad request" or "socket busy" error to be returned from the method calls).
You should always initiate `resty.redis` objects in function local
variables or in the `ngx.ctx` table. These places all have their own data copies for
each request.
[Back to TOC](#table-of-contents)
Installation
============
If you are using the OpenResty bundle (http://openresty.org ), then
you do not need to do anything because it already includes and enables
lua-resty-redis by default. And you can just use it in your Lua code,
as in
```lua
local redis = require "resty.redis"
...
```
If you are using your own nginx + ngx_lua build, then you need to configure
the lua_package_path directive to add the path of your lua-resty-redis source
tree to ngx_lua's LUA_PATH search path, as in
```nginx
# nginx.conf
http {
lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
...
}
```
Ensure that the system account running your Nginx ''worker'' proceses have
enough permission to read the `.lua` file.
[Back to TOC](#table-of-contents)
TODO
====
[Back to TOC](#table-of-contents)
Community
=========
[Back to TOC](#table-of-contents)
English Mailing List
--------------------
The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers.
[Back to TOC](#table-of-contents)
Chinese Mailing List
--------------------
The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers.
[Back to TOC](#table-of-contents)
Bugs and Patches
================
Please report bugs or submit patches by
1. creating a ticket on the [GitHub Issue Tracker](http://github.com/agentzh/lua-resty-redis/issues),
1. or posting to the [OpenResty community](#community).
[Back to TOC](#table-of-contents)
Author
======
Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, OpenResty Inc.
[Back to TOC](#table-of-contents)
Copyright and License
=====================
This module is licensed under the BSD license.
Copyright (C) 2012-2017, by Yichun Zhang (agentzh) <agentzh@gmail.com>, OpenResty Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[Back to TOC](#table-of-contents)
See Also
========
* the ngx_lua module: https://github.com/openresty/lua-nginx-module/#readme
* the redis wired protocol specification: http://redis.io/topics/protocol
* the [lua-resty-memcached](https://github.com/agentzh/lua-resty-memcached) library
* the [lua-resty-mysql](https://github.com/agentzh/lua-resty-mysql) library
[Back to TOC](#table-of-contents)

View File

@ -0,0 +1,9 @@
name=lua-resty-redis
abstract=Lua redis client driver for the ngx_lua based on the cosocket API
author=Yichun "agentzh" Zhang (agentzh)
is_original=yes
license=2bsd
lib_dir=lib
doc_dir=lib
repo_link=https://github.com/openresty/lua-resty-redis
main_module=lib/resty/redis.lua

View File

@ -0,0 +1,695 @@
-- Copyright (C) Yichun Zhang (agentzh)
local sub = string.sub
local byte = string.byte
local tab_insert = table.insert
local tab_remove = table.remove
local tcp = ngx.socket.tcp
local null = ngx.null
local ipairs = ipairs
local type = type
local pairs = pairs
local unpack = unpack
local setmetatable = setmetatable
local tonumber = tonumber
local tostring = tostring
local rawget = rawget
local select = select
--local error = error
local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
new_tab = function (narr, nrec) return {} end
end
local _M = new_tab(0, 55)
_M._VERSION = '0.30'
local common_cmds = {
"get", "set", "mget", "mset",
"del", "incr", "decr", -- Strings
"llen", "lindex", "lpop", "lpush",
"lrange", "linsert", -- Lists
"hexists", "hget", "hset", "hmget",
--[[ "hmset", ]] "hdel", -- Hashes
"smembers", "sismember", "sadd", "srem",
"sdiff", "sinter", "sunion", -- Sets
"zrange", "zrangebyscore", "zrank", "zadd",
"zrem", "zincrby", -- Sorted Sets
"auth", "eval", "expire", "script",
"sort" -- Others
}
local sub_commands = {
"subscribe", "psubscribe"
}
local unsub_commands = {
"unsubscribe", "punsubscribe"
}
local mt = { __index = _M }
function _M.new(self)
local sock, err = tcp()
if not sock then
return nil, err
end
return setmetatable({ _sock = sock,
_subscribed = false,
_n_channel = {
unsubscribe = 0,
punsubscribe = 0,
},
}, mt)
end
function _M.register_module_prefix(mod)
_M[mod] = function(self)
self._module_prefix = mod
return self
end
end
function _M.set_timeout(self, timeout)
local sock = rawget(self, "_sock")
if not sock then
error("not initialized", 2)
return
end
sock:settimeout(timeout)
end
function _M.set_timeouts(self, connect_timeout, send_timeout, read_timeout)
local sock = rawget(self, "_sock")
if not sock then
error("not initialized", 2)
return
end
sock:settimeouts(connect_timeout, send_timeout, read_timeout)
end
function _M.connect(self, host, port_or_opts, opts)
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
local unix
do
local typ = type(host)
if typ ~= "string" then
error("bad argument #1 host: string expected, got " .. typ, 2)
end
if sub(host, 1, 5) == "unix:" then
unix = true
end
if unix then
typ = type(port_or_opts)
if port_or_opts ~= nil and typ ~= "table" then
error("bad argument #2 opts: nil or table expected, got " ..
typ, 2)
end
else
typ = type(port_or_opts)
if typ ~= "number" then
port_or_opts = tonumber(port_or_opts)
if port_or_opts == nil then
error("bad argument #2 port: number expected, got " ..
typ, 2)
end
end
if opts ~= nil then
typ = type(opts)
if typ ~= "table" then
error("bad argument #3 opts: nil or table expected, got " ..
typ, 2)
end
end
end
end
self._subscribed = false
local ok, err
if unix then
-- second argument of sock:connect() cannot be nil
if port_or_opts ~= nil then
ok, err = sock:connect(host, port_or_opts)
opts = port_or_opts
else
ok, err = sock:connect(host)
end
else
ok, err = sock:connect(host, port_or_opts, opts)
end
if not ok then
return ok, err
end
if opts and opts.ssl then
ok, err = sock:sslhandshake(false, opts.server_name, opts.ssl_verify)
if not ok then
return ok, "failed to do ssl handshake: " .. err
end
end
return ok, err
end
function _M.set_keepalive(self, ...)
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
if rawget(self, "_subscribed") then
return nil, "subscribed state"
end
return sock:setkeepalive(...)
end
function _M.get_reused_times(self)
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
local function close(self)
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
return sock:close()
end
_M.close = close
local function _read_reply(self, sock)
local line, err = sock:receive()
if not line then
if err == "timeout" and not rawget(self, "_subscribed") then
sock:close()
end
return nil, err
end
local prefix = byte(line)
if prefix == 36 then -- char '$'
-- print("bulk reply")
local size = tonumber(sub(line, 2))
if size < 0 then
return null
end
local data, err = sock:receive(size)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
local dummy, err = sock:receive(2) -- ignore CRLF
if not dummy then
if err == "timeout" then
sock:close()
end
return nil, err
end
return data
elseif prefix == 43 then -- char '+'
-- print("status reply")
return sub(line, 2)
elseif prefix == 42 then -- char '*'
local n = tonumber(sub(line, 2))
-- print("multi-bulk reply: ", n)
if n < 0 then
return null
end
local vals = new_tab(n, 0)
local nvals = 0
for i = 1, n do
local res, err = _read_reply(self, sock)
if res then
nvals = nvals + 1
vals[nvals] = res
elseif res == nil then
return nil, err
else
-- be a valid redis error value
nvals = nvals + 1
vals[nvals] = {false, err}
end
end
return vals
elseif prefix == 58 then -- char ':'
-- print("integer reply")
return tonumber(sub(line, 2))
elseif prefix == 45 then -- char '-'
-- print("error reply: ", n)
return false, sub(line, 2)
else
-- when `line` is an empty string, `prefix` will be equal to nil.
return nil, "unknown prefix: \"" .. tostring(prefix) .. "\""
end
end
local function _gen_req(args)
local nargs = #args
local req = new_tab(nargs * 5 + 1, 0)
req[1] = "*" .. nargs .. "\r\n"
local nbits = 2
for i = 1, nargs do
local arg = args[i]
if type(arg) ~= "string" then
arg = tostring(arg)
end
req[nbits] = "$"
req[nbits + 1] = #arg
req[nbits + 2] = "\r\n"
req[nbits + 3] = arg
req[nbits + 4] = "\r\n"
nbits = nbits + 5
end
-- it is much faster to do string concatenation on the C land
-- in real world (large number of strings in the Lua VM)
return req
end
local function _check_msg(self, res)
return rawget(self, "_subscribed") and
type(res) == "table" and (res[1] == "message" or res[1] == "pmessage")
end
local function _do_cmd(self, ...)
local args = {...}
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
local req = _gen_req(args)
local reqs = rawget(self, "_reqs")
if reqs then
reqs[#reqs + 1] = req
return
end
-- print("request: ", table.concat(req))
local bytes, err = sock:send(req)
if not bytes then
return nil, err
end
local res, err = _read_reply(self, sock)
while _check_msg(self, res) do
if rawget(self, "_buffered_msg") == nil then
self._buffered_msg = new_tab(1, 0)
end
tab_insert(self._buffered_msg, res)
res, err = _read_reply(self, sock)
end
return res, err
end
local function _check_unsubscribed(self, res)
if type(res) == "table"
and (res[1] == "unsubscribe" or res[1] == "punsubscribe")
then
self._n_channel[res[1]] = self._n_channel[res[1]] - 1
local buffered_msg = rawget(self, "_buffered_msg")
if buffered_msg then
-- remove messages of unsubscribed channel
local msg_type =
(res[1] == "punsubscribe") and "pmessage" or "message"
local j = 1
for _, msg in ipairs(buffered_msg) do
if msg[1] == msg_type and msg[2] ~= res[2] then
-- move messages to overwrite the removed ones
buffered_msg[j] = msg
j = j + 1
end
end
-- clear remain messages
for i = j, #buffered_msg do
buffered_msg[i] = nil
end
if #buffered_msg == 0 then
self._buffered_msg = nil
end
end
if res[3] == 0 then
-- all channels are unsubscribed
self._subscribed = false
end
end
end
local function _check_subscribed(self, res)
if type(res) == "table"
and (res[1] == "subscribe" or res[1] == "psubscribe")
then
if res[1] == "subscribe" then
self._n_channel.unsubscribe = self._n_channel.unsubscribe + 1
elseif res[1] == "psubscribe" then
self._n_channel.punsubscribe = self._n_channel.punsubscribe + 1
end
end
end
function _M.read_reply(self)
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
if not rawget(self, "_subscribed") then
return nil, "not subscribed"
end
local buffered_msg = rawget(self, "_buffered_msg")
if buffered_msg then
local msg = buffered_msg[1]
tab_remove(buffered_msg, 1)
if #buffered_msg == 0 then
self._buffered_msg = nil
end
return msg
end
local res, err = _read_reply(self, sock)
_check_unsubscribed(self, res)
return res, err
end
local function do_cmd(self, cmd, ...)
local module_prefix = rawget(self, "_module_prefix")
if module_prefix then
self._module_prefix = nil
return _do_cmd(self, module_prefix .. "." .. cmd, ...)
end
return _do_cmd(self, cmd, ...)
end
for i = 1, #common_cmds do
local cmd = common_cmds[i]
_M[cmd] =
function (self, ...)
return do_cmd(self, cmd, ...)
end
end
local function handle_subscribe_result(self, cmd, nargs, res)
local err
_check_subscribed(self, res)
if nargs <= 1 then
return res
end
local results = new_tab(nargs, 0)
results[1] = res
local sock = rawget(self, "_sock")
for i = 2, nargs do
res, err = _read_reply(self, sock)
if not res then
return nil, err
end
_check_subscribed(self, res)
results[i] = res
end
return results
end
for i = 1, #sub_commands do
local cmd = sub_commands[i]
_M[cmd] =
function (self, ...)
if not rawget(self, "_subscribed") then
self._subscribed = true
end
local nargs = select("#", ...)
local res, err = _do_cmd(self, cmd, ...)
if not res then
return nil, err
end
return handle_subscribe_result(self, cmd, nargs, res)
end
end
local function handle_unsubscribe_result(self, cmd, nargs, res)
local err
_check_unsubscribed(self, res)
if self._n_channel[cmd] == 0 or nargs == 1 then
return res
end
local results = new_tab(nargs, 0)
results[1] = res
local sock = rawget(self, "_sock")
local i = 2
while nargs == 0 or i <= nargs do
res, err = _read_reply(self, sock)
if not res then
return nil, err
end
results[i] = res
i = i + 1
_check_unsubscribed(self, res)
if self._n_channel[cmd] == 0 then
-- exit the loop for unsubscribe() call
break
end
end
return results
end
for i = 1, #unsub_commands do
local cmd = unsub_commands[i]
_M[cmd] =
function (self, ...)
-- assume all channels are unsubscribed by only one time
if not rawget(self, "_subscribed") then
return nil, "not subscribed"
end
local nargs = select("#", ...)
local res, err = _do_cmd(self, cmd, ...)
if not res then
return nil, err
end
return handle_unsubscribe_result(self, cmd, nargs, res)
end
end
function _M.hmset(self, hashname, ...)
if select('#', ...) == 1 then
local t = select(1, ...)
local n = 0
for k, v in pairs(t) do
n = n + 2
end
local array = new_tab(n, 0)
local i = 0
for k, v in pairs(t) do
array[i + 1] = k
array[i + 2] = v
i = i + 2
end
-- print("key", hashname)
return _do_cmd(self, "hmset", hashname, unpack(array))
end
-- backwards compatibility
return _do_cmd(self, "hmset", hashname, ...)
end
function _M.init_pipeline(self, n)
self._reqs = new_tab(n or 4, 0)
end
function _M.cancel_pipeline(self)
self._reqs = nil
end
function _M.commit_pipeline(self)
local reqs = rawget(self, "_reqs")
if not reqs then
return nil, "no pipeline"
end
self._reqs = nil
local sock = rawget(self, "_sock")
if not sock then
return nil, "not initialized"
end
local bytes, err = sock:send(reqs)
if not bytes then
return nil, err
end
local nvals = 0
local nreqs = #reqs
local vals = new_tab(nreqs, 0)
for i = 1, nreqs do
local res, err = _read_reply(self, sock)
if res then
nvals = nvals + 1
vals[nvals] = res
elseif res == nil then
if err == "timeout" then
close(self)
end
return nil, err
else
-- be a valid redis error value
nvals = nvals + 1
vals[nvals] = {false, err}
end
end
return vals
end
function _M.array_to_hash(self, t)
local n = #t
-- print("n = ", n)
local h = new_tab(0, n / 2)
for i = 1, n, 2 do
h[t[i]] = t[i + 1]
end
return h
end
-- this method is deperate since we already do lazy method generation.
function _M.add_commands(...)
local cmds = {...}
for i = 1, #cmds do
local cmd = cmds[i]
_M[cmd] =
function (self, ...)
return _do_cmd(self, cmd, ...)
end
end
end
setmetatable(_M, {__index = function(self, cmd)
local method =
function (self, ...)
return do_cmd(self, cmd, ...)
end
-- cache the lazily generated method in our
-- module table
_M[cmd] = method
return method
end})
return _M

View File

@ -0,0 +1,57 @@
package t::Test;
use strict;
use warnings;
use Test::Nginx::Socket::Lua::Stream -Base;
use Cwd qw(cwd);
my $pwd = cwd();
my $HtmlDir = html_dir;
our @EXPORT = qw($GlobalConfig);
our $GlobalConfig = qq{
lua_package_path "$pwd/lib/?.lua;;";
lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;";
};
$ENV{TEST_NGINX_RESOLVER} = '8.8.8.8';
$ENV{TEST_NGINX_REDIS_PORT} ||= 6379;
no_long_string();
add_block_preprocessor(sub {
my $block = shift;
if (!defined $block->http_only) {
if (defined($ENV{TEST_SUBSYSTEM}) && $ENV{TEST_SUBSYSTEM} eq "stream") {
if (!defined $block->stream_config) {
$block->set_value("stream_config", $block->global_config);
}
if (!defined $block->stream_server_config) {
$block->set_value("stream_server_config", $block->server_config);
}
if (defined $block->internal_server_error) {
$block->set_value("stream_respons", "");
}
} else {
if (!defined $block->http_config) {
$block->set_value("http_config", $block->global_config);
}
if (!defined $block->request) {
$block->set_value("request", <<\_END_);
GET /t
_END_
}
if (!defined $block->config) {
$block->set_value("config", "location /t {\n" . $block->server_config . "\n}");
}
if (defined $block->internal_server_error) {
$block->set_value("error_code", 500);
$block->set_value("ignore_response_body", "");
}
}
}
});
1;

View File

@ -0,0 +1,245 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
log_level 'warn';
run_tests();
__DATA__
=== TEST 1: github issue #108: ngx.location.capture + redis.set_keepalive
--- http_only
--- http_config eval: $::GlobalConfig
--- config
location /r1 {
default_type text/html;
set $port $TEST_NGINX_REDIS_PORT;
#lua_code_cache off;
lua_need_request_body on;
content_by_lua_file html/r1.lua;
}
location /r2 {
default_type text/html;
set $port $TEST_NGINX_REDIS_PORT;
#lua_code_cache off;
lua_need_request_body on;
content_by_lua_file html/r2.lua;
}
location /anyurl {
internal;
proxy_pass http://127.0.0.1:$server_port/dummy;
}
location = /dummy {
echo dummy;
}
--- user_files
>>> r1.lua
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", ngx.var.port)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:flushall()
if not ok then
ngx.say("failed to flushall: ", err)
return
end
ok, err = red:set_keepalive()
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
local http_ress = ngx.location.capture("/r2") -- 1
ngx.say("ok")
>>> r2.lua
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", ngx.var.port) --2
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res = ngx.location.capture("/anyurl") --3
--- request
GET /r1
--- response_body
ok
--- no_error_log
[error]
=== TEST 2: exit(404) after I/O (ngx_lua github issue #110
https://github.com/chaoslawful/lua-nginx-module/issues/110
--- http_only
--- http_config eval: $::GlobalConfig
--- config
error_page 400 /400.html;
error_page 404 /404.html;
location /foo {
access_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(2000) -- 2 sec
-- ngx.log(ngx.ERR, "hello");
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.log(ngx.ERR, "failed to connect: ", err)
return
end
res, err = red:set("dog", "an animal")
if not res then
ngx.log(ngx.ERR, "failed to set dog: ", err)
return
end
-- ngx.say("set dog: ", res)
local res, err = red:get("dog")
if err then
ngx.log(ngx.ERR, "failed to get dog: ", err)
return
end
if not res then
ngx.log(ngx.ERR, "dog not found.")
return
end
-- ngx.say("dog: ", res)
-- red:close()
local ok, err = red:set_keepalive(0, 100)
if not ok then
ngx.log(ngx.ERR, "failed to set keepalive: ", err)
return
end
ngx.exit(404)
';
echo Hello;
}
--- user_files
>>> 400.html
Bad request, dear...
>>> 404.html
Not found, dear...
--- request
GET /foo
--- response_body
Not found, dear...
--- error_code: 404
--- no_error_log
[error]
=== TEST 3: set and get an empty string
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
res, err = red:set("dog", "")
if not res then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set dog: ", res)
for i = 1, 2 do
local res, err = red:get("dog")
if err then
ngx.say("failed to get dog: ", err)
return
end
if not res then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
end
red:close()
';
--- response_body
set dog: OK
dog:
dog:
--- no_error_log
[error]
=== TEST 4: ngx.exec() after red:get()
--- http_only
--- http_config eval: $::GlobalConfig
--- config
location /t {
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:get("dog")
if err then
ngx.say("failed to get dog: ", err)
return
end
ngx.exec("/hello")
';
}
location = /hello {
echo hello world;
}
--- request
GET /t
--- response_body
hello world
--- no_error_log
[error]

View File

@ -0,0 +1,17 @@
-----BEGIN CERTIFICATE-----
MIICqTCCAhICCQClDm1WkreW4jANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UEBhMC
VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28x
EjAQBgNVBAoMCU9wZW5SZXN0eTESMBAGA1UECwwJT3BlblJlc3R5MREwDwYDVQQD
DAh0ZXN0LmNvbTEgMB4GCSqGSIb3DQEJARYRYWdlbnR6aEBnbWFpbC5jb20wIBcN
MTQwNzIxMDMyMzQ3WhgPMjE1MTA2MTMwMzIzNDdaMIGXMQswCQYDVQQGEwJVUzET
MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzESMBAG
A1UECgwJT3BlblJlc3R5MRIwEAYDVQQLDAlPcGVuUmVzdHkxETAPBgNVBAMMCHRl
c3QuY29tMSAwHgYJKoZIhvcNAQkBFhFhZ2VudHpoQGdtYWlsLmNvbTCBnzANBgkq
hkiG9w0BAQEFAAOBjQAwgYkCgYEA6P18zUvtmaKQK2xePy8ZbFwSyTLw+jW6t9eZ
aiTec8X3ibN9WemrxHzkTRikxP3cAQoITRuZiQvF4Q7DO6wMkz/b0zwfgX5uedGq
047AJP6n/mwlDOjGSNomBLoXQzo7tVe60ikEm3ZyDUqnJPJMt3hImO5XSop4MPMu
Za9WhFcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQA4OBb9bOyWB1//93nSXX1mdENZ
IQeyTK0Dd6My76lnZxnZ4hTWrvvd0b17KLDU6JnS2N5ee3ATVkojPidRLWLIhnh5
0eXrcKalbO2Ce6nShoFvQCQKXN2Txmq2vO/Mud2bHAWwJALg+qi1Iih/gVYB9sct
FLg8zFOzRlYiU+6Mmw==
-----END CERTIFICATE-----

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDo/XzNS+2ZopArbF4/LxlsXBLJMvD6Nbq315lqJN5zxfeJs31Z
6avEfORNGKTE/dwBCghNG5mJC8XhDsM7rAyTP9vTPB+Bfm550arTjsAk/qf+bCUM
6MZI2iYEuhdDOju1V7rSKQSbdnINSqck8ky3eEiY7ldKingw8y5lr1aEVwIDAQAB
AoGBANgB66sKMga2SKN5nQdHS3LDCkevCutu1OWM5ZcbB4Kej5kC57xsf+tzPtab
emeIVGhCPOAALqB4YcT+QtMX967oM1MjcFbtH7si5oq6UYyp3i0G9Si6jIoVHz3+
8yOUaqwKbK+bRX8VS0YsHZmBsPK5ryN50iUwsU08nemoA94BAkEA9GS9Q5OPeFkM
tFxsIQ1f2FSsZAuN/1cpZgJqY+YaAN7MSPGTWyfd7nWG/Zgk3GO9/2ihh4gww+7B
To09GkmW4QJBAPQOHC2V+t2TA98+6Lj6+TYwcGEkhOENfVpH25mQ+kXgF/1Bd6rA
nosT1bdAY+SnmWXbSw6Kv5C20Em+bEX8WjcCQCSRRjhsRdVODbaW9Z7kb2jhEoJN
sEt6cTlQNzcHYPCsZYisjM3g4zYg47fiIfHQAsfKkhDDcfh/KvFj9LaQOEECQQCH
eBWYEDpSJ7rsfqT7mQQgWj7nDThdG/nK1TxGP71McBmg0Gg2dfkLRhVJRQqt74Is
kc9V4Rp4n6F6baL4Lh19AkEA6pZZer0kg3Kv9hjhaITIKUYdfIp9vYnDRWbQlBmR
atV8V9u9q2ETZvqfHpN+9Lu6NYR4yXIEIRf1bnIZ/mr9eQ==
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,27 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: module size of resty.redis
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
n = 0
for _, _ in pairs(redis) do
n = n + 1
end
ngx.say("size: ", n)
';
--- response_body
size: 56
--- no_error_log
[error]

View File

@ -0,0 +1,128 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks()) - 2;
run_tests();
__DATA__
=== TEST 1: hmset key-pairs
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:hmset("animals", "dog", "bark", "cat", "meow")
if not res then
ngx.say("failed to set animals: ", err)
return
end
ngx.say("hmset animals: ", res)
local res, err = red:hmget("animals", "dog", "cat")
if not res then
ngx.say("failed to get animals: ", err)
return
end
ngx.say("hmget animals: ", res)
red:close()
';
--- response_body
hmset animals: OK
hmget animals: barkmeow
--- no_error_log
[error]
=== TEST 2: hmset lua tables
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local t = { dog = "bark", cat = "meow", cow = "moo" }
local res, err = red:hmset("animals", t)
if not res then
ngx.say("failed to set animals: ", err)
return
end
ngx.say("hmset animals: ", res)
local res, err = red:hmget("animals", "dog", "cat", "cow")
if not res then
ngx.say("failed to get animals: ", err)
return
end
ngx.say("hmget animals: ", res)
red:close()
';
--- response_body
hmset animals: OK
hmget animals: barkmeowmoo
--- no_error_log
[error]
=== TEST 3: hmset a single scalar
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:hmset("animals", "cat")
if not res then
ngx.say("failed to set animals: ", err)
return
end
ngx.say("hmset animals: ", res)
local res, err = red:hmget("animals", "cat")
if not res then
ngx.say("failed to get animals: ", err)
return
end
ngx.say("hmget animals: ", res)
red:close()
';
--- internal_server_error
--- error_log
table expected, got string

View File

@ -0,0 +1,55 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (4 * blocks());
run_tests();
__DATA__
=== TEST 1: continue using the obj when read timeout happens
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 1921);
if not ok then
ngx.say("failed to connect: ", err)
return
end
red:set_timeout(100) -- 0.1 sec
for i = 1, 2 do
local data, err = red:get("foo")
if not data then
ngx.say("failed to get: ", err)
else
ngx.say("get: ", data);
end
ngx.sleep(0.1)
end
red:close()
';
--- tcp_listen: 1921
--- tcp_query eval
"*2\r
\$3\r
get\r
\$3\r
foo\r
"
--- tcp_reply eval
"\$5\r\nhello\r\n"
--- tcp_reply_delay: 150ms
--- response_body
failed to get: timeout
failed to get: closed
--- error_log
lua tcp socket read timed out

View File

@ -0,0 +1,81 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: sanity
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
redis.register_module_prefix("bf")
redis.register_module_prefix("test")
local red = redis:new()
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:del("module_1")
if not res then
ngx.say(err)
return
end
res, err = red:bf():add("module_1", 1)
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
res, err = red:bf():exists("module_1", 1)
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
-- call normal command
res, err = red:del("module_1")
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
-- call cached 'exists' again
res, err = red:exists("module_1")
if not res then
ngx.say(err)
return
end
ngx.say("receive: ", cjson.encode(res))
-- call pre-created 'get' method
res, err = red:test():get()
if not res then
ngx.say(err)
end
red:close()
}
--- response_body_like
receive: 1
receive: 1
receive: 1
receive: 0
ERR unknown command `test.get`.+
--- no_error_log
[error]

View File

@ -0,0 +1,294 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: basic
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
for i = 1, 2 do
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
red:set("dog", "hello")
red:get("dog")
local results = red:commit_pipeline()
local cjson = require "cjson"
ngx.say(cjson.encode(results))
end
red:close()
';
--- response_body
["OK","an animal","OK","hello"]
["OK","an animal","OK","hello"]
--- no_error_log
[error]
=== TEST 2: cancel automatically
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
for i = 1, 2 do
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
red:set("dog", "hello")
red:get("dog")
local results = red:commit_pipeline()
local cjson = require "cjson"
ngx.say(cjson.encode(results))
end
red:close()
';
--- response_body
["OK","an animal","OK","hello"]
["OK","an animal","OK","hello"]
--- no_error_log
[error]
=== TEST 3: cancel explicitly
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
red:cancel_pipeline()
local res, err = red:flushall()
if not res then
ngx.say("failed to flush all: ", err)
return
end
ngx.say("flushall: ", res)
for i = 1, 2 do
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
red:set("dog", "hello")
red:get("dog")
local results = red:commit_pipeline()
local cjson = require "cjson"
ngx.say(cjson.encode(results))
end
red:close()
';
--- response_body
flushall: OK
["OK","an animal","OK","hello"]
["OK","an animal","OK","hello"]
--- no_error_log
[error]
=== TEST 4: mixed
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
res, err = red:set("dog", "an aniaml")
if not ok then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set result: ", res)
local res, err = red:get("dog")
if not res then
ngx.say("failed to get dog: ", err)
return
end
if res == ngx.null then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if res[1] == false then
ngx.say("failed to run command ", i, ": ", res[2])
else
ngx.say("cmd ", i, ": ", res)
end
else
-- process the scalar value
ngx.say("cmd ", i, ": ", res)
end
end
-- put it into the connection pool of size 100,
-- with 0 idle timeout
local ok, err = red:set_keepalive(0, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
-- or just close the connection right away:
-- local ok, err = red:close()
-- if not ok then
-- ngx.say("failed to close: ", err)
-- return
-- end
';
--- response_body
set result: OK
dog: an aniaml
cmd 1: OK
cmd 2: OK
cmd 3: Marry
cmd 4: Bob
--- no_error_log
[error]
=== TEST 5: redis return error in pipeline
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:del("dog")
if not res then
ngx.say("failed to del dog: ", err)
return
end
red:init_pipeline()
red:hkeys("dog")
red:set("dog", "an animal")
red:hkeys("dog")
red:get("dog")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if res[1] == false then
ngx.say("failed to run command ", i, ": ", res[2])
else
ngx.say("cmd ", i, ": ", res)
end
else
-- process the scalar value
ngx.say("cmd ", i, ": ", res)
end
end
-- put it into the connection pool of size 100,
-- with 0 idle timeout
local ok, err = red:set_keepalive(0, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
';
--- response_body
cmd 1:
cmd 2: OK
failed to run command 3: WRONGTYPE Operation against a key holding the wrong kind of value
cmd 4: an animal
--- no_error_log
[error]

View File

@ -0,0 +1,929 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: single channel
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
res, err = red2:publish("dog", "Hello")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
ngx.say("2: publish: ", cjson.encode(res))
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
return
end
ngx.say("1: receive: ", cjson.encode(res))
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
2: publish: 1
1: receive: ["message","dog","Hello"]
--- no_error_log
[error]
=== TEST 2: single channel (retry read_reply() after timeout)
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
red:set_timeout(1)
for i = 1, 2 do
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
if err ~= "timeout" then
return
end
end
end
red:set_timeout(1000)
res, err = red:unsubscribe("dog")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
res, err = red2:publish("dog", "Hello")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
ngx.say("2: publish: ", cjson.encode(res))
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:unsubscribe("dog")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
return
end
ngx.say("1: unsubscribe: ", cjson.encode(res))
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
1: failed to read reply: timeout
1: failed to read reply: timeout
1: unsubscribe: ["unsubscribe","dog",0]
2: publish: 0
1: failed to read reply: not subscribed
1: failed to unsubscribe: not subscribed
--- no_error_log
[error]
=== TEST 3: multiple channels
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe dog: ", cjson.encode(res))
res, err = red:subscribe("cat")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe cat: ", cjson.encode(res))
res, err = red2:publish("dog", "Hello")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
ngx.say("2: publish: ", cjson.encode(res))
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
red:set_timeout(10) -- 10ms
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
red:set_timeout(1000) -- 1s
res, err = red:unsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
red:set_timeout(10) -- 10ms
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
red:set_timeout(1000) -- 1s
red:close()
red2:close()
';
--- response_body_like chop
^1: subscribe dog: \["subscribe","dog",1\]
1: subscribe cat: \["subscribe","cat",2\]
2: publish: 1
1: receive: \["message","dog","Hello"\]
1: failed to read reply: timeout
1: unsubscribe: \[\["unsubscribe","(?:cat|dog)",1\],\["unsubscribe","(?:cat|dog)",0\]\]
1: failed to read reply: not subscribed
1: failed to read reply: not subscribed$
--- no_error_log
[error]
=== TEST 4: call subscribe after read_reply() times out
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
red:set_timeout(1)
for i = 1, 2 do
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
if err ~= "timeout" then
return
end
end
end
red:set_timeout(1000)
res, err = red:subscribe("cat")
if not res then
ngx.say("1: failed to subscribe to cat: ", err)
else
ngx.say("1: subscribe: ", cjson.encode(res))
end
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
1: failed to read reply: timeout
1: failed to read reply: timeout
1: subscribe: ["subscribe","cat",2]
--- no_error_log
[error]
=== TEST 5: call set_keepalive in subscribed mode (previous read_reply calls timed out)
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
red:set_timeout(1)
for i = 1, 2 do
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
if err ~= "timeout" then
return
end
end
end
red:set_timeout(1000)
res, err = red:set_keepalive()
if not res then
ngx.say("1: failed to set keepalive: ", err)
else
ngx.say("1: set keepalive: ", cjson.encode(res))
end
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
1: failed to read reply: timeout
1: failed to read reply: timeout
1: failed to set keepalive: subscribed state
--- no_error_log
[error]
=== TEST 6: call set_keepalive in subscribed mode
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
res, err = red:set_keepalive()
if not res then
ngx.say("1: failed to set keepalive: ", err)
else
ngx.say("1: set keepalive: ", cjson.encode(res))
end
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
1: failed to set keepalive: subscribed state
--- no_error_log
[error]
=== TEST 7: call set_keepalive in unsubscribed mode
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
ngx.say("1: subscribe: ", cjson.encode(res))
res, err = red:unsubscribe()
if not res then
ngx.say("1: failed to unsubscribe: ", err)
return
end
ngx.say("1: unsubscribe: ", cjson.encode(res))
res, err = red:set_keepalive()
if not res then
ngx.say("1: failed to set keepalive: ", err)
else
ngx.say("1: set keepalive: ", cjson.encode(res))
end
red:close()
red2:close()
';
--- response_body
1: subscribe: ["subscribe","dog",1]
1: unsubscribe: ["unsubscribe","dog",0]
1: set keepalive: 1
--- no_error_log
[error]
=== TEST 8: mix read_reply and other commands
--- global_config eval: $::GlobalConfig
--- server_config
lua_socket_log_errors off;
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red2:publish("dog", "Hello")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red:ping()
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red2:publish("dog", "World")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:unsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:set_timeout(1) -- 1s
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
red:close()
red2:close()
';
--- request
GET /t
--- response_body_like chop
1: receive: \["message","dog","Hello"\]
1: receive: \["message","dog","World"\]
1: unsubscribe: \["unsubscribe","dog",0\]
1: failed to read reply: not subscribed$
--- no_error_log
[error]
=== TEST 9: multiple subscribe
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
local res, err = red:subscribe("dog", "cat")
if not res then
ngx.say("1: failed to subscribe: ", err)
else
ngx.say("1: subscribe: ", cjson.encode(res))
end
res, err = red:unsubscribe("dog")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
res, err = red:unsubscribe("cat")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:close()
}
--- response_body
1: subscribe: [["subscribe","dog",1],["subscribe","cat",2]]
1: unsubscribe: ["unsubscribe","dog",1]
1: unsubscribe: ["unsubscribe","cat",0]
--- no_error_log
[error]
=== TEST 10: multiple unsubscribe
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
local res, err = red:subscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red:subscribe("cat")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red:unsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:close()
}
--- response_body_like
^1: unsubscribe: \[\["unsubscribe","(?:cat|dog)",1\],\["unsubscribe","(?:cat|dog)",0\]\]$
--- no_error_log
[error]
=== TEST 11: multiple psubscribe
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
local res, err = red:psubscribe("dog", "cat")
if not res then
ngx.say("1: failed to subscribe: ", err)
else
ngx.say("1: subscribe: ", cjson.encode(res))
end
res, err = red:punsubscribe("dog")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
res, err = red:punsubscribe("cat")
if not res then
ngx.say("1: failed to unsubscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:close()
}
--- response_body
1: subscribe: [["psubscribe","dog",1],["psubscribe","cat",2]]
1: unsubscribe: ["punsubscribe","dog",1]
1: unsubscribe: ["punsubscribe","cat",0]
--- no_error_log
[error]
=== TEST 12: multiple punsubscribe
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
local res, err = red:psubscribe("dog")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red:psubscribe("cat")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red:punsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:close()
}
--- response_body_like
^1: unsubscribe: \[\["punsubscribe","(?:cat|dog)",1\],\["punsubscribe","(?:cat|dog)",0\]\]$
--- no_error_log
[error]
=== TEST 13: mix read_reply, subscribe, and psubscribe
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua_block {
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local red2 = redis:new()
red:set_timeout(1000) -- 1 sec
red2:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("1: failed to connect: ", err)
return
end
ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("2: failed to connect: ", err)
return
end
local res, err = red:subscribe("two")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red:psubscribe("t*o")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red2:publish("two", "foo")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red2:publish("too", "bar")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red2:publish("too", "baz")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:punsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
local res, err = red:subscribe("three")
if not res then
ngx.say("1: failed to subscribe: ", err)
return
end
res, err = red2:publish("three", "foo")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red2:publish("two", "bar")
if not res then
ngx.say("2: failed to publish: ", err)
return
end
res, err = red:unsubscribe("three")
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
res, err = red:read_reply()
if not res then
ngx.say("1: failed to read reply: ", err)
else
ngx.say("1: receive: ", cjson.encode(res))
end
res, err = red:unsubscribe()
if not res then
ngx.say("1: failed to unscribe: ", err)
else
ngx.say("1: unsubscribe: ", cjson.encode(res))
end
red:close()
red2:close()
}
--- response_body_like chop
^1: receive: \["p?message",("two"|"t\*o","two"),"foo"\]
1: receive: \["p?message",("two"|"t\*o","two"),"foo"\]
1: unsubscribe: \["punsubscribe","t\*o",1\]
1: unsubscribe: \["unsubscribe","three",1\]
1: receive: \["message","two","bar"\]
1: unsubscribe: \["unsubscribe","two",0\]
--- no_error_log
[error]

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,343 @@
# vim:set ft= ts=4 sw=4 et:
use Test::Nginx::Socket::Lua;
use Cwd qw(cwd);
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
$ENV{TEST_NGINX_HTML_DIR} ||= html_dir();
$ENV{TEST_NGINX_REDIS_PORT} ||= 6379;
$ENV{TEST_NGINX_STREAM_REDIS_PORT} ||= 12345;
my $MainConfig = qq{
stream {
server {
listen unix:$ENV{TEST_NGINX_HTML_DIR}/nginx.sock;
listen unix:$ENV{TEST_NGINX_HTML_DIR}/nginx-ssl.sock ssl;
listen 127.0.0.1:$ENV{TEST_NGINX_STREAM_REDIS_PORT} ssl;
ssl_certificate ../../cert/test.crt;
ssl_certificate_key ../../cert/test.key;
proxy_pass 127.0.0.1:$ENV{TEST_NGINX_REDIS_PORT};
}
}
};
my $pwd = cwd();
my $HttpConfig = qq{
lua_package_path "$pwd/lib/?.lua;;";
};
add_block_preprocessor(sub {
my $block = shift;
if (!defined $block->main_config) {
$block->set_value("main_config", $MainConfig);
}
if (!defined $block->http_config) {
$block->set_value("http_config", $HttpConfig);
}
if (!defined $block->request) {
$block->set_value("request", "GET /t");
}
if (!defined $block->no_error_log) {
$block->set_value("no_error_log", "[error]");
}
});
no_long_string();
#no_diff();
run_tests();
__DATA__
=== TEST 1: ssl connection on non ssl server
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx.sock", {
ssl = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
}
}
--- response_body
failed to connect: failed to do ssl handshake: timeout
=== TEST 2: set and get on ssl connection
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_STREAM_REDIS_PORT, {
ssl = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
ok, err = red:select(1)
if not ok then
ngx.say("failed to select: ", err)
return
end
local res, err = red:set("dog", "an animal")
if not res then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set dog: ", res)
for i = 1, 2 do
local res, err = red:get("dog")
if err then
ngx.say("failed to get dog: ", err)
return
end
if not res then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
end
red:close()
}
}
--- response_body
set dog: OK
dog: an animal
dog: an animal
=== TEST 3: set and get on ssl connection via unix socket
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx-ssl.sock", {
ssl = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
ok, err = red:select(1)
if not ok then
ngx.say("failed to select: ", err)
return
end
local res, err = red:set("dog", "an animal")
if not res then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set dog: ", res)
for i = 1, 2 do
local res, err = red:get("dog")
if err then
ngx.say("failed to get dog: ", err)
return
end
if not res then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
end
red:close()
}
}
--- response_body
set dog: OK
dog: an animal
dog: an animal
=== TEST 4: ssl connection with ssl_verify (without CA)
--- config
lua_socket_log_errors off;
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx-ssl.sock", {
ssl = true,
ssl_verify = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
}
}
--- response_body
failed to connect: failed to do ssl handshake: 18: self signed certificate
=== TEST 5: ssl connection with ssl_verify (with CA)
--- config
lua_socket_log_errors off;
lua_ssl_trusted_certificate ../../cert/test.crt;
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx-ssl.sock", {
ssl = true,
ssl_verify = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("ok")
}
}
--- response_body
ok
=== TEST 6: non-ssl connection to unix socket (issue #187)
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx-ssl.sock")
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("ok")
}
}
--- response_body
ok
=== TEST 7: non-ssl connection to unix socket with second argument nil (issue #187)
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(100)
local ok, err = red:connect("unix:$TEST_NGINX_HTML_DIR/nginx-ssl.sock",nil)
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("ok")
}
}
--- response_body
ok
=== TEST 8: ssl reuse
--- config
location /t {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local function connect_set(red)
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_STREAM_REDIS_PORT, {
ssl = true
})
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("sock reusetimes: ", red:get_reused_times())
ok, err = red:select(1)
if not ok then
ngx.say("failed to select: ", err)
return
end
local res, err = red:set("dog", "an animal")
if not res then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set dog: ", res)
local ok, err = red:set_keepalive()
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
end
connect_set(red)
connect_set(red)
}
}
--- response_body eval
qr/sock reusetimes: (0|2)
set dog: OK
sock reusetimes: (1|3)
set dog: OK/

View File

@ -0,0 +1,119 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: sanity
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local redis_key = "foo"
local ok, err = red:multi()
if not ok then
ngx.say("failed to run multi: ", err)
return
end
ngx.say("multi ans: ", cjson.encode(ok))
local ans, err = red:sort("log", "by", redis_key .. ":*->timestamp")
if not ans then
ngx.say("failed to run sort: ", err)
return
end
ngx.say("sort ans: ", cjson.encode(ans))
ans, err = red:exec()
ngx.say("exec ans: ", cjson.encode(ans))
local ok, err = red:set_keepalive(0, 1024)
if not ok then
ngx.say("failed to put the current redis connection into pool: ", err)
return
end
';
--- response_body
multi ans: "OK"
sort ans: "QUEUED"
exec ans: [{}]
--- no_error_log
[error]
=== TEST 2: redis cmd reference sample: redis does not halt on errors
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:multi()
if not ok then
ngx.say("failed to run multi: ", err)
return
end
ngx.say("multi ans: ", cjson.encode(ok))
local ans, err = red:set("a", "abc")
if not ans then
ngx.say("failed to run sort: ", err)
return
end
ngx.say("set ans: ", cjson.encode(ans))
local ans, err = red:lpop("a")
if not ans then
ngx.say("failed to run sort: ", err)
return
end
ngx.say("set ans: ", cjson.encode(ans))
ans, err = red:exec()
ngx.say("exec ans: ", cjson.encode(ans))
red:close()
';
--- response_body_like chop
^multi ans: "OK"
set ans: "QUEUED"
set ans: "QUEUED"
exec ans: \["OK",\[false,"(?:ERR|WRONGTYPE) Operation against a key holding the wrong kind of value"\]\]
$
--- no_error_log
[error]

View File

@ -0,0 +1,47 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: single channel
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local cjson = require "cjson"
local redis = require "resty.redis"
redis.add_commands("foo", "bar")
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:foo("a")
if not res then
ngx.say("failed to foo: ", err)
end
res, err = red:bar()
if not res then
ngx.say("failed to bar: ", err)
end
';
--- response_body eval
qr/\Afailed to foo: ERR unknown command [`']foo[`'](?:, with args beginning with: `a`,\s*)?
failed to bar: ERR unknown command [`']bar[`'](?:, with args beginning with:\s*)?
\z/
--- no_error_log
[error]

View File

@ -0,0 +1,23 @@
# vim:set ft= ts=4 sw=4 et:
use t::Test;
repeat_each(2);
plan tests => repeat_each() * (3 * blocks());
run_tests();
__DATA__
=== TEST 1: basic
--- global_config eval: $::GlobalConfig
--- server_config
content_by_lua '
local redis = require "resty.redis"
ngx.say(redis._VERSION)
';
--- response_body_like chop
^\d+\.\d+$
--- no_error_log
[error]

View File

@ -0,0 +1,379 @@
{
<insert_a_suppression_name_here>
Memcheck:Param
write(buf)
fun:__write_nocancel
fun:ngx_log_error_core
fun:ngx_resolver_read_response
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:ngx_sprintf_num
fun:ngx_vslprintf
fun:ngx_log_error_core
fun:ngx_resolver_read_response
fun:ngx_epoll_process_events
fun:ngx_process_events_and_timers
fun:ngx_single_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Addr1
fun:ngx_vslprintf
fun:ngx_snprintf
fun:ngx_sock_ntop
fun:ngx_event_accept
}
{
<insert_a_suppression_name_here>
Memcheck:Param
write(buf)
fun:__write_nocancel
fun:ngx_log_error_core
fun:ngx_resolver_read_response
fun:ngx_event_process_posted
fun:ngx_process_events_and_timers
fun:ngx_single_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:ngx_sprintf_num
fun:ngx_vslprintf
fun:ngx_log_error_core
fun:ngx_resolver_read_response
fun:ngx_event_process_posted
fun:ngx_process_events_and_timers
fun:ngx_single_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
obj:*
}
{
<insert_a_suppression_name_here>
exp-sgcheck:SorG
fun:ngx_http_lua_ndk_set_var_get
}
{
<insert_a_suppression_name_here>
exp-sgcheck:SorG
fun:ngx_http_variables_init_vars
fun:ngx_http_block
}
{
<insert_a_suppression_name_here>
exp-sgcheck:SorG
fun:ngx_conf_parse
}
{
<insert_a_suppression_name_here>
exp-sgcheck:SorG
fun:ngx_vslprintf
fun:ngx_log_error_core
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_calloc
fun:ngx_event_process_init
}
{
<insert_a_suppression_name_here>
Memcheck:Param
epoll_ctl(event)
fun:epoll_ctl
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_event_process_init
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:ngx_conf_flush_files
fun:ngx_single_process_cycle
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:memcpy
fun:ngx_vslprintf
fun:ngx_log_error_core
fun:ngx_http_charset_header_filter
}
{
<insert_a_suppression_name_here>
Memcheck:Param
socketcall.setsockopt(optval)
fun:setsockopt
fun:drizzle_state_connect
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_pool_cleanup_add
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:ngx_conf_flush_files
fun:ngx_single_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_array_push
fun:ngx_http_get_variable_index
fun:ngx_http_memc_add_variable
fun:ngx_http_memc_init
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_event_process_init
fun:ngx_single_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_crc32_table_init
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_event_process_init
fun:ngx_worker_process_init
fun:ngx_worker_process_cycle
fun:ngx_spawn_process
fun:ngx_start_worker_processes
fun:ngx_master_process_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_hash_init
fun:ngx_http_variables_init_vars
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_http_upstream_drizzle_create_srv_conf
fun:ngx_http_upstream
fun:ngx_conf_parse
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_hash_keys_array_init
fun:ngx_http_variables_add_core_vars
fun:ngx_http_core_preconfiguration
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_array_push
fun:ngx_hash_add_key
fun:ngx_http_add_variable
fun:ngx_http_echo_add_variables
fun:ngx_http_echo_handler_init
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_http_upstream_drizzle_create_srv_conf
fun:ngx_http_core_server
fun:ngx_conf_parse
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_http_upstream_drizzle_create_srv_conf
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_array_push
fun:ngx_hash_add_key
fun:ngx_http_variables_add_core_vars
fun:ngx_http_core_preconfiguration
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_hash_init
fun:ngx_http_upstream_init_main_conf
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_pcalloc
fun:ngx_http_drizzle_keepalive_init
fun:ngx_http_upstream_drizzle_init
fun:ngx_http_upstream_init_main_conf
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
fun:malloc
fun:ngx_alloc
fun:ngx_palloc_large
fun:ngx_palloc
fun:ngx_hash_init
fun:ngx_http_variables_init_vars
fun:ngx_http_block
fun:ngx_conf_parse
fun:ngx_init_cycle
fun:main
}
{
<insert_a_suppression_name_here>
Memcheck:Cond
fun:index
fun:expand_dynamic_string_token
fun:_dl_map_object
fun:map_doit
fun:_dl_catch_error
fun:do_preload
fun:dl_main
fun:_dl_sysdep_start
fun:_dl_start
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
match-leak-kinds: definite
fun:malloc
fun:ngx_alloc
fun:ngx_set_environment
fun:ngx_single_process_cycle
}
{
<insert_a_suppression_name_here>
Memcheck:Leak
match-leak-kinds: definite
fun:malloc
fun:ngx_alloc
fun:ngx_set_environment
fun:ngx_worker_process_init
fun:ngx_worker_process_cycle
}